Decompiled source of Zoersel v9.6.4
plugins/x64/Release/netstandard2.1/Oxygen.dll
Decompiled a month agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text.Json; using System.Text.Json.Serialization; using AK; using Agents; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using GTFO.API; using GTFO.API.Utilities; using GameData; using GameEvent; using HarmonyLib; using Il2CppInterop.Runtime.Injection; using Il2CppInterop.Runtime.InteropTypes.Arrays; using Il2CppSystem.Collections.Generic; using LevelGeneration; using Localization; using MTFO.Managers; using Microsoft.CodeAnalysis; using Oxygen.Components; using Oxygen.Config; using Oxygen.Utils; using Oxygen.Utils.PartialData; using Player; using SNetwork; using TMPro; using UnityEngine; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Oxygen")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("Oxygen")] [assembly: AssemblyTitle("Oxygen")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace Oxygen { [BepInPlugin("Inas.Oxygen", "Oxygen", "1.3.2")] [BepInProcess("GTFO.exe")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Plugin : BasePlugin { [CompilerGenerated] private static class <>O { public static Action <0>__OnBuildDone; public static Action <1>__OnLevelCleanup; public static Action <2>__Setup; public static Action <3>__OnLevelCleanup; public static Action <4>__OnBuildStart; public static Action <5>__OnLevelCleanup; public static LiveEditEventHandler <6>__Listener_FileChanged1; } public const string MODNAME = "Oxygen"; public const string AUTHOR = "Inas"; public const string GUID = "Inas.Oxygen"; public const string VERSION = "1.3.2"; public static readonly string OXYGEN_CONFIG_PATH = Path.Combine(ConfigManager.CustomPath, "Oxygen"); public static Dictionary<uint, OxygenBlock> lookup = new Dictionary<uint, OxygenBlock>(); private static LiveEditListener listener = null; public override void Load() { //IL_011a: 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_020d: Unknown result type (might be due to invalid IL or missing references) //IL_0213: Expected O, but got Unknown if (!Directory.Exists(OXYGEN_CONFIG_PATH)) { Directory.CreateDirectory(OXYGEN_CONFIG_PATH); StreamWriter streamWriter = File.CreateText(Path.Combine(OXYGEN_CONFIG_PATH, "Template.json")); streamWriter.WriteLine(ConfigManager.Serialize(new OxygenConfig())); streamWriter.Flush(); streamWriter.Close(); } ClassInjector.RegisterTypeInIl2Cpp<AirManager>(); LevelAPI.OnBuildDone += AirManager.OnBuildDone; LevelAPI.OnLevelCleanup += AirManager.OnLevelCleanup; ClassInjector.RegisterTypeInIl2Cpp<AirBar>(); LevelAPI.OnBuildStart += AirBar.Setup; LevelAPI.OnLevelCleanup += AirBar.OnLevelCleanup; ClassInjector.RegisterTypeInIl2Cpp<AirPlane>(); LevelAPI.OnBuildStart += AirPlane.OnBuildStart; LevelAPI.OnLevelCleanup += AirPlane.OnLevelCleanup; new Harmony("Inas.Oxygen").PatchAll(); foreach (string item in Directory.EnumerateFiles(OXYGEN_CONFIG_PATH, "*.json", SearchOption.AllDirectories)) { ConfigManager.Load<OxygenConfig>(item, out var config); foreach (OxygenBlock block in config.Blocks) { foreach (uint fogSetting in block.FogSettings) { if (!lookup.ContainsKey(fogSetting)) { lookup.Add(fogSetting, block); } } } } listener = LiveEdit.CreateListener(OXYGEN_CONFIG_PATH, "*.json", true); LiveEditListener obj = listener; object obj2 = <>O.<6>__Listener_FileChanged1; if (obj2 == null) { LiveEditEventHandler val = Listener_FileChanged1; <>O.<6>__Listener_FileChanged1 = val; obj2 = (object)val; } obj.FileChanged += (LiveEditEventHandler)obj2; } private static void Listener_FileChanged1(LiveEditEventArgs e) { Log.Warning("LiveEdit File Changed: " + e.FullPath + "."); LiveEdit.TryReadFileContent(e.FullPath, (Action<string>)delegate(string content) { foreach (OxygenBlock block in ConfigManager.Deserialize<OxygenConfig>(content).Blocks) { foreach (uint fogSetting in block.FogSettings) { if (lookup.ContainsKey(fogSetting)) { lookup.Remove(fogSetting); } lookup.Add(fogSetting, block); Log.Warning($"Replaced OxygenConfig for FogSetting: {fogSetting}."); } } if (GameStateManager.IsInExpedition) { AirManager.Current.UpdateAirConfig(AirManager.Current.FogSetting(), LiveEditForceUpdate: true); } }); } } } namespace Oxygen.Utils { internal static class Extension { public static T Instantiate<T>(this GameObject gameObject, string name) where T : Component { GameObject obj = Object.Instantiate<GameObject>(gameObject, gameObject.transform.parent, false); ((Object)obj).name = name; return obj.GetComponent<T>(); } } internal class LocalizedTextConverter : JsonConverter<LocalizedText> { public override bool HandleNull => false; public override LocalizedText Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Expected O, but got Unknown switch (reader.TokenType) { case JsonTokenType.String: { string @string = reader.GetString(); return new LocalizedText { Id = 0u, UntranslatedText = @string }; } case JsonTokenType.Number: return new LocalizedText { Id = reader.GetUInt32(), UntranslatedText = null }; default: throw new JsonException($"LocalizedTextJson type: {reader.TokenType} is not implemented!"); } } public override void Write(Utf8JsonWriter writer, LocalizedText value, JsonSerializerOptions options) { JsonSerializer.Serialize<LocalizedText>(writer, value, options); } } internal static class Log { private static ManualLogSource source; static Log() { source = Logger.CreateLogSource("Oxygen"); } public static void Debug(object msg) { source.LogDebug(msg); } public static void Error(object msg) { source.LogError(msg); } public static void Fatal(object msg) { source.LogFatal(msg); } public static void Info(object msg) { source.LogInfo(msg); } public static void Message(object msg) { source.LogMessage(msg); } public static void Warning(object msg) { source.LogWarning(msg); } } } namespace Oxygen.Utils.PartialData { public static class MTFOPartialDataUtil { public const string PLUGIN_GUID = "MTFO.Extension.PartialBlocks"; public static JsonConverter PersistentIDConverter { get; private set; } public static JsonConverter LocalizedTextConverter { get; private set; } public static bool IsLoaded { get; private set; } public static bool Initialized { get; private set; } public static string PartialDataPath { get; private set; } public static string ConfigPath { get; private set; } static MTFOPartialDataUtil() { PersistentIDConverter = null; LocalizedTextConverter = null; IsLoaded = false; Initialized = false; PartialDataPath = string.Empty; ConfigPath = string.Empty; if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("MTFO.Extension.PartialBlocks", out var value)) { return; } try { Assembly obj = ((value == null) ? null : value.Instance?.GetType()?.Assembly) ?? null; if ((object)obj == null) { throw new Exception("Assembly is Missing!"); } Type[] types = obj.GetTypes(); Type type = types.First((Type t) => t.Name == "PersistentIDConverter"); if ((object)type == null) { throw new Exception("Unable to Find PersistentIDConverter Class"); } Type type2 = types.First((Type t) => t.Name == "LocalizedTextConverter"); if ((object)type2 == null) { throw new Exception("Unable to Find LocalizedTextConverter Class"); } Type obj2 = types.First((Type t) => t.Name == "PartialDataManager") ?? throw new Exception("Unable to Find PartialDataManager Class"); PropertyInfo property = obj2.GetProperty("Initialized", BindingFlags.Static | BindingFlags.Public); PropertyInfo property2 = obj2.GetProperty("PartialDataPath", BindingFlags.Static | BindingFlags.Public); PropertyInfo? property3 = obj2.GetProperty("ConfigPath", BindingFlags.Static | BindingFlags.Public); if ((object)property == null) { throw new Exception("Unable to Find Property: Initialized"); } if ((object)property2 == null) { throw new Exception("Unable to Find Property: PartialDataPath"); } if ((object)property3 == null) { throw new Exception("Unable to Find Field: ConfigPath"); } Initialized = (bool)property.GetValue(null); PartialDataPath = (string)property2.GetValue(null); ConfigPath = (string)property3.GetValue(null); PersistentIDConverter = (JsonConverter)Activator.CreateInstance(type); LocalizedTextConverter = (JsonConverter)Activator.CreateInstance(type2); IsLoaded = true; } catch (Exception value2) { Log.Error($"Exception thrown while reading data from MTFO_Extension_PartialData:\n{value2}"); } } } public static class MTFOUtil { public const string PLUGIN_GUID = "com.dak.MTFO"; public const BindingFlags PUBLIC_STATIC = BindingFlags.Static | BindingFlags.Public; public static string GameDataPath { get; private set; } public static string CustomPath { get; private set; } public static bool HasCustomContent { get; private set; } public static bool IsLoaded { get; private set; } static MTFOUtil() { GameDataPath = string.Empty; CustomPath = string.Empty; HasCustomContent = false; IsLoaded = false; if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("com.dak.MTFO", out var value)) { return; } try { Assembly obj = ((value == null) ? null : value.Instance?.GetType()?.Assembly) ?? null; if ((object)obj == null) { throw new Exception("Assembly is Missing!"); } Type obj2 = obj.GetTypes().First((Type t) => t.Name == "ConfigManager") ?? throw new Exception("Unable to Find ConfigManager Class"); FieldInfo field = obj2.GetField("GameDataPath", BindingFlags.Static | BindingFlags.Public); FieldInfo field2 = obj2.GetField("CustomPath", BindingFlags.Static | BindingFlags.Public); FieldInfo? field3 = obj2.GetField("HasCustomContent", BindingFlags.Static | BindingFlags.Public); if ((object)field == null) { throw new Exception("Unable to Find Field: GameDataPath"); } if ((object)field2 == null) { throw new Exception("Unable to Find Field: CustomPath"); } if ((object)field3 == null) { throw new Exception("Unable to Find Field: HasCustomContent"); } GameDataPath = (string)field.GetValue(null); CustomPath = (string)field2.GetValue(null); HasCustomContent = (bool)field3.GetValue(null); IsLoaded = true; } catch (Exception value2) { Log.Error($"Exception thrown while reading path from DataDumper (MTFO): \n{value2}"); } } } } namespace Oxygen.Patches { [HarmonyPatch] internal class Patches_Dam_PlayerDamageLocal { [HarmonyPrefix] [HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceiveNoAirDamage")] public static bool Pre_ReceiveNoAirDamage(Dam_PlayerDamageLocal __instance, pMiniDamageData data) { //IL_00a1: Unknown result type (might be due to invalid IL or missing references) float num = ((UFloat16)(ref data.damage)).Get(((Dam_SyncedDamageBase)__instance).HealthMax); ((Dam_PlayerDamageBase)__instance).m_nextRegen = Clock.Time + ((Dam_PlayerDamageBase)__instance).Owner.PlayerData.healthRegenStartDelayAfterDamage; if (((Agent)((Dam_PlayerDamageBase)__instance).Owner).IsLocallyOwned) { DramaManager.CurrentState.OnLocalDamage(num); GameEventManager.PostEvent((eGameEvent)13, ((Dam_PlayerDamageBase)__instance).Owner, num, "", (Dictionary<string, string>)null); } else { DramaManager.CurrentState.OnTeammatesDamage(num); } if (((Dam_PlayerDamageBase)__instance).IgnoreAllDamage) { return false; } if (SNet.IsMaster && !((Dam_SyncedDamageBase)__instance).RegisterDamage(num)) { ((Dam_SyncedDamageBase)__instance).SendSetHealth(((Dam_SyncedDamageBase)__instance).Health); } __instance.Hitreact(((UFloat16)(ref data.damage)).Get(((Dam_SyncedDamageBase)__instance).HealthMax), Vector3.zero, true, false, false); return false; } [HarmonyPostfix] [HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceiveBulletDamage")] public static void Post_ReceiveBulletDamage() { AirManager.Current.ResetHealthToRegen(); } [HarmonyPostfix] [HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceiveMeleeDamage")] public static void Post_ReceiveMeleeDamage() { AirManager.Current.ResetHealthToRegen(); } [HarmonyPostfix] [HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceiveFireDamage")] public static void Post_ReceiveFireDamage() { AirManager.Current.ResetHealthToRegen(); } [HarmonyPostfix] [HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceiveShooterProjectileDamage")] public static void Post_ReceiveShooterProjectileDamage() { AirManager.Current.ResetHealthToRegen(); } [HarmonyPostfix] [HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceiveTentacleAttackDamage")] public static void Post_ReceiveTentacleAttackDamage() { AirManager.Current.ResetHealthToRegen(); } [HarmonyPostfix] [HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceivePushDamage")] public static void Post_ReceivePushDamage() { AirManager.Current.ResetHealthToRegen(); } [HarmonyPostfix] [HarmonyPatch(typeof(Dam_PlayerDamageLocal), "ReceiveSetDead")] public static void Post_ReceiveSetDead() { AirManager.Current.ResetHealthToRegen(); } } [HarmonyPatch(typeof(EnvironmentStateManager), "UpdateFog")] internal class EnvironmentStateManager_UpdateFog { public static void Prefix(EnvironmentStateManager __instance) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002a: 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) if ((Object)(object)AirManager.Current == (Object)null) { return; } FogState val = ((Il2CppArrayBase<FogState>)(object)__instance.m_stateReplicator.State.FogStates)[__instance.m_latestKnownLocalDimensionCreationIndex]; if (val.FogDataID != 0) { AirManager.Current.UpdateAirConfig(val.FogDataID); if (!AirManager.Current.HasAirConfig()) { AirManager.Current.StopInfectionLoop(); } } } } [HarmonyPatch(typeof(FogRepeller_Sphere), "StartRepelling")] internal class FogRepeller_Sphere_StartRepelling { public static void Postfix(ref FogRepeller_Sphere __instance) { if (__instance.m_infectionShield != null) { EffectVolumeManager.UnregisterVolume((EffectVolume)(object)__instance.m_infectionShield); ((EffectVolume)__instance.m_infectionShield).contents = (eEffectVolumeContents)0; EffectVolumeManager.RegisterVolume((EffectVolume)(object)__instance.m_infectionShield); } } } [HarmonyPatch(typeof(LocalPlayerAgentSettings), "UpdateBlendTowardsTargetFogSetting")] internal class LocalPlayerAgentSettings_UpdateBlendTowardsTargetFogSetting { public static void Postfix(LocalPlayerAgentSettings __instance, float amount) { //IL_005f: Unknown result type (might be due to invalid IL or missing references) if (!AirManager.Current.HasAirConfig()) { AirPlane.Current.Unregister(); } else { if (__instance.m_targetFogSettings == null || !SNet.LocalPlayer.HasPlayerAgent) { return; } PlayerAgent localPlayerAgent = PlayerManager.GetLocalPlayerAgent(); if ((Object)(object)localPlayerAgent.FPSCamera == (Object)null) { return; } AirPlane current = AirPlane.Current; if (!((Object)(object)current == (Object)null) && RundownManager.ExpeditionIsStarted) { float num = 0f; Dimension val = default(Dimension); if (Dimension.GetDimension(((Agent)localPlayerAgent).DimensionIndex, ref val)) { num = val.GroundY; } PreLitVolume prelitVolume = localPlayerAgent.FPSCamera.PrelitVolume; ((EffectVolume)current.airPlane).invert = (double)prelitVolume.m_densityHeightMaxBoost > (double)prelitVolume.m_fogDensity; ((EffectVolume)current.airPlane).contents = (eEffectVolumeContents)1; ((EffectVolume)current.airPlane).modification = (eEffectVolumeModification)0; ((EffectVolume)current.airPlane).modificationScale = AirManager.Current.AirLoss(); current.airPlane.lowestAltitude = prelitVolume.m_densityHeightAltitude + num; current.airPlane.highestAltitude = prelitVolume.m_densityHeightAltitude + prelitVolume.m_densityHeightRange + num; AirPlane.Current.Register(); } } } } [HarmonyPatch] internal class Patch_PlayerAgent { [HarmonyPrefix] [HarmonyPatch(typeof(PlayerAgent), "ReceiveModification")] public static void ReceiveModification(PlayerAgent __instance, ref EV_ModificationData data) { if (AirManager.Current.HasAirConfig()) { if ((double)data.health != 0.0) { AirManager.Current.RemoveAir(data.health); } else { AirManager.Current.AddAir(); } data.health = 0f; } } [HarmonyPostfix] [HarmonyWrapSafe] [HarmonyPatch(typeof(PlayerAgent), "Setup")] internal static void Post_Setup(PlayerAgent __instance) { if (((Agent)__instance).IsLocallyOwned) { AirManager.Setup(__instance); } } } } namespace Oxygen.Config { public class ConfigManager { private static readonly JsonSerializerOptions s_SerializerOptions; public static T Deserialize<T>(string json) { return JsonSerializer.Deserialize<T>(json, s_SerializerOptions); } public static string Serialize<T>(T value) { return JsonSerializer.Serialize(value, s_SerializerOptions); } static ConfigManager() { s_SerializerOptions = new JsonSerializerOptions { AllowTrailingCommas = true, ReadCommentHandling = JsonCommentHandling.Skip, PropertyNameCaseInsensitive = true, WriteIndented = true }; s_SerializerOptions.Converters.Add(new JsonStringEnumConverter()); if (MTFOPartialDataUtil.IsLoaded && MTFOPartialDataUtil.Initialized) { s_SerializerOptions.Converters.Add(MTFOPartialDataUtil.PersistentIDConverter); s_SerializerOptions.Converters.Add(MTFOPartialDataUtil.LocalizedTextConverter); Log.Message("PartialData Support Found!"); } else { s_SerializerOptions.Converters.Add(new LocalizedTextConverter()); } } public static void Load<T>(string file, out T config) where T : new() { if (file.Length < ".json".Length) { config = default(T); return; } if (file.Substring(file.Length - ".json".Length) != ".json") { file += ".json"; } file = File.ReadAllText(Path.Combine(ConfigManager.CustomPath, "Oxygen", file)); config = Deserialize<T>(file); } } public class AirText { public float x { get; set; } public float y { get; set; } public LocalizedText Text { get; set; } } public class OxygenConfig { public List<OxygenBlock> Blocks { get; set; } = new List<OxygenBlock> { new OxygenBlock() }; } public class OxygenBlock { public float AirLoss { get; set; } public float AirGain { get; set; } = 1f; public float DamageTime { get; set; } = 1f; public float DamageAmount { get; set; } public bool ShatterGlass { get; set; } public float ShatterAmount { get; set; } public float DamageThreshold { get; set; } = 0.1f; public bool AlwaysDisplayAirBar { get; set; } public float HealthRegenProportion { get; set; } = 1f; public float TimeToStartHealthRegen { get; set; } = 3f; public float TimeToCompleteHealthRegen { get; set; } = 5f; public AirText AirText { get; set; } public List<uint> FogSettings { get; set; } = new List<uint> { 0u }; } } namespace Oxygen.Components { public class AirBar : MonoBehaviour { public static AirBar Current; private TextMeshPro m_airText; private TextMeshPro m_airTextLocalization; private float m_airTextX; private float m_airTextY; private float m_airTextZ; private RectTransform m_air1; private RectTransform m_air2; private SpriteRenderer m_airBar1; private SpriteRenderer m_airBar2; private float m_airWidth = 100f; private float m_barHeightMin = 3f; private float m_barHeightMax = 9f; private Color m_airLow = new Color(0f, 0.5f, 0.5f); private Color m_airHigh = new Color(0f, 0.3f, 0.8f); public AirBar(IntPtr value) : base(value) { }//IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) public static void Setup() { if ((Object)(object)Current == (Object)null) { Current = ((Component)GuiManager.Current.m_playerLayer.m_playerStatus).gameObject.AddComponent<AirBar>(); Current.Init(); } } private void Init() { //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_01ac: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: Unknown result type (might be due to invalid IL or missing references) //IL_0270: Unknown result type (might be due to invalid IL or missing references) //IL_027a: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)m_airText == (Object)null) { m_airText = ((Component)GuiManager.Current.m_playerLayer.m_playerStatus.m_healthText).gameObject.Instantiate<TextMeshPro>("AirText"); TextMeshPro airText = m_airText; ((TMP_Text)airText).fontSize = ((TMP_Text)airText).fontSize / 1.25f; m_airText.transform.Translate(0f, -30f, 0f); } if ((Object)(object)m_airTextLocalization == (Object)null) { m_airTextLocalization = ((Component)GuiManager.Current.m_playerLayer.m_playerStatus.m_pulseText).gameObject.Instantiate<TextMeshPro>("AirText Localization"); ((Behaviour)m_airTextLocalization).enabled = true; m_airTextLocalization.transform.Translate(300f - m_airWidth, -45f, 0f); m_airTextX = m_airTextLocalization.transform.position.x; m_airTextY = m_airTextLocalization.transform.position.y; m_airTextZ = m_airTextLocalization.transform.position.z; } if ((Object)(object)m_air1 == (Object)null) { m_air1 = ((Component)((Component)GuiManager.Current.m_playerLayer.m_playerStatus.m_health1).gameObject.transform.parent).gameObject.Instantiate<RectTransform>("AirFill Right"); ((Component)m_air1).transform.Translate(0f, -30f, 0f); SpriteRenderer component = ((Component)((Transform)m_air1).GetChild(0)).GetComponent<SpriteRenderer>(); component.size = new Vector2(m_airWidth, component.size.y); m_airBar1 = ((Component)((Transform)m_air1).GetChild(1)).GetComponent<SpriteRenderer>(); ((Renderer)((Component)((Transform)m_air1).GetChild(2)).GetComponent<SpriteRenderer>()).enabled = false; } if ((Object)(object)m_air2 == (Object)null) { m_air2 = ((Component)((Component)GuiManager.Current.m_playerLayer.m_playerStatus.m_health2).gameObject.transform.parent).gameObject.Instantiate<RectTransform>("AirFill Left"); ((Component)m_air2).transform.Translate(0f, 30f, 0f); SpriteRenderer component2 = ((Component)((Transform)m_air2).GetChild(0)).GetComponent<SpriteRenderer>(); component2.size = new Vector2(m_airWidth, component2.size.y); m_airBar2 = ((Component)((Transform)m_air2).GetChild(1)).GetComponent<SpriteRenderer>(); ((Renderer)((Component)((Transform)m_air2).GetChild(2)).GetComponent<SpriteRenderer>()).enabled = false; } UpdateAirBar(1f); SetVisible(vis: false); } public void UpdateAirBar(float air) { SetAirPercentageText(air); SetAirBar(m_airBar1, air); SetAirBar(m_airBar2, air); } private void SetAirBar(SpriteRenderer bar, float val) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) bar.size = new Vector2(val * m_airWidth, Mathf.Lerp(m_barHeightMin, m_barHeightMax, val)); bar.color = Color.Lerp(m_airLow, m_airHigh, val); } private void SetAirPercentageText(float val) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0029: 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) Color color = Color.Lerp(m_airLow, m_airHigh, val); ((TMP_Text)m_airText).text = "O<size=75%>2</size>"; ((Graphic)m_airText).color = color; ((TMP_Text)m_airText).ForceMeshUpdate(true, false); ((Graphic)m_airTextLocalization).color = color; ((TMP_Text)m_airTextLocalization).ForceMeshUpdate(true, false); } public void UpdateAirText(OxygenBlock config) { //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) if (config != null) { string text = LocalizedText.op_Implicit(config.AirText.Text); float x = config.AirText.x; float y = config.AirText.y; ((TMP_Text)m_airTextLocalization).text = text; ((TMP_Text)m_airTextLocalization).ForceMeshUpdate(true, false); CoroutineManager.BlinkIn(((Component)m_airTextLocalization).gameObject, 0f); m_airTextLocalization.transform.SetPositionAndRotation(new Vector3(m_airTextX + x, m_airTextY + y, m_airTextZ), m_airTextLocalization.transform.rotation); } } public void SetVisible(bool vis) { ((Component)m_airText).gameObject.SetActive(vis); ((Component)m_airTextLocalization).gameObject.SetActive(vis); ((Component)m_air1).gameObject.SetActive(vis); ((Component)m_air2).gameObject.SetActive(vis); } public static void OnLevelCleanup() { if (!((Object)(object)Current == (Object)null)) { Current.SetVisible(vis: false); } } } public class AirManager : MonoBehaviour { public static AirManager Current; public PlayerAgent m_playerAgent; private HUDGlassShatter m_hudGlass; private Dam_PlayerDamageBase Damage; public OxygenBlock config; private uint fogSetting; private FogSettingsDataBlock fogSettingDB; private float airAmount = 1f; private float damageTick; private float glassShatterAmount; private bool m_isInInfectionLoop; private bool isRegeningHealth; private float healthToRegen; private float healthRegenTick; private float tickUntilHealthRegenHealthStart; private readonly float regenHealthTickInterval = 0.25f; private float healthRegenAmountPerInterval; internal bool PlayerShouldCough; private readonly float CoughPerLoss = 0.1f; private float CoughLoss; public AirManager(IntPtr value) : base(value) { } public static void Setup(PlayerAgent playerAgent) { Current = ((Component)playerAgent).gameObject.AddComponent<AirManager>(); } public static void OnBuildDone() { if (!((Object)(object)Current == (Object)null)) { Current.m_playerAgent = PlayerManager.GetLocalPlayerAgent(); Current.m_hudGlass = ((Component)Current.m_playerAgent.FPSCamera).GetComponent<HUDGlassShatter>(); Current.Damage = ((Component)Current.m_playerAgent).gameObject.GetComponent<Dam_PlayerDamageBase>(); Current.UpdateAirConfig(RundownManager.ActiveExpedition.Expedition.FogSettings); AirBar.Current.UpdateAirText(Current.config); } } public static void OnLevelCleanup() { if (!((Object)(object)Current == (Object)null)) { if (Current.m_isInInfectionLoop) { Current.StopInfectionLoop(); } Current.config = null; Current.fogSetting = 0u; Current.fogSettingDB = null; Current.airAmount = 0f; Current.damageTick = 0f; Current.glassShatterAmount = 0f; Current.healthToRegen = 0f; Current.m_playerAgent = null; Current.m_hudGlass = null; Current.Damage = null; } } private void Update() { if (!RundownManager.ExpeditionIsStarted) { return; } if (!HasAirConfig()) { AirBar.Current.SetVisible(vis: false); return; } if (airAmount == 1f) { if (config.AlwaysDisplayAirBar) { AirBar.Current.SetVisible(vis: true); } else { AirBar.Current.SetVisible(vis: false); } } else { AirBar.Current.SetVisible(vis: true); } if (airAmount <= config.DamageThreshold) { damageTick += Time.deltaTime; if (damageTick > config.DamageTime && ((Agent)m_playerAgent).Alive) { AirDamage(); } isRegeningHealth = false; } else if (healthToRegen > 0f) { tickUntilHealthRegenHealthStart += Time.deltaTime; if (tickUntilHealthRegenHealthStart > config.TimeToStartHealthRegen) { if (healthRegenAmountPerInterval == 0f) { healthRegenAmountPerInterval = healthToRegen * (regenHealthTickInterval / config.TimeToCompleteHealthRegen); } RegenHealth(); if (!isRegeningHealth) { Damage.m_nextRegen = Clock.Time + config.TimeToStartHealthRegen + config.TimeToCompleteHealthRegen; isRegeningHealth = true; } } } else { isRegeningHealth = false; } } public void AddAir() { if (HasAirConfig()) { float airGain = config.AirGain; airAmount = Mathf.Clamp01(airAmount + airGain); AirBar.Current.UpdateAirBar(airAmount); if (fogSettingDB.Infection <= 0f && m_isInInfectionLoop) { StopInfectionLoop(); } } } public void RemoveAir(float amount) { if (HasAirConfig()) { amount = config.AirLoss; airAmount = Mathf.Clamp01(airAmount - amount); AirBar.Current.UpdateAirBar(airAmount); if (fogSettingDB.Infection <= 0f && amount > 0f) { StartInfectionLoop(); } } } public void AirDamage() { float health = ((Dam_SyncedDamageBase)Damage).Health; float damageAmount = config.DamageAmount; Damage.m_nextRegen = Clock.Time + config.TimeToStartHealthRegen; if (!(health <= 1f)) { ((Dam_SyncedDamageBase)Damage).NoAirDamage(damageAmount); if (config.ShatterGlass) { glassShatterAmount += config.ShatterAmount; m_hudGlass.SetGlassShatterProgression(glassShatterAmount); } damageTick = 0f; tickUntilHealthRegenHealthStart = 0f; healthRegenAmountPerInterval = 0f; healthToRegen += damageAmount * config.HealthRegenProportion; CoughLoss += damageAmount; if (CoughLoss > CoughPerLoss) { PlayerShouldCough = true; CoughLoss = 0f; } } } public void RegenHealth() { if (healthToRegen <= 0f) { return; } tickUntilHealthRegenHealthStart = config.TimeToStartHealthRegen; healthRegenTick += Time.deltaTime; if (healthRegenTick > regenHealthTickInterval) { float num = healthRegenAmountPerInterval; if (num >= healthToRegen) { num = healthToRegen; healthToRegen = 0f; tickUntilHealthRegenHealthStart = 0f; healthRegenAmountPerInterval = 0f; isRegeningHealth = false; } else { healthToRegen -= num; } ((Dam_SyncedDamageBase)Damage).AddHealth(num, (Agent)(object)m_playerAgent); healthRegenTick = 0f; } } public void UpdateAirConfig(uint fogsetting, bool LiveEditForceUpdate = false) { if (fogsetting != 0 && (fogsetting != fogSetting || LiveEditForceUpdate)) { if (Plugin.lookup.ContainsKey(fogsetting)) { config = Plugin.lookup[fogsetting]; } else if (Plugin.lookup.ContainsKey(0u)) { config = Plugin.lookup[0u]; } else { config = null; airAmount = 1f; } fogSetting = fogsetting; fogSettingDB = GameDataBlockBase<FogSettingsDataBlock>.GetBlock(fogsetting); if (GameStateManager.IsInExpedition) { AirBar.Current.UpdateAirText(config); } } } public void ResetHealthToRegen() { healthRegenTick = 0f; healthToRegen = 0f; tickUntilHealthRegenHealthStart = 0f; } public float AirLoss() { if (config != null) { return config.AirLoss; } return 0f; } public bool AlwaysDisplayAirBar() { if (config != null) { return config.AlwaysDisplayAirBar; } return false; } public uint FogSetting() { return fogSetting; } public float HealthToRegen() { return healthToRegen; } public string AirText() { return LocalizedText.op_Implicit((config == null) ? null : config.AirText.Text); } public float AirTextX() { if (config != null) { return config.AirText.x; } return 0f; } public float AirTextY() { if (config != null) { return config.AirText.y; } return 0f; } public bool HasAirConfig() { return config != null; } public void StartInfectionLoop() { if (!m_isInInfectionLoop) { m_playerAgent.Sound.Post(EVENTS.INFECTION_EFFECT_LOOP_START, true); m_isInInfectionLoop = true; } } public void StopInfectionLoop() { if (m_isInInfectionLoop) { if ((Object)(object)m_playerAgent != (Object)null && m_playerAgent.Sound != null) { m_playerAgent.Sound.Post(EVENTS.INFECTION_EFFECT_LOOP_STOP, true); } m_isInInfectionLoop = false; } } } public class AirPlane : MonoBehaviour { public static AirPlane Current; public EV_Plane airPlane; private bool isAirPlaneRegistered; public AirPlane(IntPtr value) : base(value) { } public static void OnBuildStart() { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown if ((Object)(object)Current == (Object)null) { Current = ((Component)LocalPlayerAgentSettings.Current).gameObject.AddComponent<AirPlane>(); } Current.airPlane = new EV_Plane(); uint num = RundownManager.ActiveExpedition.Expedition.FogSettings; if (num == 0) { num = 21u; } OxygenBlock oxygenBlock = (Plugin.lookup.ContainsKey(num) ? Plugin.lookup[num] : ((!Plugin.lookup.ContainsKey(0u)) ? null : Plugin.lookup[0u])); FogSettingsDataBlock block = GameDataBlockBase<FogSettingsDataBlock>.GetBlock(num); ((EffectVolume)Current.airPlane).invert = block.DensityHeightMaxBoost > block.FogDensity; ((EffectVolume)Current.airPlane).contents = (eEffectVolumeContents)1; ((EffectVolume)Current.airPlane).modification = (eEffectVolumeModification)0; Current.airPlane.lowestAltitude = block.DensityHeightAltitude; Current.airPlane.highestAltitude = block.DensityHeightAltitude + block.DensityHeightRange; if (oxygenBlock != null) { ((EffectVolume)Current.airPlane).modificationScale = oxygenBlock.AirLoss; Current.Register(); } } public static void OnLevelCleanup() { if (!((Object)(object)Current == (Object)null)) { Current.Unregister(); Current.isAirPlaneRegistered = false; Current.airPlane = null; } } public void Register() { if (airPlane != null && !isAirPlaneRegistered) { EffectVolumeManager.RegisterVolume((EffectVolume)(object)airPlane); isAirPlaneRegistered = true; } } public void Unregister() { if (airPlane != null && isAirPlaneRegistered) { EffectVolumeManager.UnregisterVolume((EffectVolume)(object)airPlane); isAirPlaneRegistered = false; } } } }
plugins/net6/AccurateCrosshair.dll
Decompiled a month agousing System; using System.Collections; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using AccurateCrosshair.CrosshairPatches; using AccurateCrosshair.PluginDependencies; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Unity.IL2CPP; using BepInEx.Unity.IL2CPP.Utils.Collections; using ColorCrosshair.API; using GTFO.API; using GameData; using Gear; using HarmonyLib; using Il2CppInterop.Runtime.InteropTypes; using Il2CppSystem; using Microsoft.CodeAnalysis; using Player; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("AccurateCrosshair")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("AccurateCrosshair")] [assembly: AssemblyTitle("AccurateCrosshair")] [assembly: AssemblyVersion("1.0.0.0")] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace AccurateCrosshair { public static class Configuration { public static bool followsRecoil = true; public static FirstShotType firstShotType = FirstShotType.Inner; public static float firstShotMinDelay = 0.15f; public static bool popEnabled = false; public static float minSize = 10f; public static float speedScalar = 1f; public static void CreateAndBindAll() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown BindAll(new ConfigFile(Path.Combine(Paths.ConfigPath, "AccurateCrosshair.cfg"), true)); } private static void BindAll(ConfigFile config) { BindCrosshairPopEnabled(config); } private static void BindCrosshairPopEnabled(ConfigFile config) { //IL_0015: 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_0030: Expected O, but got Unknown //IL_0030: Expected O, but got Unknown //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown //IL_0064: Expected O, but got Unknown //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Expected O, but got Unknown //IL_0098: Expected O, but got Unknown //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Expected O, but got Unknown //IL_00cc: Expected O, but got Unknown //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Expected O, but got Unknown //IL_0100: Expected O, but got Unknown //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Expected O, but got Unknown //IL_0134: Expected O, but got Unknown string text = "General Settings"; string text2 = "Follow Recoil"; string text3 = "Enables or disables the crosshair moving to match weapon recoil that is independent of your aim."; followsRecoil = config.Bind<bool>(new ConfigDefinition(text, text2), followsRecoil, new ConfigDescription(text3, (AcceptableValueBase)null, Array.Empty<object>())).Value; text2 = "First Shot Display Mode"; text3 = "Determines how the crosshair shows the hidden bonus accuracy after waiting 2 seconds to shoot.\r\nInner: Shows another circle. Match: Reduces crosshair size to match. None: Turns this off."; firstShotType = config.Bind<FirstShotType>(new ConfigDefinition(text, text2), firstShotType, new ConfigDescription(text3, (AcceptableValueBase)null, Array.Empty<object>())).Value; text2 = "First Shot Min Delay"; text3 = "If First Shot Display Mode is set to Match, the minimum shot delay non-semi automatic weapons need for the first shot effect to appear."; firstShotMinDelay = config.Bind<float>(new ConfigDefinition(text, text2), firstShotMinDelay, new ConfigDescription(text3, (AcceptableValueBase)null, Array.Empty<object>())).Value; text2 = "Pop Enabled"; text3 = "Enables or disables the visual crosshair bloom when shooting.\r\nNote: Pop is not scaled to the accurate size and may be disproportionately large."; popEnabled = config.Bind<bool>(new ConfigDefinition(text, text2), popEnabled, new ConfigDescription(text3, (AcceptableValueBase)null, Array.Empty<object>())).Value; text2 = "Minimum Size"; text3 = "The minimum size of the reticle. Does not scale with field of view.\r\nNote: Cannot be smaller than 10."; minSize = config.Bind<float>(new ConfigDefinition(text, text2), minSize, new ConfigDescription(text3, (AcceptableValueBase)null, Array.Empty<object>())).Value; text2 = "Resize Modifier"; text3 = "Scalar applied to the speed at which the crosshair resizes to its target spread.\r\nNote: Must be larger than 0. Does not affect the resize speed of pop."; speedScalar = config.Bind<float>(new ConfigDefinition(text, text2), speedScalar, new ConfigDescription(text3, (AcceptableValueBase)null, Array.Empty<object>())).Value; if (speedScalar <= 0f) { speedScalar = 1f; } } } [BepInPlugin("Dinorush.AccurateCrosshair", "AccurateCrosshair", "1.3.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] internal sealed class Loader : BasePlugin { public const string MODNAME = "AccurateCrosshair"; [Conditional("DEBUG")] public static void DebugLog(object data) { } public override void Load() { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected O, but got Unknown ((BasePlugin)this).Log.LogMessage((object)"Loading AccurateCrosshair"); Configuration.CreateAndBindAll(); Harmony val = new Harmony("AccurateCrosshair"); val.PatchAll(typeof(SpreadPatches)); if (!Configuration.popEnabled) { val.PatchAll(typeof(PopPatches)); } if (Configuration.followsRecoil) { val.PatchAll(typeof(RecoilPatches)); } if (Configuration.firstShotType != 0) { val.PatchAll(typeof(FirstShotPatches)); } if (Configuration.firstShotType == FirstShotType.Inner) { val.PatchAll(typeof(FirstShotGuiPatches)); } AssetAPI.OnStartupAssetsLoaded += AssetAPI_OnStartupAssetsLoaded; ((BasePlugin)this).Log.LogMessage((object)"Loaded AccurateCrosshair"); } private void AssetAPI_OnStartupAssetsLoaded() { ColorCrosshairDependency.Init(); } } } namespace AccurateCrosshair.PluginDependencies { internal static class ColorCrosshairDependency { public static bool HasColorCrosshair => ((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.ContainsKey("Dinorush.ColorCrosshair"); public static Color DefaultColor => ColorCrosshairAPI.DefaultColor; public static Color ChargeColor => ColorCrosshairAPI.ChargeColor; public static Color ChargeBlinkColor => ColorCrosshairAPI.ChargeBlinkColor; public static Color ChargeWarningColor => ColorCrosshairAPI.ChargeWarningColor; public static Color EnemyBlinkColor => ColorCrosshairAPI.EnemyBlinkColor; public static void Init() { if (HasColorCrosshair && Configuration.firstShotType == FirstShotType.Inner) { UnsafeInit(); } } private static void UnsafeInit() { FirstShotGuiPatches.RefreshCrosshairColor(); ColorCrosshairAPI.OnReload += ApplyColorChanges; } private static void ApplyColorChanges() { FirstShotGuiPatches.RefreshCrosshairColor(); } } } namespace AccurateCrosshair.CrosshairPatches { internal sealed class FirstShotGui : GuiLayer { private CircleCrosshair? smallCrosshair; public override void OnLevelCleanup() { CircleCrosshair? obj = smallCrosshair; if (obj != null) { ((GuiLayerComp)obj).SetVisible(false, false); } } public override void Setup(Transform root, string name) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) ((GuiLayer)this).Setup(root, name); GuiLayerComp val = ((GuiLayer)this).AddComp("Gui/Crosshairs/CanvasCircleCrosshair", (GuiAnchor)3, default(Vector2), (Transform)null); smallCrosshair = ((Il2CppObjectBase)val).TryCast<CircleCrosshair>(); if ((Object)(object)smallCrosshair != (Object)null) { smallCrosshair.UpdateAlphaMul(CellSettingsManager.SettingsData.HUD.Player_CrosshairOpacity.Value); RefreshColor(); ((GuiLayerComp)smallCrosshair).SetVisible(false, false); } } public void Disable() { CircleCrosshair? obj = smallCrosshair; if (obj != null) { ((GuiLayerComp)obj).SetVisible(false, false); } } public void Enable(float size) { if (!((Object)(object)smallCrosshair == (Object)null) && !(size < 0f) && !(size <= Configuration.minSize)) { float num = Math.Max(size * 0.2f, Configuration.minSize); ((GuiLayerComp)smallCrosshair).SetVisible(true, false); smallCrosshair.SetScale(num / smallCrosshair.m_circleRadius); } } public void RefreshAlpha() { CircleCrosshair? obj = smallCrosshair; if (obj != null) { obj.UpdateAlphaMul(CellSettingsManager.SettingsData.HUD.Player_CrosshairOpacity.Value); } } public void RefreshColor() { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_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) if (!((Object)(object)smallCrosshair == (Object)null) && ColorCrosshairDependency.HasColorCrosshair) { CircleCrosshair? obj = smallCrosshair; Color color = (smallCrosshair.m_crosshairColOrg = ColorCrosshairDependency.DefaultColor); obj.SetColor(color); } } } internal static class FirstShotGuiPatches { public static FirstShotGui crosshairGui = new FirstShotGui(); public static void Disable() { crosshairGui.Disable(); } public static void Enable(float size, bool forceOn = false) { if (forceOn || ((GuiLayerComp)GuiManager.CrosshairLayer.m_circleCrosshair).GetVisible()) { crosshairGui.Enable(size); } } public static void RefreshCrosshairColor() { crosshairGui.RefreshColor(); } [HarmonyPatch(typeof(GuiManager), "Setup")] [HarmonyWrapSafe] [HarmonyPostfix] private static void SetupSmallCrosshair(GuiManager __instance) { ((GuiLayer)crosshairGui).Setup(__instance.m_root, "SmallCrosshairLayer"); } [HarmonyPatch(typeof(CrosshairGuiLayer), "OnSetVisible")] [HarmonyWrapSafe] [HarmonyPostfix] private static void MatchLayerVisibility(CrosshairGuiLayer __instance, bool visible) { ((GuiLayer)crosshairGui).SetVisible(visible); } [HarmonyPatch(typeof(CrosshairGuiLayer), "HideCircleCrosshair")] [HarmonyWrapSafe] [HarmonyPostfix] private static void MatchCrosshairVisibility(CrosshairGuiLayer __instance) { crosshairGui.Disable(); } [HarmonyPatch(typeof(CrosshairGuiLayer), "UpdateAlphaFromSettings")] [HarmonyWrapSafe] [HarmonyPostfix] private static void MatchCrosshairAlpha(CrosshairGuiLayer __instance) { crosshairGui.RefreshAlpha(); } } internal static class FirstShotPatches { private static Coroutine? firstShotRoutine = null; private static float firstShotTime = 0f; private static float fireRecoilCooldown = 2f; private static float storedCrosshairSize = -1f; private static void EnableSmallCrosshair(bool forceGuiOn = false) { if (Configuration.firstShotType == FirstShotType.Match) { SpreadPatches.SetCrosshairSize(storedCrosshairSize * 0.2f); } else if (Configuration.firstShotType == FirstShotType.Inner) { FirstShotGuiPatches.Enable(storedCrosshairSize, forceGuiOn); } } private static IEnumerator MinimizeAfterDelay() { while (firstShotTime > Clock.Time) { yield return (object)new WaitForSeconds(firstShotTime - Clock.Time); } firstShotRoutine = null; if (!(storedCrosshairSize < 0f)) { EnableSmallCrosshair(); } } public static void SetStoredCrosshair(BulletWeapon weapon, ref float crosshairSize) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) ArchetypeDataBlock archetypeData = ((ItemEquippable)weapon).ArchetypeData; if (Configuration.firstShotType == FirstShotType.Match && (int)archetypeData.FireMode != 0 && archetypeData.ShotDelay < Configuration.firstShotMinDelay) { return; } storedCrosshairSize = crosshairSize; fireRecoilCooldown = weapon.m_fireRecoilCooldown; firstShotTime = weapon.m_lastFireTime + fireRecoilCooldown; if (firstShotTime > Clock.Time) { if (firstShotRoutine == null) { firstShotRoutine = CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(MinimizeAfterDelay()), (Action)null); } return; } if (Configuration.firstShotType == FirstShotType.Match) { crosshairSize = Math.Max(crosshairSize * 0.2f, Configuration.minSize); } EnableSmallCrosshair(forceGuiOn: true); } public static void ResetStoredCrosshair() { storedCrosshairSize = -1f; FirstShotGuiPatches.Disable(); } [HarmonyPatch(typeof(BulletWeapon), "Fire")] [HarmonyWrapSafe] [HarmonyPostfix] private static void ResetFirstShotTimer(BulletWeapon __instance) { firstShotTime = Clock.Time + fireRecoilCooldown; SpreadPatches.SetCrosshairSize(storedCrosshairSize); FirstShotGuiPatches.Disable(); if (firstShotRoutine == null) { firstShotRoutine = CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(MinimizeAfterDelay()), (Action)null); } } } public enum FirstShotType { None, Match, Inner } internal static class PopPatches { [HarmonyPatch(typeof(CrosshairGuiLayer), "PopCircleCrosshair")] [HarmonyPrefix] public static bool CancelRecoilPop(CrosshairGuiLayer __instance, float pop, float sizeMax) { return false; } } internal static class RecoilPatches { [HarmonyPatch(typeof(CrosshairGuiLayer), "ShowSpreadCircle")] [HarmonyWrapSafe] [HarmonyPostfix] private static void EnableCrosshairMovement(CrosshairGuiLayer __instance, ref float crosshairSize) { __instance.m_moveCircleCrosshair = !SpreadPatches.isShotgun; } [HarmonyPatch(typeof(FPS_RecoilSystem), "FPS_Update")] [HarmonyWrapSafe] [HarmonyPostfix] private static void TightCrosshairMovement(FPS_RecoilSystem __instance) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) float scale = GuiManager.CrosshairLayer.m_circleCrosshair.GetScale(); Vector2 val = __instance.CurrentVSPos - new Vector2(0.5f, 0.5f); val.y *= 0.78f; GuiManager.CrosshairLayer.SetCrosshairPosition(val / scale + new Vector2(0.5f, 0.5f)); } } internal static class SpreadPatches { private const float BASE_CROSSHAIR_SIZE = 20f; private const float EXTRA_BUFFER_SIZE = 10f; public static bool isShotgun; public static void SetCrosshairSize(float crosshairSize) { if (Configuration.firstShotType == FirstShotType.Match && !(crosshairSize < 0f)) { crosshairSize = Math.Max(Configuration.minSize, crosshairSize); CrosshairGuiLayer crosshairLayer = GuiManager.CrosshairLayer; float num2 = (GuiManager.CrosshairLayer.m_neutralCircleSize = crosshairSize); crosshairLayer.ScaleToSize(num2); } } [HarmonyPatch(typeof(CrosshairGuiLayer), "ShowSpreadCircle")] [HarmonyWrapSafe] [HarmonyPrefix] private static void AdjustCrosshairSize(CrosshairGuiLayer __instance, ref float crosshairSize) { if (Configuration.firstShotType != 0) { FirstShotPatches.ResetStoredCrosshair(); } BulletWeapon val = ((Il2CppObjectBase)PlayerManager.GetLocalPlayerAgent().Inventory.m_wieldedItem).TryCast<BulletWeapon>(); if ((Object)(object)val == (Object)null) { return; } isShotgun = (Object)(object)((Il2CppObjectBase)val).TryCast<Shotgun>() != (Object)null; float num = CellSettingsManager.SettingsData.Video.Fov.Value; ArchetypeDataBlock archetypeData = ((ItemEquippable)val).ArchetypeData; if (archetypeData != null) { float num2 = (float)(20.0 / Math.Tan(Math.PI / 180.0 * (double)num / 2.0)); float num3 = (isShotgun ? ((float)(archetypeData.ShotgunConeSize + archetypeData.ShotgunBulletSpread)) : archetypeData.HipFireSpread); float num4 = Math.Max(Configuration.minSize, num3 * num2 + 10f); crosshairSize = num4; if (!isShotgun && Configuration.firstShotType != 0) { FirstShotPatches.SetStoredCrosshair(val, ref crosshairSize); } } } [HarmonyPatch(typeof(CrosshairGuiLayer), "Setup")] [HarmonyWrapSafe] [HarmonyPostfix] private static void AdjustResizeSpeed(CrosshairGuiLayer __instance) { __instance.m_circleSpeed *= Configuration.speedScalar; } } }
plugins/net6/AggroFix.dll
Decompiled a month agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using AIGraph; using API; using Agents; using AggroFix.BepInEx; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using Enemies; using GameData; using HarmonyLib; using Il2CppInterop.Runtime.InteropTypes; using Il2CppSystem.Collections.Generic; using LevelGeneration; using Microsoft.CodeAnalysis; using Player; using SNetwork; using StateMachines; using UnityEngine; using UnityEngine.Analytics; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("AggroFix")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+5123c82eb5645215ab741db6f025d7437a163404")] [assembly: AssemblyProduct("AggroFix")] [assembly: AssemblyTitle("AggroFix")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace AggroFix { [HarmonyPatch] internal static class Fix { private static bool patch = true; private static bool IsTargetReachable(AIG_CourseNode source, AIG_CourseNode target) { //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Invalid comparison between Unknown and I4 //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Invalid comparison between Unknown and I4 if (source == null || target == null) { return false; } if (source.NodeID == target.NodeID) { return true; } AIG_SearchID.IncrementSearchID(); ushort searchID = AIG_SearchID.SearchID; Queue<AIG_CourseNode> queue = new Queue<AIG_CourseNode>(); queue.Enqueue(source); while (queue.Count > 0) { AIG_CourseNode val = queue.Dequeue(); ((AIG_CourseGraphMember)val).m_searchID = searchID; Enumerator<AIG_CoursePortal> enumerator = val.m_portals.GetEnumerator(); while (enumerator.MoveNext()) { AIG_CoursePortal current = enumerator.Current; LG_Gate gate = current.Gate; object obj; if (gate == null) { obj = null; } else { iLG_Door_Core spawnedDoor = gate.SpawnedDoor; obj = ((spawnedDoor != null) ? ((Il2CppObjectBase)spawnedDoor).TryCast<LG_SecurityDoor>() : null); } LG_SecurityDoor val2 = (LG_SecurityDoor)obj; if ((Object)(object)val2 != (Object)null) { DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(16, 2); defaultInterpolatedStringHandler.AppendLiteral("SecurityDoor "); defaultInterpolatedStringHandler.AppendFormatted(val2.m_serialNumber); defaultInterpolatedStringHandler.AppendLiteral(" - "); eDoorStatus lastStatus = val2.LastStatus; defaultInterpolatedStringHandler.AppendFormatted(((object)(eDoorStatus)(ref lastStatus)).ToString()); APILogger.Debug(defaultInterpolatedStringHandler.ToStringAndClear()); if ((int)val2.LastStatus != 10 && (int)val2.LastStatus != 16) { continue; } } AIG_CourseNode oppositeNode = current.GetOppositeNode(val); if (((AIG_CourseGraphMember)oppositeNode).m_searchID != searchID) { if (oppositeNode.NodeID == target.NodeID) { return true; } queue.Enqueue(oppositeNode); } } } return false; } [HarmonyPatch(typeof(EnemyCourseNavigation), "UpdateTracking")] [HarmonyPostfix] private static void UpdateTracking(EnemyCourseNavigation __instance) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Invalid comparison between Unknown and I4 if (!patch || !SNet.IsMaster) { return; } EnemyAgent owner = __instance.m_owner; if (((Agent)owner).CourseNode != null && __instance.m_targetRef != null && (int)((StateMachine<ES_Base>)(object)owner.Locomotion).m_currentState.m_stateEnum != 14 && !IsTargetReachable(((Agent)owner).CourseNode, __instance.m_targetRef.m_agent.CourseNode)) { int num = Random.RandomRangeInt(0, PlayerManager.PlayerAgentsInLevel.Count); PlayerAgent val = PlayerManager.PlayerAgentsInLevel[num]; while (PlayerManager.PlayerAgentsInLevel.Count != 1 && ((Object)val).GetInstanceID() == ((Object)__instance.m_targetRef.m_agent).GetInstanceID()) { num = (num + 1) % PlayerManager.PlayerAgentsInLevel.Count; val = PlayerManager.PlayerAgentsInLevel[num]; } patch = false; ((AgentAI)owner.AI).SetTarget((Agent)(object)val); patch = true; } } } } namespace AggroFix.BepInEx { public static class Module { public const string GUID = "randomuserhi.AggroFix"; public const string Name = "AggroFix"; public const string Version = "0.0.1"; } public static class ConfigManager { public static ConfigFile configFile; private static ConfigEntry<bool> debug; public static bool Debug { get { return debug.Value; } set { debug.Value = value; } } static ConfigManager() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown configFile = new ConfigFile(Path.Combine(Paths.ConfigPath, "AggroFix.cfg"), true); debug = configFile.Bind<bool>("Debug", "enable", false, "Enables debug messages when true."); } } [BepInPlugin("randomuserhi.AggroFix", "AggroFix", "0.0.1")] public class Plugin : BasePlugin { private static Harmony? harmony; public override void Load() { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected O, but got Unknown APILogger.Log("Plugin is loaded!"); harmony = new Harmony("randomuserhi.AggroFix"); harmony.PatchAll(); APILogger.Log("Debug is " + (ConfigManager.Debug ? "Enabled" : "Disabled")); } } } namespace API { [HarmonyPatch(typeof(GameDataInit))] internal class GameDataInit_Patches { [HarmonyPatch("Initialize")] [HarmonyWrapSafe] [HarmonyPostfix] public static void Initialize_Postfix() { Analytics.enabled = false; } } internal static class APILogger { private static readonly ManualLogSource logger; static APILogger() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Expected O, but got Unknown logger = new ManualLogSource("Rand-API"); Logger.Sources.Add((ILogSource)(object)logger); } private static string Format(string module, object msg) { return $"[{module}]: {msg}"; } public static void Info(string module, object data) { logger.LogMessage((object)Format(module, data)); } public static void Verbose(string module, object data) { } public static void Log(object data) { logger.LogDebug((object)Format("AggroFix", data)); } public static void Debug(object data) { if (ConfigManager.Debug) { Log(data); } } public static void Warn(object data) { logger.LogWarning((object)Format("AggroFix", data)); } public static void Error(object data) { logger.LogError((object)Format("AggroFix", data)); } } }
plugins/net6/DMRReloadFix.dll
Decompiled a month agousing System; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using API; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using GameData; using HarmonyLib; using Microsoft.CodeAnalysis; using Player; using UnityEngine.Analytics; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("DMRReloadFix")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+186b8e6130edc88c84ce66b13d2fa3c82c8ec868")] [assembly: AssemblyProduct("DMRReloadFix")] [assembly: AssemblyTitle("DMRReloadFix")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace DMRReloadFix { public static class ConfigManager { private static ConfigEntry<bool> debug; public static bool Debug => debug.Value; static ConfigManager() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) debug = new ConfigFile(Path.Combine(Paths.ConfigPath, "DMRReloadFix.cfg"), true).Bind<bool>("Debug", "enable", false, "Enables debug messages when true."); } } public static class Module { public const string GUID = "randomuserhi.DMRReloadFix"; public const string Name = "DMRReloadFix"; public const string Version = "0.0.1"; } [BepInPlugin("randomuserhi.DMRReloadFix", "DMRReloadFix", "0.0.1")] internal class Entry : BasePlugin { private Harmony harmony; public override void Load() { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown APILogger.Debug("DMRReloadFix", "Loaded DMRReloadFix"); harmony = new Harmony("randomuserhi.DMRReloadFix"); harmony.PatchAll(); APILogger.Debug("DMRReloadFix", "Debug is " + (ConfigManager.Debug ? "Enabled" : "Disabled")); } } } namespace DMRReloadFix.Patches { [HarmonyPatch(typeof(GameDataInit))] internal class GameDataInit_Patches { [HarmonyPatch("Initialize")] [HarmonyWrapSafe] [HarmonyPostfix] public static void Initialize_Postfix() { Analytics.enabled = false; } } [HarmonyPatch] internal static class Reload { private static bool callOriginal; [HarmonyPatch(typeof(PlayerAmmoStorage), "GetClipBulletsFromPack")] [HarmonyPrefix] private static bool Prefix_GetClipBulletsFromPack(PlayerAmmoStorage __instance, ref int __result, int currentClip, AmmoType ammoType) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (!callOriginal) { callOriginal = true; __result = __instance.GetClipBulletsFromPack(__instance.GetClipBulletsFromPack(currentClip, ammoType), ammoType); callOriginal = false; return false; } return true; } } } namespace API { internal static class APILogger { private static readonly ManualLogSource logger; static APILogger() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Expected O, but got Unknown logger = new ManualLogSource("Rand-API"); Logger.Sources.Add((ILogSource)(object)logger); } private static string Format(string module, object msg) { return $"[{module}]: {msg}"; } public static void Info(string module, object data) { logger.LogMessage((object)Format(module, data)); } public static void Verbose(string module, object data) { } public static void Debug(string module, object data) { logger.LogDebug((object)Format(module, data)); } public static void Warn(string module, object data) { logger.LogWarning((object)Format(module, data)); } public static void Error(string module, object data) { logger.LogError((object)Format(module, data)); } } }
plugins/net6/FloLib.dll
Decompiled a month ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using AIGraph; using AK; using Agents; using AssetShards; using BepInEx; using BepInEx.Core.Logging.Interpolation; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using BepInEx.Unity.IL2CPP.Hook; using BepInEx.Unity.IL2CPP.Utils; using BepInEx.Unity.IL2CPP.Utils.Collections; using FloLib.Attributes; using FloLib.Events; using FloLib.Infos; using FloLib.Infos.Comps; using FloLib.Infos.Inject; using FloLib.Networks; using FloLib.Networks.Inject; using FloLib.Networks.PayloadStructs; using FloLib.Utils; using FloLib.Utils.Comps; using FloLib.Utils.Extensions; using GTFO.API; using GameData; using HarmonyLib; using Il2CppInterop.Runtime; using Il2CppInterop.Runtime.Injection; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.InteropTypes.Arrays; using Il2CppInterop.Runtime.InteropTypes.Fields; using Il2CppInterop.Runtime.Runtime; using Il2CppSystem; using Il2CppSystem.Collections.Generic; using LevelGeneration; using Microsoft.CodeAnalysis; using Player; using SNetwork; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("FloLib")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+gitd7090d7-dirty-master")] [assembly: AssemblyProduct("FloLib")] [assembly: AssemblyTitle("FloLib")] [assembly: TargetPlatform("Windows7.0")] [assembly: SupportedOSPlatform("Windows7.0")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NativeIntegerAttribute : Attribute { public readonly bool[] TransformFlags; public NativeIntegerAttribute() { TransformFlags = new bool[1] { true }; } public NativeIntegerAttribute(bool[] P_0) { TransformFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FloLib { public static class Automation { private const BindingFlags ALL = BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic; private static readonly Queue<(MethodInfo method, object[] args)> _InvokeWhenStartGame; private static readonly Queue<(MethodInfo method, object[] args)> _InvokeWhenStartupAssetLoaded; private static readonly Queue<(MethodInfo method, object[] args)> _InvokeWhenEnemyAssetLoaded; private static readonly Queue<(MethodInfo method, object[] args)> _InvokeWhenSharedAssetLoaded; private static readonly Queue<(MethodInfo method, object[] args)> _InvokeWhenAllAssetsLoaded; static Automation() { _InvokeWhenStartGame = new Queue<(MethodInfo, object[])>(); _InvokeWhenStartupAssetLoaded = new Queue<(MethodInfo, object[])>(); _InvokeWhenEnemyAssetLoaded = new Queue<(MethodInfo, object[])>(); _InvokeWhenSharedAssetLoaded = new Queue<(MethodInfo, object[])>(); _InvokeWhenAllAssetsLoaded = new Queue<(MethodInfo, object[])>(); StartGameEvent.OnGameLoaded += delegate { (MethodInfo, object[]) result5; while (_InvokeWhenStartGame.TryDequeue(out result5)) { RunMethod(result5.Item1, result5.Item2); } }; AssetEvent.OnStartupAssetLoaded += delegate { (MethodInfo, object[]) result4; while (_InvokeWhenStartupAssetLoaded.TryDequeue(out result4)) { RunMethod(result4.Item1, result4.Item2); } }; AssetEvent.OnEnemyAssetLoaded += delegate { (MethodInfo, object[]) result3; while (_InvokeWhenEnemyAssetLoaded.TryDequeue(out result3)) { RunMethod(result3.Item1, result3.Item2); } }; AssetEvent.OnSharedAssetLoaded += delegate { (MethodInfo, object[]) result2; while (_InvokeWhenSharedAssetLoaded.TryDequeue(out result2)) { RunMethod(result2.Item1, result2.Item2); } }; AssetEvent.OnAllAssetsLoaded += delegate { (MethodInfo, object[]) result; while (_InvokeWhenAllAssetsLoaded.TryDequeue(out result)) { RunMethod(result.Item1, result.Item2); } }; } public static void RegisterTypes() { Assembly obj = new StackFrame(1).GetMethod()?.GetType()?.Assembly ?? null; if (obj == null) { throw new NullReferenceException("Caller Assembly was null"); } RegisterTypes(obj); } public static void RegisterTypes(Type target) { if (target == null) { throw new ArgumentNullException("target"); } RegisterTypes(target.Assembly); } public static void RegisterTypes(Assembly target) { if (target == null) { throw new ArgumentNullException("target"); } InjectAll(target); AddAutoInvokes(target); } private static void InjectAll(Assembly assem) { //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_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Expected O, but got Unknown foreach (Type item in assem.GetTypes()?.Where((Type x) => Attribute.IsDefined(x, typeof(AutoInjectAttribute))) ?? Enumerable.Empty<Type>()) { AutoInjectAttribute autoInjectAttribute = (AutoInjectAttribute)Attribute.GetCustomAttribute(item, typeof(AutoInjectAttribute)); if (autoInjectAttribute.Interfaces.Length != 0) { RegisterTypeOptions val = new RegisterTypeOptions(); val.set_Interfaces(Il2CppInterfaceCollection.op_Implicit(autoInjectAttribute.Interfaces)); val.set_LogSuccess(RegisterTypeOptions.Default.LogSuccess); ClassInjector.RegisterTypeInIl2Cpp(item, val); } else { ClassInjector.RegisterTypeInIl2Cpp(item); } } } private static void AddAutoInvokes(Assembly assem) { foreach (MethodInfo item in assem.GetTypes()?.SelectMany((Type x) => x.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))?.Where((MethodInfo x) => x.IsStatic && Attribute.IsDefined(x, typeof(AutoInvokeAttribute))) ?? Enumerable.Empty<MethodInfo>()) { AutoInvokeAttribute obj = (AutoInvokeAttribute)Attribute.GetCustomAttribute(item, typeof(AutoInvokeAttribute)); object[] arguments = obj.Arguments; switch (obj.When) { case InvokeWhen.PluginLoaded: RunMethod(item, arguments); break; case InvokeWhen.StartGame: _InvokeWhenStartGame.Enqueue((item, arguments)); break; case InvokeWhen.StartupAssetLoaded: _InvokeWhenStartupAssetLoaded.Enqueue((item, arguments)); break; case InvokeWhen.EnemyAssetLoaded: _InvokeWhenEnemyAssetLoaded.Enqueue((item, arguments)); break; case InvokeWhen.SharedAssetLoaded: _InvokeWhenSharedAssetLoaded.Enqueue((item, arguments)); break; case InvokeWhen.AllAssetsLoaded: _InvokeWhenAllAssetsLoaded.Enqueue((item, arguments)); break; } } } private static void RunMethod(MethodInfo method, params object[] args) { if (method.IsConstructor) { RuntimeHelpers.RunClassConstructor(method.DeclaringType.TypeHandle); } else { method.Invoke(null, args); } } } [BepInPlugin("GTFO.FloLib", "FloLib", "1.0.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] internal class EntryPoint : BasePlugin { private Harmony _Harmony; public override void Load() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown _Harmony = new Harmony("FloLib.Harmony"); _Harmony.PatchAll(); Automation.RegisterTypes(((object)this).GetType()); } public override bool Unload() { _Harmony.UnpatchSelf(); return ((BasePlugin)this).Unload(); } } internal static class Logger { internal static bool LogExceptionInDetail; private static readonly ManualLogSource _Logger; static Logger() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Expected O, but got Unknown _Logger = new ManualLogSource("FloLib"); Logger.Sources.Add((ILogSource)(object)_Logger); } private static string Format(object msg) { return msg.ToString(); } public static void Info(BepInExInfoLogInterpolatedStringHandler handler) { _Logger.LogInfo(handler); } public static void Info(string str) { _Logger.LogMessage((object)str); } public static void Info(object data) { _Logger.LogMessage((object)Format(data)); } public static void Debug(BepInExDebugLogInterpolatedStringHandler handler) { _Logger.LogDebug(handler); } public static void Debug(string str) { _Logger.LogDebug((object)str); } public static void Debug(object data) { _Logger.LogDebug((object)Format(data)); } public static void Error(BepInExErrorLogInterpolatedStringHandler handler) { _Logger.LogError(handler); } public static void Error(string str) { _Logger.LogError((object)str); } public static void Error(object data) { _Logger.LogError((object)Format(data)); } public static void Fatal(BepInExFatalLogInterpolatedStringHandler handler) { _Logger.LogFatal(handler); } public static void Fatal(string str) { _Logger.LogFatal((object)str); } public static void Fatal(object data) { _Logger.LogFatal((object)Format(data)); } public static void Warn(BepInExWarningLogInterpolatedStringHandler handler) { _Logger.LogWarning(handler); } public static void Warn(string str) { _Logger.LogWarning((object)str); } public static void Warn(object data) { _Logger.LogWarning((object)Format(data)); } [Conditional("DEBUG")] public static void DebugOnly(object data) { } public static void Exception(Exception e) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown if (LogExceptionInDetail) { _Logger.LogError((object)e.ToString()); return; } bool flag = default(bool); BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(2, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(e.GetType().Name); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(e.Message); } _Logger.LogError(val); } } internal static class TaskQueue { public const float INTERVAL = 0.15f; private static readonly ConcurrentQueue<(Action action, string? name)> q; public static Coroutine mainCoroutine { get; private set; } private static IEnumerator MainLoop() { while (true) { if (q.TryDequeue(out (Action, string) result)) { CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(ExecuteTask(result.Item1, (result.Item2 == null) ? "unnamed" : result.Item2)), (Action)null); } yield return (object)new WaitForSeconds(0.15f); } } private static IEnumerator ExecuteTask(Action task, string name) { try { task?.Invoke(); } catch (Exception ex) { bool flag = default(bool); BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(46, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Exception occurred during execution of task "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(name); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex); } Logger.Error(val); } yield break; } public static void AddTask(Action task, string name = null) { q.Enqueue((task, name)); } static TaskQueue() { q = new ConcurrentQueue<(Action, string)>(); Logger.Debug("TaskQueue: Coroutine started"); mainCoroutine = CoroutineManager.StartPersistantCoroutine(CollectionExtensions.WrapToIl2Cpp(MainLoop())); } } [GeneratedCode("VersionInfoGenerator", "2.1.3+git35c0c2a-master")] [CompilerGenerated] internal static class VersionInfo { public const string RootNamespace = "FloLib"; public const string Version = "1.0.0"; public const string VersionPrerelease = null; public const string VersionMetadata = "gitd7090d7-dirty-master"; public const string SemVer = "1.0.0+gitd7090d7-dirty-master"; public const string GitRevShort = "d7090d7-dirty"; public const string GitRevLong = "d7090d7625ec9ea5a37260ec10ba96729e107216-dirty"; public const string GitBranch = "master"; public const string GitTag = null; public const int GitCommitsSinceTag = 0; public const bool GitIsDirty = true; } } namespace FloLib.Utils { public enum CoroutineLifeTime { Forever, Lobby, Level, BetweenRecall } public static class Coroutines { private static MonoBehaviour _Runner; private static readonly Queue<Coroutine> _Coroutines_Lobby = new Queue<Coroutine>(); private static readonly Queue<Coroutine> _Coroutines_Level = new Queue<Coroutine>(); private static readonly Queue<Coroutine> _Coroutines_CPLoad = new Queue<Coroutine>(); [AutoInvoke(InvokeWhen.StartGame)] internal static void Init() { //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_000b: Expected O, but got Unknown GameObject val = new GameObject(); Object.DontDestroyOnLoad((Object)val); _Runner = (MonoBehaviour)(object)val.AddComponent<EmptyMB>(); LevelAPI.OnLevelCleanup += LevelAPI_OnLevelCleanup; Inject_SNet_Capture.OnBufferRecalled += Inject_SNet_Capture_OnBufferRecalled; } private static void Inject_SNet_Capture_OnBufferRecalled(eBufferType obj) { StopAll(CoroutineLifeTime.BetweenRecall); } private static void LevelAPI_OnLevelCleanup() { StopAll(); StopAll(CoroutineLifeTime.BetweenRecall); } public static void StopAll(CoroutineLifeTime lifeTime = CoroutineLifeTime.Level) { Queue<Coroutine> queue = lifeTime switch { CoroutineLifeTime.Lobby => _Coroutines_Lobby, CoroutineLifeTime.Level => _Coroutines_Level, CoroutineLifeTime.BetweenRecall => _Coroutines_CPLoad, _ => throw new NotSupportedException($"{"CoroutineLifeTime"}: {lifeTime} is not supported!"), }; Coroutine result; while (queue.TryDequeue(out result)) { _Runner.StopCoroutine(result); } } public static void Stop(Coroutine coroutine) { _Runner.StopCoroutine(coroutine); } public static Coroutine Start(IEnumerator coroutine, CoroutineLifeTime lifeTime = CoroutineLifeTime.Forever) { switch (lifeTime) { case CoroutineLifeTime.Forever: return MonoBehaviourExtensions.StartCoroutine(_Runner, coroutine); case CoroutineLifeTime.Lobby: { Coroutine val = MonoBehaviourExtensions.StartCoroutine(_Runner, coroutine); _Coroutines_Lobby.Enqueue(val); return val; } case CoroutineLifeTime.Level: { Coroutine val = MonoBehaviourExtensions.StartCoroutine(_Runner, coroutine); _Coroutines_Level.Enqueue(val); return val; } case CoroutineLifeTime.BetweenRecall: { Coroutine val = MonoBehaviourExtensions.StartCoroutine(_Runner, coroutine); _Coroutines_CPLoad.Enqueue(val); return val; } default: throw new NotSupportedException($"{"CoroutineLifeTime"}: {lifeTime} is not supported!!"); } } public static Coroutine DoWait(float delay, Action onDone, CoroutineLifeTime lifeTime = CoroutineLifeTime.Forever) { return Start(Wait(delay, onDone), lifeTime); } public static Coroutine DoWaitRealtime(float delay, Action onDone, CoroutineLifeTime lifeTime = CoroutineLifeTime.Forever) { return Start(WaitRealtime(delay, onDone), lifeTime); } public static Coroutine DoBlink(BlinkInfo blinkInfo, Action<bool> onBlinkChanged, CoroutineLifeTime lifeTime = CoroutineLifeTime.Forever) { return Start(Blink(blinkInfo, onBlinkChanged), lifeTime); } public static Coroutine DoLerp(LerpInfo lerpInfo, Action<float> onValueChanged, CoroutineLifeTime lifeTime = CoroutineLifeTime.Forever) { return Start(Lerp(lerpInfo, onValueChanged), lifeTime); } public static IEnumerator Wait(float delay, Action onDone) { yield return (object)new WaitForSeconds(delay); onDone?.Invoke(); } public static IEnumerator WaitRealtime(float delay, Action onDone) { yield return (object)new WaitForSecondsRealtime(delay); onDone?.Invoke(); } public static IEnumerator Blink(BlinkInfo info, Action<bool> onBlinkChanged) { float time = 0f; bool lastCond = false; onBlinkChanged?.Invoke(obj: false); while (time < info.Duration) { bool flag = BlinkByProgress(Mathf.Repeat(time * info.Speed, 1f)); if (flag != lastCond) { onBlinkChanged?.Invoke(flag); lastCond = flag; } time += Time.deltaTime; yield return null; } onBlinkChanged?.Invoke(info.EndBlinkState); } public static IEnumerator Lerp(LerpInfo info, Action<float> onValueChanged) { float time = 0f; onValueChanged?.Invoke(info.From); while (time < info.Duration) { float num = info.Easing.Evaluate(time / info.Duration); float obj = Mathf.Lerp(info.From, info.To, num); onValueChanged?.Invoke(obj); time += Time.deltaTime; yield return null; } onValueChanged?.Invoke(info.To); } private static bool BlinkByProgress(float progress) { return progress % 0.25f < 0.125f; } } public struct BlinkInfo { public bool EndBlinkState; public float Speed; public float Duration; public static readonly BlinkInfo InDefault = new BlinkInfo { Duration = 0.33f, Speed = 3f, EndBlinkState = true }; public static readonly BlinkInfo OutDefault = new BlinkInfo { Duration = 0.33f, Speed = 3f, EndBlinkState = false }; } public struct LerpInfo { public float From; public float To; public float Duration; public EaseFunc.Type Easing; public LerpInfo(float from, float to, float duration, EaseFunc.Type ease = EaseFunc.Type.Linear) { From = from; To = to; Duration = duration; Easing = ease; } } public static class EaseFunc { public enum Type : byte { Linear, Zero, One, InQuad, OutQuad, InOutQuad, InCubic, OutCubic, InOutCubic, InQuart, OutQuart, InOutQuart, InQuint, OutQuint, InOutQuint, InSine, OutSine, InOutSine, InExpo, OutExpo, InOutExpo, InCirc, OutCirc, InOutCirc, InElastic, OutElastic, InOutElastic, InBack, OutBack, InOutBack, InBounce, OutBounce, InOutBounce } public static float Evaluate(this Type type, float t) { t = Mathf.Clamp01(t); return type switch { Type.Linear => t, Type.Zero => 0f, Type.One => 1f, Type.InQuad => InQuad(t), Type.OutQuad => OutQuad(t), Type.InOutQuad => InOutQuad(t), Type.InCubic => InCubic(t), Type.OutCubic => OutCubic(t), Type.InOutCubic => InOutCubic(t), Type.InQuart => InQuart(t), Type.OutQuart => OutQuart(t), Type.InOutQuart => InOutQuart(t), Type.InQuint => InQuint(t), Type.OutQuint => OutQuint(t), Type.InOutQuint => InOutQuint(t), Type.InSine => InSine(t), Type.OutSine => OutSine(t), Type.InOutSine => InOutSine(t), Type.InExpo => InExpo(t), Type.OutExpo => OutExpo(t), Type.InOutExpo => InOutExpo(t), Type.InCirc => InCirc(t), Type.OutCirc => OutCirc(t), Type.InOutCirc => InOutCirc(t), Type.InElastic => InElastic(t), Type.OutElastic => OutElastic(t), Type.InOutElastic => InOutElastic(t), Type.InBack => InBack(t), Type.OutBack => OutBack(t), Type.InOutBack => InOutBack(t), Type.InBounce => InBounce(t), Type.OutBounce => OutBounce(t), Type.InOutBounce => InOutBounce(t), _ => throw new ArgumentOutOfRangeException("type", "Given type was invalid!"), }; } public static float InQuad(float t) { return t * t; } public static float OutQuad(float t) { return 1f - InQuad(1f - t); } public static float InOutQuad(float t) { if ((double)t < 0.5) { return InQuad(t * 2f) / 2f; } return 1f - InQuad((1f - t) * 2f) / 2f; } public static float InCubic(float t) { return t * t * t; } public static float OutCubic(float t) { return 1f - InCubic(1f - t); } public static float InOutCubic(float t) { if ((double)t < 0.5) { return InCubic(t * 2f) / 2f; } return 1f - InCubic((1f - t) * 2f) / 2f; } public static float InQuart(float t) { return t * t * t * t; } public static float OutQuart(float t) { return 1f - InQuart(1f - t); } public static float InOutQuart(float t) { if ((double)t < 0.5) { return InQuart(t * 2f) / 2f; } return 1f - InQuart((1f - t) * 2f) / 2f; } public static float InQuint(float t) { return t * t * t * t * t; } public static float OutQuint(float t) { return 1f - InQuint(1f - t); } public static float InOutQuint(float t) { if ((double)t < 0.5) { return InQuint(t * 2f) / 2f; } return 1f - InQuint((1f - t) * 2f) / 2f; } public static float InSine(float t) { return (float)(0.0 - Math.Cos((double)t * Math.PI / 2.0)); } public static float OutSine(float t) { return (float)Math.Sin((double)t * Math.PI / 2.0); } public static float InOutSine(float t) { return (float)(Math.Cos((double)t * Math.PI) - 1.0) / -2f; } public static float InExpo(float t) { return (float)Math.Pow(2.0, 10f * (t - 1f)); } public static float OutExpo(float t) { return 1f - InExpo(1f - t); } public static float InOutExpo(float t) { if ((double)t < 0.5) { return InExpo(t * 2f) / 2f; } return 1f - InExpo((1f - t) * 2f) / 2f; } public static float InCirc(float t) { return 0f - ((float)Math.Sqrt(1f - t * t) - 1f); } public static float OutCirc(float t) { return 1f - InCirc(1f - t); } public static float InOutCirc(float t) { if ((double)t < 0.5) { return InCirc(t * 2f) / 2f; } return 1f - InCirc((1f - t) * 2f) / 2f; } public static float InElastic(float t) { return 1f - OutElastic(1f - t); } public static float OutElastic(float t) { float num = 0.3f; return (float)Math.Pow(2.0, -10f * t) * (float)Math.Sin((double)(t - num / 4f) * (Math.PI * 2.0) / (double)num) + 1f; } public static float InOutElastic(float t) { if ((double)t < 0.5) { return InElastic(t * 2f) / 2f; } return 1f - InElastic((1f - t) * 2f) / 2f; } public static float InBack(float t) { float num = 1.70158f; return t * t * ((num + 1f) * t - num); } public static float OutBack(float t) { return 1f - InBack(1f - t); } public static float InOutBack(float t) { if ((double)t < 0.5) { return InBack(t * 2f) / 2f; } return 1f - InBack((1f - t) * 2f) / 2f; } public static float InBounce(float t) { return 1f - OutBounce(1f - t); } public static float OutBounce(float t) { float num = 2.75f; float num2 = 7.5625f; if (t < 1f / num) { return num2 * t * t; } if (t < 2f / num) { t -= 1.5f / num; return num2 * t * t + 0.75f; } if ((double)t < 2.5 / (double)num) { t -= 2.25f / num; return num2 * t * t + 0.9375f; } t -= 2.625f / num; return num2 * t * t + 63f / 64f; } public static float InOutBounce(float t) { if ((double)t < 0.5) { return InBounce(t * 2f) / 2f; } return 1f - InBounce((1f - t) * 2f) / 2f; } } public static class EasyDetour { public unsafe delegate void StaticVoidDelegate(Il2CppMethodInfo* methodInfo); public unsafe delegate void InstanceVoidDelegate(IntPtr instancePtr, Il2CppMethodInfo* methodInfo); public static bool TryCreate<T>(DetourDescriptor descriptor, T to, out T originalCall, out INativeDetour detourInstance) where T : Delegate { try { nint methodPointer = descriptor.GetMethodPointer(); detourInstance = INativeDetour.CreateAndApply<T>((IntPtr)methodPointer, to, ref originalCall); return detourInstance != null; } catch (Exception ex) { Logger.Error("Exception Thrown while creating Detour:"); Logger.Error(ex.ToString()); } originalCall = null; detourInstance = null; return false; } } public struct DetourDescriptor { public Type Type; public Type ReturnType; public Type[] ArgTypes; public string MethodName; public bool IsGeneric; public unsafe nint GetMethodPointer() { if (Type == null) { throw new MissingFieldException("Field Type is not set!"); } if (ReturnType == null) { throw new MissingFieldException("Field ReturnType is not set! If you mean 'void' do typeof(void)"); } if (string.IsNullOrEmpty(MethodName)) { throw new MissingFieldException("Field MethodName is not set or valid!"); } Il2CppType.From(Type, true); IntPtr nativeClassPointer = Il2CppClassPointerStore.GetNativeClassPointer(Type); string fullName = GetFullName(ReturnType); string[] array; if (ArgTypes == null || ArgTypes.Length == 0) { array = Array.Empty<string>(); } else { int num = ArgTypes.Length; array = new string[num]; for (int i = 0; i < num; i++) { Type type = ArgTypes[i]; array[i] = GetFullName(type); } } void** ptr = (void**)IL2CPP.GetIl2CppMethod(nativeClassPointer, IsGeneric, MethodName, fullName, array).ToPointer(); if (ptr == null) { return (nint)ptr; } return (nint)(*ptr); } private static string GetFullName(Type type) { bool isPointer = type.IsPointer; if (isPointer) { type = type.GetElementType(); } if (type.IsPrimitive || type == typeof(string)) { if (isPointer) { return type.MakePointerType().FullName; } return type.FullName; } Type val = Il2CppType.From(type, true); if (isPointer) { return val.MakePointerType().FullName; } return val.FullName; } } public struct HalfColor { public Half R; public Half G; public Half B; public Half A; public HalfColor() { R = (Half)0f; G = (Half)0f; B = (Half)0f; A = (Half)0f; } public HalfColor(float r, float g, float b, float a) { R = (Half)r; G = (Half)g; B = (Half)b; A = (Half)a; } public static implicit operator Color(HalfColor halfCol) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) return new Color((float)halfCol.R, (float)halfCol.G, (float)halfCol.B, (float)halfCol.A); } public static implicit operator HalfColor(Color col) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) HalfColor result = new HalfColor(); result.R = (Half)col.r; result.G = (Half)col.g; result.B = (Half)col.b; result.A = (Half)col.a; return result; } } public struct HalfRGBColor { public Half R; public Half G; public Half B; public static implicit operator Color(HalfRGBColor halfCol) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) return new Color((float)halfCol.R, (float)halfCol.G, (float)halfCol.B); } public static implicit operator HalfRGBColor(Color col) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) HalfRGBColor result = default(HalfRGBColor); result.R = (Half)col.r; result.G = (Half)col.g; result.B = (Half)col.b; return result; } } public class RNG { private const int Float01Precision = 2000000000; private const float Float01Inv = 5E-10f; private static uint _UniqueIDForRandomSeed = 0u; private Random _Rand; private int _Seed; public static GlobalRNG Global { get; private set; } = new GlobalRNG(); public float Float01 => (float)_Rand.Next(0, 2000000001) * 5E-10f; public float FloatMinusOneToPlusOne => (float)_Rand.Next(-2000000000, 2000000001) * 5E-10f; public int Int0ToPositive => _Rand.Next(0, int.MaxValue); public int Int0ToNegative => _Rand.Next(int.MinValue, 1); public int Int => _Rand.Next(int.MinValue, int.MaxValue); public RNG() { if (_UniqueIDForRandomSeed == uint.MaxValue) { _UniqueIDForRandomSeed = 0u; } else { _UniqueIDForRandomSeed++; } _Seed = $"{_UniqueIDForRandomSeed} {Environment.TickCount64}".GetHashCode(); _Rand = new Random(_Seed); } public RNG(int seed) { _Seed = seed; _Rand = new Random(seed); } public virtual void Reset(int? newSeed = null) { if (newSeed.HasValue) { _Seed = newSeed.Value; } _Rand = new Random(_Seed); } public bool Probability(float probability) { if (probability <= 0f) { return false; } if (probability >= 1f) { return true; } return Float01 < probability; } public bool OneIn(int cases) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Expected O, but got Unknown if (cases <= 0) { bool flag = default(bool); BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(46, 3, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("RNG"); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("."); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("OneIn"); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" received "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(cases); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" (0 or negative); fallback to false"); } Logger.Warn(val); return false; } if (cases == 1) { return true; } return _Rand.Next(0, cases) == 0; } public T Choice<T>(params T[] items) { return Choice((IEnumerable<T>)items); } public T Choice<T>(IEnumerable<T> items) { if (IsChoiceHaveSimpleScenarioValue(items, out var value)) { return value; } int maxValue = items.Count(); int index = _Rand.Next(0, maxValue); return items.ElementAt(index); } public T[] Choice<T>(IEnumerable<T> items, int count) { if (IsChoiceHaveSimpleScenarioValue(items, out var value)) { return new T[1] { value }; } return items.OrderBy((T x) => _Rand.NextDouble()).Take(count).ToArray(); } public T WeightedChoice<T>(IEnumerable<(T item, float weight)> itemTuples) { if (IsChoiceHaveSimpleScenarioValue<(T, float)>(itemTuples, out var value)) { return value.Item1; } T[] array = itemTuples.Select(((T item, float weight) x) => x.item).ToArray(); float[] array2 = itemTuples.Select(((T item, float weight) x) => x.weight).ToArray(); float num = 0f; for (int i = 0; i < array2.Length; i++) { float num2 = array2[i]; if (num2 <= 0f) { array2[i] = -1f; } else { num = (array2[i] = num + num2); } } if (num <= 0f) { return Choice(array); } float num3 = Float01 * num; for (int j = 0; j < array2.Length; j++) { if (j == array2.Length - 1 || num3 <= array2[j]) { return array[j]; } } throw new InvalidOperationException("What? this should never happen"); } private static bool IsChoiceHaveSimpleScenarioValue<T>(IEnumerable<T> items, out T value) { int num = items.Count(); if (num <= 0) { throw new ArgumentException("Argument Item Count is 0!", "items"); } if (num == 1) { value = items.First(); return true; } value = default(T); return false; } } public sealed class GlobalRNG : RNG { public sealed override void Reset(int? newSeed = null) { Logger.Warn("Resetting Seed Value is not allowed on RNG.Global"); } } } namespace FloLib.Utils.Extensions { public static class ColorExtension { public static string ToHex(this Color input) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) return "#" + ColorUtility.ToHtmlStringRGB(input); } public static string ToHexRGBA(this Color input) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) return "#" + ColorUtility.ToHtmlStringRGBA(input); } public static void GetColorInfo(this Color input, out Color baseColor, out float colorMultiplier) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001a: 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_0086: 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_0077: Unknown result type (might be due to invalid IL or missing references) float num = 0f; float num2 = 0f; float r = input.r; float g = input.g; float b = input.b; float num3 = Mathf.Abs(r); float num4 = Mathf.Abs(g); float num5 = Mathf.Abs(b); if (num3 > num2) { num2 = num3; num = r; } if (num4 > num2) { num2 = num4; num = g; } if (num5 > num2) { num2 = num5; num = b; } if (num2 > 0f) { baseColor = new Color(r / num, g / num, b / num, 1f); colorMultiplier = num; } else { baseColor = Color.black; colorMultiplier = 1f; } } } public static class ComponentExtension { public static bool TryGetComp<T>(this Component comp, out T component) { component = comp.GetComponent<T>(); return component != null; } public static bool TryGetVirtualScene(this Component comp, out GUIX_VirtualScene scene) { GUIX_VirtualSceneLink component = comp.GetComponent<GUIX_VirtualSceneLink>(); if ((Object)(object)component == (Object)null) { scene = null; return false; } scene = component.m_virtualScene; return (Object)(object)scene != (Object)null; } public static string GetGameObjectPath(this Component comp) { return comp.gameObject.GetPath(); } } public static class GameObjectExtension { public static bool TryGetComp<T>(this GameObject obj, out T component) { component = obj.GetComponent<T>(); return component != null; } public static T GetCompInParentOrChild<T>(this GameObject obj) { T val = obj.GetComponentInParent<T>(); if (val == null) { val = obj.GetComponentInChildren<T>(); if (val == null) { obj.GetComponent<T>(); } } return val; } public static string GetPath(this GameObject obj) { string text = "/" + ((Object)obj).name; while ((Object)(object)obj.transform.parent != (Object)null) { obj = ((Component)obj.transform.parent).gameObject; text = "/" + ((Object)obj).name + text; } return text; } } public static class Il2CppBoxingExtension { public static Object BoxToIl2CppObject(this bool value) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) Boolean val = default(Boolean); val.m_value = value; return ((Boolean)(ref val)).BoxIl2CppObject(); } public static Object BoxToIl2CppObject(this byte value) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) Byte val = default(Byte); val.m_value = value; return ((Byte)(ref val)).BoxIl2CppObject(); } public static Object BoxToIl2CppObject(this sbyte value) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) SByte val = default(SByte); val.m_value = value; return ((SByte)(ref val)).BoxIl2CppObject(); } public static Object BoxToIl2CppObject(this char value) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) Char val = default(Char); val.m_value = value; return ((Char)(ref val)).BoxIl2CppObject(); } public static Object BoxToIl2CppObject(this short value) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) Int16 val = default(Int16); val.m_value = value; return ((Int16)(ref val)).BoxIl2CppObject(); } public static Object BoxToIl2CppObject(this ushort value) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) UInt16 val = default(UInt16); val.m_value = value; return ((UInt16)(ref val)).BoxIl2CppObject(); } public static Object BoxToIl2CppObject(this int value) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) Int32 val = default(Int32); val.m_value = value; return ((Int32)(ref val)).BoxIl2CppObject(); } public static Object BoxToIl2CppObject(this uint value) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) UInt32 val = default(UInt32); val.m_value = value; return ((UInt32)(ref val)).BoxIl2CppObject(); } public static Object BoxToIl2CppObject(this long value) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) Int64 val = default(Int64); val.m_value = value; return ((Int64)(ref val)).BoxIl2CppObject(); } public static Object BoxToIl2CppObject(this ulong value) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) UInt64 val = default(UInt64); val.m_value = value; return ((UInt64)(ref val)).BoxIl2CppObject(); } public static Object BoxToIl2CppObject(this float value) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) Single val = default(Single); val.m_value = value; return ((Single)(ref val)).BoxIl2CppObject(); } public static Object BoxToIl2CppObject(this double value) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) Double val = default(Double); val.m_value = value; return ((Double)(ref val)).BoxIl2CppObject(); } public static Object BoxToIl2CppObject(this nint value) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) IntPtr val = default(IntPtr); val.m_value = value; return ((IntPtr)(ref val)).BoxIl2CppObject(); } } public static class Il2CppObjectExtension { public static bool CanCastToType<T>(this Il2CppObjectBase obj) where T : Il2CppObjectBase { return obj.TryCast<T>() != null; } public static bool TryCastToType<T>(this Il2CppObjectBase obj, out T result) where T : Il2CppObjectBase { result = obj.TryCast<T>(); return result != null; } } public static class LGLightExtension { public static void SetColor(this IEnumerable<LG_Light> lights, Color color) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) foreach (LG_Light light in lights) { light.ChangeColor(color); } } public static void SetEnabled(this IEnumerable<LG_Light> lights, bool enabled) { foreach (LG_Light light in lights) { light.SetEnabled(enabled); } } public static bool Is(this LG_Light light, LightCategory lightCategory) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 return (int)light.m_category == (int)lightCategory; } public static bool IsAny(this LG_Light light, params LightCategory[] categories) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Invalid comparison between Unknown and I4 for (int i = 0; i < categories.Length; i++) { if ((int)light.m_category == (int)categories[i]) { return true; } } return false; } } public enum LightCategory { General = 0, Special = 1, Independent = 3, Sign = 5, Door = 4, DoorImportant = 6, Emergency = 2 } public static class TerminalExtension { public static void SetPowered(this LG_ComputerTerminal terminal, bool isPowered) { terminal.OnProximityExit(); Interact_ComputerTerminal componentInChildren = ((Component)terminal).GetComponentInChildren<Interact_ComputerTerminal>(true); if ((Object)(object)componentInChildren != (Object)null) { ((Behaviour)componentInChildren).enabled = isPowered; ((Interact_Base)componentInChildren).SetActive(isPowered); } GUIX_VirtualSceneLink component = ((Component)terminal).GetComponent<GUIX_VirtualSceneLink>(); if ((Object)(object)component != (Object)null && (Object)(object)component.m_virtualScene != (Object)null) { GUIX_VirtualCamera virtualCamera = component.m_virtualScene.virtualCamera; float num = (isPowered ? 0.3f : 0f); float num2 = (isPowered ? 1000f : 0f); virtualCamera.SetFovAndClip(virtualCamera.paramCamera.fieldOfView, num, num2); } if ((Object)(object)terminal.m_text != (Object)null) { ((Behaviour)terminal.m_text).enabled = isPowered; } if (!isPowered) { PlayerAgent localInteractionSource = terminal.m_localInteractionSource; if ((Object)(object)localInteractionSource != (Object)null && localInteractionSource.FPItemHolder.InTerminalTrigger) { terminal.ExitFPSView(); } } } } public static class VectorExtension { public static string ToFormattedString(this Vector2 vector) { //IL_0017: 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) return $"x: {vector.x:0.0000}, y: {vector.y:0.0000}"; } public static string ToFormattedString(this Vector3 vector) { //IL_0018: 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_0054: Unknown result type (might be due to invalid IL or missing references) return $"x: {vector.x:0.0000}, y: {vector.y:0.0000} z: {vector.z:0.0000}"; } public static string ToFormattedString(this Vector4 vector) { //IL_0018: 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_0054: 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) return $"x: {vector.x:0.0000}, y: {vector.y:0.0000} z: {vector.z:0.0000} w: {vector.w:0.0000}"; } } } namespace FloLib.Utils.Comps { [AutoInject] internal sealed class EmptyMB : MonoBehaviour { } } namespace FloLib.Networks { public static class GlobalNetAction<P> where P : struct { private static string _EventName; private static bool _IsSetup; public static SNet_ChannelType SendChannel { get; set; } public static SNet_Player LastSender { get; private set; } public static ulong LastSenderID { get; private set; } public static event Action<ulong, P> OnReceive; public static event Action<ulong, P> OnReceiveLocally; static GlobalNetAction() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) SendChannel = (SNet_ChannelType)2; _IsSetup = false; Setup(); } public static void Setup() { if (!_IsSetup) { _EventName = UName.Get(typeof(P), "NA"); NetworkAPI.RegisterEvent<P>(_EventName, (Action<ulong, P>)Received); _IsSetup = true; } } public static void Send(P payload) { if (!_IsSetup) { Logger.Error("Action Wasn't Setup!"); return; } SendToLocal(payload); TaskQueue.AddTask(delegate { //IL_000b: Unknown result type (might be due to invalid IL or missing references) NetworkAPI.InvokeEvent<P>(_EventName, payload, SendChannel); }, "GlobalNetAction.Send"); } public static void SendTo(P payload, SNet_Player target) { if (!_IsSetup) { Logger.Error("Action Wasn't Setup!"); return; } if (target.IsLocal) { SendToLocal(payload); return; } TaskQueue.AddTask(delegate { //IL_000b: Unknown result type (might be due to invalid IL or missing references) NetworkAPI.InvokeEvent<P>(_EventName, payload, SendChannel); }, "GlobalNetAction.SendTo"); } public static void SendTo(P payload, SNet_SendGroup group) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) if (!_IsSetup) { Logger.Error("Action Wasn't Setup!"); return; } Enumerator<SNet_Player> enumerator = SNet_PlayerSendGroupManager.GetGroup(group).GetEnumerator(); while (enumerator.MoveNext()) { SNet_Player current = enumerator.Current; SendTo(payload, current); } } private static void SendToLocal(P payload) { if (!_IsSetup) { Logger.Error("Action Wasn't Setup!"); return; } SNet_Player val = (LastSender = SNet.LocalPlayer); if ((Object)(object)val != (Object)null) { LastSenderID = val.Lookup; } GlobalNetAction<P>.OnReceive?.Invoke(LastSenderID, payload); GlobalNetAction<P>.OnReceiveLocally?.Invoke(LastSenderID, payload); } private static void Received(ulong sender, P payload) { if (!_IsSetup) { Logger.Error("Action Wasn't Setup!"); return; } SNet_Player lastSender = default(SNet_Player); if (!SNet.Core.TryGetPlayer(sender, ref lastSender, false)) { LastSender = null; LastSenderID = 0uL; Logger.Error("NetAction sender was invalid!"); } LastSender = lastSender; LastSenderID = sender; GlobalNetAction<P>.OnReceive?.Invoke(sender, payload); } } public static class GlobalNetMasterAction<P> where P : struct { public static Func<ulong, P, bool> IsActionValid; private static string _AskEventName; private static string _EventName; private static bool _IsSetup; public static SNet_ChannelType SendChannel { get; set; } public static SNet_Player LastSender { get; private set; } public static ulong LastSenderID { get; private set; } public static event Action<ulong, P> OnReceive; public static event Action<ulong, P> OnMasterReceive; static GlobalNetMasterAction() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) SendChannel = (SNet_ChannelType)2; IsActionValid = (ulong sender, P p) => true; _IsSetup = false; Setup(); } public static void Setup() { if (!_IsSetup) { _AskEventName = UName.Get(typeof(P), "NMA0"); _EventName = UName.Get(typeof(P), "NMA1"); NetworkAPI.RegisterEvent<P>(_AskEventName, (Action<ulong, P>)ReceivedAsk); NetworkAPI.RegisterEvent<P>(_EventName, (Action<ulong, P>)Received); _IsSetup = true; } } public static void Ask(P payload) { if (!_IsSetup) { Logger.Error("Action Wasn't Setup!"); } else { if (!SNet.HasMaster) { return; } if (SNet.IsMaster) { Func<ulong, P, bool> isActionValid = IsActionValid; if (isActionValid == null || isActionValid(SNet.LocalPlayer.Lookup, payload)) { TaskQueue.AddTask(delegate { //IL_000b: Unknown result type (might be due to invalid IL or missing references) NetworkAPI.InvokeEvent<P>(_EventName, payload, SendChannel); }, "GlobalNetMasterAction.Master"); GlobalNetMasterAction<P>.OnReceive?.Invoke(SNet.LocalPlayer.Lookup, payload); GlobalNetMasterAction<P>.OnMasterReceive?.Invoke(SNet.LocalPlayer.Lookup, payload); } } else { TaskQueue.AddTask(delegate { //IL_0010: Unknown result type (might be due to invalid IL or missing references) NetworkAPI.InvokeEvent<P>(_AskEventName, payload, SNet.Master, SendChannel); }, "GlobalNetMasterAction.Ask.Client"); } } } private static void ReceivedAsk(ulong sender, P payload) { if (!_IsSetup) { Logger.Error("Action Wasn't Setup!"); return; } if (!SNet.IsMaster) { Logger.Error("Non Master Received Ask Action!"); return; } Func<ulong, P, bool> isActionValid = IsActionValid; if (isActionValid == null || isActionValid(sender, payload)) { TaskQueue.AddTask(delegate { //IL_000b: Unknown result type (might be due to invalid IL or missing references) NetworkAPI.InvokeEvent<P>(_EventName, payload, SendChannel); }, "GlobalNetMasterAction.ReceivedAsk.Master"); GlobalNetMasterAction<P>.OnReceive?.Invoke(SNet.LocalPlayer.Lookup, payload); GlobalNetMasterAction<P>.OnMasterReceive?.Invoke(sender, payload); } } private static void Received(ulong sender, P payload) { if (!_IsSetup) { Logger.Error("Action Wasn't Setup!"); return; } SNet_Player lastSender = default(SNet_Player); if (!SNet.Core.TryGetPlayer(sender, ref lastSender, false)) { LastSender = null; LastSenderID = 0uL; Logger.Error("NetMasterAction sender was invalid!"); return; } LastSender = lastSender; LastSenderID = sender; if (!LastSender.IsMaster) { Logger.Error("Sender was not a master"); } else { GlobalNetMasterAction<P>.OnReceive?.Invoke(sender, payload); } } } internal static class UName { private static readonly SHA1 SHA = SHA1.Create(); public static string Get(Type type, string prefix) { return prefix + GetHash(type.FullName); } public static string GetHash(string text) { return Convert.ToBase64String(SHA.ComputeHash(Encoding.Unicode.GetBytes(text + "this is salt text, Awesome!"))); } } } namespace FloLib.Networks.Replications { public interface IStateReplicatorHolder<S> where S : struct { StateReplicator<S> Replicator { get; } void OnStateChange(S oldState, S state, bool isRecall); } public sealed class ReplicatorHandshake { public delegate void ClientRequestedSyncDel(SNet_Player requestedPlayer); public struct Packet { public uint replicatorID; public PacketAction action; } public enum PacketAction : byte { Created, Destroyed, SyncRequest } public sealed class Data { public bool SetupOnHost; public bool SetupOnClient; } private readonly Dictionary<uint, Data> _Lookup = new Dictionary<uint, Data>(); public string EventName { get; private set; } public bool IsReadyToSync { get; private set; } public event ClientRequestedSyncDel OnClientSyncRequested; public static ReplicatorHandshake Create(string guid) { if (string.IsNullOrWhiteSpace(guid)) { return null; } string text = "RHs" + guid; if (!NetworkAPI.IsEventRegistered(text)) { return new ReplicatorHandshake(text); } return null; } private ReplicatorHandshake(string eventName) { EventName = eventName; NetworkAPI.RegisterEvent<Packet>(eventName, (Action<ulong, Packet>)OnSyncAction); Inject_OnRecallDone.OnRecallDone += delegate { Logger.Warn("ReplicatorHandshake: client sending sync request"); ClientSyncRequest(); }; } private void ClientSyncRequest() { if (SNet.IsMaster) { return; } foreach (uint replicatorID in _Lookup.Keys) { TaskQueue.AddTask(delegate { NetworkAPI.InvokeEvent<Packet>(EventName, new Packet { replicatorID = replicatorID, action = PacketAction.SyncRequest }, SNet.Master, (SNet_ChannelType)2); }, $"SyncReplicatorID_{replicatorID}"); } } public void Reset() { _Lookup.Clear(); } private void OnSyncAction(ulong sender, Packet packet) { //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Expected O, but got Unknown if (!SNet.IsMaster && sender == SNet.Master.Lookup) { if (packet.action == PacketAction.Created) { SetHostState(packet.replicatorID, isSetup: true); } else if (packet.action == PacketAction.Destroyed) { SetHostState(packet.replicatorID, isSetup: false); } } else { if (!SNet.IsMaster) { return; } if (packet.action == PacketAction.Created) { SetClientState(packet.replicatorID, isSetup: true); } else if (packet.action == PacketAction.Destroyed) { SetClientState(packet.replicatorID, isSetup: false); } else { if (packet.action != PacketAction.SyncRequest) { return; } SNet_Player requestedPlayer = default(SNet_Player); if (!SNet.TryGetPlayer(sender, ref requestedPlayer)) { bool flag = default(bool); BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(32, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Cannot find player from sender: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<ulong>(sender); } Logger.Error(val); } else { this.OnClientSyncRequested?.Invoke(requestedPlayer); } } } } public void UpdateCreated(uint id) { if (SNet.IsInLobby) { if (SNet.IsMaster) { SetHostState(id, isSetup: true); TaskQueue.AddTask(delegate { NetworkAPI.InvokeEvent<Packet>(EventName, new Packet { replicatorID = id, action = PacketAction.Created }, (SNet_ChannelType)2); }, "UpdateCreated.Master"); } else if (SNet.HasMaster) { SetClientState(id, isSetup: true); TaskQueue.AddTask(delegate { NetworkAPI.InvokeEvent<Packet>(EventName, new Packet { replicatorID = id, action = PacketAction.Created }, SNet.Master, (SNet_ChannelType)2); }, "UpdateCreated.Client"); } else { Logger.Error("Handshake::MASTER is NULL in lobby; This should NOT happen!!!!!!!!!!!!"); } } else { Logger.Error("Handshake::Session Type StateReplicator cannot be created without lobby!"); } } public void UpdateDestroyed(uint id) { if (SNet.IsInLobby) { if (SNet.IsMaster) { SetHostState(id, isSetup: true); TaskQueue.AddTask(delegate { NetworkAPI.InvokeEvent<Packet>(EventName, new Packet { replicatorID = id, action = PacketAction.Destroyed }, (SNet_ChannelType)2); }, "UpdateDestroyed.Master"); } else if (SNet.HasMaster) { SetClientState(id, isSetup: true); TaskQueue.AddTask(delegate { NetworkAPI.InvokeEvent<Packet>(EventName, new Packet { replicatorID = id, action = PacketAction.Destroyed }, SNet.Master, (SNet_ChannelType)2); }, "UpdateDestroyed.Client"); } else { Logger.Error("Handshake::MASTER is NULL in lobby; This should NOT happen!!!!!!!!!!!!"); } } else { Logger.Error("Handshake::Session Type StateReplicator cannot be created without lobby!"); } } private void SetHostState(uint id, bool isSetup) { if (_Lookup.TryGetValue(id, out var value)) { value.SetupOnHost = isSetup; } else { _Lookup[id] = new Data { SetupOnHost = isSetup }; } UpdateSyncState(id); } private void SetClientState(uint id, bool isSetup) { if (_Lookup.TryGetValue(id, out var value)) { value.SetupOnClient = isSetup; } else { _Lookup[id] = new Data { SetupOnClient = isSetup }; } UpdateSyncState(id); } private void UpdateSyncState(uint id) { bool isReadyToSync = IsReadyToSync; if (_Lookup.TryGetValue(id, out var value)) { IsReadyToSync = value.SetupOnHost && value.SetupOnClient; } else { IsReadyToSync = false; } if (IsReadyToSync && isReadyToSync != IsReadyToSync && SNet.HasMaster && !SNet.IsMaster) { TaskQueue.AddTask(delegate { NetworkAPI.InvokeEvent<Packet>(EventName, new Packet { replicatorID = id, action = PacketAction.SyncRequest }, SNet.Master, (SNet_ChannelType)2); }, "Client.UpdateSyncState.SyncRequest"); } } } public delegate void OnReceiveDel<S>(ulong sender, uint replicatorID, S newState) where S : struct; public static class StatePayloads { public enum Size { State4Byte = 4, State8Byte = 8, State16Byte = 16, State32Byte = 32, State48Byte = 48, State64Byte = 64, State80Byte = 80, State96Byte = 96, State128Byte = 128, State196Byte = 196, State256Byte = 256 } public static Size GetSizeType(int size) { Size size2 = Size.State8Byte; foreach (object value in Enum.GetValues(typeof(Size))) { if (size <= (int)value && (int)size2 < (int)value) { size2 = (Size)value; break; } } return size2; } public static IReplicatorEvent<S> CreateEvent<S>(Size size, string eventName, OnReceiveDel<S> onReceiveCallback) where S : struct { return size switch { Size.State4Byte => ReplicatorPayloadWrapper<S, StatePayload4Byte>.Create(eventName, onReceiveCallback), Size.State8Byte => ReplicatorPayloadWrapper<S, StatePayload8Byte>.Create(eventName, onReceiveCallback), Size.State16Byte => ReplicatorPayloadWrapper<S, StatePayload16Byte>.Create(eventName, onReceiveCallback), Size.State32Byte => ReplicatorPayloadWrapper<S, StatePayload32Byte>.Create(eventName, onReceiveCallback), Size.State48Byte => ReplicatorPayloadWrapper<S, StatePayload48Byte>.Create(eventName, onReceiveCallback), Size.State64Byte => ReplicatorPayloadWrapper<S, StatePayload64Byte>.Create(eventName, onReceiveCallback), Size.State80Byte => ReplicatorPayloadWrapper<S, StatePayload80Byte>.Create(eventName, onReceiveCallback), Size.State96Byte => ReplicatorPayloadWrapper<S, StatePayload96Byte>.Create(eventName, onReceiveCallback), Size.State128Byte => ReplicatorPayloadWrapper<S, StatePayload128Byte>.Create(eventName, onReceiveCallback), Size.State196Byte => ReplicatorPayloadWrapper<S, StatePayload196Byte>.Create(eventName, onReceiveCallback), Size.State256Byte => ReplicatorPayloadWrapper<S, StatePayload256Byte>.Create(eventName, onReceiveCallback), _ => null, }; } public static S Get<S>(byte[] bytes, int bytesLength) where S : struct { int num = Marshal.SizeOf(typeof(S)); if (num > bytesLength) { throw new ArgumentException($"StateData Exceed size of {bytesLength} : Unable to Deserialize", "S"); } IntPtr intPtr = Marshal.AllocHGlobal(num); Marshal.Copy(bytes, 0, intPtr, num); S result = (S)Marshal.PtrToStructure(intPtr, typeof(S)); Marshal.FreeHGlobal(intPtr); return result; } public static void Set<S>(S stateData, int size, ref byte[] payloadBytes) where S : struct { if (Marshal.SizeOf(stateData) > size) { throw new ArgumentException($"StateData Exceed size of {size} : Unable to Serialize", "S"); } byte[] array = new byte[size]; IntPtr intPtr = Marshal.AllocHGlobal(size); Marshal.StructureToPtr(stateData, intPtr, fDeleteOld: false); Marshal.Copy(intPtr, array, 0, size); Marshal.FreeHGlobal(intPtr); payloadBytes = array; } } public interface IReplicatorEvent<S> where S : struct { string Name { get; } bool IsRegistered { get; } void Invoke(uint replicatorID, S data); void Invoke(uint replicatorID, S data, SNet_ChannelType channelType); void Invoke(uint replicatorID, S data, SNet_Player target); void Invoke(uint replicatorID, S data, SNet_Player target, SNet_ChannelType channelType); } public class ReplicatorPayloadWrapper<S, P> : IReplicatorEvent<S> where S : struct where P : struct, IStatePayload { public string Name { get; private set; } public bool IsRegistered { get; private set; } public static IReplicatorEvent<S> Create(string eventName, OnReceiveDel<S> onReceiveCallback) { ReplicatorPayloadWrapper<S, P> replicatorPayloadWrapper = new ReplicatorPayloadWrapper<S, P>(); replicatorPayloadWrapper.Register(eventName, onReceiveCallback); if (!replicatorPayloadWrapper.IsRegistered) { return null; } return replicatorPayloadWrapper; } public void Register(string eventName, OnReceiveDel<S> onReceiveCallback) { if (!IsRegistered && !NetworkAPI.IsEventRegistered(eventName)) { NetworkAPI.RegisterEvent<P>(eventName, (Action<ulong, P>)delegate(ulong sender, P payload) { onReceiveCallback?.Invoke(sender, payload.ID, payload.Get<S>()); }); IsRegistered = true; Name = eventName; } } public void Invoke(uint replicatorID, S data) { P payload = new P { ID = replicatorID }; payload.Set(data); TaskQueue.AddTask(delegate { NetworkAPI.InvokeEvent<P>(Name, payload, (SNet_ChannelType)2); }, "ReplicatorPayloadWrapper.Invoke(uint, S)"); } public void Invoke(uint replicatorID, S data, SNet_ChannelType channelType) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) P payload = new P { ID = replicatorID }; payload.Set(data); TaskQueue.AddTask(delegate { //IL_0012: Unknown result type (might be due to invalid IL or missing references) NetworkAPI.InvokeEvent<P>(Name, payload, channelType); }, "ReplicatorPayloadWrapper.Invoke(uint, S, SNet_ChannelType)"); } public void Invoke(uint replicatorID, S data, SNet_Player target) { P payload = new P { ID = replicatorID }; payload.Set(data); TaskQueue.AddTask(delegate { NetworkAPI.InvokeEvent<P>(Name, payload, target, (SNet_ChannelType)2); }, "ReplicatorPayloadWrapper.Invoke(uint, S, SNet_Player)"); } public void Invoke(uint replicatorID, S data, SNet_Player target, SNet_ChannelType channelType) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) P payload = new P { ID = replicatorID }; payload.Set(data); TaskQueue.AddTask(delegate { //IL_0018: Unknown result type (might be due to invalid IL or missing references) NetworkAPI.InvokeEvent<P>(Name, payload, target, channelType); }, "ReplicatorPayloadWrapper.Invoke(uint, S, SNet_Player, SNet_ChannelType)"); } } public interface IStatePayload { uint ID { get; set; } S Get<S>() where S : struct; void Set<S>(S stateData) where S : struct; } public struct StatePayload4Byte : IStatePayload { public const int Size = 4; private uint id; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 4)] public byte[] PayloadBytes; public uint ID { get { return id; } set { id = value; } } public S Get<S>() where S : struct { return StatePayloads.Get<S>(PayloadBytes, 4); } public void Set<S>(S stateData) where S : struct { StatePayloads.Set(stateData, 4, ref PayloadBytes); } } public struct StatePayload8Byte : IStatePayload { public const int Size = 8; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 8)] public byte[] PayloadBytes; [field: MarshalAs(UnmanagedType.U4)] public uint ID { get; set; } public S Get<S>() where S : struct { return StatePayloads.Get<S>(PayloadBytes, 8); } public void Set<S>(S stateData) where S : struct { StatePayloads.Set(stateData, 8, ref PayloadBytes); } } public struct StatePayload16Byte : IStatePayload { public const int Size = 16; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 16)] public byte[] PayloadBytes; [field: MarshalAs(UnmanagedType.U4)] public uint ID { get; set; } public S Get<S>() where S : struct { return StatePayloads.Get<S>(PayloadBytes, 16); } public void Set<S>(S stateData) where S : struct { StatePayloads.Set(stateData, 16, ref PayloadBytes); } } public struct StatePayload32Byte : IStatePayload { public const int Size = 32; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 32)] public byte[] PayloadBytes; [field: MarshalAs(UnmanagedType.U4)] public uint ID { get; set; } public S Get<S>() where S : struct { return StatePayloads.Get<S>(PayloadBytes, 32); } public void Set<S>(S stateData) where S : struct { StatePayloads.Set(stateData, 32, ref PayloadBytes); } } public struct StatePayload48Byte : IStatePayload { public const int Size = 48; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 48)] public byte[] PayloadBytes; [field: MarshalAs(UnmanagedType.U4)] public uint ID { get; set; } public S Get<S>() where S : struct { return StatePayloads.Get<S>(PayloadBytes, 48); } public void Set<S>(S stateData) where S : struct { StatePayloads.Set(stateData, 48, ref PayloadBytes); } } public struct StatePayload64Byte : IStatePayload { public const int Size = 64; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 64)] public byte[] PayloadBytes; [field: MarshalAs(UnmanagedType.U4)] public uint ID { get; set; } public S Get<S>() where S : struct { return StatePayloads.Get<S>(PayloadBytes, 64); } public void Set<S>(S stateData) where S : struct { StatePayloads.Set(stateData, 64, ref PayloadBytes); } } public struct StatePayload80Byte : IStatePayload { public const int Size = 80; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 80)] public byte[] PayloadBytes; [field: MarshalAs(UnmanagedType.U4)] public uint ID { get; set; } public S Get<S>() where S : struct { return StatePayloads.Get<S>(PayloadBytes, 80); } public void Set<S>(S stateData) where S : struct { StatePayloads.Set(stateData, 80, ref PayloadBytes); } } public struct StatePayload96Byte : IStatePayload { public const int Size = 96; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 96)] public byte[] PayloadBytes; [field: MarshalAs(UnmanagedType.U4)] public uint ID { get; set; } public S Get<S>() where S : struct { return StatePayloads.Get<S>(PayloadBytes, 96); } public void Set<S>(S stateData) where S : struct { StatePayloads.Set(stateData, 96, ref PayloadBytes); } } public struct StatePayload128Byte : IStatePayload { public const int Size = 128; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 128)] public byte[] PayloadBytes; [field: MarshalAs(UnmanagedType.U4)] public uint ID { get; set; } public S Get<S>() where S : struct { return StatePayloads.Get<S>(PayloadBytes, 128); } public void Set<S>(S stateData) where S : struct { StatePayloads.Set(stateData, 128, ref PayloadBytes); } } public struct StatePayload196Byte : IStatePayload { public const int Size = 196; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 196)] public byte[] PayloadBytes; [field: MarshalAs(UnmanagedType.U4)] public uint ID { get; set; } public S Get<S>() where S : struct { return StatePayloads.Get<S>(PayloadBytes, 196); } public void Set<S>(S stateData) where S : struct { StatePayloads.Set(stateData, 196, ref PayloadBytes); } } public struct StatePayload256Byte : IStatePayload { public const int Size = 256; [MarshalAs(UnmanagedType.ByValArray, SizeConst = 256)] public byte[] PayloadBytes; [field: MarshalAs(UnmanagedType.U4)] public uint ID { get; set; } public S Get<S>() where S : struct { return StatePayloads.Get<S>(PayloadBytes, 256); } public void Set<S>(S stateData) where S : struct { StatePayloads.Set(stateData, 256, ref PayloadBytes); } } public enum LifeTimeType { Forever, Level } public sealed class StateReplicator<S> where S : struct { private readonly Dictionary<eBufferType, S> _RecallStateSnapshots = new Dictionary<eBufferType, S>(); public static readonly string Name; public static readonly string HashName; public static readonly string ClientRequestEventName; public static readonly string HostSetStateEventName; public static readonly string HostSetRecallStateEventName; public static readonly int StateSize; public static readonly StatePayloads.Size StateSizeType; private static readonly IReplicatorEvent<S> _C_RequestEvent; private static readonly IReplicatorEvent<S> _H_SetStateEvent; private static readonly IReplicatorEvent<S> _H_SetRecallStateEvent; private static readonly ReplicatorHandshake _Handshake; private static readonly Dictionary<uint, StateReplicator<S>> _Replicators; public bool IsValid => ID != 0; public bool IsInvalid => ID == 0; public uint ID { get; private set; } public LifeTimeType LifeTime { get; private set; } public IStateReplicatorHolder<S> Holder { get; private set; } public S State { get; private set; } public bool ClientSendStateAllowed { get; set; } = true; public bool CanSendToClient { get { if (SNet.IsInLobby) { return SNet.IsMaster; } return false; } } public bool CanSendToHost { get { if (SNet.IsInLobby && !SNet.IsMaster && SNet.HasMaster) { return ClientSendStateAllowed; } return false; } } public bool IsHandshakeSetup { get; private set; } public event Action<S, S, bool> OnStateChanged; public void SetupHandshake() { if (!IsInvalid && !IsHandshakeSetup) { _Handshake.UpdateCreated(ID); IsHandshakeSetup = true; } } public void SetState(S state) { if (!IsInvalid) { DoSync(state); } } public void SetStateUnsynced(S state) { if (!IsInvalid) { State = state; } } public void Unload() { if (IsValid) { _Replicators.Remove(ID); _RecallStateSnapshots.Clear(); _Handshake.UpdateDestroyed(ID); IsHandshakeSetup = false; ID = 0u; } } private void DoSync(S newState) { if (!IsInvalid) { if (CanSendToClient) { _H_SetStateEvent.Invoke(ID, newState); Internal_ChangeState(newState, isRecall: false); } else if (CanSendToHost) { _C_RequestEvent.Invoke(ID, newState, SNet.Master); } } } private void Internal_ChangeState(S state, bool isRecall) { if (!IsInvalid) { S state2 = State; State = state; this.OnStateChanged?.Invoke(state2, state, isRecall); Holder?.OnStateChange(state2, state, isRecall); } } private void SendDropInState(SNet_Player target) { if (!IsInvalid) { if ((Object)(object)target == (Object)null) { Logger.Error("SendDropInState::Target was null??"); } else { _H_SetRecallStateEvent.Invoke(ID, State, target); } } } public void ClearAllRecallSnapshot() { if (!IsInvalid) { _RecallStateSnapshots.Clear(); } } private void SaveSnapshot(eBufferType type) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) if (!IsInvalid) { _RecallStateSnapshots[type] = State; } } private void RestoreSnapshot(eBufferType type) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Expected O, but got Unknown //IL_0060: Unknown result type (might be due to invalid IL or missing references) if (IsInvalid || !CanSendToClient) { return; } if (_RecallStateSnapshots.TryGetValue(type, out var value)) { _H_SetRecallStateEvent.Invoke(ID, value); Internal_ChangeState(value, isRecall: true); return; } bool flag = default(bool); BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(29, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("RestoreSnapshot"); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("::There was no snapshot for "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<eBufferType>(type); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("?"); } Logger.Error(val); } static StateReplicator() { _Replicators = new Dictionary<uint, StateReplicator<S>>(); Name = typeof(S).Name; StateSize = Marshal.SizeOf(typeof(S)); StateSizeType = StatePayloads.GetSizeType(StateSize); using (MD5.Create()) { HashName = UName.GetHash(typeof(S).FullName); ClientRequestEventName = "SRs" + Name + "-" + HashName; HostSetStateEventName = "SRr" + Name + "-" + HashName; HostSetRecallStateEventName = "SRre" + Name + "-" + HashName; _C_RequestEvent = StatePayloads.CreateEvent<S>(StateSizeType, ClientRequestEventName, ClientRequestEventCallback); _H_SetStateEvent = StatePayloads.CreateEvent<S>(StateSizeType, HostSetStateEventName, HostSetStateEventCallback); _H_SetRecallStateEvent = StatePayloads.CreateEvent<S>(StateSizeType, HostSetRecallStateEventName, HostSetRecallStateEventCallback); _Handshake = ReplicatorHandshake.Create(Name + "-" + HashName); _Handshake.OnClientSyncRequested += ClientSyncRequested; Inject_SNet_Capture.OnBufferCapture += BufferStored; Inject_SNet_Capture.OnBufferRecalled += BufferRecalled; Inject_Builder.BeforeBuildStart += LevelCleanedUp; LevelAPI.OnLevelCleanup += LevelCleanedUp; } } public static void Setup() { } private static void ClientSyncRequested(SNet_Player requestedPlayer) { foreach (StateReplicator<S> value in _Replicators.Values) { if (value.IsValid) { value.SendDropInState(requestedPlayer); } } } private static void BufferStored(eBufferType type) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) foreach (StateReplicator<S> value in _Replicators.Values) { if (value.IsValid) { value.SaveSnapshot(type); } } } private static void BufferRecalled(eBufferType type) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) foreach (StateReplicator<S> value in _Replicators.Values) { if (value.IsValid) { value.RestoreSnapshot(type); } } } private static void LevelCleanedUp() { UnloadSessionReplicator(); } private StateReplicator() { } public static StateReplicator<S> Create(uint replicatorID, S startState, LifeTimeType lifeTime, IStateReplicatorHolder<S> owner = null) { //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Expected O, but got Unknown if (replicatorID == 0) { Logger.Error("Replicator ID 0 is reserved for empty!"); return null; } if (_Replicators.ContainsKey(replicatorID)) { Logger.Error("Replicator ID has already assigned!"); return null; } StateReplicator<S> stateReplicator = new StateReplicator<S> { ID = replicatorID, LifeTime = lifeTime, Holder = owner, State = startState }; switch (lifeTime) { case LifeTimeType.Forever: stateReplicator.IsHandshakeSetup = true; break; case LifeTimeType.Level: stateReplicator.SetupHandshake(); break; default: { bool flag = default(bool); BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(22, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("LifeTime is invalid!: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<LifeTimeType>(lifeTime); } Logger.Error(val); return null; } } _Replicators[replicatorID] = stateReplicator; return stateReplicator; } public static void UnloadSessionReplicator() { List<uint> list = new List<uint>(); foreach (StateReplicator<S> value in _Replicators.Values) { if (value.LifeTime == LifeTimeType.Level) { list.Add(value.ID); value.Unload(); } } foreach (uint item in list) { _Replicators.Remove(item); } _Handshake.Reset(); } private static void ClientRequestEventCallback(ulong sender, uint replicatorID, S newState) { if (SNet.IsMaster && _Replicators.TryGetValue(replicatorID, out var value)) { value.SetState(newState); } } private static void HostSetStateEventCallback(ulong sender, uint replicatorID, S newState) { if (SNet.HasMaster && SNet.Master.Lookup == sender && _Replicators.TryGetValue(replicatorID, out var value)) { value.Internal_ChangeState(newState, isRecall: false); } } private static void HostSetRecallStateEventCallback(ulong sender, uint replicatorID, S newState) { if (SNet.HasMaster && SNet.Master.Lookup == sender && _Replicators.TryGetValue(replicatorID, out var value)) { value.Internal_ChangeState(newState, isRecall: true); } } } } namespace FloLib.Networks.PayloadStructs { public struct PL_Agent { public ushort AgentID; public PL_Agent() { AgentID = 0; } public PL_Agent(Agent agent) { AgentID = agent.GlobalID; } public void Set(Agent agent) { AgentID = agent.GlobalID; } public bool TryGet(out Agent agent) { IReplicator val = default(IReplicator); if (!SNet_Replication.TryGetReplicator(AgentID, ref val)) { agent = null; return false; } if (val == null) { agent = null; return false; } if (val.ReplicatorSupplier == null) { agent = null; return false; } MonoBehaviour val2 = ((Il2CppObjectBase)val.ReplicatorSupplier).TryCast<MonoBehaviour>(); if ((Object)(object)val2 == (Object)null) { agent = null; return false; } agent = ((Component)val2).GetComponent<Agent>(); return (Object)(object)agent != (Object)null; } } } namespace FloLib.Networks.Inject { [HarmonyPatch] internal class Inject_OnRecallDone { public static event Action OnRecallDone; [HarmonyPostfix] [HarmonyPatch(typeof(SNet_SyncManager), "OnRecallDone")] private static void Post_OnRecallDone(SNet_SyncManager __instance) { Inject_OnRecallDone.OnRecallDone?.Invoke(); } } [HarmonyPatch(typeof(SNet_Capture))] internal static class Inject_SNet_Capture { public static event Action<eBufferType> OnBufferCapture; public static event Action<eBufferType> OnBufferRecalled; [HarmonyPatch("TriggerCapture")] [HarmonyPrefix] private static void Pre_TriggerCapture(SNet_Capture __instance) { //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_0011: Unknown result type (might be due to invalid IL or missing references) eBufferType primedBufferType = __instance.PrimedBufferType; Inject_SNet_Capture.OnBufferCapture?.Invoke(primedBufferType); } [HarmonyPatch("RecallBuffer")] [HarmonyPostfix] [HarmonyWrapSafe] private static void Post_RecallBuffer(SNet_Capture __instance, eBufferType bufferType) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) if (!__instance.IsRecalling) { Inject_SNet_Capture.OnBufferRecalled?.Invoke(bufferType); } } } } namespace FloLib.Infos { public sealed class ComponentList<T> : IEnumerable<T>, IEnumerable where T : Component { private readonly List<T> _InternalList = new List<T>(); private T[] _ArrayCache = Array.Empty<T>(); public T[] Items => _ArrayCache; internal void Add(T itemToAdd) { int id = ((Object)(object)itemToAdd).GetInstanceID(); if (!_InternalList.Any((T t) => ((Object)(object)t).GetInstanceID() == id)) { _InternalList.Add(itemToAdd); _ArrayCache = _InternalList.ToArray(); } } internal void AddRange(IEnumerable<T> itemsToAdd) { foreach (T item in itemsToAdd) { Add(item); } } internal void Remove(T itemToRemove) { int id = ((Object)(object)itemToRemove).GetInstanceID(); int num = _InternalList.FindIndex((T i) => ((Object)(object)i).GetInstanceID() == id); if (num > -1) { _InternalList.RemoveAt(num); _ArrayCache = _InternalList.ToArray(); } } internal void Clear() { _InternalList.Clear(); _ArrayCache = Array.Empty<T>(); } public IEnumerator<T> GetEnumerator() { return _InternalList.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _InternalList.GetEnumerator(); } } public static class LG_LightInfo { public struct Data { public float PrefabIntensity; public LightMode SpawnedMode; public float SpawnedIntensity; public Color SpawnedColor; } public static bool TryGetLightData(LG_Light light, out Data data) { if ((Object)(object)light == (Object)null) { data = default(Data); return false; } if (!((Component)(object)light).TryGetComp<LightData>(out var component)) { data = default(Data); return false; } data = component.CreateData(); return true; } public static void RevertToSpawnedState(LG_Light light) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)light == (Object)null) && ((Component)(object)light).TryGetComp<LightData>(out var component)) { light.ChangeColor(component.SpawnedColor); light.ChangeIntensity(component.SpawnedIntensity); } } } public enum LightMode { Off, On, Broken_Flickering } public static class LG_Objects { public static ComponentList<LG_SecurityDoor> SecurityDoors { get; private set; } = new ComponentList<LG_SecurityDoor>(); public static ComponentList<LG_WeakDoor> WeakDoors { get; private set; } = new ComponentList<LG_WeakDoor>(); public static ComponentList<LG_Light> Lights { get; private set; } = new ComponentList<LG_Light>(); public static ComponentList<LG_ComputerTerminal> Terminals { get; private set; } = new ComponentList<LG_ComputerTerminal>(); public static ComponentList<LG_LabDisplay> LabDisplays { get; private set; } = new ComponentList<LG_LabDisplay>(); public static ComponentList<LG_DoorButton> DoorButtons { get; private set; } = new ComponentList<LG_DoorButton>(); public static ComponentList<LG_WeakLock> WeakLocks { get; private set; } = new ComponentList<LG_WeakLock>(); public static ComponentList<LG_HSUActivator_Core> HSUActivators { get; private set; } = new ComponentList<LG_HSUActivator_Core>(); public static ComponentList<CarryItemPickup_Core> CarryItems { get; private set; } = new ComponentList<CarryItemPickup_Core>(); public static ComponentList<GenericSmallPickupItem_Core> PickupItems { get; private set; } = new ComponentList<GenericSmallPickupItem_Core>(); public static ComponentList<LG_Ladder> Ladders { get; private set; } = new ComponentList<LG_Ladder>(); public static ComponentList<LG_WardenObjective_Reactor> Reactors { get; private set; } = new ComponentList<LG_WardenObjective_Reactor>(); public static ComponentList<LG_PowerGeneratorCluster> GeneratorClusters { get; private set; } = new ComponentList<LG_PowerGeneratorCluster>(); public static ComponentList<LG_PowerGenerator_Core> Generators { get; private set; } = new ComponentList<LG_PowerGenerator_Core>(); [AutoInvoke(InvokeWhen.PluginLoaded)] internal static void Init() { LevelAPI.OnLevelCleanup += OnLevelCleanup; } private static void OnLevelCleanup() { SecurityDoors.Clear(); WeakDoors.Clear(); Lights.Clear(); Terminals.Clear(); LabDisplays.Clear(); DoorButtons.Clear(); WeakLocks.Clear(); HSUActivators.Clear(); CarryItems.Clear(); PickupItems.Clear(); Ladders.Clear(); Reactors.Clear(); GeneratorClusters.Clear(); Generators.Clear(); } public static O FindObjectInLevel<O>(bool includeInactive = false) where O : Object { return ((Component)Builder.CurrentFloor).GetComponentInChildren<O>(includeInactive); } public static IEnumerable<O> FindObjectsInLevel<O>(bool includeInactive = false) where O : Object { return (IEnumerable<O>)((Component)Builder.CurrentFloor).GetComponentsInChildren<O>(includeInactive); } public static LG_SecurityDoor FindSecurityDoor(LG_LayerType layer, eLocalZoneIndex localindex) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) return FindSecurityDoor((eDimensionIndex)0, layer, localindex); } public static LG_SecurityDoor FindSecurityDoor(eDimensionIndex dim, LG_LayerType layer, eLocalZoneIndex localindex) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) LG_Zone val = default(LG_Zone); Builder.CurrentFloor.TryGetZoneByLocalIndex(dim, layer, localindex, ref val); if ((Object)(object)val == (Object)null) { return null; } if ((Object)(object)val.m_sourceGate == (Object)null) { return null; } if (val.m_sourceGate.SpawnedDoor == null) { return null; } return ((Il2CppObjectBase)val.m_sourceGate.SpawnedDoor).TryCast<LG_SecurityDoor>(); } } public static class LocalPlayer { private static int? _InstanceID; public static bool HasAgent { get; private set; } public static PlayerAgent Agent { get; private set; } public static LocalPlayerAgent LocalAgent { get; private set; } public static bool TryGetAgent(out PlayerAgent agent) { agent = Agent; return HasAgent; } public static bool TryGetLocalAgent(out LocalPlayerAgent agent) { agent = LocalAgent; return HasAgent; } public static Vector3 GetPosition() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) if (HasAgent) { return ((Agent)Agent).Position; } return Vector3.zero; } public static Vector3 GetPosition(Vector3 fallback) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) if (HasAgent) { return ((Agent)Agent).Position; } return fallback; } public static Vector3 GetEyePosition() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) if (HasAgent) { return ((Agent)Agent).EyePosition; } return Vector3.zero; } public static Vector3 GetEyePosition(Vector3 fallback) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) if (HasAgent) { return ((Agent)Agent).EyePosition; } return fallback; } [AutoInvoke(InvokeWhen.StartupAssetLoaded)] internal static void Init() { Coroutines.Start(UpdatePlayerInfo()); } private static IEnumerator UpdatePlayerInfo() { while (true) { if (PlayerManager.HasLocalPlayerAgent()) { PlayerAgent localPlayerAgent = PlayerManager.GetLocalPlayerAgent(); int instanceID = ((Object)localPlayerAgent).GetInstanceID(); if (!_InstanceID.HasValue || _InstanceID.Value != instanceID) { Agent = localPlayerAgent; LocalAgent = ((Il2CppObjectBase)localPlayerAgent).Cast<LocalPlayerAgent>(); _InstanceID = ((Object)localPlayerAgent).GetInstanceID(); HasAgent = true; } } else { Agent = null; LocalAgent = null; _InstanceID = null; HasAgent = false; } yield return null; } } } } namespace FloLib.Infos.Inject { [HarmonyPatch] internal static class Inject_Builder { internal static event Action BeforeBuildStart; [HarmonyPostfix] [HarmonyPatch(typeof(Builder), "BuildDone")] [HarmonyPriority(800)] private static void Post_BuildDone() { LG_Objects.Terminals.AddRange(Find<LG_ComputerTerminal>()); LG_Objects.LabDisplays.AddRange(Find<LG_LabDisplay>()); LG_Objects.DoorButtons.AddRange(Find<LG_DoorButton>()); LG_Objects.WeakLocks.AddRange(Find<LG_WeakLock>()); LG_Objects.HSUActivators.AddRange(Find<LG_HSUActivator_Core>()); LG_Objects.CarryItems.AddRange(Find<CarryItemPickup_Core>()); LG_Objects.PickupItems.AddRange(Find<GenericSmallPickupItem_Core>()); LG_Objects.Ladders.AddRange(Find<LG_Ladder>()); LG_Objects.Reactors.AddRange(Find<LG_WardenObjective_Reactor>()); LG_Objects.GeneratorClusters.AddRange(Find<LG_PowerGeneratorCluster>()); LG_Objects.Generators.AddRange(Find<LG_PowerGenerator_Core>()); } [HarmonyPrefix] [HarmonyPatch(typeof(Builder), "Build")] private static void Pre_Build() { Inject_Builder.BeforeBuildStart?.Invoke(); } private static IEnumerable<T> Find<T>() where T : Object { return LG_Objects.FindObjectsInLevel<T>(); } } [HarmonyPatch(typeof(LG_BuildZoneLightsJob), "Build")] internal static class Inject_LG_LightBuild { [HarmonyPriority(0)] private static void Prefix(LG_BuildZoneLightsJob __instance, out List<LG_Light> __state) { __state = new List<LG_Light>(); Enumerator<AIG_CourseNode> enumerator = __instance.m_zone.m_courseNodes.GetEnumerator(); while (enumerator.MoveNext()) { foreach (LG_Light componentsInChild in ((Component)enumerator.Current.m_area).GetComponentsInChildren<LG_Light>()) { LightData lightData = ((Component)componentsInChild).gameObject.AddComponent<LightData>(); LG_PointLight result2; if (((Il2CppObjectBase)(object)componentsInChild).TryCastToType<LG_SpotLight>(out LG_SpotLight result)) { lightData.PrefabIntensity.Set(result.m_spotLight.intensity); } else if (((Il2CppObjectBase)(object)componentsInChild).TryCastToType<LG_PointLight>(out result2)) { lightData.PrefabIntensity.Set(result2.m_pointLight.intensity); } else { if (!((Il2CppObjectBase)(object)componentsInChild).TryCastToType<LG_SpotLightAmbient>(out LG_SpotLightAmbient result3)) { continue; } lightData.PrefabIntensity.Set(result3.m_spotLight.intensity); } __state.Add(componentsInChild); } } LG_Objects.Lights.AddRange(__state); } [HarmonyPriority(0)] private static void Postfix(List<LG_Light> __state) { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown bool flag = default(bool); foreach (LG_Light item in __state) { LightData component = ((Component)item).GetComponent<LightData>(); if ((Object)(object)component == (Object)null) { BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(32, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Found Light without "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("LightData"); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" Component! "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(((Component)(object)item).GetGameObjectPath()); } Logger.Error(val); } else { component.SpawnedIntensity = item.m_intensity; component.SpawnedColor = item.m_color; component.SpawnedMode = GetLightMode(item); } } __state.Clear(); } private static LightMode GetLightMode(LG_Light light) { if (light.GetC_Light().LightUpdator != null) { return LightMode.Broken_Flickering; } if (((Component)light).gameObject.active) { return LightMode.On; } return LightMode.Off; } } [HarmonyPatch(typeof(LG_SecurityDoor), "Setup")] internal static class Inject_LG_SecDoor { private static void Postfix(LG_SecurityDoor __instance) { LG_Objects.SecurityDoors.Add(__instance); } } [HarmonyPatch(typeof(LG_WeakDoor), "Setup")] internal static class Inject_LG_WeakDoor { private static void Postfix(LG_WeakDoor __instance) { LG_Objects.WeakDoors.Add(__instance); } } } namespace FloLib.Infos.Comps { [AutoInject] internal sealed class LightData : MonoBehaviour { public Il2CppValueField<float> PrefabIntensity; public LightMode SpawnedMode; public float SpawnedIntensity; public Color SpawnedColor; public LG_LightInfo.Data CreateData() { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) LG_LightInfo.Data result = default(LG_LightInfo.Data); result.PrefabIntensity = Il2CppValueField<float>.op_Implicit(PrefabIntensity); result.SpawnedMode = SpawnedMode; result.SpawnedIntensity = SpawnedIntensity; result.SpawnedColor = SpawnedColor; return result; } } } namespace FloLib.Game.ScreenShakes { public sealed class ScreenShake { [AutoInvoke(InvokeWhen.StartupAssetLoaded)] internal static void Init() { GlobalNetAction<ScreenShakeDescriptor>.OnReceive += OnReceive; } public static void Trigger(ScreenShakeDescriptor data) { GlobalNetAction<ScreenShakeDescriptor>.Send(data); } private static void OnReceive(ulong sender, ScreenShakeDescriptor data) { if (LocalPlayer.TryGetAgent(out var agent)) { FPSCamera fPSCamera = agent.FPSCamera; MonoBehaviourExtensions.StartCoroutine((MonoBehaviour)(object)fPSCamera, DoShake(fPSCamera, data)); } } private static IEnumerator DoShake(FPSCamera camera, ScreenShakeDescriptor data) { float time = 0f; while (time < data.Duration) { float num = 1f; if (data.Mode == ScreenShakeMode.PositionFalloff) { float num2 = Vector3.Distance(data.Position, camera.Position); num = Mathf.InverseLerp(data.FalloffEnd, data.FalloffStart, num2); } float t = data.Modifier switch { ScreenShakeModifier.PingPong => Mathf.PingPong(Mathf.InverseLerp(data.Duration, 0f, time) * 2f, 1f), ScreenShakeModifier.Increase => Mathf.InverseLerp(0f, data.Duration, time), ScreenShakeModifier.Decrease => Mathf.InverseLerp(data.Duration, 0f, time), _ => 1f, }; t = data.IntensityEasing.Evaluate(t); float constantCameraShakeAmount = num * t * data.Intensity; camera.SetConstantCameraShakeAmount(constantCameraShakeAmount); time += Time.deltaTime; yield return null; } camera.SetConstantCameraShakeAmount(0f); } } public struct ScreenShakeDescriptor { public ScreenShakeMode Mode; public ScreenShakeModifier Modifier; public Vector3 Position; public float Intensity; public float Duration; public float FalloffStart; public float FalloffEnd; public EaseFunc.Type IntensityEasing; } public enum ScreenShakeMode : byte { Global, PositionFalloff } public enum ScreenShakeModifier : byte { PingPong, Increase, Decrease, Constant } } namespace FloLib.Game.Projectiles { public class Projectile : MonoBehaviour { } } namespace FloLib.Game.Explosions { public sealed class Explosion { public static readonly Color DefaultFlashColor = new Color(1f, 0.2f, 0f, 1f); [AutoInvoke(InvokeWhen.StartupAssetLoaded)] internal static void Init() { ExplosionEffectPooling.Initialize(); GlobalNetAction<ExplosionDescriptor>.OnReceive += OnReceive; } private static void OnReceive(ulong sender, ExplosionDescriptor data) { Internal_TriggerExplosion(data); } public static void Trigger(ExplosionDescriptor data) { GlobalNetAction<ExplosionDescriptor>.Send(data); } internal static void Internal_TriggerExplosion(ExplosionDescriptor data) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) CellSound.Post(EVENTS.STICKYMINEEXPLODE, data.Position); LightFlash(data.Position, data.MaxDamageRange, data.LightColor); if (!SNet.IsMaster) { return; } Il2CppReferenceArray<Collider> val = Physics.OverlapSphere(data.Position, data.MaxDamageRange, LayerManager.MASK_EXPLOSION_TARGETS); if (((Il2CppArrayBase<Collider>)(object)val).Count < 1) { return; } DamageUtil.IncrementSearchID(); uint searchID = DamageUtil.SearchID; foreach (Collider item in (Il2CppArrayBase<Collider>)(object)val) { ProcessExplosion(data, item, searchID); } } private static void ProcessExplosion(ExplosionDescriptor data, Collider target, uint searchID) { //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)target == (Object)null || (Object)(object)((Component)target).gameObject == (Object)null || !((Component)target).gameObject.TryGetComp<IDamageable>(out var component)) { return; } component = component.GetBaseDamagable(); if (component == null || component.TempSearchID == searchID) { return; } Vector3 damagablePosition = GetDamagablePosition(component); component.TempSearchID = searchID; float distance = Vector3.Distance(data.Position, damagablePosition); if (!IsExplosionBlocked(data.Position, damagablePosition, target)) { float num = CalcBaseRangeDamage(data.MaxDamage, distance, data.MaxDamageRange, data.MinDamageRange); if ((Object)(object)((Il2CppObjectBase)component).TryCast<Dam_EnemyDamageBase>() != (Object)null) { num *= (float)data.DamageMultiplierToEnemy; } else if ((Object)(object)((Il2CppObjectBase)component).TryCast<Dam_PlayerDamageBase>() != (Object)null) { num *= (float)data.DamageMultiplierToPlayer; } Agent baseAgent = component.GetBaseAgent(); if ((Object)(object)baseAgent != (Object)null && baseAgent.GlobalID == data.Inflictor.AgentID) { num *= (float)data.DamageMultiplierToInflictor; } if (Mathf.Abs(num) > float.Epsilon) { component.ExplosionDamage(num, data.Position, Vector3.up * 1000f, 0u); } } } private static Vector3 GetDamagablePosition(IDamageable damagable) { //IL_0018: 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) Agent baseAgent = damagable.GetBaseAgent(); if ((Object)(object)baseAgent != (Object)null) { return baseAgent.EyePosition; } return damagable.DamageTargetPos; } private static bool IsExplosionBlocked(Vector3 pos1, Vector3 pos2, Collider targetCollider) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) RaycastHit val = default(RaycastHit); if (Physics.Linecast(pos1, pos2, ref val, LayerManager.MASK_EXPLOSION_BLOCKERS)) { if
plugins/net6/FlowGeos.dll
Decompiled a month agousing System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using GTFO.API; using HarmonyLib; using LevelGeneration; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")] [assembly: AssemblyCompany("FlowGeos")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("FlowGeos")] [assembly: AssemblyTitle("FlowGeos")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] namespace FlowGeos; [BepInPlugin("FlowGeos", "FlowGeos", "1.0.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class EntryPoint : BasePlugin { private Harmony m_Harmony; public override void Load() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown m_Harmony = new Harmony("FlowGeos"); m_Harmony.PatchAll(); } } internal static class FlowGeosLogger { private static readonly ManualLogSource _logger; static FlowGeosLogger() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Expected O, but got Unknown _logger = new ManualLogSource("FlowGeos"); Logger.Sources.Add((ILogSource)(object)_logger); } private static string Format(object msg) { return msg.ToString(); } public static void Info(object data) { _logger.LogMessage((object)Format(data)); } public static void Verbose(object data) { } public static void Debug(object data) { _logger.LogDebug((object)Format(data)); } public static void Error(object data) { _logger.LogError((object)Format(data)); } } [HarmonyPatch(typeof(LG_WardenObjective_Reactor), "Start")] internal static class Inject_WO_Reactor { private static void Postfix(LG_WardenObjective_Reactor __instance) { if ((Object)(object)__instance.m_terminalPrefab == (Object)null) { FlowGeosLogger.Info("Resolving Terminal Prefab for reactor!"); __instance.m_terminalPrefab = AssetAPI.GetLoadedAsset<GameObject>("Assets/AssetPrefabs/Complex/Generic/FunctionMarkers/Terminal_Floor.prefab"); if ((Object)(object)__instance.m_terminalPrefab == (Object)null) { FlowGeosLogger.Error("We tried to resolve terminal prefab for reactor but it doesn't work..."); } } } }
plugins/net6/Hikaria.PlayerSpawnApart_u.dll
Decompiled a month 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.Json; using System.Text.Json.Serialization; using Agents; using BepInEx; using BepInEx.Unity.IL2CPP; using BepInEx.Unity.IL2CPP.Utils.Collections; using CellMenu; using GTFO.API; using GTFO.API.JSON; using GameData; using HarmonyLib; using Hikaria.PlayerSpawnApart.API; using Hikaria.PlayerSpawnApart.Managers; using Il2CppSystem; using Il2CppSystem.Collections.Generic; using LevelGeneration; using MTFO.Managers; using Player; using SNetwork; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("Hikaria.PlayerSpawnApart")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+2a7852de13d87d53616ee8732a63fbbf5c77ccdc")] [assembly: AssemblyProduct("Hikaria.PlayerSpawnApart")] [assembly: AssemblyTitle("Hikaria.PlayerSpawnApart")] [assembly: AssemblyVersion("1.0.0.0")] namespace Hikaria.PlayerSpawnApart { [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInPlugin("Hikaria.PlayerSpawnApart", "PlayerSpawnApart", "1.0.0")] public class EntryPoint : BasePlugin { private static Harmony m_Harmony; public static EntryPoint Instance { get; private set; } public override void Load() { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected O, but got Unknown Instance = this; Directory.CreateDirectory(Path.Combine(ConfigManager.CustomPath, "PlayerSpawnApart")); PlayerSpawnApartManager.Setup(); m_Harmony = new Harmony("Hikaria.PlayerSpawnApart"); m_Harmony.PatchAll(); Logs.LogMessage("OK"); } public override bool Unload() { if (m_Harmony != null) { m_Harmony.UnpatchSelf(); } return ((BasePlugin)this).Unload(); } } internal static class Logs { public static void LogDebug(object data) { ((BasePlugin)EntryPoint.Instance).Log.LogDebug(data); } public static void LogError(object data) { ((BasePlugin)EntryPoint.Instance).Log.LogError(data); } public static void LogFatal(object data) { ((BasePlugin)EntryPoint.Instance).Log.LogFatal(data); } public static void LogInfo(object data) { ((BasePlugin)EntryPoint.Instance).Log.LogInfo(data); } public static void LogMessage(object data) { ((BasePlugin)EntryPoint.Instance).Log.LogMessage(data); } public static void LogWarning(object data) { ((BasePlugin)EntryPoint.Instance).Log.LogWarning(data); } } public static class PluginInfo { public const string GUID = "Hikaria.PlayerSpawnApart"; public const string NAME = "PlayerSpawnApart"; public const string VERSION = "1.0.0"; } } namespace Hikaria.PlayerSpawnApart.Patches { [HarmonyPatch(typeof(CM_MenuBar))] public class Patch__CM_MenuBar { [HarmonyPatch("OnExpeditionUpdated")] [HarmonyPostfix] private static void CM_MenuBar__OnExpeditionUpdated__Postfix(pActiveExpedition expData, ExpeditionInTierData expInTierData) { PlayerSpawnApartManager.OnExpeditionUpdated(expData, expInTierData); } } [HarmonyPatch(typeof(GameDataInit))] public class Patch__GameDataInit { [HarmonyPatch("Initialize")] [HarmonyPostfix] private static void GameDataInit__Initialize__Postfix() { PlayerSpawnApartManager.OnGameDataInitialized(); } } [HarmonyPatch(typeof(GameStateManager))] public class Patch__GameStateManager { [HarmonyPatch("IsEveryoneReady")] [HarmonyPostfix] private static void GameStateManager__IsEveryoneReady__Postfix(ref bool __result) { if (SNet.IsMaster && __result) { __result = PlayerSpawnApartManager.IsEveryoneReady; } } [HarmonyPatch("set_IsReady")] [HarmonyPrefix] private static void GameStateManager__set_IsReady__Prefix(ref bool value) { if (!PlayerSpawnApartManager.IsReady) { if (value) { GameEventLogManager.AddLog("<color=orange>[PlayerSpawnApart]</color> <color=red>You must choose a slot before get ready!</color>"); GameEventLogManager.AddLog("<color=orange>[PlayerSpawnApart]</color> Type in '/psa help' to show helps."); } value = false; } } [HarmonyPatch("OnResetSession")] [HarmonyPostfix] private static void GameStateManager__OnResetSession__Postfix() { PlayerSpawnApartManager.ResetLocalSpawnApartSlot(); Logs.LogMessage("ResetLocalSpawnApartSlot: OnResetSession"); } [HarmonyPatch("OnLevelCleanup")] [HarmonyPostfix] private static void GameStateManager__OnLevelCleanup__Postfix() { PlayerSpawnApartManager.ResetLocalSpawnApartSlot(); Logs.LogMessage("ResetLocalSpawnApartSlot: OnLevelCleanup"); } [HarmonyPatch("SendGameState")] [HarmonyPostfix] private static void GameStateManager__SendGameState__Postfix() { SNetworkAPI.SendCustomData<pPlayerSpawnApartSlot>(); } } [HarmonyPatch] public class Patch__PlayerChatManager { private static bool isSelecting; [HarmonyPatch(typeof(PlayerChatManager), "PostMessage")] private static void Prefix(PlayerChatManager __instance) { if (string.IsNullOrEmpty(__instance.m_currentValue)) { return; } string text = __instance.m_currentValue.ToLowerInvariant(); if (!isSelecting) { if (text == "5") { isSelecting = true; GameEventLogManager.AddLog("<color=orange>[PlayerSpawnApart]</color> Select position mode activated. Use 1, 2, 3, or 4 to choose position. Enter 6 to stop selecting."); __instance.m_currentValue = string.Empty; } else { if (!text.StartsWith("/psa")) { return; } try { string[] array = text.Split(' '); switch (array.Length) { case 2: if (array[1] == "check") { GameEventLogManager.AddLog("<color=orange>[PlayerSpawnApart]</color> Slot assignments:"); PlayerSpawnApartManager.ShowAllAssignedSlots(); break; } if (array[1] == "reset") { if (!PlayerSpawnApartManager.AllowAssign) { GameEventLogManager.AddLog("<color=orange>[PlayerSpawnApart]</color> <color=red>Slot assignment is only available when in the lobby.</color>"); break; } PlayerSpawnApartManager.ResetLocalSpawnApartSlot(); Logs.LogMessage("ResetLocalSpawnApartSlot: Manual reset"); break; } if (array[1] == "help") { GameEventLogManager.AddLog("<color=orange>[PlayerSpawnApart]</color> Commands available:"); GameEventLogManager.AddLog("/psa assign [slot], assign slot for spawn apart. Range (1-4)."); GameEventLogManager.AddLog("/psa check, check current slot assignments."); GameEventLogManager.AddLog("/psa reset, reset your slot assignment."); break; } goto default; case 3: if (array[1] == "assign") { string msg; if (!PlayerSpawnApartManager.AllowAssign) { GameEventLogManager.AddLog("<color=orange>[PlayerSpawnApart]</color> <color=red>Slot assignment is only available when in the lobby.</color>"); } else if (!PlayerSpawnApartManager.TryAssignSpawnApartSlot(Convert.ToInt32(array[2]), out msg)) { GameEventLogManager.AddLog(msg); } break; } goto default; default: throw new Exception(); } return; } catch (Exception data) { Logs.LogError(data); GameEventLogManager.AddLog("<color=orange>[PlayerSpawnApart]</color> <color=red>Wrong input! Type in '/psa help' to show helps.</color>"); return; } finally { __instance.m_currentValue = string.Empty; } } return; } if (text == "6") { isSelecting = false; GameEventLogManager.AddLog("<color=orange>[PlayerSpawnApart]</color> Select position mode deactivated."); __instance.m_currentValue = string.Empty; return; } try { int num = int.Parse(text); if (num >= 1 && num <= 4) { if (PlayerSpawnApartManager.TryAssignSpawnApartSlot(num, out var msg2)) { GameEventLogManager.AddLog($"<color=orange>[PlayerSpawnApart]</color> Slot {num} assigned successfully."); } else { GameEventLogManager.AddLog(msg2); } } else { GameEventLogManager.AddLog("<color=orange>[PlayerSpawnApart]</color> <color=red>Invalid slot. Please enter a number between 1 and 4.</color>"); } } catch (Exception data2) { Logs.LogError(data2); GameEventLogManager.AddLog("<color=orange>[PlayerSpawnApart]</color> <color=red>Invalid input. Please enter a number between 1 and 4.</color>"); } finally { __instance.m_currentValue = string.Empty; } } } [HarmonyPatch(typeof(SNet_SessionHub))] public class Patch__SNet_SessionHub { [HarmonyPatch("AddPlayerToSession")] [HarmonyPostfix] private static void SNet_SessionHub__AddPlayerToSession__Postfix(SNet_Player player) { if (player.IsLocal) { PlayerSpawnApartManager.ResetLocalSpawnApartSlot(); SNetworkAPI.SendCustomData<pPlayerSpawnApartSlot>(); } else if (!player.IsBot) { SNetworkAPI.SendCustomData<pPlayerSpawnApartSlot>(player); } } } } namespace Hikaria.PlayerSpawnApart.Managers { internal static class GameEventLogManager { public static void AddLog(string log) { MainMenuGuiLayer.Current.PageLoadout.m_gameEventLog.AddLogItem(log, (eGameEventChatLogType)2); GuiManager.PlayerLayer.m_gameEventLog.AddLogItem(log, (eGameEventChatLogType)2); } } public static class PlayerSpawnApartManager { private static readonly string PlayerSpawnApartEventName = typeof(pPlayerSpawnApartSlot).FullName; private static List<PlayerSpawnApartData> PlayerSpawnApartDataLookup = new List<PlayerSpawnApartData>(); private static uint LevelLayoutID; private static PlayerSpawnApartData ActivatedPlayerSpawnApartData; public static bool CanDoSpawnApart { get; set; } private static bool HasActivatedPlayerSpawnApartData => ActivatedPlayerSpawnApartData != null; public static bool AllowAssign => (int)GameStateManager.CurrentStateName == 5; public static bool IsReady { get { if (HasActivatedPlayerSpawnApartData && !((Object)(object)SNet.LocalPlayer == (Object)null)) { return IsPlayerReady(SNet.LocalPlayer); } return true; } } public static bool IsEveryoneReady { get { if (!HasActivatedPlayerSpawnApartData) { return true; } if (SNet.Slots.SlottedPlayers.Count == 0) { return false; } for (int i = 0; i < SNet.Slots.SlottedPlayers.Count; i++) { SNet_Player val = SNet.Slots.SlottedPlayers[i]; if (!val.IsBot) { int slot = val.LoadCustomData<pPlayerSpawnApartSlot>().slot; if (!IsValidSlotRange(slot) || slot == -1) { return false; } } } if (CheckAllSpawnApartSlotHasConflict()) { return false; } return true; } } public static void Setup() { SNetworkAPI.SetupCustomData<pPlayerSpawnApartSlot>(PlayerSpawnApartEventName, OnPlayerSpawnApartSlotChanged); LevelAPI.OnEnterLevel += ApplySpawnApartData; } private static bool IsPlayerReady(SNet_Player player) { if (!HasActivatedPlayerSpawnApartData) { return true; } if ((Object)(object)player == (Object)null || player.IsBot) { return true; } int slot = player.LoadCustomData<pPlayerSpawnApartSlot>().slot; if (slot != -1) { return IsValidSlotRange(slot); } return false; } public static void OnGameDataInitialized() { new JsonSerializerOptions { IncludeFields = false, ReadCommentHandling = JsonCommentHandling.Skip, PropertyNameCaseInsensitive = true, WriteIndented = true, Converters = { (JsonConverter)new JsonStringEnumConverter() } }; PlayerSpawnApartDataLookup = JsonSerializer.Deserialize<List<PlayerSpawnApartData>>(File.ReadAllText(Path.Combine(ConfigManager.CustomPath, "PlayerSpawnApart", "SpawnApartData.json")), (JsonSerializerOptions)null); } public static void ApplySpawnApartData() { if (HasActivatedPlayerSpawnApartData) { CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(DoSpawnApart()), (Action)null); } } private static IEnumerator DoSpawnApart() { PlayerAgent playerAgent = PlayerManager.GetLocalPlayerAgent(); int slot = playerAgent.Owner.LoadCustomData<pPlayerSpawnApartSlot>().slot; Vector3 pos; switch (slot) { case 1: pos = ActivatedPlayerSpawnApartData.Slot1; break; case 2: pos = ActivatedPlayerSpawnApartData.Slot2; break; case 3: pos = ActivatedPlayerSpawnApartData.Slot3; break; case 4: pos = ActivatedPlayerSpawnApartData.Slot4; break; default: GameEventLogManager.AddLog($"<color=orange>[PlayerSpawnApart]</color> <color=red>Illegal Slot[{slot}]!</color>"); yield break; } Dimension val = default(Dimension); Dimension.GetDimension((eDimensionIndex)0, ref val); playerAgent.TryWarpTo((eDimensionIndex)0, val.GetStartCourseNode().Position, ((Agent)playerAgent).TargetLookDir, (WarpOptions)0); yield return (object)new WaitForFixedUpdate(); eDimensionIndex dimensionIndex = Dimension.GetDimensionFromPos(pos).DimensionIndex; if ((int)dimensionIndex != 0) { playerAgent.RequestWarpToSync(dimensionIndex, pos, ((Agent)playerAgent).TargetLookDir, (WarpOptions)0); } else { playerAgent.TeleportTo(pos); } } private static bool AssignSlotValidate(SNet_Player player, int slot) { if (!IsValidSlotRange(slot)) { return false; } if (slot == -1) { return true; } for (int i = 0; i < SNet.Slots.SlottedPlayers.Count; i++) { SNet_Player val = SNet.Slots.SlottedPlayers[i]; if (!((Object)(object)val == (Object)(object)player) && val.LoadCustomData<pPlayerSpawnApartSlot>().slot == slot) { return false; } } return true; } private static bool IsValidSlotRange(int slot) { if (slot != -1) { if (slot >= 1) { return slot <= 4; } return false; } return true; } public static void ResetLocalSpawnApartSlot() { pPlayerSpawnApartSlot pPlayerSpawnApartSlot2 = new pPlayerSpawnApartSlot(SNet.LocalPlayer, -1); SNetworkAPI.SetLocalCustomData(pPlayerSpawnApartSlot2); OnPlayerSpawnApartSlotChanged(SNet.LocalPlayer, pPlayerSpawnApartSlot2); } private static bool LocalCheckSpawnApartSlotHasConflict() { int slot = SNet.LocalPlayer.LoadCustomData<pPlayerSpawnApartSlot>().slot; if (slot == -1) { return false; } for (int i = 0; i < SNet.Slots.SlottedPlayers.Count; i++) { SNet_Player val = SNet.Slots.SlottedPlayers[i]; if (!val.IsBot && !val.IsLocal && val.LoadCustomData<pPlayerSpawnApartSlot>().slot == slot) { return true; } } return false; } private static bool CheckAllSpawnApartSlotHasConflict() { List<SNet_Player> players = ((IEnumerable<SNet_Player>)SNet.Slots.SlottedPlayers.ToArray()).ToList(); if (players.Any((SNet_Player p) => p.LoadCustomData<pPlayerSpawnApartSlot>().slot != -1 && players.Any((SNet_Player q) => (Object)(object)p != (Object)(object)q && p.LoadCustomData<pPlayerSpawnApartSlot>().slot == q.LoadCustomData<pPlayerSpawnApartSlot>().slot))) { return true; } return false; } public static bool TryAssignSpawnApartSlot(int slot, out string msg) { msg = string.Empty; if (!IsValidSlotRange(slot)) { msg = "<color=orange>[PlayerSpawnApart]</color> <color=red>Illegal slot range. Range (1-4).</color>"; return false; } if (!AssignSlotValidate(SNet.LocalPlayer, slot)) { msg = $"<color=orange>[PlayerSpawnApart]</color> <color=red>Slot[{slot}] is not avaliable!</color>"; return false; } pPlayerSpawnApartSlot pPlayerSpawnApartSlot2 = new pPlayerSpawnApartSlot(SNet.LocalPlayer, slot); SNetworkAPI.SetLocalCustomData(pPlayerSpawnApartSlot2); OnPlayerSpawnApartSlotChanged(SNet.LocalPlayer, pPlayerSpawnApartSlot2); return true; } public static void OnExpeditionUpdated(pActiveExpedition expData, ExpeditionInTierData expInTierData) { LevelLayoutID = expInTierData.LevelLayoutData; for (int i = 0; i < PlayerSpawnApartDataLookup.Count; i++) { PlayerSpawnApartData playerSpawnApartData = PlayerSpawnApartDataLookup[i]; if (playerSpawnApartData.MainLevelLayoutID == LevelLayoutID && playerSpawnApartData.InternalEnabled) { ActivatedPlayerSpawnApartData = playerSpawnApartData; return; } } ActivatedPlayerSpawnApartData = null; } private static void OnPlayerSpawnApartSlotChanged(SNet_Player player, pPlayerSpawnApartSlot data) { //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Invalid comparison between Unknown and I4 if (!HasActivatedPlayerSpawnApartData) { return; } if (player.IsLocal && LocalCheckSpawnApartSlotHasConflict()) { GameEventLogManager.AddLog($"<color=orange>[PlayerSpawnApart]</color> <color=red>Slot[{data.slot}] has a conflict, please reassign!</color>"); return; } if (data.slot == -1) { GameEventLogManager.AddLog("<color=orange>[PlayerSpawnApart]</color> " + player.NickName + "</color> reset slot."); } else { GameEventLogManager.AddLog($"<color=orange>[PlayerSpawnApart]</color> {player.NickName}</color> assign slot[{data.slot}]."); } if ((int)GameStateManager.CurrentStateName == 5) { if (IsEveryoneReady) { GameEventLogManager.AddLog("<color=orange>[PlayerSpawnApart]</color> <color=green>All players are ready:</color>"); ShowAllAssignedSlots(); } else if (CheckAllSpawnApartSlotHasConflict()) { GameEventLogManager.AddLog("<color=orange>[PlayerSpawnApart]</color> <color=red>Slot assignments conflict, please review!</color>"); ShowAllAssignedSlots(); } } } public static void ShowAllAssignedSlots() { for (int i = 0; i < SNet.Slots.SlottedPlayers.Count; i++) { SNet_Player val = SNet.Slots.SlottedPlayers[i]; if (!val.IsBot) { GameEventLogManager.AddLog($"{val.NickName}</color>: Slot[{val.LoadCustomData<pPlayerSpawnApartSlot>().slot}]"); } } } } public class PlayerSpawnApartData { public Vector3 Slot1 { get; set; } public Vector3 Slot2 { get; set; } public Vector3 Slot3 { get; set; } public Vector3 Slot4 { get; set; } public uint MainLevelLayoutID { get; set; } public bool InternalEnabled { get; set; } public string DebugName { get; set; } } public struct pPlayerSpawnApartSlot : IReplicatedPlayerData { public pPlayer PlayerData { get; set; } public int slot { get; set; } public pPlayerSpawnApartSlot() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) PlayerData = default(pPlayer); slot = -1; } public pPlayerSpawnApartSlot(SNet_Player player, int slot) { //IL_0006: 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_0020: Unknown result type (might be due to invalid IL or missing references) PlayerData = default(pPlayer); this.slot = -1; this.slot = slot; pPlayer playerData = PlayerData; ((pPlayer)(ref playerData)).SetPlayer(player); } } } namespace Hikaria.PlayerSpawnApart.API { public interface IReplicatedPlayerData { pPlayer PlayerData { get; set; } } public static class SNetworkAPI { public abstract class DataWrapper { public abstract void Send(SNet_Player fromPlayer, SNet_Player toPlayer = null); } public class DataWrapper<A> : DataWrapper where A : struct { private A m_data; public A Load() { return m_data; } public void Store(SNet_Player player, A data) { m_data = data; SNet_ReplicatedPlayerData<A>.SendData(player, m_data); } public override void Send(SNet_Player fromPlayer, SNet_Player toPlayer = null) { SNet_ReplicatedPlayerData<A>.SendData(fromPlayer, m_data, toPlayer); } } private static Dictionary<ulong, Dictionary<Type, DataWrapper>> DataWrappersLookup = new Dictionary<ulong, Dictionary<Type, DataWrapper>>(); public static void SetupCustomData<A>(string eventName, Action<SNet_Player, A> callback) where A : struct, IReplicatedPlayerData { SNet_ReplicatedPlayerData<A>.Setup(eventName, callback); } public static void SetLocalCustomData<A>(A data) where A : struct { if ((Object)(object)SNet.LocalPlayer != (Object)null) { SNet.LocalPlayer.StoreCustomData(data); } } public static void SendCustomData<A>(SNet_Player toPlayer = null) where A : struct { if ((Object)(object)toPlayer != (Object)null && toPlayer.IsBot) { return; } if ((Object)(object)SNet.LocalPlayer != (Object)null) { SNet_ReplicatedPlayerData<A>.SendData(SNet.LocalPlayer, GetLocalCustomData<A>(), toPlayer); } if (!SNet.IsMaster || !((Object)(object)toPlayer != (Object)null) || toPlayer.IsBot) { return; } List<SNet_Player> allBots = SNet.Core.GetAllBots(true); for (int i = 0; i < allBots.Count; i++) { SNet_Player val = allBots[i]; if ((Object)(object)val != (Object)null && val.IsBot) { SNet_ReplicatedPlayerData<A>.SendData(val, val.LoadCustomData<A>(), toPlayer); } } } public static A GetLocalCustomData<A>() where A : struct { if ((Object)(object)SNet.LocalPlayer != (Object)null) { return SNet.LocalPlayer.LoadCustomData<A>(); } return new A(); } public static A LoadCustomData<A>(this SNet_Player player) where A : struct { Type typeFromHandle = typeof(A); if (!DataWrappersLookup.TryGetValue(player.Lookup, out var value)) { DataWrappersLookup[player.Lookup] = new Dictionary<Type, DataWrapper>(); value = DataWrappersLookup[player.Lookup]; } DataWrapper<A> dataWrapper; if (!value.TryGetValue(typeFromHandle, out var value2)) { dataWrapper = new DataWrapper<A>(); value.Add(typeFromHandle, dataWrapper); } else { dataWrapper = (DataWrapper<A>)value2; } return dataWrapper.Load(); } public static void StoreCustomData<A>(this SNet_Player player, A data) where A : struct { Type typeFromHandle = typeof(A); if (!DataWrappersLookup.TryGetValue(player.Lookup, out var value)) { DataWrappersLookup[player.Lookup] = new Dictionary<Type, DataWrapper>(); value = DataWrappersLookup[player.Lookup]; } DataWrapper<A> dataWrapper; if (!value.TryGetValue(typeFromHandle, out var value2)) { dataWrapper = new DataWrapper<A>(); value.Add(typeFromHandle, dataWrapper); } else { dataWrapper = (DataWrapper<A>)value2; } dataWrapper.Store(player, data); } } public class SNet_Packet<T> where T : struct { private T m_data = new T(); private bool m_hasValidateAction; public string EventName { get; set; } private Action<T> ValidateAction { get; set; } private Action<ulong, T> ReceiveAction { get; set; } public void Setup(string eventName) { EventName = eventName; NetworkAPI.RegisterEvent<T>(eventName, (Action<ulong, T>)OnReceiveData); } public static SNet_Packet<T> Create(string eventName, Action<ulong, T> receiveAction, Action<T> validateAction = null) { SNet_Packet<T> sNet_Packet = new SNet_Packet<T> { EventName = eventName, ReceiveAction = receiveAction, ValidateAction = validateAction, m_hasValidateAction = (validateAction != null) }; NetworkAPI.RegisterEvent<T>(eventName, (Action<ulong, T>)sNet_Packet.OnReceiveData); return sNet_Packet; } public void Ask(T data, SNet_ChannelType channelType = 0) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) if (SNet.IsMaster) { ValidateAction(data); } else if (SNet.HasMaster) { Send(data, channelType, SNet.Master); } } public void Send(T data, SNet_ChannelType type, SNet_Player player = null) { //IL_001f: 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) if ((Object)(object)player == (Object)null) { NetworkAPI.InvokeEvent<T>(EventName, data, type); } else { NetworkAPI.InvokeEvent<T>(EventName, data, player, type); } } public void OnReceiveData(ulong sender, T data) { m_data = data; if (m_hasValidateAction && SNet.IsMaster) { ValidateAction(m_data); } else { ReceiveAction(sender, m_data); } } } public class SNet_ReplicatedPlayerData<A> where A : struct { public delegate bool delegateComparisonAction(A playerData, SNet_Player player, A comparisonData); private static SNet_ReplicatedPlayerData<A> s_singleton; private SNet_Packet<A> m_syncPacket; private Action<SNet_Player, A> m_onChangeCallback; public static void Setup(string eventName, Action<SNet_Player, A> callback) { if (s_singleton == null) { s_singleton = new SNet_ReplicatedPlayerData<A>(); s_singleton.m_syncPacket = SNet_Packet<A>.Create(eventName, OnReceiveData); } s_singleton.m_onChangeCallback = callback; } private static void OnReceiveData(ulong sender, A wrappedData) { //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) pPlayer playerData = ((IReplicatedPlayerData)(object)wrappedData).PlayerData; SNet_Player val = default(SNet_Player); if (((pPlayer)(ref playerData)).TryGetPlayer(ref val) && !val.IsLocal) { val.StoreCustomData(wrappedData); s_singleton.m_onChangeCallback?.Invoke(val, wrappedData); } } public static void SendData(SNet_Player player, A data, SNet_Player toPlayer = null) { //IL_0023: 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) if ((!((Object)(object)toPlayer != (Object)null) || !toPlayer.IsBot) && (player.IsLocal || SNet.IsMaster)) { pPlayer playerData = default(pPlayer); ((pPlayer)(ref playerData)).SetPlayer(player); IReplicatedPlayerData obj = (IReplicatedPlayerData)(object)data; obj.PlayerData = playerData; data = (A)obj; if ((Object)(object)toPlayer != (Object)null) { s_singleton.m_syncPacket.Send(data, (SNet_ChannelType)0, toPlayer); } else { s_singleton.m_syncPacket.Send(data, (SNet_ChannelType)0); } } } public static bool Compare(delegateComparisonAction comparisonAction, A comparisonValue, eComparisonGroup group, bool includeBots = false) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Invalid comparison between Unknown and I4 List<SNet_Player> val; if ((int)group != 0) { if ((int)group != 1) { return false; } val = SNet.Slots.PlayersSynchedWithGame; } else { val = SNet.Slots.SlottedPlayers; } int count = val.Count; for (int i = 0; i < count; i++) { SNet_Player val2 = val[i]; if (includeBots || !val2.IsBot) { A playerData = val2.LoadCustomData<A>(); if (!comparisonAction(playerData, val2, comparisonValue)) { return false; } } } return true; } } }
plugins/net6/Inas07.EOSExt.DimensionWarp.dll
Decompiled a month agousing System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using AIGraph; using Agents; using BepInEx; using BepInEx.Unity.IL2CPP; using EOSExt.DimensionWarp.Definition; using ExtraObjectiveSetup.BaseClasses; using ExtraObjectiveSetup.ExtendedWardenEvents; using ExtraObjectiveSetup.Utils; using GameData; using HarmonyLib; using Il2CppInterop.Runtime.InteropTypes; using Il2CppSystem.Collections.Generic; using LevelGeneration; using Microsoft.CodeAnalysis; using Player; using SNetwork; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("Inas07.EOSExt.DimensionWarp")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("Inas07.EOSExt.DimensionWarp")] [assembly: AssemblyTitle("Inas07.EOSExt.DimensionWarp")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace EOSExt.DimensionWarp { public class DimensionWarpManager : GenericExpeditionDefinitionManager<DimensionWarpDefinition> { public enum WardenEvents_Warp { WarpTeam = 160, WarpRange, WarpItemsInZone } private readonly ImmutableList<Vector3> lookDirs = new List<Vector3> { Vector3.forward, Vector3.back, Vector3.left, Vector3.right }.ToImmutableList(); public static DimensionWarpManager Current { get; private set; } protected override string DEFINITION_NAME => "DimensionWarp"; public AIG_NodeCluster GetNodeFromDimensionPosition(eDimensionIndex dimensionIndex, Vector3 position) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0012: 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) AIG_GeomorphNodeVolume val = default(AIG_GeomorphNodeVolume); AIG_VoxelNodePillar val2 = default(AIG_VoxelNodePillar); AIG_INode val3 = default(AIG_INode); AIG_NodeCluster result = default(AIG_NodeCluster); if (!AIG_GeomorphNodeVolume.TryGetGeomorphVolume(0, dimensionIndex, position, ref val) || !((AIG_NodeVolume)val).m_voxelNodeVolume.TryGetPillar(position, ref val2) || !val2.TryGetVoxelNode(position.y, ref val3) || !AIG_NodeCluster.TryGetNodeCluster(val3.ClusterID, ref result)) { EOSLogger.Error("GetNodeFromDimensionPosition: Position is not valid, try again inside an area."); return null; } return result; } public DimensionWarpDefinition GetWarpDefinition(string worldEventObjectFilter) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 if ((int)GameStateManager.CurrentStateName != 10 || !base.definitions.ContainsKey(RundownManager.ActiveExpedition.LevelLayoutData)) { EOSLogger.Error($"GetWarpPositions: Didn't find config with MainLevelLayout {RundownManager.ActiveExpedition.LevelLayoutData}"); return null; } DimensionWarpDefinition dimensionWarpDefinition = base.definitions[RundownManager.ActiveExpedition.LevelLayoutData].Definitions.Find((DimensionWarpDefinition def) => def.WorldEventObjectFilter == worldEventObjectFilter); if (dimensionWarpDefinition == null) { EOSLogger.Error($"GetWarpPositions: Didn't find config for {worldEventObjectFilter} with MainLevelLayout {RundownManager.ActiveExpedition.LevelLayoutData}"); return new DimensionWarpDefinition(); } return dimensionWarpDefinition; } public void WarpItem(ItemInLevel item, eDimensionIndex warpToDim, Vector3 warpToPosition) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Invalid comparison between Unknown and I4 //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) if (SNet.IsMaster && (int)GameStateManager.CurrentStateName == 10 && (Object)(object)item != (Object)null) { AIG_NodeCluster nodeFromDimensionPosition = GetNodeFromDimensionPosition(warpToDim, warpToPosition); if (nodeFromDimensionPosition != null) { item.GetSyncComponent().AttemptPickupInteraction((ePickupItemInteractionType)1, (SNet_Player)null, ((Item)item).pItemData.custom, warpToPosition, Quaternion.identity, nodeFromDimensionPosition.CourseNode, true, true); } else { EOSLogger.Error("WarpTeam: cannot find course node for item to warp"); } } } public void WarpItemsInZone(eDimensionIndex dimensionIndex, LG_LayerType layer, eLocalZoneIndex localIndex, string worldEventObjectFilter) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Invalid comparison between Unknown and I4 //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: 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_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Unknown result type (might be due to invalid IL or missing references) if (!SNet.IsMaster || (int)GameStateManager.CurrentStateName != 10) { return; } if ((Object)(object)PlayerManager.GetLocalPlayerAgent() == (Object)null) { EOSLogger.Error("WarpItemsInZone: master - LocalPlayerAgent is null???"); return; } DimensionWarpDefinition warpDefinition = GetWarpDefinition(worldEventObjectFilter); if (warpDefinition == null) { EOSLogger.Error("WarpItemsInZone: worldEventObjectFilter '" + worldEventObjectFilter + "' is not defined"); return; } List<PositionAndLookDir> locations = warpDefinition.Locations; if (locations.Count < 1) { EOSLogger.Error("WarpItemsInZone: no warp position found"); return; } int num = 0; Enumerator<IWarpableObject> enumerator = Dimension.WarpableObjects.GetEnumerator(); while (enumerator.MoveNext()) { ItemInLevel val = ((Il2CppObjectBase)enumerator.Current).TryCast<ItemInLevel>(); if ((Object)(object)val != (Object)null) { AIG_CourseNode courseNode = val.CourseNode; if (val.internalSync.GetCurrentState().placement.droppedOnFloor && courseNode.m_dimension.DimensionIndex == dimensionIndex && courseNode.LayerType == layer && courseNode.m_zone.LocalIndex == localIndex && (!warpDefinition.OnWarp.WarpItemsInZone_OnlyWarpWarpable || val.CanWarp)) { Vector3 warpToPosition = locations[num].Position.ToVector3(); WarpItem(val, dimensionIndex, warpToPosition); } num = (num + 1) % locations.Count; } } } internal void WarpItemsInZone(WardenObjectiveEventData e) { //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_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) eDimensionIndex dimensionIndex = e.DimensionIndex; LG_LayerType layer = e.Layer; eLocalZoneIndex localIndex = e.LocalIndex; string worldEventObjectFilter = e.WorldEventObjectFilter; WarpItemsInZone(dimensionIndex, layer, localIndex, worldEventObjectFilter); } public void WarpRange(Vector3 rangeOrigin, float range, string worldEventObjectFilter) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 //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) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_01fa: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Unknown result type (might be due to invalid IL or missing references) //IL_0204: Unknown result type (might be due to invalid IL or missing references) //IL_0176: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_017c: Unknown result type (might be due to invalid IL or missing references) //IL_0181: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_010b: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0212: Unknown result type (might be due to invalid IL or missing references) //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_019a: Unknown result type (might be due to invalid IL or missing references) //IL_019f: Unknown result type (might be due to invalid IL or missing references) //IL_01a5: Unknown result type (might be due to invalid IL or missing references) //IL_01aa: Unknown result type (might be due to invalid IL or missing references) //IL_011f: 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_012c: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Unknown result type (might be due to invalid IL or missing references) //IL_023b: Unknown result type (might be due to invalid IL or missing references) if ((int)GameStateManager.CurrentStateName != 10) { return; } PlayerAgent localPlayerAgent = PlayerManager.GetLocalPlayerAgent(); if ((Object)(object)localPlayerAgent == (Object)null) { EOSLogger.Error("WarpTeam: LocalPlayerAgent is null"); return; } DimensionWarpDefinition warpDefinition = GetWarpDefinition(worldEventObjectFilter); if (warpDefinition == null) { EOSLogger.Error("WarpItemsInZone: worldEventObjectFilter '" + worldEventObjectFilter + "' is not defined"); return; } List<PositionAndLookDir> locations = warpDefinition.Locations; if (locations.Count < 1) { EOSLogger.Error("WarpAlivePlayersInRange: no warp locations found"); return; } int index = localPlayerAgent.PlayerSlotIndex % locations.Count; Vector3 val = locations[index].Position.ToVector3(); int index2 = locations[index].LookDir % lookDirs.Count; Vector3 val2 = lookDirs[index2]; int num = 0; List<SentryGunInstance> list = new List<SentryGunInstance>(); Enumerator<IWarpableObject> enumerator = Dimension.WarpableObjects.GetEnumerator(); Vector3 val4; while (enumerator.MoveNext()) { IWarpableObject current = enumerator.Current; SentryGunInstance val3 = ((Il2CppObjectBase)current).TryCast<SentryGunInstance>(); if ((Object)(object)val3 != (Object)null) { if (!((ItemEquippable)val3).LocallyPlaced || !((Agent)((Item)val3).Owner).Alive) { continue; } val4 = rangeOrigin - ((Agent)((Item)val3).Owner).Position; if (((Vector3)(ref val4)).magnitude < range) { val4 = rangeOrigin - ((Component)val3).transform.position; if (((Vector3)(ref val4)).magnitude < range || warpDefinition.OnWarp.WarpRange_WarpDeployedSentryOutsideRange) { list.Add(val3); } } } else { if (!SNet.IsMaster) { continue; } ItemInLevel val5 = ((Il2CppObjectBase)current).TryCast<ItemInLevel>(); if ((Object)(object)val5 != (Object)null) { val4 = ((Component)val5).transform.position - rangeOrigin; if (((Vector3)(ref val4)).magnitude < range) { Vector3 warpToPosition = locations[num].Position.ToVector3(); WarpItem(val5, warpDefinition.DimensionIndex, warpToPosition); num = (num + 1) % locations.Count; } } } } list.ForEach(delegate(SentryGunInstance sentryGun) { sentryGun.m_sync.WantItemAction(((Item)sentryGun).Owner, (SyncedItemAction_New)0); }); if (((Agent)localPlayerAgent).Alive) { val4 = rangeOrigin - ((Agent)localPlayerAgent).Position; if (((Vector3)(ref val4)).magnitude < range && !localPlayerAgent.TryWarpTo(warpDefinition.DimensionIndex, val, val2, true)) { EOSLogger.Error($"WarpAlivePlayersInRange: TryWarpTo failed, Position: {val}"); } } } internal void WarpRange(WardenObjectiveEventData e) { //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_0016: Unknown result type (might be due to invalid IL or missing references) Vector3 position = e.Position; float fogTransitionDuration = e.FogTransitionDuration; string worldEventObjectFilter = e.WorldEventObjectFilter; WarpRange(position, fogTransitionDuration, worldEventObjectFilter); } public void WarpTeam(string worldEventObjectFilter) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 //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) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_01c0: Unknown result type (might be due to invalid IL or missing references) //IL_01c5: Unknown result type (might be due to invalid IL or missing references) //IL_01c7: Unknown result type (might be due to invalid IL or missing references) //IL_01e9: Unknown result type (might be due to invalid IL or missing references) //IL_0135: 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_0153: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0163: Unknown result type (might be due to invalid IL or missing references) if ((int)GameStateManager.CurrentStateName != 10) { return; } PlayerAgent localPlayerAgent = PlayerManager.GetLocalPlayerAgent(); if ((Object)(object)localPlayerAgent == (Object)null) { EOSLogger.Error("WarpTeam: LocalPlayerAgent is null"); return; } DimensionWarpDefinition warpDefinition = GetWarpDefinition(worldEventObjectFilter); if (warpDefinition == null) { EOSLogger.Error("WarpTeam: worldEventObjectFilter '" + worldEventObjectFilter + "' is not defined"); return; } List<PositionAndLookDir> locations = warpDefinition.Locations; if (locations.Count < 1) { EOSLogger.Error("WarpTeam: no warp locations found"); return; } int num = localPlayerAgent.PlayerSlotIndex % locations.Count; Vector3 val = locations[num].Position.ToVector3(); int index = locations[num].LookDir % lookDirs.Count; Vector3 val2 = lookDirs[index]; int num2 = 0; List<SentryGunInstance> list = new List<SentryGunInstance>(); Enumerator<IWarpableObject> enumerator = Dimension.WarpableObjects.GetEnumerator(); while (enumerator.MoveNext()) { IWarpableObject current = enumerator.Current; SentryGunInstance val3 = ((Il2CppObjectBase)current).TryCast<SentryGunInstance>(); if ((Object)(object)val3 != (Object)null) { if (((ItemEquippable)val3).LocallyPlaced) { list.Add(val3); } } else if (SNet.IsMaster && warpDefinition.OnWarp.WarpTeam_WarpAllWarpableBigPickupItems) { ItemInLevel val4 = ((Il2CppObjectBase)current).TryCast<ItemInLevel>(); if ((Object)(object)val4 != (Object)null && val4.CanWarp && val4.internalSync.GetCurrentState().placement.droppedOnFloor) { Vector3 warpToPosition = locations[num2].Position.ToVector3(); WarpItem(val4, warpDefinition.DimensionIndex, warpToPosition); EOSLogger.Warning(((Item)val4).PublicName ?? ""); num2 = (num2 + 1) % locations.Count; } } } list.ForEach(delegate(SentryGunInstance sentryGun) { sentryGun.m_sync.WantItemAction(((Item)sentryGun).Owner, (SyncedItemAction_New)0); }); if (!localPlayerAgent.TryWarpTo(warpDefinition.DimensionIndex, val, val2, true)) { EOSLogger.Error($"WarpTeam: TryWarpTo failed. Position: {val}, playerSlotIndex: {localPlayerAgent.PlayerSlotIndex}, warpLocationIndex: {num}"); } } internal void WarpTeam(WardenObjectiveEventData e) { WarpTeam(e.WorldEventObjectFilter); } private DimensionWarpManager() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001d: 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) EOSWardenEventManager.Current.AddEventDefinition(WardenEvents_Warp.WarpTeam.ToString(), 160u, (Action<WardenObjectiveEventData>)WarpTeam); EOSWardenEventManager.Current.AddEventDefinition(WardenEvents_Warp.WarpRange.ToString(), 161u, (Action<WardenObjectiveEventData>)WarpRange); EOSWardenEventManager.Current.AddEventDefinition(WardenEvents_Warp.WarpItemsInZone.ToString(), 162u, (Action<WardenObjectiveEventData>)WarpItemsInZone); } static DimensionWarpManager() { Current = new DimensionWarpManager(); } } [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInPlugin("Inas.EOSExt.DimensionWarp", "EOSExt.DimensionWarp", "1.0.1")] public class EntryPoint : BasePlugin { public const string AUTHOR = "Inas"; public const string PLUGIN_NAME = "EOSExt.DimensionWarp"; public const string VERSION = "1.0.1"; private Harmony m_Harmony; public override void Load() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown SetupManagers(); m_Harmony = new Harmony("EOSExt.DimensionWarp"); m_Harmony.PatchAll(); EOSLogger.Log("ExtraObjectiveSetup.DimensionWarp loaded."); } private void SetupManagers() { ((GenericExpeditionDefinitionManager<DimensionWarpDefinition>)DimensionWarpManager.Current).Init(); } } } namespace EOSExt.DimensionWarp.Definition { public class PositionAndLookDir { public Vec3 Position { get; set; } = new Vec3(); public int LookDir { get; set; } } public class OnWarp { public bool WarpTeam_WarpAllWarpableBigPickupItems { get; set; } = true; public bool WarpRange_WarpDeployedSentryOutsideRange { get; set; } = true; public bool WarpItemsInZone_OnlyWarpWarpable { get; set; } = true; } public class DimensionWarpDefinition { public string WorldEventObjectFilter { get; set; } = string.Empty; public eDimensionIndex DimensionIndex { get; set; } public OnWarp OnWarp { get; set; } = new OnWarp(); public List<PositionAndLookDir> Locations { get; set; } = new List<PositionAndLookDir>(); } }
plugins/net6/Inas07.EOSExt.EMP.dll
Decompiled a month agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using AK; using Agents; using BepInEx; using BepInEx.Unity.IL2CPP; using CellMenu; using EOSExt.EMP.Definition; using EOSExt.EMP.EMPComponent; using EOSExt.EMP.Impl; using EOSExt.EMP.Impl.Handlers; using EOSExt.EMP.Impl.PersistentEMP; using ExtraObjectiveSetup; using ExtraObjectiveSetup.BaseClasses; using ExtraObjectiveSetup.ExtendedWardenEvents; using ExtraObjectiveSetup.Utils; using FloLib.Networks.Replications; using GTFO.API; using GTFO.API.Utilities; using GameData; using Gear; using HarmonyLib; using Il2CppInterop.Runtime.Attributes; using Il2CppInterop.Runtime.Injection; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.InteropTypes.Arrays; using Il2CppSystem.Collections.Generic; using LevelGeneration; using Microsoft.CodeAnalysis; using Player; using SNetwork; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("Inas07.EOSExt.EMP")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("Inas07.EOSExt.EMP")] [assembly: AssemblyTitle("Inas07.EOSExt.EMP")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace EOSExt.EMP { public class EMPManager : GenericExpeditionDefinitionManager<pEMPDefinition> { private Dictionary<uint, pEMP> _pEMPs { get; } = new Dictionary<uint, pEMP>(); public IEnumerable<pEMP> pEMPs => _pEMPs.Values; protected override string DEFINITION_NAME => "PersistentEMP"; public static EMPManager Current { get; private set; } public PlayerAgent Player { get; private set; } internal List<EMPShock> ActiveEMPs { get; } = new List<EMPShock>(); internal void SetupHUDAndFlashlight() { if ((Object)(object)Player == (Object)null) { EOSLogger.Error($"{"SetupHUDAndFlashlight": LocalPlayerAgent is not set!}"); return; } if (EMPPlayerHudHandler.Instance == null) { ((Component)Player).gameObject.AddComponent<EMPController>().AssignHandler(new EMPPlayerHudHandler()); EOSLogger.Log("pEMP: PlayerHud setup completed"); } if (EMPPlayerFlashLightHandler.Instance == null) { ((Component)Player).gameObject.AddComponent<EMPController>().AssignHandler(new EMPPlayerFlashLightHandler()); EOSLogger.Log("pEMP: PlayerFlashlight setup completed"); } } internal void SetupAmmoWeaponHandlers(InventorySlot slot) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0004: Invalid comparison between Unknown and I4 //IL_0006: Unknown result type (might be due to invalid IL or missing references) if (slot - 1 <= 1) { SetupAmmoWeaponHandlerForSlot(slot); } static void SetupAmmoWeaponHandlerForSlot(InventorySlot slot) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) BackpackItem val = default(BackpackItem); if (PlayerBackpackManager.LocalBackpack.TryGetBackpackItem(slot, ref val)) { if (!((Object)(object)((Component)val.Instance).gameObject.GetComponent<EMPController>() != (Object)null)) { ((Component)val.Instance).gameObject.AddComponent<EMPController>().AssignHandler(new EMPGunSightHandler()); EOSLogger.Log($"pEMP: Backpack {slot} setup completed"); } } else { EOSLogger.Warning($"Couldn't get item for slot {slot}!"); } } } internal void SetupToolHandler() { BackpackItem val = default(BackpackItem); if (PlayerBackpackManager.LocalBackpack.TryGetBackpackItem((InventorySlot)3, ref val)) { if (!((Object)(object)((Component)val.Instance).gameObject.GetComponent<EMPController>() != (Object)null) && (Object)(object)((Component)val.Instance).GetComponent<EnemyScanner>() != (Object)null) { ((Component)val.Instance).gameObject.AddComponent<EMPController>().AssignHandler(new EMPBioTrackerHandler()); EOSLogger.Log($"pEMP: Backpack {3} setup completed"); } } else { EOSLogger.Warning($"Couldn't get item for slot {3}!"); } } public void TogglepEMPState(uint pEMPIndex, bool enabled) { if (!_pEMPs.ContainsKey(pEMPIndex)) { EOSLogger.Error($"TogglepEMPState: pEMPIndex {pEMPIndex} not defined"); } else { ActiveState newState = (enabled ? ActiveState.ENABLED : ActiveState.DISABLED); _pEMPs[pEMPIndex].ChangeToState(newState); } } public void TogglepEMPState(WardenObjectiveEventData e) { uint count = (uint)e.Count; bool enabled = e.Enabled; TogglepEMPState(count, enabled); } private void pEMPInit() { LevelAPI.OnBuildStart += delegate { pEMPClear(); InitializepEMPs(); }; LevelAPI.OnLevelCleanup += pEMPClear; } private void pEMPClear() { foreach (pEMP value in _pEMPs.Values) { value.Destroy(); } _pEMPs.Clear(); } private void InitializepEMPs() { if (!base.definitions.ContainsKey(base.CurrentMainLevelLayout)) { return; } GenericExpeditionDefinition<pEMPDefinition> val = base.definitions[base.CurrentMainLevelLayout]; if (val == null || val.Definitions.Count < 1) { return; } foreach (pEMPDefinition definition in val.Definitions) { pEMP pEMP = new pEMP(definition); _pEMPs[definition.pEMPIndex] = pEMP; uint num = EOSNetworking.AllotReplicatorID(); if (num == 0) { EOSLogger.Error("SetuppEMPReplicators: replicator ID depleted, cannot set up!"); continue; } pEMP.SetupReplicator(num); EOSLogger.Debug($"pEMP_{definition.pEMPIndex} initialized"); } } internal void SetLocalPlayerAgent(PlayerAgent localPlayerAgent) { Player = localPlayerAgent; PlayerpEMPComponent.Current = ((Component)localPlayerAgent).gameObject.AddComponent<PlayerpEMPComponent>(); PlayerpEMPComponent.Current.player = localPlayerAgent; EOSLogger.Debug("LocalPlayerAgent setup completed"); } internal void OnLocalPlayerAgentDestroy() { PlayerpEMPComponent.Current = null; EOSLogger.Debug("LocalPlayerAgent Destroyed"); } public void ActivateEMPShock(Vector3 position, float range, float duration) { //IL_001a: 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_0039: Unknown result type (might be due to invalid IL or missing references) if (!GameStateManager.IsInExpedition) { EOSLogger.Error("Tried to activate an EMP when not in level, this shouldn't happen!"); return; } float endTime = Clock.Time + duration; EMPShock eMPShock = new EMPShock(position, range, endTime); foreach (EMPHandler allHandler in EMPHandler.AllHandlers) { if (Vector3.Distance(position, allHandler.position) < range) { allHandler.AddAffectedBy(eMPShock); } } ActiveEMPs.Add(eMPShock); } internal void RemoveInactiveEMPs() { float time = Clock.Time; ActiveEMPs.RemoveAll((EMPShock emp) => emp.endTime < time); } public bool IsPlayerMapEMPD() { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0039: 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_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)Player == (Object)null || !GameStateManager.IsInExpedition) { return false; } Vector3 position = ((Agent)Player).Position; foreach (EMPShock activeEMP in ActiveEMPs) { if (Vector3.Distance(position, activeEMP.position) < activeEMP.range) { return true; } } foreach (pEMP pEMP in pEMPs) { if (pEMP.State == ActiveState.ENABLED && pEMP.ItemToDisable.Map && Vector3.Distance(position, pEMP.position) < pEMP.range) { EOSLogger.Warning("MapEMPD: by pEMP"); return true; } } return false; } protected override void FileChanged(LiveEditEventArgs e) { base.FileChanged(e); if (!base.definitions.TryGetValue(base.CurrentMainLevelLayout, out var value)) { return; } foreach (pEMPDefinition definition in value.Definitions) { EOSLogger.Warning(definition.ItemToDisable.ToString()); } } public override void Init() { EMPWardenEvents.Init(); Events.InventoryWielded = (Action<InventorySlot>)Delegate.Combine(Events.InventoryWielded, new Action<InventorySlot>(SetupAmmoWeaponHandlers)); pEMPInit(); } private EMPManager() { } static EMPManager() { Current = new EMPManager(); ClassInjector.RegisterTypeInIl2Cpp<EMPController>(); ClassInjector.RegisterTypeInIl2Cpp<PlayerpEMPComponent>(); } } internal static class EMPWardenEvents { public enum EMPEvents { Instant_Shock = 300, Toggle_PEMP_State } internal static void InstantShock(WardenObjectiveEventData e) { //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_001a: Unknown result type (might be due to invalid IL or missing references) Vector3 position = e.Position; float fogTransitionDuration = e.FogTransitionDuration; float duration = e.Duration; EMPManager.Current.ActivateEMPShock(position, fogTransitionDuration, duration); } internal static void TogglepEMPState(WardenObjectiveEventData e) { EMPManager.Current.TogglepEMPState(e); } internal static void Init() { EOSWardenEventManager.Current.AddEventDefinition(EMPEvents.Instant_Shock.ToString(), 300u, (Action<WardenObjectiveEventData>)InstantShock); EOSWardenEventManager.Current.AddEventDefinition(EMPEvents.Toggle_PEMP_State.ToString(), 301u, (Action<WardenObjectiveEventData>)TogglepEMPState); } } public static class Events { public static Action<GearPartFlashlight> FlashLightWielded; public static Action<InventorySlot> InventoryWielded; public static Action EnterGSInLevel; } [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInPlugin("Inas.EOSExt.EMP", "EOSExt.EMP", "1.1.6")] public class EntryPoint : BasePlugin { public const string AUTHOR = "Inas"; public const string PLUGIN_NAME = "EOSExt.EMP"; public const string VERSION = "1.1.6"; private Harmony m_Harmony; public override void Load() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown m_Harmony = new Harmony("EOSExt.EMP"); m_Harmony.PatchAll(); SetupManagers(); } private void SetupManagers() { ((GenericExpeditionDefinitionManager<pEMPDefinition>)EMPManager.Current).Init(); } } } namespace EOSExt.EMP.Patches { [HarmonyPatch] [HarmonyWrapSafe] internal class Inject_CM_PageMap { [HarmonyPostfix] [HarmonyPatch(typeof(CM_PageMap), "UpdatePlayerData")] private static void Pre_CM_PageMap_OnEnable() { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Invalid comparison between Unknown and I4 CM_PageMap pageMap = MainMenuGuiLayer.Current.PageMap; if (!((Object)(object)pageMap == (Object)null) && RundownManager.ActiveExpedition != null && (int)GameStateManager.CurrentStateName == 10 && EMPManager.Current.IsPlayerMapEMPD()) { pageMap.SetMapVisualsIsActive(false); pageMap.SetMapDisconnetedTextIsActive(true); } } } [HarmonyPatch(typeof(EnemyScanner))] internal static class Inject_EnemyScanner { [HarmonyPrefix] [HarmonyWrapSafe] [HarmonyPatch("UpdateDetectedEnemies")] internal static bool Pre_UpdateDetectedEnemies() { return !EMPBioTrackerHandler.Instance.IsEMPed(); } [HarmonyPrefix] [HarmonyWrapSafe] [HarmonyPatch("UpdateTagProgress")] internal static bool Pre_UpdateTagProgress(EnemyScanner __instance) { //IL_0066: 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) if (EMPBioTrackerHandler.Instance.IsEMPed()) { ((ItemEquippable)__instance).Sound.Post(EVENTS.BIOTRACKER_TOOL_LOOP_STOP, true); __instance.m_screen.SetStatusText("ERROR"); ((ProgressBarBase)__instance.m_progressBar).SetProgress(1f); __instance.m_screen.SetGuixColor(Color.yellow); return false; } __instance.m_screen.SetStatusText("Ready to tag"); __instance.m_screen.SetGuixColor(Color.red); return true; } } [HarmonyPatch] internal static class Inject_LG_Light { [HarmonyPrefix] [HarmonyWrapSafe] [HarmonyPatch(typeof(LG_Light), "Start")] internal static void Pre_Start(LG_Light __instance) { ((Component)__instance).gameObject.AddComponent<EMPController>().AssignHandler(new EMPLightHandler()); } [HarmonyPostfix] [HarmonyPatch(typeof(LG_BuildZoneLightsJob), "ApplyLightSettings")] private static void Post_ApplyColorScheme(Il2CppReferenceArray<LG_Light> lights, bool firstPass) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) foreach (LG_Light item in (Il2CppArrayBase<LG_Light>)(object)lights) { if ((firstPass && ((Component)item).gameObject.activeInHierarchy) || (!firstPass && item.AvailableInLevel)) { EMPLightHandler handler = EMPLightHandler.GetHandler(item); if (handler != null) { handler.SetOriginalColor(item.m_color); handler.SetOriginalIntensity(item.m_intensity); } } } } } [HarmonyPatch] internal static class Inject_PlayerAgent { [HarmonyPostfix] [HarmonyWrapSafe] [HarmonyPatch(typeof(PlayerAgent), "Setup")] internal static void Post_Setup(PlayerAgent __instance) { if (((Agent)__instance).IsLocallyOwned) { EMPManager.Current.SetLocalPlayerAgent(__instance); } } } [HarmonyPatch] internal static class Inject_PlayerHUD { [HarmonyPrefix] [HarmonyWrapSafe] [HarmonyPatch(typeof(PlayerGuiLayer), "UpdateGUIElementsVisibility")] private static bool Pre_UpdateGUIElementsVisibility() { if (EMPPlayerHudHandler.Instance != null && EMPPlayerHudHandler.Instance.IsEMPed()) { return false; } return true; } [HarmonyPrefix] [HarmonyWrapSafe] [HarmonyPatch(typeof(CellSettingsApply), "ApplyPlayerGhostOpacity")] private static void Pre_ApplyPlayerGhostOpacity(ref float value) { if (EMPPlayerHudHandler.Instance != null && EMPPlayerHudHandler.Instance.IsEMPed()) { value = 0f; } } [HarmonyPrefix] [HarmonyWrapSafe] [HarmonyPatch(typeof(CellSettingsApply), "ApplyHUDAlwaysShowTeammateInfo")] private static void Pre_ApplyHUDAlwaysShowTeammateInfo(ref bool value) { if (EMPPlayerHudHandler.Instance != null && EMPPlayerHudHandler.Instance.IsEMPed()) { value = false; } } } [HarmonyPatch] internal static class Inject_Events { [HarmonyPostfix] [HarmonyWrapSafe] [HarmonyPatch(typeof(PlayerInventoryBase), "OnItemEquippableFlashlightWielded")] internal static void Post_OnItemEquippableFlashlightWielded(GearPartFlashlight flashlight) { Events.FlashLightWielded?.Invoke(flashlight); } [HarmonyPostfix] [HarmonyWrapSafe] [HarmonyPatch(typeof(PlayerInventoryLocal), "DoWieldItem")] internal static void Post_DoWieldItem(PlayerInventoryLocal __instance) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) Events.InventoryWielded?.Invoke(((PlayerInventoryBase)__instance).WieldedSlot); } [HarmonyPostfix] [HarmonyPatch(typeof(GS_InLevel), "Enter")] private static void Post_SetupGear(GS_InLevel __instance) { Events.EnterGSInLevel?.Invoke(); } } [HarmonyPatch(typeof(PlayerSync))] internal static class Inject_PlayerSync { [HarmonyPrefix] [HarmonyWrapSafe] [HarmonyPatch("WantsToSetFlashlightEnabled")] internal static void Pre_WantsToSetFlashlightEnabled(PlayerSync __instance, ref bool enable) { if (EMPPlayerFlashLightHandler.Instance != null && EMPPlayerFlashLightHandler.Instance.IsEMPed()) { enable = false; } } } [HarmonyPatch(typeof(SentryGunInstance))] internal static class Inject_SentryGunInstance { [HarmonyPostfix] [HarmonyWrapSafe] [HarmonyPatch("Setup")] internal static void Post_Setup(SentryGunInstance __instance) { ((Component)__instance).gameObject.AddComponent<EMPController>().AssignHandler(new EMPSentryHandler()); } } } namespace EOSExt.EMP.EMPComponent { public class PlayerpEMPComponent : MonoBehaviour { private float nextUpdateTime = float.NaN; public const float UPDATE_INTERVAL = 0.2f; public static PlayerpEMPComponent Current { get; internal set; } public PlayerAgent player { get; internal set; } private void CheckSetup() { if (!((Object)(object)EMPManager.Current.Player == (Object)null)) { EMPManager.Current.SetupHUDAndFlashlight(); EMPManager.Current.SetupToolHandler(); } } private void Update() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 //IL_008b: Unknown result type (might be due to invalid IL or missing references) if ((int)GameStateManager.CurrentStateName != 10 || (!float.IsNaN(nextUpdateTime) && Clock.Time < nextUpdateTime)) { return; } nextUpdateTime = Clock.Time + 0.2f; CheckSetup(); EMPManager.Current.RemoveInactiveEMPs(); if ((Object)(object)player == (Object)null) { return; } foreach (pEMP pEMP in EMPManager.Current.pEMPs) { ItemToDisable itemToDisable = pEMP.ItemToDisable; if (pEMP.State == ActiveState.ENABLED && pEMP.InRange(((Agent)player).Position)) { if (itemToDisable.BioTracker) { EMPBioTrackerHandler.Instance?.AddAffectedBy(pEMP); } if (itemToDisable.PlayerFlashLight) { EMPPlayerFlashLightHandler.Instance?.AddAffectedBy(pEMP); } if (itemToDisable.PlayerHUD) { EMPPlayerHudHandler.Instance?.AddAffectedBy(pEMP); } if (itemToDisable.Sentry) { EMPSentryHandler.Instance?.AddAffectedBy(pEMP); } if (!itemToDisable.GunSight) { continue; } foreach (EMPGunSightHandler instance in EMPGunSightHandler.Instances) { instance.AddAffectedBy(pEMP); } continue; } EMPBioTrackerHandler.Instance?.RemoveAffectedBy(pEMP); EMPPlayerFlashLightHandler.Instance?.RemoveAffectedBy(pEMP); EMPPlayerHudHandler.Instance?.RemoveAffectedBy(pEMP); EMPSentryHandler.Instance?.RemoveAffectedBy(pEMP); foreach (EMPGunSightHandler instance2 in EMPGunSightHandler.Instances) { instance2.RemoveAffectedBy(pEMP); } } } private void OnDestroy() { EMPManager.Current.OnLocalPlayerAgentDestroy(); player = null; } static PlayerpEMPComponent() { } } } namespace EOSExt.EMP.Impl { public sealed class EMPController : MonoBehaviour { private bool _hasHandler; private bool _setup; private float next_remove_time = float.NaN; private const float UPDATE_INTERVAL = 1f; public EMPHandler Handler { get; private set; } public float endTime { get; private set; } public Vector3 Position => ((Component)this).transform.position; private void Update() { if (_hasHandler) { float time = Clock.Time; Handler.Tick(); if (float.IsNaN(next_remove_time) || next_remove_time < time) { Handler.RemoveEndedEMPs(); next_remove_time = time + 1f; } } } [HideFromIl2Cpp] public void AssignHandler(EMPHandler handler) { if (Handler != null) { EOSLogger.Warning("Tried to assign a handler to a controller that already had one!"); return; } Handler = handler; Handler.Setup(((Component)this).gameObject, this); _hasHandler = true; _setup = true; } [HideFromIl2Cpp] public void ForceState(EMPState state) { if (Handler != null) { Handler.ForceState(state); } } private void OnDestroy() { Handler.OnDespawn(); Handler = null; } } public abstract class EMPHandler { protected enum DeviceState { On, Off, Unknown } private static long next_handler_id = 0L; protected DeviceState _deviceState; protected float _stateTimer; private float _delayTimer; private bool _destroyed; protected static Dictionary<long, EMPHandler> Handlers { get; } = new Dictionary<long, EMPHandler>(); public static IEnumerable<EMPHandler> AllHandlers => Handlers.Values; protected long HandlerId { get; private set; } public EMPState State { get; protected set; } protected HashSet<EMPShock> AffectedBy { get; } = new HashSet<EMPShock>(); public GameObject go { get; protected set; } public Vector3 position { get { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) GameObject obj = go; if (obj == null) { return Vector3.zero; } return obj.transform.position; } } protected virtual float FlickerDuration => 0.2f; protected virtual float OnToOffMinDelay => 0f; protected virtual float OnToOffMaxDelay => 0.75f; protected virtual float OffToOnMinDelay => 0.85f; protected virtual float OffToOnMaxDelay => 1.5f; protected virtual bool IsDeviceOnPlayer => false; public virtual bool IsEMPed() { foreach (EMPShock item in AffectedBy) { if (Clock.Time < item.endTime) { return true; } } return false; } public virtual void Setup(GameObject gameObject, EMPController controller) { //IL_002c: 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) go = gameObject; foreach (EMPShock activeEMP in EMPManager.Current.ActiveEMPs) { if (Vector3.Distance(go.transform.position, activeEMP.position) < activeEMP.range) { AddAffectedBy(activeEMP); } } HandlerId = next_handler_id++; if (Handlers.ContainsKey(HandlerId)) { EOSLogger.Warning("What the hell we got a duplicate EMPHandler ID!?"); } Handlers[HandlerId] = this; } public virtual void OnDespawn() { _destroyed = true; AffectedBy.Clear(); Handlers.Remove(HandlerId); go = null; } public void AddAffectedBy(EMPShock empShock) { AffectedBy.Add(empShock); } public void RemoveAffectedBy(EMPShock empShock) { AffectedBy.Remove(empShock); } internal void RemoveEndedEMPs() { float time = Clock.Time; AffectedBy.RemoveWhere((EMPShock emp) => emp.endTime < time); } public void ForceState(EMPState state) { if (State != state) { State = state; _delayTimer = Clock.Time - 1f; _stateTimer = Clock.Time - 1f; switch (state) { case EMPState.Off: _deviceState = DeviceState.Off; DeviceOff(); break; default: _deviceState = DeviceState.Unknown; break; case EMPState.On: _deviceState = DeviceState.On; DeviceOn(); break; } } } public void Tick() { if (_destroyed) { return; } bool flag = IsEMPed(); if (flag && State == EMPState.On) { float randomDelay = Random.GetRandomDelay(OnToOffMinDelay, OnToOffMaxDelay); State = EMPState.FlickerOff; _delayTimer = Clock.Time + randomDelay; _stateTimer = Clock.Time + randomDelay + FlickerDuration; } if (!flag && State == EMPState.Off) { float randomDelay2 = Random.GetRandomDelay(OffToOnMinDelay, OffToOnMaxDelay); State = EMPState.FlickerOn; _delayTimer = Clock.Time + randomDelay2; _stateTimer = Clock.Time + randomDelay2 + FlickerDuration; } switch (State) { case EMPState.On: if (_deviceState != 0) { DeviceOn(); _deviceState = DeviceState.On; } break; case EMPState.FlickerOff: if (!(_delayTimer > Clock.Time)) { if (Clock.Time < _stateTimer) { FlickerDevice(); } else { State = EMPState.Off; } } break; case EMPState.Off: if (_deviceState != DeviceState.Off) { DeviceOff(); _deviceState = DeviceState.Off; } break; case EMPState.FlickerOn: if (!(_delayTimer > Clock.Time)) { if (Clock.Time < _stateTimer) { FlickerDevice(); } else { State = EMPState.On; } } break; } OnTick(flag); } protected virtual void OnTick(bool isEMPD) { } protected abstract void FlickerDevice(); protected abstract void DeviceOn(); protected abstract void DeviceOff(); } public class EMPShock { public static readonly ItemToDisable DISABLE_NOTHING = new ItemToDisable { BioTracker = false, PlayerFlashLight = false, PlayerHUD = false, Sentry = false, EnvLight = false, GunSight = false, Map = false }; public virtual ActiveState State { get { if (!(RemainingTime > 0f)) { return ActiveState.DISABLED; } return ActiveState.ENABLED; } } public Vector3 position { get; protected set; } public float range { get; protected set; } public float endTime { get; protected set; } public virtual float RemainingTime => endTime - Clock.Time; public virtual ItemToDisable ItemToDisable => new ItemToDisable(); public EMPShock(Vector3 position, float range, float endTime) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) this.position = position; this.range = range; this.endTime = endTime; } public bool InRange(Vector3 position) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) return Vector3.Distance(position, this.position) < range; } public override bool Equals(object obj) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) if (obj is EMPShock eMPShock && State == eMPShock.State && position == eMPShock.position && range == eMPShock.range && endTime == eMPShock.endTime && RemainingTime == eMPShock.RemainingTime) { return ItemToDisable.Equals(eMPShock.ItemToDisable); } return false; } public override int GetHashCode() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return HashCode.Combine<ActiveState, Vector3, float, float, float, ItemToDisable>(State, position, range, endTime, RemainingTime, ItemToDisable); } } public enum EMPState { On, FlickerOff, Off, FlickerOn } internal static class Random { internal static System.Random _rand { get; private set; } = new System.Random(); internal static float GetRandomDelay(float min, float max) { return min + GetRandom01() * (max - min); } internal static float GetRandom01() { return (float)_rand.NextDouble(); } internal static int GetRandomRange(int min, int maxPlusOne) { return _rand.Next(min, maxPlusOne); } internal static int Index(int length) { return _rand.Next(0, length); } internal static bool FlickerUtil(int oneInX = 2) { return Index(oneInX) == 0; } } } namespace EOSExt.EMP.Impl.PersistentEMP { public enum ActiveState { DISABLED, ENABLED } public class pEMP : EMPShock { public pEMPDefinition def { get; private set; } public StateReplicator<pEMPState> StateReplicator { get; private set; } public override ActiveState State { get { if (StateReplicator == null) { return ActiveState.DISABLED; } return StateReplicator.State.status; } } public override float RemainingTime => base.endTime; public override ItemToDisable ItemToDisable => def?.ItemToDisable ?? EMPShock.DISABLE_NOTHING; private void OnStateChanged(pEMPState oldState, pEMPState newState, bool isRecall) { if (isRecall) { ChangeToStateUnsynced(newState.status); } } private void ChangeToStateUnsynced(ActiveState newState) { //IL_00c0: Unknown result type (might be due to invalid IL or missing references) EOSLogger.Debug($"pEMP_{def.pEMPIndex} Change state: {State} -> {newState}"); switch (newState) { case ActiveState.DISABLED: base.endTime = float.NegativeInfinity; break; case ActiveState.ENABLED: base.endTime = float.PositiveInfinity; break; default: throw new NotImplementedException(); } if (!ItemToDisable.EnvLight) { return; } foreach (EMPLightHandler instance in EMPLightHandler.Instances) { switch (newState) { case ActiveState.DISABLED: instance.RemoveAffectedBy(this); break; case ActiveState.ENABLED: if (InRange(instance.position)) { instance.AddAffectedBy(this); } else { instance.RemoveAffectedBy(this); } break; default: throw new NotImplementedException(); } } } public void ChangeToState(ActiveState newState) { ChangeToStateUnsynced(newState); if (SNet.IsMaster) { StateReplicator?.SetState(new pEMPState { status = newState }); } } internal void SetupReplicator(uint replicatorID) { StateReplicator = StateReplicator<pEMPState>.Create(replicatorID, new pEMPState { status = ActiveState.DISABLED }, (LifeTimeType)1, (IStateReplicatorHolder<pEMPState>)null); StateReplicator.OnStateChanged += OnStateChanged; } public pEMP(pEMPDefinition def) : base(def.Position.ToVector3(), def.Range, float.NegativeInfinity) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) this.def = new pEMPDefinition(def); } internal void Destroy() { base.endTime = float.NegativeInfinity; StateReplicator = null; def = null; } public override bool Equals(object obj) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) if (obj is pEMP pEMP2 && base.Equals(obj) && base.position == pEMP2.position && base.range == pEMP2.range) { return def.Equals(pEMP2.def); } return false; } public override int GetHashCode() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) return HashCode.Combine<int, Vector3, float, pEMPDefinition>(base.GetHashCode(), base.position, base.range, def); } } public struct pEMPState { public ActiveState status; public pEMPState() { status = ActiveState.DISABLED; } public pEMPState(ActiveState status) { this.status = status; } public pEMPState(pEMPState o) { status = o.status; } } } namespace EOSExt.EMP.Impl.Handlers { public class EMPBioTrackerHandler : EMPHandler { private EnemyScanner _scanner; public static EMPBioTrackerHandler Instance { get; private set; } static EMPBioTrackerHandler() { } public override void Setup(GameObject gameObject, EMPController controller) { if (Instance != null) { EOSLogger.Warning("EMP: re-setup EMPBioTrackerHandler"); Instance.OnDespawn(); } base.Setup(gameObject, controller); _scanner = gameObject.GetComponent<EnemyScanner>(); if ((Object)(object)_scanner == (Object)null) { EOSLogger.Error("Couldn't get bio-tracker component!"); } Instance = this; } public override void OnDespawn() { base.OnDespawn(); Instance = null; } protected override void DeviceOff() { ((ItemEquippable)_scanner).Sound.Post(EVENTS.BIOTRACKER_TOOL_LOOP_STOP, true); _scanner.m_graphics.m_display.enabled = false; } protected override void DeviceOn() { _scanner.m_graphics.m_display.enabled = true; } protected override void FlickerDevice() { ((Behaviour)_scanner).enabled = Random.FlickerUtil(); } } public class EMPGunSightHandler : EMPHandler { private static List<EMPGunSightHandler> handlers; public GameObject[] _sightPictures; public static IEnumerable<EMPGunSightHandler> Instances => handlers; static EMPGunSightHandler() { handlers = new List<EMPGunSightHandler>(); LevelAPI.OnLevelCleanup += Clear; LevelAPI.OnBuildStart += Clear; } private void SetupGunSights() { Il2CppArrayBase<Renderer> componentsInChildren = base.go.GetComponentsInChildren<Renderer>(true); if (componentsInChildren != null) { _sightPictures = (from x in (IEnumerable<Renderer>)componentsInChildren where (Object)(object)x.sharedMaterial != (Object)null && (Object)(object)x.sharedMaterial.shader != (Object)null where ((Object)x.sharedMaterial.shader).name.Contains("HolographicSight") select ((Component)x).gameObject).ToArray(); } if (_sightPictures == null || _sightPictures.Length < 1) { EOSLogger.Error("Unable to find sight on " + ((Object)base.go).name + "!"); } } public override void Setup(GameObject gameObject, EMPController controller) { base.Setup(gameObject, controller); SetupGunSights(); handlers.Add(this); } protected override void DeviceOff() { ForEachSights(delegate(GameObject x) { x.SetActive(false); }); } protected override void DeviceOn() { ForEachSights(delegate(GameObject x) { x.SetActive(true); }); } protected override void FlickerDevice() { ForEachSights(delegate(GameObject x) { x.SetActive(Random.FlickerUtil()); }); } private void ForEachSights(Action<GameObject> action) { GameObject[] sightPictures = _sightPictures; foreach (GameObject val in sightPictures) { if ((Object)(object)val != (Object)null) { action?.Invoke(val); } } } private static void Clear() { handlers.Clear(); } } public class EMPLightHandler : EMPHandler { private static Dictionary<IntPtr, EMPLightHandler> handlers; private LG_Light _light; private float _originalIntensity; private Color _originalColor; public static IEnumerable<EMPLightHandler> Instances => handlers.Values; internal static EMPLightHandler GetHandler(LG_Light light) { if (!handlers.TryGetValue(((Il2CppObjectBase)light).Pointer, out var value)) { return null; } return value; } private static void Clear() { handlers.Clear(); } static EMPLightHandler() { handlers = new Dictionary<IntPtr, EMPLightHandler>(); LevelAPI.OnBuildStart += Clear; LevelAPI.OnLevelCleanup += Clear; } public override void Setup(GameObject gameObject, EMPController controller) { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) base.Setup(gameObject, controller); _light = gameObject.GetComponent<LG_Light>(); if ((Object)(object)_light == (Object)null) { EOSLogger.Warning("No Light!"); } else { _originalIntensity = _light.GetIntensity(); _originalColor = new Color(_light.m_color.r, _light.m_color.g, _light.m_color.b, _light.m_color.a); base.State = EMPState.On; } handlers[((Il2CppObjectBase)_light).Pointer] = this; } public void SetOriginalColor(Color color) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) _originalColor = new Color(color.r, color.g, color.b, color.a); } public void SetOriginalIntensity(float intensity) { _originalIntensity = intensity; } protected override void OnTick(bool isEMPD) { base.OnTick(isEMPD); if (base.State == EMPState.Off) { DeviceOff(); } else if (base.State == EMPState.On) { DeviceOn(); } } protected override void FlickerDevice() { if (!((Object)(object)_light == (Object)null)) { _light.ChangeIntensity(Random.GetRandom01() * _originalIntensity); } } protected override void DeviceOn() { //IL_0027: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)_light == (Object)null)) { _light.ChangeIntensity(_originalIntensity); _light.ChangeColor(_originalColor); } } protected override void DeviceOff() { //IL_0025: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)_light == (Object)null)) { _light.ChangeIntensity(0f); _light.ChangeColor(Color.black); } } } public class EMPPlayerFlashLightHandler : EMPHandler { private PlayerInventoryBase _inventory; private float _originalIntensity; private bool _originalFlashlightState; public static EMPPlayerFlashLightHandler Instance { get; private set; } protected override bool IsDeviceOnPlayer => true; private bool FlashlightEnabled => _inventory.FlashlightEnabled; static EMPPlayerFlashLightHandler() { } public override void Setup(GameObject gameObject, EMPController controller) { if (Instance != null) { EOSLogger.Warning("EMP: re-setup EMPPlayerFlashLightHandler"); Instance.OnDespawn(); } base.Setup(gameObject, controller); _inventory = gameObject.GetComponent<PlayerAgent>().Inventory; if ((Object)(object)_inventory == (Object)null) { EOSLogger.Warning("Player inventory was null!"); } else { base.State = EMPState.On; Events.FlashLightWielded = (Action<GearPartFlashlight>)Delegate.Combine(Events.FlashLightWielded, new Action<GearPartFlashlight>(InventoryEvents_ItemWielded)); } Instance = this; } public override void OnDespawn() { base.OnDespawn(); Events.FlashLightWielded = (Action<GearPartFlashlight>)Delegate.Remove(Events.FlashLightWielded, new Action<GearPartFlashlight>(Instance.InventoryEvents_ItemWielded)); Instance = null; } private void InventoryEvents_ItemWielded(GearPartFlashlight flashlight) { _originalIntensity = GameDataBlockBase<FlashlightSettingsDataBlock>.GetBlock(flashlight.m_settingsID).intensity; } protected override void DeviceOff() { _originalFlashlightState = FlashlightEnabled; if (_originalFlashlightState) { _inventory.Owner.Sync.WantsToSetFlashlightEnabled(false, false); } } protected override void DeviceOn() { if (_originalFlashlightState != FlashlightEnabled) { _inventory.Owner.Sync.WantsToSetFlashlightEnabled(_originalFlashlightState, false); } _inventory.m_flashlight.intensity = _originalIntensity; } protected override void FlickerDevice() { if (FlashlightEnabled) { _inventory.m_flashlight.intensity = Random.GetRandom01() * _originalIntensity; } } } public class EMPPlayerHudHandler : EMPHandler { private readonly List<RectTransformComp> _targets = new List<RectTransformComp>(); public static EMPPlayerHudHandler Instance { get; private set; } static EMPPlayerHudHandler() { } public override void Setup(GameObject gameObject, EMPController controller) { if (Instance != null) { EOSLogger.Warning("EMP: re-setup EMPPlayerHudHandler"); Instance.OnDespawn(); } _targets.Clear(); base.Setup(gameObject, controller); _targets.Add((RectTransformComp)(object)GuiManager.PlayerLayer.m_compass); _targets.Add((RectTransformComp)(object)GuiManager.PlayerLayer.m_wardenObjective); _targets.Add((RectTransformComp)(object)GuiManager.PlayerLayer.Inventory); _targets.Add((RectTransformComp)(object)GuiManager.PlayerLayer.m_playerStatus); Instance = this; } public override void OnDespawn() { base.OnDespawn(); _targets.Clear(); Instance = null; } private void ForAllComponents(bool enabled) { foreach (RectTransformComp target in _targets) { ((Component)target).gameObject.SetActive(enabled); } } private void ForPlayerNavMarker(bool enabled) { Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator(); while (enumerator.MoveNext()) { PlayerAgent current = enumerator.Current; if (!((Agent)current).IsLocallyOwned) { current.NavMarker.SetMarkerVisible(enabled); } } } private void ForPlayerGhostOpacity(bool enabled) { CellSettingsApply.ApplyPlayerGhostOpacity(enabled ? CellSettingsManager.SettingsData.HUD.Player_GhostOpacity.Value : 0f); } protected override void OnTick(bool isEMPD) { base.OnTick(isEMPD); if (base.State == EMPState.Off) { DeviceOff(); } else if (base.State == EMPState.On) { DeviceOn(); } } protected override void DeviceOff() { ForAllComponents(enabled: false); ForPlayerNavMarker(enabled: false); ForPlayerGhostOpacity(enabled: false); } protected override void DeviceOn() { ForAllComponents(enabled: true); ForPlayerNavMarker(enabled: true); ForPlayerGhostOpacity(enabled: true); } protected override void FlickerDevice() { bool enabled = Random.FlickerUtil(); ForAllComponents(enabled); ForPlayerNavMarker(enabled); ForPlayerGhostOpacity(enabled); } } public class EMPSentryHandler : EMPHandler { private static Color _offColor; private SentryGunInstance _sentry; private SentryGunInstance_ScannerVisuals_Plane _visuals; public static EMPSentryHandler Instance { get; private set; } static EMPSentryHandler() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) _offColor = new Color { r = 0f, g = 0f, b = 0f, a = 0f }; } public override void Setup(GameObject gameObject, EMPController controller) { if (Instance != null) { EOSLogger.Warning("EMP: re-setup EMPSentryHandler"); Instance.OnDespawn(); } base.Setup(gameObject, controller); _sentry = gameObject.GetComponent<SentryGunInstance>(); _visuals = gameObject.GetComponent<SentryGunInstance_ScannerVisuals_Plane>(); if ((Object)(object)_sentry == (Object)null || (Object)(object)_visuals == (Object)null) { EOSLogger.Error($"Missing components on Sentry! Has Sentry?: {(Object)(object)_sentry == (Object)null}, Has Visuals?: {(Object)(object)_visuals == (Object)null}"); } Instance = this; } public override void OnDespawn() { base.OnDespawn(); Instance = null; } protected override void DeviceOff() { //IL_000b: 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) _visuals.m_scannerPlane.SetColor(_offColor); _visuals.UpdateLightProps(_offColor, false); _sentry.m_isSetup = false; _sentry.m_isScanning = false; _sentry.m_isFiring = false; ((ItemEquippable)_sentry).Sound.Post(EVENTS.SENTRYGUN_STOP_ALL_LOOPS, true); } protected override void DeviceOn() { _sentry.m_isSetup = true; _sentry.m_visuals.SetVisualStatus((eSentryGunStatus)0, true); _sentry.m_isScanning = false; _sentry.m_startScanTimer = Clock.Time + _sentry.m_initialScanDelay; ((ItemEquippable)_sentry).Sound.Post(EVENTS.SENTRYGUN_LOW_AMMO_WARNING, true); } protected override void FlickerDevice() { int randomRange = Random.GetRandomRange(0, 3); _sentry.StopFiring(); switch (randomRange) { case 0: _visuals.SetVisualStatus((eSentryGunStatus)4, true); break; case 1: _visuals.SetVisualStatus((eSentryGunStatus)1, true); break; case 2: _visuals.SetVisualStatus((eSentryGunStatus)2, true); break; } } } } namespace EOSExt.EMP.Definition { public class ItemToDisable { public bool BioTracker { get; set; } = true; public bool PlayerHUD { get; set; } = true; public bool PlayerFlashLight { get; set; } = true; public bool EnvLight { get; set; } = true; public bool GunSight { get; set; } = true; public bool Sentry { get; set; } = true; public bool Map { get; set; } = true; public override bool Equals(object obj) { if (obj is ItemToDisable itemToDisable && BioTracker == itemToDisable.BioTracker && PlayerHUD == itemToDisable.PlayerHUD && PlayerFlashLight == itemToDisable.PlayerFlashLight && EnvLight == itemToDisable.EnvLight && GunSight == itemToDisable.GunSight && Sentry == itemToDisable.Sentry) { return Map == itemToDisable.Map; } return false; } public override int GetHashCode() { return HashCode.Combine(BioTracker, PlayerHUD, PlayerFlashLight, EnvLight, GunSight, Sentry, Map); } public override string ToString() { return $"ItemToDisable:\nBioTracker: {BioTracker}, PlayerHUD: {PlayerHUD}, PlayerFlashLight: {PlayerFlashLight},\nEnvLight: {EnvLight}, GunSight: {GunSight}, Sentry: {Sentry}, Map: {Map}"; } } public class pEMPDefinition { public uint pEMPIndex { get; set; } public Vec3 Position { get; set; } = new Vec3(); public float Range { get; set; } public ItemToDisable ItemToDisable { get; set; } = new ItemToDisable(); public pEMPDefinition() { }//IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown public pEMPDefinition(pEMPDefinition other) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Expected O, but got Unknown pEMPIndex = other.pEMPIndex; Position = new Vec3 { x = other.Position.x, y = other.Position.y, z = other.Position.z }; Range = other.Range; ItemToDisable = new ItemToDisable { BioTracker = other.ItemToDisable.BioTracker, PlayerHUD = other.ItemToDisable.PlayerHUD, PlayerFlashLight = other.ItemToDisable.PlayerFlashLight, EnvLight = other.ItemToDisable.EnvLight, GunSight = other.ItemToDisable.GunSight, Sentry = other.ItemToDisable.Sentry, Map = other.ItemToDisable.Map }; } public override bool Equals(object obj) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) if (obj is pEMPDefinition pEMPDefinition2 && pEMPIndex == pEMPDefinition2.pEMPIndex && Position.ToVector3() == pEMPDefinition2.Position.ToVector3() && Range == pEMPDefinition2.Range) { return ItemToDisable.Equals(pEMPDefinition2.ItemToDisable); } return false; } public override int GetHashCode() { return HashCode.Combine<uint, Vec3, float, ItemToDisable>(pEMPIndex, Position, Range, ItemToDisable); } } }
plugins/net6/Inas07.EOSExt.Reactor.dll
Decompiled a month agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text.Json.Serialization; using AIGraph; using AK; using BepInEx; using BepInEx.Unity.IL2CPP; using ChainedPuzzles; using EOSExt.Reactor.Component; using EOSExt.Reactor.Definition; using EOSExt.Reactor.Managers; using ExtraObjectiveSetup.BaseClasses; using ExtraObjectiveSetup.BaseClasses.CustomTerminalDefinition; using ExtraObjectiveSetup.ExtendedWardenEvents; using ExtraObjectiveSetup.Instances; using ExtraObjectiveSetup.Utils; using GTFO.API; using GTFO.API.Extensions; using GameData; using HarmonyLib; using Il2CppInterop.Runtime.Injection; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.InteropTypes.Arrays; using Il2CppSystem; using Il2CppSystem.Collections.Generic; using LevelGeneration; using Localization; using Microsoft.CodeAnalysis; using SNetwork; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("Inas07.EOSExt.Reactor")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("Inas07.EOSExt.Reactor")] [assembly: AssemblyTitle("Inas07.EOSExt.Reactor")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace EOSExt.Reactor { [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInPlugin("Inas.EOSExt.Reactor", "EOSExt.Reactor", "1.0.4")] public class EntryPoint : BasePlugin { public const string AUTHOR = "Inas"; public const string PLUGIN_NAME = "EOSExt.Reactor"; public const string VERSION = "1.0.4"; private Harmony m_Harmony; public override void Load() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown m_Harmony = new Harmony("EOSExt.Reactor"); m_Harmony.PatchAll(); SetupManagers(); SetupExtraWardenEventDefinitions(); ClassInjector.RegisterTypeInIl2Cpp<OverrideReactorComp>(); EOSLogger.Log("ExtraObjectiveSetup.Reactor loaded."); } private void SetupManagers() { ((InstanceDefinitionManager<ReactorShutdownDefinition>)ReactorShutdownObjectiveManager.Current).Init(); ((InstanceDefinitionManager<ReactorStartupOverride>)ReactorStartupOverrideManager.Current).Init(); } private void SetupExtraWardenEventDefinitions() { EOSWardenEventManager.Current.AddEventDefinition(WardenEvents.EventType.ReactorStartup.ToString(), 150u, (Action<WardenObjectiveEventData>)WardenEvents.ReactorStartup); EOSWardenEventManager.Current.AddEventDefinition(WardenEvents.EventType.CompleteCurrentVerify.ToString(), 151u, (Action<WardenObjectiveEventData>)WardenEvents.CompleteCurrentVerify); } } } namespace EOSExt.Reactor.Patches { [HarmonyPatch] internal class CommandInterpreter_ReactorVerify { [HarmonyPrefix] [HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "ReactorVerify")] private static bool Pre_LG_ComputerTerminalCommandInterpreter_ReactorVerify(LG_ComputerTerminalCommandInterpreter __instance, string param1) { LG_WardenObjective_Reactor connectedReactor = __instance.m_terminal.ConnectedReactor; if ((Object)(object)connectedReactor == (Object)null) { EOSLogger.Error("ReactorVerify: connected reactor is null - bug detected"); return true; } if (connectedReactor.m_isWardenObjective) { return true; } if (connectedReactor.ReadyForVerification && param1 == connectedReactor.CurrentStateOverrideCode) { __instance.m_terminal.ChangeState((TERM_State)7); } else { __instance.AddOutput("", true); __instance.AddOutput((TerminalLineType)3, Text.Get(2195342028u), 4f, (TerminalSoundType)0, (TerminalSoundType)0); __instance.AddOutput("", true); } return false; } } [HarmonyPatch] internal class OnTerminalStartupSequenceVerify { [HarmonyPostfix] [HarmonyPatch(typeof(LG_WardenObjective_Reactor), "OnTerminalStartupSequenceVerify")] private static void Post_ExecuteEventsOnEndOnClientSide(LG_WardenObjective_Reactor __instance) { if (!SNet.IsMaster) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(__instance.m_currentWaveData.Events, (eWardenObjectiveEventTrigger)3, false, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null); } } } [HarmonyPatch] internal class Reactor_OnBuildDone { [HarmonyPostfix] [HarmonyPatch(typeof(LG_WardenObjective_Reactor), "OnBuildDone")] private static void Post_LG_WardenObjective_Reactor_OnBuildDone(LG_WardenObjective_Reactor __instance) { //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Invalid comparison between Unknown and I4 uint num = ((InstanceManager<LG_WardenObjective_Reactor>)ReactorInstanceManager.Current).Register(__instance); if (__instance.m_isWardenObjective) { ReactorStartupOverride definition = ((InstanceDefinitionManager<ReactorStartupOverride>)ReactorStartupOverrideManager.Current).GetDefinition(__instance.SpawnNode.m_dimension.DimensionIndex, __instance.SpawnNode.LayerType, __instance.SpawnNode.m_zone.LocalIndex, num); if (definition == null) { return; } WardenObjectiveDataBlock val = default(WardenObjectiveDataBlock); if (!WardenObjectiveManager.TryGetWardenObjectiveDataForLayer(__instance.SpawnNode.LayerType, __instance.WardenObjectiveChainIndex, ref val) || val == null) { EOSLogger.Error("Failed to get WardenObjectiveData for this reactor"); return; } if ((int)val.Type != 1) { EOSLogger.Error($"Reactor Instance {(((InstanceManager<LG_WardenObjective_Reactor>)ReactorInstanceManager.Current).GetGlobalZoneIndex(__instance), num)} is not setup as vanilla ReactorStartup, cannot override"); return; } definition.ObjectiveDB = val; ReactorStartupOverrideManager.Current.Build(__instance, definition); } else { ReactorShutdownDefinition definition2 = ((InstanceDefinitionManager<ReactorShutdownDefinition>)ReactorShutdownObjectiveManager.Current).GetDefinition(__instance.SpawnNode.m_dimension.DimensionIndex, __instance.SpawnNode.LayerType, __instance.SpawnNode.m_zone.LocalIndex, num); if (definition2 != null) { ReactorShutdownObjectiveManager.Current.Build(__instance, definition2); EOSLogger.Debug($"Reactor Shutdown Instance {(((InstanceManager<LG_WardenObjective_Reactor>)ReactorInstanceManager.Current).GetGlobalZoneIndex(__instance), num)}: custom setup complete"); } } if ((Object)(object)__instance.m_terminal != (Object)null) { TerminalInstanceManager.Current.RegisterReactorTerminal(__instance); } } } [HarmonyPatch] internal class Reactor_OnStateChange { private static void Startup_OnStateChange(LG_WardenObjective_Reactor reactor, pReactorState oldState, pReactorState newState, bool isDropinState) { } private static void Shutdown_OnStateChange(LG_WardenObjective_Reactor reactor, pReactorState oldState, pReactorState newState, bool isDropinState, ReactorShutdownDefinition def) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected I4, but got Unknown eReactorStatus status = newState.status; switch (status - 6) { case 0: GuiManager.PlayerLayer.m_wardenIntel.ShowSubObjectiveMessage("", Text.Get(1080u), false, 200f, 8f, (Action)null); reactor.m_progressUpdateEnabled = true; reactor.m_currentDuration = 15f; reactor.m_lightCollection.SetMode(false); reactor.m_sound.Stop(); def.EventsOnActive.ForEach(delegate(WardenObjectiveEventData e) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f); }); break; case 1: GuiManager.PlayerLayer.m_wardenIntel.ShowSubObjectiveMessage("", Text.Get(1081u), false, 200f, 8f, (Action)null); reactor.m_progressUpdateEnabled = false; reactor.ReadyForVerification = true; break; case 2: reactor.m_progressUpdateEnabled = false; if ((Object)(object)def.ChainedPuzzleOnVerificationInstance != (Object)null) { GuiManager.PlayerLayer.m_wardenIntel.ShowSubObjectiveMessage("", Text.Get(1082u), false, 200f, 8f, (Action)null); def.ChainedPuzzleOnVerificationInstance.AttemptInteract((eChainedPuzzleInteraction)0); } def.EventsOnShutdownPuzzleStarts.ForEach(delegate(WardenObjectiveEventData e) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f); }); break; case 3: reactor.m_progressUpdateEnabled = false; reactor.m_objectiveCompleteTimer = Clock.Time + 5f; def.EventsOnComplete.ForEach(delegate(WardenObjectiveEventData e) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f); }); break; } } [HarmonyPrefix] [HarmonyPatch(typeof(LG_WardenObjective_Reactor), "OnStateChange")] private static bool Pre_LG_WardenObjective_Reactor_OnStateChange(LG_WardenObjective_Reactor __instance, pReactorState oldState, pReactorState newState, bool isDropinState) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0045: 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_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) if (__instance.m_isWardenObjective) { return true; } if (oldState.stateCount != newState.stateCount) { __instance.OnStateCountUpdate(newState.stateCount); } if (oldState.stateProgress != newState.stateProgress) { __instance.OnStateProgressUpdate(newState.stateProgress); } if (oldState.status == newState.status) { return false; } __instance.ReadyForVerification = false; uint zoneInstanceIndex = ((InstanceManager<LG_WardenObjective_Reactor>)ReactorInstanceManager.Current).GetZoneInstanceIndex(__instance); (eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = ((InstanceManager<LG_WardenObjective_Reactor>)ReactorInstanceManager.Current).GetGlobalZoneIndex(__instance); if (ReactorInstanceManager.Current.IsStartupReactor(__instance)) { return true; } if (ReactorInstanceManager.Current.IsShutdownReactor(__instance)) { ReactorShutdownDefinition definition = ((InstanceDefinitionManager<ReactorShutdownDefinition>)ReactorShutdownObjectiveManager.Current).GetDefinition(globalZoneIndex, zoneInstanceIndex); if (definition == null) { EOSLogger.Error("Reactor_OnStateChange: found built custom reactor but its definition is missing, what happened?"); return false; } Shutdown_OnStateChange(__instance, oldState, newState, isDropinState, definition); __instance.m_currentState = newState; return false; } EOSLogger.Error("Reactor_OnStateChange: found built custom reactor but it's neither startup nor shutdown reactor, what happened?"); return false; } } [HarmonyPatch] internal class Reactor_OnStateCountUpdate { [HarmonyPrefix] [HarmonyPatch(typeof(LG_WardenObjective_Reactor), "OnStateCountUpdate")] private static bool Pre_LG_WardenObjective_Reactor_OnStateCountUpdate(LG_WardenObjective_Reactor __instance, int count) { //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Unknown result type (might be due to invalid IL or missing references) //IL_014c: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Expected O, but got Unknown //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_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_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Expected O, but got Unknown if (__instance.m_isWardenObjective) { return true; } uint zoneInstanceIndex = ((InstanceManager<LG_WardenObjective_Reactor>)ReactorInstanceManager.Current).GetZoneInstanceIndex(__instance); (eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = ((InstanceManager<LG_WardenObjective_Reactor>)ReactorInstanceManager.Current).GetGlobalZoneIndex(__instance); if (ReactorInstanceManager.Current.IsStartupReactor(__instance)) { return true; } if (ReactorInstanceManager.Current.IsShutdownReactor(__instance)) { ReactorShutdownDefinition definition = ((InstanceDefinitionManager<ReactorShutdownDefinition>)ReactorShutdownObjectiveManager.Current).GetDefinition(globalZoneIndex, zoneInstanceIndex); if (definition == null) { EOSLogger.Error("Reactor_OnStateCountUpdate: found built custom reactor but its definition is missing, what happened?"); return true; } __instance.m_currentWaveCount = count; if (definition.PutVerificationCodeOnTerminal) { LG_ComputerTerminal instance = ((InstanceManager<LG_ComputerTerminal>)(object)TerminalInstanceManager.Current).GetInstance(((GlobalZoneIndex)definition.VerificationCodeTerminal).GlobalZoneIndexTuple(), definition.VerificationCodeTerminal.InstanceIndex); __instance.m_currentWaveData = new ReactorWaveData { HasVerificationTerminal = (definition.PutVerificationCodeOnTerminal && (Object)(object)instance != (Object)null), VerificationTerminalSerial = (((Object)(object)instance != (Object)null) ? instance.ItemKey : string.Empty), Warmup = 1f, WarmupFail = 1f, Wave = 1f, Verify = 1f, VerifyFail = 1f }; } else { __instance.m_currentWaveData = new ReactorWaveData { HasVerificationTerminal = false, VerificationTerminalSerial = string.Empty, Warmup = 1f, WarmupFail = 1f, Wave = 1f, Verify = 1f, VerifyFail = 1f }; } if (__instance.m_overrideCodes != null && !string.IsNullOrEmpty(((Il2CppArrayBase<string>)(object)__instance.m_overrideCodes)[0])) { __instance.CurrentStateOverrideCode = ((Il2CppArrayBase<string>)(object)__instance.m_overrideCodes)[0]; } else { EOSLogger.Error("Reactor_OnStateCountUpdate: code is not built?"); } return false; } EOSLogger.Error("Reactor_OnStateCountUpdate: found built custom reactor but it's neither a startup nor shutdown reactor, what happen?"); return true; } } [HarmonyPatch] internal class Reactor_Update { private static bool _checked; private static TextDataBlock shutdownVerification_GUIText; [HarmonyPrefix] [HarmonyPatch(typeof(LG_WardenObjective_Reactor), "Update")] private static bool Pre_LG_WardenObjective_Reactor_Update(LG_WardenObjective_Reactor __instance) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 if (__instance.m_isWardenObjective || (int)__instance.m_currentState.status != 7) { return true; } if (!_checked) { shutdownVerification_GUIText = GameDataBlockBase<TextDataBlock>.GetBlock("InGame.ExtraObjectiveSetup_ReactorShutdown.SecurityVerificationRequired"); _checked = true; } string empty = string.Empty; empty = ((!__instance.m_currentWaveData.HasVerificationTerminal) ? string.Format(Text.Get(1107u), "<color=orange>" + __instance.CurrentStateOverrideCode + "</color>") : string.Format((shutdownVerification_GUIText != null) ? Text.Get(((GameDataBlockBase<TextDataBlock>)(object)shutdownVerification_GUIText).persistentID) : "SECURITY VERIFICATION REQUIRED. USE COMMAND <color=orange>REACTOR_VERIFY</color> AND FIND CODE ON <color=orange>{0}</color>.", __instance.m_currentWaveData.VerificationTerminalSerial)); __instance.SetGUIMessage(true, empty, (ePUIMessageStyle)3, false, "", ""); return false; } } [HarmonyPatch] internal class Reactor_CommandInterpreter { private static bool Handle_ReactorShutdown(LG_ComputerTerminalCommandInterpreter __instance) { LG_WardenObjective_Reactor connectedReactor = __instance.m_terminal.ConnectedReactor; uint zoneInstanceIndex = ((InstanceManager<LG_WardenObjective_Reactor>)ReactorInstanceManager.Current).GetZoneInstanceIndex(connectedReactor); (eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = ((InstanceManager<LG_WardenObjective_Reactor>)ReactorInstanceManager.Current).GetGlobalZoneIndex(connectedReactor); ReactorShutdownDefinition definition = ((InstanceDefinitionManager<ReactorShutdownDefinition>)ReactorShutdownObjectiveManager.Current).GetDefinition(globalZoneIndex, zoneInstanceIndex); if (definition == null) { EOSLogger.Error("ReactorVerify: found built custom reactor shutdown but its definition is missing, what happened?"); return true; } __instance.AddOutput((TerminalLineType)3, Text.Get(3436726297u), 4f, (TerminalSoundType)0, (TerminalSoundType)0); if ((Object)(object)definition.ChainedPuzzleToActiveInstance != (Object)null) { __instance.AddOutput(Text.Get(2277987284u), true); if (SNet.IsMaster) { definition.ChainedPuzzleToActiveInstance.AttemptInteract((eChainedPuzzleInteraction)0); } } else { connectedReactor.AttemptInteract((eReactorInteraction)6, 0f); } return false; } private static bool Handle_ReactorStartup_SpecialCommand(LG_ComputerTerminalCommandInterpreter __instance, TERM_Command cmd) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) LG_WardenObjective_Reactor connectedReactor = __instance.m_terminal.ConnectedReactor; if (__instance.m_terminal.CommandIsHidden(cmd)) { return true; } _ = __instance.m_terminal.ItemKey; OverrideReactorComp component = ((Component)connectedReactor).gameObject.GetComponent<OverrideReactorComp>(); if ((Object)(object)component == (Object)null) { return true; } if (!connectedReactor.ReadyForVerification) { __instance.AddOutput("", true); __instance.AddOutput((TerminalLineType)3, ReactorStartupOverrideManager.NotReadyForVerificationOutputText, 4f, (TerminalSoundType)0, (TerminalSoundType)0); __instance.AddOutput("", true); return false; } if (component.IsCorrectTerminal(__instance.m_terminal)) { EOSLogger.Log("Reactor Verify Correct!"); if (SNet.IsMaster) { if (connectedReactor.m_currentWaveCount == connectedReactor.m_waveCountMax) { connectedReactor.AttemptInteract((eReactorInteraction)5, 0f); } else { connectedReactor.AttemptInteract((eReactorInteraction)3, 0f); } } else { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(connectedReactor.m_currentWaveData.Events, (eWardenObjectiveEventTrigger)3, false, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null); } __instance.AddOutput(ReactorStartupOverrideManager.CorrectTerminalOutputText, true); } else { EOSLogger.Log("Reactor Verify Incorrect!"); __instance.AddOutput("", true); __instance.AddOutput((TerminalLineType)3, ReactorStartupOverrideManager.IncorrectTerminalOutputText, 4f, (TerminalSoundType)0, (TerminalSoundType)0); __instance.AddOutput("", true); } return false; } [HarmonyPrefix] [HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "ReceiveCommand")] private static bool Pre_ReceiveCommand(LG_ComputerTerminalCommandInterpreter __instance, TERM_Command cmd, string inputLine, string param1, string param2) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Invalid comparison between Unknown and I4 //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Invalid comparison between Unknown and I4 //IL_0031: Unknown result type (might be due to invalid IL or missing references) LG_WardenObjective_Reactor connectedReactor = __instance.m_terminal.ConnectedReactor; if ((Object)(object)connectedReactor == (Object)null) { return true; } if ((int)cmd == 23 && !connectedReactor.m_isWardenObjective) { return Handle_ReactorShutdown(__instance); } if ((int)cmd == 42) { return Handle_ReactorStartup_SpecialCommand(__instance, cmd); } return true; } } } namespace EOSExt.Reactor.Patches.Shutdown { [HarmonyPatch] internal class Reactor_OnReactorShutdownVerifyChaosDone { [HarmonyPrefix] [HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "OnReactorShutdownVerifyChaosDone")] private static bool Pre_LG_ComputerTerminalCommandInterpreter_OnReactorShutdownVerifyChaosDone(LG_ComputerTerminalCommandInterpreter __instance) { LG_WardenObjective_Reactor connectedReactor = __instance.m_terminal.ConnectedReactor; if ((Object)(object)connectedReactor == (Object)null || connectedReactor.m_isWardenObjective) { return true; } (eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = ((InstanceManager<LG_WardenObjective_Reactor>)ReactorInstanceManager.Current).GetGlobalZoneIndex(connectedReactor); uint zoneInstanceIndex = ((InstanceManager<LG_WardenObjective_Reactor>)ReactorInstanceManager.Current).GetZoneInstanceIndex(connectedReactor); ReactorShutdownDefinition definition = ((InstanceDefinitionManager<ReactorShutdownDefinition>)ReactorShutdownObjectiveManager.Current).GetDefinition(globalZoneIndex, zoneInstanceIndex); if (definition == null) { EOSLogger.Error("OnReactorShutdownVerifyChaosDone: found built custom reactor shutdown but its definition is missing, what happened?"); return false; } connectedReactor.AttemptInteract((eReactorInteraction)(((Object)(object)definition.ChainedPuzzleOnVerificationInstance != (Object)null) ? 8 : 9), 0f); return false; } } } namespace EOSExt.Reactor.Managers { public sealed class ReactorInstanceManager : InstanceManager<LG_WardenObjective_Reactor> { private HashSet<IntPtr> startupReactor = new HashSet<IntPtr>(); private HashSet<IntPtr> shutdownReactor = new HashSet<IntPtr>(); public static ReactorInstanceManager Current { get; private set; } public override (eDimensionIndex, LG_LayerType, eLocalZoneIndex) GetGlobalZoneIndex(LG_WardenObjective_Reactor instance) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) return (instance.SpawnNode.m_dimension.DimensionIndex, instance.SpawnNode.LayerType, instance.SpawnNode.m_zone.LocalIndex); } public void MarkAsStartupReactor(LG_WardenObjective_Reactor reactor) { if (shutdownReactor.Contains(((Il2CppObjectBase)reactor).Pointer)) { throw new ArgumentException("Invalid: cannot mark a reactor both as startup and shutdown reactor"); } startupReactor.Add(((Il2CppObjectBase)reactor).Pointer); } public void MarkAsShutdownReactor(LG_WardenObjective_Reactor reactor) { if (startupReactor.Contains(((Il2CppObjectBase)reactor).Pointer)) { throw new ArgumentException("Invalid: cannot mark a reactor both as startup and shutdown reactor"); } shutdownReactor.Add(((Il2CppObjectBase)reactor).Pointer); } public bool IsStartupReactor(LG_WardenObjective_Reactor reactor) { return startupReactor.Contains(((Il2CppObjectBase)reactor).Pointer); } public bool IsShutdownReactor(LG_WardenObjective_Reactor reactor) { return shutdownReactor.Contains(((Il2CppObjectBase)reactor).Pointer); } private void Clear() { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) foreach (IntPtr item in startupReactor) { LG_WardenObjective_Reactor val = new LG_WardenObjective_Reactor(item); if ((int)val != 0) { CellSoundPlayer sound = val.m_sound; if (sound != null) { sound.Recycle(); } } } foreach (IntPtr item2 in shutdownReactor) { LG_WardenObjective_Reactor val2 = new LG_WardenObjective_Reactor(item2); if ((int)val2 != 0) { CellSoundPlayer sound2 = val2.m_sound; if (sound2 != null) { sound2.Recycle(); } } } startupReactor.Clear(); shutdownReactor.Clear(); } public void SetupReactorTerminal(LG_WardenObjective_Reactor reactor, TerminalDefinition reactorTerminalData) { reactor.SpawnNode.m_zone.TerminalsSpawnedInZone.Add(reactor.m_terminal); if (reactorTerminalData != null) { reactorTerminalData.LocalLogFiles?.ForEach(delegate(TerminalLogFileData log) { reactor.m_terminal.AddLocalLog(log, true); }); reactorTerminalData.UniqueCommands?.ForEach(delegate(CustomCommand cmd) { EOSTerminalUtils.AddUniqueCommand(reactor.m_terminal, cmd); }); EOSTerminalUtils.BuildPassword(reactor.m_terminal, reactorTerminalData.PasswordData); } } public static LG_WardenObjective_Reactor FindVanillaReactor(LG_LayerType layer, int count) { //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) if (count < 0) { EOSLogger.Error($"FindVanillaReactor: Count should be non-negative, but got {count}!"); return null; } LG_WardenObjective_Reactor val = null; int num = count; Enumerator<LayerChainIndex, iWardenObjectiveItem> enumerator = WardenObjectiveManager.Current.m_wardenObjectiveItem.GetEnumerator(); while (enumerator.MoveNext()) { KeyValuePair<LayerChainIndex, iWardenObjectiveItem> current = enumerator.Current; if (current.Key.Layer != layer) { continue; } iWardenObjectiveItem value = current.Value; val = ((value != null) ? ((Il2CppObjectBase)value).TryCast<LG_WardenObjective_Reactor>() : null); if (!((Object)(object)val == (Object)null)) { if (num <= 0) { break; } val = null; num--; } } if ((Object)(object)val == (Object)null) { EOSLogger.Error($"FindVanillaReactor: reactor not found with index(Count) {num} in {layer}!"); } return val; } private ReactorInstanceManager() { LevelAPI.OnLevelCleanup += Clear; } static ReactorInstanceManager() { Current = new ReactorInstanceManager(); } } internal class ReactorStartupOverrideManager : InstanceDefinitionManager<ReactorStartupOverride> { private List<ReactorStartupOverride> builtOverride = new List<ReactorStartupOverride>(); public static uint SpecialCmdVerifyTextID { get; private set; } public static uint MainTerminalTextID { get; private set; } public static uint CooldownCommandDescTextID { get; private set; } public static uint InfiniteWaveVerifyTextID { get; private set; } public static uint NotReadyForVerificationOutputTextID { get; private set; } public static uint IncorrectTerminalOutputTextID { get; private set; } public static uint CorrectTerminalOutputTextID { get; private set; } public static string CoolDownCommandDesc { get { if (CooldownCommandDescTextID == 0) { return "Confirm Reactor Startup Cooling Protocol"; } return Text.Get(CooldownCommandDescTextID); } } public static string MainTerminalText { get { if (MainTerminalTextID == 0) { return "Main Terminal"; } return Text.Get(MainTerminalTextID); } } public static string SpecialCmdVerifyText { get { if (SpecialCmdVerifyTextID == 0) { return "REACTOR COOLING REQUIRED ({0}/{1})\nMANUAL OVERRIDE REQUIRED. USE COMMAND <color=orange>REACTOR_COOLDOWN</color> AT {2}"; } return Text.Get(SpecialCmdVerifyTextID); } } public static string InfiniteWaveVerifyText { get { if (InfiniteWaveVerifyTextID == 0) { return "VERIFICATION ({0}/{1})."; } return Text.Get(InfiniteWaveVerifyTextID); } } public static string NotReadyForVerificationOutputText { get { if (NotReadyForVerificationOutputTextID == 0) { return "<color=red>Reactor intensive test in progress, cannot initate cooldown</color>"; } return Text.Get(NotReadyForVerificationOutputTextID); } } public static string CorrectTerminalOutputText { get { if (CorrectTerminalOutputTextID == 0) { return "<color=red>Reactor stage cooldown completed</color>"; } return Text.Get(CorrectTerminalOutputTextID); } } public static string IncorrectTerminalOutputText { get { if (IncorrectTerminalOutputTextID == 0) { return "<color=red>Incorrect terminal, cannot initate cooldown</color>"; } return Text.Get(IncorrectTerminalOutputTextID); } } public static ReactorStartupOverrideManager Current { get; private set; } protected override string DEFINITION_NAME => "ReactorStartup"; public static void FetchOverrideTextDB() { SpecialCmdVerifyTextID = GameDataBlockBase<TextDataBlock>.GetBlockID("InGame.WardenObjective_Reactor.MeltdownVerification"); MainTerminalTextID = GameDataBlockBase<TextDataBlock>.GetBlockID("InGame.WardenObjective_Reactor.MeltdownMainTerminalName"); CooldownCommandDescTextID = GameDataBlockBase<TextDataBlock>.GetBlockID("InGame.WardenObjective_Reactor.MeltdownCoolDown.CommandDesc"); InfiniteWaveVerifyTextID = GameDataBlockBase<TextDataBlock>.GetBlockID("InGame.WardenObjective_Reactor.Verification.InfiniteWave"); NotReadyForVerificationOutputTextID = GameDataBlockBase<TextDataBlock>.GetBlockID("InGame.WardenObjective_Reactor.MeltdownCoolDown.Not_ReadyForVerification_Output"); IncorrectTerminalOutputTextID = GameDataBlockBase<TextDataBlock>.GetBlockID("InGame.WardenObjective_Reactor.MeltdownCoolDown.IncorrectTerminal_Output"); CorrectTerminalOutputTextID = GameDataBlockBase<TextDataBlock>.GetBlockID("InGame.WardenObjective_Reactor.MeltdownCoolDown.CorrectTerminal_Output"); } protected override void AddDefinitions(InstanceDefinitionsForLevel<ReactorStartupOverride> definitions) { definitions.Definitions.ForEach(delegate(ReactorStartupOverride def) { def.Overrides.Sort((WaveOverride o1, WaveOverride o2) => (o1.WaveIndex >= o2.WaveIndex) ? ((o1.WaveIndex > o2.WaveIndex) ? 1 : 0) : (-1)); }); base.AddDefinitions(definitions); } internal void Build(LG_WardenObjective_Reactor reactor, ReactorStartupOverride def) { if (!reactor.m_isWardenObjective) { EOSLogger.Error($"ReactorStartup: Reactor Override for reactor {((GlobalZoneIndex)def).GlobalZoneIndexTuple()}, Instance_{((BaseInstanceDefinition)def).InstanceIndex} is not setup by vanilla, won't override"); return; } OverrideReactorComp overrideReactorComp = ((Component)reactor).gameObject.AddComponent<OverrideReactorComp>(); overrideReactorComp.ChainedReactor = reactor; overrideReactorComp.overrideData = def; overrideReactorComp.UsingLightEffect = false; overrideReactorComp.Init(); ReactorInstanceManager.Current.MarkAsStartupReactor(reactor); ReactorInstanceManager.Current.SetupReactorTerminal(reactor, def.ReactorTerminal); def.ChainedPuzzleToActiveInstance = reactor.m_chainedPuzzleToStartSequence; if ((Object)(object)def.ChainedPuzzleToActiveInstance != (Object)null) { ChainedPuzzleInstance chainedPuzzleToActiveInstance = def.ChainedPuzzleToActiveInstance; chainedPuzzleToActiveInstance.OnPuzzleSolved += Action.op_Implicit((Action)delegate { def.EventsOnActive.ForEach(delegate(WardenObjectiveEventData e) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f); }); }); } builtOverride.Add(def); EOSLogger.Debug($"ReactorStartup: {((GlobalZoneIndex)def).GlobalZoneIndexTuple()}, Instance_{((BaseInstanceDefinition)def).InstanceIndex}, override completed"); } private void OnLevelCleanup() { builtOverride.ForEach(delegate(ReactorStartupOverride def) { def.ChainedPuzzleToActiveInstance = null; }); builtOverride.Clear(); } private ReactorStartupOverrideManager() { LevelAPI.OnLevelCleanup += OnLevelCleanup; LevelAPI.OnBuildStart += OnLevelCleanup; } static ReactorStartupOverrideManager() { SpecialCmdVerifyTextID = 0u; MainTerminalTextID = 0u; CooldownCommandDescTextID = 0u; InfiniteWaveVerifyTextID = 0u; NotReadyForVerificationOutputTextID = 0u; IncorrectTerminalOutputTextID = 0u; CorrectTerminalOutputTextID = 0u; Current = new ReactorStartupOverrideManager(); EventAPI.OnExpeditionStarted += FetchOverrideTextDB; } } internal class ReactorShutdownObjectiveManager : InstanceDefinitionManager<ReactorShutdownDefinition> { private List<ReactorShutdownDefinition> builtShutdownPuzzles = new List<ReactorShutdownDefinition>(); public static ReactorShutdownObjectiveManager Current { get; private set; } protected override string DEFINITION_NAME => "ReactorShutdown"; private void GenericObjectiveSetup(LG_WardenObjective_Reactor reactor, TerminalDefinition reactorTerminalData) { //IL_0052: Unknown result type (might be due to invalid IL or missing references) reactor.m_serialNumber = SerialGenerator.GetUniqueSerialNo(); reactor.m_itemKey = "REACTOR_" + reactor.m_serialNumber; reactor.m_terminalItem = GOUtil.GetInterfaceFromComp<iTerminalItem>(reactor.m_terminalItemComp); reactor.m_terminalItem.Setup(reactor.m_itemKey, (AIG_CourseNode)null); reactor.m_terminalItem.FloorItemStatus = EnumUtil.GetRandomValue<eFloorInventoryObjectStatus>(); reactor.m_overrideCodes = Il2CppStringArray.op_Implicit(new string[1] { SerialGenerator.GetCodeWord() }); reactor.m_terminalItem.OnWantDetailedInfo = Func<List<string>, List<string>>.op_Implicit((Func<List<string>, List<string>>)delegate(List<string> defaultDetails) { List<string> list = new List<string> { "----------------------------------------------------------------", "MAIN POWER REACTOR" }; Enumerator<string> enumerator = defaultDetails.GetEnumerator(); while (enumerator.MoveNext()) { string current = enumerator.Current; list.Add(current); } list.Add("----------------------------------------------------------------"); return ListExtensions.ToIl2Cpp<string>(list); }); reactor.m_terminal = GOUtil.SpawnChildAndGetComp<LG_ComputerTerminal>(reactor.m_terminalPrefab, reactor.m_terminalAlign); reactor.m_terminal.Setup((TerminalStartStateData)null, (TerminalPlacementData)null); reactor.m_terminal.ConnectedReactor = reactor; ReactorInstanceManager.Current.SetupReactorTerminal(reactor, reactorTerminalData); } private void OnLateBuildJob(LG_WardenObjective_Reactor reactor, BaseReactorDefinition reactorDefinition) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Expected O, but got Unknown //IL_0066: Unknown result type (might be due to invalid IL or missing references) reactor.m_stateReplicator = SNet_StateReplicator<pReactorState, pReactorInteraction>.Create(new iSNet_StateReplicatorProvider<pReactorState, pReactorInteraction>(((Il2CppObjectBase)reactor).Pointer), (eSNetReplicatorLifeTime)1, default(pReactorState), (SNet_ChannelType)2); GenericObjectiveSetup(reactor, reactorDefinition.ReactorTerminal); reactor.m_sound = new CellSoundPlayer(reactor.m_terminalAlign.position); reactor.m_sound.Post(EVENTS.REACTOR_POWER_LEVEL_1_LOOP, true); reactor.m_sound.SetRTPCValue(GAME_PARAMETERS.REACTOR_POWER, 100f); reactor.m_terminal.m_command.SetupReactorCommands(false, true); } internal void Build(LG_WardenObjective_Reactor reactor, ReactorShutdownDefinition def) { //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_018f: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Expected O, but got Unknown //IL_019d: Expected O, but got Unknown //IL_024f: Unknown result type (might be due to invalid IL or missing references) //IL_0273: Unknown result type (might be due to invalid IL or missing references) //IL_02f1: Unknown result type (might be due to invalid IL or missing references) //IL_0315: Unknown result type (might be due to invalid IL or missing references) if (reactor.m_isWardenObjective) { EOSLogger.Error($"ReactorShutdown: Reactor definition for reactor {((GlobalZoneIndex)def).GlobalZoneIndexTuple()}, Instance_{((BaseInstanceDefinition)def).InstanceIndex} is already setup by vanilla, won't build."); return; } OnLateBuildJob(reactor, def); reactor.m_lightCollection = LG_LightCollection.Create(reactor.m_reactorArea.m_courseNode, reactor.m_terminalAlign.position, (LG_LightCollectionSorting)1, float.MaxValue); reactor.m_lightCollection.SetMode(true); if (def.PutVerificationCodeOnTerminal) { LG_ComputerTerminal instance = ((InstanceManager<LG_ComputerTerminal>)(object)TerminalInstanceManager.Current).GetInstance(((GlobalZoneIndex)def.VerificationCodeTerminal).GlobalZoneIndexTuple(), def.VerificationCodeTerminal.InstanceIndex); if ((Object)(object)instance == (Object)null) { EOSLogger.Error($"ReactorShutdown: PutVerificationCodeOnTerminal is specified but could NOT find terminal {def.VerificationCodeTerminal}, will show verification code upon shutdown initiation"); } else { string fileName = "reactor_ver" + SerialGenerator.GetCodeWordPrefix() + ".log"; TerminalLogFileData val = new TerminalLogFileData { FileName = fileName, FileContent = new LocalizedText { UntranslatedText = string.Format(Text.Get(182408469u), ((Il2CppArrayBase<string>)(object)reactor.m_overrideCodes)[0].ToUpperInvariant()), Id = 0u } }; instance.AddLocalLog(val, true); instance.m_command.ClearOutputQueueAndScreenBuffer(); instance.m_command.AddInitialTerminalOutput(); } } if (reactor.SpawnNode != null && reactor.m_terminalItem != null) { reactor.m_terminalItem.SpawnNode = reactor.SpawnNode; reactor.m_terminalItem.FloorItemLocation = reactor.SpawnNode.m_zone.NavInfo.GetFormattedText((LG_NavInfoFormat)7); } if (def.ChainedPuzzleToActive != 0) { ChainedPuzzleDataBlock block = GameDataBlockBase<ChainedPuzzleDataBlock>.GetBlock(def.ChainedPuzzleToActive); if (block == null) { EOSLogger.Error("ReactorShutdown: ChainedPuzzleToActive is specified but could not find its ChainedPuzzleDatablock definition!"); } else { _ = ((Component)reactor).transform.position; def.ChainedPuzzleToActiveInstance = ChainedPuzzleManager.CreatePuzzleInstance(block, reactor.SpawnNode.m_area, reactor.m_chainedPuzzleAlign.position, ((Component)reactor).transform); ChainedPuzzleInstance chainedPuzzleToActiveInstance = def.ChainedPuzzleToActiveInstance; chainedPuzzleToActiveInstance.OnPuzzleSolved += Action.op_Implicit((Action)delegate { if (SNet.IsMaster) { reactor.AttemptInteract((eReactorInteraction)6, 0f); } }); } } else { EOSLogger.Debug("ReactorShutdown: Reactor has no ChainedPuzzleToActive, will start shutdown sequence on shutdown command initiation."); } if (def.ChainedPuzzleOnVerification != 0) { ChainedPuzzleDataBlock block2 = GameDataBlockBase<ChainedPuzzleDataBlock>.GetBlock(def.ChainedPuzzleOnVerification); if (block2 == null) { EOSLogger.Error("ReactorShutdown: ChainedPuzzleOnVerification is specified but could not find its ChainedPuzzleDatablock definition! Will complete shutdown on verification"); } _ = ((Component)reactor).transform.position; def.ChainedPuzzleOnVerificationInstance = ChainedPuzzleManager.CreatePuzzleInstance(block2, reactor.SpawnNode.m_area, reactor.m_chainedPuzzleAlign.position, ((Component)reactor).transform); ChainedPuzzleInstance chainedPuzzleOnVerificationInstance = def.ChainedPuzzleOnVerificationInstance; chainedPuzzleOnVerificationInstance.OnPuzzleSolved += Action.op_Implicit((Action)delegate { if (SNet.IsMaster) { reactor.AttemptInteract((eReactorInteraction)9, 0f); } }); } else { EOSLogger.Debug("ReactorShutdown: ChainedPuzzleOnVerification unspecified, will complete shutdown on verification."); } LG_ComputerTerminal terminal = reactor.m_terminal; iLG_SpawnedInNodeHandler val2 = ((terminal != null) ? ((Component)terminal).GetComponent<iLG_SpawnedInNodeHandler>() : null); if (val2 != null) { val2.SpawnNode = reactor.SpawnNode; } reactor.SetLightsEnabled(reactor.m_lightsWhenOff, false); reactor.SetLightsEnabled(reactor.m_lightsWhenOn, true); builtShutdownPuzzles.Add(def); ReactorInstanceManager.Current.MarkAsShutdownReactor(reactor); EOSLogger.Debug($"ReactorShutdown: {((GlobalZoneIndex)def).GlobalZoneIndexTuple()}, Instance_{((BaseInstanceDefinition)def).InstanceIndex}, custom setup completed"); } private void OnLevelCleanup() { builtShutdownPuzzles.ForEach(delegate(ReactorShutdownDefinition def) { ChainedPuzzleInstance chainedPuzzleOnVerificationInstance = (def.ChainedPuzzleToActiveInstance = null); def.ChainedPuzzleOnVerificationInstance = chainedPuzzleOnVerificationInstance; }); builtShutdownPuzzles.Clear(); } private ReactorShutdownObjectiveManager() { LevelAPI.OnLevelCleanup += OnLevelCleanup; LevelAPI.OnBuildStart += OnLevelCleanup; } static ReactorShutdownObjectiveManager() { Current = new ReactorShutdownObjectiveManager(); } } } namespace EOSExt.Reactor.Definition { public enum EOSReactorVerificationType { NORMAL, BY_SPECIAL_COMMAND, BY_WARDEN_EVENT } public class WaveOverride { public int WaveIndex { get; set; } = -1; public EOSReactorVerificationType VerificationType { get; set; } public bool HideVerificationTimer { get; set; } public bool ChangeVerifyZone { get; set; } public BaseInstanceDefinition VerifyZone { get; set; } = new BaseInstanceDefinition(); [JsonIgnore] public LG_ComputerTerminal VerifyTerminal { get; set; } } public class ReactorStartupOverride : BaseReactorDefinition { public bool StartupOnDrop { get; set; } [JsonIgnore] public WardenObjectiveDataBlock ObjectiveDB { get; set; } public List<WaveOverride> Overrides { get; set; } = new List<WaveOverride> { new WaveOverride() }; } internal class WardenEvents { public enum EventType { ReactorStartup = 150, CompleteCurrentVerify } internal static void ReactorStartup(WardenObjectiveEventData e) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Invalid comparison between Unknown and I4 //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: 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_010c: Unknown result type (might be due to invalid IL or missing references) if (!SNet.IsMaster) { return; } LG_WardenObjective_Reactor val = ReactorInstanceManager.FindVanillaReactor(e.Layer, e.Count); WardenObjectiveDataBlock val2 = default(WardenObjectiveDataBlock); if (!WardenObjectiveManager.Current.TryGetActiveWardenObjectiveData(e.Layer, ref val2) || val2 == null) { EOSLogger.Error("CompleteCurrentReactorWave: Cannot get WardenObjectiveDataBlock"); return; } if ((int)val2.Type != 1) { EOSLogger.Error($"CompleteCurrentReactorWave: {e.Layer} is not ReactorStartup. CompleteCurrentReactorWave is invalid."); return; } if ((Object)(object)val == (Object)null) { EOSLogger.Error($"ReactorStartup: Cannot find reactor in {e.Layer}."); return; } if ((int)val.m_currentState.status == 0) { if (SNet.IsMaster) { val.AttemptInteract((eReactorInteraction)0, 0f); } val.m_terminal.TrySyncSetCommandHidden((TERM_Command)21); } EOSLogger.Debug($"ReactorStartup: Current reactor wave for {e.Layer} completed"); } internal static void CompleteCurrentVerify(WardenObjectiveEventData e) { //IL_0006: 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_0029: Invalid comparison between Unknown and I4 //IL_0068: 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_009b: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Unknown result type (might be due to invalid IL or missing references) WardenObjectiveDataBlock val = default(WardenObjectiveDataBlock); if (!WardenObjectiveManager.Current.TryGetActiveWardenObjectiveData(e.Layer, ref val) || val == null) { EOSLogger.Error("CompleteCurrentReactorWave: Cannot get WardenObjectiveDataBlock"); return; } if ((int)val.Type != 1) { EOSLogger.Error($"CompleteCurrentReactorWave: {e.Layer} is not ReactorStartup. CompleteCurrentReactorWave is invalid."); return; } LG_WardenObjective_Reactor val2 = ReactorInstanceManager.FindVanillaReactor(e.Layer, e.Count); if ((Object)(object)val2 == (Object)null) { EOSLogger.Error($"CompleteCurrentReactorWave: Cannot find reactor in {e.Layer}."); return; } if (SNet.IsMaster) { if (val2.m_currentWaveCount == val2.m_waveCountMax) { val2.AttemptInteract((eReactorInteraction)5, 0f); } else { val2.AttemptInteract((eReactorInteraction)3, 0f); } } else { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(val2.m_currentWaveData.Events, (eWardenObjectiveEventTrigger)3, false, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null); } EOSLogger.Debug($"CompleteCurrentReactorWave: Current reactor verify for {e.Layer} completed"); } } public class BaseReactorDefinition : BaseInstanceDefinition { [JsonPropertyOrder(-9)] public TerminalDefinition ReactorTerminal { get; set; } = new TerminalDefinition(); [JsonPropertyOrder(-9)] public List<WardenObjectiveEventData> EventsOnActive { get; set; } = new List<WardenObjectiveEventData>(); [JsonIgnore] public ChainedPuzzleInstance ChainedPuzzleToActiveInstance { get; set; } } public class ReactorShutdownDefinition : BaseReactorDefinition { [JsonPropertyOrder(-9)] public uint ChainedPuzzleToActive { get; set; } public bool PutVerificationCodeOnTerminal { get; set; } public BaseInstanceDefinition VerificationCodeTerminal { get; set; } = new BaseInstanceDefinition(); public uint ChainedPuzzleOnVerification { get; set; } [JsonIgnore] public ChainedPuzzleInstance ChainedPuzzleOnVerificationInstance { get; set; } public List<WardenObjectiveEventData> EventsOnShutdownPuzzleStarts { get; set; } = new List<WardenObjectiveEventData>(); public List<WardenObjectiveEventData> EventsOnComplete { get; set; } = new List<WardenObjectiveEventData>(); } } namespace EOSExt.Reactor.Component { public class OverrideReactorComp : MonoBehaviour { private static Color LowTemperature; private static Color HighTemperature; private LG_Light[] _lights; private float _updateTimer; private List<WaveOverride> WaveData = new List<WaveOverride>(); public LG_WardenObjective_Reactor ChainedReactor { get; internal set; } public ReactorStartupOverride overrideData { get; internal set; } public bool UsingLightEffect { get; set; } = true; public WardenObjectiveDataBlock ObjectiveData => overrideData?.ObjectiveDB; public void Init() { if ((Object)(object)ChainedReactor == (Object)null || overrideData == null) { EOSLogger.Error("ReactorOverride not properly initialized!"); return; } int i; for (i = 0; i < ObjectiveData.ReactorWaves.Count; i++) { int num = overrideData.Overrides.FindIndex((WaveOverride o) => o.WaveIndex == i); if (num != -1) { WaveData.Add(new WaveOverride { WaveIndex = i, VerificationType = overrideData.Overrides[num].VerificationType, HideVerificationTimer = overrideData.Overrides[num].HideVerificationTimer, ChangeVerifyZone = overrideData.Overrides[num].ChangeVerifyZone, VerifyZone = overrideData.Overrides[num].VerifyZone }); } else { WaveData.Add(new WaveOverride { WaveIndex = i }); } } LevelAPI.OnEnterLevel += OnEnterLevel; } private void OnEnterLevel() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Invalid comparison between Unknown and I4 LG_WardenObjective_Reactor chainedReactor = ChainedReactor; LG_ComputerTerminal terminal = ChainedReactor.m_terminal; if ((int)ObjectiveData.Type != 1) { EOSLogger.Error("Only Reactor Startup is supported"); ((Behaviour)this).enabled = false; return; } if (UsingLightEffect) { _lights = ((IEnumerable<LG_Light>)chainedReactor.SpawnNode.m_lightsInNode).Where((LG_Light x) => (int)x.m_category == 3).ToArray(); chainedReactor.m_lightCollection.RemoveLights(Il2CppReferenceArray<LG_Light>.op_Implicit(_lights)); } if (overrideData.StartupOnDrop && SNet.IsMaster) { chainedReactor.AttemptInteract((eReactorInteraction)0, 0f); terminal.TrySyncSetCommandHidden((TERM_Command)21); } SetupVerifyZoneOverrides(); SetupWaves(); } private void SetupVerifyZoneOverrides() { //IL_0094: 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_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_03c5: Unknown result type (might be due to invalid IL or missing references) //IL_03ca: Unknown result type (might be due to invalid IL or missing references) //IL_03db: Unknown result type (might be due to invalid IL or missing references) //IL_03dc: 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_0411: Unknown result type (might be due to invalid IL or missing references) //IL_041d: Expected O, but got Unknown //IL_041f: Expected O, but got Unknown //IL_0240: 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_025b: Unknown result type (might be due to invalid IL or missing references) //IL_02c5: Unknown result type (might be due to invalid IL or missing references) //IL_02d5: Unknown result type (might be due to invalid IL or missing references) //IL_02e0: Unknown result type (might be due to invalid IL or missing references) LG_Zone val = default(LG_Zone); foreach (WaveOverride waveDatum in WaveData) { if (!waveDatum.ChangeVerifyZone) { continue; } if (waveDatum.VerificationType == EOSReactorVerificationType.BY_WARDEN_EVENT) { EOSLogger.Error($"VerifyZoneOverrides: Wave_{waveDatum.WaveIndex} - Verification Type is {2}, which doesn't work with VerifyZoneOverride"); continue; } BaseInstanceDefinition verifyZone = waveDatum.VerifyZone; if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(((GlobalZoneIndex)verifyZone).DimensionIndex, ((GlobalZoneIndex)verifyZone).LayerType, ((GlobalZoneIndex)verifyZone).LocalIndex, ref val) || (Object)(object)val == (Object)null) { EOSLogger.Error($"VerifyZoneOverrides: Wave_{waveDatum.WaveIndex} - Cannot find target zone {((GlobalZoneIndex)verifyZone).GlobalZoneIndexTuple()}."); continue; } if (val.TerminalsSpawnedInZone == null || val.TerminalsSpawnedInZone.Count <= 0) { EOSLogger.Error($"VerifyZoneOverrides: No spawned terminal found in target zone {((GlobalZoneIndex)verifyZone).GlobalZoneIndexTuple()}."); continue; } LG_ComputerTerminal val2 = null; if (verifyZone.InstanceIndex >= 0) { val2 = ((InstanceManager<LG_ComputerTerminal>)(object)TerminalInstanceManager.Current).GetInstance(((GlobalZoneIndex)verifyZone).GlobalZoneIndexTuple(), verifyZone.InstanceIndex); } else { List<LG_ComputerTerminal> instancesInZone = ((InstanceManager<LG_ComputerTerminal>)(object)TerminalInstanceManager.Current).GetInstancesInZone(((GlobalZoneIndex)verifyZone).GlobalZoneIndexTuple()); int index = Builder.SessionSeedRandom.Range(0, instancesInZone.Count, "NO_TAG"); val2 = instancesInZone[index]; } if ((Object)(object)val2 == (Object)null) { EOSLogger.Error($"VerifyZoneOverride: cannot find target terminal with Terminal Instance Index: {waveDatum}"); } waveDatum.VerifyTerminal = val2; ReactorWaveData waveData = ObjectiveData.ReactorWaves[waveDatum.WaveIndex]; TerminalLogFileData val3 = null; if (waveData.VerifyInOtherZone) { List<LG_ComputerTerminal> list = EOSTerminalUtils.FindTerminal(ChainedReactor.SpawnNode.m_dimension.DimensionIndex, ChainedReactor.SpawnNode.LayerType, waveData.ZoneForVerification, (Predicate<LG_ComputerTerminal>)((LG_ComputerTerminal x) => x.ItemKey == waveData.VerificationTerminalSerial)); if (list == null || list.Count < 1) { EOSLogger.Error($"Wave_{waveDatum.WaveIndex}: cannot find vanilla verification terminal in {(ChainedReactor.SpawnNode.m_dimension.DimensionIndex, ChainedReactor.SpawnNode.LayerType, waveData.ZoneForVerification)}, unable to override"); continue; } LG_ComputerTerminal val4 = list[0]; if ((Object)(object)val4 == (Object)null) { EOSLogger.Error($"VerifyZoneOverrides: Wave_{waveDatum.WaveIndex} - Cannot find log terminal"); continue; } string text = waveData.VerificationTerminalFileName.ToUpperInvariant(); val3 = EOSTerminalUtils.GetLocalLog(val4, text); if (val3 == null) { EOSLogger.Error("VerifyZoneOverrides: Cannot find vanilla-generated reactor verify log on terminal..."); continue; } val4.RemoveLocalLog(text); EOSTerminalUtils.ResetInitialOutput(val4); } else { waveData.VerificationTerminalFileName = "reactor_ver" + SerialGenerator.GetCodeWordPrefix() + ".log"; val3 = new TerminalLogFileData { FileName = waveData.VerificationTerminalFileName, FileContent = new LocalizedText { UntranslatedText = string.Format(Text.Get(182408469u), ((Il2CppArrayBase<string>)(object)ChainedReactor.m_overrideCodes)[waveDatum.WaveIndex].ToUpper()), Id = 0u } }; EOSLogger.Debug($"VerifyZoneOverrides: Wave_{waveDatum.WaveIndex} - Log generated."); } waveData.HasVerificationTerminal = true; waveData.VerificationTerminalSerial = val2.ItemKey; val2.AddLocalLog(val3, true); EOSTerminalUtils.ResetInitialOutput(val2); EOSLogger.Debug($"VerifyZoneOverrides: Wave_{waveDatum.WaveIndex} verification overriden"); } } private void SetupWaves() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_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_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00d0: Unknown result type (might be due to invalid IL or missing references) LG_WardenObjective_Reactor chainedReactor = ChainedReactor; eDimensionIndex dimensionIndex = chainedReactor.SpawnNode.m_dimension.DimensionIndex; LG_LayerType layerType = chainedReactor.SpawnNode.LayerType; int num = 0; for (int i = 0; i < WaveData.Count; i++) { ReactorWaveData reactorWave = ObjectiveData.ReactorWaves[i]; WaveOverride waveOverride = WaveData[i]; switch (waveOverride.VerificationType) { case EOSReactorVerificationType.BY_SPECIAL_COMMAND: if (!reactorWave.HasVerificationTerminal) { waveOverride.VerifyTerminal = ChainedReactor.m_terminal; AddVerifyCommand(ChainedReactor.m_terminal); } else { LG_ComputerTerminal val = waveOverride.VerifyTerminal; if ((Object)(object)val == (Object)null) { val = EOSTerminalUtils.FindTerminal(dimensionIndex, layerType, reactorWave.ZoneForVerification, (Predicate<LG_ComputerTerminal>)((LG_ComputerTerminal terminal) => terminal.ItemKey.Equals(reactorWave.VerificationTerminalSerial, StringComparison.InvariantCultureIgnoreCase)))?[0]; if ((Object)(object)val == (Object)null) { EOSLogger.Error($"SetupWaves: cannot find verify terminal for Wave_{i}, skipped"); break; } waveOverride.VerifyTerminal = val; } val.ConnectedReactor = chainedReactor; val.RemoveLocalLog(reactorWave.VerificationTerminalFileName.ToUpperInvariant()); AddVerifyCommand(val); EOSTerminalUtils.ResetInitialOutput(val); } num++; EOSLogger.Debug($"WaveOverride: Setup as Wave Verification {1} for Wave_{i}"); break; default: EOSLogger.Error($"Unimplemented Verification Type {waveOverride.VerificationType}"); break; case EOSReactorVerificationType.NORMAL: case EOSReactorVerificationType.BY_WARDEN_EVENT: break; } } if (num == ObjectiveData.ReactorWaves.Count) { ChainedReactor.m_terminal.TrySyncSetCommandHidden((TERM_Command)22); } } private void AddVerifyCommand(LG_ComputerTerminal terminal) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown LG_ComputerTerminalCommandInterpreter command = terminal.m_command; if (command.HasRegisteredCommand((TERM_Command)42)) { EOSLogger.Debug("TERM_Command.UniqueCommand5 already registered. If this terminal is specified as objective terminal for 2 waves and the number of commands in 'UniqueCommands' on this terminal isn't more than 4, simply ignore this message."); return; } command.AddCommand((TERM_Command)42, "REACTOR_COOLDOWN", new LocalizedText { UntranslatedText = ReactorStartupOverrideManager.CoolDownCommandDesc, Id = 0u }, (TERM_CommandRule)0); terminal.TrySyncSetCommandRule((TERM_Command)42, (TERM_CommandRule)0); } public bool IsCorrectTerminal(LG_ComputerTerminal terminal) { int num = ChainedReactor.m_currentWaveCount - 1; if (num >= 0) { EOSLogger.Debug($"Index: {num}"); EOSLogger.Debug("Comp Terminal Key1: " + terminal.ItemKey); EOSLogger.Debug("Comp Terminal Key2: " + (((Object)(object)WaveData[num].VerifyTerminal != (Object)null) ? WaveData[num].VerifyTerminal.ItemKey : "empty")); if (WaveData[num].VerifyTerminal.ItemKey != null && WaveData[num].VerifyTerminal.ItemKey.Equals(terminal.ItemKey, StringComparison.InvariantCultureIgnoreCase)) { return true; } } return false; } public void SetIdle() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_003b: 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_0048: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)ChainedReactor == (Object)null)) { pReactorState val = default(pReactorState); val.status = (eReactorStatus)0; val.stateCount = 0; val.stateProgress = 0f; val.verifyFailed = false; pReactorState state = val; ChainedReactor.m_stateReplicator.State = state; } } private void OnDestroy() { LevelAPI.OnEnterLevel -= OnEnterLevel; ChainedReactor = null; overrideData = null; } private void LateUpdate() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001a: 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_0024: Unknown result type (might be due to invalid IL or missing references) if ((int)GameStateManager.CurrentStateName == 10) { eReactorStatus status = ChainedReactor.m_currentState.status; if (UsingLightEffect) { UpdateLight(status, ChainedReactor.m_currentWaveProgress); } UpdateGUIText(status); } } private void UpdateGUIText(eReactorStatus status) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Invalid comparison between Unknown and I4 int num = ChainedReactor.m_currentWaveCount - 1; if (num < 0) { return; } WaveOverride waveOverride = WaveData[num]; if ((int)status != 4) { return; } switch (waveOverride.VerificationType) { case EOSReactorVerificationType.NORMAL: if (ChainedReactor.m_currentWaveData.HasVerificationTerminal) { ChainedReactor.SetGUIMessage(true, Text.Format(1103u, (Object[])(object)new Object[3] { Object.op_Implicit(ChainedReactor.m_currentWaveCount), Object.op_Implicit(ChainedReactor.m_waveCountMax), Object.op_Implicit("<color=orange>" + ChainedReactor.m_currentWaveData.VerificationTerminalSerial + "</color>") }), (ePUIMessageStyle)3, !waveOverride.HideVerificationTimer, "<size=125%>" + Text.Get(1104u), "</size>"); } else { ChainedReactor.SetGUIMessage(true, Text.Format(1105u, (Object[])(object)new Object[3] { Object.op_Implicit(ChainedReactor.m_currentWaveCount), Object.op_Implicit(ChainedReactor.m_waveCountMax), Object.op_Implicit("<color=orange>" + ChainedReactor.CurrentStateOverrideCode + "</color>") }), (ePUIMessageStyle)3, !waveOverride.HideVerificationTimer, "<size=125%>" + Text.Get(1104u), "</size>"); } break; case EOSReactorVerificationType.BY_SPECIAL_COMMAND: { string text = (ChainedReactor.m_currentWaveData.HasVerificationTerminal ? ChainedReactor.m_currentWaveData.VerificationTerminalSerial : ReactorStartupOverrideManager.MainTerminalText); ChainedReactor.SetGUIMessage(true, string.Format(ReactorStartupOverrideManager.SpecialCmdVerifyText, ChainedReactor.m_currentWaveCount, ChainedReactor.m_waveCountMax, "<color=orange>" + text + "</color>"), (ePUIMessageStyle)3, !waveOverride.HideVerificationTimer, "<size=125%>" + Text.Get(1104u), "</size>"); break; } case EOSReactorVerificationType.BY_WARDEN_EVENT: ChainedReactor.SetGUIMessage(true, string.Format(ReactorStartupOverrideManager.InfiniteWaveVerifyText, ChainedReactor.m_currentWaveCount, ChainedReactor.m_waveCountMax), (ePUIMessageStyle)3, !waveOverride.HideVerificationTimer, "<size=125%>" + Text.Get(1104u), "</size>"); break; } } private void UpdateLight(eReactorStatus status, float progress) { //IL_001f: 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_003b: Expected I4, but got Unknown //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) if (!(_updateTimer > Clock.Time)) { _updateTimer = Clock.Time + 0.15f; switch (status - 1) { case 0: SetLightColor(Color.black); break; case 1: SetLightColor(Color.Lerp(LowTemperature, HighTemperature, progress)); break; case 2: SetLightColor(Color.Lerp(HighTemperature, LowTemperature, progress)); break; case 3: SetLightColor(LowTemperature); break; case 4: SetLightColor(LowTemperature); break; } } } private void SetLightColor(Color color) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) if (UsingLightEffect && _lights != null) { for (int i = 0; i < _lights.Length; i++) { _lights[i].ChangeColor(color); } } } static OverrideReactorComp() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) LowTemperature = ColorExt.Hex("#23E4F2") * 2.5f; HighTemperature = ColorExt.Hex("#F63838") * 12f; } } }
plugins/net6/Inas07.EOSExt.SecurityDoorTerminal.dll
Decompiled a month agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using AIGraph; using BepInEx; using BepInEx.Unity.IL2CPP; using ChainedPuzzles; using EOSExt.SecurityDoorTerminal.Definition; using ExtraObjectiveSetup; using ExtraObjectiveSetup.BaseClasses; using ExtraObjectiveSetup.BaseClasses.CustomTerminalDefinition; using ExtraObjectiveSetup.ExtendedWardenEvents; using ExtraObjectiveSetup.Utils; using GTFO.API; using GTFO.API.Extensions; using GameData; using Il2CppInterop.Runtime.InteropTypes; using Il2CppSystem; using LevelGeneration; using Localization; using Microsoft.CodeAnalysis; using Player; using SecDoorTerminalInterface; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("Inas07.EOSExt.SecurityDoorTerminal")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("Inas07.EOSExt.SecurityDoorTerminal")] [assembly: AssemblyTitle("Inas07.EOSExt.SecurityDoorTerminal")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace EOSExt.SecurityDoorTerminal { [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInPlugin("Inas.EOSExt.SecurityDoorTerminal", "EOSExt.SecurityDoorTerminal", "1.0.0")] public class EntryPoint : BasePlugin { public const string AUTHOR = "Inas"; public const string PLUGIN_NAME = "EOSExt.SecurityDoorTerminal"; public const string VERSION = "1.0.0"; public override void Load() { SetupManagers(); EOSLogger.Log("ExtraObjectiveSetup.SecurityDoorTerminal loaded."); } private void SetupManagers() { ((ZoneDefinitionManager<SecurityDoorTerminalDefinition>)SecurityDoorTerminalManager.Current).Init(); } } public sealed class SecurityDoorTerminalManager : ZoneDefinitionManager<SecurityDoorTerminalDefinition> { private enum SDTWardenEvents { ADD_OVERRIDE_COMMAND = 1000 } private const string OVERRIDE_COMMAND = "ACCESS_OVERRIDE"; private List<(SecDoorTerminal sdt, SecurityDoorTerminalDefinition def)> levelSDTs = new List<(SecDoorTerminal, SecurityDoorTerminalDefinition)>(); public static SecurityDoorTerminalManager Current { get; private set; } protected override string DEFINITION_NAME => "SecDoorTerminal"; public bool TryGetZoneEntranceSecDoor(LG_Zone zone, out LG_SecurityDoor door) { if ((Object)(object)zone == (Object)null) { door = null; return false; } if ((Object)(object)zone.m_sourceGate == (Object)null) { door = null; return false; } if (zone.m_sourceGate.SpawnedDoor == null) { door = null; return false; } door = ((Il2CppObjectBase)zone.m_sourceGate.SpawnedDoor).TryCast<LG_SecurityDoor>(); return (Object)(object)door != (Object)null; } protected override void AddDefinitions(ZoneDefinitionsForLevel<SecurityDoorTerminalDefinition> definitions) { base.Sort(definitions); base.AddDefinitions(definitions); } private void AddOverrideCommandWithAlarmText(SecDoorTerminal sdt) { if (sdt.CmdProcessor.HasRegisteredCommand((TERM_Command)254)) { return; } string text = "<color=orange>" + Text.Get(841u) + "</color>"; if ((Object)(object)sdt.LinkedDoorLocks.ChainedPuzzleToSolve != (Object)null && sdt.LinkedDoorLocks.ChainedPuzzleToSolve.Data.TriggerAlarmOnActivate) { string format = Text.Get(840u); ChainedPuzzleInstance chainedPuzzleToSolve = sdt.LinkedDoorLocks.ChainedPuzzleToSolve; text = "<color=orange>" + string.Format(format, (chainedPuzzleToSolve != null) ? chainedPuzzleToSolve.Data.PublicAlarmName : null) + "</color>"; int num = text.IndexOf('['); if (num >= 0 && num < text.Length) { text = text.Insert(num, "\n"); } } sdt.AddOverrideCommand("ACCESS_OVERRIDE", text, (Action<LG_ComputerTerminalCommandInterpreter>)null); } private void BuildSDT_UniqueCommands(SecDoorTerminal sdt, SecurityDoorTerminalDefinition def) { def.TerminalSettings.UniqueCommands.ForEach(delegate(CustomCommand cmd) { EOSTerminalUtils.AddUniqueCommand(sdt.ComputerTerminal, cmd); }); } private void BuildLevelSDTs_UniqueCommands() { levelSDTs.ForEach(delegate((SecDoorTerminal sdt, SecurityDoorTerminalDefinition def) tp) { BuildSDT_UniqueCommands(tp.sdt, tp.def); }); } private void BuildLevelSDTs_Passwords() { levelSDTs.ForEach(delegate((SecDoorTerminal sdt, SecurityDoorTerminalDefinition def) tp) { EOSTerminalUtils.BuildPassword(tp.sdt.ComputerTerminal, tp.def.TerminalSettings.PasswordData); }); } private void WardenEvent_AddOverrideCommand(WardenObjectiveEventData e) { //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: 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_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) int num = levelSDTs.FindIndex(delegate((SecDoorTerminal sdt, SecurityDoorTerminalDefinition def) tp) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0034: 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_004c: 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) AIG_CourseNode courseNode = ((LG_ZoneExpander)tp.sdt.LinkedDoor.Gate).m_linksTo.m_courseNode; return courseNode.m_dimension.DimensionIndex == e.DimensionIndex && courseNode.LayerType == e.Layer && courseNode.m_zone.LocalIndex == e.LocalIndex; }); if (num == -1) { EOSLogger.Error($"SDT_AddOverrideCommand: SDT not found on door to {(e.DimensionIndex, e.Layer, e.LocalIndex)}"); } else { SecDoorTerminal item = levelSDTs[num].sdt; AddOverrideCommandWithAlarmText(item); EOSLogger.Debug($"SDT_AddOverrideCommand: added for SDT {(e.DimensionIndex, e.Layer, e.LocalIndex)}"); } } private SecDoorTerminal BuildSDT_Instantiation(SecurityDoorTerminalDefinition def) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_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_00e5: Expected O, but got Unknown //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_019a: Unknown result type (might be due to invalid IL or missing references) //IL_01dc: Expected I4, but got Unknown var (val, val2, val3) = ((GlobalZoneIndex)def).GlobalZoneIndexTuple(); LG_Zone val4 = default(LG_Zone); if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(val, val2, val3, ref val4) || (Object)(object)val4 == (Object)null) { EOSLogger.Error($"SecDoorTerminal: Cannot find target zone {((GlobalZoneIndex)def).GlobalZoneIndexTuple()}"); return null; } if (!TryGetZoneEntranceSecDoor(val4, out var door) || (Object)(object)door == (Object)null) { EOSLogger.Error($"SecDoorTerminal: Cannot find spawned sec-door for zone {((GlobalZoneIndex)def).GlobalZoneIndexTuple()}"); return null; } SecDoorTerminal sdt = SecDoorTerminal.Place(door, new TerminalStartStateData { StartingState = (TERM_State)0 }, (TerminalPlacementData)null); sdt.BioscanScanSolvedBehaviour = def.StateSettings.OnPuzzleSolved; if (sdt == null) { EOSLogger.Error("Build failed: Can only attach SDT to regular security door"); return null; } ((LG_ZoneExpander)val4.m_sourceGate).m_linksFrom.m_zone.TerminalsSpawnedInZone.Add(sdt.ComputerTerminal); sdt.BioscanScanSolvedBehaviour = def.StateSettings.OnPuzzleSolved; def.TerminalSettings.LocalLogFiles.ForEach(delegate(TerminalLogFileData log) { sdt.ComputerTerminal.AddLocalLog(log, true); }); eDoorStatus status = sdt.LinkedDoor.m_sync.GetCurrentSyncState().status; switch (status - 1) { case 2: if (def.StateSettings.LockedStateSetting.AccessibleWhenLocked) { sdt.LinkedDoorLocks.m_gateKeyItemNeeded.keyPickupCore.m_interact.OnPickedUpByPlayer += Action<PlayerAgent>.op_Implicit((Action<PlayerAgent>)delegate { sdt.SetTerminalActive(false); }); sdt.SetTerminalActive(def.StateSettings.LockedStateSetting.AccessibleWhenLocked); List<string> list4 = new List<string> { string.Format("<color=orange>" + Text.Get(849u) + "</color>", sdt.LinkedDoorLocks.m_gateKeyItemNeeded.PublicName) }; sdt.ComputerTerminal.m_command.AddOutput(ListExtensions.ToIl2Cpp<string>(list4)); } break; case 5: sdt.SetTerminalActive(def.StateSettings.LockedStateSetting.AccessibleWhenLocked); if (def.StateSettings.LockedStateSetting.AccessibleWhenLocked) { List<string> list2 = new List<string> { string.Format("<color=orange>" + Text.Get(842u) + "</color>", sdt.LinkedDoorLocks.m_powerGeneratorNeeded.PublicName) }; sdt.ComputerTerminal.m_command.AddOutput(ListExtensions.ToIl2Cpp<string>(list2)); } break; case 14: sdt.SetTerminalActive(def.StateSettings.LockedStateSetting.AccessibleWhenLocked); if (def.StateSettings.LockedStateSetting.AccessibleWhenLocked) { List<string> list = new List<string> { string.Format("<color=orange>" + Text.Get(843u) + "</color>", sdt.LinkedDoorLocks.m_bulkheadDCNeeded.PublicName) }; sdt.ComputerTerminal.m_command.AddOutput(ListExtensions.ToIl2Cpp<string>(list)); } break; case 6: sdt.SetTerminalActive(def.StateSettings.LockedStateSetting.AccessibleWhenLocked); if (def.StateSettings.LockedStateSetting.AccessibleWhenLocked) { List<string> list3 = new List<string> { sdt.LinkedDoorLocks.m_intCustomMessage.m_message }; sdt.ComputerTerminal.m_command.AddOutput(ListExtensions.ToIl2Cpp<string>(list3)); } else { sdt.SetCustomMessageActive(true); } break; case 0: case 3: case 4: case 8: if (def.StateSettings.OverrideCommandAccessibility != OverrideCmdAccess.ADDED_BY_WARDEN_EVENT) { AddOverrideCommandWithAlarmText(sdt); } sdt.SetTerminalActive(def.StateSettings.LockedStateSetting.AccessibleWhenUnlocked); break; } sdt.LinkedDoor.m_sync.OnDoorStateChange += Action<pDoorState, bool>.op_Implicit((Action<pDoorState, bool>)delegate(pDoorState state, bool isDropin) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Expected I4, but got Unknown //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Invalid comparison between Unknown and I4 eDoorStatus status3 = state.status; switch (status3 - 3) { case 0: case 3: case 4: case 12: sdt.SetTerminalActive(def.StateSettings.LockedStateSetting.AccessibleWhenLocked); if ((int)state.status == 7) { sdt.SetCustomMessageActive(true); } break; case 1: case 2: case 6: sdt.SetTerminalActive(def.StateSettings.LockedStateSetting.AccessibleWhenUnlocked); break; case 5: case 7: case 8: case 9: case 10: case 11: break; } }); switch (def.StateSettings.OverrideCommandAccessibility) { case OverrideCmdAccess.ALWAYS: AddOverrideCommandWithAlarmText(sdt); break; case OverrideCmdAccess.ON_UNLOCK: sdt.LinkedDoor.m_sync.OnDoorStateChange += Action<pDoorState, bool>.op_Implicit((Action<pDoorState, bool>)delegate(pDoorState state, bool isDropin) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Invalid comparison between Unknown and I4 eDoorStatus status2 = state.status; if (status2 - 4 <= 1 || (int)status2 == 9) { AddOverrideCommandWithAlarmText(sdt); } }); break; } return sdt; } public override void Init() { base.Init(); } private void BuildLevelSDTs_Instantiation() { if (!base.definitions.ContainsKey(RundownManager.ActiveExpedition.LevelLayoutData)) { return; } foreach (SecurityDoorTerminalDefinition definition in base.definitions[RundownManager.ActiveExpedition.LevelLayoutData].Definitions) { SecDoorTerminal item = BuildSDT_Instantiation(definition); levelSDTs.Add((item, definition)); } } private void OnLevelCleanup() { levelSDTs.Clear(); } private SecurityDoorTerminalManager() { EOSWardenEventManager.Current.AddEventDefinition(SDTWardenEvents.ADD_OVERRIDE_COMMAND.ToString(), 1000u, (Action<WardenObjectiveEventData>)WardenEvent_AddOverrideCommand); BatchBuildManager.Current.Add_OnBatchDone((BatchName)75, (Action)BuildLevelSDTs_Instantiation); BatchBuildManager.Current.Add_OnBatchDone((BatchName)76, (Action)BuildLevelSDTs_Passwords); LevelAPI.OnBuildDone += BuildLevelSDTs_UniqueCommands; LevelAPI.OnLevelCleanup += OnLevelCleanup; } static SecurityDoorTerminalManager() { Current = new SecurityDoorTerminalManager(); } } } namespace EOSExt.SecurityDoorTerminal.Definition { public enum OverrideCmdAccess { ALWAYS, ON_UNLOCK, ADDED_BY_WARDEN_EVENT } public class SDTStateSetting_Locked { public bool AccessibleWhenLocked { get; set; } public bool AccessibleWhenUnlocked { get; set; } = true; } public class SDTStateSetting { public SDTStateSetting_Locked LockedStateSetting { get; set; } = new SDTStateSetting_Locked(); public OverrideCmdAccess OverrideCommandAccessibility { get; set; } = OverrideCmdAccess.ON_UNLOCK; public CPSolvedBehaviour OnPuzzleSolved { get; set; } = (CPSolvedBehaviour)1; } public class SecurityDoorTerminalDefinition : GlobalZoneIndex { public SDTStateSetting StateSettings { get; set; } = new SDTStateSetting(); public TerminalDefinition TerminalSettings { get; set; } = new TerminalDefinition(); } }
plugins/net6/Inas07.EOSExt.SecuritySensor.dll
Decompiled a month agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using Agents; using BepInEx; using BepInEx.Unity.IL2CPP; using ChainedPuzzles; using EOSExt.SecuritySensor.Component; using EOSExt.SecuritySensor.Definition; using ExtraObjectiveSetup; using ExtraObjectiveSetup.BaseClasses; using ExtraObjectiveSetup.ExtendedWardenEvents; using ExtraObjectiveSetup.Utils; using FloLib.Networks.Replications; using GTFO.API; using GTFO.API.Extensions; using GameData; using HarmonyLib; using Il2CppInterop.Runtime.Injection; using Il2CppInterop.Runtime.InteropTypes; using Il2CppSystem.Collections.Generic; using LevelGeneration; using Microsoft.CodeAnalysis; using Player; using SNetwork; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("Inas07.EOSExt.SecuritySensor")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("Inas07.EOSExt.SecuritySensor")] [assembly: AssemblyTitle("Inas07.EOSExt.SecuritySensor")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace EOSExt.SecuritySensor { internal static class Assets { public static GameObject CircleSensor { get; private set; } public static GameObject MovableSensor { get; private set; } public static void Init() { CircleSensor = AssetAPI.GetLoadedAsset<GameObject>("Assets/SecuritySensor/CircleSensor.prefab"); MovableSensor = AssetAPI.GetLoadedAsset<GameObject>("Assets/SecuritySensor/MovableSensor.prefab"); } } [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInPlugin("Inas.EOSExt.SecuritySensor", "EOSExt.SecuritySensor", "1.1.6")] public class EntryPoint : BasePlugin { public const string AUTHOR = "Inas"; public const string PLUGIN_NAME = "EOSExt.SecuritySensor"; public const string VERSION = "1.1.6"; private Harmony m_Harmony; public override void Load() { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown SetupManagers(); AssetAPI.OnAssetBundlesLoaded += Assets.Init; m_Harmony = new Harmony("EOSExt.SecuritySensor"); m_Harmony.PatchAll(); ClassInjector.RegisterTypeInIl2Cpp<SensorCollider>(); EOSLogger.Log("ExtraObjectiveSetup.SecuritySensor loaded."); } private void SetupManagers() { ((GenericExpeditionDefinitionManager<SensorGroupSettings>)SecuritySensorManager.Current).Init(); } } internal class MovableSensor { public GameObject movableGO { get; private set; } public CP_BasicMovable movingComp { get; private set; } private GameObject graphicsGO { get { GameObject obj = movableGO; if (obj == null) { return null; } return ((Component)obj.transform.GetChild(0)).gameObject; } } public static MovableSensor Instantiate(SensorSettings sensorSetting) { //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0087: 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_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: 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) if (sensorSetting.MovingPosition.Count < 1) { EOSLogger.Error("SensorGroup.Instantiate: At least 1 moving position required to setup T-Sensor!"); return null; } if (EOSNetworking.AllotReplicatorID() == 0) { EOSLogger.Error("SensorGroup.Instantiate: replicator ID depleted, cannot create StateReplicator..."); return null; } MovableSensor movableSensor = new MovableSensor(); movableSensor.movableGO = Object.Instantiate<GameObject>(Assets.MovableSensor); movableSensor.movingComp = movableSensor.movableGO.GetComponent<CP_BasicMovable>(); movableSensor.movingComp.Setup(); Vector3 element = sensorSetting.Position.ToVector3(); Vector3 val = sensorSetting.MovingPosition.First().ToVector3(); Vector3 val2 = sensorSetting.MovingPosition.Last().ToVector3(); IEnumerable<Vector3> source = sensorSetting.MovingPosition.ConvertAll((Vec3 e) => e.ToVector3()).AsEnumerable(); if (!((Vector3)(ref element)).Equals(val)) { source = source.Prepend(element); } if (!((Vector3)(ref element)).Equals(val2)) { source = source.Append(element); } movableSensor.movingComp.ScanPositions = ListExtensions.ToIl2Cpp<Vector3>(source.ToList()); movableSensor.movingComp.m_amountOfPositions = source.Count() - 1; if (sensorSetting.MovingSpeedMulti > 0f) { CP_BasicMovable obj = movableSensor.movingComp; obj.m_movementSpeed *= sensorSetting.MovingSpeedMulti; } return movableSensor; } public void StartMoving() { graphicsGO.SetActive(true); movingComp.SyncUpdate(); movingComp.StartMoving(); } public void ResumeMoving() { graphicsGO.SetActive(true); movingComp.ResumeMovement(); } public void StopMoving() { movingComp.StopMoving(); graphicsGO.SetActive(false); } public void PauseMoving() { movingComp.PauseMovement(); graphicsGO.SetActive(false); } public void Destroy() { Object.Destroy((Object)(object)movableGO); movableGO = null; movingComp = null; } private MovableSensor() { } } public enum SensorEventType { ToggleSensorGroupState = 400 } public sealed class SecuritySensorManager : GenericExpeditionDefinitionManager<SensorGroupSettings> { private List<(SensorGroupSettings settings, SensorGroup sensorGroup)> securitySensorGroups = new List<(SensorGroupSettings, SensorGroup)>(); private Dictionary<IntPtr, int> sensorGroupIndex = new Dictionary<IntPtr, int>(); public static SecuritySensorManager Current { get; private set; } protected override string DEFINITION_NAME => "SecuritySensor"; public void BuildSensorGroup(SensorGroupSettings sensorGroupSettings) { int count = securitySensorGroups.Count; SensorGroup sensorGroup = SensorGroup.Instantiate(sensorGroupSettings, count); securitySensorGroups.Add((sensorGroupSettings, sensorGroup)); foreach (GameObject basicSensor in sensorGroup.BasicSensors) { sensorGroupIndex[((Il2CppObjectBase)basicSensor).Pointer] = count; } foreach (MovableSensor movableSensor in sensorGroup.MovableSensors) { sensorGroupIndex[((Il2CppObjectBase)movableSensor.movableGO).Pointer] = count; } EOSLogger.Debug($"SensorGroup_{count} built"); } internal void TriggerSensor(IntPtr pointer) { if (!sensorGroupIndex.ContainsKey(pointer)) { EOSLogger.Error("Triggering a sensor but doesn't find its corresponding sensor group! This should not happen!"); return; } int num = sensorGroupIndex[pointer]; if (num < 0 || num >= securitySensorGroups.Count) { EOSLogger.Error($"TriggerSensor: invalid SensorGroup index {num}"); return; } (SensorGroupSettings, SensorGroup) tuple = securitySensorGroups[num]; if (tuple.Item2.StateReplicator.State.status == ActiveState.ENABLED) { tuple.Item1.EventsOnTrigger.ForEach(delegate(WardenObjectiveEventData e) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, e.Trigger, true, 0f); }); EOSLogger.Warning($"TriggerSensor: SensorGroup_{num} triggered"); } } private void BuildSecuritySensor() { if (base.definitions.ContainsKey(RundownManager.ActiveExpedition.LevelLayoutData)) { base.definitions[RundownManager.ActiveExpedition.LevelLayoutData].Definitions.ForEach(BuildSensorGroup); } } private void Clear() { securitySensorGroups.ForEach(delegate((SensorGroupSettings settings, SensorGroup sensorGroup) builtSensorGroup) { builtSensorGroup.sensorGroup.Destroy(); }); securitySensorGroups.Clear(); sensorGroupIndex.Clear(); } private void ToggleSensorGroup(WardenObjectiveEventData e) { int count = e.Count; bool enabled = e.Enabled; if (count < 0 || count >= securitySensorGroups.Count) { EOSLogger.Error($"ToggleSensorGroup: invalid SensorGroup index {count}"); } else { securitySensorGroups[count].sensorGroup.ChangeState(enabled ? ActiveState.ENABLED : ActiveState.DISABLED); } } private SecuritySensorManager() { LevelAPI.OnBuildStart += delegate { Clear(); BuildSecuritySensor(); }; LevelAPI.OnLevelCleanup += Clear; EventAPI.OnExpeditionStarted += delegate { securitySensorGroups.ForEach(delegate((SensorGroupSettings settings, SensorGroup sensorGroup) tuple) { tuple.sensorGroup.StartMovingMovables(); }); }; EOSWardenEventManager.Current.AddEventDefinition(SensorEventType.ToggleSensorGroupState.ToString(), 400u, (Action<WardenObjectiveEventData>)ToggleSensorGroup); } static SecuritySensorManager() { Current = new SecuritySensorManager(); } } internal class SensorGroup { private List<GameObject> basicSensors = new List<GameObject>(); private List<MovableSensor> movableSensors = new List<MovableSensor>(); public int sensorGroupIndex { get; private set; } public StateReplicator<SensorGroupState> StateReplicator { get; private set; } public IEnumerable<GameObject> BasicSensors => basicSensors; public IEnumerable<MovableSensor> MovableSensors => movableSensors; public void ChangeState(ActiveState status) { ChangeToStateUnsynced(new SensorGroupState { status = status }); EOSLogger.Debug($"ChangeState: SecuritySensorGroup_{sensorGroupIndex} changed to state {status}"); if (SNet.IsMaster) { StateReplicator.SetState(new SensorGroupState { status = status }); } } private void OnStateChanged(SensorGroupState oldState, SensorGroupState newState, bool isRecall) { EOSLogger.Warning($"OnStateChanged: isRecall ? {isRecall}"); if (isRecall) { EOSLogger.Debug($"Recalling: SecuritySensorGroup_{sensorGroupIndex} changed to state {newState.status}"); ChangeToStateUnsynced(newState); } } private void ChangeToStateUnsynced(SensorGroupState newState) { switch (newState.status) { case ActiveState.ENABLED: basicSensors.ForEach(delegate(GameObject sensorGO) { sensorGO.SetActiveRecursively(true); }); ResumeMovingMovables(); break; case ActiveState.DISABLED: PauseMovingMovables(); basicSensors.ForEach(delegate(GameObject sensorGO) { sensorGO.SetActiveRecursively(false); }); break; } } public static SensorGroup Instantiate(SensorGroupSettings sensorGroupSettings, int sensorGroupIndex) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0033: 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_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) SensorGroup sensorGroup = new SensorGroup(); sensorGroup.sensorGroupIndex = sensorGroupIndex; foreach (SensorSettings item in sensorGroupSettings.SensorGroup) { Vector3 val = item.Position.ToVector3(); if (val == Vector3.zeroVector) { continue; } GameObject val2 = null; switch (item.SensorType) { case SensorType.BASIC: val2 = Object.Instantiate<GameObject>(Assets.CircleSensor); sensorGroup.basicSensors.Add(val2); break; case SensorType.MOVABLE: { MovableSensor movableSensor = MovableSensor.Instantiate(item); if (movableSensor == null) { EOSLogger.Error("ERROR: failed to build movable sensor"); continue; } val2 = movableSensor.movableGO; sensorGroup.movableSensors.Add(movableSensor); break; } default: EOSLogger.Error($"Unsupported SensorType {item.SensorType}, skipped"); continue; } val2.transform.SetPositionAndRotation(val, Quaternion.identityQuaternion); float num = 0.16216217f; val2.transform.localScale = new Vector3(item.Radius, item.Radius, item.Radius); Transform transform = val2.transform; transform.localPosition += Vector3.up * num; val2.AddComponent<SensorCollider>().Setup(item); val2.SetActive(true); } uint num2 = EOSNetworking.AllotReplicatorID(); if (num2 == 0) { EOSLogger.Error("SensorGroup.Instantiate: replicator ID depleted, cannot create StateReplicator..."); } else { sensorGroup.StateReplicator = StateReplicator<SensorGroupState>.Create(num2, new SensorGroupState { status = ActiveState.ENABLED }, (LifeTimeType)1, (IStateReplicatorHolder<SensorGroupState>)null); sensorGroup.StateReplicator.OnStateChanged += sensorGroup.OnStateChanged; } return sensorGroup; } public void StartMovingMovables() { movableSensors.ForEach(delegate(MovableSensor movable) { movable.StartMoving(); }); } public void PauseMovingMovables() { movableSensors.ForEach(delegate(MovableSensor movable) { movable.PauseMoving(); }); } public void ResumeMovingMovables() { movableSensors.ForEach(delegate(MovableSensor movable) { movable.ResumeMoving(); }); } public void Destroy() { basicSensors.ForEach((Action<GameObject>)Object.Destroy); basicSensors.Clear(); movableSensors.ForEach(delegate(MovableSensor m) { m.Destroy(); }); movableSensors.Clear(); StateReplicator = null; } private SensorGroup() { } } public enum ActiveState { DISABLED, ENABLED } public struct SensorGroupState { public ActiveState status; public SensorGroupState() { status = ActiveState.DISABLED; } public SensorGroupState(SensorGroupState o) { status = o.status; } public SensorGroupState(ActiveState status) { this.status = status; } } public struct MovableSensorLerp { public float lerp; public MovableSensorLerp() { lerp = 0f; } public MovableSensorLerp(MovableSensorLerp o) { lerp = o.lerp; } public MovableSensorLerp(float lerp) { this.lerp = lerp; } } } namespace EOSExt.SecuritySensor.Component { public class SensorCollider : MonoBehaviour { private float nextCheckTime = float.NaN; private SensorSettings sensorSettings; private int last_playersInSensor; public static float CHECK_INTERVAL { get; } = 0.1f; private Vector3 Position => ((Component)this).gameObject.transform.position; internal void Setup(SensorSettings sensorSettings) { this.sensorSettings = sensorSettings; } private void Update() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: 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) if ((int)GameStateManager.CurrentStateName != 10 || (!float.IsNaN(nextCheckTime) && Clock.Time < nextCheckTime)) { return; } nextCheckTime = Clock.Time + CHECK_INTERVAL; int num = 0; Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator(); while (enumerator.MoveNext()) { PlayerAgent current = enumerator.Current; if (!current.Owner.IsBot && ((Agent)current).Alive) { Vector3 val = Position - ((Agent)current).Position; if (((Vector3)(ref val)).magnitude < sensorSettings.Radius) { num++; } } } if (num > last_playersInSensor) { SecuritySensorManager.Current.TriggerSensor(((Il2CppObjectBase)((Component)this).gameObject).Pointer); } last_playersInSensor = num; } } } namespace EOSExt.SecuritySensor.Patches { [HarmonyPatch] internal class Debug { [HarmonyPostfix] [HarmonyPatch(typeof(LG_CollisionWorldEventTrigger), "Update")] private static void Post(LG_CollisionWorldEventTrigger __instance) { } static Debug() { } } } namespace EOSExt.SecuritySensor.Definition { public class SensorColor { public float r { get; set; } public float g { get; set; } public float b { get; set; } public float a { get; set; } public Color toColor() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) return new Color(r, g, b, a); } } public class SensorGroupSettings { public List<SensorSettings> SensorGroup { get; set; } = new List<SensorSettings> { new SensorSettings() }; public List<WardenObjectiveEventData> EventsOnTrigger { get; set; } = new List<WardenObjectiveEventData>(); } public enum SensorType { BASIC, MOVABLE } public class SensorSettings { public Vec3 Position { get; set; } = new Vec3(); public float Radius { get; set; } = 2.3f; public SensorType SensorType { get; set; } public float MovingSpeedMulti { get; set; } = 1f; public List<Vec3> MovingPosition { get; set; } = new List<Vec3> { new Vec3() }; } }
plugins/net6/Inas07.ExtraObjectiveSetup.dll
Decompiled a month 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.Immutable; 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.Json; using System.Text.Json.Serialization; using AIGraph; using AK; using Agents; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using BepInEx.Unity.IL2CPP.Utils.Collections; using ChainedPuzzles; using Enemies; using ExtraObjectiveSetup.BaseClasses; using ExtraObjectiveSetup.BaseClasses.CustomTerminalDefinition; using ExtraObjectiveSetup.Expedition; using ExtraObjectiveSetup.Expedition.Gears; using ExtraObjectiveSetup.Expedition.IndividualGeneratorGroup; using ExtraObjectiveSetup.ExtendedWardenEvents; using ExtraObjectiveSetup.Instances; using ExtraObjectiveSetup.Instances.ChainedPuzzle; using ExtraObjectiveSetup.JSON; using ExtraObjectiveSetup.Objectives.ActivateSmallHSU; using ExtraObjectiveSetup.Objectives.GeneratorCluster; using ExtraObjectiveSetup.Objectives.IndividualGenerator; using ExtraObjectiveSetup.Objectives.ObjectiveCounter; using ExtraObjectiveSetup.Objectives.TerminalUplink; using ExtraObjectiveSetup.Tweaks.BossEvents; using ExtraObjectiveSetup.Tweaks.Scout; using ExtraObjectiveSetup.Tweaks.TerminalPosition; using ExtraObjectiveSetup.Tweaks.TerminalTweak; using ExtraObjectiveSetup.Utils; using FloLib.Networks.Replications; using GTFO.API; using GTFO.API.Extensions; using GTFO.API.JSON.Converters; using GTFO.API.Utilities; using GameData; using Gear; using HarmonyLib; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.InteropTypes.Arrays; using Il2CppSystem; using Il2CppSystem.Collections.Generic; using LevelGeneration; using Localization; using MTFO.API; using Microsoft.CodeAnalysis; using Player; using SNetwork; using StateMachines; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("Inas07.ExtraObjectiveSetup")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("Inas07.ExtraObjectiveSetup")] [assembly: AssemblyTitle("Inas07.ExtraObjectiveSetup")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ExtraObjectiveSetup { public static class EOSNetworking { public const uint INVALID_ID = 0u; public const uint FOREVER_REPLICATOR_ID_START = 1000u; public const uint REPLICATOR_ID_START = 10000u; private static uint currentForeverID; private static uint currentID; private static HashSet<uint> foreverUsedIDs; private static HashSet<uint> usedIDs; public static uint AllotReplicatorID() { while (currentID >= 10000 && usedIDs.Contains(currentID)) { currentID++; } if (currentID < 10000) { EOSLogger.Error("Replicator ID depleted. How?"); return 0u; } uint num = currentID; usedIDs.Add(num); currentID++; return num; } public static bool TryAllotID(uint id) { return usedIDs.Add(id); } public static uint AllotForeverReplicatorID() { while (currentForeverID < 10000 && foreverUsedIDs.Contains(currentForeverID)) { currentForeverID++; } if (currentForeverID >= 10000) { EOSLogger.Error("Forever Replicator ID depleted."); return 0u; } uint num = currentForeverID; foreverUsedIDs.Add(num); currentForeverID++; return num; } private static void Clear() { usedIDs.Clear(); currentID = 10000u; } public static void ClearForever() { foreverUsedIDs.Clear(); currentForeverID = 1000u; } static EOSNetworking() { currentForeverID = 1000u; currentID = 10000u; foreverUsedIDs = new HashSet<uint>(); usedIDs = new HashSet<uint>(); LevelAPI.OnBuildStart += Clear; LevelAPI.OnLevelCleanup += Clear; } } public sealed class BatchBuildManager { private Dictionary<BatchName, Action> OnBatchDone = new Dictionary<BatchName, Action>(); public static BatchBuildManager Current { get; private set; } public void Init() { //IL_0034: Unknown result type (might be due to invalid IL or missing references) if (OnBatchDone.Count > 0) { return; } foreach (object value in Enum.GetValues(typeof(BatchName))) { OnBatchDone[(BatchName)value] = null; } } public void Add_OnBatchDone(BatchName batchName, Action action) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) Dictionary<BatchName, Action> onBatchDone = OnBatchDone; onBatchDone[batchName] = (Action)Delegate.Combine(onBatchDone[batchName], action); } public void Remove_OnBatchDone(BatchName batchName, Action action) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) Dictionary<BatchName, Action> onBatchDone = OnBatchDone; onBatchDone[batchName] = (Action)Delegate.Remove(onBatchDone[batchName], action); } public Action Get_OnBatchDone(BatchName batchName) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return OnBatchDone[batchName]; } private BatchBuildManager() { } static BatchBuildManager() { Current = new BatchBuildManager(); } } [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInPlugin("Inas.ExtraObjectiveSetup", "ExtraObjectiveSetup", "1.6.3")] public class EntryPoint : BasePlugin { public const string AUTHOR = "Inas"; public const string PLUGIN_NAME = "ExtraObjectiveSetup"; public const string VERSION = "1.6.3"; private Harmony m_Harmony; public override void Load() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown m_Harmony = new Harmony("ExtraObjectiveSetup"); m_Harmony.PatchAll(); SetupManagers(); } private void SetupManagers() { BatchBuildManager.Current.Init(); IndividualGeneratorObjectiveManager.Current.Init(); GeneratorClusterObjectiveManager.Current.Init(); HSUActivatorObjectiveManager.Current.Init(); UplinkObjectiveManager.Current.Init(); TerminalPositionOverrideManager.Current.Init(); ScoutScreamEventManager.Current.Init(); BossDeathEventManager.Current.Init(); ExpeditionDefinitionManager.Current.Init(); ExpeditionGearManager.Current.Init(); ExpeditionIGGroupManager.Current.Init(); GeneratorClusterInstanceManager.Current.Init(); HSUActivatorInstanceManager.Current.Init(); PowerGeneratorInstanceManager.Current.Init(); TerminalInstanceManager.Current.Init(); ObjectiveCounterManager.Current.Init(); } } } namespace ExtraObjectiveSetup.Utils { public static class EOSTerminalUtils { public static List<LG_ComputerTerminal> FindTerminal(eDimensionIndex dimensionIndex, LG_LayerType layerType, eLocalZoneIndex localIndex, Predicate<LG_ComputerTerminal> predicate) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: 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_0033: 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_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) LG_Zone val = default(LG_Zone); if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(dimensionIndex, layerType, localIndex, ref val) || (Object)(object)val == (Object)null) { EOSLogger.Error($"SelectTerminal: Could NOT find zone {(dimensionIndex, layerType, localIndex)}"); return null; } if (val.TerminalsSpawnedInZone.Count <= 0) { EOSLogger.Error($"SelectTerminal: Could not find any terminals in zone {(dimensionIndex, layerType, localIndex)}"); return null; } List<LG_ComputerTerminal> list = new List<LG_ComputerTerminal>(); Enumerator<LG_ComputerTerminal> enumerator = val.TerminalsSpawnedInZone.GetEnumerator(); while (enumerator.MoveNext()) { LG_ComputerTerminal current = enumerator.Current; if (predicate != null) { if (predicate(current)) { list.Add(current); } } else { list.Add(current); } } return list; } public static TerminalLogFileData GetLocalLog(this LG_ComputerTerminal terminal, string logName) { Dictionary<string, TerminalLogFileData> localLogs = terminal.GetLocalLogs(); logName = logName.ToUpperInvariant(); if (!localLogs.ContainsKey(logName)) { return null; } return localLogs[logName]; } public static void ResetInitialOutput(this LG_ComputerTerminal terminal) { terminal.m_command.ClearOutputQueueAndScreenBuffer(); terminal.m_command.AddInitialTerminalOutput(); if (terminal.IsPasswordProtected) { terminal.m_command.AddPasswordProtectedOutput((Il2CppStringArray)null); } } public static List<WardenObjectiveEventData> GetUniqueCommandEvents(this LG_ComputerTerminal terminal, string command) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Expected I4, but got Unknown //IL_0100: 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_0091: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) List<WardenObjectiveEventData> result = new List<WardenObjectiveEventData>(); if ((Object)(object)terminal.ConnectedReactor != (Object)null) { return result; } uint num = 0u; if (terminal.SpawnNode.m_dimension.IsMainDimension) { LG_LayerType layerType = terminal.SpawnNode.LayerType; switch ((int)layerType) { case 0: num = RundownManager.ActiveExpedition.LevelLayoutData; break; case 1: num = RundownManager.ActiveExpedition.SecondaryLayout; break; case 2: num = RundownManager.ActiveExpedition.ThirdLayout; break; default: EOSLogger.Error($"GetCommandEvents: Unimplemented layer type {terminal.SpawnNode.LayerType}"); return result; } } else { num = terminal.SpawnNode.m_dimension.DimensionData.LevelLayoutData; } LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock(num); if (block == null) { EOSLogger.Error($"GetCommandEvents: {terminal.ItemKey} is in {terminal.SpawnNode.LayerType}, {terminal.SpawnNode.m_dimension.DimensionIndex} but its LevelLayoutData is not found!"); return result; } int num2 = terminal.SpawnNode.m_zone.TerminalsSpawnedInZone.IndexOf(terminal); ExpeditionZoneData val = null; Enumerator<ExpeditionZoneData> enumerator = block.Zones.GetEnumerator(); while (enumerator.MoveNext()) { ExpeditionZoneData current = enumerator.Current; if (current.LocalIndex == terminal.SpawnNode.m_zone.LocalIndex) { val = current; break; } } if (val == null) { EOSLogger.Error("GetCommandEvents: Cannot find target zone data."); return result; } if (num2 >= val.TerminalPlacements.Count) { EOSLogger.Debug("GetCommandEvents: TerminalDataIndex >= TargetZoneData.TerminalPlacements.Count: found a custom terminal, skipped"); return result; } Enumerator<CustomTerminalCommand> enumerator2 = val.TerminalPlacements[num2].UniqueCommands.GetEnumerator(); while (enumerator2.MoveNext()) { CustomTerminalCommand current2 = enumerator2.Current; if (current2.Command.ToLower().Equals(command.ToLower())) { return current2.CommandEvents.ToManaged<WardenObjectiveEventData>(); } } EOSLogger.Error("GetCommandEvents: command '" + command + "' not found on " + terminal.ItemKey); return result; } public static LG_ComputerTerminal SelectPasswordTerminal(eDimensionIndex dimensionIndex, LG_LayerType layerType, eLocalZoneIndex localIndex, eSeedType seedType, int staticSeed = 1) { //IL_0000: 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_0030: 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_001b: 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_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Expected I4, but got Unknown //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: 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_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) if ((int)seedType == 0) { EOSLogger.Error($"SelectTerminal: unsupported seed type {seedType}"); return null; } List<LG_ComputerTerminal> list = FindTerminal(dimensionIndex, layerType, localIndex, (LG_ComputerTerminal x) => !x.HasPasswordPart); if (list == null) { EOSLogger.Error($"SelectTerminal: Could not find zone {(dimensionIndex, layerType, localIndex)}!"); return null; } if (list.Count <= 0) { EOSLogger.Error($"SelectTerminal: Could not find any terminals without a password part in zone {(dimensionIndex, layerType, localIndex)}, putting the password on random (session) already used terminal."); LG_Zone val = default(LG_Zone); Builder.CurrentFloor.TryGetZoneByLocalIndex(dimensionIndex, layerType, localIndex, ref val); return val.TerminalsSpawnedInZone[Builder.SessionSeedRandom.Range(0, val.TerminalsSpawnedInZone.Count, "NO_TAG")]; } switch (seedType - 1) { case 0: return list[Builder.SessionSeedRandom.Range(0, list.Count, "NO_TAG")]; case 1: return list[Builder.BuildSeedRandom.Range(0, list.Count, "NO_TAG")]; case 2: Random.InitState(staticSeed); return list[Random.Range(0, list.Count)]; default: EOSLogger.Error("SelectTerminal: did not have a valid SeedType!!"); return null; } } public static void BuildPassword(LG_ComputerTerminal terminal, TerminalPasswordData data) { //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_02c8: Unknown result type (might be due to invalid IL or missing references) //IL_02cf: Unknown result type (might be due to invalid IL or missing references) //IL_02d6: Unknown result type (might be due to invalid IL or missing references) //IL_02dd: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_01f9: Unknown result type (might be due to invalid IL or missing references) //IL_0200: Unknown result type (might be due to invalid IL or missing references) //IL_0427: Unknown result type (might be due to invalid IL or missing references) //IL_042c: Unknown result type (might be due to invalid IL or missing references) //IL_0498: Unknown result type (might be due to invalid IL or missing references) //IL_0499: Unknown result type (might be due to invalid IL or missing references) //IL_049e: Unknown result type (might be due to invalid IL or missing references) //IL_04c0: Unknown result type (might be due to invalid IL or missing references) //IL_04cc: Expected O, but got Unknown //IL_04ce: Expected O, but got Unknown if (!data.PasswordProtected) { return; } if (terminal.IsPasswordProtected) { EOSLogger.Error("EOSTerminalUtils.BuildPassword: " + terminal.PublicName + " is already password-protected!"); return; } if (!data.GeneratePassword) { terminal.LockWithPassword(data.Password, new string[1] { data.PasswordHintText }); return; } if (data.TerminalZoneSelectionDatas.Count <= 0) { EOSLogger.Error($"Tried to generate a password for terminal {terminal.PublicName} with no {typeof(TerminalZoneSelectionData).Name}!! This is not allowed."); return; } string codeWord = SerialGenerator.GetCodeWord(); string passwordHintText = data.PasswordHintText; string text = "<b>[Forgot your password?]</b> Backup security key(s) located in logs on "; int num = data.PasswordPartCount; if (codeWord.Length % num != 0) { EOSLogger.Error($"Build() password.Length ({codeWord.Length}) not divisible by passwordParts ({num}). Defaulting to 1."); num = 1; } string[] array = ((num > 1) ? Il2CppArrayBase<string>.op_Implicit((Il2CppArrayBase<string>)(object)StringUtils.SplitIntoChunksArray(codeWord, codeWord.Length / num)) : new string[1] { codeWord }); string text2 = ""; if (data.ShowPasswordPartPositions) { for (int i = 0; i < array[0].Length; i++) { text2 += "-"; } } HashSet<LG_ComputerTerminal> hashSet = new HashSet<LG_ComputerTerminal>(); LG_Zone val = default(LG_Zone); for (int j = 0; j < num; j++) { int index = j % data.TerminalZoneSelectionDatas.Count; List<CustomTerminalZoneSelectionData> list = data.TerminalZoneSelectionDatas[index]; int index2 = Builder.SessionSeedRandom.Range(0, list.Count, "NO_TAG"); CustomTerminalZoneSelectionData customTerminalZoneSelectionData = list[index2]; LG_ComputerTerminal val2; if ((int)customTerminalZoneSelectionData.SeedType == 0) { if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(customTerminalZoneSelectionData.DimensionIndex, customTerminalZoneSelectionData.LayerType, customTerminalZoneSelectionData.LocalIndex, ref val) || (Object)(object)val == (Object)null) { EOSLogger.Error($"BuildPassword: seedType {0} specified but cannot find zone {customTerminalZoneSelectionData.GlobalZoneIndexTuple()}"); } if (val.TerminalsSpawnedInZone.Count <= 0) { EOSLogger.Error($"BuildPassword: seedType {0} specified but cannot find terminal zone {customTerminalZoneSelectionData.GlobalZoneIndexTuple()}"); } val2 = val.TerminalsSpawnedInZone[customTerminalZoneSelectionData.TerminalIndex]; } else { val2 = SelectPasswordTerminal(customTerminalZoneSelectionData.DimensionIndex, customTerminalZoneSelectionData.LayerType, customTerminalZoneSelectionData.LocalIndex, customTerminalZoneSelectionData.SeedType); } if ((Object)(object)val2 == (Object)null) { EOSLogger.Error($"BuildPassword: CRITICAL ERROR, could not get a LG_ComputerTerminal for password part ({j + 1}/{num}) for {terminal.PublicName} backup log."); continue; } string text3 = ""; string text4; if (data.ShowPasswordPartPositions) { for (int k = 0; k < j; k++) { text3 += text2; } text4 = text3 + array[j]; for (int l = j; l < num - 1; l++) { text4 += text2; } } else { text4 = array[j]; } string value = (data.ShowPasswordPartPositions ? $"0{j + 1}" : $"0{Builder.SessionSeedRandom.Range(0, 9, "NO_TAG")}"); TerminalLogFileData val3 = new TerminalLogFileData { FileName = $"key{value}_{LG_TerminalPasswordLinkerJob.GetTerminalNumber(terminal)}{(val2.HasPasswordPart ? "_1" : "")}.LOG", FileContent = new LocalizedText { UntranslatedText = string.Format(Text.Get((num > 1) ? 1431221909u : 2260297836u), text4), Id = 0u } }; val2.AddLocalLog(val3, true); if (!hashSet.Contains(val2)) { if (j > 0) { text += ", "; } text = text + val2.PublicName + " in " + val2.SpawnNode.m_zone.AliasName; } hashSet.Add(val2); val2.HasPasswordPart = true; } string text5 = text + "."; if (data.ShowPasswordLength) { terminal.LockWithPassword(codeWord, new string[3] { passwordHintText, text5, "Char[" + codeWord.Length + "]" }); } else { terminal.LockWithPassword(codeWord, new string[2] { passwordHintText, text5 }); } } public static void AddUniqueCommand(LG_ComputerTerminal terminal, CustomCommand cmd) { //IL_0053: 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_0141: Unknown result type (might be due to invalid IL or missing references) //IL_019f: Unknown result type (might be due to invalid IL or missing references) if (terminal.m_command.m_commandsPerString.ContainsKey(cmd.Command)) { EOSLogger.Error("Duplicate command name: '" + cmd.Command + "', cannot add command"); return; } TERM_Command val = default(TERM_Command); if (!terminal.m_command.TryGetUniqueCommandSlot(ref val)) { EOSLogger.Error("Cannot get more unique command slot, max: 5"); return; } terminal.m_command.AddCommand(val, cmd.Command, cmd.CommandDesc, cmd.SpecialCommandRule, ListExtensions.ToIl2Cpp<WardenObjectiveEventData>(cmd.CommandEvents), ListExtensions.ToIl2Cpp<TerminalOutput>(cmd.PostCommandOutputs)); for (int i = 0; i < cmd.CommandEvents.Count; i++) { WardenObjectiveEventData val2 = cmd.CommandEvents[i]; if (val2.ChainPuzzle == 0) { continue; } ChainedPuzzleDataBlock block = GameDataBlockBase<ChainedPuzzleDataBlock>.GetBlock(val2.ChainPuzzle); if (block == null) { continue; } LG_Area val3; Transform val4; if (terminal.SpawnNode != null) { val3 = terminal.SpawnNode.m_area; val4 = terminal.m_wardenObjectiveSecurityScanAlign; } else { LG_WardenObjective_Reactor connectedReactor = terminal.ConnectedReactor; object obj; if (connectedReactor == null) { obj = null; } else { AIG_CourseNode spawnNode = connectedReactor.SpawnNode; obj = ((spawnNode != null) ? spawnNode.m_area : null); } if (obj == null) { obj = null; } val3 = (LG_Area)obj; LG_WardenObjective_Reactor connectedReactor2 = terminal.ConnectedReactor; val4 = ((connectedReactor2 != null) ? connectedReactor2.m_chainedPuzzleAlign : null) ?? null; } if ((Object)(object)val3 == (Object)null) { EOSLogger.Error("Terminal Source Area is not found! Cannot create chained puzzle for command " + cmd.Command + "!"); continue; } ChainedPuzzleInstance val5 = ChainedPuzzleManager.CreatePuzzleInstance(block, val3, val4.position, val4, val2.UseStaticBioscanPoints); List<WardenObjectiveEventData> events = ListExtensions.ToIl2Cpp<WardenObjectiveEventData>(cmd.CommandEvents.GetRange(i, cmd.CommandEvents.Count - i)); val5.OnPuzzleSolved += Action.op_Implicit((Action)delegate { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(events, (eWardenObjectiveEventTrigger)0, true, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null); }); terminal.SetChainPuzzleForCommand(val, i, val5); } } } public static class EOSUtils { public static List<T> ToManaged<T>(this List<T> il2cppList) { List<T> list = new List<T>(); Enumerator<T> enumerator = il2cppList.GetEnumerator(); while (enumerator.MoveNext()) { T current = enumerator.Current; list.Add(current); } return list; } public static void ResetProgress(this ChainedPuzzleInstance chainedPuzzle) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected O, but got Unknown //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_0065: 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_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009b: 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_00a9: Unknown result type (might be due to invalid IL or missing references) if (chainedPuzzle.Data.DisableSurvivalWaveOnComplete) { chainedPuzzle.m_sound = new CellSoundPlayer(chainedPuzzle.m_parent.position); } foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)chainedPuzzle.m_chainedPuzzleCores) { ResetChild(item); } if (SNet.IsMaster) { pChainedPuzzleState state = chainedPuzzle.m_stateReplicator.State; pChainedPuzzleState val = default(pChainedPuzzleState); val.status = (eChainedPuzzleStatus)0; val.currentSurvivalWave_EventID = state.currentSurvivalWave_EventID; val.isSolved = false; val.isActive = false; pChainedPuzzleState val2 = val; chainedPuzzle.m_stateReplicator.InteractWithState(val2, new pChainedPuzzleInteraction { type = (eChainedPuzzleInteraction)2 }); } static void ResetChild(iChainedPuzzleCore ICore) { CP_Bioscan_Core val3 = ((Il2CppObjectBase)ICore).TryCast<CP_Bioscan_Core>(); if ((Object)(object)val3 != (Object)null) { ((Il2CppObjectBase)val3.m_spline).Cast<CP_Holopath_Spline>(); ((Il2CppObjectBase)val3.PlayerScanner).Cast<CP_PlayerScanner>().ResetScanProgression(0f); val3.Deactivate(); } else { CP_Cluster_Core val4 = ((Il2CppObjectBase)ICore).TryCast<CP_Cluster_Core>(); if ((Object)(object)val4 == (Object)null) { EOSLogger.Error("ResetChild: found iChainedPuzzleCore that is neither CP_Bioscan_Core nor CP_Cluster_Core..."); } else { ((Il2CppObjectBase)val4.m_spline).Cast<CP_Holopath_Spline>(); foreach (iChainedPuzzleCore item2 in (Il2CppArrayBase<iChainedPuzzleCore>)(object)val4.m_childCores) { ResetChild(item2); } val4.Deactivate(); } } } } } public class EOSColor { public float r { get; set; } public float g { get; set; } public float b { get; set; } public float a { get; set; } = 1f; public Color ToUnityColor() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) return new Color(r, g, b, a); } } public class Vec4 : Vec3 { [JsonPropertyOrder(-9)] public float w { get; set; } public Vector4 ToVector4() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) return new Vector4(base.x, base.y, base.z, w); } } public class Vec3 { [JsonPropertyOrder(-10)] public float x { get; set; } [JsonPropertyOrder(-10)] public float y { get; set; } [JsonPropertyOrder(-10)] public float z { get; set; } public Vector3 ToVector3() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) return new Vector3(x, y, z); } public Quaternion ToQuaternion() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) return Quaternion.Euler(x, y, z); } } public static class EOSLogger { private static ManualLogSource logger = Logger.CreateLogSource("ExtraObjectiveSetup"); public static void Log(string format, params object[] args) { Log(string.Format(format, args)); } public static void Log(string str) { if (logger != null) { logger.Log((LogLevel)8, (object)str); } } public static void Warning(string format, params object[] args) { Warning(string.Format(format, args)); } public static void Warning(string str) { if (logger != null) { logger.Log((LogLevel)4, (object)str); } } public static void Error(string format, params object[] args) { Error(string.Format(format, args)); } public static void Error(string str) { if (logger != null) { logger.Log((LogLevel)2, (object)str); } } public static void Debug(string format, params object[] args) { Debug(string.Format(format, args)); } public static void Debug(string str) { if (logger != null) { logger.Log((LogLevel)32, (object)str); } } } } namespace ExtraObjectiveSetup.Tweaks.TerminalTweak { public struct TerminalState { public bool Enabled; public TerminalState() { Enabled = true; } public TerminalState(bool Enabled) { this.Enabled = true; this.Enabled = Enabled; } public TerminalState(TerminalState o) { Enabled = true; Enabled = o.Enabled; } } public class TerminalWrapper { public LG_ComputerTerminal lgTerminal { get; private set; } public StateReplicator<TerminalState> stateReplicator { get; private set; } private void ChangeStateUnsynced(bool enabled) { EOSLogger.Debug($"{lgTerminal.ItemKey} state, enabled: {enabled}"); lgTerminal.OnProximityExit(); Interact_ComputerTerminal componentInChildren = ((Component)lgTerminal).GetComponentInChildren<Interact_ComputerTerminal>(true); bool flag = enabled; if ((Object)(object)componentInChildren != (Object)null) { ((Behaviour)componentInChildren).enabled = flag; ((Interact_Base)componentInChildren).SetActive(flag); } lgTerminal.m_interfaceScreen.SetActive(flag); lgTerminal.m_loginScreen.SetActive(flag); if ((Object)(object)lgTerminal.m_text != (Object)null) { ((Behaviour)lgTerminal.m_text).enabled = flag; } if (!flag) { PlayerAgent localInteractionSource = lgTerminal.m_localInteractionSource; if ((Object)(object)localInteractionSource != (Object)null && localInteractionSource.FPItemHolder.InTerminalTrigger) { lgTerminal.ExitFPSView(); } } } public void ChangeState(bool enabled) { ChangeStateUnsynced(enabled); if (SNet.IsMaster) { stateReplicator.SetState(new TerminalState { Enabled = enabled }); } } private void OnStateChanged(TerminalState oldState, TerminalState newState, bool isRecall) { if (isRecall) { ChangeStateUnsynced(newState.Enabled); } } public static TerminalWrapper Instantiate(LG_ComputerTerminal lgTerminal, uint replicatorID) { if ((Object)(object)lgTerminal == (Object)null || replicatorID == 0) { return null; } TerminalWrapper terminalWrapper = new TerminalWrapper(); terminalWrapper.lgTerminal = lgTerminal; terminalWrapper.stateReplicator = StateReplicator<TerminalState>.Create(replicatorID, new TerminalState { Enabled = true }, (LifeTimeType)1, (IStateReplicatorHolder<TerminalState>)null); terminalWrapper.stateReplicator.OnStateChanged += terminalWrapper.OnStateChanged; return terminalWrapper; } private TerminalWrapper() { } } } namespace ExtraObjectiveSetup.Tweaks.TerminalPosition { public class TerminalPosition : BaseInstanceDefinition { public Vec3 Position { get; set; } = new Vec3(); public Vec3 Rotation { get; set; } = new Vec3(); } internal class TerminalPositionOverrideManager : InstanceDefinitionManager<TerminalPosition> { public static TerminalPositionOverrideManager Current; protected override string DEFINITION_NAME => "TerminalPosition"; private TerminalPositionOverrideManager() { } static TerminalPositionOverrideManager() { Current = new TerminalPositionOverrideManager(); } } } namespace ExtraObjectiveSetup.Tweaks.Scout { public class EventsOnZoneScoutScream : GlobalZoneIndex { public bool SuppressVanillaScoutWave { get; set; } public List<WardenObjectiveEventData> EventsOnScoutScream { get; set; } = new List<WardenObjectiveEventData>(); } internal class ScoutScreamEventManager : ZoneDefinitionManager<EventsOnZoneScoutScream> { public static ScoutScreamEventManager Current; protected override string DEFINITION_NAME => "EventsOnScoutScream"; private ScoutScreamEventManager() { } static ScoutScreamEventManager() { Current = new ScoutScreamEventManager(); } } } namespace ExtraObjectiveSetup.Tweaks.BossEvents { public struct FiniteBDEState { public int ApplyToHibernateCount; public int ApplyToWaveCount; public FiniteBDEState() { ApplyToHibernateCount = int.MaxValue; ApplyToWaveCount = int.MaxValue; } public FiniteBDEState(FiniteBDEState other) { ApplyToHibernateCount = int.MaxValue; ApplyToWaveCount = int.MaxValue; ApplyToHibernateCount = other.ApplyToHibernateCount; ApplyToHibernateCount = other.ApplyToWaveCount; } public FiniteBDEState(int ApplyToHibernateCount, int ApplyToWaveCount) { this.ApplyToHibernateCount = int.MaxValue; this.ApplyToWaveCount = int.MaxValue; this.ApplyToHibernateCount = ApplyToHibernateCount; this.ApplyToWaveCount = ApplyToWaveCount; } } public class EventsOnZoneBossDeath : GlobalZoneIndex { public bool ApplyToHibernate { get; set; } = true; public int ApplyToHibernateCount { get; set; } = int.MaxValue; public bool ApplyToWave { get; set; } public int ApplyToWaveCount { get; set; } = int.MaxValue; public List<uint> BossIDs { get; set; } = new List<uint> { 29u, 36u, 37u }; public List<WardenObjectiveEventData> EventsOnBossDeath { get; set; } = new List<WardenObjectiveEventData>(); [JsonIgnore] public StateReplicator<FiniteBDEState> FiniteBDEStateReplicator { get; private set; } [JsonIgnore] public int RemainingWaveBDE { get { if (FiniteBDEStateReplicator == null) { return ApplyToWaveCount; } return FiniteBDEStateReplicator.State.ApplyToWaveCount; } } [JsonIgnore] public int RemainingHibernateBDE { get { if (FiniteBDEStateReplicator == null) { return ApplyToHibernateCount; } return FiniteBDEStateReplicator.State.ApplyToHibernateCount; } } public void SetupReplicator(uint replicatorID) { if (ApplyToHibernateCount != int.MaxValue || ApplyToWaveCount != int.MaxValue) { FiniteBDEStateReplicator = StateReplicator<FiniteBDEState>.Create(replicatorID, new FiniteBDEState { ApplyToHibernateCount = ApplyToHibernateCount, ApplyToWaveCount = ApplyToWaveCount }, (LifeTimeType)1, (IStateReplicatorHolder<FiniteBDEState>)null); FiniteBDEStateReplicator.OnStateChanged += OnStateChanged; } } private void OnStateChanged(FiniteBDEState oldState, FiniteBDEState newState, bool isRecall) { } internal void Destroy() { FiniteBDEStateReplicator = null; } } internal class BossDeathEventManager : ZoneDefinitionManager<EventsOnZoneBossDeath> { public enum Mode { HIBERNATE, WAVE } public static BossDeathEventManager Current; public const int UNLIMITED_COUNT = int.MaxValue; private ConcurrentDictionary<(eDimensionIndex, LG_LayerType, eLocalZoneIndex), EventsOnZoneBossDeath> LevelBDEs { get; } = new ConcurrentDictionary<(eDimensionIndex, LG_LayerType, eLocalZoneIndex), EventsOnZoneBossDeath>(); protected override string DEFINITION_NAME => "EventsOnBossDeath"; public bool TryConsumeBDEventsExecutionTimes(EventsOnZoneBossDeath def, Mode mode) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) return TryConsumeBDEventsExecutionTimes(def.DimensionIndex, def.LayerType, def.LocalIndex, mode); } public bool TryConsumeBDEventsExecutionTimes(eDimensionIndex dimensionIndex, LG_LayerType layer, eLocalZoneIndex localIndex, Mode mode) { //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_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0051: 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_002d: 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_002f: Unknown result type (might be due to invalid IL or missing references) if (!LevelBDEs.ContainsKey((dimensionIndex, layer, localIndex))) { EOSLogger.Error($"BossDeathEventManager: got an unregistered entry: {(dimensionIndex, layer, localIndex, mode)}"); return false; } EventsOnZoneBossDeath eventsOnZoneBossDeath = LevelBDEs[(dimensionIndex, layer, localIndex)]; int num = ((mode == Mode.HIBERNATE) ? eventsOnZoneBossDeath.RemainingHibernateBDE : eventsOnZoneBossDeath.RemainingWaveBDE); if (num == int.MaxValue) { return true; } if (num > 0) { FiniteBDEState state = eventsOnZoneBossDeath.FiniteBDEStateReplicator.State; if (SNet.IsMaster) { eventsOnZoneBossDeath.FiniteBDEStateReplicator.SetState(new FiniteBDEState { ApplyToHibernateCount = ((mode == Mode.HIBERNATE) ? (num - 1) : state.ApplyToHibernateCount), ApplyToWaveCount = ((mode == Mode.WAVE) ? (num - 1) : state.ApplyToWaveCount) }); } return true; } return false; } private void Clear() { foreach (EventsOnZoneBossDeath value in LevelBDEs.Values) { value.Destroy(); } LevelBDEs.Clear(); } private void SetupForCurrentExpedition() { if (!definitions.ContainsKey(RundownManager.ActiveExpedition.LevelLayoutData)) { return; } foreach (EventsOnZoneBossDeath definition in definitions[RundownManager.ActiveExpedition.LevelLayoutData].Definitions) { if (LevelBDEs.ContainsKey(definition.GlobalZoneIndexTuple())) { EOSLogger.Error($"BossDeathEvent: found duplicate setup for zone {definition.GlobalZoneIndexTuple()}, will overwrite!"); } if (definition.ApplyToHibernateCount != int.MaxValue || definition.ApplyToWaveCount != int.MaxValue) { uint num = EOSNetworking.AllotReplicatorID(); if (num != 0) { definition.SetupReplicator(num); } else { EOSLogger.Error("BossDeathEvent: replicator ID depleted, cannot setup replicator!"); } } LevelBDEs[definition.GlobalZoneIndexTuple()] = definition; } } private BossDeathEventManager() { LevelAPI.OnBuildStart += delegate { Clear(); SetupForCurrentExpedition(); }; LevelAPI.OnLevelCleanup += Clear; } static BossDeathEventManager() { Current = new BossDeathEventManager(); } } } namespace ExtraObjectiveSetup.Patches { [HarmonyPatch] internal class Patch_CheckAndExecuteEventsOnTrigger { [HarmonyPrefix] [HarmonyPatch(typeof(WardenObjectiveManager), "CheckAndExecuteEventsOnTrigger", new Type[] { typeof(WardenObjectiveEventData), typeof(eWardenObjectiveEventTrigger), typeof(bool), typeof(float) })] private static bool Pre_CheckAndExecuteEventsOnTrigger(WardenObjectiveEventData eventToTrigger, eWardenObjectiveEventTrigger trigger, bool ignoreTrigger, float currentDuration) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected I4, but got Unknown if (eventToTrigger == null || (!ignoreTrigger && eventToTrigger.Trigger != trigger) || ((double)currentDuration != 0.0 && eventToTrigger.Delay <= currentDuration)) { return true; } uint num = (uint)(int)eventToTrigger.Type; if (!EOSWardenEventManager.Current.HasEventDefinition(num)) { return true; } string value = (EOSWardenEventManager.Current.IsVanillaEventID(num) ? "overriding vanilla event implementation..." : "executing..."); EOSLogger.Debug($"WardenEvent: found definition for event ID {num}, {value}"); EOSWardenEventManager.Current.ExecuteEvent(eventToTrigger, currentDuration); return false; } } [HarmonyPatch] internal class Patch_EventsOnBossDeath { private static HashSet<ushort> ExecutedForInstances; [HarmonyPostfix] [HarmonyPatch(typeof(EnemySync), "OnSpawn")] private static void Post_SpawnEnemy(EnemySync __instance, pEnemySpawnData spawnData) { //IL_0032: 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_0043: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Invalid comparison between Unknown and I4 //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Invalid comparison between Unknown and I4 //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Invalid comparison between Unknown and I4 //IL_00a9: 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 //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) AIG_CourseNode val = default(AIG_CourseNode); if (!((pCourseNode)(ref spawnData.courseNode)).TryGet(ref val) || val == null) { EOSLogger.Error("Failed to get spawnnode for a boss! Skipped EventsOnBossDeath for it"); return; } LG_Zone zone = val.m_zone; EventsOnZoneBossDeath def = BossDeathEventManager.Current.GetDefinition(zone.DimensionIndex, zone.Layer.m_type, zone.LocalIndex); if (def == null) { return; } EnemyAgent enemy = __instance.m_agent; if (!def.BossIDs.Contains(((GameDataBlockBase<EnemyDataBlock>)(object)enemy.EnemyData).persistentID) || ((((int)spawnData.mode != 4 && (int)spawnData.mode != 3) || !def.ApplyToHibernate) && ((int)spawnData.mode != 1 || !def.ApplyToWave))) { return; } BossDeathEventManager.Mode mode = (((int)spawnData.mode != 4) ? BossDeathEventManager.Mode.WAVE : BossDeathEventManager.Mode.HIBERNATE); enemy.OnDeadCallback += Action.op_Implicit((Action)delegate { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 if ((int)GameStateManager.CurrentStateName == 10) { if (!BossDeathEventManager.Current.TryConsumeBDEventsExecutionTimes(def, mode)) { EOSLogger.Debug($"EventsOnBossDeath: execution times depleted for {def.GlobalZoneIndexTuple()}, {mode}"); } else { ushort globalID = ((Agent)enemy).GlobalID; if (ExecutedForInstances.Contains(globalID)) { ExecutedForInstances.Remove(globalID); } else { def.EventsOnBossDeath.ForEach(delegate(WardenObjectiveEventData e) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f); }); ExecutedForInstances.Add(globalID); } } } }); EOSLogger.Debug($"EventsOnBossDeath: added for enemy with id {((GameDataBlockBase<EnemyDataBlock>)(object)enemy.EnemyData).persistentID}, mode: {spawnData.mode}"); } static Patch_EventsOnBossDeath() { ExecutedForInstances = new HashSet<ushort>(); LevelAPI.OnLevelCleanup += ExecutedForInstances.Clear; } } [HarmonyPatch] internal class Patch_EventsOnZoneScoutScream { [HarmonyPrefix] [HarmonyPatch(typeof(ES_ScoutScream), "CommonUpdate")] private static bool Pre_ES_ScoutScream_CommonUpdate(ES_ScoutScream __instance) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Invalid comparison between Unknown and I4 //IL_0153: 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) AIG_CourseNode courseNode = ((Agent)((ES_Base)__instance).m_enemyAgent).CourseNode; EventsOnZoneScoutScream definition = ScoutScreamEventManager.Current.GetDefinition(courseNode.m_dimension.DimensionIndex, courseNode.LayerType, courseNode.m_zone.LocalIndex); if (definition == null) { return true; } if ((int)__instance.m_state != 3 || __instance.m_stateDoneTimer >= Clock.Time) { return true; } if (definition.EventsOnScoutScream != null && definition.EventsOnScoutScream.Count > 0) { EOSLogger.Debug($"EventsOnZoneScoutScream: found config for {definition.GlobalZoneIndexTuple()}, executing events."); definition.EventsOnScoutScream.ForEach(delegate(WardenObjectiveEventData e) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f); }); } if (!definition.SuppressVanillaScoutWave) { if (SNet.IsMaster && ((Agent)((ES_Base)__instance).m_enemyAgent).CourseNode != null) { if (RundownManager.ActiveExpedition.Expedition.ScoutWaveSettings != 0 && RundownManager.ActiveExpedition.Expedition.ScoutWavePopulation != 0) { ushort num = default(ushort); Mastermind.Current.TriggerSurvivalWave(((Agent)((ES_Base)__instance).m_enemyAgent).CourseNode, RundownManager.ActiveExpedition.Expedition.ScoutWaveSettings, RundownManager.ActiveExpedition.Expedition.ScoutWavePopulation, ref num, (SurvivalWaveSpawnType)0, 0f, 2f, true, false, default(Vector3), ""); } else { Debug.LogError(Object.op_Implicit("ES_ScoutScream, a scout is screaming but we can't spawn a wave because the the scout settings are not set for this expedition! ScoutWaveSettings: " + RundownManager.ActiveExpedition.Expedition.ScoutWaveSettings + " ScoutWavePopulation: " + RundownManager.ActiveExpedition.Expedition.ScoutWavePopulation)); } } } else { EOSLogger.Debug("Vanilla scout wave suppressed."); } if (SNet.IsMaster) { ((ES_Base)__instance).m_enemyAgent.AI.m_behaviour.ChangeState((EB_States)5); } ((MachineState<ES_Base>)(object)__instance).m_machine.ChangeState(2); __instance.m_state = (ScoutScreamState)4; return false; } } } namespace ExtraObjectiveSetup.Patches.Uplink { [HarmonyPatch] internal static class CorruptedUplinkConfirm { [HarmonyPrefix] [HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "TerminalCorruptedUplinkConfirm")] private static bool Pre_LG_ComputerTerminalCommandInterpreter_TerminalCorruptedUplinkConfirm(LG_ComputerTerminalCommandInterpreter __instance, string param1, string param2, ref bool __result) { LG_ComputerTerminal receiver = __instance.m_terminal; LG_ComputerTerminal sender = __instance.m_terminal.CorruptedUplinkReceiver; if ((Object)(object)sender == (Object)null) { EOSLogger.Error("TerminalCorruptedUplinkConfirm() critical failure because terminal does not have a CorruptedUplinkReceiver (sender)."); __result = false; return false; } if (sender.m_isWardenObjective) { return true; } (eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(sender); uint zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(sender); UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex); receiver.m_command.AddOutput((TerminalLineType)0, string.Format(Text.Get(2816126705u), sender.PublicName), 0f, (TerminalSoundType)0, (TerminalSoundType)0); if ((Object)(object)sender.ChainedPuzzleForWardenObjective != (Object)null) { ChainedPuzzleInstance chainedPuzzleForWardenObjective = sender.ChainedPuzzleForWardenObjective; chainedPuzzleForWardenObjective.OnPuzzleSolved += Action.op_Implicit((Action)delegate { receiver.m_command.StartTerminalUplinkSequence(string.Empty, true); UplinkObjectiveManager.Current.ChangeState(sender, new UplinkState { Status = UplinkStatus.InProgress, CurrentRoundIndex = 0 }); }); sender.m_command.AddOutput("", true); sender.m_command.AddOutput(Text.Get(3268596368u), true); sender.m_command.AddOutput(Text.Get(2277987284u), true); receiver.m_command.AddOutput("", true); receiver.m_command.AddOutput(Text.Get(3268596368u), true); receiver.m_command.AddOutput(Text.Get(2277987284u), true); if (SNet.IsMaster) { sender.ChainedPuzzleForWardenObjective.AttemptInteract((eChainedPuzzleInteraction)0); } } else { receiver.m_command.StartTerminalUplinkSequence(string.Empty, true); UplinkObjectiveManager.Current.ChangeState(sender, new UplinkState { Status = UplinkStatus.InProgress, CurrentRoundIndex = 0 }); } __result = true; return false; } } [HarmonyPatch] internal static class CorruptedUplinkConnect { [HarmonyPrefix] [HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "TerminalCorruptedUplinkConnect")] private static bool Pre_LG_ComputerTerminalCommandInterpreter_TerminalCorruptedUplinkConnect(LG_ComputerTerminalCommandInterpreter __instance, string param1, string param2, ref bool __result) { //IL_01b4: Unknown result type (might be due to invalid IL or missing references) //IL_01b9: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Unknown result type (might be due to invalid IL or missing references) //IL_01d6: Expected O, but got Unknown LG_ComputerTerminal terminal = __instance.m_terminal; if (terminal.m_isWardenObjective) { return true; } __result = false; LG_ComputerTerminal corruptedUplinkReceiver = terminal.CorruptedUplinkReceiver; if ((Object)(object)corruptedUplinkReceiver == (Object)null) { EOSLogger.Error("TerminalCorruptedUplinkConnect() critical failure because terminal does not have a CorruptedUplinkReceiver."); return false; } if (LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId != 0 && LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId != terminal.SyncID) { __instance.AddOngoingUplinkOutput(); __result = false; return false; } LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId = terminal.SyncID; (eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(terminal); uint zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(terminal); UplinkDefinition definition = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex); if (definition.UseUplinkAddress) { param1 = param1.ToUpper(); EOSLogger.Debug("TerminalCorruptedUplinkConnect, param1: " + param1 + ", TerminalUplink: " + ((Object)terminal.UplinkPuzzle).ToString()); } else { param1 = terminal.UplinkPuzzle.TerminalUplinkIP.ToUpper(); EOSLogger.Debug("TerminalCorruptedUplinkConnect, not using uplink address, TerminalUplink: " + ((Object)terminal.UplinkPuzzle).ToString()); } if (!definition.UseUplinkAddress || param1 == terminal.UplinkPuzzle.TerminalUplinkIP) { if (corruptedUplinkReceiver.m_command.HasRegisteredCommand((TERM_Command)27)) { terminal.m_command.AddUplinkCorruptedOutput(); } else { terminal.m_command.AddUplinkCorruptedOutput(); terminal.m_command.AddOutput("", true); terminal.m_command.AddOutput((TerminalLineType)4, string.Format(Text.Get(3492863045u), corruptedUplinkReceiver.PublicName), 3f, (TerminalSoundType)0, (TerminalSoundType)0); terminal.m_command.AddOutput((TerminalLineType)0, Text.Get(2761366063u), 0.6f, (TerminalSoundType)0, (TerminalSoundType)0); terminal.m_command.AddOutput("", true); terminal.m_command.AddOutput((TerminalLineType)0, Text.Get(3435969025u), 0.8f, (TerminalSoundType)0, (TerminalSoundType)0); corruptedUplinkReceiver.m_command.AddCommand((TERM_Command)27, "UPLINK_CONFIRM", new LocalizedText { UntranslatedText = Text.Get(112719254u), Id = 0u }, (TERM_CommandRule)2); corruptedUplinkReceiver.m_command.AddOutput((TerminalLineType)0, string.Format(Text.Get(1173595354u), terminal.PublicName), 0f, (TerminalSoundType)0, (TerminalSoundType)0); } } else { terminal.m_command.AddUplinkWrongAddressError(param1); } return false; } } [HarmonyPatch] internal static class StartTerminalUplinkSequence { [HarmonyPrefix] [HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "StartTerminalUplinkSequence")] private static bool Pre_LG_ComputerTerminalCommandInterpreter_StartTerminalUplinkSequence(LG_ComputerTerminalCommandInterpreter __instance, string uplinkIp, bool corrupted) { if (!corrupted) { LG_ComputerTerminal uplinkTerminal = __instance.m_terminal; if (uplinkTerminal.m_isWardenObjective) { return true; } (eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(uplinkTerminal); uint zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(uplinkTerminal); UplinkDefinition uplinkConfig = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex); uplinkTerminal.m_command.AddOutput((TerminalLineType)4, string.Format(Text.Get(2583360288u), uplinkIp), 3f, (TerminalSoundType)0, (TerminalSoundType)0); __instance.TerminalUplinkSequenceOutputs(uplinkTerminal, false); uplinkTerminal.m_command.OnEndOfQueue = Action.op_Implicit((Action)delegate { EOSLogger.Debug("UPLINK CONNECTION DONE!"); uplinkTerminal.UplinkPuzzle.Connected = true; uplinkTerminal.UplinkPuzzle.CurrentRound.ShowGui = true; uplinkTerminal.UplinkPuzzle.OnStartSequence(); uplinkConfig.EventsOnCommence.ForEach(delegate(WardenObjectiveEventData e) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f); }); int num2 = uplinkConfig.RoundOverrides.FindIndex((UplinkRound o) => o.RoundIndex == 0); ((num2 != -1) ? uplinkConfig.RoundOverrides[num2] : null)?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)1, false, 0f); }); }); } else { LG_ComputerTerminal terminal = __instance.m_terminal; LG_ComputerTerminal sender = __instance.m_terminal.CorruptedUplinkReceiver; if (sender.m_isWardenObjective) { return true; } (eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex2 = TerminalInstanceManager.Current.GetGlobalZoneIndex(sender); uint zoneInstanceIndex2 = TerminalInstanceManager.Current.GetZoneInstanceIndex(sender); UplinkDefinition uplinkConfig2 = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex2, zoneInstanceIndex2); sender.m_command.AddOutput((TerminalLineType)4, string.Format(Text.Get(2056072887u), sender.PublicName), 3f, (TerminalSoundType)0, (TerminalSoundType)0); sender.m_command.AddOutput("", true); terminal.m_command.AddOutput((TerminalLineType)4, string.Format(Text.Get(2056072887u), sender.PublicName), 3f, (TerminalSoundType)0, (TerminalSoundType)0); terminal.m_command.AddOutput("", true); terminal.m_command.TerminalUplinkSequenceOutputs(sender, false); terminal.m_command.TerminalUplinkSequenceOutputs(terminal, true); terminal.m_command.OnEndOfQueue = Action.op_Implicit((Action)delegate { EOSLogger.Debug("UPLINK CONNECTION DONE!"); sender.UplinkPuzzle.Connected = true; sender.UplinkPuzzle.CurrentRound.ShowGui = true; sender.UplinkPuzzle.OnStartSequence(); uplinkConfig2.EventsOnCommence.ForEach(delegate(WardenObjectiveEventData e) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f); }); int num = uplinkConfig2.RoundOverrides.FindIndex((UplinkRound o) => o.RoundIndex == 0); ((num != -1) ? uplinkConfig2.RoundOverrides[num] : null)?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)1, false, 0f); }); }); } return false; } } [HarmonyPatch] internal static class TerminalUplinkConnect { [HarmonyPrefix] [HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "TerminalUplinkConnect")] private static bool Pre_LG_ComputerTerminalCommandInterpreter_TerminalUplinkConnect(LG_ComputerTerminalCommandInterpreter __instance, string param1, string param2, ref bool __result) { LG_ComputerTerminal terminal = __instance.m_terminal; if (terminal.m_isWardenObjective) { return true; } if (LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId != 0 && LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId != terminal.SyncID) { __instance.AddOngoingUplinkOutput(); return false; } (eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(__instance.m_terminal); uint zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(terminal); UplinkDefinition definition = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex); if (!definition.UseUplinkAddress) { param1 = __instance.m_terminal.UplinkPuzzle.TerminalUplinkIP; } if (!definition.UseUplinkAddress || param1 == __instance.m_terminal.UplinkPuzzle.TerminalUplinkIP) { __instance.m_terminal.TrySyncSetCommandRule((TERM_Command)25, (TERM_CommandRule)1); if ((Object)(object)__instance.m_terminal.ChainedPuzzleForWardenObjective != (Object)null) { ChainedPuzzleInstance chainedPuzzleForWardenObjective = __instance.m_terminal.ChainedPuzzleForWardenObjective; chainedPuzzleForWardenObjective.OnPuzzleSolved += Action.op_Implicit((Action)delegate { __instance.StartTerminalUplinkSequence(param1, false); }); __instance.AddOutput("", true); __instance.AddOutput(Text.Get(3268596368u), true); __instance.AddOutput(Text.Get(3041541194u), true); if (SNet.IsMaster) { __instance.m_terminal.ChainedPuzzleForWardenObjective.AttemptInteract((eChainedPuzzleInteraction)0); } } else { __instance.StartTerminalUplinkSequence(param1, false); } __result = true; } else { __instance.AddUplinkWrongAddressError(param1); __result = false; } return false; } } [HarmonyPatch] internal static class TerminalUplinkSequenceOutput { [HarmonyPrefix] [HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "TerminalUplinkSequenceOutputs")] private static bool Pre_LG_ComputerTerminalCommandInterpreter_TerminalUplinkSequenceOutputs(LG_ComputerTerminal terminal, bool corrupted) { if (terminal.m_isWardenObjective) { return true; } (eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(terminal); uint zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(terminal); UplinkDefinition definition = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex); if (definition == null) { if (!((Object)(object)terminal.CorruptedUplinkReceiver != (Object)null)) { return true; } LG_ComputerTerminal corruptedUplinkReceiver = terminal.CorruptedUplinkReceiver; globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(corruptedUplinkReceiver); zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(corruptedUplinkReceiver); definition = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex); if (definition == null || definition.DisplayUplinkWarning) { return true; } } terminal.m_command.AddOutput((TerminalLineType)3, Text.Get(3418104670u), 3f, (TerminalSoundType)0, (TerminalSoundType)0); terminal.m_command.AddOutput("", true); if (!corrupted) { terminal.m_command.AddOutput(string.Format(Text.Get(947485599u), terminal.UplinkPuzzle.CurrentRound.CorrectPrefix), true); } return false; } } [HarmonyPatch] internal static class TerminalUplinkVerify { [HarmonyPrefix] [HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "TerminalUplinkVerify")] private static bool Pre_LG_ComputerTerminalCommandInterpreter_TerminalUplinkVerify(LG_ComputerTerminalCommandInterpreter __instance, string param1, string param2, ref bool __result) { if (__instance.m_terminal.m_isWardenObjective) { return true; } TerminalUplinkPuzzle uplinkPuzzle = __instance.m_terminal.UplinkPuzzle; (eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(__instance.m_terminal); uint zoneInstanceIndex = TerminalInstanceManager.Current.GetZoneInstanceIndex(__instance.m_terminal); UplinkDefinition definition = UplinkObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex); int CurrentRoundIndex = uplinkPuzzle.m_roundIndex; int num = definition.RoundOverrides.FindIndex((UplinkRound o) => o.RoundIndex == CurrentRoundIndex); UplinkRound roundOverride = ((num != -1) ? definition.RoundOverrides[num] : null); TimeSettings timeSettings = ((num != -1) ? roundOverride.OverrideTimeSettings : definition.DefaultTimeSettings); float num2 = ((timeSettings.TimeToStartVerify >= 0f) ? timeSettings.TimeToStartVerify : definition.DefaultTimeSettings.TimeToStartVerify); float timeToCompleteVerify = ((timeSettings.TimeToCompleteVerify >= 0f) ? timeSettings.TimeToCompleteVerify : definition.DefaultTimeSettings.TimeToCompleteVerify); float num3 = ((timeSettings.TimeToRestoreFromFail >= 0f) ? timeSettings.TimeToRestoreFromFail : definition.DefaultTimeSettings.TimeToRestoreFromFail); if (uplinkPuzzle.Connected) { __instance.AddOutput((TerminalLineType)3, Text.Get(2734004688u), num2, (TerminalSoundType)0, (TerminalSoundType)0); if (!uplinkPuzzle.Solved && uplinkPuzzle.CurrentRound.CorrectCode.ToUpper() == param1.ToUpper()) { __instance.AddOutput(string.Format(Text.Get(1221800228u), uplinkPuzzle.CurrentProgress), true); if (uplinkPuzzle.TryGoToNextRound()) { int newRoundIndex = uplinkPuzzle.m_roundIndex; int num4 = definition.RoundOverrides.FindIndex((UplinkRound o) => o.RoundIndex == newRoundIndex); UplinkRound newRoundOverride = ((num4 != -1) ? definition.RoundOverrides[num4] : null); roundOverride?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)2, false, 0f); }); if (roundOverride != null && (Object)(object)roundOverride.ChainedPuzzleToEndRoundInstance != (Object)null) { TextDataBlock block = GameDataBlockBase<TextDataBlock>.GetBlock("InGame.UplinkTerminal.ScanRequiredToProgress"); if (block != null) { __instance.AddOutput((TerminalLineType)4, Text.Get(((GameDataBlockBase<TextDataBlock>)(object)block).persistentID), 0f, (TerminalSoundType)0, (TerminalSoundType)0); } ChainedPuzzleInstance chainedPuzzleToEndRoundInstance = roundOverride.ChainedPuzzleToEndRoundInstance; chainedPuzzleToEndRoundInstance.OnPuzzleSolved += Action.op_Implicit((Action)delegate { __instance.AddOutput((TerminalLineType)4, Text.Get(27959760u), timeToCompleteVerify, (TerminalSoundType)0, (TerminalSoundType)0); __instance.AddOutput("", true); __instance.AddOutput(string.Format(Text.Get(4269617288u), uplinkPuzzle.CurrentProgress, uplinkPuzzle.CurrentRound.CorrectPrefix), true); __instance.OnEndOfQueue = Action.op_Implicit((Action)delegate { EOSLogger.Log("UPLINK VERIFICATION GO TO NEXT ROUND!"); uplinkPuzzle.CurrentRound.ShowGui = true; newRoundOverride?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)1, false, 0f); }); UplinkObjectiveManager.Current.ChangeState(__instance.m_terminal, new UplinkState { Status = UplinkStatus.InProgress, CurrentRoundIndex = uplinkPuzzle.m_roundIndex }); }); }); if (SNet.IsMaster) { roundOverride.ChainedPuzzleToEndRoundInstance.AttemptInteract((eChainedPuzzleInteraction)0); } } else { __instance.AddOutput((TerminalLineType)4, Text.Get(27959760u), timeToCompleteVerify, (TerminalSoundType)0, (TerminalSoundType)0); __instance.AddOutput("", true); __instance.AddOutput(string.Format(Text.Get(4269617288u), uplinkPuzzle.CurrentProgress, uplinkPuzzle.CurrentRound.CorrectPrefix), true); __instance.OnEndOfQueue = Action.op_Implicit((Action)delegate { EOSLogger.Log("UPLINK VERIFICATION GO TO NEXT ROUND!"); uplinkPuzzle.CurrentRound.ShowGui = true; newRoundOverride?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)1, false, 0f); }); UplinkObjectiveManager.Current.ChangeState(__instance.m_terminal, new UplinkState { Status = UplinkStatus.InProgress, CurrentRoundIndex = uplinkPuzzle.m_roundIndex }); }); } } else { __instance.AddOutput((TerminalLineType)3, Text.Get(1780488547u), 3f, (TerminalSoundType)0, (TerminalSoundType)0); __instance.AddOutput("", true); __instance.OnEndOfQueue = Action.op_Implicit((Action)delegate { roundOverride?.EventsOnRound.ForEach(delegate(WardenObjectiveEventData e) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)2, false, 0f); }); uplinkPuzzle.CurrentRound.ShowGui = false; if (roundOverride != null && (Object)(object)roundOverride.ChainedPuzzleToEndRoundInstance != (Object)null) { ChainedPuzzleInstance chainedPuzzleToEndRoundInstance2 = roundOverride.ChainedPuzzleToEndRoundInstance; chainedPuzzleToEndRoundInstance2.OnPuzzleSolved += Action.op_Implicit((Action)delegate { __instance.AddOutput((TerminalLineType)0, string.Format(Text.Get(3928683780u), uplinkPuzzle.TerminalUplinkIP), 2f, (TerminalSoundType)0, (TerminalSoundType)0); __instance.AddOutput("", true); __instance.OnEndOfQueue = Action.op_Implicit((Action)delegate { EOSLogger.Error("UPLINK VERIFICATION SEQUENCE DONE!"); LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId = 0u; uplinkPuzzle.Solved = true; Action onPuzzleSolved2 = uplinkPuzzle.OnPuzzleSolved; if (onPuzzleSolved2 != null) { onPuzzleSolved2.Invoke(); } UplinkObjectiveManager.Current.ChangeState(__instance.m_terminal, new UplinkState { Status = UplinkStatus.Finished, CurrentRoundIndex = uplinkPuzzle.m_roundIndex }); }); }); if (SNet.IsMaster) { roundOverride.ChainedPuzzleToEndRoundInstance.AttemptInteract((eChainedPuzzleInteraction)0); } } else { __instance.AddOutput((TerminalLineType)0, string.Format(Text.Get(3928683780u), uplinkPuzzle.TerminalUplinkIP), 2f, (TerminalSoundType)0, (TerminalSoundType)0); __instance.AddOutput("", true); EOSLogger.Error("UPLINK VERIFICATION SEQUENCE DONE!"); LG_ComputerTerminalManager.OngoingUplinkConnectionTerminalId = 0u; uplinkPuzzle.Solved = true; Action onPuzzleSolved = uplinkPuzzle.OnPuzzleSolved; if (onPuzzleSolved != null) { onPuzzleSolved.Invoke(); } UplinkObjectiveManager.Current.ChangeState(__instance.m_terminal, new UplinkState { Status = UplinkStatus.Finished, CurrentRoundIndex = uplinkPuzzle.m_roundIndex }); } }); } } else if (uplinkPuzzle.Solved) { __instance.AddOutput("", true); __instance.AddOutput((TerminalLineType)1, Text.Get(4080876165u), 0f, (TerminalSoundType)0, (TerminalSoundType)0); __instance.AddOutput((TerminalLineType)0, Text.Get(4104839742u), 6f, (TerminalSoundType)0, (TerminalSoundType)0); } else { __instance.AddOutput("", true); __instance.AddOutput((TerminalLineType)1, string.Format(Text.Get(507647514u), uplinkPuzzle.CurrentRound.CorrectPrefix), 0f, (TerminalSoundType)0, (TerminalSoundType)0); __instance.AddOutput((TerminalLineType)0, Text.Get(4104839742u), num3, (TerminalSoundType)0, (TerminalSoundType)0); } } else { __instance.AddOutput("", true); __instance.AddOutput(Text.Get(403360908u), true); } __result = false; return false; } } [HarmonyPatch] internal static class UplinkGUI_Update { [HarmonyPostfix] [HarmonyPatch(typeof(LG_ComputerTerminal), "Update")] private static void Post_LG_ComputerTerminal_Update(LG_ComputerTerminal __instance) { if (!__instance.m_isWardenObjective && __instance.UplinkPuzzle != null) { __instance.UplinkPuzzle.UpdateGUI(false); } } } } namespace ExtraObjectiveSetup.Patches.PowerGenerator { [HarmonyPatch] internal static class Patch_LG_PowerGeneratorCluster { [HarmonyPostfix] [HarmonyPatch(typeof(LG_PowerGeneratorCluster), "Setup")] private static void Post_PowerGeneratorCluster_Setup(LG_PowerGeneratorCluster __instance) { uint instanceIndex = GeneratorClusterInstanceManager.Current.Register(__instance); (eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = GeneratorClusterInstanceManager.Current.GetGlobalZoneIndex(__instance); GeneratorClusterDefinition definition = GeneratorClusterObjectiveManager.Current.GetDefinition(globalZoneIndex, instanceIndex); if (definition == null) { return; } EOSLogger.Debug("Found LG_PowerGeneratorCluster and its definition! Building this Generator cluster..."); __instance.m_serialNumber = SerialGenerator.GetUniqueSerialNo(); __instance.m_itemKey = "GENERATOR_CLUSTER_" + __instance.m_serialNumber; __instance.m_terminalItem = GOUtil.GetInterfaceFromComp<iTerminalItem>(__instance.m_terminalItemComp); __instance.m_terminalItem.Setup(__instance.m_itemKey, (AIG_CourseNode)null); __instance.m_terminalItem.FloorItemStatus = (eFloorInventoryObjectStatus)4; if (__instance.SpawnNode != null) { __instance.m_terminalItem.FloorItemLocation = __instance.SpawnNode.m_zone.NavInfo.GetFormattedText((LG_NavInfoFormat)7); } List<Transform> list = new List<Transform>((IEnumerable<Transform>)__instance.m_generatorAligns); uint numberOfGenerators = definition.NumberOfGenerators; __instance.m_generators = Il2CppReferenceArray<LG_PowerGenerator_Core>.op_Implicit((LG_PowerGenerator_Core[])(object)new LG_PowerGenerator_Core[numberOfGenerators]); if (list.Count >= numberOfGenerators) { for (int i = 0; i < numberOfGenerators; i++) { int index = Builder.BuildSeedRandom.Range(0, list.Count, "NO_TAG"); LG_PowerGenerator_Core val = GOUtil.SpawnChildAndGetComp<LG_PowerGenerator_Core>(__instance.m_generatorPrefab, list[index]); ((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)__instance.m_generators)[i] = val; val.SpawnNode = __instance.SpawnNode; PowerGeneratorInstanceManager.Current.MarkAsGCGenerator(__instance, val); val.Setup(); val.SetCanTakePowerCell(true); Debug.Log(Object.op_Implicit("Spawning generator at alignIndex: " + index)); list.RemoveAt(index); } } else { Debug.LogError(Object.op_Implicit("LG_PowerGeneratorCluster does NOT have enough generator aligns to support the warden objective! Has " + list.Count + " needs " + numberOfGenerators)); } __instance.ObjectiveItemSolved = true; if (definition.EndSequenceChainedPuzzle != 0) { GeneratorClusterObjectiveManager.Current.RegisterForChainedPuzzleBuild(__instance, definition); } } } [HarmonyPatch] internal static class Patch_LG_PowerGenerator_Core_SyncStatusChanged { [HarmonyPostfix] [HarmonyPatch(typeof(LG_PowerGenerator_Core), "SyncStatusChanged")] private static void Post_SyncStatusChanged(LG_PowerGenerator_Core __instance, pPowerGeneratorState state, bool isDropinState) { //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005e: 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_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_026f: Unknown result type (might be due to invalid IL or missing references) //IL_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_02d4: 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) uint zoneInstanceIndex = PowerGeneratorInstanceManager.Current.GetZoneInstanceIndex(__instance); (eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = PowerGeneratorInstanceManager.Current.GetGlobalZoneIndex(__instance); LG_PowerGeneratorCluster parentGeneratorCluster = PowerGeneratorInstanceManager.Current.GetParentGeneratorCluster(__instance); GeneratorClusterDefinition generatorClusterDefinition = null; if ((Object)(object)parentGeneratorCluster != (Object)null) { uint zoneInstanceIndex2 = GeneratorClusterInstanceManager.Current.GetZoneInstanceIndex(parentGeneratorCluster); (eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex2 = GeneratorClusterInstanceManager.Current.GetGlobalZoneIndex(parentGeneratorCluster); generatorClusterDefinition = GeneratorClusterObjectiveManager.Current.GetDefinition(globalZoneIndex2, zoneInstanceIndex2); } ePowerGeneratorStatus status = state.status; if (generatorClusterDefinition != null) { EOSLogger.Log($"LG_PowerGeneratorCluster.powerGenerator.OnSyncStatusChanged! status: {status}, isDropinState: {isDropinState}"); if ((int)status == 0) { uint num = 0u; for (int i = 0; i < ((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)parentGeneratorCluster.m_generators).Length; i++) { if ((int)((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)parentGeneratorCluster.m_generators)[i].m_stateReplicator.State.status == 0) { num++; } } EOSLogger.Log($"Generator Cluster PowerCell inserted ({num} / {((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)parentGeneratorCluster.m_generators).Count})"); List<List<WardenObjectiveEventData>> eventsOnInsertCell = generatorClusterDefinition.EventsOnInsertCell; int num2 = (int)(num - 1); if (!isDropinState) { if (num2 >= 0 && num2 < eventsOnInsertCell.Count) { EOSLogger.Log($"Executing events ({num} / {((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)parentGeneratorCluster.m_generators).Count}). Event count: {eventsOnInsertCell[num2].Count}"); eventsOnInsertCell[num2].ForEach(delegate(WardenObjectiveEventData e) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f); }); } if (num == ((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)parentGeneratorCluster.m_generators).Count && !parentGeneratorCluster.m_endSequenceTriggered) { EOSLogger.Log("All generators powered, executing end sequence"); ((MonoBehaviour)__instance).StartCoroutine(parentGeneratorCluster.ObjectiveEndSequence()); parentGeneratorCluster.m_endSequenceTriggered = true; } } else if (num != ((Il2CppArrayBase<LG_PowerGenerator_Core>)(object)parentGeneratorCluster.m_generators).Count) { parentGeneratorCluster.m_endSequenceTriggered = false; } } } IndividualGeneratorDefinition definition = IndividualGeneratorObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex); if (definition != null && definition.EventsOnInsertCell != null && (int)status == 0 && !isDropinState) { definition.EventsOnInsertCell.ForEach(delegate(WardenObjectiveEventData e) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f); }); } ExpeditionIGGroup expeditionIGGroup = ExpeditionIGGroupManager.Current.FindGroupDefOf(__instance); if (expeditionIGGroup == null) { return; } int num3 = 0; foreach (LG_PowerGenerator_Core generatorInstance in expeditionIGGroup.GeneratorInstances) { if ((int)generatorInstance.m_stateReplicator.State.status == 0) { num3++; } } if (isDropinState) { return; } if (num3 == expeditionIGGroup.GeneratorInstances.Count && expeditionIGGroup.PlayEndSequenceOnGroupComplete) { Coroutine val = CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(ExpeditionIGGroupManager.PlayGroupEndSequence(expeditionIGGroup)), (Action)null); WorldEventManager.m_worldEventEventCoroutines.Add(val); return; } int num4 = num3 - 1; if (num4 >= 0 && num4 < expeditionIGGroup.EventsOnInsertCell.Count) { expeditionIGGroup.EventsOnInsertCell[num4].ForEach(delegate(WardenObjectiveEventData e) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f); }); } } } [HarmonyPatch] internal static class Patch_LG_PowerGenerator_Core_Setup { [HarmonyPostfix] [HarmonyPatch(typeof(LG_PowerGenerator_Core), "Setup")] private static void Post_PowerGenerator_Setup(LG_PowerGenerator_Core __instance) { //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: 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) iCarryItemInteractionTarget powerCellInteraction = __instance.m_powerCellInteraction; powerCellInteraction.AttemptCarryItemInsert += Action<SNet_Player, Item>.op_Implicit((Action<SNet_Player, Item>)delegate(SNet_Player p, Item item) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) Item val2 = default(Item); if (PlayerBackpackManager.TryGetItemInLevelFromItemData(item.Get_pItemData(), ref val2)) { ((Il2CppObjectBase)val2).Cast<ItemInLevel>().CanWarp = false; } else { EOSLogger.Error($"Inserting sth other than PowerCell ({item.PublicName}) into {__instance.m_itemKey}, how?"); } }); if (PowerGeneratorInstanceManager.Current.IsGCGenerator(__instance)) { return; } uint num = PowerGeneratorInstanceManager.Current.Register(__instance); (eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = PowerGeneratorInstanceManager.Current.GetGlobalZoneIndex(__instance); IndividualGeneratorDefinition definition = IndividualGeneratorObjectiveManager.Current.GetDefinition(globalZoneIndex, num); if (definition != null) { Vector3 val = definition.Position.ToVector3(); Quaternion rotation = definition.Rotation.ToQuaternion(); if (val != Vector3.zero) { ((Component)__instance).transform.position = val; ((Component)__instance).transform.rotation = rotation; __instance.m_sound.UpdatePosition(val); EOSLogger.Debug("LG_PowerGenerator_Core: modified position / rotation"); } if (definition.ForceAllowPowerCellInsertion) { __instance.SetCanTakePowerCell(true); } EOSLogger.Debug($"LG_PowerGenerator_Core: overriden, instance {num} in {globalZoneIndex}"); } } [HarmonyPostfix] [HarmonyPatch(typeof(LG_PowerGenerator_Core), "SyncStatusChanged")] private static void Post_SyncStatusChanged(LG_PowerGenerator_Core __instance, pPowerGeneratorState state, bool isDropinState) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Invalid comparison between Unknown and I4 uint zoneInstanceIndex = PowerGeneratorInstanceManager.Current.GetZoneInstanceIndex(__instance); (eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = PowerGeneratorInstanceManager.Current.GetGlobalZoneIndex(__instance); IndividualGeneratorDefinition definition = IndividualGeneratorObjectiveManager.Current.GetDefinition(globalZoneIndex, zoneInstanceIndex); if (!(definition == null || definition.EventsOnInsertCell == null || (int)state.status > 0 || isDropinState) && definition.EventsOnInsertCell.Count > 0) { definition.EventsOnInsertCell.ForEach(delegate(WardenObjectiveEventData e) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f); }); } } } } namespace ExtraObjectiveSetup.Patches.Terminal { [HarmonyPatch] internal static class Patch_FixHiddenCommandExecution { [HarmonyPrefix] [HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "ReceiveCommand")] private static void Pre_TerminalInterpreter_ReceiveCommand(LG_ComputerTerminalCommandInterpreter __instance, ref TERM_Command cmd) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0003: 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_00b7: Expected I4, but got Unknown TERM_Command val = cmd; switch (val - 1) { case 0: case 1: case 2: case 3: case 11: case 13: case 14: case 17: case 18: case 19: case 20: case 21: case 22: case 23: case 24: case 25: case 26: case 27: case 28: case 31: case 32: case 33: case 42: if (__instance.m_terminal.CommandIsHidden(cmd)) { cmd = (TERM_Command)10; } break; case 4: case 5: case 6: case 7: case 8: case 9: case 10: case 12: case 15: case 16: case 29: case 30: case 34: case 35: case 36: case 37: case 38: case 39: case 40: case 41: break; } } } [HarmonyPatch] internal static class Patch_FixRepeatablePuzzleBugs { [HarmonyPrefix] [HarmonyPatch(typeof(CP_Cluster_Core), "OnSyncStateChange")] private static bool Pre_CheckEventsOnPuzzleSolved(CP_Cluster_Core __instance, eClusterStatus newStatus, bool isDropinState) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Invalid comparison between Unknown and I4 //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Invalid comparison between Unknown and I4 //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Invalid comparison between Unknown and I4 pClusterState currentState = __instance.m_sync.GetCurrentState(); if (isDropinState && (int)newStatus == 3) { __instance.m_spline.SetVisible(false); for (int i = 0; i < ((Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores).Length; i++) { ((Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores)[i].Deactivate(); } return false; } if (!isDropinState && (int)currentState.status == 3 && (int)newStatus == 1) { __instance.m_spline.Reveal(0f); return false; } return true; } } [HarmonyPatch] internal static class Patch_LG_ComputerTerminal_Setup { [HarmonyPostfix] [HarmonyPatch(typeof(LG_ComputerTerminal), "Setup")] private static void Post_LG_ComputerTerminal_Setup(LG_ComputerTerminal __instance) { //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_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: 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_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) uint instanceIndex = TerminalInstanceManager.Current.Register(__instance); TerminalInstanceManager.Current.SetupTerminalWrapper(__instance); if (__instance.SpawnNode == null) { return; } (eDimensionIndex, LG_LayerType, eLocalZoneIndex) globalZoneIndex = TerminalInstanceManager.Current.GetGlobalZoneIndex(__instance); TerminalPosition definition = TerminalPositionOverrideManager.Current.GetDefinition(globalZoneIndex, instanceIndex); if (definition != null) { if (definition.Position.ToVector3() != Vector3.zeroVector) { ((Component)__instance).transform.position = definition.Position.ToVector3(); ((Component)__instance).transform.rotation = definition.Rotation.ToQuaternion(); } EOSLogger.Debug($"TerminalPositionOverride: {definition.LocalIndex}, {definition.LayerType}, {definition.DimensionIndex}, TerminalIndex {definition.InstanceIndex}"); } } } [HarmonyPatch] internal static class Patch_RepeatableCommandEventFix { [HarmonyPostfix] [HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "SetupCommandEvents")] private static void Post_ResetRepeatableUniqueCommandChainedPuzzle(LG_ComputerTerminalCommandInterpreter __instance) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0043: 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_007d: Unknown result type (might be due to invalid IL or missing references) LG_ComputerTerminal terminal = __instance.m_terminal; ChainedPuzzleInstance val = default(ChainedPuzzleInstance); foreach (TERM_Command uNIQUE_CMD in TerminalInstanceManager.UNIQUE_CMDS) { if (!__instance.m_commandsPerEnum.ContainsKey(uNIQUE_CMD)) { continue; } string text = __instance.m_commandsPerEnum[uNIQUE_CMD]; if ((int)__instance.m_terminal.GetCommandRule(uNIQUE_CMD) != 0) { continue; } List<WardenObjectiveEventData> uniqueCommandEvents = __instance.m_terminal.GetUniqueCommandEvents(text); for (int i = 0; i < uniqueCommandEvents.Count; i++) { if (uniqueCommandEvents[i].ChainPuzzle != 0) { if (__instance.m_terminal.TryGetChainPuzzleForCommand(uNIQUE_CMD, i, ref val) && (Object)(object)val != (Object)null) { ChainedPuzzleInstance obj = val; obj.OnPuzzleSolved += Action.op_Implicit((Action)val.ResetProgress); } EOSLogger.Debug($"TerminalTweak: {terminal.ItemKey}, command {text} set to be repeatable!"); } } } } } } namespace ExtraObjectiveSetup.Patches.LGFactory { [HarmonyPatch] internal class Patch_LG_Factory_NextBatch { [HarmonyPostfix] [HarmonyPatch(typeof(LG_Factory), "NextBatch")] private static void Post_LG_Factory_NextBatch(LG_Factory __instance) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0025: 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) int num = __instance.m_batchStep - 1; if (num >= 0) { BatchName batchName = ((Il2CppArrayBase<LG_FactoryBatch>)(object)__instance.m_batches)[num].m_batchName; Action action = BatchBuildManager.Current.Get_OnBatchDone(batchName); if (action != null) { EOSLogger.Warning($"On Batch '{batchName}' Done: {action.GetInvocationList().Length} injected jobs"); action(); } } } } } namespace ExtraObjectiveSetup.Patches.HSUActivator { [HarmonyPatch] internal class SetupFromCustomGeomorph { [HarmonyPostfix] [HarmonyPatch(typeof(LG_HSUActivator_Core), "SetupFromCustomGeomorph")] private static void Post_LG_HSUActivator_Core_SetupFromCustomGeomorph(LG_HSUActivator_Core __instance) { //IL_0033: 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_0058: 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_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_0239: Unknown result type (might be due to invalid IL or missing references) //IL_023f: Unknown result type (might be due to invalid IL or missing references) //IL_0245: Unknown result type (might be due to invalid IL or missing references) uint instanceIndex = HSUActivatorInstanceManager.Current.Register(__instance); HSUActivatorDefinition definition = HSUActivatorObjectiveManager.Current.GetDefinition(__instance.SpawnNode.m_dimension.DimensionIndex, __instance.SpawnNode.LayerType, __instance.SpawnNode.m_zone.LocalIndex, instanceIndex); if (definition == null) { return; } if (__instance.m_isWardenObjective) { EOSLogger.Error("BuildCustomHSUActivator: the HSUActivator has been set up by vanilla! Aborting custom setup..."); EOSLogger.Error($"HSUActivator in {__instance.SpawnNode.m_zone.LocalIndex}, {__instance.SpawnNode.LayerType}, {__instance.SpawnNode.m_dimension.DimensionIndex}"); return; } __instance.m_linkedItemGoingIn = __instance.SpawnPickupItemOnAlign(definition.ItemFromStart, __instance.m_itemGoingInAlign, false, -1); __instance.m_linkedItemComingOut = __instance.SpawnPickupItemOnAlign(definition.ItemAfterActivation, __instance.m_itemComingOutAlign, false, -1); LG_LevelInteractionManager.DeregisterTerminalItem(((Component)__instance.m_linkedItemGoingIn).GetComponentInChildren<iTerminalItem>()); LG_LevelInteractionManager.DeregisterTerminalItem(((Component)__instance.m_linkedItemComingOut).GetComponentInChildren<iTerminalItem>()); __instance.m_linkedItemGoingIn.SetPickupInteractionEnabled(false); __instance.m_linkedItemComingOut.SetPickupInteractionEnabled(false); __instance.m_insertHSUInteraction.OnInteractionSelected = Action<PlayerAgent>.op_Implicit((Action<PlayerAgent>)delegate { }); __instance.m_sequencerInsertItem.OnSequenceDone = Action.op_Implicit((Action)delegate { //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_0011: 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) pHSUActivatorState state2 = __instance.m_stateReplicator.State; if (!state2.isSequenceIncomplete) { EOSLogger.Log(">>>>>> HSUInsertSequenceDone! Sequence was already complete"); } state2.isSequenceIncomplete = false; __instance.m_stateReplicator.SetStateUnsynced(state2); EOSLogger.Log(">>>>>> HSUInsertSequenceDone!"); if (__instance.m_triggerExtractSequenceRoutine != null) { ((MonoBehaviour)__instance).StopCoroutine(__instance.m_triggerExtractSequenceRoutine); } }); __instance.m_sequencerExtractItem.OnSequenceDone = Action.op_Implicit((Action)delegate { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0024: 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_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) SNet_StateReplicator<pHSUActivatorState, pHSUActivatorInteraction> stateReplicator = __instance.m_stateReplicator; pHSUActivatorState state = __instance.m_stateReplicator.State; state.isSequenceIncomplete = true; stateReplicator.SetStateUnsynced(state); if (SNet.IsMaster) { __instance.AttemptInteract(new pHSUActivatorInteraction { type = (eHSUActivatorInteractionType)2 }); } }); EOSLogger.Debug($"HSUActivator: {(definition.DimensionIndex, definition.LayerType, definition.LocalIndex, definition.InstanceIndex)}, custom setup complete"); } } [HarmonyPatch] internal class SyncStatusChanged { [HarmonyPrefix] [HarmonyPatch(typeof(LG_HSUActivator_Core), "SyncStatusChanged")] private static bool Pre_LG_HSUActivator_Core_SyncStatusChanged(LG_HSUActivator_Core __instance, pHSUActivatorState newState, bool isRecall) { //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_007b: 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_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Expected I4, but got Unknown //IL_030b: Unknown result type (might be due to invalid IL or missing references) if (__instance.m_isWardenObjective) { return true; } uint zoneInstanceIndex = HSUActivatorInstanceManager.Current.GetZoneInstanceIndex(__instance); if (zoneInstanceIndex == uint.MaxValue) { EOSLogger.Error($"Found unregistered HSUActivator!! {HSUActivatorInstanceManager.Current.GetGlobalZoneIndex(__instance)}"); return true; } HSUActivatorDefinition definition = HSUActivatorObjectiveManager.Current.GetDefinition(__instance.SpawnNode.m_dimension.DimensionIndex, __instance.SpawnNode.LayerType, __instance.SpawnNode.m_zone.LocalIndex, zoneInstanceIndex); if (definition == null) { return true; } if (__instance.m_triggerExtractSequenceRoutine != null) { ((MonoBehaviour)__instance).StopCoroutine(__instance.m_triggerExtractSequenceRoutine); } bool goingInVisibleForPostCulling = __instance.m_goingInVisibleForPostCulling; bool comingOutVisibleForPostCulling = __instance.m_comingOutVisibleForPostCulling; EOSLogger.Debug("LG_HSUActivator_Core.OnSyncStatusChanged " + ((object)(eHSUActivatorStatus)(ref newState.status)).ToString()); eHSUActivatorStatus status = newState.status; switch ((int)status) { case 0: __instance.m_insertHSUInteraction.SetActive(true); __instance.ResetItem(__instance.m_itemGoingInAlign, __instance.m_linkedItemGoingIn, false, false, true, ref goingInVisibleForPostCulling); __instance.ResetItem(__instance.m_itemComingOutAlign, __instance.m_linkedItemComingOut, false, false, true, ref comingOutVisibleForPostCulling); __instance.m_sequencerWaitingForItem.StartSequence(); __instance.m_sequencerInsertItem.StopSequence(); __instance.m_sequencerExtractItem.StopSequence(); __instance.m_sequencerExtractionDone.StopSequence(); break; case 1: __instance.m_insertHSUInteraction.SetActive(false); __instance.ResetItem(__instance.m_itemGoingInAlign, __instance.m_linkedItemGoingIn, true, false, true, ref goingInVisibleForPostCulling); __instance.ResetItem(__instance.m_itemComingOutAlign, __instance.m_linkedItemComingOut, false, false, true, ref comingOutVisibleForPostCulling); __instance.m_sequencerWaitingForItem.StopSequence(); if (!isRecall) { __instance.m_sequencerInsertItem.StartSequence(); definition.EventsOnHSUActivation.ForEach(delegate(WardenObjectiveEventData e) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(e, (eWardenObjectiveEventTrigger)0, true, 0f); }); ChainedPuzzleInstance chainedPuzzleOnActivationInstance = definition.ChainedPuzzleOnActivationInstance; if (SNet.IsMaster && (Object)(object)chainedPuzzleOnActivationInstance != (Object)null) { definition.ChainedPuzzleOnActivationInstance.AttemptInteract((eChainedPuzzleInteraction)0); } } __instance.m_sequencerExtractItem.StopSequence(); __instance.m_sequencerExtractionDone.StopSequence(); break; case 2: __instance.m_insertHSUInteraction.SetActive(false); __instance.ResetItem(__instance.m_itemGoingInAlign, __instance.m_linkedItemGoingIn, !__instance.m_showItemComingOut, fals
plugins/net6/Inas07.ExtraSurvivalWaveSettings.dll
Decompiled a month agousing System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using AIGraph; using AK; using Agents; using BepInEx; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using BepInEx.Unity.IL2CPP.Utils.Collections; using GTFO.API; using GameData; using HarmonyLib; using Il2CppSystem; using LevelGeneration; using Localization; using Microsoft.CodeAnalysis; using Player; using SNetwork; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("Inas07.ExtraSurvivalWaveSettings")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("Inas07.ExtraSurvivalWaveSettings")] [assembly: AssemblyTitle("Inas07.ExtraSurvivalWaveSettings")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ExtraSurvivalWaveSettings { [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInPlugin("Inas.ExtraSurvivalWaveSettings", "ExtraSurvivalWaveSettings", "1.1.1")] public class EntryPoint : BasePlugin { public const string AUTHOR = "Inas"; public const string PLUGIN_NAME = "ExtraSurvivalWaveSettings"; public const string VERSION = "1.1.1"; private Harmony m_Harmony; public override void Load() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown m_Harmony = new Harmony("ExtraSurvivalWaveSettings"); m_Harmony.PatchAll(); } } public class SurvivalWaveManager { public static readonly SurvivalWaveManager Current; private ConcurrentDictionary<string, List<ushort>> WaveEventsMap = new ConcurrentDictionary<string, List<ushort>>(); public void SpawnWave(WardenObjectiveEventData e) { //IL_006c: 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_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Unknown result type (might be due to invalid IL or missing references) //IL_025f: Unknown result type (might be due to invalid IL or missing references) //IL_0261: Unknown result type (might be due to invalid IL or missing references) //IL_026a: Unknown result type (might be due to invalid IL or missing references) //IL_0270: Unknown result type (might be due to invalid IL or missing references) //IL_0276: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Invalid comparison between Unknown and I4 //IL_02ae: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Invalid comparison between Unknown and I4 //IL_02ea: Unknown result type (might be due to invalid IL or missing references) //IL_02ef: Unknown result type (might be due to invalid IL or missing references) //IL_01ee: Unknown result type (might be due to invalid IL or missing references) //IL_0207: Unknown result type (might be due to invalid IL or missing references) //IL_0220: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Invalid comparison between Unknown and I4 //IL_0352: Unknown result type (might be due to invalid IL or missing references) //IL_0355: Invalid comparison between Unknown and I4 //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Invalid comparison between Unknown and I4 //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) //IL_03c9: Unknown result type (might be due to invalid IL or missing references) //IL_03cc: Invalid comparison between Unknown and I4 //IL_0370: Unknown result type (might be due to invalid IL or missing references) //IL_0389: Unknown result type (might be due to invalid IL or missing references) //IL_03a2: 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_00fa: Invalid comparison between Unknown and I4 //IL_03ea: Unknown result type (might be due to invalid IL or missing references) //IL_0403: Unknown result type (might be due to invalid IL or missing references) //IL_041c: Unknown result type (might be due to invalid IL or missing references) //IL_017f: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_01b1: Unknown result type (might be due to invalid IL or missing references) //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_0131: Invalid comparison between Unknown and I4 //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_013c: 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) if (!SNet.IsMaster) { return; } PlayerAgent localPlayerAgent = PlayerManager.GetLocalPlayerAgent(); if ((Object)(object)localPlayerAgent == (Object)null) { ESWSLogger.Error("SpawnWave: LocalPlayerAgent is null, wtf?"); return; } GenericEnemyWaveData enemyWaveData = e.EnemyWaveData; if (enemyWaveData.WaveSettings == 0 || enemyWaveData.WavePopulation == 0) { ESWSLogger.Error("SpawnWave: WaveSettings or WavePopulation is 0"); return; } SurvivalWaveSettingsDataBlock block = GameDataBlockBase<SurvivalWaveSettingsDataBlock>.GetBlock(enemyWaveData.WaveSettings); SurvivalWavePopulationDataBlock block2 = GameDataBlockBase<SurvivalWavePopulationDataBlock>.GetBlock(enemyWaveData.WavePopulation); if (block == null || block2 == null) { return; } AIG_CourseNode val = ((Agent)localPlayerAgent).CourseNode; SurvivalWaveSpawnType val2 = (SurvivalWaveSpawnType)0; Vector3 val3 = Vector3.zero; if (block.m_overrideWaveSpawnType) { LG_Zone val4 = default(LG_Zone); if ((int)block.m_survivalWaveSpawnType != 1 && (int)block.m_survivalWaveSpawnType != 2 && (int)block.m_survivalWaveSpawnType != 3) { val2 = block.m_survivalWaveSpawnType; } else if (Builder.CurrentFloor.TryGetZoneByLocalIndex(e.DimensionIndex, e.Layer, e.LocalIndex, ref val4) && (Object)(object)val4 != (Object)null) { val = val4.m_courseNodes[0]; val2 = (SurvivalWaveSpawnType)1; if ((int)block.m_survivalWaveSpawnType == 2 || (int)block.m_survivalWaveSpawnType == 3) { if (e.Count < val4.m_courseNodes.Count) { val = val4.m_courseNodes[e.Count]; val2 = (SurvivalWaveSpawnType)2; if ((int)block.m_survivalWaveSpawnType == 3) { val3 = e.Position; val2 = (SurvivalWaveSpawnType)3; } } else { ESWSLogger.Error($"SpawnWave: SpawnType InSuppliedCourseNode(_OnPosition) is specified but cannot find AREA_{(ushort)(65 + e.Count)} in ({e.DimensionIndex}, {e.Layer}, {e.LocalIndex}), falling back to SpawnType: InSuppliedCourseNodeZone"); } } } else { ESWSLogger.Error($"SpawnWave: Failed to find zone with GlobalIndex ({e.DimensionIndex}, {e.Layer}, {e.LocalIndex}), falling back to default spawn type"); } } Mastermind current = Mastermind.Current; AIG_CourseNode obj = val; uint waveSettings = enemyWaveData.WaveSettings; uint wavePopulation = enemyWaveData.WavePopulation; SurvivalWaveSpawnType val5 = val2; float spawnDelay = enemyWaveData.SpawnDelay; Vector3 val6 = val3; ushort num = default(ushort); if (!current.TriggerSurvivalWave(obj, waveSettings, wavePopulation, ref num, val5, spawnDelay, (float)enemyWaveData.AreaDistance, val6, true, false, default(Vector3), "")) { ESWSLogger.Error("SpawnWave: Critical ERROR! Failed spawning enemy wave"); return; } WardenObjectiveManager.RegisterSurvivalWaveID(num); ESWSLogger.Log($"SpawnWave: Enemy wave spawned ({val2}) with eventID {num}"); if (enemyWaveData.TriggerAlarm) { WardenObjectiveManager.Current.m_sound.UpdatePosition(val.Position); WardenObjectiveManager.Current.m_sound.Post(EVENTS.APEX_PUZZLE_START_ALARM, true); ESWSLogger.Debug("SpawnWave: Trigger Alarm (prolly bugged when there're multiple alarms)"); } if (!string.IsNullOrEmpty(LocalizedText.op_Implicit(enemyWaveData.IntelMessage))) { GuiManager.PlayerLayer.m_wardenIntel.ShowSubObjectiveMessage("", LocalizedText.op_Implicit(enemyWaveData.IntelMessage), false, 200f, 8f, (Action)null); } if ((int)val2 == 1) { ESWSLogger.Log($"Spawning in: ({e.DimensionIndex}, {e.Layer}, {e.LocalIndex})"); } else if ((int)val2 == 2) { ESWSLogger.Log($"Spawning in: ({e.DimensionIndex}, {e.Layer}, {e.LocalIndex}, AREA_{(ushort)(65 + e.Count)})"); } string worldEventObjectFilter = e.WorldEventObjectFilter; if (!string.IsNullOrEmpty(worldEventObjectFilter)) { if (!WaveEventsMap.ContainsKey(worldEventObjectFilter)) { WaveEventsMap[worldEventObjectFilter] = new List<ushort>(); } WaveEventsMap[worldEventObjectFilter].Add(num); ESWSLogger.Debug($"SpawnWave: Registered wave with filter {worldEventObjectFilter}, number of waves assigned: {WaveEventsMap[worldEventObjectFilter].Count}"); } } public void StopNamedWaves(string waveName) { if (string.IsNullOrEmpty(waveName)) { return; } if (!WaveEventsMap.Remove(waveName, out var value)) { ESWSLogger.Error("Wave Filter " + waveName + " is unregistered, cannot stop wave."); return; } ESWSLogger.Debug($"StopNamedWaves: Stopping waves with name {waveName}, wave count: {value.Count}"); value.ForEach(delegate(ushort eventID) { MastermindEvent val = default(MastermindEvent); if (Mastermind.Current.TryGetEvent(eventID, ref val)) { val.StopEvent(); } else { ESWSLogger.Error($"Wave with ID {eventID}: cannot find event. Are you debugging a level?"); } }); } internal void OnStopAllWave() { WaveEventsMap.Clear(); } public void Clear() { WaveEventsMap.Clear(); } private SurvivalWaveManager() { } static SurvivalWaveManager() { Current = new SurvivalWaveManager(); LevelAPI.OnLevelCleanup += Current.Clear; } } internal static class ESWSLogger { private static ManualLogSource logger = Logger.CreateLogSource("ExtraSurvivalWaveSettings"); public static void Log(string format, params object[] args) { Log(string.Format(format, args)); } public static void Log(string str) { if (logger != null) { logger.Log((LogLevel)8, (object)str); } } public static void Warning(string format, params object[] args) { Warning(string.Format(format, args)); } public static void Warning(string str) { if (logger != null) { logger.Log((LogLevel)4, (object)str); } } public static void Error(string format, params object[] args) { Error(string.Format(format, args)); } public static void Error(string str) { if (logger != null) { logger.Log((LogLevel)2, (object)str); } } public static void Debug(string format, params object[] args) { Debug(string.Format(format, args)); } public static void Debug(string str) { if (logger != null) { logger.Log((LogLevel)32, (object)str); } } } [HarmonyPatch] internal class Patch_CheckAndExecuteEventsOnTrigger { [HarmonyPrefix] [HarmonyPatch(typeof(WardenObjectiveManager), "CheckAndExecuteEventsOnTrigger", new Type[] { typeof(WardenObjectiveEventData), typeof(eWardenObjectiveEventTrigger), typeof(bool), typeof(float) })] private static bool Pre_CheckAndExecuteEventsOnTrigger(WardenObjectiveEventData eventToTrigger, eWardenObjectiveEventTrigger trigger, bool ignoreTrigger, float currentDuration) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_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_0030: 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_0035: Invalid comparison between Unknown and I4 if (eventToTrigger == null || (!ignoreTrigger && eventToTrigger.Trigger != trigger) || ((double)currentDuration != 0.0 && eventToTrigger.Delay <= currentDuration)) { return true; } bool flag = false; eWardenObjectiveEventType type = eventToTrigger.Type; if (type - 9 <= 1) { flag = true; Coroutine val = CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(Handle(eventToTrigger, 0f)), (Action)null); WorldEventManager.m_worldEventEventCoroutines.Add(val); } return !flag; } internal static IEnumerator Handle(WardenObjectiveEventData e, float currentDuration) { float num = Mathf.Max(e.Delay - currentDuration, 0f); if (num > 0f) { yield return (object)new WaitForSeconds(num); } if (e.Condition.ConditionIndex >= 0 && WorldEventManager.GetCondition(e.Condition.ConditionIndex) != e.Condition.IsTrue) { yield break; } WardenObjectiveManager.DisplayWardenIntel(e.Layer, e.WardenIntel); if (e.DialogueID != 0) { PlayerDialogManager.WantToStartDialog(e.DialogueID, -1, false, false); } if (e.SoundID != 0) { WardenObjectiveManager.Current.m_sound.Post(e.SoundID, true); string text = ((Object)e.SoundSubtitle).ToString(); if (!string.IsNullOrWhiteSpace(text)) { GuiManager.PlayerLayer.ShowMultiLineSubtitle(text); } } eWardenObjectiveEventType type = e.Type; if ((int)type != 9) { if ((int)type == 10) { if (string.IsNullOrEmpty(e.WorldEventObjectFilter)) { WardenObjectiveManager.StopAlarms(); WardenObjectiveManager.StopAllWardenObjectiveEnemyWaves(); WardenObjectiveManager.Current.m_sound.Post(EVENTS.ALARM_AMBIENT_STOP, true); SurvivalWaveManager.Current.OnStopAllWave(); } else { SurvivalWaveManager.Current.StopNamedWaves(e.WorldEventObjectFilter); } } } else { SurvivalWaveManager.Current.SpawnWave(e); } } } }
plugins/net6/Inas07.FixEndScreen.dll
Decompiled a month agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Unity.IL2CPP; using HarmonyLib; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("Inas07.FixEndScreen")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("Inas07.FixEndScreen")] [assembly: AssemblyTitle("Inas07.FixEndScreen")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace FixEndScreen { [BepInPlugin("Inas.FixEndScreen", "FixEndScreen", "1.0.0")] public class EntryPoint : BasePlugin { private Harmony m_Harmony; public override void Load() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown m_Harmony = new Harmony("FixEndScreen"); m_Harmony.PatchAll(); } } } namespace FixEndScreen.Patches { [HarmonyPatch] internal class Patch_DiscordManager { [HarmonyPrefix] [HarmonyPatch(typeof(DiscordManager), "UpdateDiscordDetails")] private static bool Pre_UpdateDiscordDetails() { return false; } } }
plugins/net6/Inas07.LocalProgression.dll
Decompiled a month agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; using BepInEx; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using BoosterImplants; using CellMenu; using DropServer; using GTFO.API; using GameData; using HarmonyLib; using Il2CppInterop.Runtime.Injection; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.InteropTypes.Arrays; using Il2CppSystem; using Il2CppSystem.Collections.Generic; using LevelGeneration; using LocalProgression.Component; using LocalProgression.Data; using Localization; using MTFO.API; using Microsoft.CodeAnalysis; using SNetwork; using TMPro; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("Inas07.LocalProgression")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("Inas07.LocalProgression")] [assembly: AssemblyTitle("Inas07.LocalProgression")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace LocalProgression { internal static class Assets { internal static GameObject NoBoosterIcon { get; private set; } internal static void Init() { NoBoosterIcon = AssetAPI.GetLoadedAsset<GameObject>("Assets/Misc/CM_ExpeditionSectorIcon.prefab"); } } [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInPlugin("Inas.LocalProgression", "LocalProgression", "1.3.6")] public class EntryPoint : BasePlugin { private Harmony m_Harmony; public override void Load() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown m_Harmony = new Harmony("LocalProgression"); m_Harmony.PatchAll(); EventAPI.OnManagersSetup += LocalProgressionManager.Current.Init; AssetAPI.OnAssetBundlesLoaded += Assets.Init; } } internal static class JSON { private static JsonSerializerOptions _setting; public static T Deserialize<T>(string json) { return JsonSerializer.Deserialize<T>(json, _setting); } public static string Serialize<T>(T value) { return JsonSerializer.Serialize(value, _setting); } static JSON() { _setting = new JsonSerializerOptions { ReadCommentHandling = JsonCommentHandling.Skip, IncludeFields = false, PropertyNameCaseInsensitive = true, WriteIndented = true, IgnoreReadOnlyProperties = true }; _setting.Converters.Add(new JsonStringEnumConverter()); } } public class LocalProgressionManager { public const string CONFIG_FILE_NAME = "ProgressionConfig.json"; public static readonly LocalProgressionManager Current; private CM_PageRundown_New rundownPage; public static readonly string DirPath; public string LP_CONFIG_DIR => Path.Combine(MTFOPathAPI.CustomPath, "LocalProgressionConfig"); public string CONFIG_PATH => Path.Combine(LP_CONFIG_DIR, "ProgressionConfig.json"); public RundownProgressonConfig RundownProgressonConfig { get; private set; } = new RundownProgressonConfig(); private RundownProgressionData CurrentRundownPData { get; } = new RundownProgressionData(); internal RundownProgData nativeProgData { get; private set; } internal void SetCurrentRundownPageInstance(CM_PageRundown_New __instance) { rundownPage = __instance; } private void UpdateRundownPageExpeditionIconProgression() { //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Expected O, but got Unknown //IL_00e8: 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_011e: Unknown result type (might be due to invalid IL or missing references) //IL_01c6: Unknown result type (might be due to invalid IL or missing references) //IL_018d: Unknown result type (might be due to invalid IL or missing references) //IL_0235: Unknown result type (might be due to invalid IL or missing references) //IL_01fc: Unknown result type (might be due to invalid IL or missing references) //IL_02bf: Unknown result type (might be due to invalid IL or missing references) //IL_02dd: Unknown result type (might be due to invalid IL or missing references) //IL_032d: Unknown result type (might be due to invalid IL or missing references) //IL_034b: Unknown result type (might be due to invalid IL or missing references) //IL_039b: Unknown result type (might be due to invalid IL or missing references) //IL_03b9: Unknown result type (might be due to invalid IL or missing references) //IL_0409: 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_026b: Unknown result type (might be due to invalid IL or missing references) //IL_04b4: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)rundownPage == (Object)null) { return; } uint rundownID = CurrentRundownPData.RundownID; if (rundownID == 0) { LPLogger.Warning("UpdateRundownPageExpeditionIconProgression: rundown_id == 0!"); return; } RundownDataBlock block = GameDataBlockBase<RundownDataBlock>.GetBlock(rundownID); LPLogger.Log($"CM_PageRundown_New.UpdateRundownExpeditionProgression, overwrite with LocalProgression Data, RundownID {CurrentRundownPData.RundownID}"); nativeProgData = ComputeLocalProgressionDataToRundownProgData(); if ((Object)(object)rundownPage.m_tierMarker1 != (Object)null) { rundownPage.m_tierMarker1.SetProgression(nativeProgData, new RundownTierProgressionData()); if (rundownPage.m_expIconsTier1 != null) { UpdateTierIconsWithProgression(rundownPage.m_expIconsTier1, rundownPage.m_tierMarker1, thisTierUnlocked: true); } } if ((Object)(object)rundownPage.m_tierMarker2 != (Object)null) { rundownPage.m_tierMarker2.SetProgression(nativeProgData, block.ReqToReachTierB); if (rundownPage.m_expIconsTier2 != null) { UpdateTierIconsWithProgression(rundownPage.m_expIconsTier2, rundownPage.m_tierMarker2, nativeProgData.tierBUnlocked && block.UseTierUnlockRequirements); } } if ((Object)(object)rundownPage.m_tierMarker3 != (Object)null) { rundownPage.m_tierMarker3.SetProgression(nativeProgData, block.ReqToReachTierC); if (rundownPage.m_expIconsTier3 != null) { UpdateTierIconsWithProgression(rundownPage.m_expIconsTier3, rundownPage.m_tierMarker3, nativeProgData.tierCUnlocked && block.UseTierUnlockRequirements); } } if ((Object)(object)rundownPage.m_tierMarker4 != (Object)null) { rundownPage.m_tierMarker4.SetProgression(nativeProgData, block.ReqToReachTierD); if (rundownPage.m_expIconsTier4 != null) { UpdateTierIconsWithProgression(rundownPage.m_expIconsTier4, rundownPage.m_tierMarker4, nativeProgData.tierDUnlocked && block.UseTierUnlockRequirements); } } if ((Object)(object)rundownPage.m_tierMarker5 != (Object)null) { rundownPage.m_tierMarker5.SetProgression(nativeProgData, block.ReqToReachTierE); if (rundownPage.m_expIconsTier5 != null) { UpdateTierIconsWithProgression(rundownPage.m_expIconsTier5, rundownPage.m_tierMarker5, nativeProgData.tierEUnlocked && block.UseTierUnlockRequirements); } } if (!((Object)(object)rundownPage.m_tierMarkerSectorSummary != (Object)null)) { return; } rundownPage.m_tierMarkerSectorSummary.SetSectorIconTextForMain($"<color=orange>[{nativeProgData.clearedMain}/{nativeProgData.totalMain}]</color>", "#FFFFFFCC"); rundownPage.m_tierMarkerSectorSummary.SetSectorIconTextForSecondary($"<color=orange>[{nativeProgData.clearedSecondary}/{nativeProgData.totalSecondary}]</color>", "#CCCCCCCC"); rundownPage.m_tierMarkerSectorSummary.SetSectorIconTextForThird($"<color=orange>[{nativeProgData.clearedThird}/{nativeProgData.totalThird}]</color>", "#CCCCCCCC"); rundownPage.m_tierMarkerSectorSummary.SetSectorIconTextForAllCleared($"<color=orange>[{nativeProgData.clearedAllClear}/{nativeProgData.totalAllClear}]</color>", "#CCCCCCCC"); RundownTierMarker_NoBoosterIcon component = ((Component)rundownPage.m_tierMarkerSectorSummary).GetComponent<RundownTierMarker_NoBoosterIcon>(); if (!((Object)(object)component != (Object)null) || !TryGetRundownConfig(rundownID, out var rundownConf)) { return; } int value = rundownConf.ComputeNoBoosterClearPossibleCount(); if (rundownConf.EnableNoBoosterUsedProgressionForRundown && (rundownConf.AlwaysShowIcon || CurrentRundownPData.NoBoosterAllClearCount > 0)) { if (rundownConf.EnableNoBoosterUsedProgressionForRundown) { value = nativeProgData.totalMain; } component.SetVisible(visible: true); component.SetSectorIconText($"<color=orange>[{CurrentRundownPData.NoBoosterAllClearCount}/{value}]</color>"); } else { component.SetVisible(visible: false); } } private void UpdateTierIconsWithProgression(List<CM_ExpeditionIcon_New> tierIcons, CM_RundownTierMarker tierMarker, bool thisTierUnlocked) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0141: Unknown result type (might be due to invalid IL or missing references) if (tierIcons == null || tierIcons.Count == 0) { if (tierMarker != null) { tierMarker.SetVisible(false, 0f); } return; } for (int i = 0; i < tierIcons.Count; i++) { CM_ExpeditionIcon_New val = tierIcons[i]; string rundownProgressionExpeditionKey = RundownManager.GetRundownProgressionExpeditionKey(tierIcons[i].Tier, tierIcons[i].ExpIndex); ExpeditionProgressionData value; bool flag = CurrentRundownPData.LPData.TryGetValue(rundownProgressionExpeditionKey, out value); string text = "0"; string text2 = (RundownManager.HasSecondaryLayer(tierIcons[i].DataBlock) ? "0" : "-"); string text3 = (RundownManager.HasThirdLayer(tierIcons[i].DataBlock) ? "0" : "-"); string text4 = (RundownManager.HasAllCompletetionPossibility(tierIcons[i].DataBlock) ? "0" : "-"); if (flag) { if (value.MainCompletionCount > 0) { text = value.MainCompletionCount.ToString(); } if (value.SecondaryCompletionCount > 0) { text2 = value.SecondaryCompletionCount.ToString(); } if (value.ThirdCompletionCount > 0) { text3 = value.ThirdCompletionCount.ToString(); } if (value.AllClearCount > 0) { text4 = value.AllClearCount.ToString(); } } if (CheckExpeditionUnlocked(val.DataBlock, val.Tier)) { if (flag) { rundownPage.SetIconStatus(val, (eExpeditionIconStatus)4, text, text2, text3, text4, 1f, false, (eExpeditionAccessibility)0); } else { rundownPage.SetIconStatus(val, (eExpeditionIconStatus)2, "-", "-", "-", "-", 1f, false, (eExpeditionAccessibility)0); } } else if (flag) { rundownPage.SetIconStatus(val, (eExpeditionIconStatus)1, text, text2, text3, text4, 1f, false, (eExpeditionAccessibility)0); } else if (val.DataBlock.HideOnLocked) { ((RectTransformComp)val).SetVisible(false); } else { rundownPage.SetIconStatus(val, (eExpeditionIconStatus)0, "-", "-", "-", "-", 1f, false, (eExpeditionAccessibility)0); } } if (thisTierUnlocked) { if (tierMarker != null) { tierMarker.SetStatus((eRundownTierMarkerStatus)1); } } else if (tierMarker != null) { tierMarker.SetStatus((eRundownTierMarkerStatus)0); } } private RundownProgData ComputeLocalProgressionDataToRundownProgData() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: 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) RundownProgData progressionData = default(RundownProgData); if (CurrentRundownPData.RundownID == 0) { LPLogger.Error("ComputeLocalProgressionDataToRundownProgData: rundown_id == 0..."); return progressionData; } RundownDataBlock block = GameDataBlockBase<RundownDataBlock>.GetBlock(CurrentRundownPData.RundownID); if (block == null) { LPLogger.Error($"ComputeLocalProgressionDataToRundownProgData: cannot get rundown datablock with rundown_id: {CurrentRundownPData.RundownID}"); return progressionData; } progressionData.clearedMain = CurrentRundownPData.MainClearCount; progressionData.clearedSecondary = CurrentRundownPData.SecondaryClearCount; progressionData.clearedThird = CurrentRundownPData.ThirdClearCount; progressionData.clearedAllClear = CurrentRundownPData.AllClearCount; AccumulateTierClearance(block, (eRundownTier)1, ref progressionData); AccumulateTierClearance(block, (eRundownTier)2, ref progressionData); AccumulateTierClearance(block, (eRundownTier)3, ref progressionData); AccumulateTierClearance(block, (eRundownTier)4, ref progressionData); AccumulateTierClearance(block, (eRundownTier)5, ref progressionData); return progressionData; } private void AccumulateTierClearance(RundownDataBlock rundownDB, eRundownTier tier, ref RundownProgData progressionData) { //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_0023: Expected I4, but got Unknown //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) List<ExpeditionInTierData> val = rundownDB.TierA; switch (tier - 1) { case 1: val = rundownDB.TierB; break; case 2: val = rundownDB.TierC; break; case 3: val = rundownDB.TierD; break; case 4: val = rundownDB.TierE; break; default: LPLogger.Error($"Unsupported eRundownTier {tier}"); return; case 0: break; } int num = 0; Enumerator<ExpeditionInTierData> enumerator = val.GetEnumerator(); while (enumerator.MoveNext()) { ExpeditionInTierData current = enumerator.Current; if (current.Enabled && (!current.HideOnLocked || CheckExpeditionUnlocked(current, tier))) { progressionData.totalMain++; if (RundownManager.HasSecondaryLayer(current)) { progressionData.totalSecondary++; } if (RundownManager.HasThirdLayer(current)) { progressionData.totalThird++; } if (RundownManager.HasAllCompletetionPossibility(current)) { progressionData.totalAllClear++; } if (current.Descriptive.IsExtraExpedition) { progressionData.totatlExtra++; } string uniqueExpeditionKey = RundownManager.GetUniqueExpeditionKey(rundownDB, tier, num); if (CurrentRundownPData.LPData.ContainsKey(uniqueExpeditionKey)) { progressionData.clearedExtra++; } num++; } } } private bool CheckTierUnlocked(eRundownTier tier) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected I4, but got Unknown //IL_0064: Unknown result type (might be due to invalid IL or missing references) RundownDataBlock block = GameDataBlockBase<RundownDataBlock>.GetBlock(CurrentRundownPData.RundownID); RundownTierProgressionData val = null; switch (tier - 1) { case 0: return true; case 1: val = block.ReqToReachTierB; break; case 2: val = block.ReqToReachTierC; break; case 3: val = block.ReqToReachTierD; break; case 4: val = block.ReqToReachTierE; break; default: LPLogger.Error("Unsupporrted tier: {0}", tier); return true; } if (CurrentRundownPData.MainClearCount >= val.MainSectors && CurrentRundownPData.SecondaryClearCount >= val.SecondarySectors && CurrentRundownPData.ThirdClearCount >= val.ThirdSectors) { return CurrentRundownPData.AllClearCount >= val.AllClearedSectors; } return false; } private bool CheckExpeditionUnlocked(ExpeditionInTierData expedition, eRundownTier tier) { //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_0025: Expected I4, but got Unknown //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Expected I4, but got Unknown //IL_00c8: Unknown result type (might be due to invalid IL or missing references) eExpeditionAccessibility accessibility = expedition.Accessibility; switch ((int)accessibility) { case 1: case 3: return false; case 2: return true; case 0: return CheckTierUnlocked(tier); case 4: { RundownTierProgressionData customProgressionLock = expedition.CustomProgressionLock; if (CurrentRundownPData.MainClearCount >= customProgressionLock.MainSectors && CurrentRundownPData.SecondaryClearCount >= customProgressionLock.SecondarySectors && CurrentRundownPData.ThirdClearCount >= customProgressionLock.ThirdSectors) { return CurrentRundownPData.AllClearCount >= customProgressionLock.AllClearedSectors; } return false; } case 5: { ExpeditionIndex unlockedByExpedition = expedition.UnlockedByExpedition; string rundownProgressionExpeditionKey = RundownManager.GetRundownProgressionExpeditionKey(unlockedByExpedition.Tier, (int)unlockedByExpedition.Exp); return CurrentRundownPData.LPData.ContainsKey(rundownProgressionExpeditionKey); } default: LPLogger.Warning("Unsupported eExpeditionAccessibility: {0}", expedition.Accessibility); return true; } } private void SetNativeRundownProgression() { //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Expected O, but got Unknown //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_012e: 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_0159: Unknown result type (might be due to invalid IL or missing references) //IL_0173: Unknown result type (might be due to invalid IL or missing references) Dictionary<string, Expedition> expeditions = RundownManager.RundownProgression.Expeditions; if (expeditions.Count > 0) { LPLogger.Warning($"Non-empty native rundown progression data! RundownID: {CurrentRundownPData.RundownID}"); expeditions.Clear(); } Dictionary<string, ExpeditionProgressionData> lPData = CurrentRundownPData.LPData; Layer val2 = default(Layer); Layer val3 = default(Layer); Layer val4 = default(Layer); foreach (string key in lPData.Keys) { Expedition val = new Expedition(); ExpeditionProgressionData expeditionProgressionData = lPData[key]; val.AllLayerCompletionCount = expeditionProgressionData.AllClearCount; val.Layers = new LayerSet<Layer>(); val2.CompletionCount = expeditionProgressionData.MainCompletionCount; val2.State = (LayerProgressionState)((expeditionProgressionData.MainCompletionCount > 0) ? 3 : 0); val3.CompletionCount = expeditionProgressionData.SecondaryCompletionCount; val3.State = (LayerProgressionState)((expeditionProgressionData.SecondaryCompletionCount > 0) ? 3 : 0); val4.CompletionCount = expeditionProgressionData.ThirdCompletionCount; val4.State = (LayerProgressionState)((expeditionProgressionData.ThirdCompletionCount > 0) ? 3 : 0); val.Layers.SetLayer((ExpeditionLayers)0, val2); val.Layers.SetLayer((ExpeditionLayers)1, val3); val.Layers.SetLayer((ExpeditionLayers)2, val4); LPLogger.Warning($"{val2.CompletionCount}, {val3.CompletionCount}, {val4.CompletionCount}"); expeditions[key] = val; } } private void InitConfig() { if (!Directory.Exists(LP_CONFIG_DIR)) { Directory.CreateDirectory(LP_CONFIG_DIR); } if (!File.Exists(CONFIG_PATH)) { StreamWriter streamWriter = File.CreateText(CONFIG_PATH); streamWriter.WriteLine(JSON.Serialize(new RundownProgressonConfig())); streamWriter.Flush(); streamWriter.Close(); RundownProgressonConfig = new RundownProgressonConfig(); } ReloadConfig(); RundownManager.OnRundownProgressionUpdated += Action.op_Implicit((Action)ReloadConfig); } private void ReloadConfig() { try { RundownProgressonConfig = JSON.Deserialize<RundownProgressonConfig>(File.ReadAllText(CONFIG_PATH)); } catch { LPLogger.Error("Cannot reload RundownProgressonConfig, probably the file is invalid"); RundownProgressonConfig = new RundownProgressonConfig(); } } public bool TryGetRundownConfig(uint RundownID, out RundownConfig rundownConf) { rundownConf = RundownProgressonConfig.Configs.Find((RundownConfig rundownConf) => rundownConf.RundownID == RundownID); return rundownConf != null; } public bool TryGetExpeditionConfig(uint RundownID, eRundownTier tier, int expIndex, out ExpeditionProgressionConfig expConf) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) expConf = null; if (TryGetRundownConfig(RundownID, out var rundownConf)) { expConf = rundownConf.Expeditions.Find((ExpeditionProgressionConfig e) => e.Tier == tier && e.ExpeditionIndex == expIndex); } return expConf != null; } public void RecordExpeditionSuccessForCurrentRundown(string expeditionKey, bool mainLayerCleared, bool secondaryLayerCleared, bool thirdLayerCleared, bool clearedWithNoBooster) { if (RundownManager.ActiveExpedition.ExcludeFromProgression) { return; } UpdateLPDataToActiveRundown(); bool flag = mainLayerCleared && secondaryLayerCleared && thirdLayerCleared; Dictionary<string, ExpeditionProgressionData> lPData = CurrentRundownPData.LPData; if (!lPData.ContainsKey(expeditionKey)) { lPData[expeditionKey] = new ExpeditionProgressionData { ExpeditionKey = expeditionKey, MainCompletionCount = (mainLayerCleared ? 1 : 0), SecondaryCompletionCount = (secondaryLayerCleared ? 1 : 0), ThirdCompletionCount = (thirdLayerCleared ? 1 : 0), AllClearCount = (flag ? 1 : 0), NoBoosterAllClearCount = (clearedWithNoBooster ? 1 : 0) }; CurrentRundownPData.MainClearCount += (mainLayerCleared ? 1 : 0); CurrentRundownPData.SecondaryClearCount += (secondaryLayerCleared ? 1 : 0); CurrentRundownPData.ThirdClearCount += (thirdLayerCleared ? 1 : 0); CurrentRundownPData.AllClearCount += (flag ? 1 : 0); CurrentRundownPData.NoBoosterAllClearCount += (clearedWithNoBooster ? 1 : 0); } else { ExpeditionProgressionData expeditionProgressionData = lPData[expeditionKey]; if (expeditionProgressionData.MainCompletionCount == 0 && mainLayerCleared) { CurrentRundownPData.MainClearCount++; } if (expeditionProgressionData.SecondaryCompletionCount == 0 && secondaryLayerCleared) { CurrentRundownPData.SecondaryClearCount++; } if (expeditionProgressionData.ThirdCompletionCount == 0 && thirdLayerCleared) { CurrentRundownPData.ThirdClearCount++; } if (expeditionProgressionData.AllClearCount == 0 && flag) { CurrentRundownPData.AllClearCount++; } if (expeditionProgressionData.NoBoosterAllClearCount == 0 && clearedWithNoBooster) { CurrentRundownPData.NoBoosterAllClearCount++; } expeditionProgressionData.MainCompletionCount += (mainLayerCleared ? 1 : 0); expeditionProgressionData.SecondaryCompletionCount += (secondaryLayerCleared ? 1 : 0); expeditionProgressionData.ThirdCompletionCount += (thirdLayerCleared ? 1 : 0); expeditionProgressionData.AllClearCount += (flag ? 1 : 0); expeditionProgressionData.NoBoosterAllClearCount += (clearedWithNoBooster ? 1 : 0); } SaveRundownLPDataToDisk(); } public void UpdateLPDataToActiveRundown() { uint num = ActiveRundownID(); if (num == 0) { LPLogger.Debug("UpdateLPDataToActiveRundown: cannot find any active rundown!"); return; } LPLogger.Warning($"Update LPData to rundown_id: {num}"); CurrentRundownPData.Reset(); RundownDataBlock block = GameDataBlockBase<RundownDataBlock>.GetBlock(num); if (block == null) { LPLogger.Error($"Didn't find Rundown Datablock with rundown id {num}"); return; } Dictionary<string, ExpeditionProgressionData> dictionary = ReadRundownLPData(((GameDataBlockBase<RundownDataBlock>)(object)block).name); CurrentRundownPData.RundownID = num; CurrentRundownPData.RundownName = ((GameDataBlockBase<RundownDataBlock>)(object)block).name; CurrentRundownPData.LPData = dictionary; foreach (ExpeditionProgressionData value in dictionary.Values) { CurrentRundownPData.MainClearCount += ((value.MainCompletionCount > 0) ? 1 : 0); CurrentRundownPData.SecondaryClearCount += ((value.SecondaryCompletionCount > 0) ? 1 : 0); CurrentRundownPData.ThirdClearCount += ((value.ThirdCompletionCount > 0) ? 1 : 0); CurrentRundownPData.AllClearCount += ((value.AllClearCount > 0) ? 1 : 0); CurrentRundownPData.NoBoosterAllClearCount += ((value.NoBoosterAllClearCount > 0) ? 1 : 0); } } internal void Init() { if (!Directory.Exists(DirPath)) { Directory.CreateDirectory(DirPath); } RundownManager.OnRundownProgressionUpdated += Action.op_Implicit((Action)OnNativeRundownProgressionUpdated); InitConfig(); } internal void OnNativeRundownProgressionUpdated() { UpdateLPDataToActiveRundown(); if (!((Object)(object)rundownPage == (Object)null) && ((CM_PageBase)rundownPage).m_isActive) { UpdateRundownPageExpeditionIconProgression(); } } public bool AllSectorCompletedWithoutBoosterAndCheckpoint() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Invalid comparison between Unknown and I4 //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Invalid comparison between Unknown and I4 if (RundownManager.HasSecondaryLayer(RundownManager.ActiveExpedition) && (int)WardenObjectiveManager.CurrentState.second_status != 40) { return false; } if (RundownManager.HasThirdLayer(RundownManager.ActiveExpedition) && (int)WardenObjectiveManager.CurrentState.second_status != 40) { return false; } bool flag = CheckpointManager.CheckpointUsage == 0; if (flag) { foreach (PlayerBoosterImplantState item in (Il2CppArrayBase<PlayerBoosterImplantState>)(object)BoosterImplantManager.Current.m_boosterPlayers) { if (item == null) { continue; } foreach (pBoosterImplantData item2 in (Il2CppArrayBase<pBoosterImplantData>)(object)item.BoosterImplantDatas) { if (item2.BoosterImplantID != 0) { flag = false; break; } } } } return flag; } public uint ActiveRundownID() { uint num = default(uint); if (!RundownManager.TryGetIdFromLocalRundownKey(RundownManager.ActiveRundownKey, ref num) || num == 0) { return 0u; } return num; } public string ExpeditionKey(eRundownTier tier, int expIndex) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) return RundownManager.GetRundownProgressionExpeditionKey(tier, expIndex); } public ExpeditionProgressionData GetExpeditionLP(uint RundownID, eRundownTier tier, int expIndex) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) ExpeditionProgressionData result = new ExpeditionProgressionData { ExpeditionKey = ExpeditionKey(tier, expIndex) }; Dictionary<string, ExpeditionProgressionData> dictionary; if (CurrentRundownPData.RundownID != RundownID) { RundownDataBlock block = GameDataBlockBase<RundownDataBlock>.GetBlock(RundownID); if (block == null) { LPLogger.Error($"Didn't find Rundown Datablock with rundown id {RundownID}"); return result; } dictionary = ReadRundownLPData(((GameDataBlockBase<RundownDataBlock>)(object)block).name); } else { dictionary = CurrentRundownPData.LPData; } string key = ExpeditionKey(tier, expIndex); if (dictionary.TryGetValue(key, out var value)) { return value; } return result; } static LocalProgressionManager() { Current = new LocalProgressionManager(); DirPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "GTFO-Modding", "LocalProgression"); } private LocalProgressionManager() { } private static string RundownLPDataPath(string rundownName) { char[] invalidPathChars = Path.GetInvalidPathChars(); foreach (char oldChar in invalidPathChars) { rundownName = rundownName.Replace(oldChar, '_'); } return Path.Combine(DirPath, rundownName); } private static string NBSClearDataPath(string rundownName) { return RundownLPDataPath(rundownName) + " - NBSClear"; } private bool TryReadAggregatedFormatData(string datapath, out Dictionary<string, ExpeditionProgressionData> dataDict) { dataDict = new Dictionary<string, ExpeditionProgressionData>(); bool result = true; FileStream fileStream = null; BinaryReader binaryReader = null; try { fileStream = File.Open(datapath, FileMode.Open); binaryReader = new BinaryReader(fileStream, Encoding.UTF8, leaveOpen: false); int num = binaryReader.ReadInt32(); for (int i = 0; i < num; i++) { ExpeditionProgressionData expeditionProgressionData = new ExpeditionProgressionData(); expeditionProgressionData.ExpeditionKey = binaryReader.ReadString(); expeditionProgressionData.MainCompletionCount = binaryReader.ReadInt32(); expeditionProgressionData.SecondaryCompletionCount = binaryReader.ReadInt32(); expeditionProgressionData.ThirdCompletionCount = binaryReader.ReadInt32(); expeditionProgressionData.AllClearCount = binaryReader.ReadInt32(); expeditionProgressionData.NoBoosterAllClearCount = binaryReader.ReadInt32(); dataDict[expeditionProgressionData.ExpeditionKey] = expeditionProgressionData; } } catch (EndOfStreamException) { dataDict.Clear(); result = false; } finally { binaryReader?.Close(); fileStream?.Close(); } return result; } private bool TryReadOldFormatData(string datapath, out Dictionary<string, ExpeditionProgressionData> dataDict) { dataDict = new Dictionary<string, ExpeditionProgressionData>(); bool result = true; FileStream fileStream = null; BinaryReader binaryReader = null; if (!File.Exists(datapath)) { return true; } try { fileStream = File.Open(datapath, FileMode.Open); binaryReader = new BinaryReader(fileStream, Encoding.UTF8, leaveOpen: false); int num = binaryReader.ReadInt32(); for (int i = 0; i < num; i++) { ExpeditionProgressionData expeditionProgressionData = new ExpeditionProgressionData(); expeditionProgressionData.ExpeditionKey = binaryReader.ReadString(); expeditionProgressionData.MainCompletionCount = binaryReader.ReadInt32(); expeditionProgressionData.SecondaryCompletionCount = binaryReader.ReadInt32(); expeditionProgressionData.ThirdCompletionCount = binaryReader.ReadInt32(); expeditionProgressionData.AllClearCount = binaryReader.ReadInt32(); dataDict[expeditionProgressionData.ExpeditionKey] = expeditionProgressionData; } } catch (EndOfStreamException) { dataDict.Clear(); result = false; } finally { binaryReader?.Close(); fileStream?.Close(); } return result; } private bool TryReadNBSClearData(string datapath, out Dictionary<string, ExpeditionProgressionData> dataDict) { dataDict = new Dictionary<string, ExpeditionProgressionData>(); bool result = true; FileStream fileStream = null; BinaryReader binaryReader = null; if (!File.Exists(datapath)) { return true; } try { fileStream = File.Open(datapath, FileMode.Open); binaryReader = new BinaryReader(fileStream, Encoding.UTF8, leaveOpen: false); int num = binaryReader.ReadInt32(); for (int i = 0; i < num; i++) { ExpeditionProgressionData expeditionProgressionData = new ExpeditionProgressionData(); expeditionProgressionData.ExpeditionKey = binaryReader.ReadString(); expeditionProgressionData.NoBoosterAllClearCount = binaryReader.ReadInt32(); dataDict[expeditionProgressionData.ExpeditionKey] = expeditionProgressionData; } } catch (EndOfStreamException) { dataDict.Clear(); result = false; } finally { binaryReader?.Close(); fileStream?.Close(); } return result; } private void WriteOldFormatDataToDisk(string filepath, Dictionary<string, ExpeditionProgressionData> dataDict) { using FileStream output = File.Open(filepath, FileMode.Create); using BinaryWriter binaryWriter = new BinaryWriter(output, Encoding.UTF8, leaveOpen: false); binaryWriter.Write(dataDict.Count); foreach (string key in dataDict.Keys) { ExpeditionProgressionData expeditionProgressionData = dataDict[key]; binaryWriter.Write(key); binaryWriter.Write(expeditionProgressionData.MainCompletionCount); binaryWriter.Write(expeditionProgressionData.SecondaryCompletionCount); binaryWriter.Write(expeditionProgressionData.ThirdCompletionCount); binaryWriter.Write(expeditionProgressionData.AllClearCount); } } private void WriteNBSClearDataToDisk(string filepath, Dictionary<string, ExpeditionProgressionData> dataDict) { using FileStream output = File.Open(filepath, FileMode.Create); using BinaryWriter binaryWriter = new BinaryWriter(output, Encoding.UTF8, leaveOpen: false); binaryWriter.Write(dataDict.Count); foreach (string key in dataDict.Keys) { ExpeditionProgressionData expeditionProgressionData = dataDict[key]; binaryWriter.Write(key); binaryWriter.Write(expeditionProgressionData.NoBoosterAllClearCount); } } private Dictionary<string, ExpeditionProgressionData> ReadRundownLPData(string rundownName) { string text = RundownLPDataPath(rundownName); string text2 = NBSClearDataPath(rundownName); Dictionary<string, ExpeditionProgressionData> dataDict = new Dictionary<string, ExpeditionProgressionData>(); if (File.Exists(text)) { if (TryReadAggregatedFormatData(text, out dataDict)) { LPLogger.Warning(rundownName + " - aggregated format"); WriteOldFormatDataToDisk(text, dataDict); WriteNBSClearDataToDisk(text2, dataDict); LPLogger.Warning("wrote old format and nbs data"); } else if (TryReadOldFormatData(text, out dataDict)) { LPLogger.Warning(rundownName + " - old format"); if (TryReadNBSClearData(text2, out var dataDict2)) { foreach (string key in dataDict.Keys) { dataDict[key].NoBoosterAllClearCount = (dataDict2.TryGetValue(key, out var value) ? value.NoBoosterAllClearCount : 0); } } } else { LPLogger.Error("Something went wrong with localprogression data, contact the plugin developer..."); } } return dataDict; } internal RundownProgressionData GetLPDataForCurrentRundown() { return CurrentRundownPData; } private void SaveRundownLPDataToDisk() { string rundownName = CurrentRundownPData.RundownName; Dictionary<string, ExpeditionProgressionData> lPData = CurrentRundownPData.LPData; string text = RundownLPDataPath(rundownName); string filepath = NBSClearDataPath(rundownName); LPLogger.Warning($"SaveData: saving {CurrentRundownPData.RundownName} LPData to '{text}'"); WriteOldFormatDataToDisk(text, lPData); WriteNBSClearDataToDisk(filepath, lPData); } } internal static class LPLogger { private static ManualLogSource logger = Logger.CreateLogSource("LocalProgression"); public static void Log(string format, params object[] args) { Log(string.Format(format, args)); } public static void Log(string str) { if (logger != null) { logger.Log((LogLevel)8, (object)str); } } public static void Warning(string format, params object[] args) { Warning(string.Format(format, args)); } public static void Warning(string str) { if (logger != null) { logger.Log((LogLevel)4, (object)str); } } public static void Error(string format, params object[] args) { Error(string.Format(format, args)); } public static void Error(string str) { if (logger != null) { logger.Log((LogLevel)2, (object)str); } } public static void Debug(string format, params object[] args) { Debug(string.Format(format, args)); } public static void Debug(string str) { if (logger != null) { logger.Log((LogLevel)32, (object)str); } } } public static class Utils { public static bool TryGetComponent<T>(this GameObject obj, out T comp) { comp = obj.GetComponent<T>(); return comp != null; } } } namespace LocalProgression.Patches { [HarmonyPatch] internal static class Patches_CM_ExpeditionWindow { [HarmonyPostfix] [HarmonyPatch(typeof(CM_ExpeditionWindow), "Setup")] private static void Post_Setup(CM_ExpeditionWindow __instance) { ExpeditionWindow_NoBoosterIcon expeditionWindow_NoBoosterIcon = ((Component)__instance).gameObject.AddComponent<ExpeditionWindow_NoBoosterIcon>(); expeditionWindow_NoBoosterIcon.m_window = __instance; expeditionWindow_NoBoosterIcon.InitialSetup(); } [HarmonyPostfix] [HarmonyPatch(typeof(CM_ExpeditionWindow), "SetExpeditionInfo")] private static void Post_SetExpeditionInfo(CM_ExpeditionWindow __instance) { //IL_002e: 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_00a0: Unknown result type (might be due to invalid IL or missing references) ExpeditionWindow_NoBoosterIcon component = ((Component)__instance).gameObject.GetComponent<ExpeditionWindow_NoBoosterIcon>(); if (!((Object)(object)component == (Object)null)) { float num = 0f; float num2 = 410f; ((RectTransformComp)__instance.m_sectorIconMain).SetPosition(new Vector2(num, 0f)); num += num2; if (RundownManager.HasSecondaryLayer(__instance.m_data)) { num += num2; } if (RundownManager.HasThirdLayer(__instance.m_data)) { num += num2; } ExpeditionProgressionData expeditionLP = LocalProgressionManager.Current.GetExpeditionLP(LocalProgressionManager.Current.ActiveRundownID(), __instance.m_tier, __instance.m_expIndex); if (RundownManager.HasAllCompletetionPossibility(__instance.m_data) && expeditionLP.AllClearCount > 0) { num += num2; } component.SetIconPosition(new Vector2(num, 0f)); } } [HarmonyPrefix] [HarmonyPatch(typeof(CM_ExpeditionWindow), "SetVisible")] private static bool Pre_SetVisible(CM_ExpeditionWindow __instance, bool visible, bool inMenuBar) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Invalid comparison between Unknown and I4 //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Invalid comparison between Unknown and I4 //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Invalid comparison between Unknown and I4 //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Invalid comparison between Unknown and I4 //IL_033d: Unknown result type (might be due to invalid IL or missing references) ExpeditionWindow_NoBoosterIcon component = ((Component)__instance).GetComponent<ExpeditionWindow_NoBoosterIcon>(); if (!visible) { return true; } if (__instance.m_data == null) { return true; } uint rundownID = LocalProgressionManager.Current.ActiveRundownID(); ExpeditionProgressionData expeditionLP = LocalProgressionManager.Current.GetExpeditionLP(rundownID, __instance.m_tier, __instance.m_expIndex); ((Component)__instance).gameObject.SetActive(visible); ((RectTransformComp)__instance.m_joinWindow).SetVisible(!inMenuBar && !SNet.IsInLobby); ((RectTransformComp)__instance.m_hostButton).SetVisible(!inMenuBar && !SNet.IsInLobby && (int)__instance.m_status != 0 && (int)__instance.m_status != 5 && (int)__instance.m_status != 1); ((RectTransformComp)__instance.m_changeExpeditionButton).SetVisible(SNet.IsMaster && !((RectTransformComp)__instance.m_hostButton).IsVisible && !inMenuBar && SNet.IsInLobby && RundownManager.ActiveExpedition != null && (int)__instance.m_status != 0 && (int)__instance.m_status != 5 && (int)__instance.m_status != 1); __instance.m_bottomStripes.SetActive(!((RectTransformComp)__instance.m_hostButton).IsVisible && !((RectTransformComp)__instance.m_changeExpeditionButton).IsVisible); ((Component)__instance.m_title).gameObject.SetActive(false); ((Component)__instance.m_wardenObjective).gameObject.SetActive(false); ((Component)__instance.m_wardenIntel).gameObject.SetActive(false); ((Component)__instance.m_depthTitle).gameObject.SetActive(false); ((Component)__instance.m_artifactHeatTitle).gameObject.SetActive(false); CoroutineManager.BlinkIn(__instance.m_title, 0.3f, (Transform)null); CoroutineManager.BlinkIn(__instance.m_wardenObjective, 1.1f, (Transform)null); CoroutineManager.BlinkIn(__instance.m_wardenIntel, 2.5f, (Transform)null); CoroutineManager.BlinkIn(__instance.m_depthTitle, 3f, (Transform)null); CoroutineManager.BlinkIn(__instance.m_artifactHeatTitle, 3.25f, (Transform)null); float num = 1.8f; float num2 = 0.4f; __instance.m_sectorIconMain.Setup((LG_LayerType)0, __instance.m_root, true, expeditionLP.MainCompletionCount > 0, true, 0.5f, 0.8f); ((RectTransformComp)__instance.m_sectorIconMain).SetVisible(false); ((RectTransformComp)__instance.m_sectorIconSecond).SetVisible(false); ((RectTransformComp)__instance.m_sectorIconThird).SetVisible(false); ((RectTransformComp)__instance.m_sectorIconAllCompleted).SetVisible(false); component.SetVisible(visible: false); __instance.m_sectorIconMain.StopBlink(); __instance.m_sectorIconSecond.StopBlink(); __instance.m_sectorIconThird.StopBlink(); __instance.m_sectorIconAllCompleted.StopBlink(); __instance.m_sectorIconMain.BlinkIn(num); num += num2; if (RundownManager.HasSecondaryLayer(__instance.m_data)) { __instance.m_sectorIconSecond.Setup((LG_LayerType)1, __instance.m_root, true, expeditionLP.SecondaryCompletionCount > 0, true, 0.5f, 0.8f); __instance.m_sectorIconSecond.BlinkIn(num); num += num2; } if (RundownManager.HasThirdLayer(__instance.m_data)) { __instance.m_sectorIconThird.Setup((LG_LayerType)2, __instance.m_root, true, expeditionLP.ThirdCompletionCount > 0, true, 0.5f, 0.8f); __instance.m_sectorIconThird.BlinkIn(num); num += num2; } if (expeditionLP.AllClearCount > 0) { __instance.m_sectorIconAllCompleted.BlinkIn(num); num += num2; } bool flag = expeditionLP.NoBoosterAllClearCount > 0; if ((LocalProgressionManager.Current.TryGetRundownConfig(rundownID, out var rundownConf) && rundownConf.EnableNoBoosterUsedProgressionForRundown && (rundownConf.AlwaysShowIcon || flag)) || (LocalProgressionManager.Current.TryGetExpeditionConfig(rundownID, __instance.m_tier, __instance.m_expIndex, out var expConf) && expConf.EnableNoBoosterUsedProgression && (expConf.AlwaysShowIcon || flag))) { component.SetupNoBoosterUsedIcon(flag); component.BlinkIn(num); } return false; } } [HarmonyPatch] internal static class Patches_CM_ExpeditionIcon { private static readonly Color BORDER_COLOR = new Color(0f, 1f, 82f / 85f, 1f); private static readonly Color TEXT_COLOR = new Color(0f, 1f, 0.5882353f, 1f); [HarmonyPostfix] [HarmonyPatch(typeof(CM_ExpeditionIcon_New), "UpdateBorderColor")] private static void Post_UpdateBorderColor(CM_ExpeditionIcon_New __instance) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) if ((int)__instance.Status != 5) { uint rundownID = LocalProgressionManager.Current.ActiveRundownID(); if (((LocalProgressionManager.Current.TryGetRundownConfig(rundownID, out var rundownConf) && rundownConf.EnableNoBoosterUsedProgressionForRundown) || (LocalProgressionManager.Current.TryGetExpeditionConfig(rundownID, __instance.Tier, __instance.ExpIndex, out var expConf) && expConf.EnableNoBoosterUsedProgression)) && LocalProgressionManager.Current.GetExpeditionLP(rundownID, __instance.Tier, __instance.ExpIndex).NoBoosterAllClearCount > 0) { __instance.SetBorderColor(BORDER_COLOR); } } } } [HarmonyPatch] internal static class Patch_CM_PageExpeditionSuccess { [HarmonyPostfix] [HarmonyPatch(typeof(CM_PageExpeditionSuccess), "Setup")] private static void Post_Setup(CM_PageExpeditionSuccess __instance) { if ((Object)(object)((Component)__instance).GetComponent<ExpeditionSuccessPage_NoBoosterIcon>() == (Object)null) { ExpeditionSuccessPage_NoBoosterIcon expeditionSuccessPage_NoBoosterIcon = ((Component)__instance).gameObject.AddComponent<ExpeditionSuccessPage_NoBoosterIcon>(); expeditionSuccessPage_NoBoosterIcon.m_page = __instance; expeditionSuccessPage_NoBoosterIcon.Setup(); } } } [HarmonyPatch] internal class Patches_CM_PageRundown_New { [HarmonyPostfix] [HarmonyPatch(typeof(CM_PageRundown_New), "Setup")] private static void Post_Setup(CM_PageRundown_New __instance) { LocalProgressionManager.Current.SetCurrentRundownPageInstance(__instance); } [HarmonyPostfix] [HarmonyPatch(typeof(CM_PageRundown_New), "PlaceRundown")] private static void Post_PlaceRundown(CM_PageRundown_New __instance) { LocalProgressionManager.Current.OnNativeRundownProgressionUpdated(); } [HarmonyPostfix] [HarmonyPatch(typeof(CM_PageRundown_New), "OnEnable")] private static void Post_OnEnable(CM_PageRundown_New __instance) { LocalProgressionManager.Current.OnNativeRundownProgressionUpdated(); } } [HarmonyPatch] internal class Patches_CM_RundownTierMarker { [HarmonyPostfix] [HarmonyPatch(typeof(CM_RundownTierMarker), "Setup")] private static void Post_Setup(CM_RundownTierMarker __instance) { RundownTierMarker_NoBoosterIcon rundownTierMarker_NoBoosterIcon = ((Component)__instance).gameObject.AddComponent<RundownTierMarker_NoBoosterIcon>(); rundownTierMarker_NoBoosterIcon.m_tierMarker = __instance; rundownTierMarker_NoBoosterIcon.Setup(); } } [HarmonyPatch] internal class FixEndScreen { [HarmonyPrefix] [HarmonyPatch(typeof(DiscordManager), "UpdateDiscordDetails")] private static bool Pre_UpdateDiscordDetails() { return false; } } [HarmonyPatch] internal class Patches_GS_ExpeditionSuccess { [HarmonyPostfix] [HarmonyPatch(typeof(GS_ExpeditionSuccess), "Enter")] private static void DoChangeState(GS_ExpeditionSuccess __instance) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Invalid comparison between Unknown and I4 //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Invalid comparison between Unknown and I4 //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Invalid comparison between Unknown and I4 pActiveExpedition activeExpeditionData = RundownManager.GetActiveExpeditionData(); string text = LocalProgressionManager.Current.ExpeditionKey(activeExpeditionData.tier, activeExpeditionData.expeditionIndex); bool mainLayerCleared = (int)WardenObjectiveManager.CurrentState.main_status == 40; bool secondaryLayerCleared = (int)WardenObjectiveManager.CurrentState.second_status == 40; bool thirdLayerCleared = (int)WardenObjectiveManager.CurrentState.third_status == 40; bool clearedWithNoBooster = LocalProgressionManager.Current.AllSectorCompletedWithoutBoosterAndCheckpoint(); LPLogger.Debug("Level cleared, recording - " + text); LocalProgressionManager.Current.RecordExpeditionSuccessForCurrentRundown(text, mainLayerCleared, secondaryLayerCleared, thirdLayerCleared, clearedWithNoBooster); } } } namespace LocalProgression.Data { public class ExpeditionProgressionData { public string ExpeditionKey { get; set; } = string.Empty; public int MainCompletionCount { get; set; } public int SecondaryCompletionCount { get; set; } public int ThirdCompletionCount { get; set; } public int AllClearCount { get; set; } public int NoBoosterAllClearCount { get; set; } } public class ExpeditionProgressionConfig { public eRundownTier Tier { get; set; } public int ExpeditionIndex { get; set; } public bool EnableNoBoosterUsedProgression { get; set; } public bool AlwaysShowIcon { get; set; } = true; } public class RundownConfig { public uint RundownID { get; set; } public bool EnableNoBoosterUsedProgressionForRundown { get; set; } public bool AlwaysShowIcon { get; set; } = true; public List<ExpeditionProgressionConfig> Expeditions { get; set; } = new List<ExpeditionProgressionConfig> { new ExpeditionProgressionConfig() }; internal int ComputeNoBoosterClearPossibleCount() { if (EnableNoBoosterUsedProgressionForRundown) { return int.MaxValue; } return Expeditions.TakeWhile((ExpeditionProgressionConfig conf) => conf.EnableNoBoosterUsedProgression).Count(); } } public class RundownProgressonConfig { public List<RundownConfig> Configs { get; set; } = new List<RundownConfig> { new RundownConfig() }; } public class RundownProgressionData { public string RundownName { get; set; } = string.Empty; public uint RundownID { get; set; } public Dictionary<string, ExpeditionProgressionData> LPData { get; set; } = new Dictionary<string, ExpeditionProgressionData>(); public int MainClearCount { get; set; } public int SecondaryClearCount { get; set; } public int ThirdClearCount { get; set; } public int AllClearCount { get; set; } public int NoBoosterAllClearCount { get; set; } public void Reset() { RundownName = string.Empty; RundownID = 0u; LPData.Clear(); int num2 = (NoBoosterAllClearCount = 0); int num4 = (AllClearCount = num2); int num6 = (ThirdClearCount = num4); int mainClearCount = (SecondaryClearCount = num6); MainClearCount = mainClearCount; } } } namespace LocalProgression.Component { public class ExpeditionSuccessPage_NoBoosterIcon : MonoBehaviour { internal CM_PageExpeditionSuccess m_page; private CM_ExpeditionSectorIcon m_completeWithNoBoosterIcon; private SpriteRenderer m_icon; private SpriteRenderer m_bg; private TextMeshPro m_title; private TextMeshPro m_rightSideText; private NoBoosterIconGOWrapper Wrapper; internal void Setup() { if ((Object)(object)m_page == (Object)null) { LPLogger.Error("ExpeditionSuccess_NoBooster: Assign the page instance before setup"); } else { if ((Object)(object)m_completeWithNoBoosterIcon != (Object)null) { return; } if ((Object)(object)Assets.NoBoosterIcon == (Object)null) { AssetAPI.OnAssetBundlesLoaded += delegate { LoadAsset(); AssetAPI.OnAssetBundlesLoaded -= LoadAsset; }; } else { LoadAsset(); } } } private void LoadAsset() { //IL_0034: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)Assets.NoBoosterIcon == (Object)null) { LPLogger.Error("ExpeditionSuccess_NoBooster.Setup: cannot instantiate NoBooster icon..."); return; } m_completeWithNoBoosterIcon = ((Il2CppObjectBase)((GuiLayer)((CM_PageBase)m_page).m_guiLayer).AddRectComp(Assets.NoBoosterIcon, (GuiAnchor)1, new Vector2(1200f, 0f), m_page.m_sectorIconAlign)).Cast<CM_ExpeditionSectorIcon>(); Wrapper = new NoBoosterIconGOWrapper(((Component)m_completeWithNoBoosterIcon).gameObject); m_bg = Wrapper.BGGO.GetComponent<SpriteRenderer>(); m_icon = Wrapper.IconGO.GetComponent<SpriteRenderer>(); m_title = Object.Instantiate<TextMeshPro>(m_page.m_sectorIconMain.m_title); m_title.transform.SetParent(Wrapper.ObjectiveIcon.transform, false); m_rightSideText = Object.Instantiate<TextMeshPro>(m_page.m_sectorIconMain.m_rightSideText); m_rightSideText.transform.SetParent(Wrapper.RightSideText.transform, false); m_completeWithNoBoosterIcon.m_title = m_title; m_completeWithNoBoosterIcon.m_rightSideText = m_rightSideText; ((RectTransformComp)m_completeWithNoBoosterIcon).SetVisible(false); } private void OnEnable() { //IL_003b: 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_00ab: Invalid comparison between Unknown and I4 //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Invalid comparison between Unknown and I4 //IL_00fd: Unknown result type (might be due to invalid IL or missing references) ((RectTransformComp)m_completeWithNoBoosterIcon).SetVisible(false); uint rundownID = LocalProgressionManager.Current.ActiveRundownID(); pActiveExpedition activeExpeditionData = RundownManager.GetActiveExpeditionData(); if ((LocalProgressionManager.Current.TryGetRundownConfig(rundownID, out var rundownConf) && rundownConf.EnableNoBoosterUsedProgressionForRundown) || (LocalProgressionManager.Current.TryGetExpeditionConfig(rundownID, activeExpeditionData.tier, activeExpeditionData.expeditionIndex, out var expConf) && expConf.EnableNoBoosterUsedProgression)) { bool boosterUnused = LocalProgressionManager.Current.AllSectorCompletedWithoutBoosterAndCheckpoint(); int num = 1; bool flag = RundownManager.HasSecondaryLayer(RundownManager.ActiveExpedition); bool flag2 = RundownManager.HasThirdLayer(RundownManager.ActiveExpedition); num += (flag ? 1 : 0); num += (flag2 ? 1 : 0); num += ((flag && (int)WardenObjectiveManager.CurrentState.second_status == 40 && flag2 && (int)WardenObjectiveManager.CurrentState.second_status == 40) ? 1 : 0); float num2 = m_page.m_time_sectorIcon + (float)num * 0.7f; SetupNoBoosterUsedIcon(boosterUnused); ((RectTransformComp)m_completeWithNoBoosterIcon).SetPosition(new Vector2((float)num * 400f, 0f)); m_completeWithNoBoosterIcon.BlinkIn(num2); } } private void SetupNoBoosterUsedIcon(bool boosterUnused) { //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: 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: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) CM_ExpeditionSectorIcon completeWithNoBoosterIcon = m_completeWithNoBoosterIcon; completeWithNoBoosterIcon.m_isFinishedAll = true; completeWithNoBoosterIcon.SetupIcon(completeWithNoBoosterIcon.m_iconMainSkull, completeWithNoBoosterIcon.m_iconMainBG, false, false, 0.5f, 0.7f); completeWithNoBoosterIcon.SetupIcon(completeWithNoBoosterIcon.m_iconSecondarySkull, completeWithNoBoosterIcon.m_iconSecondaryBG, false, false, 0.5f, 0.7f); completeWithNoBoosterIcon.SetupIcon(completeWithNoBoosterIcon.m_iconThirdSkull, completeWithNoBoosterIcon.m_iconThirdBG, false, false, 0.5f, 0.7f); completeWithNoBoosterIcon.SetupIcon(completeWithNoBoosterIcon.m_iconFinishedAllSkull, completeWithNoBoosterIcon.m_iconFinishedAllBG, false, false, 0.5f, 0.7f); Color color = m_icon.color; Color color2 = m_bg.color; m_icon.color = new Color(color.r, color.g, color.b, boosterUnused ? 1f : 0.4f); m_bg.color = new Color(color2.r, color2.g, color2.b, boosterUnused ? 1f : 0.3f); ((TMP_Text)m_title).alpha = (boosterUnused ? 1f : 0.2f); completeWithNoBoosterIcon.m_titleVisible = true; completeWithNoBoosterIcon.m_isCleared = boosterUnused; if (boosterUnused) { completeWithNoBoosterIcon.m_isFinishedAll = true; } else { completeWithNoBoosterIcon.m_isFinishedAll = false; completeWithNoBoosterIcon.m_type = (LG_LayerType)0; } ((Component)completeWithNoBoosterIcon.m_rightSideText).gameObject.SetActive(false); TextDataBlock block = GameDataBlockBase<TextDataBlock>.GetBlock("InGame.ExpeditionSuccessPage.AllClearWithNoBoosterUsed"); if (block != null) { ((TMP_Text)completeWithNoBoosterIcon.m_title).SetText(Text.Get(((GameDataBlockBase<TextDataBlock>)(object)block).persistentID), true); } else { ((TMP_Text)completeWithNoBoosterIcon.m_title).SetText("<color=orange>OMNIPOTENT</color>", true); } ((Component)completeWithNoBoosterIcon.m_title).gameObject.SetActive(true); } private void OnDestroy() { m_icon = (m_bg = null); m_completeWithNoBoosterIcon = null; Wrapper.Destory(); } static ExpeditionSuccessPage_NoBoosterIcon() { ClassInjector.RegisterTypeInIl2Cpp<ExpeditionSuccessPage_NoBoosterIcon>(); } } internal class ExpeditionWindow_NoBoosterIcon : MonoBehaviour { internal CM_ExpeditionWindow m_window; private CM_ExpeditionSectorIcon m_completeWithNoBoosterIcon; private NoBoosterIconGOWrapper Wrapper; private SpriteRenderer m_icon; private SpriteRenderer m_bg; private TextMeshPro m_title; private TextMeshPro m_rightSideText; internal void InitialSetup() { if ((Object)(object)m_window == (Object)null) { LPLogger.Error("ExpeditionSuccess_NoBooster: Assign the page instance before setup"); } else { if ((Object)(object)m_completeWithNoBoosterIcon != (Object)null) { return; } if ((Object)(object)Assets.NoBoosterIcon == (Object)null) { AssetAPI.OnAssetBundlesLoaded += delegate { LoadAsset(); AssetAPI.OnAssetBundlesLoaded -= LoadAsset; }; } else { LoadAsset(); } } } private void LoadAsset() { if ((Object)(object)Assets.NoBoosterIcon == (Object)null) { LPLogger.Error("ExpeditionSuccess_NoBooster.Setup: cannot instantiate NoBooster icon..."); return; } m_completeWithNoBoosterIcon = GOUtil.SpawnChildAndGetComp<CM_ExpeditionSectorIcon>(Assets.NoBoosterIcon, m_window.m_sectorIconAlign); Wrapper = new NoBoosterIconGOWrapper(((Component)m_completeWithNoBoosterIcon).gameObject); m_bg = Wrapper.BGGO.GetComponent<SpriteRenderer>(); m_icon = Wrapper.IconGO.GetComponent<SpriteRenderer>(); m_title = Object.Instantiate<TextMeshPro>(m_window.m_sectorIconMain.m_title); m_title.transform.SetParent(Wrapper.ObjectiveIcon.transform, false); m_rightSideText = Object.Instantiate<TextMeshPro>(m_window.m_sectorIconMain.m_rightSideText); m_rightSideText.transform.SetParent(Wrapper.RightSideText.transform, false); m_completeWithNoBoosterIcon.m_title = m_title; m_completeWithNoBoosterIcon.m_rightSideText = m_rightSideText; ((RectTransformComp)m_completeWithNoBoosterIcon).SetAnchor((GuiAnchor)1, true); ((RectTransformComp)m_completeWithNoBoosterIcon).SetVisible(false); m_completeWithNoBoosterIcon.SortAsPopupLayer(); m_completeWithNoBoosterIcon.m_root = m_window.m_root; } internal void SetVisible(bool visible) { ((RectTransformComp)m_completeWithNoBoosterIcon).SetVisible(visible); } internal void SetIconPosition(Vector2 position) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) ((RectTransformComp)m_completeWithNoBoosterIcon).SetPosition(position); } internal void BlinkIn(float delay) { m_completeWithNoBoosterIcon.BlinkIn(delay); } internal void SetupNoBoosterUsedIcon(bool boosterUnused) { //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: 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: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) CM_ExpeditionSectorIcon completeWithNoBoosterIcon = m_completeWithNoBoosterIcon; completeWithNoBoosterIcon.m_isFinishedAll = true; completeWithNoBoosterIcon.SetupIcon(completeWithNoBoosterIcon.m_iconMainSkull, completeWithNoBoosterIcon.m_iconMainBG, false, false, 0.5f, 0.7f); completeWithNoBoosterIcon.SetupIcon(completeWithNoBoosterIcon.m_iconSecondarySkull, completeWithNoBoosterIcon.m_iconSecondaryBG, false, false, 0.5f, 0.7f); completeWithNoBoosterIcon.SetupIcon(completeWithNoBoosterIcon.m_iconThirdSkull, completeWithNoBoosterIcon.m_iconThirdBG, false, false, 0.5f, 0.7f); completeWithNoBoosterIcon.SetupIcon(completeWithNoBoosterIcon.m_iconFinishedAllSkull, completeWithNoBoosterIcon.m_iconFinishedAllBG, false, false, 0.5f, 0.7f); Color color = m_icon.color; Color color2 = m_bg.color; m_icon.color = new Color(color.r, color.g, color.b, boosterUnused ? 1f : 0.4f); m_bg.color = new Color(color2.r, color2.g, color2.b, boosterUnused ? 1f : 0.3f); ((TMP_Text)m_title).alpha = (boosterUnused ? 1f : 0.2f); completeWithNoBoosterIcon.m_titleVisible = true; completeWithNoBoosterIcon.m_isCleared = boosterUnused; if (boosterUnused) { completeWithNoBoosterIcon.m_isFinishedAll = true; } else { completeWithNoBoosterIcon.m_isFinishedAll = false; completeWithNoBoosterIcon.m_type = (LG_LayerType)0; } ((Component)completeWithNoBoosterIcon.m_rightSideText).gameObject.SetActive(false); TextDataBlock block = GameDataBlockBase<TextDataBlock>.GetBlock("InGame.ExpeditionSuccessPage.AllClearWithNoBoosterUsed"); if (block != null) { ((TMP_Text)completeWithNoBoosterIcon.m_title).SetText(Text.Get(((GameDataBlockBase<TextDataBlock>)(object)block).persistentID), true); } else { ((TMP_Text)completeWithNoBoosterIcon.m_title).SetText("<color=orange>OMNIPOTENT</color>", true); } ((Component)completeWithNoBoosterIcon.m_title).gameObject.SetActive(true); } private void OnDestroy() { m_icon = (m_bg = null); m_completeWithNoBoosterIcon = null; Wrapper.Destory(); } static ExpeditionWindow_NoBoosterIcon() { ClassInjector.RegisterTypeInIl2Cpp<ExpeditionWindow_NoBoosterIcon>(); } } public class NoBoosterIconGOWrapper { public GameObject GameObject { get; private set; } public GameObject ObjectiveIcon { get { GameObject gameObject = GameObject; if (gameObject == null) { return null; } return ((Component)gameObject.transform.GetChild(0)).gameObject; } } public GameObject BGHolder { get { GameObject objectiveIcon = ObjectiveIcon; if (objectiveIcon == null) { return null; } return ((Component)objectiveIcon.transform.GetChild(2)).gameObject; } } public GameObject SkullHolder { get { GameObject objectiveIcon = ObjectiveIcon; if (objectiveIcon == null) { return null; } return ((Component)objectiveIcon.transform.GetChild(3)).gameObject; } } public GameObject BGGO { get { GameObject bGHolder = BGHolder; if (bGHolder == null) { return null; } return ((Component)bGHolder.transform.GetChild(4)).gameObject; } } public GameObject IconGO { get { GameObject skullHolder = SkullHolder; if (skullHolder == null) { return null; } return ((Component)skullHolder.transform.GetChild(4)).gameObject; } } public GameObject TitleGO { get { GameObject objectiveIcon = ObjectiveIcon; if (objectiveIcon == null) { return null; } return ((Component)objectiveIcon.transform.GetChild(1)).gameObject; } } public GameObject RightSideText { get { GameObject gameObject = GameObject; if (gameObject == null) { return null; } return ((Component)gameObject.transform.GetChild(2)).gameObject; } } public NoBoosterIconGOWrapper(GameObject iconGO) { GameObject = iconGO; } public void Destory() { if ((Object)(object)GameObject != (Object)null) { Object.Destroy((Object)(object)GameObject); } GameObject = null; } } internal class RundownTierMarker_NoBoosterIcon : MonoBehaviour { internal CM_RundownTierMarker m_tierMarker; private CM_ExpeditionSectorIcon m_completeWithNoBoosterIcon; private SpriteRenderer m_icon; private SpriteRenderer m_bg; private TextMeshPro m_title; private TextMeshPro m_rightSideText; private NoBoosterIconGOWrapper Wrapper; internal void Setup() { if ((Object)(object)m_tierMarker == (Object)null) { LPLogger.Error("ExpeditionSuccess_NoBooster: Assign the page instance before setup"); } else { if ((Object)(object)m_completeWithNoBoosterIcon != (Object)null) { return; } if ((Object)(object)Assets.NoBoosterIcon == (Object)null) { AssetAPI.OnAssetBundlesLoaded += delegate { LoadAsset(); AssetAPI.OnAssetBundlesLoaded -= LoadAsset; }; } else { LoadAsset(); } } } private void LoadAsset() { //IL_0139: 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_015a: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Unknown result type (might be due to invalid IL or missing references) //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)Assets.NoBoosterIcon == (Object)null) { LPLogger.Error("ExpeditionSuccess_NoBooster.Setup: cannot instantiate NoBooster icon..."); return; } m_completeWithNoBoosterIcon = GOUtil.SpawnChildAndGetComp<CM_ExpeditionSectorIcon>(Assets.NoBoosterIcon, m_tierMarker.m_sectorIconAlign_main); Wrapper = new NoBoosterIconGOWrapper(((Component)m_completeWithNoBoosterIcon).gameObject); m_bg = Wrapper.BGGO.GetComponent<SpriteRenderer>(); m_icon = Wrapper.IconGO.GetComponent<SpriteRenderer>(); m_title = Object.Instantiate<TextMeshPro>(m_tierMarker.m_sectorIconSummaryMain.m_title); m_title.transform.SetParent(Wrapper.ObjectiveIcon.transform, false); m_rightSideText = Object.Instantiate<TextMeshPro>(m_tierMarker.m_sectorIconSummaryMain.m_rightSideText); m_rightSideText.transform.SetParent(Wrapper.RightSideText.transform, false); m_completeWithNoBoosterIcon.m_title = m_title; m_completeWithNoBoosterIcon.m_rightSideText = m_rightSideText; SetupNoBoosterUsedIcon(boosterUnused: true); float num = 0.16f; Vector3 localScale = default(Vector3); ((Vector3)(ref localScale))..ctor(num, num, num); _ = num / 0.16f; ((Component)m_completeWithNoBoosterIcon).transform.localScale = localScale; Vector2 val = ((RectTransformComp)m_tierMarker.m_sectorIconSummarySecondary).GetPosition() - ((RectTransformComp)m_tierMarker.m_sectorIconSummaryMain).GetPosition(); ((RectTransformComp)m_completeWithNoBoosterIcon).SetPosition(val * 4f); ((RectTransformComp)m_completeWithNoBoosterIcon).SetVisible(false); } internal void SetVisible(bool visible) { ((RectTransformComp)m_completeWithNoBoosterIcon).SetVisible(visible); } internal void SetSectorIconText(string text) { ((RectTransformComp)m_completeWithNoBoosterIcon).SetVisible(true); m_completeWithNoBoosterIcon.SetRightSideText(text); } private void SetupNoBoosterUsedIcon(bool boosterUnused) { //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: 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: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) CM_ExpeditionSectorIcon completeWithNoBoosterIcon = m_completeWithNoBoosterIcon; completeWithNoBoosterIcon.m_isFinishedAll = true; completeWithNoBoosterIcon.SetupIcon(completeWithNoBoosterIcon.m_iconMainSkull, completeWithNoBoosterIcon.m_iconMainBG, false, false, 0.5f, 0.7f); completeWithNoBoosterIcon.SetupIcon(completeWithNoBoosterIcon.m_iconSecondarySkull, completeWithNoBoosterIcon.m_iconSecondaryBG, false, false, 0.5f, 0.7f); completeWithNoBoosterIcon.SetupIcon(completeWithNoBoosterIcon.m_iconThirdSkull, completeWithNoBoosterIcon.m_iconThirdBG, false, false, 0.5f, 0.7f); completeWithNoBoosterIcon.SetupIcon(completeWithNoBoosterIcon.m_iconFinishedAllSkull, completeWithNoBoosterIcon.m_iconFinishedAllBG, false, false, 0.5f, 0.7f); Color color = m_icon.color; Color color2 = m_bg.color; m_icon.color = new Color(color.r, color.g, color.b, boosterUnused ? 1f : 0.4f); m_bg.color = new Color(color2.r, color2.g, color2.b, boosterUnused ? 1f : 0.3f); ((TMP_Text)m_title).alpha = (boosterUnused ? 1f : 0.2f); completeWithNoBoosterIcon.m_titleVisible = true; completeWithNoBoosterIcon.m_isCleared = boosterUnused; if (boosterUnused) { completeWithNoBoosterIcon.m_isFinishedAll = true; } else { completeWithNoBoosterIcon.m_isFinishedAll = false; completeWithNoBoosterIcon.m_type = (LG_LayerType)0; } ((Component)completeWithNoBoosterIcon.m_rightSideText).gameObject.SetActive(false); TextDataBlock block = GameDataBlockBase<TextDataBlock>.GetBlock("InGame.ExpeditionSuccessPage.AllClearWithNoBoosterUsed"); if (block != null) { ((TMP_Text)completeWithNoBoosterIcon.m_title).SetText(Text.Get(((GameDataBlockBase<TextDataBlock>)(object)block).persistentID), true); } else { ((TMP_Text)completeWithNoBoosterIcon.m_title).SetText("<color=orange>OMNIPOTENT</color>", true); } ((Component)completeWithNoBoosterIcon.m_title).gameObject.SetActive(true); } static RundownTierMarker_NoBoosterIcon() { ClassInjector.RegisterTypeInIl2Cpp<RundownTierMarker_NoBoosterIcon>(); } } }
plugins/net6/InjectLib.dll
Decompiled a month agousing System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; using BepInEx; using BepInEx.Core.Logging.Interpolation; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using BepInEx.Unity.IL2CPP.Hook; using GTFO.API; using GTFO.API.JSON; using Il2CppInterop.Runtime; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.Runtime; using Il2CppInterop.Runtime.Runtime.VersionSpecific.Class; using Il2CppJsonNet; using Il2CppJsonNet.Converters; using Il2CppJsonNet.Linq; using Il2CppJsonNet.Serialization; using Il2CppSystem; using Il2CppSystem.Runtime.InteropServices; using InjectLib.FieldInjection; using InjectLib.JsonNETInjection; using InjectLib.JsonNETInjection.Converter; using InjectLib.JsonNETInjection.Detours; using InjectLib.JsonNETInjection.Handler; using InjectLib.Utils; using Microsoft.CodeAnalysis; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")] [assembly: AssemblyCompany("InjectLib")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+gitc83a124-master")] [assembly: AssemblyProduct("InjectLib")] [assembly: AssemblyTitle("InjectLib")] [assembly: TargetPlatform("Windows7.0")] [assembly: SupportedOSPlatform("Windows7.0")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsUnmanagedAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NativeIntegerAttribute : Attribute { public readonly bool[] TransformFlags; public NativeIntegerAttribute() { TransformFlags = new bool[1] { true }; } public NativeIntegerAttribute(bool[] P_0) { TransformFlags = P_0; } } } namespace InjectLib { [BepInPlugin("GTFO.InjectLib", "InjectLib", "1.0.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] internal class EntryPoint : BasePlugin { public override void Load() { NativeJsonProcessorStore.Initialize(); } public override bool Unload() { return ((BasePlugin)this).Unload(); } } internal static class Logger { private static readonly ManualLogSource _Logger; static Logger() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Expected O, but got Unknown _Logger = new ManualLogSource("InjectLib"); Logger.Sources.Add((ILogSource)(object)_Logger); } private static string Format(object msg) { return msg.ToString(); } public static void Info(BepInExInfoLogInterpolatedStringHandler handler) { _Logger.LogInfo(handler); } public static void Info(string str) { _Logger.LogMessage((object)str); } public static void Info(object data) { _Logger.LogMessage((object)Format(data)); } public static void Debug(BepInExDebugLogInterpolatedStringHandler handler) { _Logger.LogDebug(handler); } public static void Debug(string str) { _Logger.LogDebug((object)str); } public static void Debug(object data) { _Logger.LogDebug((object)Format(data)); } public static void Error(BepInExErrorLogInterpolatedStringHandler handler) { _Logger.LogError(handler); } public static void Error(string str) { _Logger.LogError((object)str); } public static void Error(object data) { _Logger.LogError((object)Format(data)); } public static void Fatal(BepInExFatalLogInterpolatedStringHandler handler) { _Logger.LogFatal(handler); } public static void Fatal(string str) { _Logger.LogFatal((object)str); } public static void Fatal(object data) { _Logger.LogFatal((object)Format(data)); } public static void Warn(BepInExWarningLogInterpolatedStringHandler handler) { _Logger.LogWarning(handler); } public static void Warn(string str) { _Logger.LogWarning((object)str); } public static void Warn(object data) { _Logger.LogWarning((object)Format(data)); } [Conditional("DEBUG")] public static void DebugOnly(object data) { } } [GeneratedCode("VersionInfoGenerator", "2.1.3+git35c0c2a-master")] [CompilerGenerated] internal static class VersionInfo { public const string RootNamespace = "InjectLib"; public const string Version = "1.0.0"; public const string VersionPrerelease = null; public const string VersionMetadata = "gitc83a124-master"; public const string SemVer = "1.0.0+gitc83a124-master"; public const string GitRevShort = "c83a124"; public const string GitRevLong = "c83a124696b1272397115ca04d902622f35ba87e"; public const string GitBranch = "master"; public const string GitTag = null; public const int GitCommitsSinceTag = 0; public const bool GitIsDirty = false; } } namespace InjectLib.Utils { internal static class FieldsExtension { public static void SetNativeJsonProcessor(this DataSetConverter converter, NativeJsonProcessor processor) { FieldInjector<DataSetConverter>.TrySetManagedField(converter, "m_JsonProcessor", processor); } public static NativeJsonProcessor GetNativeJsonProcessor(this DataSetConverter converter) { FieldInjector<DataSetConverter>.TryGetManagedField<NativeJsonProcessor>(converter, "m_JsonProcessor", out var value); return value; } } internal static class ObjectCopier { public static void CopyProperties<T>(T source, T target) where T : Il2CppObjectBase { PropertyInfo[] properties = typeof(T).GetProperties(); foreach (PropertyInfo propertyInfo in properties) { Type propertyType = propertyInfo.PropertyType; if (!propertyInfo.Name.Contains("_k__BackingField") && !(propertyType == typeof(IntPtr)) && propertyInfo.CanRead && propertyInfo.CanWrite) { propertyInfo.SetValue(target, propertyInfo.GetValue(source)); } } } } } namespace InjectLib.JsonNETInjection { public static class JsonInjector { static JsonInjector() { FieldInjector<DataSetConverter>.DefineManagedField<NativeJsonProcessor>("m_JsonProcessor"); } public static void SetConverter<T>(Il2CppJsonReferenceTypeConverter<T> converter) where T : Il2CppObjectBase { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Expected O, but got Unknown //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Expected O, but got Unknown if (converter == null) { throw new ArgumentNullException("converter"); } if (!NativeJsonProcessorStore.Prepare<T>(out var processor)) { return; } if (processor.Converter != null) { bool flag = default(bool); BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(76, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Converter (type: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(typeof(T).FullName); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(") will be replaced! This would leads to unwanted behaviour!"); } Logger.Warn(val); Logger.Warn(" - Suggetion: If your converter does not require to deep-level altering of JSON, consider use Il2CppJsonReferenceTypeHandler instead."); val = new BepInExWarningLogInterpolatedStringHandler(19, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Previous Owner: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(processor.Converter.GetType().Assembly.FullName); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" / "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(processor.Converter.GetType().FullName); } Logger.Warn(val); val = new BepInExWarningLogInterpolatedStringHandler(14, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("New Owner: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(converter.GetType().Assembly.FullName); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" / "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(converter.GetType().FullName); } Logger.Warn(val); } processor.Converter = converter; } public static void SetConverter<T>(Il2CppJsonUnmanagedTypeConverter<T> converter) where T : unmanaged { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Expected O, but got Unknown //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Expected O, but got Unknown if (converter == null) { throw new ArgumentNullException("converter"); } if (!NativeJsonProcessorStore.Prepare<T>(out var processor)) { return; } if (processor.Converter != null) { bool flag = default(bool); BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(76, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Converter (type: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(typeof(T).FullName); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(") will be replaced! This would leads to unwanted behaviour!"); } Logger.Warn(val); Logger.Warn(" - Suggetion: If your converter does not require to deep-level altering of JSON, consider use Il2CppJsonUnmanagedTypeHandler instead."); val = new BepInExWarningLogInterpolatedStringHandler(22, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" - Previous Owner: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(processor.Converter.GetType().Assembly.FullName); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" / "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(processor.Converter.GetType().FullName); } Logger.Warn(val); val = new BepInExWarningLogInterpolatedStringHandler(17, 2, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" - New Owner: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(converter.GetType().Assembly.FullName); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" / "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(converter.GetType().FullName); } Logger.Warn(val); } processor.Converter = converter; } public static void AddHandler<T>(Il2CppJsonReferenceTypeHandler<T> handler) where T : Il2CppObjectBase { if (handler == null) { throw new ArgumentNullException("handler"); } if (NativeJsonProcessorStore.Prepare<T>(out var processor)) { processor.Handlers.Add(handler); } } public static void AddHandler<T>(Il2CppJsonUnmanagedTypeHandler<T> handler) where T : unmanaged { if (handler == null) { throw new ArgumentNullException("handler"); } if (NativeJsonProcessorStore.Prepare<T>(out var processor)) { processor.Handlers.Add(handler); } } } internal class NativeJsonProcessor { public Type Type { get; set; } public DataSetConverter DummyConverter { get; set; } public INativeJsonConverter Converter { get; set; } public IList<INativeJsonHandler> Handlers { get; } = new List<INativeJsonHandler>(); public bool Enabled { get; set; } = true; public IntPtr ProcessRead(JsonReader reader, IntPtr existingValue, JsonSerializer serializer) { JToken jToken = JToken.ReadFrom(reader); IntPtr pointer; if (Converter != null) { pointer = ((Il2CppObjectBase)Converter.ReadJson(jToken, existingValue, serializer)).Pointer; } else { SetUsingContractConverter(serializer, use: false); pointer = ((Il2CppObjectBase)serializer.Deserialize(jToken.CreateReader(), Type)).Pointer; SetUsingContractConverter(serializer, use: true); } Object result = PtrToObject(pointer); foreach (INativeJsonHandler handler in Handlers) { handler.OnRead(in result, in jToken); } return pointer; } public void ProcessWrite(JsonWriter writer, IntPtr valueToWrite, JsonSerializer serializer) { if (Converter != null) { Converter.WriteJson(writer, valueToWrite, serializer); return; } SetUsingContractConverter(serializer, use: false); serializer.Serialize(writer, PtrToObject(valueToWrite)); SetUsingContractConverter(serializer, use: true); } private static Object PtrToObject(IntPtr ptr) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown if (ptr == IntPtr.Zero) { return null; } return new Object(ptr); } private void SetUsingContractConverter(JsonSerializer serializer, bool use) { JsonContract val = serializer.ContractResolver.ResolveContract(Type); if (use) { val.Converter = (JsonConverter)(object)DummyConverter; val.InternalConverter = (JsonConverter)(object)DummyConverter; } else { val.Converter = null; val.InternalConverter = null; } } } internal static class NativeJsonProcessorStore { private static readonly Dictionary<IntPtr, NativeJsonProcessor> _RegisteredProcessors = new Dictionary<IntPtr, NativeJsonProcessor>(); internal static void Initialize() { Detour_JsonConverterTrampoline.Patch(); Detour_NativeConverterLink.Patch(); } public static bool Prepare<T>(out NativeJsonProcessor processor) { //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Expected O, but got Unknown //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Expected O, but got Unknown Type val = Il2CppType.From(typeof(T)); if (val != (Type)null && ((Il2CppObjectBase)val).Pointer != IntPtr.Zero) { if (_RegisteredProcessors.TryGetValue(((Il2CppObjectBase)val).Pointer, out processor)) { return true; } DataSetConverter val2 = new DataSetConverter(); NativeJsonProcessor nativeJsonProcessor2 = (_RegisteredProcessors[((Il2CppObjectBase)val).Pointer] = new NativeJsonProcessor()); processor = nativeJsonProcessor2; processor.Type = val; processor.DummyConverter = val2; val2.SetNativeJsonProcessor(processor); return true; } bool flag = default(bool); BepInExErrorLogInterpolatedStringHandler val3 = new BepInExErrorLogInterpolatedStringHandler(33, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Type: '"); ((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(typeof(T).Name); ((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("' is not in il2cpp domain!"); } Logger.Error(val3); processor = null; return false; } public static bool TryGetConverterPointer(IntPtr typePtr, out IntPtr converterPtr) { if (TryGetProcessor(typePtr, out var processor) && processor.DummyConverter != null) { converterPtr = ((Il2CppObjectBase)processor.DummyConverter).Pointer; return converterPtr != IntPtr.Zero; } converterPtr = IntPtr.Zero; return false; } public static bool TryGetProcessor(IntPtr typePtr, out NativeJsonProcessor processor) { if (_RegisteredProcessors.TryGetValue(typePtr, out processor) && processor != null && processor.Enabled) { return processor != null; } processor = null; return false; } } } namespace InjectLib.JsonNETInjection.Supports { internal interface IBaseConnector { NativeJsonProcessor Processor { get; set; } } public sealed class InjectLibConnector : JsonConverterFactory { public override bool CanConvert(Type typeToConvert) { Type val = Il2CppType.From(typeToConvert, false); if (val != (Type)null && NativeJsonProcessorStore.TryGetProcessor(((Il2CppObjectBase)val).Pointer, out var _)) { return true; } return false; } public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) { if (!NativeJsonProcessorStore.TryGetProcessor(((Il2CppObjectBase)Il2CppType.From(typeToConvert, false)).Pointer, out var processor)) { return null; } if (typeToConvert.IsAssignableTo(typeof(Il2CppObjectBase))) { JsonConverter obj = (JsonConverter)Activator.CreateInstance(typeof(ReferenceTypeConnector<>).MakeGenericType(typeToConvert), BindingFlags.Instance | BindingFlags.Public, null, null, null); ((IBaseConnector)obj).Processor = processor; return obj; } if (typeToConvert.IsValueType) { JsonConverter obj2 = (JsonConverter)Activator.CreateInstance(typeof(ValueTypeConnector<>).MakeGenericType(typeToConvert), BindingFlags.Instance | BindingFlags.Public, null, null, null); ((IBaseConnector)obj2).Processor = processor; return obj2; } return null; } } public class InjectLibJSON { public static JsonSerializerOptions JsonOptions => new JsonSerializerOptions(JsonSerializer.DefaultSerializerSettingsWithLocalizedText) { Converters = { (JsonConverter)new InjectLibConnector() } }; public static T Deserialize<T>(string json, params JsonConverter[] converters) { JsonSerializerOptions jsonOptions = JsonOptions; if (converters != null) { foreach (JsonConverter item in converters) { jsonOptions.Converters.Add(item); } } return JsonSerializer.Deserialize<T>(json, jsonOptions); } public static object Deserialize(string json, Type type, params JsonConverter[] converters) { JsonSerializerOptions jsonOptions = JsonOptions; if (converters != null) { foreach (JsonConverter item in converters) { jsonOptions.Converters.Add(item); } } return JsonSerializer.Deserialize(json, type, jsonOptions); } public static string Serialize<T>(T obj, params JsonConverter[] converters) { JsonSerializerOptions jsonOptions = JsonOptions; if (converters != null) { foreach (JsonConverter item in converters) { jsonOptions.Converters.Add(item); } } return JsonSerializer.Serialize(obj, JsonOptions); } public static string Serialize(object obj, params JsonConverter[] converters) { JsonSerializerOptions jsonOptions = JsonOptions; if (converters != null) { foreach (JsonConverter item in converters) { jsonOptions.Converters.Add(item); } } return JsonSerializer.Serialize(obj, JsonOptions); } } internal class ReferenceTypeConnector<T> : JsonConverter<T>, IBaseConnector where T : Il2CppObjectBase { public NativeJsonProcessor Processor { get; set; } public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { Type val = Il2CppType.From(typeToConvert, false); JsonNode jsonNode = JsonNode.Parse(ref reader); return (T)Activator.CreateInstance(typeof(T), ((Il2CppObjectBase)JsonConvert.DeserializeObject(jsonNode.ToJsonString(), val, (JsonSerializerSettings)null)).Pointer); } public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) { JsonSerializer.Serialize(writer, value); } } internal class ValueTypeConnector<T> : JsonConverter<T>, IBaseConnector where T : unmanaged { public NativeJsonProcessor Processor { get; set; } public override T Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { Type val = Il2CppType.From(typeToConvert, false); return ((Il2CppObjectBase)JsonConvert.DeserializeObject(JsonNode.Parse(ref reader).ToJsonString(), val, (JsonSerializerSettings)null)).Unbox<T>(); } public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options) { JsonSerializer.Serialize(writer, value); } } } namespace InjectLib.JsonNETInjection.Handler { public abstract class Il2CppJsonReferenceTypeHandler<T> : INativeJsonHandler where T : Il2CppObjectBase { public abstract void OnRead(in Object result, in JToken jToken); } public abstract class Il2CppJsonUnmanagedTypeHandler<T> : INativeJsonHandler where T : unmanaged { public abstract void OnRead(in Object result, in JToken jToken); } internal interface INativeJsonHandler { void OnRead(in Object result, in JToken jToken); } } namespace InjectLib.JsonNETInjection.Detours { internal class Detour_JsonConverterTrampoline { public unsafe delegate IntPtr GetMatchingConverterDel(IntPtr converters, IntPtr objectType, Il2CppMethodInfo* methodInfo); private static INativeDetour _Detour; private static GetMatchingConverterDel _Original; public unsafe static void Patch() { _Detour = INativeDetour.CreateAndApply<GetMatchingConverterDel>((IntPtr)(nint)Il2CppAPI.GetIl2CppMethod<JsonSerializer>("GetMatchingConverter", "Newtonsoft.Json.JsonConverter", false, new string[2] { "System.Collections.Generic.IList<Newtonsoft.Json.JsonConverter>", typeof(Type).FullName }), (GetMatchingConverterDel)Detour, ref _Original); } private unsafe static IntPtr Detour(IntPtr converters, IntPtr objectType, Il2CppMethodInfo* methodInfo) { if (NativeJsonProcessorStore.TryGetConverterPointer(objectType, out var converterPtr)) { return converterPtr; } return _Original(converters, objectType, methodInfo); } } internal class Detour_NativeConverterLink { public delegate IntPtr ReadJsonDel(IntPtr _this, IntPtr reader, IntPtr objectType, IntPtr existingValue, IntPtr serializer); public delegate void WriteJsonDel(IntPtr _this, IntPtr writer, IntPtr value, IntPtr serializer); private static INativeDetour _ReadDetour; private static INativeDetour _WriteDetour; private static ReadJsonDel _ReadOriginal; private static WriteJsonDel _WriteOriginal; public unsafe static void Patch() { void* il2CppMethod = Il2CppAPI.GetIl2CppMethod<DataSetConverter>("ReadJson", "System.Object", false, new string[4] { "Newtonsoft.Json.JsonReader", "System.Type", "System.Object", "Newtonsoft.Json.JsonSerializer" }); void* il2CppMethod2 = Il2CppAPI.GetIl2CppMethod<DataSetConverter>("WriteJson", typeof(void).FullName, false, new string[3] { "Newtonsoft.Json.JsonWriter", "System.Object", "Newtonsoft.Json.JsonSerializer" }); _ReadDetour = INativeDetour.CreateAndApply<ReadJsonDel>((IntPtr)(nint)il2CppMethod, (ReadJsonDel)Detour_Read, ref _ReadOriginal); _WriteDetour = INativeDetour.CreateAndApply<WriteJsonDel>((IntPtr)(nint)il2CppMethod2, (WriteJsonDel)Detour_Write, ref _WriteOriginal); } private static IntPtr Detour_Read(IntPtr _this, IntPtr reader, IntPtr objectType, IntPtr existingValue, IntPtr serializer) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown NativeJsonProcessor nativeJsonProcessor = FieldsExtension.GetNativeJsonProcessor(new DataSetConverter(_this)); if (nativeJsonProcessor != null) { JsonReader reader2 = new JsonReader(reader); JsonSerializer serializer2 = new JsonSerializer(serializer); return nativeJsonProcessor.ProcessRead(reader2, existingValue, serializer2); } return _ReadOriginal(_this, reader, objectType, existingValue, serializer); } private static void Detour_Write(IntPtr _this, IntPtr writer, IntPtr value, IntPtr serializer) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown NativeJsonProcessor nativeJsonProcessor = FieldsExtension.GetNativeJsonProcessor(new DataSetConverter(_this)); if (nativeJsonProcessor != null) { JsonWriter writer2 = new JsonWriter(writer); JsonSerializer serializer2 = new JsonSerializer(serializer); nativeJsonProcessor.ProcessWrite(writer2, value, serializer2); } else { _WriteOriginal(_this, writer, value, serializer); } } } } namespace InjectLib.JsonNETInjection.Converter { public abstract class Il2CppJsonReferenceTypeConverter<T> : INativeJsonConverter where T : Il2CppObjectBase { public virtual string Name => GetType().Name; public Object ReadJson(JToken jToken, IntPtr existingValue, JsonSerializer serializer) { if (existingValue == IntPtr.Zero) { return ((Il2CppObjectBase)Read(jToken, default(T), serializer)).Cast<Object>(); } T existingValue2 = (T)Activator.CreateInstance(typeof(T), existingValue); return ((Il2CppObjectBase)Read(jToken, existingValue2, serializer)).Cast<Object>(); } public void WriteJson(JsonWriter writer, IntPtr valueToWrite, JsonSerializer serializer) { if (valueToWrite == IntPtr.Zero) { Write(writer, default(T), serializer); return; } T value = (T)Activator.CreateInstance(typeof(T), valueToWrite); Write(writer, value, serializer); } protected abstract T Read(JToken jToken, T existingValue, JsonSerializer serializer); protected abstract void Write(JsonWriter writer, T value, JsonSerializer serializer); } public abstract class Il2CppJsonUnmanagedTypeConverter<T> : INativeJsonConverter where T : unmanaged { public virtual string Name => GetType().Name; public Object ReadJson(JToken jToken, IntPtr existingValue, JsonSerializer serializer) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown if (existingValue == IntPtr.Zero) { return ToIl2CppObject(Read(jToken, default(T), serializer)); } Object val = new Object(existingValue); return ToIl2CppObject(Read(jToken, ((Il2CppObjectBase)val).Unbox<T>(), serializer)); } public void WriteJson(JsonWriter writer, IntPtr valueToWrite, JsonSerializer serializer) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Expected O, but got Unknown if (valueToWrite == IntPtr.Zero) { Write(writer, default(T), serializer); return; } Object val = new Object(valueToWrite); Write(writer, ((Il2CppObjectBase)val).Unbox<T>(), serializer); } protected abstract T Read(JToken jToken, T existingValue, JsonSerializer serializer); protected abstract void Write(JsonWriter writer, T value, JsonSerializer serializer); protected abstract Object ToIl2CppObject(T value); } internal interface INativeJsonConverter { string Name { get; } Object ReadJson(JToken jToken, IntPtr existingValue, JsonSerializer serializer); void WriteJson(JsonWriter writer, IntPtr valueToWrite, JsonSerializer serializer); } } namespace InjectLib.FieldInjection { public static class FieldInjector<Il2CppType> where Il2CppType : Il2CppObjectBase { private static readonly Dictionary<string, InjectedFieldInfo> _OffsetLookup = new Dictionary<string, InjectedFieldInfo>(); public static void DefineValueField<Value>(string fieldName) where Value : unmanaged { if (!_OffsetLookup.ContainsKey(fieldName)) { InjectValueField<Value>(fieldName); } } public static void DefineManagedField<Value>(string fieldName) where Value : class { if (!_OffsetLookup.ContainsKey(fieldName)) { InjectManagedField<Value>(fieldName); } } private unsafe static void InjectManagedField<Value>(string fieldName) where Value : class { int num = 8; INativeClassStruct val = UnityVersionHandler.Wrap((Il2CppClass*)(void*)Il2CppClassPointerStore<Il2CppType>.NativeClassPtr); val.InstanceSize += (uint)num; val.ActualSize = val.InstanceSize; _OffsetLookup[fieldName] = new InjectedFieldInfo { FieldOffset = (nint)(val.InstanceSize - num), FieldSize = num }; } public unsafe static bool TryGetManagedField<Value>(Il2CppType obj, string fieldName, out Value value) where Value : class { if (obj == null) { value = null; return false; } if (((Il2CppObjectBase)obj).Pointer == IntPtr.Zero) { value = null; return false; } if (!_OffsetLookup.TryGetValue(fieldName, out var value2)) { value = null; return false; } if (8 != value2.FieldSize) { value = null; return false; } ulong num = *(ulong*)((nint)((Il2CppObjectBase)obj).Pointer + value2.FieldOffset); if (num == 0L) { value = null; return false; } value = ManagedReferenceStore<Il2CppType, Value>.Get(num); return value != null; } public unsafe static bool TrySetManagedField<Value>(Il2CppType obj, string fieldName, Value value) where Value : class { if (obj == null) { return false; } if (((Il2CppObjectBase)obj).Pointer == IntPtr.Zero) { return false; } if (!_OffsetLookup.TryGetValue(fieldName, out var value2)) { return false; } if (8 != value2.FieldSize) { return false; } ulong num = *(ulong*)((nint)((Il2CppObjectBase)obj).Pointer + value2.FieldOffset); if (num == 0L) { ulong uniqueKey = ManagedReferenceStore<Il2CppType, Value>.UniqueKey; ManagedReferenceStore<Il2CppType, Value>.Set(uniqueKey, value); *(ulong*)((nint)((Il2CppObjectBase)obj).Pointer + value2.FieldOffset) = uniqueKey; return true; } ManagedReferenceStore<Il2CppType, Value>.Set(num, value); return true; } private static int SizeOfUnmanagedType<Value>() where Value : unmanaged { if (typeof(Value) == typeof(bool)) { return 1; } return Marshal.SizeOf<Value>(); } private unsafe static void InjectValueField<Value>(string fieldName) where Value : unmanaged { int num = SizeOfUnmanagedType<Value>(); INativeClassStruct val = UnityVersionHandler.Wrap((Il2CppClass*)(void*)Il2CppClassPointerStore<Il2CppType>.NativeClassPtr); val.InstanceSize += (uint)num; val.ActualSize = val.InstanceSize; _OffsetLookup[fieldName] = new InjectedFieldInfo { FieldOffset = (nint)(val.InstanceSize - num), FieldSize = num }; } public unsafe static bool TryGetValueField<Value>(Il2CppType obj, string fieldName, out Value value) where Value : unmanaged { if (obj == null) { value = default(Value); return false; } if (((Il2CppObjectBase)obj).Pointer == IntPtr.Zero) { value = default(Value); return false; } if (!_OffsetLookup.TryGetValue(fieldName, out var value2)) { value = default(Value); return false; } if (SizeOfUnmanagedType<Value>() != value2.FieldSize) { value = default(Value); return false; } value = *(Value*)((nint)((Il2CppObjectBase)obj).Pointer + value2.FieldOffset); return true; } public unsafe static bool TrySetValueField<Value>(Il2CppType obj, string fieldName, Value value) where Value : unmanaged { if (obj == null) { return false; } if (((Il2CppObjectBase)obj).Pointer == IntPtr.Zero) { return false; } if (!_OffsetLookup.TryGetValue(fieldName, out var value2)) { return false; } if (SizeOfUnmanagedType<Value>() != value2.FieldSize) { return false; } *(Value*)((nint)((Il2CppObjectBase)obj).Pointer + value2.FieldOffset) = value; return true; } } internal struct InjectedFieldInfo { public nint FieldOffset; public int FieldSize; } public static class ManagedReferenceStore<C, T> where C : Il2CppObjectBase where T : class { private static readonly Dictionary<ulong, T> _Lookup = new Dictionary<ulong, T>(); private static ulong _Key = 1uL; public static ulong UniqueKey => _Key++; public static T Get(ulong key) { _Lookup.TryGetValue(key, out var value); return value; } public static void Set(ulong key, T value) { _Lookup[key] = value; } public static void Remove(ulong key) { _Lookup.Remove(key); } } }
plugins/net6/LEGACY.dll
Decompiled a month ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Immutable; using System.ComponentModel.DataAnnotations; 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.Json; using System.Text.Json.Serialization; using AIGraph; using AK; using Agents; using AssetShards; using BepInEx; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using BepInEx.Unity.IL2CPP.Utils.Collections; using BoosterImplants; using CellMenu; using ChainedPuzzles; using EOSExt.Reactor.Managers; using Enemies; using ExtraObjectiveSetup; using ExtraObjectiveSetup.BaseClasses; using ExtraObjectiveSetup.Expedition.Gears; using ExtraObjectiveSetup.ExtendedWardenEvents; using ExtraObjectiveSetup.Instances; using ExtraObjectiveSetup.Utils; using FirstPersonItem; using FloLib.Infos; using FloLib.Networks.Replications; using GTFO.API; using GTFO.API.Utilities; using GameData; using Gear; using HarmonyLib; using Il2CppInterop.Runtime.Injection; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.InteropTypes.Arrays; using Il2CppSystem; using Il2CppSystem.Collections.Generic; using LEGACY.ExtraEvents; using LEGACY.LegacyOverride; using LEGACY.LegacyOverride.DummyVisual; using LEGACY.LegacyOverride.DummyVisual.VisualGOAnimation; using LEGACY.LegacyOverride.DummyVisual.VisualGOAnimation.AnimationConfig; using LEGACY.LegacyOverride.DummyVisual.VisualSequenceType; using LEGACY.LegacyOverride.ElevatorCargo; using LEGACY.LegacyOverride.EnemyTagger; using LEGACY.LegacyOverride.EventScan; using LEGACY.LegacyOverride.ExpeditionIntelNotification; using LEGACY.LegacyOverride.ExpeditionSuccessPage; using LEGACY.LegacyOverride.FogBeacon; using LEGACY.LegacyOverride.ForceFail; using LEGACY.LegacyOverride.Music; using LEGACY.LegacyOverride.ResourceStations; using LEGACY.LegacyOverride.SecDoorIntText; using LEGACY.LegacyOverride.ThermalSightAdjustment; using LEGACY.Utils; using LEGACY.VanillaFix; using LevelGeneration; using Localization; using MTFO.API; using Microsoft.CodeAnalysis; using Player; using SNetwork; using ScanPosOverride.JSON; using ScanPosOverride.Managers; using StateMachines; using TMPro; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("LEGACY")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("LEGACY")] [assembly: AssemblyTitle("LEGACY")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } [HarmonyPatch(typeof(PUI_Watermark), "UpdateWatermark")] internal static class Patch_WatermarkUpdateWatermark { private static void Postfix(PUI_Watermark __instance) { string text = "4.6.1+gitf831086-dirty-main".Remove("x.x.x".Length); ((TMP_Text)__instance.m_watermarkText).SetText("<color=red>MODDED</color> <color=orange>" + text + "</color>\n<color=#00ae9d>LEGACY</color> <color=orange>STANDALONE</color>", true); } } namespace LEGACY { internal static class Assets { public static GameObject CircleSensor { get; private set; } public static GameObject MovableSensor { get; private set; } public static GameObject OBSVisual { get; private set; } public static GameObject ObjectiveMarker { get; private set; } public static GameObject EventScan { get; private set; } internal static GameObject DummyScan { get; private set; } internal static GameObject DummySensor { get; private set; } internal static GameObject AmmoStation { get; private set; } internal static GameObject MediStation { get; private set; } public static void Init() { CircleSensor = AssetAPI.GetLoadedAsset<GameObject>("Assets/SecuritySensor/CircleSensor.prefab"); MovableSensor = AssetAPI.GetLoadedAsset<GameObject>("Assets/SecuritySensor/MovableSensor.prefab"); OBSVisual = AssetAPI.GetLoadedAsset<GameObject>("Assets/SecuritySensor/OBSVisual.prefab"); ObjectiveMarker = AssetAPI.GetLoadedAsset<GameObject>("Assets/SecuritySensor/ObjectiveMarker.prefab"); EventScan = AssetAPI.GetLoadedAsset<GameObject>("Assets/EventObjects/EventScan.prefab"); DummyScan = AssetAPI.GetLoadedAsset<GameObject>("Assets/DummyVisual/DummyScan.prefab"); DummySensor = AssetAPI.GetLoadedAsset<GameObject>("Assets/DummyVisual/DummySensor.prefab"); AmmoStation = AssetAPI.GetLoadedAsset<GameObject>("Assets/Misc/AmmoStation.prefab"); MediStation = AssetAPI.GetLoadedAsset<GameObject>("Assets/Misc/MediStation.prefab"); } } [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInIncompatibility("GTFO.AWO")] [BepInPlugin("Inas.LEGACY", "LEGACY", "4.2.2")] public class EntryPoint : BasePlugin { public const string AUTHOR = "Inas"; public const string RUNDOWN_NAME = "LEGACY"; public const string VERSION = "4.2.2"; public const bool TESTING = false; public const string TEST_STRING = "TESTING"; private Harmony m_Harmony; public override void Load() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown m_Harmony = new Harmony("LEGACY"); m_Harmony.PatchAll(); LegacyOverrideManagers.Init(); LegacyExtraEvents.Init(); LEGACY.VanillaFix.Debugger.Current.Init(); AssetAPI.OnAssetBundlesLoaded += Assets.Init; EventAPI.OnManagersSetup += delegate { AssetShardManager.OnStartupAssetsLoaded += Action.op_Implicit((Action)MainMenuGuiLayer.Current.PageRundownNew.SetupCustomTutorialButton); }; } } } namespace LEGACY.Reactor { [HarmonyPatch] internal class Patch_ReactorShutdown { [HarmonyPostfix] [HarmonyPatch(typeof(LG_WardenObjective_Reactor), "OnStateChange")] private static void Post_OnStateChange(LG_WardenObjective_Reactor __instance, pReactorState oldState, pReactorState newState) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0011: 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_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Invalid comparison between Unknown and I4 //IL_0060: 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_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Expected I4, but got Unknown //IL_007e: 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_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)__instance == (Object)null || oldState.status == newState.status) { return; } WardenObjectiveDataBlock val = null; if (!WardenObjectiveManager.Current.TryGetActiveWardenObjectiveData(__instance.SpawnNode.LayerType, ref val) || val == null) { LegacyLogger.Error("Patch_ReactorShutdown: "); LegacyLogger.Error("Failed to get warden objective"); } else if ((int)val.Type == 2 && !val.OnActivateOnSolveItem) { eWardenObjectiveEventTrigger val2 = (eWardenObjectiveEventTrigger)0; eReactorStatus status = newState.status; switch (status - 7) { default: return; case 0: val2 = (eWardenObjectiveEventTrigger)1; break; case 1: val2 = (eWardenObjectiveEventTrigger)2; break; case 2: val2 = (eWardenObjectiveEventTrigger)3; break; } _ = __instance.SpawnNode.LayerType; WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(val.EventsOnActivate, val2, false, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null); } } [HarmonyPrefix] [HarmonyPatch(typeof(LG_WardenObjective_Reactor), "OnBuildDone")] private static void Pre_OnBuildDone_ChainedPuzzleMidObjectiveFix(LG_WardenObjective_Reactor __instance) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) WardenObjectiveDataBlock val = null; if (!WardenObjectiveManager.Current.TryGetActiveWardenObjectiveData(__instance.SpawnNode.LayerType, ref val) || val == null) { LegacyLogger.Error("Patch_ReactorShutdown: Failed to get warden objective"); } else if (val.ChainedPuzzleMidObjective != 0) { __instance.m_chainedPuzzleAlignMidObjective = __instance.m_chainedPuzzleAlign; } } [HarmonyPrefix] [HarmonyPatch(typeof(LG_WardenObjective_Reactor), "Update")] private static bool Pre_Update(LG_WardenObjective_Reactor __instance) { //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_000c: Invalid comparison between Unknown and I4 if ((int)__instance.m_currentState.status != 7) { return true; } if (!__instance.m_currentWaveData.HasVerificationTerminal) { return true; } __instance.SetGUIMessage(true, Text.Format(3000u, (Object[])(object)new Object[1] { Object.op_Implicit("<color=orange>" + __instance.m_currentWaveData.VerificationTerminalSerial + "</color>") }), (ePUIMessageStyle)3, false, "", ""); return false; } } [HarmonyPatch] internal class Patch_ReactorStartup_ExtraEventsExecution { [HarmonyPostfix] [HarmonyPatch(typeof(LG_WardenObjective_Reactor), "OnStateChange")] private static void Post_ExecuteOnNoneEventsOnDefenseStart(LG_WardenObjective_Reactor __instance, pReactorState oldState, pReactorState newState) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_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_0016: Invalid comparison between Unknown and I4 if (oldState.status != newState.status && (int)newState.status == 3) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(__instance.m_currentWaveData.Events, (eWardenObjectiveEventTrigger)0, false, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null); } } [HarmonyPostfix] [HarmonyPatch(typeof(LG_WardenObjective_Reactor), "OnBuildDone")] private static void Post_OnBuildDone(LG_WardenObjective_Reactor __instance) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Invalid comparison between Unknown and I4 WardenObjectiveDataBlock db = default(WardenObjectiveDataBlock); if (!WardenObjectiveManager.Current.TryGetActiveWardenObjectiveData(__instance.SpawnNode.LayerType, ref db) || db == null) { LegacyLogger.Error("Patch_ReactorStartup_ExtraEventsExecution: "); LegacyLogger.Error("Failed to get warden objective"); } else if ((int)db.Type == 1 && !db.OnActivateOnSolveItem) { ChainedPuzzleInstance chainedPuzzleToStartSequence = __instance.m_chainedPuzzleToStartSequence; chainedPuzzleToStartSequence.OnPuzzleSolved += Action.op_Implicit((Action)delegate { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(db.EventsOnActivate, (eWardenObjectiveEventTrigger)0, true, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null); }); } } } [HarmonyPatch] internal class Patch_ReactorStartup_OverwriteGUIBehaviour { private static HashSet<uint> ForceDisableLevels; [HarmonyPrefix] [HarmonyPatch(typeof(LG_WardenObjective_Reactor), "OnStateChange")] private static bool Pre_HideReactorMessageForInfiniteWave(LG_WardenObjective_Reactor __instance, pReactorState oldState, pReactorState newState) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0010: 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_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Invalid comparison between Unknown and I4 //IL_0037: 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_0022: 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_0029: Invalid comparison between Unknown and I4 //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0046: 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_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Expected I4, but got Unknown //IL_0060: 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_0268: Unknown result type (might be due to invalid IL or missing references) //IL_02a6: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_01bd: Unknown result type (might be due to invalid IL or missing references) //IL_0181: Unknown result type (might be due to invalid IL or missing references) if (oldState.status == newState.status) { return true; } if ((int)newState.status != 2 && (int)newState.status != 3 && (int)newState.status != 4) { return true; } if (ForceDisable()) { if (oldState.stateCount != newState.stateCount) { __instance.OnStateCountUpdate(newState.stateCount); } if (oldState.stateProgress != newState.stateProgress) { __instance.OnStateProgressUpdate(newState.stateProgress); } __instance.ReadyForVerification = false; eReactorStatus status = newState.status; switch (status - 2) { case 0: { WardenObjectiveDataBlock val = null; if (!WardenObjectiveManager.Current.TryGetActiveWardenObjectiveData(__instance.SpawnNode.LayerType, ref val) || val == null) { LegacyLogger.Error("Patch_ReactorStartup_OverwriteGUIBehaviour: "); LegacyLogger.Error("Failed to get warden objective datablock"); break; } __instance.m_lightCollection.SetMode(val.LightsOnDuringIntro); __instance.m_lightCollection.ResetUpdateValues(true); __instance.lcReset = true; __instance.m_lightsBlinking = false; __instance.m_spawnEnemies = false; __instance.m_progressUpdateEnabled = true; __instance.m_alarmCountdownPlayed = false; __instance.m_currentDuration = ((!newState.verifyFailed) ? __instance.m_currentWaveData.Warmup : __instance.m_currentWaveData.WarmupFail); WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(__instance.m_currentWaveData.Events, (eWardenObjectiveEventTrigger)1, false, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null); if (__instance.m_currentWaveCount == 1) { Debug.LogError(Object.op_Implicit("Reactor IDLE START")); __instance.m_sound.Post(EVENTS.REACTOR_POWER_LEVEL_1_LOOP, true); __instance.m_sound.SetRTPCValue(GAME_PARAMETERS.REACTOR_POWER, 0f); } else { Debug.LogError(Object.op_Implicit("Reactor REACTOR_POWER_DOWN")); __instance.m_sound.Post(EVENTS.REACTOR_POWER_LEVEL_2_TO_1_TRANSITION, true); __instance.m_sound.SetRTPCValue(GAME_PARAMETERS.REACTOR_POWER, 0f); } break; } case 1: __instance.m_lightCollection.ResetUpdateValues(true); __instance.lcReset = true; __instance.m_spawnEnemies = true; __instance.m_currentEnemyWaveIndex = 0; __instance.m_alarmCountdownPlayed = false; __instance.m_progressUpdateEnabled = true; __instance.m_currentDuration = __instance.m_currentWaveData.Wave; __instance.m_sound.Post(EVENTS.REACTOR_POWER_LEVEL_1_TO_3_TRANSITION, true); break; case 2: __instance.m_lightCollection.ResetUpdateValues(false); __instance.lcReset = true; __instance.m_spawnEnemies = false; __instance.m_progressUpdateEnabled = true; __instance.ReadyForVerification = true; Debug.Log(Object.op_Implicit("Wait for verify! newState.verifyFailed? " + newState.verifyFailed)); __instance.m_currentDuration = ((!newState.verifyFailed) ? __instance.m_currentWaveData.Verify : __instance.m_currentWaveData.VerifyFail); WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(__instance.m_currentWaveData.Events, (eWardenObjectiveEventTrigger)2, false, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null); break; } __instance.m_currentState = newState; return false; } return true; } private static bool ForceDisable() { return ForceDisableLevels.Contains(RundownManager.ActiveExpedition.LevelLayoutData); } static Patch_ReactorStartup_OverwriteGUIBehaviour() { ForceDisableLevels = new HashSet<uint>(); LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock("Legacy_L3E2_L1"); if (block != null) { ForceDisableLevels.Add(((GameDataBlockBase<LevelLayoutDataBlock>)(object)block).persistentID); } block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock("Legacy_L1E1_L1"); if (block != null) { ForceDisableLevels.Add(((GameDataBlockBase<LevelLayoutDataBlock>)(object)block).persistentID); } } } } namespace LEGACY.HardcodedBehaviours { [HarmonyPatch] internal class Patch_PickupItem_Hardcoded { [HarmonyPrefix] [HarmonyPatch(typeof(LG_Distribute_PickupItemsPerZone), "Build")] private static void Pre_LG_Distribute_PickupItemsPerZone(LG_Distribute_PickupItemsPerZone __instance) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Invalid comparison between Unknown and I4 //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Invalid comparison between Unknown and I4 //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Invalid comparison between Unknown and I4 LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock("LAYOUT_O4_1_L1"); if (block == null || RundownManager.ActiveExpedition.LevelLayoutData != ((GameDataBlockBase<LevelLayoutDataBlock>)(object)block).persistentID) { return; } eLocalZoneIndex localIndex = __instance.m_zone.LocalIndex; if ((int)localIndex != 1) { if ((int)localIndex == 5) { __instance.m_zonePlacementWeights.Start = 0f; __instance.m_zonePlacementWeights.Middle = 0f; __instance.m_zonePlacementWeights.End = 100000f; } } else if ((int)__instance.m_pickupType == 1) { __instance.m_zonePlacementWeights.Start = 100000f; __instance.m_zonePlacementWeights.Middle = 0f; __instance.m_zonePlacementWeights.End = 0f; } } } } namespace LEGACY.VanillaFix { [HarmonyPatch] internal class Patch_FixScoutFreeze { [HarmonyPrefix] [HarmonyPatch(typeof(ES_ScoutScream), "CommonUpdate")] private static bool Prefix_Debug(ES_ScoutScream __instance) { if (((AgentAI)((ES_Base)__instance).m_ai).Target == null) { return false; } return true; } } [HarmonyPatch] internal class Patch_LG_SecurityDoor_Fix_EventsOnUnlockDoor_Powergenerator { [HarmonyPrefix] [HarmonyPatch(typeof(LG_SecurityDoor), "OnSyncDoorStatusChange")] private static void Pre_OnSyncDoorStatusChange(LG_SecurityDoor __instance, pDoorState state, bool isRecall) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Invalid comparison between Unknown and I4 //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Invalid comparison between Unknown and I4 eDoorStatus status = state.status; if ((status - 4 <= 1 || (int)status == 9) && (int)__instance.m_lastState.status == 6 && !isRecall) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(__instance.LinkedToZoneData.EventsOnUnlockDoor, (eWardenObjectiveEventTrigger)0, true, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null); } } } [HarmonyPatch] internal class Patch_LockSecurityDoor_FixCustomText { [HarmonyPostfix] [HarmonyPatch(typeof(LG_SecurityDoor_Locks), "Setup", new Type[] { typeof(LG_SecurityDoor) })] private static void Post_LG_SecurityDoor_Locks_Setup(LG_SecurityDoor door, LG_SecurityDoor_Locks __instance) { LocalizedText customText = door.LinkedToZoneData.ProgressionPuzzleToEnter.CustomText; __instance.m_lockedWithNoKeyInteractionText = customText; } } [HarmonyPatch] internal class Debugger { public static Debugger Current { get; private set; } = new Debugger(); public bool DEBUGGING { get; private set; } private Debugger() { } internal void Init() { _ = DEBUGGING; } } } namespace LEGACY.Utils { public delegate float EasingFunction(float t, float b, float c, float d); public delegate bool BoolCheck(); internal static class CoroutineEase { private static IEnumerator DoEaseLocalScale(Transform trans, Vector3 startScale, Vector3 targetScale, float startTime, float duration, EasingFunction ease, Action onDone, BoolCheck checkAbort) { //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) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) bool doAbort = false; while (Clock.Time < startTime + duration && !doAbort) { doAbort = checkAbort?.Invoke() ?? false; float num = ease(Clock.Time - startTime, 0f, 1f, duration); trans.localScale = Vector3.Lerp(startScale, targetScale, num); yield return null; } trans.localScale = targetScale; if (!doAbort) { onDone?.Invoke(); } } private static IEnumerator DoEaseLocalPos(Transform trans, Vector3 sourcePos, Vector3 targetPos, float startTime, float duration, EasingFunction ease, Action onDone, BoolCheck checkAbort) { //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) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) bool doAbort = false; while (Clock.Time < startTime + duration && !doAbort) { doAbort = checkAbort?.Invoke() ?? false; float num = ease(Clock.Time - startTime, 0f, 1f, duration); trans.localPosition = Vector3.Lerp(sourcePos, targetPos, num); yield return null; } trans.localPosition = targetPos; if (!doAbort) { onDone?.Invoke(); } } private static IEnumerator DoEaseLocalRot(Transform trans, Vector3 sourceEuler, Vector3 targetEuler, float startTime, float duration, EasingFunction ease, Action onDone, BoolCheck checkAbort) { //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) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) bool doAbort = false; while (Clock.Time < startTime + duration && !doAbort) { doAbort = checkAbort?.Invoke() ?? false; float num = ease(Clock.Time - startTime, 0f, 1f, duration); trans.localEulerAngles = Vector3.Lerp(sourceEuler, targetEuler, num); yield return null; } trans.localEulerAngles = targetEuler; if (!doAbort) { onDone?.Invoke(); } } internal static Coroutine EaseLocalScale(Transform trans, Vector3 startScale, Vector3 targetScale, float duration, EasingFunction ease = null, Action onDone = null, BoolCheck checkAbort = null) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) EasingFunction ease2 = ease ?? new EasingFunction(Easing.EaseOutExpo); return CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(DoEaseLocalScale(trans, startScale, targetScale, Clock.Time, duration, ease2, onDone, checkAbort)), (Action)null); } internal static Coroutine EaseLocalPos(Transform trans, Vector3 sourcePos, Vector3 targetPos, float duration, EasingFunction ease = null, Action onDone = null, BoolCheck checkAbort = null) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) EasingFunction ease2 = ease ?? new EasingFunction(Easing.EaseOutExpo); return CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(DoEaseLocalPos(trans, sourcePos, targetPos, Clock.Time, duration, ease2, onDone, checkAbort)), (Action)null); } internal static Coroutine EaseLocalRot(Transform trans, Vector3 sourceEuler, Vector3 targetEuler, float duration, EasingFunction ease = null, Action onDone = null, BoolCheck checkAbort = null) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) EasingFunction ease2 = ease ?? new EasingFunction(Easing.EaseOutExpo); return CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(DoEaseLocalRot(trans, sourceEuler, targetEuler, Clock.Time, duration, ease2, onDone, checkAbort)), (Action)null); } } public static class Helper { private static void ResetChild(iChainedPuzzleCore ICore) { CP_Bioscan_Core val = ((Il2CppObjectBase)ICore).TryCast<CP_Bioscan_Core>(); if ((Object)(object)val != (Object)null) { ((Il2CppObjectBase)val.m_spline).Cast<CP_Holopath_Spline>(); ((Il2CppObjectBase)val.PlayerScanner).Cast<CP_PlayerScanner>().ResetScanProgression(0f); val.Deactivate(); return; } CP_Cluster_Core val2 = ((Il2CppObjectBase)ICore).TryCast<CP_Cluster_Core>(); if ((Object)(object)val2 == (Object)null) { LegacyLogger.Error("ResetChild: found iChainedPuzzleCore that is neither CP_Bioscan_Core nor CP_Cluster_Core..."); return; } ((Il2CppObjectBase)val2.m_spline).Cast<CP_Holopath_Spline>(); foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)val2.m_childCores) { ResetChild(item); } val2.Deactivate(); } public static void ResetChainedPuzzle(ChainedPuzzleInstance chainedPuzzleInstance) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected O, but got Unknown //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_0065: 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_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009b: 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_00a9: Unknown result type (might be due to invalid IL or missing references) if (chainedPuzzleInstance.Data.DisableSurvivalWaveOnComplete) { chainedPuzzleInstance.m_sound = new CellSoundPlayer(chainedPuzzleInstance.m_parent.position); } foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)chainedPuzzleInstance.m_chainedPuzzleCores) { ResetChild(item); } if (SNet.IsMaster) { pChainedPuzzleState state = chainedPuzzleInstance.m_stateReplicator.State; pChainedPuzzleState val = default(pChainedPuzzleState); val.status = (eChainedPuzzleStatus)0; val.currentSurvivalWave_EventID = state.currentSurvivalWave_EventID; val.isSolved = false; val.isActive = false; pChainedPuzzleState val2 = val; chainedPuzzleInstance.m_stateReplicator.InteractWithState(val2, new pChainedPuzzleInteraction { type = (eChainedPuzzleInteraction)2 }); } } public static List<T> ToManagedList<T>(this List<T> il2cppList) { List<T> list = new List<T>(); Enumerator<T> enumerator = il2cppList.GetEnumerator(); while (enumerator.MoveNext()) { T current = enumerator.Current; list.Add(current); } return list; } public static bool TryGetComponent<T>(this GameObject obj, out T comp) { comp = obj.GetComponent<T>(); return comp != null; } public static bool IsPlayerInLevel(PlayerAgent player) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Invalid comparison between Unknown and I4 return (int)player.Owner.Load<pGameState>().gameState == 10; } public static ChainedPuzzleInstance GetChainedPuzzleForCommandOnTerminal(LG_ComputerTerminal terminal, string command) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected I4, but got Unknown //IL_00bc: 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_0133: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Unknown result type (might be due to invalid IL or missing references) //IL_0199: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Invalid comparison between Unknown and I4 //IL_019f: Unknown result type (might be due to invalid IL or missing references) //IL_01a3: Invalid comparison between Unknown and I4 //IL_01a5: Unknown result type (might be due to invalid IL or missing references) //IL_01a9: Invalid comparison between Unknown and I4 //IL_01ab: Unknown result type (might be due to invalid IL or missing references) //IL_01af: Invalid comparison between Unknown and I4 //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01b1: Unknown result type (might be due to invalid IL or missing references) //IL_01b5: Invalid comparison between Unknown and I4 uint num = 0u; if (terminal.SpawnNode.m_dimension.IsMainDimension) { LG_LayerType layerType = terminal.SpawnNode.LayerType; switch ((int)layerType) { case 0: num = RundownManager.ActiveExpedition.LevelLayoutData; break; case 1: num = RundownManager.ActiveExpedition.SecondaryLayout; break; case 2: num = RundownManager.ActiveExpedition.ThirdLayout; break; default: LegacyLogger.Error("Unimplemented layer type."); return null; } } else { num = terminal.SpawnNode.m_dimension.DimensionData.LevelLayoutData; } LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock(num); List<CustomTerminalCommand> val = null; List<LG_ComputerTerminal> terminalsSpawnedInZone = terminal.SpawnNode.m_zone.TerminalsSpawnedInZone; int num2 = terminalsSpawnedInZone.IndexOf(terminal); ExpeditionZoneData val2 = null; Enumerator<ExpeditionZoneData> enumerator = block.Zones.GetEnumerator(); while (enumerator.MoveNext()) { ExpeditionZoneData current = enumerator.Current; if (current.LocalIndex == terminal.SpawnNode.m_zone.LocalIndex) { val2 = current; break; } } if (val2 == null) { LegacyLogger.Error("Cannot find target zone data."); return null; } if (val2.TerminalPlacements.Count != terminalsSpawnedInZone.Count) { LegacyLogger.Error("The numbers of terminal placement and spawn, skipped for the zone terminal."); return null; } val = val2.TerminalPlacements[num2].UniqueCommands; if (val.Count == 0) { return null; } List<WardenObjectiveEventData> val3 = null; TERM_Command val4 = (TERM_Command)0; Enumerator<CustomTerminalCommand> enumerator2 = val.GetEnumerator(); string text = default(string); string text2 = default(string); while (enumerator2.MoveNext()) { CustomTerminalCommand current2 = enumerator2.Current; if (current2.Command == command) { val3 = current2.CommandEvents; if (!terminal.m_command.TryGetCommand(current2.Command, ref val4, ref text, ref text2)) { LegacyLogger.Error("Cannot get TERM_COMMAND for command {0} on the specified terminal."); } break; } } if (val3 == null || (int)val4 == 0) { return null; } if ((int)val4 != 38 && (int)val4 != 39 && (int)val4 != 40 && (int)val4 != 41 && (int)val4 != 42) { return null; } ChainedPuzzleInstance val5 = null; for (int i = 0; i < val3.Count && (val3[i].ChainPuzzle == 0 || !terminal.TryGetChainPuzzleForCommand(val4, i, ref val5) || !((Object)(object)val5 != (Object)null)); i++) { } return val5; } public static bool TryGetZoneEntranceSecDoor(LG_Zone zone, out LG_SecurityDoor door) { if ((Object)(object)zone == (Object)null) { door = null; return false; } if ((Object)(object)zone.m_sourceGate == (Object)null) { door = null; return false; } if (zone.m_sourceGate.SpawnedDoor == null) { door = null; return false; } door = ((Il2CppObjectBase)zone.m_sourceGate.SpawnedDoor).TryCast<LG_SecurityDoor>(); return (Object)(object)door != (Object)null; } internal static bool isSecDoorToZoneOpened(LG_Zone zone14) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Invalid comparison between Unknown and I4 LG_SecurityDoor door = null; if (!TryGetZoneEntranceSecDoor(zone14, out door) || (Object)(object)door == (Object)null) { return false; } return (int)door.m_sync.GetCurrentSyncState().status == 10; } public static List<T> cast<T>(List<T> list) { List<T> list2 = new List<T>(); Enumerator<T> enumerator = list.GetEnumerator(); while (enumerator.MoveNext()) { T current = enumerator.Current; list2.Add(current); } return list2; } private static eDimensionIndex GetCurrentDimensionIndex() { //IL_0023: Unknown result type (might be due to invalid IL or missing references) if (PlayerManager.PlayerAgentsInLevel.Count <= 0) { throw new Exception("? You don't have any player agent in level? How could that happen?"); } return ((Agent)PlayerManager.PlayerAgentsInLevel[0]).DimensionIndex; } public static void GetMinLayerAndLocalIndex(out LG_LayerType MinLayer, out eLocalZoneIndex MinLocalIndex) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Invalid comparison between I4 and Unknown //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Invalid comparison between I4 and Unknown //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Expected I4, but got Unknown //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Expected I4, but got Unknown MinLayer = (LG_LayerType)2; MinLocalIndex = (eLocalZoneIndex)20; Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator(); while (enumerator.MoveNext()) { PlayerAgent current = enumerator.Current; if (IsPlayerInLevel(current)) { if ((int)MinLayer > (int)current.m_courseNode.LayerType) { MinLayer = (LG_LayerType)(int)current.m_courseNode.LayerType; MinLocalIndex = (eLocalZoneIndex)20; } if ((int)MinLocalIndex >= (int)current.m_courseNode.m_zone.LocalIndex) { MinLocalIndex = (eLocalZoneIndex)(int)current.m_courseNode.m_zone.LocalIndex; } } } } public static void GetMaxLayerAndLocalIndex(out LG_LayerType MaxLayer, out eLocalZoneIndex MaxLocalIndex) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Invalid comparison between I4 and Unknown //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Invalid comparison between I4 and Unknown //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected I4, but got Unknown //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Expected I4, but got Unknown MaxLayer = (LG_LayerType)0; MaxLocalIndex = (eLocalZoneIndex)0; Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator(); while (enumerator.MoveNext()) { PlayerAgent current = enumerator.Current; if (IsPlayerInLevel(current)) { if ((int)MaxLayer < (int)current.m_courseNode.LayerType) { MaxLayer = (LG_LayerType)(int)current.m_courseNode.LayerType; MaxLocalIndex = (eLocalZoneIndex)0; } if ((int)MaxLocalIndex < (int)current.m_courseNode.m_zone.LocalIndex) { MaxLocalIndex = (eLocalZoneIndex)(int)current.m_courseNode.m_zone.LocalIndex; } } } } public static int GetMinAreaIndex(LG_Zone zone) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)zone == (Object)null) { return -1; } LG_LayerType type = zone.m_layer.m_type; eLocalZoneIndex localIndex = zone.LocalIndex; GetCurrentDimensionIndex(); int num = zone.m_areas.Count; Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator(); while (enumerator.MoveNext()) { PlayerAgent current = enumerator.Current; if (current.m_courseNode.LayerType != type || current.m_courseNode.m_zone.LocalIndex != localIndex) { continue; } int i = 0; for (List<LG_Area> areas = zone.m_areas; i < areas.Count; i++) { if (((Object)((Component)areas[i]).gameObject).GetInstanceID() == ((Object)((Component)current.m_courseNode.m_area).gameObject).GetInstanceID()) { if (num > i) { num = i; } break; } } } return num; } public static LG_ComputerTerminal FindTerminal(eDimensionIndex dimensionIndex, LG_LayerType layerType, eLocalZoneIndex localIndex, int terminalIndex) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: 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_0048: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_0106: Unknown result type (might be due to invalid IL or missing references) LG_Zone val = null; if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(dimensionIndex, layerType, localIndex, ref val) || (Object)(object)val == (Object)null) { LegacyLogger.Error($"FindTerminal: Didn't find LG_Zone {dimensionIndex}, {layerType}, {localIndex}"); return null; } if (val.TerminalsSpawnedInZone == null || terminalIndex >= val.TerminalsSpawnedInZone.Count) { LegacyLogger.Error($"FindTerminal: Invalid terminal index {terminalIndex} - {((val.TerminalsSpawnedInZone != null) ? val.TerminalsSpawnedInZone.Count : 0)} terminals are spawned in {dimensionIndex}, {layerType}, {localIndex}"); return null; } if (terminalIndex >= 0) { return val.TerminalsSpawnedInZone[terminalIndex]; } return null; } public static AIG_NodeCluster GetNodeFromDimensionPosition(eDimensionIndex dimensionIndex, Vector3 position) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0012: 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) AIG_GeomorphNodeVolume val = default(AIG_GeomorphNodeVolume); AIG_VoxelNodePillar val2 = default(AIG_VoxelNodePillar); AIG_INode val3 = default(AIG_INode); AIG_NodeCluster result = default(AIG_NodeCluster); if (!AIG_GeomorphNodeVolume.TryGetGeomorphVolume(0, dimensionIndex, position, ref val) || !((AIG_NodeVolume)val).m_voxelNodeVolume.TryGetPillar(position, ref val2) || !val2.TryGetVoxelNode(position.y, ref val3) || !AIG_NodeCluster.TryGetNodeCluster(val3.ClusterID, ref result)) { LegacyLogger.Error("TryWarpTo : Position is not valid, try again inside an area."); return null; } return result; } } internal static class Json { private static readonly JsonSerializerOptions _setting; static Json() { _setting = new JsonSerializerOptions { ReadCommentHandling = JsonCommentHandling.Skip, IncludeFields = false, PropertyNameCaseInsensitive = true, WriteIndented = true, IgnoreReadOnlyProperties = true }; _setting.Converters.Add(new JsonStringEnumConverter()); _setting.Converters.Add(MTFOPartialDataUtil.PersistentIDConverter); _setting.Converters.Add(MTFOPartialDataUtil.LocalizedTextConverter); } public static T Deserialize<T>(string json) { return JsonSerializer.Deserialize<T>(json, _setting); } public static object Deserialize(Type type, string json) { return JsonSerializer.Deserialize(json, type, _setting); } public static string Serialize<T>(T value) { return JsonSerializer.Serialize(value, _setting); } public static void Load<T>(string filePath, out T config) where T : new() { config = Deserialize<T>(File.ReadAllText(filePath)); } } internal static class LegacyLogger { private static ManualLogSource logger = Logger.CreateLogSource("LEGACYCore"); public static void Log(string format, params object[] args) { Log(string.Format(format, args)); } public static void Log(string str) { if (logger != null) { logger.Log((LogLevel)8, (object)str); } } public static void Warning(string format, params object[] args) { Warning(string.Format(format, args)); } public static void Warning(string str) { if (logger != null) { logger.Log((LogLevel)4, (object)str); } } public static void Error(string format, params object[] args) { Error(string.Format(format, args)); } public static void Error(string str) { if (logger != null) { logger.Log((LogLevel)2, (object)str); } } public static void Debug(string format, params object[] args) { Debug(string.Format(format, args)); } public static void Debug(string str) { if (logger != null) { logger.Log((LogLevel)32, (object)str); } } } public class SpawnHibernateEnemiesEvent { public eWardenObjectiveEventTrigger Trigger { get; set; } public int Type { get; set; } = 170; public eDimensionIndex DimensionIndex { get; set; } public LG_LayerType Layer { get; set; } public eLocalZoneIndex LocalIndex { get; set; } public string WorldEventObjectFilter { get; set; } = "RANDOM"; public uint EnemyID { get; set; } public int Count { get; set; } = 1; public float Delay { get; set; } public float Duration { get; set; } = 2f; } public class WeightedAreaSelector { private static readonly Dictionary<LG_Zone, WeightedAreaSelector> dict; private WeightedRandomBag<LG_Area> weightedRandomBag; public static WeightedAreaSelector Get(LG_Zone zone) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003c: 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_0059: Expected I4, but got Unknown //IL_009c: Unknown result type (might be due to invalid IL or missing references) if (!dict.ContainsKey(zone)) { WeightedAreaSelector weightedAreaSelector = new WeightedAreaSelector(); Enumerator<LG_Area> enumerator = zone.m_areas.GetEnumerator(); while (enumerator.MoveNext()) { LG_Area current = enumerator.Current; float num = 0f; LG_AreaSize size = current.m_size; switch (size - 1) { case 4: num = 7f; break; case 0: num = 20f; break; case 1: num = 30f; break; case 2: num = 35f; break; case 3: num = 45f; break; default: LegacyLogger.Error($"Unhandled LG_AreaSize: {current.m_size}. Won't build."); return null; } weightedAreaSelector.AddEntry(current, num); } dict.Add(zone, weightedAreaSelector); } return dict[zone]; } public static WeightedAreaSelector Get(eDimensionIndex eDimensionIndex, LG_LayerType layerType, eLocalZoneIndex localIndex) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) LG_Zone val = default(LG_Zone); if (!Builder.CurrentFloor.TryGetZoneByLocalIndex(eDimensionIndex, layerType, localIndex, ref val) || !Object.op_Implicit((Object)(object)val)) { return null; } return Get(val); } private WeightedAreaSelector() { weightedRandomBag = new WeightedRandomBag<LG_Area>(); } private void AddEntry(LG_Area area, float weight) { weightedRandomBag.AddEntry(area, weight); } public LG_Area GetRandom() { return weightedRandomBag.GetRandom(); } private static void OnBuildDone() { } private static void Clear() { dict.Clear(); } static WeightedAreaSelector() { dict = new Dictionary<LG_Zone, WeightedAreaSelector>(); LevelAPI.OnLevelCleanup += dict.Clear; } } public class WeightedRandomBag<T> { private struct Entry { public double accumulatedWeight; public T item; } private List<Entry> entries = new List<Entry>(); private double accumulatedWeight; private Random rand = new Random(); public void AddEntry(T item, double weight) { if (weight <= 0.0) { LegacyLogger.Error("AddEntry: no non-positive weight pls."); return; } accumulatedWeight += weight; entries.Add(new Entry { item = item, accumulatedWeight = accumulatedWeight }); } public T GetRandom() { double num = rand.NextDouble() * accumulatedWeight; foreach (Entry entry in entries) { if (entry.accumulatedWeight >= num) { return entry.item; } } return default(T); } } } namespace LEGACY.LegacyOverride { internal class NavMarkerManager { private Dictionary<string, GameObject> markerVisuals = new Dictionary<string, GameObject>(); private Dictionary<string, NavMarker> navMarkers = new Dictionary<string, NavMarker>(); private List<GameObject> arbitraryNavMarkers = new List<GameObject>(); public static NavMarkerManager Current { get; private set; } = new NavMarkerManager(); private GameObject InstantiateMarkerVisual() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) GameObject obj = Object.Instantiate<GameObject>(Assets.ObjectiveMarker); float num = 0.16216217f; Transform transform = obj.transform; transform.localPosition += Vector3.up * num; return obj; } public void EnableMarkerAt(string markerName, GameObject target, float scale) { //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Unknown result type (might be due to invalid IL or missing references) if (navMarkers.ContainsKey(markerName)) { navMarkers[markerName].SetVisible(true); } else { NavMarker val = GuiManager.NavMarkerLayer.PrepareGenericMarker(target); if ((Object)(object)val != (Object)null) { val.SetColor(new Color(0.855f, 0.482f, 0.976f)); val.SetStyle((eNavMarkerStyle)14); val.SetVisible(true); navMarkers[markerName] = val; } else { LegacyLogger.Error("EnableMarkerAt: got null nav marker"); } } GameObject val2 = null; if (markerVisuals.ContainsKey(markerName)) { val2 = markerVisuals[markerName]; } else { val2 = InstantiateMarkerVisual(); val2.transform.localScale = new Vector3(scale, scale, scale); val2.transform.SetPositionAndRotation(target.transform.position, Quaternion.identity); markerVisuals[markerName] = val2; } CoroutineManager.BlinkIn(val2, 0f); LegacyLogger.Debug("EnableMarker: marker " + markerName + " enabled"); } public void EnableArbitraryMarkerAt(string markerName, Vector3 Position) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) if (navMarkers.ContainsKey(markerName)) { navMarkers[markerName].SetVisible(true); } else { GameObject val = new GameObject(markerName); val.transform.SetPositionAndRotation(Position, Quaternion.identity); arbitraryNavMarkers.Add(val); NavMarker val2 = GuiManager.NavMarkerLayer.PrepareGenericMarker(val); if ((Object)(object)val2 != (Object)null) { val2.SetColor(new Color(0.855f, 0.482f, 0.976f)); val2.SetStyle((eNavMarkerStyle)14); val2.SetVisible(true); navMarkers[markerName] = val2; } else { LegacyLogger.Error("EnableMarkerAt: got null nav marker"); } } LegacyLogger.Debug("EnableMarker: marker " + markerName + " enabled"); } internal (GameObject markerVisual, NavMarker navMakrer) GetMarkerVisuals(string markerName) { if (!markerVisuals.TryGetValue(markerName, out var value) || !navMarkers.TryGetValue(markerName, out var value2)) { return (null, null); } return (value, value2); } public void DisableMakrer(string markerName) { if (navMarkers.ContainsKey(markerName)) { navMarkers[markerName].SetVisible(false); } if (markerVisuals.ContainsKey(markerName)) { GameObject val = markerVisuals[markerName]; if (val.active) { CoroutineManager.BlinkOut(val, 0f); } LegacyLogger.Debug("DisableMakrer: marker " + markerName + " disabled"); } } public void Clear() { foreach (GameObject value in markerVisuals.Values) { Object.Destroy((Object)(object)value); } arbitraryNavMarkers.ForEach((Action<GameObject>)Object.Destroy); markerVisuals.Clear(); navMarkers.Clear(); arbitraryNavMarkers.Clear(); } private NavMarkerManager() { LevelAPI.OnBuildStart += Clear; LevelAPI.OnLevelCleanup += Clear; } } internal static class LegacyOverrideManagers { internal static readonly string LEGACY_CONFIG_PATH = Path.Combine(MTFOPathAPI.CustomPath, "LegacyOverride"); internal static void Init() { ElevatorCargoOverrideManager.Current.Init(); BigPickupFogBeaconSettingManager.Current.Init(); EnemyTaggerSettingManager.Current.Init(); ((ZoneDefinitionManager<SecDoorIntTextOverride>)SecDoorIntTextOverrideManager.Current).Init(); ((GenericExpeditionDefinitionManager<DimensionWarpPosition>)DimensionWarpPositionManager.Current).Init(); ForceFailManager.Current.Init(); ((GenericExpeditionDefinitionManager<ExpeditionIntel>)ExpeditionIntelNotifier.Current).Init(); ((GenericExpeditionDefinitionManager<EventScanDefinition>)EventScanManager.Current).Init(); ((GenericExpeditionDefinitionManager<VisualGroupDefinition>)VisualManager.Current).Init(); ((GenericExpeditionDefinitionManager<MusicOverride>)MusicStateOverrider.Current).Init(); ((ZoneDefinitionManager<LevelSpawnedFogBeaconDefinition>)LevelSpawnedFogBeaconManager.Current).Init(); ((GenericExpeditionDefinitionManager<SuccessPageCustomization>)SuccessPageCustomizationManager.Current).Init(); ((GenericExpeditionDefinitionManager<ResourceStationDefinition>)ResourceStationManager.Current).Init(); AssetShardManager.OnStartupAssetsLoaded += Action.op_Implicit((Action)delegate { ((GenericDefinitionManager<TSADefinition>)TSAManager.Current).Init(); }); } } } namespace LEGACY.LegacyOverride.ThermalSightAdjustment { public class TSADefinition { public float OffAimPixelZoom { get; set; } = 1f; public TSShader Shader { get; set; } = new TSShader(); } internal class TSAManager : GenericDefinitionManager<TSADefinition> { private class PuzzleVisualWrapper { internal GameObject GO { get; set; } internal Renderer Renderer { get; set; } internal float Intensity { get; set; } internal float BehindWallIntensity { get; set; } internal void SetIntensity(float t) { if (GO.active) { if (Intensity > 0f) { Renderer.material.SetFloat("_Intensity", Intensity * t); } if (BehindWallIntensity > 0f) { Renderer.material.SetFloat("_BehindWallIntensity", BehindWallIntensity * t); } } } internal PuzzleVisualWrapper() { } } private const bool OUTPUT_THERMAL_SHADER_SETTINGS_ON_WIELD = false; private List<PuzzleVisualWrapper> PuzzleVisuals { get; } = new List<PuzzleVisualWrapper>(); public static TSAManager Current { get; } protected override string DEFINITION_NAME => "ThermalSight"; private Dictionary<uint, Renderer[]> InLevelGearThermals { get; } = new Dictionary<uint, Renderer[]>(); private HashSet<uint> ModifiedInLevelGearThermals { get; } = new HashSet<uint>(); private HashSet<uint> ThermalOfflineGears { get; } = new HashSet<uint>(); public uint CurrentGearPID { get; private set; } internal void RegisterPuzzleVisual(CP_Bioscan_Core core) { Il2CppArrayBase<Renderer> componentsInChildren = ((Component)core).gameObject.GetComponentsInChildren<Renderer>(true); if (componentsInChildren == null) { return; } foreach (Renderer item2 in ((IEnumerable<Renderer>)componentsInChildren).Where((Renderer comp) => ((Object)((Component)comp).gameObject).name.Equals("Zone")).ToList()) { GameObject gameObject = ((Component)item2).gameObject; float @float = item2.material.GetFloat("_Intensity"); float float2 = item2.material.GetFloat("_BehindWallIntensity"); PuzzleVisualWrapper item = new PuzzleVisualWrapper { GO = gameObject, Renderer = item2, Intensity = @float, BehindWallIntensity = float2 }; PuzzleVisuals.Add(item); } } private void AddOBSVisualRenderers() { foreach (GameObject oBSVisual in EnemyTaggerSettingManager.Current.OBSVisuals) { Renderer componentInChildren = oBSVisual.GetComponentInChildren<Renderer>(); float @float = componentInChildren.material.GetFloat("_Intensity"); float behindWallIntensity = -1f; PuzzleVisuals.Add(new PuzzleVisualWrapper { GO = oBSVisual, Renderer = componentInChildren, Intensity = @float, BehindWallIntensity = behindWallIntensity }); } } internal void SetPuzzleVisualsIntensity(float t) { PuzzleVisuals.ForEach(delegate(PuzzleVisualWrapper v) { v.SetIntensity(t); }); } private void CleanupPuzzleVisuals() { PuzzleVisuals.Clear(); } protected override void FileChanged(LiveEditEventArgs e) { base.FileChanged(e); InitThermalOfflineGears(); CleanupInLevelGearThermals(keepCurrentGear: true); TrySetThermalSightRenderer(CurrentGearPID); } public override void Init() { InitThermalOfflineGears(); } private void InitThermalOfflineGears() { ThermalOfflineGears.Clear(); foreach (PlayerOfflineGearDataBlock allBlock in GameDataBlockBase<PlayerOfflineGearDataBlock>.GetAllBlocks()) { if (((GameDataBlockBase<PlayerOfflineGearDataBlock>)(object)allBlock).name.ToLowerInvariant().EndsWith("_t")) { ThermalOfflineGears.Add(((GameDataBlockBase<PlayerOfflineGearDataBlock>)(object)allBlock).persistentID); } } LegacyLogger.Debug($"Found OfflineGear with thermal sight, count: {ThermalOfflineGears.Count}"); } private bool TryGetInLevelGearThermalRenderersFromItem(ItemEquippable item, uint gearPID, out Renderer[] renderers) { //IL_0058: Unknown result type (might be due to invalid IL or missing references) renderers = null; if (item.GearIDRange == null) { return false; } if (gearPID == 0) { gearPID = ExpeditionGearManager.GetOfflineGearPID(item.GearIDRange); } if (gearPID == 0 || !IsGearWithThermal(gearPID)) { return false; } bool flag = false; if (!InLevelGearThermals.ContainsKey(gearPID)) { flag = true; } else { try { _ = ((Component)InLevelGearThermals[gearPID][0]).gameObject.transform.position; flag = false; } catch { ModifiedInLevelGearThermals.Remove(gearPID); flag = true; } } if (flag) { renderers = (from x in ((IEnumerable<Renderer>)((Component)item).GetComponentsInChildren<Renderer>(true))?.Where((Renderer x) => (Object)(object)x.sharedMaterial != (Object)null && (Object)(object)x.sharedMaterial.shader != (Object)null) where ((Object)x.sharedMaterial.shader).name.ToLower().Contains("Thermal".ToLower()) select x).ToArray() ?? null; if (renderers != null) { if (renderers.Length != 1) { LegacyLogger.Warning(((Item)item).PublicName + " contains more than 1 thermal renderers!"); } InLevelGearThermals[gearPID] = renderers; return true; } LegacyLogger.Debug(((Item)item).PublicName + ": thermal renderer not found"); return false; } renderers = InLevelGearThermals[gearPID]; return true; } internal bool TrySetThermalSightRenderer(uint gearPID = 0u) { //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Expected O, but got Unknown //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Expected O, but got Unknown //IL_0190: Unknown result type (might be due to invalid IL or missing references) if (gearPID == 0) { gearPID = CurrentGearPID; } if (!IsGearWithThermal(gearPID)) { return false; } if (ModifiedInLevelGearThermals.Contains(gearPID)) { return true; } if (base.definitions.TryGetValue(gearPID, out var value) && InLevelGearThermals.TryGetValue(gearPID, out var value2)) { TSShader shader = value.Definition.Shader; Renderer[] array = value2; foreach (Renderer val in array) { PropertyInfo[] properties = shader.GetType().GetProperties(); foreach (PropertyInfo propertyInfo in properties) { Type type = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType; string text = "_" + propertyInfo.Name; if (type == typeof(float)) { val.material.SetFloat(text, (float)propertyInfo.GetValue(shader)); } else if (type == typeof(EOSColor)) { EOSColor val2 = (EOSColor)propertyInfo.GetValue(shader); val.material.SetVector(text, Color.op_Implicit(val2.ToUnityColor())); } else if (type == typeof(bool)) { bool flag = (bool)propertyInfo.GetValue(shader); val.material.SetFloat(text, flag ? 1f : 0f); } else if (type == typeof(Vec4)) { Vec4 val3 = (Vec4)propertyInfo.GetValue(shader); val.material.SetVector(text, val3.ToVector4()); } } } ModifiedInLevelGearThermals.Add(gearPID); return true; } return false; } internal void OnPlayerItemWielded(FirstPersonItemHolder fpsItemHolder, ItemEquippable item) { if (item.GearIDRange == null) { CurrentGearPID = 0u; return; } CurrentGearPID = ExpeditionGearManager.GetOfflineGearPID(item.GearIDRange); TryGetInLevelGearThermalRenderersFromItem(item, CurrentGearPID, out var _); TrySetThermalSightRenderer(CurrentGearPID); } public bool IsGearWithThermal(uint gearPID) { return ThermalOfflineGears.Contains(gearPID); } private void CleanupInLevelGearThermals(bool keepCurrentGear = false) { if (!keepCurrentGear || !InLevelGearThermals.ContainsKey(CurrentGearPID)) { InLevelGearThermals.Clear(); } else { Renderer[] value = InLevelGearThermals[CurrentGearPID]; InLevelGearThermals.Clear(); InLevelGearThermals[CurrentGearPID] = value; } ModifiedInLevelGearThermals.Clear(); } internal void SetCurrentThermalSightSettings(float t) { if (InLevelGearThermals.TryGetValue(CurrentGearPID, out var value) && base.definitions.TryGetValue(CurrentGearPID, out var value2)) { Renderer[] array = value; foreach (Renderer obj in array) { float zoom = value2.Definition.Shader.Zoom; float offAimPixelZoom = value2.Definition.OffAimPixelZoom; float num = Mathf.Lerp(zoom, offAimPixelZoom, t); obj.material.SetFloat("_Zoom", num); } } } private void Clear() { CurrentGearPID = 0u; CleanupInLevelGearThermals(); CleanupPuzzleVisuals(); } private TSAManager() { LevelAPI.OnBuildStart += Clear; LevelAPI.OnLevelCleanup += Clear; LevelAPI.OnEnterLevel += AddOBSVisualRenderers; } static TSAManager() { Current = new TSAManager(); } } public class TSShader { [JsonPropertyName("DistanceFalloff")] [Range(0.0, 1.0)] public float HeatFalloff { get; set; } = 0.01f; [Range(0.0, 1.0)] public float FogFalloff { get; set; } = 0.1f; [JsonPropertyName("PixelZoom")] [Range(0.0, 1.0)] public float Zoom { get; set; } = 0.8f; [JsonPropertyName("AspectRatioAdjust")] [Range(0.0, 2.0)] public float RatioAdjust { get; set; } = 1f; [Range(0.0, 1.0)] public float DistortionCenter { get; set; } = 0.5f; public float DistortionScale { get; set; } = 1f; public float DistortionSpeed { get; set; } = 1f; public float DistortionSignalSpeed { get; set; } = 0.025f; [Range(0.0, 1.0)] public float DistortionMin { get; set; } = 0.01f; [Range(0.0, 1.0)] public float DistortionMax { get; set; } = 0.4f; [JsonPropertyName("AmbientTemperature")] [Range(0.0, 1.0)] public float AmbientTemp { get; set; } = 0.15f; [JsonPropertyName("BackgroundTemperature")] [Range(0.0, 1.0)] public float BackgroundTemp { get; set; } = 0.05f; [Range(0.0, 10.0)] public float AlbedoColorFactor { get; set; } = 0.5f; [Range(0.0, 10.0)] public float AmbientColorFactor { get; set; } = 5f; public float OcclusionHeat { get; set; } = 0.5f; public float BodyOcclusionHeat { get; set; } = 2.5f; [Range(0.0, 1.0)] public float ScreenIntensity { get; set; } = 0.2f; [Range(0.0, 1.0)] public float OffAngleFade { get; set; } = 0.95f; [Range(0.0, 1.0)] public float Noise { get; set; } = 0.1f; [JsonPropertyName("MinShadowEnemyDistortion")] [Range(0.0, 1.0)] public float DistortionMinShadowEnemies { get; set; } = 0.2f; [JsonPropertyName("MaxShadowEnemyDistortion")] [Range(0.0, 1.0)] public float DistortionMaxShadowEnemies { get; set; } = 1f; [Range(0.0, 1.0)] public float DistortionSignalSpeedShadowEnemies { get; set; } = 1f; public float ShadowEnemyFresnel { get; set; } = 10f; [Range(0.0, 1.0)] public float ShadowEnemyHeat { get; set; } = 0.1f; public EOSColor ReticuleColorA { get; set; } = new EOSColor { r = 1f, g = 1f, b = 1f, a = 1f }; public EOSColor ReticuleColorB { get; set; } = new EOSColor { r = 1f, g = 1f, b = 1f, a = 1f }; public EOSColor ReticuleColorC { get; set; } = new EOSColor { r = 1f, g = 1f, b = 1f, a = 1f }; [Range(0.0, 20.0)] public float SightDirt { get; set; } public bool LitGlass { get; set; } public bool ClipBorders { get; set; } = true; public Vec4 AxisX { get; set; } = new Vec4(); public Vec4 AxisY { get; set; } = new Vec4(); public Vec4 AxisZ { get; set; } = new Vec4(); public bool Flip { get; set; } = true; [JsonPropertyName("Distance1")] [Range(0.0, 100.0)] public float ProjDist1 { get; set; } = 100f; [JsonPropertyName("Distance2")] [Range(0.0, 100.0)] public float ProjDist2 { get; set; } = 66f; [JsonPropertyName("Distance3")] [Range(0.0, 100.0)] public float ProjDist3 { get; set; } = 33f; [JsonPropertyName("Size1")] [Range(0.0, 3.0)] public float ProjSize1 { get; set; } = 1f; [JsonPropertyName("Size2")] [Range(0.0, 3.0)] public float ProjSize2 { get; set; } = 1f; [JsonPropertyName("Size3")] [Range(0.0, 3.0)] public float ProjSize3 { get; set; } = 1f; [JsonPropertyName("Zeroing")] [Range(-1.0, 1.0)] public float ZeroOffset { get; set; } } } namespace LEGACY.LegacyOverride.SecDoorIntText { public class InteractGlitchManager : MonoBehaviour { private const string HEX_CHARPOOL = "0123456789ABCDEF"; private const string ERR_CHARPOOL = "$#/-01"; private Random Random = new Random(); private float _Timer; private uint START_SECURITY_SCAN_SEQUENCE_TEXT_ID; private uint HOLD_TEXT_ID; private uint SCAN_UNKNOWN_TEXT_DB; public static InteractGlitchManager Current { get; } internal bool Enabled { get; set; } internal bool CanInteract { get; set; } private StringBuilder _StrBuilder { get; } = new StringBuilder(); internal GlitchMode Mode { get; set; } private Dictionary<IntPtr, LG_SecurityDoor> DoorLocks { get; } = new Dictionary<IntPtr, LG_SecurityDoor>(); private void Update() { if (Enabled && !(_Timer > Clock.Time) && GuiManager.InteractionLayer != null && Mode != 0) { switch (Mode) { case GlitchMode.Style1: GuiManager.InteractionLayer.SetInteractPrompt(GetFormat1(), CanInteract ? Text.Format(HOLD_TEXT_ID, (Object[])(object)new Object[1] { Object.op_Implicit(InputMapper.GetBindingName((InputAction)6)) }) : string.Empty, (ePUIMessageStyle)0); GuiManager.InteractionLayer.InteractPromptVisible = true; _Timer = Clock.Time + 0.05f; break; case GlitchMode.Style2: { string format = GetFormat2(Text.Get(START_SECURITY_SCAN_SEQUENCE_TEXT_ID)); string format2 = GetFormat2(Text.Get(SCAN_UNKNOWN_TEXT_DB)); GuiManager.InteractionLayer.SetInteractPrompt(format + "<color=red>" + format2 + "</color>", CanInteract ? Text.Format(HOLD_TEXT_ID, (Object[])(object)new Object[1] { Object.op_Implicit(InputMapper.GetBindingName((InputAction)6)) }) : string.Empty, (ePUIMessageStyle)0); GuiManager.InteractionLayer.InteractPromptVisible = true; _Timer = Clock.Time + 0.075f; break; } } } } private string GetFormat1() { return "<color=red>://Decryption E_RR at: [" + GetRandomHex() + GetRandomHex() + "-" + GetRandomHex() + GetRandomHex() + "-" + GetRandomHex() + GetRandomHex() + "-" + GetRandomHex() + GetRandomHex() + "]</color>"; } private string GetFormat2(string baseMessage) { _StrBuilder.Clear(); foreach (char c in baseMessage) { if (Random.NextDouble() > 0.009999999776482582 || c == ':') { _StrBuilder.Append(c); } else { _StrBuilder.Append("$#/-01"[Random.Next(0, "$#/-01".Length)]); } } return _StrBuilder.ToString(); } private string GetRandomHex() { return string.Format("{0}{1}", "0123456789ABCDEF"[Random.Next(0, "0123456789ABCDEF".Length)], "0123456789ABCDEF"[Random.Next(0, "0123456789ABCDEF".Length)]); } internal void RegisterDoorLocks(LG_SecurityDoor_Locks locks) { DoorLocks[((Il2CppObjectBase)locks.m_intCustomMessage).Pointer] = locks.m_door; DoorLocks[((Il2CppObjectBase)locks.m_intOpenDoor).Pointer] = locks.m_door; } public GlitchMode GetGlitchMode(Interact_Base interact) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003b: 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_003d: Unknown result type (might be due to invalid IL or missing references) if (!DoorLocks.TryGetValue(((Il2CppObjectBase)interact).Pointer, out var value)) { return GlitchMode.None; } eDimensionIndex dimensionIndex = value.Gate.DimensionIndex; LG_LayerType linksToLayerType = value.LinksToLayerType; eLocalZoneIndex localIndex = value.LinkedToZoneData.LocalIndex; return ((ZoneDefinitionManager<SecDoorIntTextOverride>)SecDoorIntTextOverrideManager.Current).GetDefinition(dimensionIndex, linksToLayerType, localIndex)?.GlitchMode ?? GlitchMode.None; } private void Clear() { DoorLocks.Clear(); } private InteractGlitchManager() { START_SECURITY_SCAN_SEQUENCE_TEXT_ID = ((GameDataBlockBase<TextDataBlock>)(object)GameDataBlockBase<TextDataBlock>.GetBlock("InGame.InteractionPrompt.SecurityDoor.StartSecurityScanSequence"))?.persistentID ?? 0; HOLD_TEXT_ID = ((GameDataBlockBase<TextDataBlock>)(object)GameDataBlockBase<TextDataBlock>.GetBlock("InGame.InteractionPrompt.Hold_X"))?.persistentID ?? 0; SCAN_UNKNOWN_TEXT_DB = ((GameDataBlockBase<TextDataBlock>)(object)GameDataBlockBase<TextDataBlock>.GetBlock("InGame.InteractionPrompt.SecurityDoor.StartSecurityScanSequence_ScanUnknown"))?.persistentID ?? 0; LevelAPI.OnBuildStart += Clear; LevelAPI.OnLevelCleanup += Clear; } static InteractGlitchManager() { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown ClassInjector.RegisterTypeInIl2Cpp<InteractGlitchManager>(); GameObject val = new GameObject("CONST_InteractGlitchManager"); Object.DontDestroyOnLoad((Object)val); Current = val.AddComponent<InteractGlitchManager>(); } } public class PositionAndLookDir { public Vec3 Position { get; set; } = new Vec3(); public int LookDir { get; set; } } public class WarpLocations { public string WorldEventObjectFilter { get; set; } = string.Empty; public List<PositionAndLookDir> Locations { get; set; } = new List<PositionAndLookDir>(); } public class DimensionWarpPosition { public eDimensionIndex DimensionIndex { get; set; } public List<WarpLocations> WarpLocations { get; set; } = new List<WarpLocations> { new WarpLocations() }; } internal class DimensionWarpPositionManager : GenericExpeditionDefinitionManager<DimensionWarpPosition> { public readonly List<PositionAndLookDir> DUMB = new List<PositionAndLookDir>(); public static DimensionWarpPositionManager Current { get; private set; } protected override string DEFINITION_NAME => "DimensionWarp"; public List<PositionAndLookDir> GetWarpPositions(eDimensionIndex dimensionIndex, string worldEventObjectFilter) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Invalid comparison between Unknown and I4 //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_013d: Unknown result type (might be due to invalid IL or missing references) if ((int)GameStateManager.CurrentStateName != 10 || !base.definitions.ContainsKey(RundownManager.ActiveExpedition.LevelLayoutData)) { LegacyLogger.Error($"GetWarpPositions: Didn't find config with MainLevelLayout {RundownManager.ActiveExpedition.LevelLayoutData}"); return DUMB; } DimensionWarpPosition dimensionWarpPosition = base.definitions[RundownManager.ActiveExpedition.LevelLayoutData].Definitions.Find((DimensionWarpPosition def) => def.DimensionIndex == dimensionIndex); if (dimensionWarpPosition == null) { LegacyLogger.Error($"GetWarpPositions: Didn't find config for {dimensionIndex} with MainLevelLayout {RundownManager.ActiveExpedition.LevelLayoutData}"); return DUMB; } WarpLocations warpLocations = dimensionWarpPosition.WarpLocations.Find((WarpLocations position) => position.WorldEventObjectFilter == worldEventObjectFilter); if (warpLocations == null) { LegacyLogger.Error($"GetWarpPositions: Didn't find config for {worldEventObjectFilter} in {dimensionIndex} with MainLevelLayout {RundownManager.ActiveExpedition.LevelLayoutData}"); return DUMB; } return warpLocations.Locations; } private DimensionWarpPositionManager() { } static DimensionWarpPositionManager() { Current = new DimensionWarpPositionManager(); } } public enum GlitchMode { None, Style1, Style2 } public class SecDoorIntTextOverride : GlobalZoneIndex { public LocalizedText Prefix { get; set; } public LocalizedText Postfix { get; set; } public LocalizedText TextToReplace { get; set; } public GlitchMode GlitchMode { get; set; } } public class SecDoorIntTextOverrideManager : ZoneDefinitionManager<SecDoorIntTextOverride> { public static SecDoorIntTextOverrideManager Current { get; } protected override string DEFINITION_NAME => "SecDoorIntText"; private SecDoorIntTextOverrideManager() { } static SecDoorIntTextOverrideManager() { Current = new SecDoorIntTextOverrideManager(); } } } namespace LEGACY.LegacyOverride.ResourceStations { public sealed class MediStation : ResourceStation { public const float VANILLA_MAX_HEALTH = 25f; protected override void SetupInteraction() { base.SetupInteraction(); TextDataBlock block = GameDataBlockBase<TextDataBlock>.GetBlock("InGame.InteractionPrompt.MediStation"); Interact.InteractionMessage = ((block == null) ? "HEALTH STATION" : Text.Get(((GameDataBlockBase<TextDataBlock>)(object)block).persistentID)); } protected override void OnTriggerInteractionAction(PlayerAgent player) { float health = ((Dam_SyncedDamageBase)player.Damage).Health; float num = 15.000001f; if (!(health >= num)) { player.GiveHealth(player, Math.Min(0.2f, (num - health) / 25f)); player.Sound.Post(EVENTS.MEDPACK_APPLY, true); } } public static MediStation Instantiate(ResourceStationDefinition def) { if (def.StationType != 0) { LegacyLogger.Error($"Trying to instantiate MediStation with def with 'StationType': {def.StationType}!"); return null; } GameObject gO = Object.Instantiate<GameObject>(Assets.MediStation); return new MediStation(def, gO); } private MediStation(ResourceStationDefinition def, GameObject GO) : base(def, GO) { } static MediStation() { } } public abstract class ResourceStation { public virtual GameObject GameObject { get; protected set; } public virtual GameObject InteractGO { get { GameObject gameObject = GameObject; return ((gameObject != null) ? ((Component)gameObject.transform.GetChild(3)).gameObject : null) ?? null; } } public virtual GameObject StationMarkerGO { get { GameObject gameObject = GameObject; return ((gameObject != null) ? ((Component)gameObject.transform.GetChild(2)).gameObject : null) ?? null; } } public virtual Interact_Timed Interact { get; protected set; } public virtual ResourceStationDefinition def { get; protected set; } public virtual void Destroy() { Object.Destroy((Object)(object)GameObject); Interact = null; def = null; } protected virtual void OnTriggerInteractionAction(PlayerAgent player) { } protected virtual void OnInteractionSelected(PlayerAgent agent, bool selected) { } protected virtual void SetupInteraction() { Interact.InteractDuration = 2.5f; Interact_Timed interact = Interact; interact.OnInteractionSelected += Action<PlayerAgent, bool>.op_Implicit((Action<PlayerAgent, bool>)OnInteractionSelected); Interact_Timed interact2 = Interact; interact2.OnInteractionTriggered += Action<PlayerAgent>.op_Implicit((Action<PlayerAgent>)OnTriggerInteractionAction); } protected virtual void OnStateChanged(RSStateStruct oldState, RSStateStruct newState, bool isRecall) { } protected virtual void SetupReplicator() { } protected ResourceStation(ResourceStationDefinition def, GameObject GO) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) GameObject = GO; GameObject.transform.SetPositionAndRotation(def.Position.ToVector3(), def.Rotation.ToQuaternion()); Interact = InteractGO.GetComponent<Interact_Timed>(); if ((Object)(object)Interact == (Object)null) { LegacyLogger.Error("ResourceStation: Interact Comp not found!"); return; } SetupInteraction(); SetupReplicator(); } static ResourceStation() { } } public sealed class AmmoStation : ResourceStation { protected override void SetupInteraction() { base.SetupInteraction(); TextDataBlock block = GameDataBlockBase<TextDataBlock>.GetBlock("InGame.InteractionPrompt.AmmoStation"); Interact.InteractionMessage = ((block == null) ? "AMMUNITION STATION" : Text.Get(((GameDataBlockBase<TextDataBlock>)(object)block).persistentID)); } protected override void OnTriggerInteractionAction(PlayerAgent player) { PlayerAmmoStorage ammoStorage = PlayerBackpackManager.GetBackpack(player.Owner).AmmoStorage; LegacyLogger.Error($"{ammoStorage.StandardAmmo.AmmoInPack}, {ammoStorage.SpecialAmmo.AmmoInPack}"); player.GiveAmmoRel(player, 0.15f, 0.15f, 0f); player.Sound.Post(EVENTS.AMMOPACK_APPLY, true); } public static AmmoStation Instantiate(ResourceStationDefinition def) { if (def.StationType != StationType.AMMO) { LegacyLogger.Error($"Trying to instantiate AmmoStation with def with 'StationType': {def.StationType}!"); return null; } GameObject gO = Object.Instantiate<GameObject>(Assets.AmmoStation); return new AmmoStation(def, gO); } private AmmoStation(ResourceStationDefinition def, GameObject GO) : base(def, GO) { } static AmmoStation() { } } public enum StationType { MEDI, AMMO, TOOL } public class ResourceStationDefinition { public string WorldEventObjectFilter { get; set; } = string.Empty; public StationType StationType { get; set; } = StationType.AMMO; public Vec3 Position { get; set; } = new Vec3(); public Vec3 Rotation { get; set; } = new Vec3(); public int AllowedUseTimePerCooldown { get; set; } = 3; public float CooldownTime { get; set; } = 5f; } public class ResourceStationManager : GenericExpeditionDefinitionManager<ResourceStationDefinition> { public static ResourceStationManager Current { get; private set; } protected override string DEFINITION_NAME => "ResourceStation"; private Dictionary<string, ResourceStation> Stations { get; } = new Dictionary<string, ResourceStation>(); private void Build(ResourceStationDefinition def) { if (Stations.ContainsKey(def.WorldEventObjectFilter)) { LegacyLogger.Error("ResourceStationManager: WorldEventObjectFilter '" + def.WorldEventObjectFilter + "' is already used"); return; } ResourceStation resourceStation = null; switch (def.StationType) { case StationType.MEDI: resourceStation = MediStation.Instantiate(def); break; case StationType.AMMO: resourceStation = AmmoStation.Instantiate(def); break; default: LegacyLogger.Error($"ResourceStation {def.StationType} is unimplemented"); return; } if (resourceStation != null) { Stations[def.WorldEventObjectFilter] = resourceStation; LegacyLogger.Debug("ResourceStation '" + def.WorldEventObjectFilter + "' instantiated"); } } private void BuildStations() { if (base.definitions.TryGetValue(base.CurrentMainLevelLayout, out var value)) { value.Definitions.ForEach(Build); } } private void Clear() { foreach (ResourceStation value in Stations.Values) { value.Destroy(); } Stations.Clear(); } private ResourceStationManager() { LevelAPI.OnBuildStart += delegate { Clear(); BuildStations(); }; LevelAPI.OnLevelCleanup += Clear; } static ResourceStationManager() { Current = new ResourceStationManager(); } } public struct RSStateStruct { public int RemainingUseTime; public float CurrentCooldownTime; public bool Enabled; public RSStateStruct() { RemainingUseTime = 0; CurrentCooldownTime = 0f; Enabled = false; } } public class RSTimer : MonoBehaviour { private float endTime; private bool hasOnGoingTimer; private Action OnTimerEnd; public float RemainingTime { get { if (!hasOnGoingTimer) { return 0f; } return Math.Max(endTime - Clock.Time, 0f); } } private static List<GameObject> TimerGOs { get; } private void Update() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 if ((int)GameStateManager.CurrentStateName == 10 && hasOnGoingTimer && !(Clock.Time < endTime)) { endTime = 0f; hasOnGoingTimer = false; Action onTimerEnd = OnTimerEnd; OnTimerEnd = null; onTimerEnd?.Invoke(); } } public void StartTimer(float time, Action onEnd = null) { if (time <= 0f) { LegacyLogger.Error("StartTimer: time is not positive!"); return; } if (hasOnGoingTimer) { LegacyLogger.Error("StartTimer: this timer is yet ended!"); return; } endTime = Clock.Time + time; OnTimerEnd = onEnd; hasOnGoingTimer = true; } private void OnDestroy() { endTime = 0f; hasOnGoingTimer = false; OnTimerEnd = null; } public static RSTimer Instantiate() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown GameObject val = new GameObject(); RSTimer result = val.AddComponent<RSTimer>(); TimerGOs.Add(val); return result; } public static void DestroyAll() { TimerGOs.ForEach((Action<GameObject>)Object.Destroy); TimerGOs.Clear(); } private RSTimer() { } static RSTimer() { TimerGOs = new List<GameObject>(); ClassInjector.RegisterTypeInIl2Cpp<RSTimer>(); LevelAPI.OnBuildStart += DestroyAll; LevelAPI.OnLevelCleanup += DestroyAll; } } } namespace LEGACY.LegacyOverride.EnemyTargeting { internal class EnemyTargetingPrioritizer : MonoBehaviour { public const float UPDATE_INTERVAL = 3f; private float nextUpdateTime = float.NaN; internal EnemyAgent enemy; private Dam_EnemyDamageBase damage { get { EnemyAgent obj = enemy; if (obj == null) { return null; } return obj.Damage; } } private AgentTarget target { get { EnemyAgent obj = enemy; if (obj == null) { return null; } return ((AgentAI)obj.AI).Target; } } private void Update() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Invalid comparison between Unknown and I4 //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) if ((int)GameStateManager.CurrentStateName != 10 || !SNet.IsMaster) { return; } if (float.IsNaN(nextUpdateTime)) { nextUpdateTime = Clock.Time + 3f; } else if (!(Clock.Time < nextUpdateTime) && !((Object)(object)enemy == (Object)null)) { nextUpdateTime = Clock.Time + 3f; if ((int)((AgentAI)enemy.AI).Mode == 1 && target != null && !(((Il2CppObjectBase)target.m_agent.CourseNode).Pointer == ((Il2CppObjectBase)((Agent)enemy).CourseNode).Pointer) && PlayerManager.PlayerAgentsInLevel.Count > 1 && ((Agent)PlayerManager.PlayerAgentsInLevel[0]).CourseNode.m_dimension.DimensionIndex == ((Agent)enemy).CourseNode.m_dimension.DimensionIndex) { TryPrioritizeCloserTarget(); } } } internal void TryPrioritizeCloserTarget() { _ = target; Agent val = null; Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator(); while (enumerator.MoveNext()) { PlayerAgent current = enumerator.Current; if (((Agent)current).Alive && ((Il2CppObjectBase)((Agent)current).CourseNode).Pointer == ((Il2CppObjectBase)((Agent)enemy).CourseNode).Pointer) { val = (Agent)(object)current; break; } } if ((Object)(object)val == (Object)null) { enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator(); while (enumerator.MoveNext()) { PlayerAgent current2 = enumerator.Current; if (((Agent)current2).Alive && ((Il2CppObjectBase)((Agent)current2).CourseNode.m_zone).Pointer == ((Il2CppObjectBase)((Agent)enemy).CourseNode.m_zone).Pointer) { val = (Agent)(object)current2; break; } } } if ((Object)(object)val != (Object)null) { ((AgentAI)enemy.AI).SetTarget(val); } } private void OnDestroy() { enemy = null; } static EnemyTargetingPrioritizer() { ClassInjector.RegisterTypeInIl2Cpp<EnemyTargetingPrioritizer>(); } } } namespace LEGACY.LegacyOverride.ElevatorCargo { internal class ElevatorCargoOverrideManager { public static readonly ElevatorCargoOverrideManager Current; private Dictionary<uint, LevelElevatorCargo> elevatorCargos = new Dictionary<uint, LevelElevatorCargo>(); private LiveEditListener liveEditListener; private static readonly string CONFIG_PATH; private void AddOverride(LevelElevatorCargo _override) { if (_override != null) { if (elevatorCargos.ContainsKey(_override.MainLevelLayout)) { LegacyLogger.Warning("Replaced MainLevelLayout {0}", _override.MainLevelLayout); elevatorCargos[_override.MainLevelLayout] = _override; } else { elevatorCargos.Add(_override.MainLevelLayout, _override); } } } public void Init() { //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Expected O, but got Unknown if (!Directory.Exists(CONFIG_PATH)) { Directory.CreateDirectory(CONFIG_PATH); StreamWriter streamWriter = File.CreateText(Path.Combine(CONFIG_PATH, "Template.json")); streamWriter.WriteLine(Json.Serialize(new LevelElevatorCargo())); streamWriter.Flush(); streamWriter.Close(); return; } foreach (string item in Directory.EnumerateFiles(CONFIG_PATH, "*.json", SearchOption.AllDirectories)) { Json.Load<LevelElevatorCargo>(item, out var config); AddOverride(config); } liveEditListener = LiveEdit.CreateListener(CONFIG_PATH, "*.json", true); liveEditListener.FileChanged += new LiveEditEventHandler(FileChanged); } private void FileChanged(LiveEditEventArgs e) { LegacyLogger.Warning("LiveEdit File Changed: " + e.FullPath); LiveEdit.TryReadFileContent(e.FullPath, (Action<string>)delegate(string content) { LevelElevatorCargo @override = Json.Deserialize<LevelElevatorCargo>(content); AddOverride(@override); }); } internal LevelElevatorCargo GetLevelElevatorCargoItems(uint MainLevelLayout) { if (!elevatorCargos.ContainsKey(MainLevelLayout)) { return null; } return elevatorCargos[MainLevelLayout]; } private ElevatorCargoOverrideManager() { } static ElevatorCargoOverrideManager() { CONFIG_PATH = Path.Combine(LegacyOverrideManagers.LEGACY_CONFIG_PATH, "ElevatorCargoOverride"); Current = new ElevatorCargoOverrideManager(); } } public enum ItemType { Consumable, BigPickup } public class ElevatorCargoItem { public uint ItemID { get; set; } public ItemType ItemType { get; set; } } public class LevelElevatorCargo { public uint MainLevelLayout { get; set; } public bool ForceDisable { get; set; } public List<ElevatorCargoItem> ElevatorCargoItems { get; set; } = new List<ElevatorCargoItem>(); } } namespace LEGACY.LegacyOverride.Patches { [HarmonyPatch] internal class CustomizeSecDoorInteractionText { [HarmonyPostfix] [HarmonyPatch(typeof(LG_SecurityDoor_Locks), "OnDoorState")] private static void Post_Customize_SecDoor_Interaction_Text(pDoorState state, LG_SecurityDoor_Locks __instance) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_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_0029: 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_002b: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Invalid comparison between Unknown and I4 //IL_0048: 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_004f: Invalid comparison between Unknown and I4 //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) LG_SecurityDoor door = __instance.m_door; eDimensionIndex dimensionIndex = door.Gate.DimensionIndex; LG_LayerType linksToLayerType = door.LinksToLayerType; eLocalZoneIndex localIndex = door.LinkedToZoneData.LocalIndex; SecDoorIntTextOverride definition = ((ZoneDefinitionManager<SecDoorIntTextOverride>)SecDoorIntTextOverrideManager.Current).GetDefinition(dimensionIndex, linksToLayerType, localIndex); if (definition != null && definition.GlitchMode == GlitchMode.None && ((int)state.status == 9 || (int)state.status == 5)) { Interact_Timed intOpenDoor = __instance.m_intOpenDoor; string text = LocalizedText.op_Implicit(definition.Prefix); string text2 = LocalizedText.op_Implicit(definition.Postfix); string text3 = LocalizedText.op_Implicit(definition.TextToReplace); if (string.IsNullOrEmpty(text)) { text = string.Empty; } if (string.IsNullOrEmpty(text2)) { text2 = string.Empty; } if (string.IsNullOrEmpty(text3)) { text3 = intOpenDoor.InteractionMessage; } intOpenDoor.InteractionMessage = text + "\n" + text3 + "\n" + text2; LegacyLogger.Debug($"SecDoorIntTextOverride: Override IntText. {((GlobalZoneIndex)definition).LocalIndex}, {((GlobalZoneIndex)definition).LayerType}, {((GlobalZoneIndex)definition).DimensionIndex}"); } } } [HarmonyPatch] internal static class DynamicVisualAdjustment { [HarmonyPostfix] [HarmonyPatch(typeof(FirstPersonItemHolder), "SetWieldedItem")] private static void Post_SetWieldedItem(FirstPersonItemHolder __instance, ItemEquippable item) { TSAManager.Current.OnPlayerItemWielded(__instance, item); TSAManager.Current.SetPuzzleVisualsIntensity(1f); TSAManager.Current.SetCurrentThermalSightSettings(1f); } [HarmonyPostfix] [HarmonyPatch(typeof(FPIS_Aim), "Update")] private static void Post_Aim_Update(FPIS_Aim __instance) { if (!((Object)(object)((FPItemState)__instance).Holder.WieldedItem == (Object)null)) { float num = 1f - FirstPersonItemHolder.m_transitionDelta; if (!TSAManager.Current.IsGearWithThermal(TSAManager.Current.CurrentGearPID)) { num = Math.Max(0.05f, num); } else { TSAManager.Current.SetCurrentThermalSightSettings(num); } TSAManager.Current.SetPuzzleVisualsIntensity(num); } } [HarmonyPostfix] [HarmonyPatch(typeof(CP_Bioscan_Core), "Setup")] private static void Post_CaptureBioscanVisual(CP_Bioscan_Core __instance) { TSAManager.Current.RegisterPuzzleVisual(__instance); } } [HarmonyPatch] internal static class ExpeditionSuccessPage { [HarmonyPostfix] [HarmonyPatch(typeof(CM_PageExpeditionSuccess), "OnEnable")] private static void Post_CM_PageExpeditionSuccess_OnEnable(CM_PageExpeditionSuccess __instance) { if (!((Object)(object)__instance == (Object)null)) { SuccessPageCustomization currentCustomization = SuccessPageCustomizationManager.Current.CurrentCustomization; if (currentCustomization != null) { ((TMP_Text)__instance.m_header).SetText(LocalizedText.op_Implicit(currentCustomization.PageHeader), true); __instance.m_overrideSuccessMusic = currentCustomization.OverrideSuccessMusic; LegacyLogger.Warning("Post_CM_PageExpeditionSuccess_OnEnable: " + ((Object)currentCustomization.PageHeader).ToString()); } } } } [HarmonyPatch] internal class InteractGlitch { [HarmonyPostfix] [HarmonyPatch(typeof(Interact_Timed), "OnSelectedChange")] private static void Post_Interact_Timed_OnSelectedChange(Interact_Timed __instance, bool selected) { Handle((Interact_Base)(object)__instance, selected, canInteract: true); } [HarmonyPostfix] [HarmonyPatch(typeof(Interact_MessageOnScreen), "OnSelectedChange")] private static void Post_Interact_MessageOnScreen_OnSelectedChange(Interact_MessageOnScreen __instance, bool selected) { Handle((Interact_Base)(object)__instance, selected, canInteract: false); } [HarmonyPostfix] [HarmonyPatch(typeof(LG_SecurityDoor_Locks), "Setup", new Type[] { typeof(LG_SecurityDoor) })] private static void Post_LG_SecurityDoor_Locks_Setup(LG_SecurityDoor_Locks __instance, LG_SecurityDoor door) { InteractGlitchManager.Current.RegisterDoorLocks(__instance); } private static void Handle(Interact_Base interact, bool selected, bool canInteract) { if (selected) { if (!((Object)(object)interact == (Object)null)) { switch (InteractGlitchManager.Current.GetGlitchMode(interact)) { case GlitchMode.Style1: InteractGlitchManager.Current.Enabled = true; InteractGlitchManager.Current.CanInteract = canInteract; InteractGlitchManager.Current.Mode = GlitchMode.Style1; GuiManager.InteractionLayer.InteractPromptVisible = false; break; case GlitchMode.Style2: InteractGlitchManager.Current.Enabled = true; InteractGlitchManager.Current.CanInteract = canInteract; InteractGlitchManager.Current.Mode = GlitchMode.Style2; GuiManager.InteractionLayer.InteractPromptVisible = false; break; } } } else { InteractGlitchManager.Current.Enabled = false; } } } [HarmonyPatch] inter
plugins/net6/LGTuner.dll
Decompiled a month agousing System; using System.CodeDom.Compiler; 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.Json; using System.Text.Json.Serialization; using AssetShards; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using Expedition; using GTFO.API; using GTFO.API.Utilities; using GameData; using HarmonyLib; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.InteropTypes.Arrays; using Il2CppSystem; using Il2CppSystem.Collections.Generic; using LGTuner.Configs; using LGTuner.Manager; using LGTuner.Utils; using LevelGeneration; using LevelGeneration.Core; using Microsoft.CodeAnalysis; using UnityEngine; using UnityEngine.SceneManagement; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("LGTuner")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+git32ee113-dirty-master.32ee113f774f28578bd63131db5298640efafe36")] [assembly: AssemblyProduct("LGTuner")] [assembly: AssemblyTitle("LGTuner")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace LGTuner { public static class BuilderInfo { private static readonly List<Complex> _extraComplexResourceToLoad = new List<Complex>(); public static IEnumerable<Complex> ExtraComplexResourceToLoad => _extraComplexResourceToLoad; public static ComplexResourceSetDataBlock ComplexResourceSet { get; private set; } public static int GridSize { get; private set; } public static int GridCenter { get; private set; } public static int GridZeroOffset { get; private set; } public static float AltitudeOffset { get; private set; } public static LayoutConfig MainLayer { get; private set; } public static LayoutConfig SecondaryLayer { get; private set; } public static LayoutConfig ThirdLayer { get; private set; } public static LayoutConfig[] DimensionLayer { get; private set; } = Array.Empty<LayoutConfig>(); internal static void OnResourceSetSelected() { //IL_0156: Unknown result type (might be due to invalid IL or missing references) ComplexResourceSet = Builder.ComplexResourceSetBlock; GridSize = ComplexResourceSet.LevelGenConfig.GridSize; GridCenter = GridSize / 2; GridZeroOffset = -GridCenter; AltitudeOffset = ComplexResourceSet.LevelGenConfig.AltitudeOffset; MainLayer = null; SecondaryLayer = null; ThirdLayer = null; DimensionLayer = new LayoutConfig[Enum.GetValues(typeof(eDimensionIndex)).Length]; _extraComplexResourceToLoad.Clear(); ExpeditionInTierData activeExpedition = RundownManager.ActiveExpedition; if (ConfigManager.TryGetConfig(activeExpedition.LevelLayoutData, out var config)) { MainLayer = config; } if (activeExpedition.SecondaryLayerEnabled && ConfigManager.TryGetConfig(activeExpedition.SecondaryLayout, out var config2)) { SecondaryLayer = config2; } if (activeExpedition.ThirdLayerEnabled && ConfigManager.TryGetConfig(activeExpedition.ThirdLayout, out var config3)) { ThirdLayer = config3; } Enumerator<Dimension> enumerator = Builder.CurrentFloor.m_dimensions.GetEnumerator(); while (enumerator.MoveNext()) { Dimension current = enumerator.Current; if (!current.IsMainDimension && !current.DimensionData.IsStaticDimension) { LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock(current.DimensionData.LevelLayoutData); if (block != null && ConfigManager.TryGetConfig(((GameDataBlockBase<LevelLayoutDataBlock>)(object)block).persistentID, out var config4)) { Logger.Info("loysimme dimension ja levellayoutin"); config4.Reset(((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)current.Grid).m_sizeX); DimensionLayer[current.DimensionIndex] = config4; } } } MainLayer?.Reset(GridSize); SecondaryLayer?.Reset(GridSize); ThirdLayer?.Reset(GridSize); AddExtraShard(MainLayer); AddExtraShard(SecondaryLayer); AddExtraShard(ThirdLayer); Array.ForEach(DimensionLayer, delegate(LayoutConfig x) { AddExtraShard(x); }); } private static void AddExtraShard(LayoutConfig layerConfig) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) if (layerConfig == null) { return; } Complex[] extraComplexResourceToLoad = layerConfig.ExtraComplexResourceToLoad; foreach (Complex item in extraComplexResourceToLoad) { if (!_extraComplexResourceToLoad.Contains(item)) { _extraComplexResourceToLoad.Add(item); } } } public static bool TryGetConfig(LG_Zone zone, out LayoutConfig config) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: 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_0044: Expected I4, but got Unknown //IL_0116: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) Dimension val = default(Dimension); if (!Dimension.GetDimension(zone.DimensionIndex, ref val)) { Logger.Info("dimension getter failed"); config = null; return false; } if (val.IsMainDimension) { LG_LayerType type = zone.Layer.m_type; switch ((int)type) { case 0: config = MainLayer; return MainLayer != null; case 1: config = SecondaryLayer; return SecondaryLayer != null; case 2: config = ThirdLayer; return ThirdLayer != null; } } else if (!val.DimensionData.IsStaticDimension) { Enumerator<Dimension> enumerator = Builder.CurrentFloor.m_dimensions.GetEnumerator(); while (enumerator.MoveNext()) { Dimension current = enumerator.Current; if (!current.IsMainDimension && !current.DimensionData.IsStaticDimension) { LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock(current.DimensionData.LevelLayoutData); if (block != null && ConfigManager.TryGetConfig(((GameDataBlockBase<LevelLayoutDataBlock>)(object)block).persistentID, out var config2)) { Logger.Info("found a dimension + levellayout"); config2.Reset(((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)current.Grid).m_sizeX); DimensionLayer[current.DimensionIndex] = config2; } } } config = DimensionLayer[zone.DimensionIndex]; return config != null; } config = null; return false; } public static GameObject GetRandomPlug(uint seed, int plugHeight, SubComplex subcomplex, bool withGate) { //IL_002d: 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_0065: Unknown result type (might be due to invalid IL or missing references) ComplexResourceSetDataBlock complexResourceSet = ComplexResourceSet; return (GameObject)(plugHeight switch { 0 => complexResourceSet.GetRandomPrefab(seed, withGate ? complexResourceSet.m_straightPlugsWithGates : complexResourceSet.m_straightPlugsNoGates, subcomplex), 1 => complexResourceSet.GetRandomPrefab(seed, withGate ? complexResourceSet.m_singleDropPlugsWithGates : complexResourceSet.m_singleDropPlugsNoGates, subcomplex), 2 => complexResourceSet.GetRandomPrefab(seed, withGate ? complexResourceSet.m_doubleDropPlugsWithGates : complexResourceSet.m_doubleDropPlugsNoGates, subcomplex), _ => null, }); } public static uint GetLayoutIdOfZone(LG_Zone zone) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected I4, but got Unknown //IL_006e: Unknown result type (might be due to invalid IL or missing references) Dimension dimension = zone.Dimension; if (dimension.IsMainDimension) { LG_LayerType type = zone.Layer.m_type; ExpeditionInTierData activeExpedition = RundownManager.ActiveExpedition; return (int)type switch { 0 => activeExpedition.LevelLayoutData, 1 => activeExpedition.SecondaryLayout, 2 => activeExpedition.ThirdLayout, _ => throw new NotSupportedException($"LayerType: {type} is not supported!"), }; } return dimension.DimensionData.LevelLayoutData; } } [BepInPlugin("LGTuner", "LGTuner", "1.0.3")] [BepInProcess("GTFO.exe")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] public class EntryPoint : BasePlugin { public Harmony HarmonyInstance { get; private set; } public override void Load() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown HarmonyInstance = new Harmony("LGTuner"); HarmonyInstance.PatchAll(); ConfigManager.Init(); } } public static class LGExtensions { public static bool IsSame(this LG_GridPosition position, LG_GridPosition other) { //IL_0000: 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_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) if (position.x == other.x) { return position.z == other.z; } return false; } public static LG_GridPosition ToNormalGrid(this LG_Tile tile, int gridSize) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) return tile.m_shape.m_gridPosition.GetNormal(gridSize); } public static LG_GridPosition GetNormal(this LG_GridPosition position, int gridSize) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0051: 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_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0021: 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) LG_GridPosition result; if (gridSize < 0) { result = default(LG_GridPosition); result.x = position.x + BuilderInfo.GridZeroOffset; result.z = position.z + BuilderInfo.GridZeroOffset; return result; } int num = gridSize / 2; result = default(LG_GridPosition); result.x = position.x - num; result.z = position.z - num; return result; } public static Vector3 GetPositionNormal(this LG_Grid grid, int x, int z, int gridSize) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) if (gridSize < 0) { return ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).GetPosition(x - BuilderInfo.GridZeroOffset, z - BuilderInfo.GridZeroOffset); } int num = gridSize / 2; return ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).GetPosition(x + num, z + num); } public static int GetGridSize(this Dimension dimension) { return ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)dimension.Grid).m_sizeX; } public static bool TryGetDimension(this LG_Floor floor, int dimensionIndex, out Dimension dimension) { if (Enum.IsDefined(typeof(eDimensionIndex), dimensionIndex)) { return floor.GetDimension((eDimensionIndex)dimensionIndex, ref dimension); } dimension = null; return false; } public static bool TryGetDimension(this LG_Floor floor, eDimensionIndex dimensionIndex, out Dimension dimension) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (Enum.IsDefined(typeof(eDimensionIndex), dimensionIndex)) { return floor.GetDimension(dimensionIndex, ref dimension); } dimension = null; return false; } } public static class RandomExtensions { public static uint NextUint(this Random random) { int num = random.Next(1073741824); uint num2 = (uint)random.Next(4); return (uint)(num << 2) | num2; } public static float NextFloat(this Random random) { return Mathf.Clamp01((float)random.NextDouble()); } public static int ToSeed(this uint seed) { return (int)seed; } } internal static class Logger { private static readonly ManualLogSource _logger; static Logger() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Expected O, but got Unknown _logger = new ManualLogSource("LGTuner"); Logger.Sources.Add((ILogSource)(object)_logger); } private static string Format(object msg) { return msg.ToString(); } public static void Info(object data) { _logger.LogMessage((object)Format(data)); } public static void Verbose(object data) { } public static void Debug(object data) { _logger.LogDebug((object)Format(data)); } public static void Error(object data) { _logger.LogError((object)Format(data)); } } public enum DirectionType { Unknown, Forward, Backward, Left, Right } public enum RotateType { None, Flip, MoveTo_Left, MoveTo_Right, Towards_Random, Towards_Forward, Towards_Backward, Towards_Left, Towards_Right } public struct LG_PlugInfo { public static readonly Quaternion NoRotation = Quaternion.AngleAxis(0f, Vector3.up); public static readonly Quaternion RightRotation = Quaternion.AngleAxis(90f, Vector3.up); public static readonly Quaternion BackwardRotation = Quaternion.AngleAxis(180f, Vector3.up); public static readonly Quaternion LeftRotation = Quaternion.AngleAxis(270f, Vector3.up); public static readonly Vector3 FrontPlugPosition = Vector3.forward * 32f; public static readonly Vector3 BackPlugPosition = Vector3.back * 32f; public static readonly Vector3 LeftPlugPosition = Vector3.left * 32f; public static readonly Vector3 RightPlugPosition = Vector3.right * 32f; public bool IsValid { get; private set; } public DirectionType StartDirection { get; private set; } public int Count { get; private set; } public bool HasFront { get; private set; } public bool HasBack { get; private set; } public bool HasLeft { get; private set; } public bool HasRight { get; private set; } public bool TryGetNewRotation(uint seed, RotateType rotate, out Quaternion rotation) { //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) DirectionType newDirection = GetNewDirection(seed, StartDirection, rotate); if (Count >= 4) { rotation = GetRotationOfDirection(newDirection); return true; } Logger.Info($"You are rotating {Count} side Geomorph, this could lead to level gen crash!"); rotation = GetRotationOfDirection(newDirection); return true; } public bool HasPlug(DirectionType direction) { if (!IsValid) { return false; } if (Count >= 4) { return true; } return direction switch { DirectionType.Forward => HasFront, DirectionType.Backward => HasBack, DirectionType.Left => HasLeft, DirectionType.Right => HasRight, _ => false, }; } public static LG_PlugInfo BuildPlugInfo(GameObject geoObject, Quaternion rotation) { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Expected I4, but got Unknown //IL_011f: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)geoObject.GetComponent<LG_Geomorph>() == (Object)null) { return default(LG_PlugInfo); } Il2CppArrayBase<LG_Plug> componentsInChildren = geoObject.GetComponentsInChildren<LG_Plug>(); if (componentsInChildren == null) { return default(LG_PlugInfo); } if (componentsInChildren.Length < 1) { return default(LG_PlugInfo); } LG_PlugInfo result = default(LG_PlugInfo); foreach (LG_Plug item in componentsInChildren) { LG_PlugDir dir = item.m_dir; switch (dir - 2) { case 0: result.HasBack = true; result.Count++; break; case 2: result.HasFront = true; result.Count++; break; case 3: result.HasLeft = true; result.Count++; break; case 1: result.HasRight = true; result.Count++; break; } } result.IsValid = result.Count > 0; float num = Mathf.Round(((Quaternion)(ref rotation)).eulerAngles.y); Logger.Verbose($"angle: {num}"); num = Mathf.Repeat(num, 360f); result.StartDirection = Mathf.RoundToInt(num / 90f) switch { 0 => DirectionType.Forward, 1 => DirectionType.Right, 2 => DirectionType.Backward, 3 => DirectionType.Left, _ => DirectionType.Unknown, }; return result; } public static DirectionType GetNewDirection(uint seed, DirectionType direction, RotateType rotate) { if (direction == DirectionType.Unknown) { return DirectionType.Unknown; } if (rotate == RotateType.Towards_Random) { rotate = new Random(seed.ToSeed()).Next(4) switch { 0 => RotateType.Towards_Forward, 1 => RotateType.Towards_Backward, 2 => RotateType.Towards_Left, 3 => RotateType.Towards_Right, _ => throw new IndexOutOfRangeException("Towards_Random: nextIndex was out of range?!"), }; } return rotate switch { RotateType.None => direction, RotateType.Flip => direction switch { DirectionType.Forward => DirectionType.Backward, DirectionType.Backward => DirectionType.Forward, DirectionType.Left => DirectionType.Right, DirectionType.Right => DirectionType.Left, _ => throw new ArgumentOutOfRangeException("direction"), }, RotateType.MoveTo_Left => direction switch { DirectionType.Forward => DirectionType.Left, DirectionType.Backward => DirectionType.Right, DirectionType.Left => DirectionType.Backward, DirectionType.Right => DirectionType.Forward, _ => throw new ArgumentOutOfRangeException("direction"), }, RotateType.MoveTo_Right => direction switch { DirectionType.Forward => DirectionType.Right, DirectionType.Backward => DirectionType.Left, DirectionType.Left => DirectionType.Forward, DirectionType.Right => DirectionType.Backward, _ => throw new ArgumentOutOfRangeException("direction"), }, RotateType.Towards_Forward => DirectionType.Forward, RotateType.Towards_Backward => DirectionType.Backward, RotateType.Towards_Left => DirectionType.Left, RotateType.Towards_Right => DirectionType.Right, _ => throw new ArgumentOutOfRangeException("direction"), }; } public static Quaternion GetRotationOfDirection(DirectionType direction) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_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_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) return (Quaternion)(direction switch { DirectionType.Forward => NoRotation, DirectionType.Backward => BackwardRotation, DirectionType.Left => LeftRotation, DirectionType.Right => RightRotation, _ => throw new ArgumentOutOfRangeException("direction"), }); } } [GeneratedCode("VersionInfoGenerator", "2.0.0+git50a4b1a-master")] [CompilerGenerated] internal static class VersionInfo { public const string RootNamespace = "LGTuner"; public const string Version = "1.0.0"; public const string VersionPrerelease = null; public const string VersionMetadata = "git32ee113-dirty-master"; public const string SemVer = "1.0.0+git32ee113-dirty-master"; public const string GitRevShort = "32ee113-dirty"; public const string GitRevLong = "32ee113f774f28578bd63131db5298640efafe36-dirty"; public const string GitBranch = "master"; public const string GitTag = null; public const bool GitIsDirty = true; } } namespace LGTuner.Utils { internal static class JSON { private static readonly JsonSerializerOptions _setting; static JSON() { _setting = new JsonSerializerOptions { ReadCommentHandling = JsonCommentHandling.Skip, IncludeFields = false, PropertyNameCaseInsensitive = true, WriteIndented = true, IgnoreReadOnlyProperties = true }; _setting.Converters.Add(new JsonStringEnumConverter()); if (MTFOPartialDataUtil.IsLoaded && MTFOPartialDataUtil.Initialized) { _setting.Converters.Add(MTFOPartialDataUtil.PersistentIDConverter); Logger.Info("PartialData Support Found!"); } } public static T Deserialize<T>(string json) { return JsonSerializer.Deserialize<T>(json, _setting); } public static object Deserialize(Type type, string json) { return JsonSerializer.Deserialize(json, type, _setting); } public static string Serialize(object value, Type type) { return JsonSerializer.Serialize(value, type, _setting); } } public static class MTFOPartialDataUtil { public const string PLUGIN_GUID = "MTFO.Extension.PartialBlocks"; public static JsonConverter PersistentIDConverter { get; private set; } public static bool IsLoaded { get; private set; } public static bool Initialized { get; private set; } public static string PartialDataPath { get; private set; } public static string ConfigPath { get; private set; } static MTFOPartialDataUtil() { PersistentIDConverter = null; IsLoaded = false; Initialized = false; PartialDataPath = string.Empty; ConfigPath = string.Empty; if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("MTFO.Extension.PartialBlocks", out var value)) { return; } try { Assembly obj = ((value == null) ? null : value.Instance?.GetType()?.Assembly) ?? null; if ((object)obj == null) { throw new Exception("Assembly is Missing!"); } Type[] types = obj.GetTypes(); Type type = types.First((Type t) => t.Name == "PersistentIDConverter"); if ((object)type == null) { throw new Exception("Unable to Find PersistentIDConverter Class"); } Type obj2 = types.First((Type t) => t.Name == "PartialDataManager") ?? throw new Exception("Unable to Find PartialDataManager Class"); PropertyInfo property = obj2.GetProperty("Initialized", BindingFlags.Static | BindingFlags.Public); PropertyInfo property2 = obj2.GetProperty("PartialDataPath", BindingFlags.Static | BindingFlags.Public); PropertyInfo? property3 = obj2.GetProperty("ConfigPath", BindingFlags.Static | BindingFlags.Public); if ((object)property == null) { throw new Exception("Unable to Find Property: Initialized"); } if ((object)property2 == null) { throw new Exception("Unable to Find Property: PartialDataPath"); } if ((object)property3 == null) { throw new Exception("Unable to Find Field: ConfigPath"); } Initialized = (bool)property.GetValue(null); PartialDataPath = (string)property2.GetValue(null); ConfigPath = (string)property3.GetValue(null); PersistentIDConverter = (JsonConverter)Activator.CreateInstance(type); IsLoaded = true; } catch (Exception value2) { Logger.Error($"Exception thrown while reading data from MTFO_Extension_PartialData:\n{value2}"); } } } public static class MTFOUtil { public const string PLUGIN_GUID = "com.dak.MTFO"; public const BindingFlags PUBLIC_STATIC = BindingFlags.Static | BindingFlags.Public; public static string GameDataPath { get; private set; } public static string CustomPath { get; private set; } public static bool HasCustomContent { get; private set; } public static bool IsLoaded { get; private set; } static MTFOUtil() { GameDataPath = string.Empty; CustomPath = string.Empty; HasCustomContent = false; IsLoaded = false; if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("com.dak.MTFO", out var value)) { return; } try { Assembly obj = ((value == null) ? null : value.Instance?.GetType()?.Assembly) ?? null; if ((object)obj == null) { throw new Exception("Assembly is Missing!"); } Type obj2 = obj.GetTypes().First((Type t) => t.Name == "ConfigManager") ?? throw new Exception("Unable to Find ConfigManager Class"); FieldInfo field = obj2.GetField("GameDataPath", BindingFlags.Static | BindingFlags.Public); FieldInfo field2 = obj2.GetField("CustomPath", BindingFlags.Static | BindingFlags.Public); FieldInfo? field3 = obj2.GetField("HasCustomContent", BindingFlags.Static | BindingFlags.Public); if ((object)field == null) { throw new Exception("Unable to Find Field: GameDataPath"); } if ((object)field2 == null) { throw new Exception("Unable to Find Field: CustomPath"); } if ((object)field3 == null) { throw new Exception("Unable to Find Field: HasCustomContent"); } GameDataPath = (string)field.GetValue(null); CustomPath = (string)field2.GetValue(null); HasCustomContent = (bool)field3.GetValue(null); IsLoaded = true; } catch (Exception value2) { Logger.Error($"Exception thrown while reading path from DataDumper (MTFO): \n{value2}"); } } } } namespace LGTuner.Manager { public static class ConfigManager { [CompilerGenerated] private static class <>O { public static LiveEditEventHandler <0>__LiveEdit_FileChanged; } private static readonly List<LayoutConfig> _layouts = new List<LayoutConfig>(); private static readonly Dictionary<uint, LayoutConfig> _lookup = new Dictionary<uint, LayoutConfig>(); private static readonly Dictionary<string, LayoutConfig> _fileNameLookup = new Dictionary<string, LayoutConfig>(); public static IEnumerable<LayoutConfig> Layouts => _layouts; public static void Init() { //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Expected O, but got Unknown if (!MTFOUtil.HasCustomContent) { return; } string text = Path.Combine(MTFOUtil.CustomPath, "LGTuner"); FileInfo[] files = Directory.CreateDirectory(text).GetFiles(); foreach (FileInfo fileInfo in files) { string extension = fileInfo.Extension; bool flag = extension.Equals(".json", StringComparison.InvariantCultureIgnoreCase); bool flag2 = extension.Equals(".jsonc", StringComparison.InvariantCultureIgnoreCase); if (flag || flag2) { LayoutConfig layoutConfig = JSON.Deserialize<LayoutConfig>(File.ReadAllText(fileInfo.FullName)); if (_lookup.ContainsKey(layoutConfig.LevelLayoutID)) { Logger.Error($"Duplicated ID found!: {fileInfo.Name}, {layoutConfig.LevelLayoutID}"); } else { _layouts.Add(layoutConfig); _lookup.Add(layoutConfig.LevelLayoutID, layoutConfig); _fileNameLookup.Add(fileInfo.Name.ToLowerInvariant(), layoutConfig); } } } LiveEditListener obj = LiveEdit.CreateListener(text, "*.*", true); object obj2 = <>O.<0>__LiveEdit_FileChanged; if (obj2 == null) { LiveEditEventHandler val = LiveEdit_FileChanged; <>O.<0>__LiveEdit_FileChanged = val; obj2 = (object)val; } obj.FileChanged += (LiveEditEventHandler)obj2; obj.StartListen(); } private static void LiveEdit_FileChanged(LiveEditEventArgs e) { string key = Path.GetFileName(e.FullPath).ToLowerInvariant(); string extension = Path.GetExtension(e.FullPath); if (!extension.Equals(".json", StringComparison.InvariantCulture) && !extension.Equals(".jsonc", StringComparison.InvariantCulture)) { return; } Logger.Error($"File Edited: '{key}' '{e.FullPath}'"); try { LayoutConfig data = _fileNameLookup[key]; uint oldID = data.LevelLayoutID; LiveEdit.TryReadFileContent(e.FullPath, (Action<string>)delegate(string json) { try { LayoutConfig layoutConfig = JSON.Deserialize<LayoutConfig>(json); layoutConfig.LevelLayoutID = oldID; _fileNameLookup.Remove(key); _lookup.Remove(oldID); _layouts.Remove(data); _layouts.Add(layoutConfig); _lookup.Add(oldID, layoutConfig); _fileNameLookup.Add(key, layoutConfig); } catch (Exception value2) { Logger.Error($"Error while reading LGTuner Config: {value2}"); } }); } catch (Exception value) { Logger.Error($"Error while reading LGTuner Config: {value}"); } } private static void DumpLevel() { } private static void DumpLayerToConfig() { } public static bool TryGetConfig(uint layoutID, out LayoutConfig config) { return _lookup.TryGetValue(layoutID, out config); } } } namespace LGTuner.Inject { [HarmonyPatch(typeof(LG_BuildPlugBaseJob), "SpawnPlug")] internal static class Inject_BuildPlug { private static void Prefix(LG_Plug plug, ref GameObject prefab) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Expected I4, but got Unknown //IL_0253: Unknown result type (might be due to invalid IL or missing references) Logger.Info($"found plug for zone: {((LG_ZoneExpander)plug).m_linksFrom.m_zone.LocalIndex}{((Object)((LG_ZoneExpander)plug).m_linksFrom).name}->{((LG_ZoneExpander)plug).m_linksTo.m_zone.LocalIndex}{((Object)((LG_ZoneExpander)plug).m_linksTo).name}"); if (!BuilderInfo.TryGetConfig(((LG_ZoneExpander)plug).m_linksFrom.m_zone, out var config)) { return; } LG_GridPosition normal = ((LG_ZoneExpander)plug).m_linksFrom.m_geomorph.m_tile.m_shape.m_gridPosition.GetNormal(config.GridSize); if (!config.TryGetTileData(normal, out var overrideData)) { return; } ZoneOverrideData zoneData = overrideData.ZoneData; if (zoneData != null && zoneData.OverridePlugs && TryGetPlugPrefab(overrideData.ZoneData.GetNextPlug(), out var prefab2)) { Logger.Info(" - Prefab Replaced by Zone OverridePlugs! " + ((Object)prefab2).name); prefab = prefab2; } LG_PlugDir dir = plug.m_dir; GameObject prefab3; switch (dir - 2) { case 0: if (TryGetPlugPrefab(overrideData.BackwardPlug, out prefab3)) { Logger.Info(" - Prefab Replaced by BackwardPlug setting! " + ((Object)prefab3).name); prefab = prefab3; return; } break; case 2: if (TryGetPlugPrefab(overrideData.ForwardPlug, out prefab3)) { Logger.Info(" - Prefab Replaced by ForwardPlug setting! " + ((Object)prefab3).name); prefab = prefab3; return; } break; case 3: if (TryGetPlugPrefab(overrideData.LeftPlug, out prefab3)) { Logger.Info(" - Prefab Replaced by LeftPlug setting! " + ((Object)prefab3).name); prefab = prefab3; return; } break; case 1: if (TryGetPlugPrefab(overrideData.RightPlug, out prefab3)) { Logger.Info(" - Prefab Replaced by RightPlug setting! " + ((Object)prefab3).name); prefab = prefab3; return; } break; } if (overrideData.OverridePlugWithNoGateChance) { Random random = new Random(((LG_ZoneExpander)plug).m_linksFrom.AreaSeed.ToSeed()); bool withGate = ((LG_ZoneExpander)plug).m_isZoneSource || (!(overrideData.PlugWithNoGateChance >= 1f) && (overrideData.PlugWithNoGateChance <= 0f || random.NextFloat() >= overrideData.PlugWithNoGateChance)); int dropHeight = GetDropHeight(plug); GameObject randomPlug = BuilderInfo.GetRandomPlug(random.NextUint(), dropHeight, GetSubComplexOfPlug(plug), withGate); if ((Object)(object)randomPlug == (Object)null) { Logger.Error($"Plug was null! - Height: {dropHeight}"); } else { prefab = randomPlug; } } } private static SubComplex GetSubComplexOfPlug(LG_Plug plug) { //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_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001c: 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) SubComplex result = ((LG_ZoneExpander)plug).m_subComplex; if (((LG_ZoneExpander)plug).m_subComplex != ((LG_ZoneExpander)plug.m_pariedWith).m_subComplex) { result = (SubComplex)8; } return result; } private static bool TryGetPlugPrefab(string prefabPath, out GameObject prefab) { if (string.IsNullOrEmpty(prefabPath)) { prefab = null; return false; } prefab = ((Il2CppObjectBase)AssetAPI.GetLoadedAsset(prefabPath)).Cast<GameObject>(); return (Object)(object)prefab != (Object)null; } private static int GetDropHeight(LG_Plug plug) { //IL_0006: 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) return Mathf.RoundToInt(Mathf.Abs(((Component)plug).transform.position.y - ((Component)plug.m_pariedWith).transform.position.y) / BuilderInfo.AltitudeOffset); } } [HarmonyPatch(typeof(LG_BuildPlugJob), "Build")] internal class Inject_BuildPlugJob { [HarmonyWrapSafe] private static bool Prefix(LG_BuildPlugJob __instance) { //IL_0022: 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_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Invalid comparison between Unknown and I4 //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Expected I4, but got Unknown //IL_01cc: Unknown result type (might be due to invalid IL or missing references) //IL_01e8: Unknown result type (might be due to invalid IL or missing references) //IL_01ed: Unknown result type (might be due to invalid IL or missing references) //IL_01f5: Unknown result type (might be due to invalid IL or missing references) //IL_01fa: Unknown result type (might be due to invalid IL or missing references) //IL_01fd: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Unknown result type (might be due to invalid IL or missing references) GameObject val = null; LG_Plug plug = __instance.m_plug; Logger.Info($"buildplugjob plug in complex {((LG_ZoneExpander)plug).m_subComplex} plug status {((LG_ZoneExpander)plug).ExpanderStatus} plug direction {plug.m_dir} .."); if ((int)((LG_ZoneExpander)plug).ExpanderStatus == 1) { return true; } if (((LG_ZoneExpander)plug).m_isZoneSource) { return true; } if (!BuilderInfo.TryGetConfig(((LG_ZoneExpander)plug).m_linksFrom.m_zone, out var config)) { return true; } LG_GridPosition normal = ((LG_ZoneExpander)plug).m_linksFrom.m_geomorph.m_tile.m_shape.m_gridPosition.GetNormal(config.GridSize); if (!config.TryGetTileData(normal, out var overrideData)) { return true; } LG_PlugDir dir = plug.m_dir; GameObject prefab; switch (dir - 2) { case 0: if (TryGetPlugPrefab(overrideData.BackwardPlug, out prefab)) { Logger.Info(" - Prefab Replaced by BackwardPlug setting! " + ((Object)prefab).name); val = prefab; } break; case 2: if (TryGetPlugPrefab(overrideData.ForwardPlug, out prefab)) { Logger.Info(" - Prefab Replaced by ForwardPlug setting! " + ((Object)prefab).name); val = prefab; } break; case 3: if (TryGetPlugPrefab(overrideData.LeftPlug, out prefab)) { Logger.Info(" - Prefab Replaced by LeftPlug setting! " + ((Object)prefab).name); val = prefab; } break; case 1: if (TryGetPlugPrefab(overrideData.RightPlug, out prefab)) { Logger.Info(" - Prefab Replaced by RightPlug setting! " + ((Object)prefab).name); val = prefab; } break; } if ((Object)(object)val != (Object)null) { Logger.Info($"we shall replace a cap going {plug.m_dir}"); Vector3 position = ((Component)plug).transform.position; Quaternion rotation = ((Component)plug).transform.rotation; GameObject val2 = Object.Instantiate<GameObject>(val, position, rotation); val2.transform.SetParent(((Component)plug).transform, true); LG_Factory.FindAndBuildSelectorsAndSpawners(val2, RandomExtensions.NextSubSeed(__instance.m_rnd.Random), false); __instance.ProcessDivider(plug, val2, false, RandomExtensions.NextSubSeed(__instance.m_rnd.Random)); ((LG_ZoneExpander)plug).m_wasProcessed = true; } return true; } private static bool TryGetPlugPrefab(string prefabPath, out GameObject prefab) { if (string.IsNullOrEmpty(prefabPath)) { prefab = null; return false; } prefab = ((Il2CppObjectBase)AssetAPI.GetLoadedAsset(prefabPath)).Cast<GameObject>(); return (Object)(object)prefab != (Object)null; } } [HarmonyPatch(typeof(LG_LevelBuilder), "PlaceRoot")] internal static class Inject_BuildGeomorph { private static LayoutConfig _configContext; private static RotateType _nextRotateType; [HarmonyPostfix] [HarmonyWrapSafe] [HarmonyPatch("BuildFloor")] private static void Post_BuildFloor() { BuilderInfo.OnResourceSetSelected(); } [HarmonyPrefix] [HarmonyWrapSafe] [HarmonyPatch("PlaceRoot")] private static void Pre_PlaceRoot(LG_Tile tile, ref GameObject tilePrefab, ref bool forceAlignToVector, ref Vector3 alignVector, LG_Zone zone) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) _configContext = null; _nextRotateType = RotateType.None; forceAlignToVector = alignVector != Vector3.zero; int gridSize = zone.Dimension.GetGridSize(); LG_GridPosition val = tile.ToNormalGrid(gridSize); Logger.Info($"tile info: {val.x} {val.z} {((Object)tilePrefab).name} for {zone.LocalIndex} : {zone.DimensionIndex}"); if (!BuilderInfo.TryGetConfig(zone, out _configContext)) { return; } if (!_configContext.TryGetTileData(val, out var overrideData)) { overrideData = _configContext.PopulateTileOverrideForZone(zone, val); if (overrideData == null) { return; } } if (!string.IsNullOrEmpty(overrideData.Geomorph)) { Object loadedAsset = AssetAPI.GetLoadedAsset(overrideData.Geomorph); GameObject val2 = ((loadedAsset != null) ? ((Il2CppObjectBase)loadedAsset).Cast<GameObject>() : null); if ((Object)(object)val2 != (Object)null) { Logger.Info(" - tile overriden! " + ((Object)val2).name); tilePrefab = val2; } } if (overrideData.Rotation != 0) { _nextRotateType = overrideData.Rotation; } } [HarmonyPostfix] [HarmonyWrapSafe] [HarmonyPatch("GetTilePosition")] private static void Post_GetTilePosition(LG_Tile tile, LG_Floor floor, int dimensionIndex, ref Vector3 __result) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0059: 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_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_007f: 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) if (_configContext != null && floor.TryGetDimension(dimensionIndex, out var dimension)) { int gridSize = _configContext.GridSize; LG_GridPosition val = tile.ToNormalGrid(gridSize); if (_configContext.TryGetTileData(val, out var overrideData) && overrideData.OverrideAltitude) { Vector3 positionNormal = dimension.Grid.GetPositionNormal(val.x, val.z, gridSize); positionNormal += new Vector3(0f, (float)overrideData.Altitude * BuilderInfo.AltitudeOffset, 0f); __result = positionNormal; } } } [HarmonyPostfix] [HarmonyWrapSafe] [HarmonyPatch("PlaceRoot")] private static void Post_PlaceRoot(LG_Tile tile, LG_Zone zone, LG_Geomorph __result) { //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) if (_configContext == null) { return; } if (_nextRotateType != 0) { GameObject gameObject = ((Component)__result).gameObject; LG_PlugInfo lG_PlugInfo = LG_PlugInfo.BuildPlugInfo(gameObject, gameObject.transform.rotation); Logger.Info($" - TRYING ROTATION! PLUG COUNT: {lG_PlugInfo.Count}"); if (lG_PlugInfo.TryGetNewRotation(zone.m_subSeed, _nextRotateType, out var rotation)) { Logger.Info(" - Done!"); gameObject.transform.rotation = rotation; } __result.SetPlaced(); } int gridSize = _configContext.GridSize; LG_GridPosition normalGridPosition = tile.ToNormalGrid(gridSize); if (!_configContext.TryGetTileData(normalGridPosition, out var overrideData) || !overrideData.OverrideAreaSeeds) { return; } if (overrideData.AreaSeeds.Length == ((Il2CppArrayBase<LG_Area>)(object)__result.m_areas).Length) { int length = ((Il2CppArrayBase<LG_Area>)(object)__result.m_areas).Length; for (int i = 0; i < length; i++) { uint num = overrideData.AreaSeeds[i]; if (num != 0) { ((Il2CppArrayBase<LG_Area>)(object)__result.m_areas)[i].AreaSeed = num; Logger.Info($" - new area seed: {((Il2CppArrayBase<LG_Area>)(object)__result.m_areas)[i].m_navInfo}, {num}"); } } } else { Logger.Error($" - Area count and AreaSeeds item count mismatched! (CFG: {overrideData.AreaSeeds.Length} != AREA: {((Il2CppArrayBase<LG_Area>)(object)__result.m_areas).Length}) Area seed will not be applied!"); } } } [HarmonyPatch(typeof(LG_LoadComplexDataSetResourcesJob), "Build")] internal static class Inject_LoadComplexShard { private static int _waitingShared; private static void Prefix(LG_LoadComplexDataSetResourcesJob __instance) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected I4, but got Unknown //IL_0032: 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_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0040: 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_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) if (__instance.m_loadingStarted) { return; } foreach (Complex item in BuilderInfo.ExtraComplexResourceToLoad) { AssetBundleName val = (AssetBundleName)((int)item switch { 0 => 2, 1 => 4, 2 => 3, _ => 0, }); if ((int)val != 0) { AssetShardManager.LoadAllShardsForBundleAsync(val, Action.op_Implicit((Action)Loaded), 1, (LoadSceneMode)1); _waitingShared++; } } } private static void Loaded() { _waitingShared--; } [HarmonyWrapSafe] private static void Postfix(LG_LoadComplexDataSetResourcesJob __instance, ref bool __result) { if (_waitingShared >= 1) { __result = false; } } } } namespace LGTuner.Configs { public sealed class LayoutConfig { private TileOverrideData[,] _builtTileOverrides = new TileOverrideData[0, 0]; public uint LevelLayoutID { get; set; } public Complex[] ExtraComplexResourceToLoad { get; set; } = Array.Empty<Complex>(); public ZoneOverrideData[] ZoneOverrides { get; set; } = Array.Empty<ZoneOverrideData>(); public TileOverrideData[] TileOverrides { get; set; } = Array.Empty<TileOverrideData>(); [JsonIgnore] public int GridSize { get; private set; } [JsonIgnore] public int GridSizeHalf { get; private set; } public void Reset(int gridSize) { Array.ForEach(ZoneOverrides, delegate(ZoneOverrideData item) { item.Clear(); }); Array.Clear(_builtTileOverrides, 0, _builtTileOverrides.Length); GridSize = gridSize; GridSizeHalf = gridSize / 2; _builtTileOverrides = new TileOverrideData[GridSize, GridSize]; TileOverrideData[] tileOverrides = TileOverrides; foreach (TileOverrideData tileOverrideData in tileOverrides) { if (_builtTileOverrides[tileOverrideData.X + GridSizeHalf, tileOverrideData.Z + GridSizeHalf] == null) { PutOverrideData(tileOverrideData); continue; } Logger.Error($"Duplicate tile data in layout: {LevelLayoutID}, ({tileOverrideData.X}, {tileOverrideData.Z})!"); } } public bool TryGetTileData(LG_GridPosition normalGridPosition, out TileOverrideData overrideData) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) int num = normalGridPosition.x + GridSizeHalf; if (num >= GridSize) { Logger.Error($"TryGetTileData grid x was out of range! {num}:{GridSize}"); overrideData = null; return false; } int num2 = normalGridPosition.z + GridSizeHalf; if (num2 >= GridSize) { Logger.Error($"TryGetTileData grid Z was out of range! {num2}:{GridSize}"); overrideData = null; return false; } overrideData = _builtTileOverrides[num, num2]; return overrideData != null; } public void PutOverrideData(TileOverrideData data) { _builtTileOverrides[data.X + GridSizeHalf, data.Z + GridSizeHalf] = data; } public TileOverrideData PopulateTileOverrideForZone(LG_Zone zone, LG_GridPosition normalGridPosition) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_003b: 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) if (!TryGetZoneOverride(zone.LocalIndex, out var data)) { return null; } if (TryGetTileData(normalGridPosition, out var overrideData)) { overrideData.ZoneData = data; TryApplyOverrides(data, overrideData); return overrideData; } TileOverrideData tileOverrideData = new TileOverrideData { ZoneData = data, X = normalGridPosition.x, Z = normalGridPosition.z, OverridePlugWithNoGateChance = data.OverridePlugWithNoGateChance, PlugWithNoGateChance = data.PlugWithNoGateChance }; TryApplyOverrides(data, tileOverrideData); PutOverrideData(tileOverrideData); return tileOverrideData; } private void TryApplyOverrides(ZoneOverrideData zoneOverrideData, TileOverrideData tileOverrideData) { if (zoneOverrideData.OverrideGeomorphs && string.IsNullOrEmpty(tileOverrideData.Geomorph)) { ZoneOverrideData.GeomorphData? nextGeo = zoneOverrideData.GetNextGeo(); if (nextGeo.HasValue) { tileOverrideData.Geomorph = nextGeo.Value.Geomorph; if (tileOverrideData.Rotation == RotateType.None) { tileOverrideData.Rotation = ZoneOverrideData.DirectionToRotate(nextGeo.Value.Direction); } } } if (zoneOverrideData.OverrideAltitudes && !tileOverrideData.OverrideAltitude) { int? nextAltitude = zoneOverrideData.GetNextAltitude(); if (nextAltitude.HasValue) { tileOverrideData.OverrideAltitude = true; tileOverrideData.Altitude = nextAltitude.Value; } } } public bool TryGetZoneOverride(eLocalZoneIndex localIndex, out ZoneOverrideData data) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) data = ZoneOverrides.SingleOrDefault((ZoneOverrideData z) => z.LocalIndex == localIndex); return data != null; } } public sealed class TileOverrideData { public int X { get; set; } public int Z { get; set; } public bool OverrideAreaSeeds { get; set; } public uint[] AreaSeeds { get; set; } = Array.Empty<uint>(); public RotateType Rotation { get; set; } public string Geomorph { get; set; } = string.Empty; public bool OverrideAltitude { get; set; } public int Altitude { get; set; } public string ForwardPlug { get; set; } = string.Empty; public string BackwardPlug { get; set; } = string.Empty; public string LeftPlug { get; set; } = string.Empty; public string RightPlug { get; set; } = string.Empty; public bool OverridePlugWithNoGateChance { get; set; } public float PlugWithNoGateChance { get; set; } = 0.5f; [JsonIgnore] public ZoneOverrideData ZoneData { get; set; } } public sealed class ZoneOverrideData { public enum Direction { Unchanged, Random, Forward, Backward, Left, Right } public struct GeomorphData { public string Geomorph { get; set; } public Direction Direction { get; set; } } private int _curGeomorphIndex; private int _curAltitudeIndex; private int _curPlugIndex; public eLocalZoneIndex LocalIndex { get; set; } public bool OverrideGeomorphs { get; set; } public GeomorphData[] Geomorphs { get; set; } = Array.Empty<GeomorphData>(); public bool OverrideAltitudes { get; set; } public int[] Altitudes { get; set; } = Array.Empty<int>(); public bool OverridePlugs { get; set; } public string[] Plugs { get; set; } = Array.Empty<string>(); public bool OverridePlugWithNoGateChance { get; set; } public float PlugWithNoGateChance { get; set; } = 0.5f; public void Clear() { _curGeomorphIndex = 0; _curAltitudeIndex = 0; _curPlugIndex = 0; } public GeomorphData? GetNextGeo() { if (Geomorphs == null || Geomorphs.Length == 0) { return null; } return Geomorphs[_curGeomorphIndex++ % Geomorphs.Length]; } public int? GetNextAltitude() { if (Altitudes == null || Altitudes.Length == 0) { return null; } return Altitudes[_curAltitudeIndex++ % Altitudes.Length]; } public string GetNextPlug() { if (Plugs == null || Plugs.Length == 0) { return string.Empty; } return Plugs[_curPlugIndex++ % Plugs.Length]; } public static RotateType DirectionToRotate(Direction direction) { return direction switch { Direction.Unchanged => RotateType.None, Direction.Random => RotateType.Towards_Random, Direction.Forward => RotateType.Towards_Forward, Direction.Backward => RotateType.Towards_Backward, Direction.Left => RotateType.Towards_Left, Direction.Right => RotateType.Towards_Right, _ => throw new NotImplementedException($"DirectionType: {direction} is not supported"), }; } } }
plugins/net6/LGTuner_Revised.dll
Decompiled a month agousing System; using System.CodeDom.Compiler; 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.Json; using System.Text.Json.Serialization; using AssetShards; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using Expedition; using GTFO.API; using GTFO.API.Utilities; using GameData; using HarmonyLib; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.InteropTypes.Arrays; using Il2CppSystem; using Il2CppSystem.Collections.Generic; using LGTuner.Configs; using LGTuner.Manager; using LGTuner.Utils; using LevelGeneration; using LevelGeneration.Core; using Microsoft.CodeAnalysis; using UnityEngine; using UnityEngine.SceneManagement; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("LGTuner")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+git32ee113-dirty-master")] [assembly: AssemblyProduct("LGTuner")] [assembly: AssemblyTitle("LGTuner")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace LGTuner { public static class BuilderInfo { private static readonly List<Complex> _extraComplexResourceToLoad = new List<Complex>(); public static IEnumerable<Complex> ExtraComplexResourceToLoad => _extraComplexResourceToLoad; public static ComplexResourceSetDataBlock ComplexResourceSet { get; private set; } public static int GridSize { get; private set; } public static int GridCenter { get; private set; } public static int GridZeroOffset { get; private set; } public static float AltitudeOffset { get; private set; } public static LayoutConfig MainLayer { get; private set; } public static LayoutConfig SecondaryLayer { get; private set; } public static LayoutConfig ThirdLayer { get; private set; } public static LayoutConfig[] DimensionLayer { get; private set; } = Array.Empty<LayoutConfig>(); internal static void OnResourceSetSelected() { //IL_0156: Unknown result type (might be due to invalid IL or missing references) ComplexResourceSet = Builder.ComplexResourceSetBlock; GridSize = ComplexResourceSet.LevelGenConfig.GridSize; GridCenter = GridSize / 2; GridZeroOffset = -GridCenter; AltitudeOffset = ComplexResourceSet.LevelGenConfig.AltitudeOffset; MainLayer = null; SecondaryLayer = null; ThirdLayer = null; DimensionLayer = new LayoutConfig[Enum.GetValues(typeof(eDimensionIndex)).Length]; _extraComplexResourceToLoad.Clear(); ExpeditionInTierData activeExpedition = RundownManager.ActiveExpedition; if (ConfigManager.TryGetConfig(activeExpedition.LevelLayoutData, out var config)) { MainLayer = config; } if (activeExpedition.SecondaryLayerEnabled && ConfigManager.TryGetConfig(activeExpedition.SecondaryLayout, out var config2)) { SecondaryLayer = config2; } if (activeExpedition.ThirdLayerEnabled && ConfigManager.TryGetConfig(activeExpedition.ThirdLayout, out var config3)) { ThirdLayer = config3; } Enumerator<Dimension> enumerator = Builder.CurrentFloor.m_dimensions.GetEnumerator(); while (enumerator.MoveNext()) { Dimension current = enumerator.Current; if (!current.IsMainDimension && !current.DimensionData.IsStaticDimension) { LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock(current.DimensionData.LevelLayoutData); if (block != null && ConfigManager.TryGetConfig(((GameDataBlockBase<LevelLayoutDataBlock>)(object)block).persistentID, out var config4)) { Logger.Info("loysimme dimension ja levellayoutin"); config4.Reset(((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)current.Grid).m_sizeX); DimensionLayer[current.DimensionIndex] = config4; } } } MainLayer?.Reset(GridSize); SecondaryLayer?.Reset(GridSize); ThirdLayer?.Reset(GridSize); AddExtraShard(MainLayer); AddExtraShard(SecondaryLayer); AddExtraShard(ThirdLayer); Array.ForEach(DimensionLayer, delegate(LayoutConfig x) { AddExtraShard(x); }); } private static void AddExtraShard(LayoutConfig layerConfig) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) if (layerConfig == null) { return; } Complex[] extraComplexResourceToLoad = layerConfig.ExtraComplexResourceToLoad; foreach (Complex item in extraComplexResourceToLoad) { if (!_extraComplexResourceToLoad.Contains(item)) { _extraComplexResourceToLoad.Add(item); } } } public static bool TryGetConfig(LG_Zone zone, out LayoutConfig config) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: 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_0044: Expected I4, but got Unknown //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Unknown result type (might be due to invalid IL or missing references) Dimension val = default(Dimension); if (!Dimension.GetDimension(zone.DimensionIndex, ref val)) { Logger.Info("dimension getter failed"); config = null; return false; } if (val.IsMainDimension) { LG_LayerType type = zone.Layer.m_type; switch ((int)type) { case 0: config = MainLayer; return MainLayer != null; case 1: config = SecondaryLayer; return SecondaryLayer != null; case 2: config = ThirdLayer; return ThirdLayer != null; } } else if (!val.DimensionData.IsStaticDimension) { Logger.Info("menimme taenne"); Enumerator<Dimension> enumerator = Builder.CurrentFloor.m_dimensions.GetEnumerator(); while (enumerator.MoveNext()) { Dimension current = enumerator.Current; if (!current.IsMainDimension && !current.DimensionData.IsStaticDimension) { LevelLayoutDataBlock block = GameDataBlockBase<LevelLayoutDataBlock>.GetBlock(current.DimensionData.LevelLayoutData); if (block != null && ConfigManager.TryGetConfig(((GameDataBlockBase<LevelLayoutDataBlock>)(object)block).persistentID, out var config2)) { Logger.Info("loysimme dimension ja levellayoutin"); config2.Reset(((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)current.Grid).m_sizeX); DimensionLayer[current.DimensionIndex] = config2; } } } config = DimensionLayer[zone.DimensionIndex]; return config != null; } config = null; return false; } public static GameObject GetRandomPlug(uint seed, int plugHeight, SubComplex subcomplex, bool withGate) { //IL_002d: 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_0065: Unknown result type (might be due to invalid IL or missing references) ComplexResourceSetDataBlock complexResourceSet = ComplexResourceSet; return (GameObject)(plugHeight switch { 0 => complexResourceSet.GetRandomPrefab(seed, withGate ? complexResourceSet.m_straightPlugsWithGates : complexResourceSet.m_straightPlugsNoGates, subcomplex), 1 => complexResourceSet.GetRandomPrefab(seed, withGate ? complexResourceSet.m_singleDropPlugsWithGates : complexResourceSet.m_singleDropPlugsNoGates, subcomplex), 2 => complexResourceSet.GetRandomPrefab(seed, withGate ? complexResourceSet.m_doubleDropPlugsWithGates : complexResourceSet.m_doubleDropPlugsNoGates, subcomplex), _ => null, }); } public static uint GetLayoutIdOfZone(LG_Zone zone) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected I4, but got Unknown //IL_006e: Unknown result type (might be due to invalid IL or missing references) Dimension dimension = zone.Dimension; if (dimension.IsMainDimension) { LG_LayerType type = zone.Layer.m_type; ExpeditionInTierData activeExpedition = RundownManager.ActiveExpedition; return (int)type switch { 0 => activeExpedition.LevelLayoutData, 1 => activeExpedition.SecondaryLayout, 2 => activeExpedition.ThirdLayout, _ => throw new NotSupportedException($"LayerType: {type} is not supported!"), }; } return dimension.DimensionData.LevelLayoutData; } } [BepInPlugin("LGTuner", "LGTuner", "1.0.0")] [BepInProcess("GTFO.exe")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] public class EntryPoint : BasePlugin { public Harmony HarmonyInstance { get; private set; } public override void Load() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown HarmonyInstance = new Harmony("LGTuner"); HarmonyInstance.PatchAll(); ConfigManager.Init(); } } public static class LGExtensions { public static bool IsSame(this LG_GridPosition position, LG_GridPosition other) { //IL_0000: 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_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) if (position.x == other.x) { return position.z == other.z; } return false; } public static LG_GridPosition ToNormalGrid(this LG_Tile tile, int gridSize) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) return tile.m_shape.m_gridPosition.GetNormal(gridSize); } public static LG_GridPosition GetNormal(this LG_GridPosition position, int gridSize) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0051: 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_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0021: 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) LG_GridPosition result; if (gridSize < 0) { result = default(LG_GridPosition); result.x = position.x + BuilderInfo.GridZeroOffset; result.z = position.z + BuilderInfo.GridZeroOffset; return result; } int num = gridSize / 2; result = default(LG_GridPosition); result.x = position.x - num; result.z = position.z - num; return result; } public static Vector3 GetPositionNormal(this LG_Grid grid, int x, int z, int gridSize) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) if (gridSize < 0) { return ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).GetPosition(x - BuilderInfo.GridZeroOffset, z - BuilderInfo.GridZeroOffset); } int num = gridSize / 2; return ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)grid).GetPosition(x + num, z + num); } public static int GetGridSize(this Dimension dimension) { return ((CellGridBase<LG_Grid, LG_Tile, LG_Cell>)(object)dimension.Grid).m_sizeX; } public static bool TryGetDimension(this LG_Floor floor, int dimensionIndex, out Dimension dimension) { if (Enum.IsDefined(typeof(eDimensionIndex), dimensionIndex)) { return floor.GetDimension((eDimensionIndex)dimensionIndex, ref dimension); } dimension = null; return false; } public static bool TryGetDimension(this LG_Floor floor, eDimensionIndex dimensionIndex, out Dimension dimension) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (Enum.IsDefined(typeof(eDimensionIndex), dimensionIndex)) { return floor.GetDimension(dimensionIndex, ref dimension); } dimension = null; return false; } } public static class RandomExtensions { public static uint NextUint(this Random random) { int num = random.Next(1073741824); uint num2 = (uint)random.Next(4); return (uint)(num << 2) | num2; } public static float NextFloat(this Random random) { return Mathf.Clamp01((float)random.NextDouble()); } public static int ToSeed(this uint seed) { return (int)seed; } } internal static class Logger { private static readonly ManualLogSource _logger; static Logger() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Expected O, but got Unknown _logger = new ManualLogSource("LGTuner"); Logger.Sources.Add((ILogSource)(object)_logger); } private static string Format(object msg) { return msg.ToString(); } public static void Info(object data) { _logger.LogMessage((object)Format(data)); } public static void Verbose(object data) { } public static void Debug(object data) { _logger.LogDebug((object)Format(data)); } public static void Error(object data) { _logger.LogError((object)Format(data)); } } public enum DirectionType { Unknown, Forward, Backward, Left, Right } public enum RotateType { None, Flip, MoveTo_Left, MoveTo_Right, Towards_Random, Towards_Forward, Towards_Backward, Towards_Left, Towards_Right } public struct LG_PlugInfo { public static readonly Quaternion NoRotation = Quaternion.AngleAxis(0f, Vector3.up); public static readonly Quaternion RightRotation = Quaternion.AngleAxis(90f, Vector3.up); public static readonly Quaternion BackwardRotation = Quaternion.AngleAxis(180f, Vector3.up); public static readonly Quaternion LeftRotation = Quaternion.AngleAxis(270f, Vector3.up); public static readonly Vector3 FrontPlugPosition = Vector3.forward * 32f; public static readonly Vector3 BackPlugPosition = Vector3.back * 32f; public static readonly Vector3 LeftPlugPosition = Vector3.left * 32f; public static readonly Vector3 RightPlugPosition = Vector3.right * 32f; public bool IsValid { get; private set; } public DirectionType StartDirection { get; private set; } public int Count { get; private set; } public bool HasFront { get; private set; } public bool HasBack { get; private set; } public bool HasLeft { get; private set; } public bool HasRight { get; private set; } public bool TryGetNewRotation(uint seed, RotateType rotate, out Quaternion rotation) { //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) DirectionType newDirection = GetNewDirection(seed, StartDirection, rotate); if (Count >= 4) { rotation = GetRotationOfDirection(newDirection); return true; } Logger.Info($"You are rotating {Count} side Geomorph, this could lead to level gen crash!"); rotation = GetRotationOfDirection(newDirection); return true; } public bool HasPlug(DirectionType direction) { if (!IsValid) { return false; } if (Count >= 4) { return true; } return direction switch { DirectionType.Forward => HasFront, DirectionType.Backward => HasBack, DirectionType.Left => HasLeft, DirectionType.Right => HasRight, _ => false, }; } public static LG_PlugInfo BuildPlugInfo(GameObject geoObject, Quaternion rotation) { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Expected I4, but got Unknown //IL_011f: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)geoObject.GetComponent<LG_Geomorph>() == (Object)null) { return default(LG_PlugInfo); } Il2CppArrayBase<LG_Plug> componentsInChildren = geoObject.GetComponentsInChildren<LG_Plug>(); if (componentsInChildren == null) { return default(LG_PlugInfo); } if (componentsInChildren.Length < 1) { return default(LG_PlugInfo); } LG_PlugInfo result = default(LG_PlugInfo); foreach (LG_Plug item in componentsInChildren) { LG_PlugDir dir = item.m_dir; switch (dir - 2) { case 0: result.HasBack = true; result.Count++; break; case 2: result.HasFront = true; result.Count++; break; case 3: result.HasLeft = true; result.Count++; break; case 1: result.HasRight = true; result.Count++; break; } } result.IsValid = result.Count > 0; float num = Mathf.Round(((Quaternion)(ref rotation)).eulerAngles.y); Logger.Verbose($"angle: {num}"); num = Mathf.Repeat(num, 360f); result.StartDirection = Mathf.RoundToInt(num / 90f) switch { 0 => DirectionType.Forward, 1 => DirectionType.Right, 2 => DirectionType.Backward, 3 => DirectionType.Left, _ => DirectionType.Unknown, }; return result; } public static DirectionType GetNewDirection(uint seed, DirectionType direction, RotateType rotate) { if (direction == DirectionType.Unknown) { return DirectionType.Unknown; } if (rotate == RotateType.Towards_Random) { rotate = new Random(seed.ToSeed()).Next(4) switch { 0 => RotateType.Towards_Forward, 1 => RotateType.Towards_Backward, 2 => RotateType.Towards_Left, 3 => RotateType.Towards_Right, _ => throw new IndexOutOfRangeException("Towards_Random: nextIndex was out of range?!"), }; } return rotate switch { RotateType.None => direction, RotateType.Flip => direction switch { DirectionType.Forward => DirectionType.Backward, DirectionType.Backward => DirectionType.Forward, DirectionType.Left => DirectionType.Right, DirectionType.Right => DirectionType.Left, _ => throw new ArgumentOutOfRangeException("direction"), }, RotateType.MoveTo_Left => direction switch { DirectionType.Forward => DirectionType.Left, DirectionType.Backward => DirectionType.Right, DirectionType.Left => DirectionType.Backward, DirectionType.Right => DirectionType.Forward, _ => throw new ArgumentOutOfRangeException("direction"), }, RotateType.MoveTo_Right => direction switch { DirectionType.Forward => DirectionType.Right, DirectionType.Backward => DirectionType.Left, DirectionType.Left => DirectionType.Forward, DirectionType.Right => DirectionType.Backward, _ => throw new ArgumentOutOfRangeException("direction"), }, RotateType.Towards_Forward => DirectionType.Forward, RotateType.Towards_Backward => DirectionType.Backward, RotateType.Towards_Left => DirectionType.Left, RotateType.Towards_Right => DirectionType.Right, _ => throw new ArgumentOutOfRangeException("direction"), }; } public static Quaternion GetRotationOfDirection(DirectionType direction) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_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_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) return (Quaternion)(direction switch { DirectionType.Forward => NoRotation, DirectionType.Backward => BackwardRotation, DirectionType.Left => LeftRotation, DirectionType.Right => RightRotation, _ => throw new ArgumentOutOfRangeException("direction"), }); } } [GeneratedCode("VersionInfoGenerator", "2.0.0+git50a4b1a-master")] [CompilerGenerated] internal static class VersionInfo { public const string RootNamespace = "LGTuner"; public const string Version = "1.0.0"; public const string VersionPrerelease = null; public const string VersionMetadata = "git32ee113-dirty-master"; public const string SemVer = "1.0.0+git32ee113-dirty-master"; public const string GitRevShort = "32ee113-dirty"; public const string GitRevLong = "32ee113f774f28578bd63131db5298640efafe36-dirty"; public const string GitBranch = "master"; public const string GitTag = null; public const bool GitIsDirty = true; } } namespace LGTuner.Utils { internal static class JSON { private static readonly JsonSerializerOptions _setting; static JSON() { _setting = new JsonSerializerOptions { ReadCommentHandling = JsonCommentHandling.Skip, IncludeFields = false, PropertyNameCaseInsensitive = true, WriteIndented = true, IgnoreReadOnlyProperties = true }; _setting.Converters.Add(new JsonStringEnumConverter()); if (MTFOPartialDataUtil.IsLoaded && MTFOPartialDataUtil.Initialized) { _setting.Converters.Add(MTFOPartialDataUtil.PersistentIDConverter); Logger.Info("PartialData Support Found!"); } } public static T Deserialize<T>(string json) { return JsonSerializer.Deserialize<T>(json, _setting); } public static object Deserialize(Type type, string json) { return JsonSerializer.Deserialize(json, type, _setting); } public static string Serialize(object value, Type type) { return JsonSerializer.Serialize(value, type, _setting); } } public static class MTFOPartialDataUtil { public const string PLUGIN_GUID = "MTFO.Extension.PartialBlocks"; public static JsonConverter PersistentIDConverter { get; private set; } public static bool IsLoaded { get; private set; } public static bool Initialized { get; private set; } public static string PartialDataPath { get; private set; } public static string ConfigPath { get; private set; } static MTFOPartialDataUtil() { PersistentIDConverter = null; IsLoaded = false; Initialized = false; PartialDataPath = string.Empty; ConfigPath = string.Empty; if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("MTFO.Extension.PartialBlocks", out var value)) { return; } try { Assembly obj = ((value == null) ? null : value.Instance?.GetType()?.Assembly) ?? null; if ((object)obj == null) { throw new Exception("Assembly is Missing!"); } Type[] types = obj.GetTypes(); Type type = types.First((Type t) => t.Name == "PersistentIDConverter"); if ((object)type == null) { throw new Exception("Unable to Find PersistentIDConverter Class"); } Type obj2 = types.First((Type t) => t.Name == "PartialDataManager") ?? throw new Exception("Unable to Find PartialDataManager Class"); PropertyInfo property = obj2.GetProperty("Initialized", BindingFlags.Static | BindingFlags.Public); PropertyInfo property2 = obj2.GetProperty("PartialDataPath", BindingFlags.Static | BindingFlags.Public); PropertyInfo? property3 = obj2.GetProperty("ConfigPath", BindingFlags.Static | BindingFlags.Public); if ((object)property == null) { throw new Exception("Unable to Find Property: Initialized"); } if ((object)property2 == null) { throw new Exception("Unable to Find Property: PartialDataPath"); } if ((object)property3 == null) { throw new Exception("Unable to Find Field: ConfigPath"); } Initialized = (bool)property.GetValue(null); PartialDataPath = (string)property2.GetValue(null); ConfigPath = (string)property3.GetValue(null); PersistentIDConverter = (JsonConverter)Activator.CreateInstance(type); IsLoaded = true; } catch (Exception value2) { Logger.Error($"Exception thrown while reading data from MTFO_Extension_PartialData:\n{value2}"); } } } public static class MTFOUtil { public const string PLUGIN_GUID = "com.dak.MTFO"; public const BindingFlags PUBLIC_STATIC = BindingFlags.Static | BindingFlags.Public; public static string GameDataPath { get; private set; } public static string CustomPath { get; private set; } public static bool HasCustomContent { get; private set; } public static bool IsLoaded { get; private set; } static MTFOUtil() { GameDataPath = string.Empty; CustomPath = string.Empty; HasCustomContent = false; IsLoaded = false; if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("com.dak.MTFO", out var value)) { return; } try { Assembly obj = ((value == null) ? null : value.Instance?.GetType()?.Assembly) ?? null; if ((object)obj == null) { throw new Exception("Assembly is Missing!"); } Type obj2 = obj.GetTypes().First((Type t) => t.Name == "ConfigManager") ?? throw new Exception("Unable to Find ConfigManager Class"); FieldInfo field = obj2.GetField("GameDataPath", BindingFlags.Static | BindingFlags.Public); FieldInfo field2 = obj2.GetField("CustomPath", BindingFlags.Static | BindingFlags.Public); FieldInfo? field3 = obj2.GetField("HasCustomContent", BindingFlags.Static | BindingFlags.Public); if ((object)field == null) { throw new Exception("Unable to Find Field: GameDataPath"); } if ((object)field2 == null) { throw new Exception("Unable to Find Field: CustomPath"); } if ((object)field3 == null) { throw new Exception("Unable to Find Field: HasCustomContent"); } GameDataPath = (string)field.GetValue(null); CustomPath = (string)field2.GetValue(null); HasCustomContent = (bool)field3.GetValue(null); IsLoaded = true; } catch (Exception value2) { Logger.Error($"Exception thrown while reading path from DataDumper (MTFO): \n{value2}"); } } } } namespace LGTuner.Manager { public static class ConfigManager { [CompilerGenerated] private static class <>O { public static LiveEditEventHandler <0>__LiveEdit_FileChanged; } private static readonly List<LayoutConfig> _layouts = new List<LayoutConfig>(); private static readonly Dictionary<uint, LayoutConfig> _lookup = new Dictionary<uint, LayoutConfig>(); private static readonly Dictionary<string, LayoutConfig> _fileNameLookup = new Dictionary<string, LayoutConfig>(); public static IEnumerable<LayoutConfig> Layouts => _layouts; public static void Init() { //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0135: Expected O, but got Unknown if (!MTFOUtil.HasCustomContent) { return; } string text = Path.Combine(MTFOUtil.CustomPath, "LGTuner"); FileInfo[] files = Directory.CreateDirectory(text).GetFiles(); foreach (FileInfo fileInfo in files) { string extension = fileInfo.Extension; bool flag = extension.Equals(".json", StringComparison.InvariantCultureIgnoreCase); bool flag2 = extension.Equals(".jsonc", StringComparison.InvariantCultureIgnoreCase); if (flag || flag2) { LayoutConfig layoutConfig = JSON.Deserialize<LayoutConfig>(File.ReadAllText(fileInfo.FullName)); if (_lookup.ContainsKey(layoutConfig.LevelLayoutID)) { Logger.Error($"Duplicated ID found!: {fileInfo.Name}, {layoutConfig.LevelLayoutID}"); } else { _layouts.Add(layoutConfig); _lookup.Add(layoutConfig.LevelLayoutID, layoutConfig); _fileNameLookup.Add(fileInfo.Name.ToLowerInvariant(), layoutConfig); } } } LiveEditListener obj = LiveEdit.CreateListener(text, "*.*", true); object obj2 = <>O.<0>__LiveEdit_FileChanged; if (obj2 == null) { LiveEditEventHandler val = LiveEdit_FileChanged; <>O.<0>__LiveEdit_FileChanged = val; obj2 = (object)val; } obj.FileChanged += (LiveEditEventHandler)obj2; obj.StartListen(); } private static void LiveEdit_FileChanged(LiveEditEventArgs e) { string key = Path.GetFileName(e.FullPath).ToLowerInvariant(); string extension = Path.GetExtension(e.FullPath); if (!extension.Equals(".json", StringComparison.InvariantCulture) && !extension.Equals(".jsonc", StringComparison.InvariantCulture)) { return; } Logger.Error($"File Edited: '{key}' '{e.FullPath}'"); try { LayoutConfig data = _fileNameLookup[key]; uint oldID = data.LevelLayoutID; LiveEdit.TryReadFileContent(e.FullPath, (Action<string>)delegate(string json) { try { LayoutConfig layoutConfig = JSON.Deserialize<LayoutConfig>(json); layoutConfig.LevelLayoutID = oldID; _fileNameLookup.Remove(key); _lookup.Remove(oldID); _layouts.Remove(data); _layouts.Add(layoutConfig); _lookup.Add(oldID, layoutConfig); _fileNameLookup.Add(key, layoutConfig); } catch (Exception value2) { Logger.Error($"Error while reading LGTuner Config: {value2}"); } }); } catch (Exception value) { Logger.Error($"Error while reading LGTuner Config: {value}"); } } private static void DumpLevel() { } private static void DumpLayerToConfig() { } public static bool TryGetConfig(uint layoutID, out LayoutConfig config) { return _lookup.TryGetValue(layoutID, out config); } } } namespace LGTuner.Inject { [HarmonyPatch(typeof(LG_BuildPlugBaseJob), "SpawnPlug")] internal static class Inject_BuildPlug { private static void Prefix(LG_Plug plug, ref GameObject prefab) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Expected I4, but got Unknown //IL_0253: Unknown result type (might be due to invalid IL or missing references) Logger.Info($"found plug for zone: {((LG_ZoneExpander)plug).m_linksFrom.m_zone.LocalIndex}{((Object)((LG_ZoneExpander)plug).m_linksFrom).name}->{((LG_ZoneExpander)plug).m_linksTo.m_zone.LocalIndex}{((Object)((LG_ZoneExpander)plug).m_linksTo).name}"); if (!BuilderInfo.TryGetConfig(((LG_ZoneExpander)plug).m_linksFrom.m_zone, out var config)) { return; } LG_GridPosition normal = ((LG_ZoneExpander)plug).m_linksFrom.m_geomorph.m_tile.m_shape.m_gridPosition.GetNormal(config.GridSize); if (!config.TryGetTileData(normal, out var overrideData)) { return; } ZoneOverrideData zoneData = overrideData.ZoneData; if (zoneData != null && zoneData.OverridePlugs && TryGetPlugPrefab(overrideData.ZoneData.GetNextPlug(), out var prefab2)) { Logger.Info(" - Prefab Replaced by Zone OverridePlugs! " + ((Object)prefab2).name); prefab = prefab2; } LG_PlugDir dir = plug.m_dir; GameObject prefab3; switch (dir - 2) { case 0: if (TryGetPlugPrefab(overrideData.BackwardPlug, out prefab3)) { Logger.Info(" - Prefab Replaced by BackwardPlug setting! " + ((Object)prefab3).name); prefab = prefab3; return; } break; case 2: if (TryGetPlugPrefab(overrideData.ForwardPlug, out prefab3)) { Logger.Info(" - Prefab Replaced by ForwardPlug setting! " + ((Object)prefab3).name); prefab = prefab3; return; } break; case 3: if (TryGetPlugPrefab(overrideData.LeftPlug, out prefab3)) { Logger.Info(" - Prefab Replaced by LeftPlug setting! " + ((Object)prefab3).name); prefab = prefab3; return; } break; case 1: if (TryGetPlugPrefab(overrideData.RightPlug, out prefab3)) { Logger.Info(" - Prefab Replaced by RightPlug setting! " + ((Object)prefab3).name); prefab = prefab3; return; } break; } if (overrideData.OverridePlugWithNoGateChance) { Random random = new Random(((LG_ZoneExpander)plug).m_linksFrom.AreaSeed.ToSeed()); bool withGate = ((LG_ZoneExpander)plug).m_isZoneSource || (!(overrideData.PlugWithNoGateChance >= 1f) && (overrideData.PlugWithNoGateChance <= 0f || random.NextFloat() >= overrideData.PlugWithNoGateChance)); int dropHeight = GetDropHeight(plug); GameObject randomPlug = BuilderInfo.GetRandomPlug(random.NextUint(), dropHeight, GetSubComplexOfPlug(plug), withGate); if ((Object)(object)randomPlug == (Object)null) { Logger.Error($"Plug was null! - Height: {dropHeight}"); } else { prefab = randomPlug; } } } private static SubComplex GetSubComplexOfPlug(LG_Plug plug) { //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_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001c: 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) SubComplex result = ((LG_ZoneExpander)plug).m_subComplex; if (((LG_ZoneExpander)plug).m_subComplex != ((LG_ZoneExpander)plug.m_pariedWith).m_subComplex) { result = (SubComplex)8; } return result; } private static bool TryGetPlugPrefab(string prefabPath, out GameObject prefab) { if (string.IsNullOrEmpty(prefabPath)) { prefab = null; return false; } prefab = ((Il2CppObjectBase)AssetAPI.GetLoadedAsset(prefabPath)).Cast<GameObject>(); return (Object)(object)prefab != (Object)null; } private static int GetDropHeight(LG_Plug plug) { //IL_0006: 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) return Mathf.RoundToInt(Mathf.Abs(((Component)plug).transform.position.y - ((Component)plug.m_pariedWith).transform.position.y) / BuilderInfo.AltitudeOffset); } } [HarmonyPatch(typeof(LG_LevelBuilder), "PlaceRoot")] internal static class Inject_BuildGeomorph { private static LayoutConfig _configContext; private static RotateType _nextRotateType; [HarmonyPostfix] [HarmonyWrapSafe] [HarmonyPatch("BuildFloor")] private static void Post_BuildFloor() { BuilderInfo.OnResourceSetSelected(); } [HarmonyPrefix] [HarmonyWrapSafe] [HarmonyPatch("PlaceRoot")] private static void Pre_PlaceRoot(LG_Tile tile, ref GameObject tilePrefab, ref bool forceAlignToVector, ref Vector3 alignVector, LG_Zone zone) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Unknown result type (might be due to invalid IL or missing references) _configContext = null; _nextRotateType = RotateType.None; forceAlignToVector = alignVector != Vector3.zero; int gridSize = zone.Dimension.GetGridSize(); LG_GridPosition val = tile.ToNormalGrid(gridSize); Logger.Info($"tile info: {val.x} {val.z} {((Object)tilePrefab).name} for {zone.LocalIndex} : {zone.DimensionIndex}"); if (!BuilderInfo.TryGetConfig(zone, out _configContext)) { Logger.Info("trygetconfig failed, returning"); return; } if (!_configContext.TryGetTileData(val, out var overrideData)) { overrideData = _configContext.PopulateTileOverrideForZone(zone, val); if (overrideData == null) { Logger.Info("overridedata is null"); return; } } if (!string.IsNullOrEmpty(overrideData.Geomorph)) { Object loadedAsset = AssetAPI.GetLoadedAsset(overrideData.Geomorph); GameObject val2 = ((loadedAsset != null) ? ((Il2CppObjectBase)loadedAsset).Cast<GameObject>() : null); if ((Object)(object)val2 != (Object)null) { Logger.Info(" - tile overriden! " + ((Object)val2).name); tilePrefab = val2; } } if (overrideData.Rotation != 0) { _nextRotateType = overrideData.Rotation; } } [HarmonyPostfix] [HarmonyWrapSafe] [HarmonyPatch("GetTilePosition")] private static void Post_GetTilePosition(LG_Tile tile, LG_Floor floor, int dimensionIndex, ref Vector3 __result) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0059: 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_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_007f: 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) if (_configContext != null && floor.TryGetDimension(dimensionIndex, out var dimension)) { int gridSize = _configContext.GridSize; LG_GridPosition val = tile.ToNormalGrid(gridSize); if (_configContext.TryGetTileData(val, out var overrideData) && overrideData.OverrideAltitude) { Vector3 positionNormal = dimension.Grid.GetPositionNormal(val.x, val.z, gridSize); positionNormal += new Vector3(0f, (float)overrideData.Altitude * BuilderInfo.AltitudeOffset, 0f); __result = positionNormal; } } } [HarmonyPostfix] [HarmonyWrapSafe] [HarmonyPatch("PlaceRoot")] private static void Post_PlaceRoot(LG_Tile tile, LG_Zone zone, LG_Geomorph __result) { //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) if (_configContext == null) { return; } if (_nextRotateType != 0) { GameObject gameObject = ((Component)__result).gameObject; LG_PlugInfo lG_PlugInfo = LG_PlugInfo.BuildPlugInfo(gameObject, gameObject.transform.rotation); Logger.Info($" - TRYING ROTATION! PLUG COUNT: {lG_PlugInfo.Count}"); if (lG_PlugInfo.TryGetNewRotation(zone.m_subSeed, _nextRotateType, out var rotation)) { Logger.Info(" - Done!"); gameObject.transform.rotation = rotation; } __result.SetPlaced(); } int gridSize = _configContext.GridSize; LG_GridPosition normalGridPosition = tile.ToNormalGrid(gridSize); if (!_configContext.TryGetTileData(normalGridPosition, out var overrideData) || !overrideData.OverrideAreaSeeds) { return; } if (overrideData.AreaSeeds.Length == ((Il2CppArrayBase<LG_Area>)(object)__result.m_areas).Length) { int length = ((Il2CppArrayBase<LG_Area>)(object)__result.m_areas).Length; for (int i = 0; i < length; i++) { uint num = overrideData.AreaSeeds[i]; if (num != 0) { ((Il2CppArrayBase<LG_Area>)(object)__result.m_areas)[i].AreaSeed = num; Logger.Info($" - new area seed: {((Il2CppArrayBase<LG_Area>)(object)__result.m_areas)[i].m_navInfo}, {num}"); } } } else { Logger.Error($" - Area count and AreaSeeds item count mismatched! (CFG: {overrideData.AreaSeeds.Length} != AREA: {((Il2CppArrayBase<LG_Area>)(object)__result.m_areas).Length}) Area seed will not be applied!"); } } } [HarmonyPatch(typeof(LG_LoadComplexDataSetResourcesJob), "Build")] internal static class Inject_LoadComplexShard { private static int _waitingShared; [HarmonyWrapSafe] private static void Prefix(LG_LoadComplexDataSetResourcesJob __instance) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected I4, but got Unknown //IL_0032: 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_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0040: 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_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) if (__instance.m_loadingStarted) { return; } foreach (Complex item in BuilderInfo.ExtraComplexResourceToLoad) { AssetBundleName val = (AssetBundleName)((int)item switch { 0 => 2, 1 => 4, 2 => 3, _ => 0, }); if ((int)val != 0) { AssetShardManager.LoadAllShardsForBundleAsync(val, Action.op_Implicit((Action)Loaded), 1, (LoadSceneMode)1); _waitingShared++; } } } private static void Loaded() { _waitingShared--; } [HarmonyWrapSafe] private static void Postfix(LG_LoadComplexDataSetResourcesJob __instance, ref bool __result) { if (_waitingShared >= 1) { __result = false; } } } } namespace LGTuner.Configs { public sealed class LayoutConfig { private TileOverrideData[,] _builtTileOverrides = new TileOverrideData[0, 0]; public uint LevelLayoutID { get; set; } public Complex[] ExtraComplexResourceToLoad { get; set; } = Array.Empty<Complex>(); public ZoneOverrideData[] ZoneOverrides { get; set; } = Array.Empty<ZoneOverrideData>(); public TileOverrideData[] TileOverrides { get; set; } = Array.Empty<TileOverrideData>(); [JsonIgnore] public int GridSize { get; private set; } [JsonIgnore] public int GridSizeHalf { get; private set; } public void Reset(int gridSize) { Array.ForEach(ZoneOverrides, delegate(ZoneOverrideData item) { item.Clear(); }); Array.Clear(_builtTileOverrides, 0, _builtTileOverrides.Length); GridSize = gridSize; GridSizeHalf = gridSize / 2; _builtTileOverrides = new TileOverrideData[GridSize, GridSize]; TileOverrideData[] tileOverrides = TileOverrides; foreach (TileOverrideData tileOverrideData in tileOverrides) { if (_builtTileOverrides[tileOverrideData.X + GridSizeHalf, tileOverrideData.Z + GridSizeHalf] == null) { PutOverrideData(tileOverrideData); continue; } Logger.Error($"Duplicate tile data in layout: {LevelLayoutID}, ({tileOverrideData.X}, {tileOverrideData.Z})!"); } } public bool TryGetTileData(LG_GridPosition normalGridPosition, out TileOverrideData overrideData) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) int num = normalGridPosition.x + GridSizeHalf; if (num >= GridSize) { Logger.Error($"TryGetTileData grid x was out of range! {num}:{GridSize}"); overrideData = null; return false; } int num2 = normalGridPosition.z + GridSizeHalf; if (num2 >= GridSize) { Logger.Error($"TryGetTileData grid Z was out of range! {num2}:{GridSize}"); overrideData = null; return false; } overrideData = _builtTileOverrides[num, num2]; return overrideData != null; } public void PutOverrideData(TileOverrideData data) { _builtTileOverrides[data.X + GridSizeHalf, data.Z + GridSizeHalf] = data; } public TileOverrideData PopulateTileOverrideForZone(LG_Zone zone, LG_GridPosition normalGridPosition) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_003b: 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) if (!TryGetZoneOverride(zone.LocalIndex, out var data)) { return null; } if (TryGetTileData(normalGridPosition, out var overrideData)) { overrideData.ZoneData = data; TryApplyOverrides(data, overrideData); return overrideData; } TileOverrideData tileOverrideData = new TileOverrideData { ZoneData = data, X = normalGridPosition.x, Z = normalGridPosition.z, OverridePlugWithNoGateChance = data.OverridePlugWithNoGateChance, PlugWithNoGateChance = data.PlugWithNoGateChance }; TryApplyOverrides(data, tileOverrideData); PutOverrideData(tileOverrideData); return tileOverrideData; } private void TryApplyOverrides(ZoneOverrideData zoneOverrideData, TileOverrideData tileOverrideData) { if (zoneOverrideData.OverrideGeomorphs && string.IsNullOrEmpty(tileOverrideData.Geomorph)) { ZoneOverrideData.GeomorphData? nextGeo = zoneOverrideData.GetNextGeo(); if (nextGeo.HasValue) { tileOverrideData.Geomorph = nextGeo.Value.Geomorph; if (tileOverrideData.Rotation == RotateType.None) { tileOverrideData.Rotation = ZoneOverrideData.DirectionToRotate(nextGeo.Value.Direction); } } } if (zoneOverrideData.OverrideAltitudes && !tileOverrideData.OverrideAltitude) { int? nextAltitude = zoneOverrideData.GetNextAltitude(); if (nextAltitude.HasValue) { tileOverrideData.OverrideAltitude = true; tileOverrideData.Altitude = nextAltitude.Value; } } } public bool TryGetZoneOverride(eLocalZoneIndex localIndex, out ZoneOverrideData data) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) data = ZoneOverrides.SingleOrDefault((ZoneOverrideData z) => z.LocalIndex == localIndex); return data != null; } } public sealed class TileOverrideData { public int X { get; set; } public int Z { get; set; } public bool OverrideAreaSeeds { get; set; } public uint[] AreaSeeds { get; set; } = Array.Empty<uint>(); public RotateType Rotation { get; set; } public string Geomorph { get; set; } = string.Empty; public bool OverrideAltitude { get; set; } public int Altitude { get; set; } public string ForwardPlug { get; set; } = string.Empty; public string BackwardPlug { get; set; } = string.Empty; public string LeftPlug { get; set; } = string.Empty; public string RightPlug { get; set; } = string.Empty; public bool OverridePlugWithNoGateChance { get; set; } public float PlugWithNoGateChance { get; set; } = 0.5f; [JsonIgnore] public ZoneOverrideData ZoneData { get; set; } } public sealed class ZoneOverrideData { public enum Direction { Unchanged, Random, Forward, Backward, Left, Right } public struct GeomorphData { public string Geomorph { get; set; } public Direction Direction { get; set; } } private int _curGeomorphIndex; private int _curAltitudeIndex; private int _curPlugIndex; public eLocalZoneIndex LocalIndex { get; set; } public bool OverrideGeomorphs { get; set; } public GeomorphData[] Geomorphs { get; set; } = Array.Empty<GeomorphData>(); public bool OverrideAltitudes { get; set; } public int[] Altitudes { get; set; } = Array.Empty<int>(); public bool OverridePlugs { get; set; } public string[] Plugs { get; set; } = Array.Empty<string>(); public bool OverridePlugWithNoGateChance { get; set; } public float PlugWithNoGateChance { get; set; } = 0.5f; public void Clear() { _curGeomorphIndex = 0; _curAltitudeIndex = 0; _curPlugIndex = 0; } public GeomorphData? GetNextGeo() { if (Geomorphs == null || Geomorphs.Length == 0) { return null; } return Geomorphs[_curGeomorphIndex++ % Geomorphs.Length]; } public int? GetNextAltitude() { if (Altitudes == null || Altitudes.Length == 0) { return null; } return Altitudes[_curAltitudeIndex++ % Altitudes.Length]; } public string GetNextPlug() { if (Plugs == null || Plugs.Length == 0) { return string.Empty; } return Plugs[_curPlugIndex++ % Plugs.Length]; } public static RotateType DirectionToRotate(Direction direction) { return direction switch { Direction.Unchanged => RotateType.None, Direction.Random => RotateType.Towards_Random, Direction.Forward => RotateType.Towards_Forward, Direction.Backward => RotateType.Towards_Backward, Direction.Left => RotateType.Towards_Left, Direction.Right => RotateType.Towards_Right, _ => throw new NotImplementedException($"DirectionType: {direction} is not supported"), }; } } }
plugins/net6/Localia.PacksHelper.dll
Decompiled a month agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using Agents; using BepInEx; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using Gear; using HarmonyLib; using Il2CppInterop.Runtime.InteropTypes; using Il2CppSystem.Collections.Generic; using Localization; using Microsoft.CodeAnalysis; using Player; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("PacksHelper")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("PacksHelper")] [assembly: AssemblyTitle("PacksHelper")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace PacksHelper { [BepInPlugin("Localia.PacksHelper", "PacksHelper", "3.1.4")] public class EntryPoint : BasePlugin { private Harmony m_Harmony; public override void Load() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown m_Harmony = new Harmony("Localia.PacksHelper"); m_Harmony.PatchAll(); Logs.Info("OK"); } } internal static class Logs { private static readonly ManualLogSource _logger; static Logs() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown _logger = new ManualLogSource("Localia.PacksHelper"); Logger.Sources.Add((ILogSource)(object)_logger); } private static string Format(object msg) { return msg.ToString(); } public static void Info(object data) { _logger.LogMessage((object)Format(data)); } public static void Verbose(object data) { _logger.LogDebug((object)Format(data)); } public static void Debug(object data) { _logger.LogDebug((object)Format(data)); } public static void Error(object data) { _logger.LogError((object)Format(data)); } } internal static class PH_Manager { public static bool canCheckTar = false; public static bool canCheckInter = false; public static bool canCheckInputCondition = false; public static float forceUpateHUDTIme = 0f; public static int pack_type = 0; public static int last_pack_type = 0; public static string[] health = new string[4]; public static string[] standard = new string[4]; public static string[] special = new string[4]; public static string[] tool = new string[4]; public static string[] ori_all_info = new string[4]; public static string[] now_show_info = new string[4]; public static void checkPackType(string name) { if (name == "AmmoPackWeaponFirstPerson(Clone)") { pack_type = 1; } else if (name == "MediPackFirstPerson(Clone)" || name == "DisinfectonPackFirstPerson(Clone)") { pack_type = 2; } else if (name == "AmmoPackToolFirstPerson(Clone)") { pack_type = 3; } else { pack_type = 0; } if (pack_type > 0) { showAll(); } if (pack_type > 0 || (last_pack_type > 0 && pack_type != last_pack_type)) { forceUpdateHUDAll(); } last_pack_type = pack_type; } public static void showAll() { List<PlayerAgent> playerAgentsInLevel = PlayerManager.PlayerAgentsInLevel; for (int i = 0; i < playerAgentsInLevel.Count; i++) { if ((Object)(object)playerAgentsInLevel[i] != (Object)null && !((Agent)playerAgentsInLevel[i]).IsLocallyOwned && pack_type > 0 && !playerAgentsInLevel[i].NavMarker.ExtraInfoVisible) { playerAgentsInLevel[i].NavMarker.SetExtraInfoVisible(true); } } } public static void forceUpdateHUDAll() { forceUpateHUDTIme = Clock.Time + 0.1f; for (int i = 0; i < PlayerManager.PlayerAgentsInLevel.Count; i++) { PlayerAgent val = PlayerManager.PlayerAgentsInLevel[i]; if ((Object)(object)val != (Object)null && !((Agent)val).IsLocallyOwned) { val.NavMarker.m_isInfoDirty = true; val.NavMarker.UpdateExtraInfo(); } } } public static string get_ext_changed(PlaceNavMarkerOnGO marker, int slot) { if (pack_type == 1) { now_show_info[slot] = "<color=#CCCCCCFF><size=140%>" + standard[slot] + "\n" + special[slot] + "</size></color>"; } else if (pack_type == 2) { now_show_info[slot] = "<color=#CCCCCCFF><size=140%>" + health[slot] + "</size></color>"; } else if (pack_type == 3) { now_show_info[slot] = "<color=#CCCCCCFF><size=140%>" + tool[slot] + "</size></color>"; } else { now_show_info[slot] = ori_all_info[slot]; } return now_show_info[slot]; } public static void update_ori_hud_info(PlaceNavMarkerOnGO marker, int slot) { string extraInfo = marker.m_extraInfo; ori_all_info[slot] = extraInfo; now_show_info[slot] = ""; health[slot] = ""; standard[slot] = ""; special[slot] = ""; tool[slot] = ""; string[] array = extraInfo.Split("\n"); int num = 0; if (array.Length > 3) { health[slot] = array[num]; num++; if (array[num].IndexOf("<color=#00FFA8>", 0) != -1) { health[slot] = health[slot] + "\n" + array[num]; num++; } health[slot] = health[slot].Replace("<color=#CCCCCC66><size=70%>", "").Replace("66>", "FF>").Replace("A8>", "FF>"); standard[slot] = array[num].Replace("66>", "FF>"); num++; special[slot] = array[num].Replace("66>", "FF>"); num++; tool[slot] = array[num].Replace("66>", "FF>").Replace("</size></color>", ""); num++; } } } [HarmonyPatch(typeof(ResourcePackFirstPerson))] internal static class patch_ResourcePackFirstPersonUpdate { [HarmonyPatch("UpdateInteraction")] [HarmonyPrefix] [HarmonyPriority(100)] [HarmonyWrapSafe] public static void UpdateInteraction_pre(ResourcePackFirstPerson __instance) { if (!((Interact_Timed)__instance.m_interactApplyResource).TimerIsActive) { __instance.m_lastActionReceiver = null; PH_Manager.canCheckTar = true; PH_Manager.canCheckInter = false; PH_Manager.canCheckInputCondition = false; } } [HarmonyPatch("UpdateInteraction")] [HarmonyPostfix] [HarmonyWrapSafe] public static void UpdateInteraction_post(ResourcePackFirstPerson __instance) { PH_Manager.canCheckTar = false; PH_Manager.canCheckInter = false; PH_Manager.canCheckInputCondition = false; if (Clock.Time > PH_Manager.forceUpateHUDTIme) { PH_Manager.forceUpdateHUDAll(); } } [HarmonyPatch("UpdateInteractionActionName")] [HarmonyPrefix] [HarmonyWrapSafe] public static bool UpdateInteractionActionName(ResourcePackFirstPerson __instance) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_0195: 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) if (!PH_Manager.canCheckTar) { return true; } PH_Manager.canCheckTar = false; PH_Manager.canCheckInputCondition = false; bool flag = false; if (InputMapper.GetButtonDown.Invoke((InputAction)6, ((Item)__instance).Owner.InputFilter)) { __instance.m_actionReceiver = ((Component)((Item)__instance).Owner).GetComponentInChildren<iResourcePackReceiver>(); RaycastHit val = default(RaycastHit); if (Physics.Raycast(((Item)__instance).Owner.FPSCamera.Position, ((Item)__instance).Owner.FPSCamera.Forward, ref val, 2.4f, LayerManager.MASK_GIVE_RESOURCE_PACK)) { iResourcePackReceiver componentInParent = ((Component)((RaycastHit)(ref val)).collider).GetComponentInParent<iResourcePackReceiver>(); if (componentInParent != null) { __instance.m_actionReceiver = componentInParent; } } } else if (InputMapper.GetButton.Invoke((InputAction)8, ((Item)__instance).Owner.InputFilter)) { __instance.m_actionReceiver = ((Component)((Item)__instance).Owner).GetComponentInChildren<iResourcePackReceiver>(); flag = true; } else { __instance.m_actionReceiver = ((Component)((Item)__instance).Owner).GetComponentInChildren<iResourcePackReceiver>(); RaycastHit val2 = default(RaycastHit); if (Physics.Raycast(((Item)__instance).Owner.FPSCamera.Position, ((Item)__instance).Owner.FPSCamera.Forward, ref val2, 2.4f, LayerManager.MASK_GIVE_RESOURCE_PACK)) { iResourcePackReceiver componentInParent2 = ((Component)((RaycastHit)(ref val2)).collider).GetComponentInParent<iResourcePackReceiver>(); if (componentInParent2 != null) { __instance.m_actionReceiver = componentInParent2; } } } __instance.m_interactApplyResource.m_input = (InputAction)6; if (__instance.m_actionReceiver.IsLocallyOwned) { __instance.UpdateInteractionActionName(Text.Get(856u), true); if (!InputMapper.GetButtonDown.Invoke((InputAction)6, ((Item)__instance).Owner.InputFilter)) { __instance.m_interactApplyResource.m_input = (InputAction)8; } } else { __instance.UpdateInteractionActionName(__instance.m_actionReceiver.InteractionName, true); PlayerAgent val3 = ((Il2CppObjectBase)__instance.m_actionReceiver).TryCast<PlayerAgent>(); if ((Object)(object)val3 != (Object)null) { int num = val3.Owner.PlayerSlotIndex(); Interact_ManualTimedWithCallback interactApplyResource = __instance.m_interactApplyResource; ((Interact_Timed)interactApplyResource).InteractionMessage = ((Interact_Timed)interactApplyResource).InteractionMessage + "\n" + PH_Manager.now_show_info[num]; } if (!InputMapper.GetButtonDown.Invoke((InputAction)6, ((Item)__instance).Owner.InputFilter)) { __instance.m_interactApplyResource.m_input = (InputAction)7; } } PH_Manager.canCheckInter = true; if (flag) { PH_Manager.canCheckInputCondition = true; } return false; } } [HarmonyPatch(typeof(Interact_ManualTimedWithCallback))] internal static class patch_Interact_ManualTimedWithCallback { [HarmonyPatch("ManualUpdateWithCondition")] [HarmonyPrefix] [HarmonyWrapSafe] public static void ManualUpdateWithCondition_Pre(Interact_ManualTimedWithCallback __instance, bool __0, PlayerAgent __1, ref bool __2) { if (PH_Manager.canCheckInputCondition) { PH_Manager.canCheckInputCondition = false; __2 = true; } } } [HarmonyPatch(typeof(Interact_Timed))] internal static class patch_Interact_Timed { [HarmonyPatch("PlayerCheckInput")] [HarmonyPrefix] [HarmonyWrapSafe] public static bool PlayerCheckInput(Interact_Timed __instance, bool __result, PlayerAgent agent) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) if (!PH_Manager.canCheckInter) { return true; } PH_Manager.canCheckInter = false; if (!__instance.InternalAllowInput) { return true; } if (__instance.m_localPlayerInteractInfo == null && InputMapper.GetButton.Invoke(((Interact_Base)__instance).InputAction, agent.InputFilter)) { __instance.OnInteractorStateChanged(agent, true); return false; } return true; } } [HarmonyPatch(typeof(PlayerInventoryLocal), "SyncWieldItem")] internal static class Patch_onChangeGear { public static void Postfix(PlayerInventoryLocal __instance, ItemEquippable item) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Invalid comparison between Unknown and I4 if ((int)GameStateManager.Current.m_currentStateName == 10 && ((PlayerInventoryBase)__instance).AllowedToWieldItem && ((PlayerInventoryBase)__instance).m_playerEnabled) { PH_Manager.checkPackType(((Object)item).name); } } } [HarmonyPatch(typeof(PlaceNavMarkerOnGO))] internal static class Patch_PlaceNavMarkerOnGO { [HarmonyPatch("UpdateExtraInfo")] [HarmonyPostfix] [HarmonyWrapSafe] public static void UpdateExtraInfo(PlaceNavMarkerOnGO __instance) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Invalid comparison between Unknown and I4 if ((int)GameStateManager.Current.m_currentStateName == 10) { int num = __instance.m_player.Owner.PlayerSlotIndex(); if (__instance.m_extraInfo != PH_Manager.ori_all_info[num] && __instance.m_extraInfo != PH_Manager.now_show_info[num]) { PH_Manager.update_ori_hud_info(__instance, num); } __instance.m_extraInfo = PH_Manager.get_ext_changed(__instance, num); if (__instance.m_extraInfoVisible) { __instance.UpdateName(__instance.Player.Owner.NickName, PH_Manager.now_show_info[num]); } } } [HarmonyPatch("SetExtraInfoVisible")] [HarmonyPrefix] [HarmonyWrapSafe] public static bool SetExtraInfoVisible(PlaceNavMarkerOnGO __instance, bool visible) { if (PH_Manager.pack_type > 0 && !visible) { return false; } return true; } } }
plugins/net6/Localia.PingEverything.dll
Decompiled a month agousing System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using Enemies; using Globals; using HarmonyLib; using Player; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")] [assembly: AssemblyCompany("PingEverything")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("PingEverything")] [assembly: AssemblyTitle("PingEverything")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] namespace PingEverything; [BepInPlugin("Localia.PingEverything", "PingEverything", "3.0.0")] public class EntryPoint : BasePlugin { private Harmony m_Harmony; public override void Load() { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown m_Harmony = new Harmony("Localia.PingEverything"); m_Harmony.PatchAll(); } } internal static class Logs { private static readonly ManualLogSource _logger; static Logs() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown _logger = new ManualLogSource("Localia.PingEve"); Logger.Sources.Add((ILogSource)(object)_logger); } private static string Format(object msg) { return msg.ToString(); } public static void Info(object data) { _logger.LogMessage((object)Format(data)); } public static void Verbose(object data) { _logger.LogDebug((object)Format(data)); } public static void Debug(object data) { _logger.LogDebug((object)Format(data)); } public static void Error(object data) { _logger.LogError((object)Format(data)); } } [HarmonyPatch(typeof(LocalPlayerAgent), "UpdateGlobalInput")] internal static class Patch_PlayerAgent { public static float extdelay; public static bool Prefix(LocalPlayerAgent __instance) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: 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_0139: Unknown result type (might be due to invalid IL or missing references) //IL_028a: Unknown result type (might be due to invalid IL or missing references) //IL_0295: Unknown result type (might be due to invalid IL or missing references) //IL_02cc: Unknown result type (might be due to invalid IL or missing references) //IL_018f: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Invalid comparison between Unknown and I4 //IL_0394: Unknown result type (might be due to invalid IL or missing references) //IL_039f: Unknown result type (might be due to invalid IL or missing references) //IL_01dc: Unknown result type (might be due to invalid IL or missing references) //IL_040b: Unknown result type (might be due to invalid IL or missing references) //IL_0323: Unknown result type (might be due to invalid IL or missing references) //IL_022b: Unknown result type (might be due to invalid IL or missing references) //IL_045a: Unknown result type (might be due to invalid IL or missing references) if (Input.GetKey(__instance.m_ffKey1) && Input.GetKeyDown(__instance.m_ffKey2)) { return true; } if (FocusStateManager.MapToggleAllowed && InputMapper.GetButtonDown.Invoke((InputAction)33, (eFocusState)0)) { return true; } if (FocusStateManager.MapToggleAllowed && InputMapper.GetButtonDown.Invoke((InputAction)34, (eFocusState)0)) { return true; } if ((Global.ForceAllowF12 || FocusStateManager.MenuToggleAllowed) && InputMapper.GetButtonDown.Invoke((InputAction)36, (eFocusState)0)) { return true; } if (InputMapper.GetButtonDown.Invoke((InputAction)62, (eFocusState)0)) { return true; } if (InputMapper.GetButtonDown.Invoke((InputAction)58, ((PlayerAgent)__instance).InputFilter)) { if (GuiManager.PlayerMarkerIsVisibleAndInFocus((PlayerAgent)(object)__instance)) { GuiManager.AttemptSetPlayerPingStatus((PlayerAgent)(object)__instance, false, default(Vector3), (eNavMarkerStyle)1); } else { bool flag = false; RaycastHit val = default(RaycastHit); if (!flag && (Clock.Time > extdelay || extdelay - Clock.Time > 3f) && Physics.Raycast(__instance.CamPos, ((PlayerAgent)__instance).FPSCamera.Forward, ref val, 11f, LayerManager.MASK_BULLETWEAPON_RAY, (QueryTriggerInteraction)1)) { GameObject gameObject = ((Component)((Component)((RaycastHit)(ref val)).collider).transform).gameObject; EnemyAgent componentInParent = gameObject.GetComponentInParent<EnemyAgent>(); if ((Object)(object)componentInParent != (Object)null && (int)componentInParent.Locomotion.CurrentStateEnum == 14 && !((Object)componentInParent).name.Contains("Shadow")) { PlayerPingTarget val2 = gameObject.AddComponent<PlayerPingTarget>(); val2.m_pingTargetStyle = (eNavMarkerStyle)2; __instance.m_pingTarget = gameObject.GetComponent<iPlayerPingTarget>(); __instance.m_pingPos = ((RaycastHit)(ref val)).point; if (__instance.m_pingTarget != null && (__instance.m_pingTarget != __instance.m_lastPingedTarget || Clock.Time > __instance.m_pingAgainTimer)) { ((PlayerAgent)__instance).TriggerMarkerPing(__instance.m_pingTarget, ((Component)((RaycastHit)(ref val)).transform).gameObject, __instance.m_pingPos); __instance.m_pingAgainTimer = Clock.Time + 0.5f; __instance.m_lastPingedTarget = __instance.m_pingTarget; flag = true; extdelay = Clock.Time + 0.5f; } Object.Destroy((Object)(object)gameObject.GetComponent<PlayerPingTarget>()); } } if (!flag && Physics.Raycast(__instance.CamPos, ((PlayerAgent)__instance).FPSCamera.Forward, ref val, 40f, LayerManager.MASK_PING_TARGET, (QueryTriggerInteraction)1)) { __instance.m_pingTarget = ((Component)((RaycastHit)(ref val)).collider).GetComponentInChildren<iPlayerPingTarget>(); __instance.m_pingPos = ((RaycastHit)(ref val)).point; if (__instance.m_pingTarget != null && (__instance.m_pingTarget != __instance.m_lastPingedTarget || Clock.Time > __instance.m_pingAgainTimer)) { flag = true; ((PlayerAgent)__instance).TriggerMarkerPing(__instance.m_pingTarget, ((Component)((RaycastHit)(ref val)).transform).gameObject, __instance.m_pingPos); __instance.m_pingAgainTimer = Clock.Time + 0.5f; __instance.m_lastPingedTarget = __instance.m_pingTarget; extdelay = Clock.Time + 0.5f; } } if (!flag && (Clock.Time > extdelay || extdelay - Clock.Time > 3f) && Physics.Raycast(__instance.CamPos, ((PlayerAgent)__instance).FPSCamera.Forward, ref val, 40f, LayerManager.MASK_DEFAULT, (QueryTriggerInteraction)1)) { GameObject gameObject2 = ((Component)((Component)((RaycastHit)(ref val)).collider).transform).gameObject; if (!((Object)(object)gameObject2.GetComponent<PlayerPingTarget>() != (Object)null)) { PlayerPingTarget val3 = gameObject2.AddComponent<PlayerPingTarget>(); __instance.m_pingTarget = gameObject2.GetComponent<iPlayerPingTarget>(); __instance.m_pingPos = ((RaycastHit)(ref val)).point; if (__instance.m_pingTarget != null && (__instance.m_pingTarget != __instance.m_lastPingedTarget || Clock.Time > __instance.m_pingAgainTimer)) { ((PlayerAgent)__instance).TriggerMarkerPing(__instance.m_pingTarget, ((Component)((RaycastHit)(ref val)).transform).gameObject, __instance.m_pingPos); __instance.m_pingAgainTimer = Clock.Time + 0.5f; __instance.m_lastPingedTarget = __instance.m_pingTarget; flag = true; extdelay = Clock.Time + 0.5f; } Object.Destroy((Object)(object)gameObject2.GetComponent<PlayerPingTarget>()); } } if (!flag) { GuiManager.CrosshairLayer.PopAngryPingIndicator(); } } return false; } return true; } }
plugins/net6/Localia.ResourceHelper.dll
Decompiled a month agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using Agents; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using GameData; using HarmonyLib; using Il2CppInterop.Runtime.Injection; using Il2CppInterop.Runtime.InteropTypes.Arrays; using LevelGeneration; using Player; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")] [assembly: AssemblyCompany("ResourceHelper")] [assembly: AssemblyConfiguration("Debug")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("ResourceHelper")] [assembly: AssemblyTitle("ResourceHelper")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] namespace ResourceHelper; [BepInPlugin("Localia.ResourceHelper", "ResourceHelper", "3.0.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class EntryPoint : BasePlugin { private Harmony m_Harmony; public static ConfigFile config_path = new ConfigFile(Path.Combine(Paths.ConfigPath, "Localia.ResourceHelper-Plus.cfg"), true); public static ConfigEntry<float> config_aim_fade_factor { get; set; } public override void Load() { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Expected O, but got Unknown ClassInjector.RegisterTypeInIl2Cpp<Res_Moniter>(); m_Harmony = new Harmony("Localia.ResourceHelper"); m_Harmony.PatchAll(); SpriteManager.Initialize(); config_aim_fade_factor = config_path.Bind<float>("General Settings", "ADS Fade Factor", 0.5f, "The opacity of the icons when ADS. ( 0.0 is completely hidden, 1.0 is no fade.)"); Res_Manager.value_aim_fade_factor = Math.Clamp(config_aim_fade_factor.Value, 0f, 1f); Logs.Info("OK"); } } internal static class Logs { private static readonly ManualLogSource _logger; static Logs() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown _logger = new ManualLogSource("Localia.ResourceHelper"); Logger.Sources.Add((ILogSource)(object)_logger); } private static string Format(object msg) { return msg.ToString(); } public static void Info(object data) { _logger.LogMessage((object)Format(data)); } public static void Verbose(object data) { _logger.LogDebug((object)Format(data)); } public static void Debug(object data) { _logger.LogDebug((object)Format(data)); } public static void Error(object data) { _logger.LogError((object)Format(data)); } } [HarmonyPatch(typeof(PlayerSyncModelData), "Setup")] internal static class Patch_PlayerSyncModelData { [HarmonyWrapSafe] public static void Postfix(PlayerSyncModelData __instance, PlayerAgent owner) { Res_Moniter res_Moniter = ((Component)owner).gameObject.AddComponent<Res_Moniter>(); res_Moniter.agent = owner; if (((Agent)owner).IsLocallyOwned) { res_Moniter.isLocal = true; Res_Moniter.localAgent = owner; } } } [HarmonyPatch(typeof(LG_PickupItem_Sync), "OnStateChange")] internal static class AttemptPickupInteraction { [HarmonyWrapSafe] public static void Postfix(LG_PickupItem_Sync __instance, pPickupItemState oldState, pPickupItemState newState) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Invalid comparison between Unknown and I4 int instanceID = ((Object)((Component)__instance).gameObject).GetInstanceID(); if (Res_Manager.OBJ.ContainsKey(instanceID) && (int)newState.status == 1) { MarkUI_Manager.DestoryMarker(instanceID); Res_Manager.RemoveID(instanceID); } } } [HarmonyPatch(typeof(GameStateManager), "DoChangeState")] internal static class Patch_DoChangeState { [HarmonyWrapSafe] public static void Postfix(GameStateManager __instance, eGameStateName nextState) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0004: Invalid comparison between Unknown and I4 //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Invalid comparison between Unknown and I4 //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Invalid comparison between Unknown and I4 //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Invalid comparison between Unknown and I4 //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Invalid comparison between Unknown and I4 //IL_0037: 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_005d: Invalid comparison between Unknown and I4 //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) if ((int)nextState == 10) { Res_Moniter.canUpdate = true; return; } Res_Moniter.canUpdate = false; if ((int)nextState == 11 || (int)nextState == 15 || (int)nextState == 14) { Logs.Verbose($"Do Clear on state {nextState}"); MarkUI_Manager.DestoryMarkerAll(); Res_Manager.ClearDics(); } else if ((int)nextState == 7 || (int)nextState == 8) { Res_Moniter.StoreList.Clear(); Res_Moniter.nextCheckPointReloadTime = 0f; Res_Moniter.hasStore = false; Res_Moniter.lastStoreDoor = Vector3.zero; } } } [HarmonyPatch(typeof(SyncedNavMarkerWrapper), "OnStateChange")] internal static class Patch_Ping { [HarmonyWrapSafe] public static void Postfix(SyncedNavMarkerWrapper __instance, pNavMarkerState oldState, pNavMarkerState newState) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) if ((int)newState.status == 0) { Res_Moniter.PingList[newState.worldPos] = 0; Res_Moniter.PingListNextTime[newState.worldPos] = 0f; } } } [HarmonyPatch(typeof(CheckpointManager), "OnStateChange")] internal static class Patch_CheckpointManagerOnStateChange { [HarmonyWrapSafe] public static void Postfix(CheckpointManager __instance, pCheckpointState oldState, pCheckpointState newState, bool isRecall) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Invalid comparison between Unknown and I4 //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Invalid comparison between Unknown and I4 //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005d: 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_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) if (Res_Moniter.hasStore && (int)newState.lastInteraction == 2) { Logs.Verbose("CheckpointManager prepare to reload"); Res_Moniter.reloadcount = 0; Res_Moniter.reloadIndex = 0; Res_Moniter.nextCheckPointReloadTime = Clock.Time + 4f; } else { if ((int)newState.lastInteraction != 1 || !(newState.doorLockPosition != Res_Moniter.lastStoreDoor)) { return; } Logs.Verbose("CheckpointManager prepare to store "); Res_Moniter.lastStoreDoor = newState.doorLockPosition; Res_Moniter.hasStore = true; Res_Moniter.StoreList.Clear(); foreach (KeyValuePair<int, PlaceNavMarkerOnGO> item in MarkUI_Manager.MARKER) { GameObject val = Res_Manager.OBJ[item.Key]; if ((Object)(object)val != (Object)null) { Res_Moniter.StoreList.Add(val.transform.position); } } Res_Moniter.reloadIndex = Res_Moniter.StoreList.Count; Logs.Verbose($"Store count {Res_Moniter.StoreList.Count}"); } } } [HarmonyPatch(typeof(FirstPersonItemHolder), "UpdateItemTransition")] internal static class Patch_FPSIUpdateItemTransition { public static void Postfix(FirstPersonItemHolder __instance, float __result) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Invalid comparison between Unknown and I4 //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Invalid comparison between Unknown and I4 //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Invalid comparison between Unknown and I4 //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Invalid comparison between Unknown and I4 if (Res_Manager.value_aim_fade_factor < 1f) { float num = __result; num = (((int)__instance.m_currentState == 3 && (int)__instance.m_lastState == 1) ? (1f - __result) : (((int)__instance.m_currentState != 1 || (int)__instance.m_lastState != 3) ? 1f : __result)); if (num < Res_Manager.value_aim_fade_factor) { Res_Moniter.ads_alpha_multi = Res_Manager.value_aim_fade_factor; } else { Res_Moniter.ads_alpha_multi = num; } } else { Res_Moniter.ads_alpha_multi = 1f; } } } public class Res_Moniter : MonoBehaviour { public PlayerAgent agent = null; public bool isLocal = false; public float nextScanTime = 0f; public static PlayerAgent localAgent = null; public static bool canUpdate = false; public static bool hasStore = false; public static int reloadcount = 0; public static int reloadIndex = 0; public static float nextCheckPointReloadTime = 0f; public static Vector3 lastStoreDoor = Vector3.zero; public static Dictionary<Vector3, int> PingList = new Dictionary<Vector3, int>(); public static Dictionary<Vector3, float> PingListNextTime = new Dictionary<Vector3, float>(); public static List<Vector3> StoreList = new List<Vector3>(); public static float ads_alpha_multi = 1f; public void LateUpdate() { if (canUpdate) { if (Clock.Time >= nextScanTime) { nextScanTime = Clock.Time + 0.012f; Res_Manager.Do_Man_Scan(agent, isLocal); } if (isLocal) { LocalResMarkerUpdate(); CheckPingList(); CheckCheckPointReload(); } } } public static void LocalResMarkerUpdate() { //IL_02f9: 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_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0328: Unknown result type (might be due to invalid IL or missing references) //IL_032d: 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_019c: Unknown result type (might be due to invalid IL or missing references) //IL_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01c1: 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_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_01db: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Unknown result type (might be due to invalid IL or missing references) int num = 0; float num2 = 360f; float num3 = 100f; bool flag = false; float nowtime = Clock.Time; Vector3 val2; foreach (KeyValuePair<int, PlaceNavMarkerOnGO> item in MarkUI_Manager.MARKER) { int id = item.Key; try { GameObject val = Res_Manager.OBJ[id]; float num4 = Vector3.Distance(val.transform.position, localAgent.FPSCamera.Position); if (num4 > 60f || (num4 > Res_Manager.MAX_DIS[id] && Clock.Time > Res_Manager.FORCE_SHOW_TIME[id])) { if (MarkUI_Manager.VISIBLE[id]) { MarkUI_Manager.VISIBLE[id] = false; item.Value.SetMarkerVisible(false); } continue; } if (!TimerCheckValid(ref nowtime, ref id)) { flag = true; num = id; Logs.Error($"Item was changed, it's ok but why? ID:{id},Name:{Res_Manager.NAME[id]}"); break; } if (!MarkUI_Manager.VISIBLE[id]) { MarkUI_Manager.VISIBLE[id] = true; item.Value.SetMarkerVisible(true); MarkUI_Manager.START_FADE_TIME[id] = nowtime; } if (num4 < 4f) { item.Value.m_marker.SetTitle(item.Value.m_nameToShow); } else { Vector3 position = val.transform.position; ((Vector3)(ref position))[1] = ((Vector3)(ref position))[1] + num4 * 0.015f; val2 = position - localAgent.FPSCamera.Position; float num5 = Vector3.Angle(((Vector3)(ref val2)).normalized, localAgent.FPSCamera.Forward); if ((double)num5 < (double)(0f - num4) * 0.3 + 20.0) { if (num5 < num2) { num2 = num5; num3 = num4; num = id; } item.Value.m_marker.SetTitle(item.Value.m_nameToShow); } else { item.Value.m_marker.SetTitle(""); } } SetMarkerAlpha(ref nowtime, ref id, item.Value.m_marker); continue; } catch { flag = true; num = id; Logs.Error($"Failed to check marker on id{id},Name:{Res_Manager.NAME[id]}"); } break; } if (flag) { GameObject val3 = Res_Manager.OBJ[num]; Res_Manager.RemoveID(num); MarkUI_Manager.DestoryMarker(num); Res_Manager.Do_Pos_Scan(val3.transform.position); } else if (num != 0) { val2 = ((Component)MarkUI_Manager.MARKER[num].m_marker).transform.localScale; float num6 = ((Vector3)(ref val2))[0] + num3 * 0.003f; ((Component)MarkUI_Manager.MARKER[num].m_marker).transform.localScale = new Vector3(num6, num6, num6); } } public static bool TimerCheckValid(ref float nowtime, ref int id) { if (nowtime > Res_Manager.TIME_CHECK_VALID[id]) { if (Res_Manager.CheckVaild(id)) { Res_Manager.TIME_CHECK_VALID[id] = nowtime + 1f; return true; } return false; } return true; } public static void SetMarkerAlpha(ref float nowtime, ref int id, NavMarker marker) { if (MarkUI_Manager.START_FADE_TIME[id] > 0f) { float num = (nowtime - MarkUI_Manager.START_FADE_TIME[id]) / 0.1f; if (num >= 0f && (double)num <= 1.0) { float easingValue = Easing.GetEasingValue((eEasingType)13, num, false); marker.SetAlpha(easingValue * ads_alpha_multi); } else { MarkUI_Manager.START_FADE_TIME[id] = 0f; marker.SetAlpha(ads_alpha_multi); } } else { marker.SetAlpha(ads_alpha_multi); } } public static void CheckPingList() { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0040: 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_006b: 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_00b6: 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_0083: 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_008b: 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) if (PingList.Count <= 0) { return; } List<Vector3> list = new List<Vector3>(PingList.Keys); for (int i = 0; i < list.Count; i++) { Vector3 val = list[i]; if (Clock.Time > PingListNextTime[val]) { PingListNextTime[val] = Clock.Time + 0.5f; if (PingList[val] < 7) { PingList[val]++; Res_Manager.GetMarkersAtPos(val); } else { PingList.Remove(val); PingListNextTime.Remove(val); } } } } public static void CheckCheckPointReload() { //IL_004b: Unknown result type (might be due to invalid IL or missing references) if (!hasStore || !(nextCheckPointReloadTime > 0f) || !(Clock.Time > nextCheckPointReloadTime)) { return; } if (reloadIndex < StoreList.Count) { if (Res_Manager.Do_Pos_Scan(StoreList[reloadIndex])) { reloadcount++; } reloadIndex++; } else { nextCheckPointReloadTime = 0f; if (reloadIndex == StoreList.Count) { Logs.Verbose($"Reload {reloadcount}/{StoreList.Count} store points"); } } } } public class SpriteManager { private static readonly Dictionary<string, Texture2D> _textureCache = new Dictionary<string, Texture2D>(); private static readonly Dictionary<string, Sprite> _spriteCache = new Dictionary<string, Sprite>(); public static string BaseSpritePath { get; private set; } public static void Initialize() { string directoryName = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); BaseSpritePath = Path.Combine(directoryName, "icons"); string[] files = Directory.GetFiles(BaseSpritePath, "*.png", SearchOption.AllDirectories); string[] array = files; foreach (string file in array) { TryCacheTexture2D(file, alsoCacheSprite: true); } if (!MTFOUtil.IsLoaded) { return; } string path = Path.Combine(MTFOUtil.CustomPath, "ExtraResourceHelper"); if (!Directory.Exists(path)) { Directory.CreateDirectory(path); return; } string[] files2 = Directory.GetFiles(path, "*.png", SearchOption.AllDirectories); string[] array2 = files2; foreach (string file2 in array2) { TryCacheTexture2D(file2, alsoCacheSprite: false); } } public static void TryCacheTexture2D(string file, bool alsoCacheSprite) { //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Expected O, but got Unknown if (!File.Exists(file)) { return; } string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(file); if (!Res_Manager.InitializeResData(fileNameWithoutExtension)) { return; } string text = fileNameWithoutExtension.ToLower(); if (_textureCache.ContainsKey(text)) { return; } byte[] array = File.ReadAllBytes(file); Texture2D val = new Texture2D(2, 2); if (ImageConversion.LoadImage(val, Il2CppStructArray<byte>.op_Implicit(array))) { ((Object)val).name = text; ((Object)val).hideFlags = (HideFlags)61; Logs.Debug("GeneratedTexture: " + text); _textureCache.Add(text, val); if (alsoCacheSprite) { GenerateSprite(text); } } } public static Sprite GenerateSprite(string fileName, float pixelsPerUnit = 128f) { //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) if (!_textureCache.TryGetValue(fileName, out var value)) { return null; } string spriteKey = GetSpriteKey(fileName, pixelsPerUnit); if (_spriteCache.TryGetValue(spriteKey, out var value2)) { return value2; } Sprite val = Sprite.Create(value, new Rect(0f, 0f, (float)((Texture)value).width, (float)((Texture)value).height), new Vector2(0.5f, 0.5f), pixelsPerUnit); ((Object)val).name = spriteKey; ((Object)val).hideFlags = (HideFlags)61; Logs.Debug("GeneratedSprite: " + spriteKey); _spriteCache.Add(spriteKey, val); return val; } public static bool TryGetSpriteCache(string fileName, float pixelsPerUnit, out Sprite sprite) { return _spriteCache.TryGetValue(GetSpriteKey(fileName, pixelsPerUnit), out sprite); } private static string GetSpriteKey(string name, float pixelsPerUnit) { return $"{name}__{pixelsPerUnit:0.##}"; } } internal static class Res_Manager { public struct Res_Data { public string rundown_name; public string tag_name; public string default_name; public string file_name; public uint persistentID; public int ammoType; public int fade_dis; public Color color; public ConfigEntry<string> config_name { get; set; } } public static Dictionary<uint, Res_Data> RES_BNK = new Dictionary<uint, Res_Data>(); public static Dictionary<int, GameObject> OBJ = new Dictionary<int, GameObject>(); public static Dictionary<int, string> NAME = new Dictionary<int, string>(); public static Dictionary<int, int> COUNT = new Dictionary<int, int>(); public static Dictionary<int, uint> PID = new Dictionary<int, uint>(); public static Dictionary<int, int> TAR = new Dictionary<int, int>(); public static Dictionary<int, float> MAX_DIS = new Dictionary<int, float>(); public static Dictionary<int, float> FORCE_SHOW_TIME = new Dictionary<int, float>(); public static Dictionary<int, float> TIME_CHECK_VALID = new Dictionary<int, float>(); public static float value_aim_fade_factor; public static bool InitializeResData(string file) { //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) string[] array = file.Split(","); if (array != null && array.Length == 9) { try { Res_Data value = default(Res_Data); value.rundown_name = array[0]; value.tag_name = array[1]; value.persistentID = uint.Parse(array[2], CultureInfo.InvariantCulture); if (!RES_BNK.ContainsKey(value.persistentID)) { value.default_name = array[3]; value.ammoType = Math.Clamp(int.Parse(array[4], CultureInfo.InvariantCulture), 0, 100); value.fade_dis = Math.Clamp(int.Parse(array[5], CultureInfo.InvariantCulture), 1, 59); value.color = new Color(float.Parse(array[6], CultureInfo.InvariantCulture.NumberFormat), float.Parse(array[7], CultureInfo.InvariantCulture.NumberFormat), float.Parse(array[8], CultureInfo.InvariantCulture.NumberFormat), 1f); value.file_name = file.ToLower(); CreateResConfig(value.rundown_name, value.tag_name, value.default_name, value.ammoType, out var config); value.config_name = config; RES_BNK[value.persistentID] = value; return true; } Logs.Error($"InitializePng duplicate persistentID: {file}"); } catch (Exception ex) { Logs.Error($"InitializePng form error : {file} MSG:{ex.Message}"); } } else { Logs.Error($"InitializePng split failed : {file}"); } return false; } public static void CreateResConfig(string rundown_name, string tag_name, string default_name, int ammoType, out ConfigEntry<string> config) { if (rundown_name == "ResourceHelper") { string text = ((ammoType == 20) ? "ResourceHelper - Resource Pack Name" : "ResourceHelper - Item Name"); tag_name = "Original Resource - " + tag_name; config = EntryPoint.config_path.Bind<string>(text, tag_name, default_name, ""); } else { tag_name = rundown_name + " - " + tag_name; string text2 = "Extra resource from " + rundown_name; config = EntryPoint.config_path.Bind<string>(rundown_name, tag_name, default_name, text2); } } public static void InitializationID(int id) { OBJ[id] = null; COUNT[id] = 0; NAME[id] = ""; PID[id] = 0u; TAR[id] = 0; MAX_DIS[id] = 0f; FORCE_SHOW_TIME[id] = 0f; TIME_CHECK_VALID[id] = 0f; } public static void RemoveID(int id) { OBJ.Remove(id); COUNT.Remove(id); NAME.Remove(id); PID.Remove(id); TAR.Remove(TAR[id]); TAR.Remove(id); MAX_DIS.Remove(id); FORCE_SHOW_TIME.Remove(id); TIME_CHECK_VALID.Remove(id); } public static void ClearDics() { PID.Clear(); TAR.Clear(); PID.Clear(); COUNT.Clear(); OBJ.Clear(); NAME.Clear(); FORCE_SHOW_TIME.Clear(); TIME_CHECK_VALID.Clear(); Res_Moniter.PingList.Clear(); Res_Moniter.PingListNextTime.Clear(); } public static void Do_Man_Scan(PlayerAgent client, bool islocal) { //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_0061: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_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_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) Vector3 position; RaycastHit[] array; if (islocal) { position = client.FPSCamera.Position; array = Il2CppArrayBase<RaycastHit>.op_Implicit((Il2CppArrayBase<RaycastHit>)(object)Physics.SphereCastAll(position, 2f, client.FPSCamera.Forward, 0f, LayerManager.MASK_PLAYER_INTERACT_SPHERE)); } else { position = ((Component)client).transform.position; ((Vector3)(ref position))[1] = ((Vector3)(ref position))[1] + 1f; array = Il2CppArrayBase<RaycastHit>.op_Implicit((Il2CppArrayBase<RaycastHit>)(object)Physics.SphereCastAll(position, 1.5f, ((Component)client).transform.forward, 0.5f, LayerManager.MASK_PLAYER_INTERACT_SPHERE)); } for (int i = 0; i < array.Length; i++) { GameObject gameObject = ((Component)((Component)((RaycastHit)(ref array[i])).collider).transform).gameObject; if (!TAR.ContainsKey(((Object)gameObject).GetInstanceID()) && (Vector3.Distance(gameObject.transform.position, position) < 1.5f || !Physics.Linecast(gameObject.transform.position, position, LayerManager.MASK_WORLD))) { TryAddItem(gameObject); } } } public static bool Do_Pos_Scan(Vector3 pos) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) RaycastHit[] array = Il2CppArrayBase<RaycastHit>.op_Implicit((Il2CppArrayBase<RaycastHit>)(object)Physics.SphereCastAll(pos, 2f, Vector3.up, 0f, LayerManager.MASK_PLAYER_INTERACT_SPHERE)); for (int i = 0; i < array.Length; i++) { GameObject gameObject = ((Component)((Component)((RaycastHit)(ref array[i])).collider).transform).gameObject; if (!TAR.ContainsKey(((Object)gameObject).GetInstanceID()) && (Vector3.Distance(gameObject.transform.position, pos) < 1.5f || !Physics.Linecast(gameObject.transform.position, pos, LayerManager.MASK_WORLD)) && TryAddItem(gameObject)) { return true; } } return false; } public static void GetMarkersAtPos(Vector3 pos) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) RaycastHit[] array = Il2CppArrayBase<RaycastHit>.op_Implicit((Il2CppArrayBase<RaycastHit>)(object)Physics.SphereCastAll(pos, 2f, Vector3.up, 0f, LayerManager.MASK_PLAYER_INTERACT_SPHERE)); int num = 0; for (int i = 0; i < array.Length; i++) { GameObject gameObject = ((Component)((Component)((RaycastHit)(ref array[i])).collider).transform).gameObject; if (TAR.ContainsKey(((Object)gameObject).GetInstanceID())) { num = TAR[((Object)gameObject).GetInstanceID()]; if (num != 0 && MarkUI_Manager.MARKER.ContainsKey(num)) { FORCE_SHOW_TIME[num] = Clock.Time + 15f; } } } } public static bool TryAddItem(GameObject hits) { //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) Interact_Pickup_PickupItem component = hits.GetComponent<Interact_Pickup_PickupItem>(); if ((Object)(object)component == (Object)null) { TAR[((Object)hits).GetInstanceID()] = 0; return false; } if (!((Behaviour)component).enabled) { return false; } int instanceID = ((Object)hits).GetInstanceID(); TAR[instanceID] = 0; LG_PickupItem_Sync componentInParent = hits.GetComponentInParent<LG_PickupItem_Sync>(); if ((Object)(object)componentInParent == (Object)null) { return false; } Item item = componentInParent.item; if ((Object)(object)item == (Object)null) { return false; } uint persistentID = ((GameDataBlockBase<ItemDataBlock>)(object)item.ItemDataBlock).persistentID; if (!RES_BNK.ContainsKey(persistentID)) { return false; } if (!item.ItemDataBlock.canMoveQuick) { return false; } GameObject gameObject = ((Component)componentInParent).gameObject; int instanceID2 = ((Object)gameObject).GetInstanceID(); if (!OBJ.ContainsKey(instanceID2)) { InitializationID(instanceID2); OBJ[instanceID2] = gameObject; PID[instanceID2] = persistentID; MAX_DIS[instanceID2] = RES_BNK[persistentID].fade_dis; COUNT[instanceID2] = Get_ResCount(RES_BNK[persistentID].ammoType, componentInParent.m_stateReplicator.State.custom.ammo); if (COUNT[instanceID2] > 0) { NAME[instanceID2] = RES_BNK[persistentID].config_name.Value + " ×" + COUNT[instanceID2].ToString(CultureInfo.InvariantCulture); } else { NAME[instanceID2] = RES_BNK[persistentID].config_name.Value; } TIME_CHECK_VALID[instanceID2] = Clock.Time + 0.1f; MarkUI_Manager.Create_ResMarker(instanceID2); TAR[instanceID2] = instanceID; TAR[instanceID] = instanceID2; return true; } return false; } public static bool CheckVaild(int id) { //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) GameObject val = OBJ[id]; LG_PickupItem_Sync componentInParent = val.GetComponentInParent<LG_PickupItem_Sync>(); if ((Object)(object)componentInParent == (Object)null) { return false; } uint persistentID = ((GameDataBlockBase<ItemDataBlock>)(object)componentInParent.item.ItemDataBlock).persistentID; if (PID[id] != persistentID) { return false; } if (COUNT[id] != Get_ResCount(RES_BNK[persistentID].ammoType, componentInParent.m_stateReplicator.State.custom.ammo)) { return false; } return true; } public static int Get_ResCount(int ammoPerCount, float ammoBase) { if (ammoPerCount > 0) { return Mathf.FloorToInt(ammoBase / ((float)ammoPerCount * 1f)); } return 0; } } internal static class MarkUI_Manager { public static Dictionary<int, PlaceNavMarkerOnGO> MARKER = new Dictionary<int, PlaceNavMarkerOnGO>(); public static Dictionary<int, bool> VISIBLE = new Dictionary<int, bool>(); public static Dictionary<int, float> START_FADE_TIME = new Dictionary<int, float>(); public static void Create_ResMarker(int id) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown //IL_0089: Unknown result type (might be due to invalid IL or missing references) if (Res_Manager.PID[id] != 0) { PlaceNavMarkerOnGO val = new PlaceNavMarkerOnGO(); val.type = (eMarkerType)3; val.m_nameToShow = Res_Manager.NAME[id]; val.m_marker = PlaceMarker(id, val.m_nameToShow); val.m_marker.SetTitle(val.m_nameToShow); val.m_marker.SetPlayerName(val.m_nameToShow); val.m_marker.SetColor(Res_Manager.RES_BNK[Res_Manager.PID[id]].color); val.SetMarkerVisible(false); MARKER[id] = val; VISIBLE[id] = false; START_FADE_TIME[id] = 0f; SetMarkerIcon(Res_Manager.PID[id], val.m_marker); } } public static NavMarker PlaceMarker(int id, string name) { NavMarker val = GuiManager.NavMarkerLayer.PrepareMarker(Res_Manager.OBJ[id], (GameObject)null); if ((Object)(object)val != (Object)null) { val.SetVisualStates((NavMarkerOption)8388632, (NavMarkerOption)8388632, (NavMarkerOption)0, (NavMarkerOption)0); return val; } return null; } public static void SetMarkerIcon(uint persistentID, NavMarker marker) { string file_name = Res_Manager.RES_BNK[persistentID].file_name; Sprite sprite = null; if (!SpriteManager.TryGetSpriteCache(file_name, 128f, out sprite)) { sprite = SpriteManager.GenerateSprite(file_name); } if ((Object)(object)sprite != (Object)null) { SpriteRenderer componentInChildren = ((Component)marker.m_carryitem).GetComponentInChildren<SpriteRenderer>(); componentInChildren.sprite = sprite; } } public static void DestoryMarker(int id) { if (MARKER.ContainsKey(id)) { if ((Object)(object)MARKER[id].m_marker != (Object)null) { GuiManager.NavMarkerLayer.RemoveMarker(MARKER[id].m_marker); MARKER[id].m_marker = null; } Object.Destroy((Object)(object)MARKER[id]); MARKER.Remove(id); VISIBLE.Remove(id); START_FADE_TIME.Remove(id); } } public static void DestoryMarkerAll() { foreach (KeyValuePair<int, PlaceNavMarkerOnGO> item in MARKER) { if ((Object)(object)item.Value.m_marker != (Object)null) { GuiManager.NavMarkerLayer.RemoveMarker(item.Value.m_marker); item.Value.m_marker = null; } Object.Destroy((Object)(object)item.Value); } MARKER.Clear(); VISIBLE.Clear(); START_FADE_TIME.Clear(); } } public static class MTFOUtil { public const string PLUGIN_GUID = "com.dak.MTFO"; public const BindingFlags PUBLIC_STATIC = BindingFlags.Static | BindingFlags.Public; public static string CustomPath { get; private set; } public static bool IsLoaded { get; private set; } static MTFOUtil() { CustomPath = string.Empty; IsLoaded = false; if (((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("com.dak.MTFO", out var value)) { InitMTFO_V5(value); } } private static void InitMTFO_V5(PluginInfo info) { try { Assembly assembly = ((info == null) ? null : info.Instance?.GetType()?.Assembly) ?? null; if ((object)assembly == null) { throw new Exception("Assembly is Missing!"); } Type[] types = assembly.GetTypes(); Type type = types.First((Type t) => t.Name == "ConfigManager"); if ((object)type == null) { throw new Exception("Unable to Find ConfigManager Class"); } FieldInfo field = type.GetField("CustomPath", BindingFlags.Static | BindingFlags.Public); if ((object)field == null) { throw new Exception("Unable to Find Field: CustomPath"); } CustomPath = (string)field.GetValue(null); IsLoaded = true; } catch (Exception value) { Logs.Error($"Exception thrown while reading metadata from MTFO (V{info.Metadata.Version}): \n{value}"); } } }
plugins/net6/MTFO.dll
Decompiled a month agousing System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.Encodings.Web; using System.Text.Json; using System.Text.Json.Nodes; using System.Text.Json.Serialization; using AK; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using BepInEx.Unity.IL2CPP.Hook; using CellMenu; using ChainedPuzzles; using GTFO.API; using GameData; using GameEvent; using Gear; using Globals; using HarmonyLib; using Il2CppInterop.Runtime; using Il2CppInterop.Runtime.Injection; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.InteropTypes.Arrays; using Il2CppInterop.Runtime.InteropTypes.Fields; using Il2CppInterop.Runtime.Runtime; using Il2CppInterop.Runtime.Runtime.VersionSpecific.Class; using Il2CppSystem; using Il2CppSystem.Collections.Generic; using MTFO.API; using MTFO.Custom; using MTFO.Custom.CCP.Components; using MTFO.CustomCP; using MTFO.HotReload; using MTFO.Managers; using MTFO.NativeDetours; using MTFO.Utilities; using Player; using SNetwork; using Steamworks; using TMPro; using UnityEngine; using UnityEngine.Analytics; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")] [assembly: AssemblyCompany("MTFO")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyCopyright("© dakkhuza 2021")] [assembly: AssemblyFileVersion("4.6.1")] [assembly: AssemblyInformationalVersion("4.6.1+gitf831086-dirty-main")] [assembly: AssemblyProduct("MTFO")] [assembly: AssemblyTitle("MTFO")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("4.6.1.0")] [module: UnverifiableCode] namespace MTFO { [GeneratedCode("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0")] [DebuggerNonUserCode] [CompilerGenerated] internal class ConfigStrings { private static ResourceManager resourceMan; private static CultureInfo resourceCulture; [EditorBrowsable(EditorBrowsableState.Advanced)] internal static ResourceManager ResourceManager { get { if (resourceMan == null) { resourceMan = new ResourceManager("MTFO.ConfigStrings", typeof(ConfigStrings).Assembly); } return resourceMan; } } [EditorBrowsable(EditorBrowsableState.Advanced)] internal static CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } internal static string SECTION_DEBUG => ResourceManager.GetString("SECTION_DEBUG", resourceCulture); internal static string SECTION_DEV => ResourceManager.GetString("SECTION_DEV", resourceCulture); internal static string SECTION_GENERAL => ResourceManager.GetString("SECTION_GENERAL", resourceCulture); internal static string SETTING_DISABLE_ACHIEVEMENTS => ResourceManager.GetString("SETTING_DISABLE_ACHIEVEMENTS", resourceCulture); internal static string SETTING_DISABLE_ACHIEVEMENTS_DESC => ResourceManager.GetString("SETTING_DISABLE_ACHIEVEMENTS_DESC", resourceCulture); internal static string SETTING_DUMPDATA => ResourceManager.GetString("SETTING_DUMPDATA", resourceCulture); internal static string SETTING_DUMPDATA_DESC => ResourceManager.GetString("SETTING_DUMPDATA_DESC", resourceCulture); internal static string SETTING_DUMPDATA_MODE => ResourceManager.GetString("SETTING_DUMPDATA_MODE", resourceCulture); internal static string SETTING_DUMPDATA_MODE_DESC => ResourceManager.GetString("SETTING_DUMPDATA_MODE_DESC", resourceCulture); internal static string SETTING_HOTRELOAD => ResourceManager.GetString("SETTING_HOTRELOAD", resourceCulture); internal static string SETTING_HOTRELOAD_DESC => ResourceManager.GetString("SETTING_HOTRELOAD_DESC", resourceCulture); internal static string SETTING_RUNDOWNPACKAGE => ResourceManager.GetString("SETTING_RUNDOWNPACKAGE", resourceCulture); internal static string SETTING_RUNDOWNPACKAGE_DESC => ResourceManager.GetString("SETTING_RUNDOWNPACKAGE_DESC", resourceCulture); internal static string SETTING_USE_LEGACY_PATH => ResourceManager.GetString("SETTING_USE_LEGACY_PATH", resourceCulture); internal static string SETTING_USE_LEGACY_PATH_DESC => ResourceManager.GetString("SETTING_USE_LEGACY_PATH_DESC", resourceCulture); internal static string SETTING_VERBOSE => ResourceManager.GetString("SETTING_VERBOSE", resourceCulture); internal static string SETTING_VERBOSE_DESC => ResourceManager.GetString("SETTING_VERBOSE_DESC", resourceCulture); internal ConfigStrings() { } } [BepInPlugin("com.dak.MTFO", "MTFO", "4.6.1+gitf831086-dirty-main")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class MTFO : BasePlugin { public const string MODNAME = "MTFO"; public const string AUTHOR = "dak"; public const string GUID = "com.dak.MTFO"; public const string VERSION = "4.6.1+gitf831086-dirty-main"; public override void Load() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown Analytics.enabled = false; Harmony harmony = new Harmony("com.dak.MTFO"); AssetAPI.OnImplReady += delegate { if (ConfigManager.IsHotReloadEnabled) { ClassInjector.RegisterTypeInIl2Cpp<HotReloader>(); harmony.PatchAll(typeof(HotReloadInjector)); } }; harmony.PatchAll(); Detour_DataBlockBase.Patch(); } } public static class DataDumperExtensions { public static int GetStableHashCode(this string str) { int num = 5381; int num2 = num; for (int i = 0; i < str.Length && str[i] != 0; i += 2) { num = ((num << 5) + num) ^ str[i]; if (i == str.Length - 1 || str[i + 1] == '\0') { break; } num2 = ((num2 << 5) + num2) ^ str[i + 1]; } return num + num2 * 1566083941; } } public static class JsonNodeExtension { private static JsonDocumentOptions _JsonDocumentOptions = new JsonDocumentOptions { AllowTrailingCommas = true, CommentHandling = JsonCommentHandling.Skip }; private static readonly JsonSerializerOptions _JsonSerializerOptions = new JsonSerializerOptions { AllowTrailingCommas = true, ReadCommentHandling = JsonCommentHandling.Skip, WriteIndented = true, Encoder = JavaScriptEncoder.UnsafeRelaxedJsonEscaping }; public static string ToJsonStringIndented(this JsonNode jsonNode) { return jsonNode.ToJsonString(_JsonSerializerOptions); } public static bool TryParseToJsonNode(this string json, out JsonNode jsonNode) { try { jsonNode = json.ToJsonNode(); return jsonNode != null; } catch { jsonNode = null; return false; } } public static bool TryParseJsonNode(this Stream stream, bool dispose, out JsonNode jsonNode) { try { jsonNode = stream.ToJsonNode(); return jsonNode != null; } catch { jsonNode = null; return false; } finally { if (dispose) { stream.Close(); } } } public static JsonNode ToJsonNode(this string json) { return JsonNode.Parse(json, null, _JsonDocumentOptions); } public static JsonNode ToJsonNode(this Stream jsonStream) { return JsonNode.Parse(jsonStream, null, _JsonDocumentOptions); } public static bool TryAddJsonItem(this JsonArray jsonArray, string json) { try { if (jsonArray == null) { throw new Exception(); } if (string.IsNullOrWhiteSpace(json)) { throw new Exception(); } if (!json.TryParseToJsonNode(out var jsonNode)) { throw new Exception(); } jsonArray.Add(jsonNode); return true; } catch { return false; } } } [GeneratedCode("VersionInfoGenerator", "2.0.0+git50a4b1a-master")] [CompilerGenerated] internal static class VersionInfo { public const string RootNamespace = "MTFO"; public const string Version = "4.6.1"; public const string VersionPrerelease = null; public const string VersionMetadata = "gitf831086-dirty-main"; public const string SemVer = "4.6.1+gitf831086-dirty-main"; public const string GitRevShort = "f831086-dirty"; public const string GitRevLong = "f831086f4f6e1b696d810fe24edc29e810e53735-dirty"; public const string GitBranch = "main"; public const string GitTag = "v4.3.0"; public const bool GitIsDirty = true; } } namespace MTFO.Utilities { public class JsonSerializer { public JsonSerializerOptions Options; public JsonSerializer() { Options = new JsonSerializerOptions { AllowTrailingCommas = true, IncludeFields = true, PropertyNameCaseInsensitive = true, ReadCommentHandling = JsonCommentHandling.Skip, WriteIndented = true }; Options.Converters.Add(new JsonStringEnumConverter()); } public JsonSerializer(bool allowTrailingCommas = true, bool includeFields = true, bool propertyNameCaseInsensitive = true, bool writeIndented = true) { Options = new JsonSerializerOptions { AllowTrailingCommas = allowTrailingCommas, IncludeFields = includeFields, PropertyNameCaseInsensitive = propertyNameCaseInsensitive, ReadCommentHandling = JsonCommentHandling.Skip, WriteIndented = writeIndented }; Options.Converters.Add(new JsonStringEnumConverter()); } public void TryRead<T>(string path, out T output) where T : new() { if (File.Exists(path)) { string json = File.ReadAllText(path); output = Deserialize<T>(json); } else { output = new T(); string json = Serialize(output); File.WriteAllText(path, json); } } public string Serialize(object value) { return System.Text.Json.JsonSerializer.Serialize(value, Options); } public T Deserialize<T>(string json) { return System.Text.Json.JsonSerializer.Deserialize<T>(json, Options); } } public static class Log { private static readonly ManualLogSource logger; static Log() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Expected O, but got Unknown logger = new ManualLogSource("MTFO"); Logger.Sources.Add((ILogSource)(object)logger); } public static void Verbose(object msg) { if (ConfigManager.IsVerbose) { logger.LogInfo(msg); } } public static void Debug(object msg) { logger.LogDebug(msg); } public static void Message(object msg) { logger.LogMessage(msg); } public static void Error(object msg) { logger.LogError(msg); } public static void Warn(object msg) { logger.LogWarning(msg); } } public enum BaseDirectory { BepInEx, Plugins, GameData } public static class PathUtil { public static string Prepare(BaseDirectory baseDir, params string[] subDirs) { string text = baseDir switch { BaseDirectory.BepInEx => Paths.BepInExRootPath, BaseDirectory.Plugins => Paths.PluginPath, BaseDirectory.GameData => Path.Combine(Paths.BepInExRootPath, "GameData"), _ => throw new ArgumentOutOfRangeException("baseDir", $"{baseDir} is not a valid value for Argument: {"baseDir"}"), }; string obj = ((subDirs == null || subDirs.Length == 0) ? text : Path.Combine(text, Path.Combine(subDirs))); Directory.CreateDirectory(obj); return obj; } public static bool CheckCustomFile(string file, out string CombinedPath) { CombinedPath = Path.Combine(ConfigManager.CustomPath, file); if (File.Exists(CombinedPath)) { return true; } return false; } public static bool CheckFile(string pathToFile) { if (File.Exists(pathToFile)) { return true; } return false; } [Obsolete] public static string MakeRelativeDirectory(string path, bool createPath = true) { string text = Path.Combine(Path.Combine(Paths.ConfigPath, "Rundowns"), path); if (createPath && !Directory.Exists(text)) { Directory.CreateDirectory(text); } return text; } public static string MakeRelativeDirectory(string path, string folder) { string text = Path.Combine(path, folder); if (!Directory.Exists(text)) { Directory.CreateDirectory(text); } return text; } public static void PrepareEmptyDirectory(string path) { if (Directory.Exists(path)) { Directory.Delete(path, recursive: true); } Directory.CreateDirectory(path); } public static Stream OpenUtf8Stream(string filePath) { return new StreamReader(filePath, Encoding.UTF8).BaseStream; } } } namespace MTFO.Patches { [HarmonyPatch(typeof(SteamUserStats), "SetAchievement")] internal static class Patch_SteamAPI_Achievement { private static bool Prefix(string pchName) { if (!ConfigManager.DisableAchievements) { return true; } Log.Error("Achievement Completion Blocked: " + pchName); return false; } } [HarmonyPatch(typeof(AnalyticsManager), "OnGameEvent", new Type[] { typeof(GameEventData) })] internal static class Patch_Analytics { public static bool Prefix(GameEventData data) { return false; } } [HarmonyPatch(typeof(SNet_Core_STEAM), "SetFriendsData", new Type[] { typeof(FriendsDataType), typeof(string) })] internal static class Patch_RichPresence2 { public static void Prefix(FriendsDataType type, ref string data, SNet_Core_STEAM __instance) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 //IL_003a: Unknown result type (might be due to invalid IL or missing references) if ((int)type != 1) { if ((int)type == 9) { data = "0"; return; } Log.Verbose($"Lobby data\nType: {type} Data: {data}"); } else { data = "MODDED - " + data; } } } [HarmonyPatch(typeof(GlowstickInstance), "Update")] internal static class Patch_Glowstick { public static void Postfix(GlowstickInstance __instance) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Invalid comparison between Unknown and I4 //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Invalid comparison between Unknown and I4 //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) if (ConfigManager.HasCustomContent && ConfigManager.CustomContent.GlowstickHolder != null && !((Object)(object)__instance == (Object)null) && (int)__instance.m_state != 3 && (int)__instance.m_state != 4 && ConfigManager.CustomContent.GlowstickHolder.GlowstickLookup.TryGetValue(((Item)__instance).PublicName, out var value) && (Object)(object)__instance.m_light != (Object)null) { ((LightBase)__instance.m_light).Range = value.Range; ((LightBase)__instance.m_light).Color = value.Color * __instance.m_progression; ((LightBase)__instance.m_light).UpdateVisibility(true); } } } [HarmonyPatch(typeof(CP_Holopath_Spline), "Reveal")] internal static class Patch_InstantRevealPuzzlePath { public static bool Prefix(CP_Holopath_Spline __instance) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) if (__instance.m_revealSpeed < 0f) { if (!__instance.m_isSetup) { return false; } __instance.SetSplineProgress(1f); __instance.SetVisible(true); __instance.m_sound.UpdatePosition(__instance.TipPos); if (!__instance.m_didSetColor) { __instance.m_didSetColor = __instance.TrySetColor(); } __instance.m_sound.Post(EVENTS.BIOSCAN_TUBE_EMITTER_STOP, true); Action onRevealDone = __instance.OnRevealDone; if (onRevealDone != null) { onRevealDone.Invoke(); } return false; } return true; } } [HarmonyPatch(typeof(CM_PageLoadout), "UpdatePageData")] internal static class Patch_PageLoadoutUpdatePageData { public static void Prefix(CM_PageLoadout __instance) { ((TMP_Text)((Component)((Transform)((CM_PageBase)__instance).m_movingContentHolder).Find("ShareServerId/ShareText")).gameObject.GetComponent<TextMeshPro>()).SetText("<color=red><b>Do not play modded content on the official GTFO server or online matchmake lobbies.</b></color>\n\nFeel free to join the unofficial discord server linked below and ask people to play.", true); __instance.m_discordButton.SetText("Mod Server"); __instance.m_discordButton.OnBtnPressCallback = Action<int>.op_Implicit((Action<int>)delegate { Application.OpenURL("https://discord.com/invite/rRMPtv4FAh"); }); } } [HarmonyPatch(typeof(CM_PageLoadout), "UpdatePlayerBars")] internal static class Patch_PageLoadoutUpdatePlayerBars { public static void Prefix(CM_PageLoadout __instance) { foreach (CM_PlayerLobbyBar item in (Il2CppArrayBase<CM_PlayerLobbyBar>)(object)__instance.m_playerLobbyBars) { item.m_matchmakeButton.SetOnBtnPressCallback((Action<int>)null); item.m_matchmakeButton.SetText("DISABLED"); } } } [HarmonyPatch(typeof(CM_PageRundown_New), "Intro_RevealRundown")] internal static class Patch_PageRundownNew { public static void Postfix(CM_PageRundown_New __instance) { __instance.m_discordButton.SetText("MOD SERVER"); __instance.m_discordButton.OnBtnPressCallback = Action<int>.op_Implicit((Action<int>)delegate { Application.OpenURL("https://discord.com/invite/rRMPtv4FAh"); }); ((RectTransformComp)__instance.m_matchmakeAllButton).SetVisible(false); __instance.m_matchmakeAllButton.SetText("MATCHMAKE DISABLED"); __instance.m_matchmakeAllButton.OnBtnPressCallback = null; __instance.m_aboutTheRundownButton.SetText("THUNDERSTORE"); __instance.m_aboutTheRundownButton.OnBtnPressCallback = Action<int>.op_Implicit((Action<int>)delegate { Application.OpenURL("https://gtfo.thunderstore.io/"); }); } } [HarmonyPatch(typeof(CM_PageRundown_New), "PlaceRundown")] internal static class Patch_RundownTierMarker { public static void Postfix(CM_PageRundown_New __instance) { ContentManager customContent = ConfigManager.CustomContent; if (customContent != null) { __instance.m_tierMarker1.m_name = customContent.TierNames.Tier1; __instance.m_tierMarker2.m_name = customContent.TierNames.Tier2; __instance.m_tierMarker3.m_name = customContent.TierNames.Tier3; __instance.m_tierMarker4.m_name = customContent.TierNames.Tier4; __instance.m_tierMarker5.m_name = customContent.TierNames.Tier5; __instance.m_tierMarker1.UpdateHeader(); __instance.m_tierMarker2.UpdateHeader(); __instance.m_tierMarker3.UpdateHeader(); __instance.m_tierMarker4.UpdateHeader(); __instance.m_tierMarker5.UpdateHeader(); } } } [HarmonyPatch(typeof(PUI_Watermark), "UpdateWatermark")] internal static class Patch_WatermarkUpdateWatermark { public static void Postfix(PUI_Watermark __instance) { ((TMP_Text)__instance.m_watermarkText).SetText("<color=red>MODDED</color> <color=orange>4.6.1</color>", true); } } } namespace MTFO.NativeDetours { internal class DataBlockBaseWrapper { private static readonly HashSet<string> _PreferPartialDumpBlocks = new HashSet<string> { "RundownDataBlock".ToLower(), "LightSettingsDataBlock".ToLower(), "FogSettingsDataBlock".ToLower(), "LevelLayoutDataBlock".ToLower(), "WardenObjectiveDataBlock".ToLower(), "DimensionDataBlock".ToLower(), "EnemyDataBlock".ToLower(), "EnemySFXDataBlock".ToLower(), "EnemyBehaviorDataBlock".ToLower(), "EnemyBalancingDataBlock".ToLower(), "EnemyMovementDataBlock".ToLower(), "ArchetypeDataBlock".ToLower(), "PlayerOfflineGearDataBlock".ToLower(), "ComplexResourceSetDataBlock".ToLower(), "TextDataBlock".ToLower() }; private IntPtr Ptr__m_fileNameNoExt; public IntPtr ClassPointer { get; private set; } public string FileName { get; private set; } public string BinaryFileName { get; private set; } public bool PreferPartialBlockOnDump { get; private set; } public unsafe DataBlockBaseWrapper(Il2CppMethodInfo* methodInfo) { INativeClassStruct val = UnityVersionHandler.Wrap(UnityVersionHandler.Wrap(methodInfo).Class); ClassPointer = ((INativeStruct)val).Pointer; Ptr__m_fileNameNoExt = IL2CPP.GetIl2CppField(((INativeStruct)val).Pointer, "m_fileNameNoExt"); IntPtr zero = IntPtr.Zero; IL2CPP.il2cpp_field_static_get_value(Ptr__m_fileNameNoExt, (void*)(&zero)); FileName = IL2CPP.Il2CppStringToManaged(zero).Replace('.', '_'); BinaryFileName = FileName + "_bin"; if (_PreferPartialDumpBlocks.Contains(FileName.ToLower().Replace("gamedata_", ""))) { PreferPartialBlockOnDump = true; } } } internal static class Detour_DataBlockBase { private unsafe delegate IntPtr GetFileContentsDel(Il2CppMethodInfo* methodInfo); private static string _BasePathToDump; private static INativeDetour _Detour; private static GetFileContentsDel _Original; public unsafe static void Patch() { _BasePathToDump = Path.Combine(Paths.BepInExRootPath, "GameData-Dump", CellBuildData.GetRevision().ToString()); if (ConfigManager.DumpGameData) { PathUtil.PrepareEmptyDirectory(_BasePathToDump); } _Detour = INativeDetour.CreateAndApply<GetFileContentsDel>((IntPtr)(nint)Il2CppAPI.GetIl2CppMethod<GameDataBlockBase<EnemyDataBlock>>("GetFileContents", typeof(string).FullName, false, Array.Empty<string>()), (GetFileContentsDel)Dtor_GetFileContents, ref _Original); } private unsafe static IntPtr Dtor_GetFileContents(Il2CppMethodInfo* methodInfo) { IntPtr intPtr = _Original(methodInfo); try { DataBlockBaseWrapper dataBlockBaseWrapper = new DataBlockBaseWrapper(methodInfo); string binaryFileName = dataBlockBaseWrapper.BinaryFileName; _ = binaryFileName + ".json"; if (ConfigManager.DumpGameData) { DumpContent(dataBlockBaseWrapper, IL2CPP.Il2CppStringToManaged(intPtr)); } Log.Verbose("GetFileContents Call of " + binaryFileName); Stream contentStream = GetContentStream(dataBlockBaseWrapper, intPtr); JsonNode jsonNode = contentStream.ToJsonNode(); JsonArray jsonArray = jsonNode["Blocks"].AsArray(); string path = Path.Combine(ConfigManager.GameDataPath, dataBlockBaseWrapper.FileName); if (Directory.Exists(path)) { int num = 0; string[] files = Directory.GetFiles(path, "*.json"); foreach (string text in files) { Log.Verbose(" - Trying to add PartialData [" + text + "]"); if (File.Exists(text) && PathUtil.OpenUtf8Stream(text).TryParseJsonNode(dispose: true, out var jsonNode2)) { jsonArray.Add(jsonNode2); num++; } } Log.Verbose($" - Added {num} partial data of {binaryFileName}"); } List<string> jsonItemsToInject = new List<string>(); MTFOGameDataAPI.Invoke_OnGameDataContentLoad(dataBlockBaseWrapper.FileName, contentStream, in jsonItemsToInject); foreach (string item2 in jsonItemsToInject) { try { JsonNode item = item2.ToJsonNode(); jsonArray.Add(item); } catch (Exception ex) { Log.Error("Exception were found while reading Injected Json Data!"); Log.Error(ex.ToString()); Log.Error("Full Json:\n" + item2); } } uint num2 = 0u; foreach (JsonNode item3 in jsonNode["Blocks"].AsArray()) { uint num3 = (uint)(JsonNode)item3["persistentID"].AsValue(); if (num3 > num2) { num2 = num3; } } jsonNode["LastPersistentID"] = num2; string text2 = jsonNode.ToJsonStringIndented(); IntPtr result = IL2CPP.ManagedStringToIl2Cpp(text2); MTFOGameDataAPI.Invoke_OnGameDataContentLoaded(dataBlockBaseWrapper.FileName, text2); return result; } catch (Exception ex2) { Log.Error("Exception were found while handling Detour;Falling back to original content!"); Log.Error(ex2.ToString()); return intPtr; } } private static Stream GetContentStream(DataBlockBaseWrapper datablock, IntPtr originalContentPtr) { string binaryFileName = datablock.BinaryFileName; string path = binaryFileName + ".json"; string s = IL2CPP.Il2CppStringToManaged(originalContentPtr); string text = Path.Combine(ConfigManager.GameDataPath, path); if (File.Exists(text)) { Log.Verbose("Opening filestream of [" + binaryFileName + "] from disk..."); Log.Verbose(text); return PathUtil.OpenUtf8Stream(text); } Log.Verbose("No file found at [" + binaryFileName + "]"); return new MemoryStream(Encoding.UTF8.GetBytes(s)); } private static void DumpContent(DataBlockBaseWrapper datablock, string json) { if (!json.TryParseToJsonNode(out var jsonNode)) { Log.Verbose("Unable to dump " + datablock.FileName + ", Invalid Json Content!"); return; } bool flag = false; switch (ConfigManager.DumpMode) { case DumpGameDataMode.Single: flag = false; break; case DumpGameDataMode.PartialData: flag = datablock.PreferPartialBlockOnDump; break; case DumpGameDataMode.FullPartialData: flag = true; break; } if (flag) { JsonArray jsonArray = jsonNode["Blocks"].AsArray(); string text = Path.Combine(path2: datablock.FileName, path1: _BasePathToDump); PathUtil.PrepareEmptyDirectory(text); foreach (JsonNode item in jsonArray) { string path = $"{item["persistentID"]}__{item["name"]}.json"; string text2 = Path.Combine(text, path); File.WriteAllText(text2, item.ToJsonStringIndented()); Log.Verbose(" - Save... " + text2); } jsonNode["Blocks"] = new JsonArray(); } string path2 = datablock.BinaryFileName + ".json"; File.WriteAllText(Path.Combine(_BasePathToDump, path2), jsonNode.ToJsonStringIndented()); Log.Verbose(datablock.FileName + " has dumped to '" + _BasePathToDump + "'"); } } } namespace MTFO.Managers { public enum DumpGameDataMode { Single, PartialData, FullPartialData } public static class ConfigManager { private const string CUSTOM_FOLDER = "Custom"; private static readonly ConfigEntry<bool> _enableHotReload; private static readonly ConfigEntry<bool> _dumpGameData; private static readonly ConfigEntry<bool> _isVerbose; private static readonly ConfigEntry<DumpGameDataMode> _dumpGameDataMode; private static readonly ConfigEntry<bool> _disableAchievements; public static int GAME_VERSION; public static ContentManager CustomContent; public static readonly string GameDataPath; public static readonly string CustomPath; public static bool HasGameDataPath; public static bool HasCustomContent; public static bool IsModded; public static bool IsPluginGameDataPath; public static bool IsVerbose => _isVerbose.Value; public static bool DisableAchievements => _disableAchievements.Value; public static bool IsHotReloadEnabled => _enableHotReload.Value; public static bool DumpGameData => _dumpGameData.Value; public static DumpGameDataMode DumpMode => _dumpGameDataMode.Value; private static string ResolveGameDataPath(string rootPath) { foreach (string item in Directory.GetFiles(rootPath, "GameData_*.json", SearchOption.AllDirectories).OrderBy(Path.GetDirectoryName)) { if (Path.GetDirectoryName(item) != GameDataPath) { HasGameDataPath = true; return Path.GetDirectoryName(item); } } return null; } static ConfigManager() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0030: 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_0066: Unknown result type (might be due to invalid IL or missing references) ConfigFile val = new ConfigFile(Path.Combine(Paths.ConfigPath, "MTFO.cfg"), true); _enableHotReload = val.Bind<bool>(ConfigStrings.SECTION_DEV, ConfigStrings.SETTING_HOTRELOAD, false, ConfigStrings.SETTING_HOTRELOAD_DESC); _dumpGameData = val.Bind<bool>(ConfigStrings.SECTION_DEV, ConfigStrings.SETTING_DUMPDATA, false, ConfigStrings.SETTING_DUMPDATA_DESC); _dumpGameDataMode = val.Bind<DumpGameDataMode>(ConfigStrings.SECTION_DEV, ConfigStrings.SETTING_DUMPDATA_MODE, DumpGameDataMode.Single, ConfigStrings.SETTING_DUMPDATA_MODE_DESC); _isVerbose = val.Bind<bool>(ConfigStrings.SECTION_DEBUG, ConfigStrings.SETTING_VERBOSE, false, ConfigStrings.SETTING_VERBOSE_DESC); _disableAchievements = val.Bind<bool>(ConfigStrings.SECTION_GENERAL, ConfigStrings.SETTING_DISABLE_ACHIEVEMENTS, true, ConfigStrings.SETTING_DISABLE_ACHIEVEMENTS_DESC); GAME_VERSION = GetGameVersion(); GameDataPath = ResolveGameDataPath(PathUtil.Prepare(BaseDirectory.GameData)); IsPluginGameDataPath = string.IsNullOrEmpty(GameDataPath); if (IsPluginGameDataPath) { GameDataPath = ResolveGameDataPath(Paths.PluginPath); Log.Warn("Plugin paths for gamedata are under legacy support and will be removed in the future. Considering migrating to the '\\BepInEx\\GameData' folder."); } if (HasGameDataPath) { CustomPath = Path.Combine(GameDataPath, "Custom"); HasCustomContent = Directory.Exists(CustomPath); } else { GameDataPath = string.Empty; CustomPath = string.Empty; HasCustomContent = false; IsPluginGameDataPath = false; } try { CustomContent = new ContentManager(); } catch (Exception value) { HasCustomContent = false; Log.Error($"Failed to init custom content!\nIs your JSON valid?\n---- ERROR MESSAGE ---- {value} ---- END ERROR MESSAGE ----"); } Log.Debug("---- DEBUG INFO ----"); Log.Debug($"Time: {DateTime.Now}"); Log.Debug($"Game Version: {GAME_VERSION}"); Log.Debug("---- PATHS ----"); Log.Debug("Path to rundown: " + GameDataPath); Log.Debug("Path to custom content: " + CustomPath); Log.Debug("---- FLAGS ----"); Log.Debug($"Has GameData Path? {HasGameDataPath}"); Log.Debug($"Using plugin GameData path? {IsPluginGameDataPath}"); Log.Debug($"Has Custom Content? {HasCustomContent}"); Log.Debug($"Hot Reload Enabled? {IsHotReloadEnabled}"); Log.Debug($"Verbose Logging? {IsVerbose}"); Log.Debug($"Dump Game Data? {DumpGameData}"); Log.Debug($"Are Achievements Disabled? {DisableAchievements}"); Log.Debug("---- DEBUG END ----"); } private static int GetGameVersion() { return CellBuildData.GetRevision(); } } public class ContentManager { private readonly global::MTFO.Utilities.JsonSerializer json = new global::MTFO.Utilities.JsonSerializer(); private readonly Dictionary<string, Action<string>> Handlers; public ScanHolder ScanHolder; public GlowstickHolder GlowstickHolder; public TierNames TierNames; public ContentManager() { Handlers = new Dictionary<string, Action<string>> { { "puzzletypes.json", SetupChainedPuzzles }, { "glowsticks.json", SetupGlowsticks }, { "tiernames.json", SetupTierNames } }; Init(); } private void Init() { if (!ConfigManager.HasCustomContent) { return; } foreach (string key in Handlers.Keys) { if (PathUtil.CheckCustomFile(key, out var CombinedPath)) { Handlers.TryGetValue(key, out var value); try { value?.Invoke(CombinedPath); } catch (Exception msg) { Log.Error(msg); } Log.Debug(CombinedPath); } } } public void SetupChainedPuzzles(string path) { Log.Debug("Custom puzzles found"); ScanHolder = json.Deserialize<ScanHolder>(File.ReadAllText(path)); } public void SetupGlowsticks(string path) { Log.Debug("Custom glowsticks found"); GlowstickHolder = json.Deserialize<GlowstickHolder>(File.ReadAllText(path)); GlowstickHolder.Setup(); } public void SetupTierNames(string path) { TierNames = json.Deserialize<TierNames>(File.ReadAllText(path)); } } } namespace MTFO.HotReload { internal class HotGameDataManager : IHotManager { public void OnHotReload(int id) { GameDataInit.ReInitialize(); Log.Verbose("Reinitialized GameData"); } } internal class HotGearManager : IHotManager { private readonly int gearSlotsTotal = 3; public void OnHotReload(int id) { GearManager.Current.m_offlineSetupDone = false; CleanGearIcons(); CleanGearSlots(); GearManager.Current.SetupGearContainers(); LoadOfflineGearDatas(); GearManager.GenerateAllGearIcons(); GearManager.Current.m_offlineSetupDone = true; Log.Verbose("Reloaded Gear"); } private void CleanGearIcons() { GearManager.m_allGearWithPostedIconJobs.Clear(); foreach (Dictionary<uint, RenderTexture> item in (Il2CppArrayBase<Dictionary<uint, RenderTexture>>)(object)GearManager.Current.m_allGearIconTexturesPerInstanceKey) { item.Clear(); } } [Obsolete] private void CleanGearLobbySlots() { if (!((Object)(object)CM_PageLoadout.Current != (Object)null)) { return; } foreach (CM_InventorySlotItem componentsInChild in ((Component)CM_PageLoadout.Current.m_popupAlign).gameObject.GetComponentsInChildren<CM_InventorySlotItem>(true)) { Object.Destroy((Object)(object)((Component)componentsInChild).gameObject); } } private void CleanGearSlots() { for (int i = 0; i < gearSlotsTotal; i++) { ((Il2CppArrayBase<List<GearIDRange>>)(object)GearManager.Current.m_gearPerSlot)[i].Clear(); } } private void LoadOfflineGearDatas() { Il2CppArrayBase<PlayerOfflineGearDataBlock> allBlocks = GameDataBlockBase<PlayerOfflineGearDataBlock>.GetAllBlocks(); if (allBlocks == null) { Log.Warn("Unable to get Player Offline Gear blocks"); return; } Log.Verbose($"Loading {allBlocks.Length} gear"); foreach (PlayerOfflineGearDataBlock item in allBlocks) { OfflineGear.Load(item); } } } public class HotReloader : MonoBehaviour { public static HotReloader Current; private CM_Item button; private readonly string buttonLabel = "Reload Game Data"; private readonly Vector3 buttonPosition = new Vector3(0f, 77f, 0f); private readonly List<IHotManager> managers = new List<IHotManager>(); public HotReloader(IntPtr intPtr) : base(intPtr) { }//IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) private void Awake() { //IL_000c: Unknown result type (might be due to invalid IL or missing references) ((Component)this).gameObject.transform.localPosition = buttonPosition; button = ((Component)this).gameObject.GetComponent<CM_Item>(); button.SetText(buttonLabel); AddOnReloadListener(new HotGameDataManager()); AddOnReloadListener(new HotRundownManager()); AddOnReloadListener(new HotGearManager()); button.OnBtnPressCallback += Action<int>.op_Implicit((Action<int>)delegate { MTFOHotReloadAPI.HotReloaded(); }); } public void AddOnReloadListener(IHotManager manager) { if (!managers.Contains(manager)) { button.OnBtnPressCallback += Action<int>.op_Implicit((Action<int>)manager.OnHotReload); managers.Add(manager); } } public void RemoveOnReloadListener(IHotManager manager) { if (managers.Contains(manager)) { button.OnBtnPressCallback -= Action<int>.op_Implicit((Action<int>)manager.OnHotReload); managers.Remove(manager); } } public static void Setup() { if (!((Object)(object)Current != (Object)null) && !((Object)(object)MainMenuGuiLayer.Current.PageRundownNew == (Object)null)) { GameObject obj = Object.Instantiate<GameObject>(((Component)MainMenuGuiLayer.Current.PageRundownNew.m_discordButton).gameObject, ((Component)MainMenuGuiLayer.Current.PageRundownNew.m_discordButton).transform.parent, false); ((Object)obj).name = "Button HotReload"; Current = obj.AddComponent<HotReloader>(); obj.SetActive(true); Log.Verbose("Created hot reload button"); } } } public class HotReloadInjector { [HarmonyPostfix] [HarmonyPatch(typeof(CM_PageRundown_New), "OnEnable")] public static void OnEnable() { HotReloader.Setup(); } } internal class HotRundownManager : IHotManager { private CM_PageRundown_New rundownPage; private bool hasValidRundown => GameDataBlockBase<RundownDataBlock>.s_blockByID.ContainsKey(Global.RundownIdToLoad); private RundownDataBlock rundownDataCurrent => GameDataBlockBase<RundownDataBlock>.GetBlock(Global.RundownIdToLoad); public HotRundownManager() { rundownPage = MainMenuGuiLayer.Current.PageRundownNew; } public void OnHotReload(int id) { if (hasValidRundown) { rundownPage.m_dataIsSetup = false; CleanIconsOfTier(); TryPlaceRundown(); } else { Log.Warn($"Failed to place the rundown due to missing Rundown id {Global.RundownIdToLoad}"); } Log.Verbose("Reloaded Rundown"); } private void CleanIconsOfTier() { CleanIconsOfTier(rundownPage.m_expIconsTier1); CleanIconsOfTier(rundownPage.m_expIconsTier2); CleanIconsOfTier(rundownPage.m_expIconsTier3); CleanIconsOfTier(rundownPage.m_expIconsTier4); CleanIconsOfTier(rundownPage.m_expIconsTier5); } private void CleanIconsOfTier(List<CM_ExpeditionIcon_New> tier) { Enumerator<CM_ExpeditionIcon_New> enumerator = tier.GetEnumerator(); while (enumerator.MoveNext()) { Object.Destroy((Object)(object)((Component)enumerator.Current).gameObject); } } private void TryPlaceRundown() { rundownPage.m_currentRundownData = rundownDataCurrent; if (rundownPage.m_currentRundownData != null) { rundownPage.PlaceRundown(rundownPage.m_currentRundownData); rundownPage.m_dataIsSetup = true; } else { Log.Warn("Unable to place rundown due to null data during reload"); } } } public interface IHotManager { void OnHotReload(int id); } public class OfflineGear { private GearIDRange gearIDRange; private ItemDataBlock itemData; private int inventorySlot; private uint persistentID; private OfflineGear(PlayerOfflineGearDataBlock block) { //IL_0067: Unknown result type (might be due to invalid IL or missing references) if (TryParseGearJson(block.GearJSON, out gearIDRange)) { gearIDRange.PlayfabItemId = ((GameDataBlockBase<PlayerOfflineGearDataBlock>)(object)block).name; gearIDRange.PlayfabItemInstanceId = $"OfflineGear_ID_{((GameDataBlockBase<PlayerOfflineGearDataBlock>)(object)block).persistentID}"; gearIDRange.OfflineGearType = block.Type; } if (TryParseGearID(gearIDRange, out itemData, out inventorySlot)) { persistentID = ((GameDataBlockBase<PlayerOfflineGearDataBlock>)(object)block).persistentID; return; } Log.Warn($"Unable to construct Offline Gear [{((GameDataBlockBase<PlayerOfflineGearDataBlock>)(object)block).persistentID}] {((GameDataBlockBase<PlayerOfflineGearDataBlock>)(object)block).name}"); } public static void Load(PlayerOfflineGearDataBlock block) { if (TryParse(block, out var result) && TryStash(result)) { Log.Verbose($"Loaded offline gear [{((GameDataBlockBase<PlayerOfflineGearDataBlock>)(object)block).persistentID}] {((GameDataBlockBase<PlayerOfflineGearDataBlock>)(object)block).name}"); } } private static bool TryParse(PlayerOfflineGearDataBlock block, out OfflineGear result) { //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_000b: Invalid comparison between Unknown and I4 //IL_004c: Unknown result type (might be due to invalid IL or missing references) eOfflineGearType type = block.Type; if (type - 1 <= 1) { result = new OfflineGear(block); return true; } result = null; Log.Warn($"Unimplemented Offline Gear Type [{((GameDataBlockBase<PlayerOfflineGearDataBlock>)(object)block).persistentID}] {block.Type}"); return false; } private bool TryParseGearID(GearIDRange gearIDRange, out ItemDataBlock itemData, out int inventorySlot) { //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Expected I4, but got Unknown inventorySlot = 0; itemData = null; if (gearIDRange == null) { Log.Warn("Unable to parse GearIDRange due to it being null"); return false; } uint compID = gearIDRange.GetCompID((eGearComponent)3); itemData = ((compID != 0) ? GameDataBlockBase<ItemDataBlock>.GetBlock(compID) : null); if (itemData == null) { Log.Warn($"Invalid ItemDataBlock for component in offlinear gear [c:{compID}]"); return false; } inventorySlot = (int)itemData.inventorySlot; return true; } private bool TryParseGearJson(string gearJson, out GearIDRange gearIDRange) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown if (string.IsNullOrEmpty(gearJson)) { gearIDRange = null; Log.Warn("Unable to assign GearIDRange due to null or empty GearJson"); return false; } gearIDRange = new GearIDRange(gearJson); if (gearIDRange == null) { return false; } return true; } private static bool TryStash(OfflineGear gear) { if (gear == null) { Log.Warn("Unable to stash due to null offline gear"); return false; } if (gear.gearIDRange == null) { Log.Warn($"Unable to stash offline gear due to null GearIDRange [{gear.persistentID}]"); return false; } if (gear.itemData == null) { Log.Warn($"Unable to stash offline gear due to null ItemDataBlock [{gear.persistentID}]"); return false; } ((Il2CppArrayBase<List<GearIDRange>>)(object)GearManager.Current.m_gearPerSlot)[gear.inventorySlot].Add(gear.gearIDRange); return true; } } } namespace MTFO.CustomCP { public static class CustomPuzzleManager { private static readonly Dictionary<uint, CustomBioScan> s_scanMap = new Dictionary<uint, CustomBioScan>(); private static readonly Dictionary<uint, CustomClusterScan> s_clusterMap = new Dictionary<uint, CustomClusterScan>(); private static bool s_initialized = false; public static bool TryGetScanByID(uint id, out CustomBioScan scan) { return s_scanMap.TryGetValue(id, out scan); } public static bool TryGetClusterByID(uint id, out CustomClusterScan cluster) { return s_clusterMap.TryGetValue(id, out cluster); } internal static void Initialize(ChainedPuzzleManager manager) { if (!s_initialized) { s_initialized = true; ClassInjector.RegisterTypeInIl2Cpp<CorePuzzleData>(); ClassInjector.RegisterTypeInIl2Cpp<ClusterPuzzleData>(); if (ConfigManager.CustomContent.ScanHolder != null) { InitScans(manager); InitClusters(manager); } } } private static void InitScans(ChainedPuzzleManager manager) { //IL_0175: 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) if ((Object)(object)manager == (Object)null) { Log.Error("Attempted to initialize custom bioscans with a null ChainedPuzzleManager. This should not happen!"); throw new NullReferenceException("ChainedPuzzleManager was null"); } foreach (CustomBioScan scan in ConfigManager.CustomContent.ScanHolder.Scans) { Log.Debug($"Adding scan with ID of [{scan.PersistentID}]"); if (!manager.m_puzzleComponentPrefabs.ContainsKey(scan.BaseScan)) { Log.Error($"Custom scan with persistent ID {scan.PersistentID} references a non-existing base scan of persistent ID {scan.BaseScan}"); continue; } GameObject val = manager.m_puzzleComponentPrefabs[scan.BaseScan]; if ((Object)(object)val.GetComponent<CP_Bioscan_Core>() == (Object)null) { Log.Error($"BaseScan id: {scan.PersistentID} does not have {"CP_Bioscan_Core"} component!"); continue; } GameObject val2 = Object.Instantiate<GameObject>(val); val2.transform.position = new Vector3(10000f, 10000f, 10000f); CP_PlayerScanner component = val2.GetComponent<CP_PlayerScanner>(); if ((Object)(object)component != (Object)null) { component.m_reduceSpeed = scan.ReduceSpeed; component.m_reduceWhenNoPlayer = scan.ReduceWhenNoPlayer; component.m_scanRadius = scan.ScanRadius; component.m_scanSpeeds = Il2CppStructArray<float>.op_Implicit(scan.PlayersInScanMulti); component.m_playerRequirement = scan.PlayerRequirement; } else { Log.Warn($"BaseScan id: {scan.BaseScan} does not have {"CP_PlayerScanner"} component! This will make following setting won't work!"); Log.Warn(" - ReduceSpeed"); Log.Warn(" - ReduceWhenNoPlayer"); Log.Warn(" - ScanRadius"); Log.Warn(" - PlayersInScanMulti"); Log.Warn(" - PlayerRequirement"); } CP_Bioscan_Graphics component2 = val2.GetComponent<CP_Bioscan_Graphics>(); if ((Object)(object)component2 != (Object)null) { component2.m_radius = scan.BioScanGraphics.Radius; component2.m_colors = Il2CppReferenceArray<ColorModeColor>.op_Implicit(ConvertToColorMode(scan.BioScanGraphics.ColorModeColor)); component2.SetText(scan.BioScanGraphics.ScanText); } else { Log.Warn($"BaseScan id: {scan.BaseScan} does not have {"CP_Bioscan_Graphics"} component! This will make {"BioScanGraphics"} setting won't work!"); } val2.GetComponent<CP_Bioscan_Core>().m_playerAgents = new List<PlayerAgent>(); val2.AddComponent<CorePuzzleData>().PersistentID.Set(scan.PersistentID); s_scanMap.Add(scan.PersistentID, scan); manager.m_puzzleComponentPrefabs.Add(scan.PersistentID, val2); } } private static void InitClusters(ChainedPuzzleManager manager) { //IL_01d8: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)manager == (Object)null) { Log.Error("Attempted to initialize custom clusters with a null ChainedPuzzleManager. This should not happen!"); throw new NullReferenceException("ChainedPuzzleManager was null"); } foreach (CustomClusterScan cluster in ConfigManager.CustomContent.ScanHolder.Clusters) { Log.Debug($"Adding cluster with ID of [{cluster.PersistentID}]"); if (!manager.m_puzzleComponentPrefabs.ContainsKey(cluster.BaseCluster)) { Log.Error($"Custom cluster scan with persistent ID {cluster.PersistentID} references a non-existing base cluster of persistent ID {cluster.BaseCluster}"); continue; } if (!manager.m_puzzleComponentPrefabs.ContainsKey(cluster.BioscanID)) { Log.Error($"Custom cluster scan with persistent ID {cluster.PersistentID} references a non-existing bioscan of persistent ID {cluster.BioscanID}"); continue; } GameObject val = manager.m_puzzleComponentPrefabs[cluster.BaseCluster]; if ((Object)(object)val.GetComponent<CP_Cluster_Core>() == (Object)null) { Log.Error($"BaseScan id: {cluster.PersistentID} does not have {"CP_Cluster_Core"} component!"); } else { GameObject val2 = Object.Instantiate<GameObject>(val); val2.transform.position = new Vector3(1000f, 1000f, 1000f); CP_Cluster_Core component = val2.GetComponent<CP_Cluster_Core>(); GameObject childPuzzlePrefab = manager.m_puzzleComponentPrefabs[cluster.BioscanID]; component.m_amountOfPuzzles = cluster.ClusterCount; component.m_childPuzzlePrefab = childPuzzlePrefab; component.m_distanceBetween = cluster.DistanceBetweenScans; component.m_revealWithHoloPath = cluster.RevealWithHoloPath; val2.AddComponent<ClusterPuzzleData>().PersistentID.Set(cluster.PersistentID); s_clusterMap.Add(cluster.PersistentID, cluster); manager.m_puzzleComponentPrefabs.Add(cluster.PersistentID, val2); } } } private static ColorModeColor[] ConvertToColorMode(CustomBioScan.BioScanColorByMode[] bioScanColorByModes) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0031: 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_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Expected O, but got Unknown ColorModeColor[] array = (ColorModeColor[])(object)new ColorModeColor[bioScanColorByModes.Length]; for (int i = 0; i < bioScanColorByModes.Length; i++) { CustomBioScan.BioScanColorByMode bioScanColorByMode = bioScanColorByModes[i]; array[i] = new ColorModeColor { col = new Color(bioScanColorByMode.R, bioScanColorByMode.G, bioScanColorByMode.B, bioScanColorByMode.A), mode = bioScanColorByMode.Mode }; } return array; } } } namespace MTFO.CustomCP.Patches { [HarmonyPatch(typeof(ChainedPuzzleManager), "OnAssetsLoaded")] internal static class Patch_PuzzleManager { internal static void Postfix(ChainedPuzzleManager __instance) { CustomPuzzleManager.Initialize(__instance); } } [HarmonyPatch(typeof(CP_Bioscan_Core), "Update")] internal static class FixNullRefSpam { internal static bool Prefix(CP_Bioscan_Core __instance) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) if (((Component)__instance).gameObject.transform.position.x > 9000f && ((Component)__instance).gameObject.transform.position.y > 9000f && ((Component)__instance).gameObject.transform.position.z > 9000f) { return false; } return true; } } [HarmonyPatch] internal static class Patch_SetupPuzzleCores { [HarmonyPostfix] [HarmonyWrapSafe] [HarmonyPatch(typeof(CP_Bioscan_Core), "Setup")] public static void SetupSpline(CP_Bioscan_Core __instance) { CorePuzzleData component = ((Component)__instance).GetComponent<CorePuzzleData>(); if (!((Object)(object)component == (Object)null) && CustomPuzzleManager.TryGetScanByID(component.PersistentID.Value, out var scan)) { CP_Holopath_Spline val = ((Il2CppObjectBase)__instance.m_spline).TryCast<CP_Holopath_Spline>(); if ((Object)(object)val != (Object)null) { scan.ApplySplineRevealSpeed(val); } } } [HarmonyPostfix] [HarmonyWrapSafe] [HarmonyPatch(typeof(CP_Cluster_Core), "Setup")] public static void SetupSpline(CP_Cluster_Core __instance) { ClusterPuzzleData component = ((Component)__instance).GetComponent<ClusterPuzzleData>(); if (!((Object)(object)component == (Object)null) && CustomPuzzleManager.TryGetClusterByID(component.PersistentID.Value, out var cluster)) { CP_Holopath_Spline val = ((Il2CppObjectBase)__instance.m_spline).TryCast<CP_Holopath_Spline>(); if ((Object)(object)val != (Object)null) { cluster.ApplySplineRevealSpeed(val); } } } } } namespace MTFO.Custom { public class GlowstickHolder { [JsonIgnore] public Dictionary<string, CustomGlowstick> GlowstickLookup; public List<GlowstickConfig> Glowsticks { get; set; } public void Setup() { //IL_009d: Unknown result type (might be due to invalid IL or missing references) GlowstickLookup = new Dictionary<string, CustomGlowstick>(); foreach (GlowstickConfig glowstick in Glowsticks) { Log.Verbose(glowstick); if (GlowstickLookup.TryGetValue(glowstick.Name, out var value)) { Log.Warn("Custom glowstick with name " + glowstick.Name + " already exists in the lookup! Skipping..."); continue; } value = default(CustomGlowstick); value.Color = new Color(glowstick.r, glowstick.g, glowstick.b, (glowstick.a == 0f) ? 1f : glowstick.a); value.Range = ((glowstick.Range == 0f) ? 15f : glowstick.Range); CustomGlowstick value2 = value; GlowstickLookup.Add(glowstick.Name, value2); } } } public struct CustomGlowstick { public Color Color { get; set; } public float Range { get; set; } } public struct GlowstickConfig { public string Name { get; set; } public float Range { get; set; } public float r { get; set; } public float g { get; set; } public float b { get; set; } public float a { get; set; } public override string ToString() { return $"{Name},{Range},{r},{g},{b},{a}"; } } public class ScanHolder { public List<CustomBioScan> Scans { get; set; } public List<CustomClusterScan> Clusters { get; set; } } public enum RevealMode { ScaleByDistance, ConstantTime, Instant } public struct CustomBioScan : IRevealableScanConfig { public struct BioScanGx { public bool HideScanText { get; set; } public string ScanText { get; set; } public float Radius { get; set; } public BioScanColorByMode[] ColorModeColor { get; set; } } public class BioScanColorByMode { public eChainedPuzzleGraphicsColorMode Mode { get; set; } public float R { get; set; } public float G { get; set; } public float B { get; set; } public float A { get; set; } } public uint BaseScan { get; set; } public uint PersistentID { get; set; } public PlayerRequirement PlayerRequirement { get; set; } public float ScanRadius { get; set; } public float[] PlayersInScanMulti { get; set; } public float ReduceSpeed { get; set; } public bool ReduceWhenNoPlayer { get; set; } public float RevealTime { get; set; } public RevealMode RevealMode { get; set; } public BioScanGx BioScanGraphics { get; set; } } public struct CustomClusterScan : IRevealableScanConfig { public uint BaseCluster { get; set; } public uint PersistentID { get; set; } public int ClusterCount { get; set; } public uint BioscanID { get; set; } public float DistanceBetweenScans { get; set; } public float RevealTime { get; set; } public RevealMode RevealMode { get; set; } public bool RevealWithHoloPath { get; set; } } internal interface IRevealableScanConfig { uint PersistentID { get; } float RevealTime { get; } RevealMode RevealMode { get; } } internal static class IRevealibleScanConfigExtensions { public static void ApplySplineRevealSpeed(this IRevealableScanConfig scan, CP_Holopath_Spline spline) { float revealTime = scan.RevealTime; switch (scan.RevealMode) { case RevealMode.ConstantTime: if (revealTime <= 0f) { Log.Warn($"Attempted to set a custom scan with persistent id '{scan.PersistentID}' to reveal in less than or equal to 0 seconds. This is not supported. Instead, use RevealMode \"{2}\" or integer value {2}"); } else { spline.m_splineLength = 1f; spline.m_revealSpeed = revealTime; } break; case RevealMode.ScaleByDistance: if (revealTime < 0f) { Log.Warn($"Attempted to set a custom scan with persistent id '{scan.PersistentID}' to reveal in less than 0 seconds. This is not supported."); } else if (revealTime != 0f) { spline.m_revealSpeed = revealTime; } break; case RevealMode.Instant: spline.m_revealSpeed = -1f; break; } } } public struct TierNames { public string Tier1 { get; set; } public string Tier2 { get; set; } public string Tier3 { get; set; } public string Tier4 { get; set; } public string Tier5 { get; set; } } } namespace MTFO.Custom.CCP.Patches { [HarmonyPatch(typeof(CP_Bioscan_Hud))] internal static class Patch_Bioscan_Hud { [HarmonyPatch("Awake")] [HarmonyPostfix] internal static void Post_Setup(CP_Bioscan_Hud __instance) { UpdateText(__instance); } [HarmonyPatch("SetVisible")] [HarmonyPostfix] internal static void Post_SetVisible(CP_Bioscan_Hud __instance) { UpdateText(__instance); } [HarmonyPatch("UpdateText")] [HarmonyPostfix] internal static void Post_UpdateText(CP_Bioscan_Hud __instance) { UpdateText(__instance); } private static void UpdateText(CP_Bioscan_Hud hud) { CorePuzzleData component = ((Component)hud).gameObject.GetComponent<CorePuzzleData>(); if ((Object)(object)component != (Object)null) { if (!CustomPuzzleManager.TryGetScanByID(component.PersistentID.Value, out var scan)) { Log.Error($"scanData missing... {component.PersistentID.Value}"); } else if (scan.BioScanGraphics.HideScanText) { ((TMP_Text)hud.m_bioscanWorldText).SetText(string.Empty, true); } else if (!string.IsNullOrWhiteSpace(scan.BioScanGraphics.ScanText)) { ((TMP_Text)hud.m_bioscanWorldText).SetText(scan.BioScanGraphics.ScanText, true); } } } } } namespace MTFO.Custom.CCP.Components { internal sealed class ClusterPuzzleData : MonoBehaviour { public Il2CppValueField<uint> PersistentID; public CP_Bioscan_Hud[] ChildHuds = Array.Empty<CP_Bioscan_Hud>(); } internal sealed class CorePuzzleData : MonoBehaviour { public Il2CppValueField<uint> PersistentID; } } namespace MTFO.API { public delegate void GameDataContentLoadEvent(string datablockName, string jsonContent, in List<string> jsonItemsToInject); public delegate void GameDataContentLoadedDelegate(string datablockName, string jsonContent); public static class MTFOGameDataAPI { public static event GameDataContentLoadEvent OnGameDataContentLoad; public static event GameDataContentLoadedDelegate OnGameDataContentLoaded; internal static void Invoke_OnGameDataContentLoad(string datablockName, Stream jsonContentStream, in List<string> jsonItemsToInject) { if (MTFOGameDataAPI.OnGameDataContentLoad != null) { MTFOGameDataAPI.OnGameDataContentLoad(datablockName, new StreamReader(jsonContentStream).ReadToEnd(), in jsonItemsToInject); } } internal static void Invoke_OnGameDataContentLoaded(string datablockName, string jsonContent) { MTFOGameDataAPI.OnGameDataContentLoaded?.Invoke(datablockName, jsonContent); } } public static class MTFOHotReloadAPI { public static bool HotReloadEnabled => ConfigManager.IsHotReloadEnabled; public static event Action OnHotReload; internal static void HotReloaded() { MTFOHotReloadAPI.OnHotReload?.Invoke(); } } public static class MTFOPathAPI { public static string RundownPath => ConfigManager.GameDataPath; public static bool HasRundownPath => ConfigManager.HasGameDataPath; public static string CustomPath => ConfigManager.CustomPath; public static bool HasCustomPath => ConfigManager.HasCustomContent; } }
plugins/net6/MTFO.Ext.PartialData.dll
Decompiled a month agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text.Json; using System.Text.Json.Serialization; using System.Text.RegularExpressions; using AIGraph; using AssetShards; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using CellMenu; using GTFO.API.Utilities; using GameData; using Gear; using Globals; using HarmonyLib; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.InteropTypes.Arrays; using Il2CppJsonNet; using Il2CppJsonNet.Linq; using Il2CppSystem; using Il2CppSystem.Collections.Generic; using InjectLib.JsonNETInjection; using InjectLib.JsonNETInjection.Converter; using LevelGeneration; using Localization; using MTFO.Ext.PartialData.DTO; using MTFO.Ext.PartialData.DataBlockTypes; using MTFO.Ext.PartialData.JsonConverters; using MTFO.Ext.PartialData.JsonInjects; using MTFO.Ext.PartialData.Utils; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")] [assembly: AssemblyCompany("MTFO.Ext.PartialData")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.1.0.0")] [assembly: AssemblyInformationalVersion("0.1.0")] [assembly: AssemblyProduct("MTFO.Ext.PartialData")] [assembly: AssemblyTitle("MTFO.Ext.PartialData")] [assembly: TargetPlatform("Windows7.0")] [assembly: SupportedOSPlatform("Windows7.0")] [assembly: AssemblyVersion("0.1.0.0")] namespace MTFO.Ext.PartialData { [BepInPlugin("MTFO.Extension.PartialBlocks", "MTFO pDataBlock", "1.4.0")] [BepInProcess("GTFO.exe")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] internal class EntryPoint : BasePlugin { private bool once; public override void Load() { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown //IL_0036: Expected O, but got Unknown //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown //IL_0062: Expected O, but got Unknown //IL_00ca: Unknown result type (might be due to invalid IL or missing references) Logger.LogInstance = ((BasePlugin)this).Log; ConfigEntry<bool> val = ((BasePlugin)this).Config.Bind<bool>(new ConfigDefinition("Logging", "UseLog"), false, new ConfigDescription("Using Log Message for Debug?", (AcceptableValueBase)null, Array.Empty<object>())); ConfigEntry<bool> obj = ((BasePlugin)this).Config.Bind<bool>(new ConfigDefinition("Developer", "UseLiveEdit"), false, new ConfigDescription("Using Live Edit?", (AcceptableValueBase)null, Array.Empty<object>())); Logger.UsingLog = val.Value; PartialDataManager.CanLiveEdit = obj.Value; if (!DataBlockTypeManager.Initialize()) { Logger.Error("Unable to Initialize DataBlockTypeCache"); return; } if (!PartialDataManager.Initialize()) { Logger.Error("Unable to Initialize PartialData"); return; } PersistentIDManager.DumpToFile(Path.Combine(PartialDataManager.PartialDataPath, "_persistentID.json")); AssetShardManager.OnStartupAssetsLoaded += Action.op_Implicit((Action)OnAssetLoaded); new Harmony("MTFO.pBlock.Harmony").PatchAll(); JsonInjector.SetConverter<uint>((Il2CppJsonUnmanagedTypeConverter<uint>)new UintConverter()); } private void OnAssetLoaded() { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) if (once) { return; } once = true; PartialDataManager.LoadPartialData(); GameDataTextLocalizationService val = ((Il2CppObjectBase)Text.TextLocalizationService).Cast<GameDataTextLocalizationService>(); val.m_textDataBlocks = null; val.m_texts.Clear(); Language currentLanguage = Text.TextLocalizationService.CurrentLanguage; TextDataBlock[] array = Il2CppArrayBase<TextDataBlock>.op_Implicit(GameDataBlockBase<TextDataBlock>.GetAllBlocks()); val.m_textDataBlocks = Il2CppReferenceArray<TextDataBlock>.op_Implicit(array); int num = array.Length; for (int i = 0; i < num; i++) { TextDataBlock val2 = array[i]; string text = val2.GetText(currentLanguage, false); if (string.IsNullOrWhiteSpace(text)) { text = val2.English; } val.m_texts[((GameDataBlockBase<TextDataBlock>)(object)val2).persistentID] = text; } Text.TextLocalizationService.SetCurrentLanguage(Text.TextLocalizationService.CurrentLanguage); Text.UpdateAllTexts(); PartialDataManager.WriteAllFile(Path.Combine(MTFOUtil.GameDataPath, "CompiledPartialData")); } } public static class LocalizedTextManager { public static Dictionary<LocalizedText, (uint, string)> _lookup = new Dictionary<LocalizedText, (uint, string)>(); public static void Register(LocalizedText localizedText, uint id, string unlocalized) { _lookup[localizedText] = (id, unlocalized); } public static void Get(LocalizedText localizedText) { } } internal class PartialDataCache { public string Name => DataBlockType.GetShortName(); public IDataBlockType DataBlockType { get; private set; } public Queue<string> JsonsToRead { get; private set; } = new Queue<string>(); private PartialDataCache() { } public PartialDataCache(IDataBlockType dbTypeCache) { DataBlockType = dbTypeCache; } } public class PartialDataManager { private static List<DataBlockDefinition> _Config; private static readonly List<string> _AddedFileList = new List<string>(); private static readonly List<PartialDataCache> _DataCache = new List<PartialDataCache>(); public static string PartialDataPath { get; private set; } public static string ConfigPath { get; private set; } public static bool Initialized { get; private set; } = false; public static bool CanLiveEdit { get; set; } = false; public static PersistentIDConverter IDConverter { get; private set; } = new PersistentIDConverter(); internal static bool Initialize() { if (Initialized) { return false; } if (!MTFOUtil.IsLoaded) { return false; } PartialDataPath = Path.GetFullPath(Path.Combine(MTFOUtil.GameDataPath, "PartialData")); if (!Directory.Exists(PartialDataPath)) { Logger.Error("Unable to setup PartialData::PartialData folder is missing"); return false; } ConfigPath = Path.GetFullPath(Path.Combine(PartialDataPath, "_config.json")); if (!File.Exists(ConfigPath)) { Logger.Error("Unable to setup PartialData::Config File (_config.json) is missing"); return false; } _AddedFileList.Clear(); _DataCache.Clear(); _Config = JSON.Deserialize<List<DataBlockDefinition>>(File.ReadAllText(ConfigPath)); Initialized = true; ReadAndAssignIDs(); return true; } private static void ReadAndAssignIDs() { foreach (DataBlockDefinition item in _Config) { DataBlockTypeManager.SetIDBuffer(item.TypeName, item.StartFromID, item.IncrementMode); } foreach (string item2 in from f in Directory.GetFiles(PartialDataPath, "*.json", SearchOption.AllDirectories) orderby f select f) { if (Path.GetFileName(item2).StartsWith("_")) { Logger.Log(item2 + " have discard prefix (_) excluding from loader!"); continue; } if (!File.Exists(item2)) { Logger.Error("File (" + item2 + ") is not exist somehow?"); continue; } if (_AddedFileList.Contains(item2)) { Logger.Error("File (" + item2 + ") has loaded multiple times!"); continue; } _AddedFileList.Add(item2); AssignPersistentID(item2); Logger.Log(" - " + item2); } } private static void AssignPersistentID(string file) { using JsonDocument jsonDocument = JsonDocument.Parse(File.ReadAllText(file), new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true }); JsonElement rootElement = jsonDocument.RootElement; switch (rootElement.ValueKind) { case JsonValueKind.Array: { foreach (JsonElement item in rootElement.EnumerateArray()) { Read(item, assignID: true, file); } break; } case JsonValueKind.Object: Read(rootElement, assignID: true, file); break; } } private static void ReadChangedFile(string content, string debugName) { using JsonDocument jsonDocument = JsonDocument.Parse(content, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true }); JsonElement rootElement = jsonDocument.RootElement; switch (rootElement.ValueKind) { case JsonValueKind.Array: { foreach (JsonElement item in rootElement.EnumerateArray()) { Read(item, assignID: false, debugName); } break; } case JsonValueKind.Object: Read(rootElement, assignID: false, debugName); break; } } private static void ReadChangedFile(string file) { ReadChangedFile(File.ReadAllText(file), file); } private static void Read(JsonElement objNode, bool assignID, string debugName) { if (!objNode.TryGetProperty("persistentID", out var value)) { Logger.Error("persistentID field is missing: " + debugName); return; } if (!objNode.TryGetProperty("datablock", out var value2)) { Logger.Error("datablock field is missing: " + debugName); return; } if (assignID && value.ValueKind == JsonValueKind.String) { if (!DataBlockTypeManager.TryGetNextID(value2.GetString(), out var id)) { Logger.Error($"datablock field is not valid: {debugName} {objNode}"); return; } PersistentIDManager.TryAssignId(value.GetString(), id); } string datablockName = DataBlockTypeManager.GetBlockName(value2.GetString()); if (!DataBlockTypeManager.TryFindCache(datablockName, out var cache)) { Logger.Error($"datablock field is not valid: {debugName} {objNode}"); return; } PartialDataCache partialDataCache = _DataCache.FirstOrDefault((PartialDataCache x) => x.Name.Equals(datablockName)); if (partialDataCache == null) { partialDataCache = new PartialDataCache(cache); _DataCache.Add(partialDataCache); } partialDataCache.JsonsToRead.Enqueue(objNode.ToString()); } internal static void LoadPartialData() { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown if (Initialized) { if (CanLiveEdit) { LiveEdit.CreateListener(PartialDataPath, "*.json", true).FileChanged += new LiveEditEventHandler(Listener_FileChanged1); } AddAllCache(); } } private static void Listener_FileChanged1(LiveEditEventArgs e) { Logger.Warning("LiveEdit File Changed: " + e.FullPath); LiveEdit.TryReadFileContent(e.FullPath, (Action<string>)delegate(string content) { ReadChangedFile(content, e.FullPath); AddAllCache(isLiveEdit: true); }); } internal static void WriteAllFile(string path) { if (!Directory.Exists(path)) { return; } foreach (PartialDataCache item in _DataCache) { string fullPath = Path.GetFullPath(Path.Combine(path, "GameData_" + item.DataBlockType.GetFullName() + "_bin.json")); item.DataBlockType.DoSaveToDisk(fullPath); } } private static void AddAllCache(bool isLiveEdit = false) { foreach (PartialDataCache item in _DataCache) { bool flag = false; while (item.JsonsToRead.Count > 0) { string json = item.JsonsToRead.Dequeue(); item.DataBlockType.AddJsonBlock(json); flag = true; } if (flag && isLiveEdit) { item.DataBlockType.OnChanged(); } } } public static uint GetID(string guid) { if (!Initialized) { return 0u; } return PersistentIDManager.GetId(guid); } } public class PartialDataPack { private readonly List<string> _AddedFiles = new List<string>(); private readonly List<PartialDataCache> _DataCaches = new List<PartialDataCache>(); public string Namespace { get; private set; } = string.Empty; public bool CheckFileChange { get; set; } = true; public PartialDataPack() { } public PartialDataPack(string namespaceString) : this() { Namespace = namespaceString; } public string GetGUIDFormat(string guid) { if (!string.IsNullOrEmpty(Namespace)) { guid = Namespace + "." + guid; } return guid; } public void ClearPack() { _AddedFiles.Clear(); _DataCaches.Clear(); } public void ReadPack(string packPath) { foreach (string item in from f in Directory.GetFiles(packPath, "*.json", SearchOption.AllDirectories) orderby f select f) { if (Path.GetFileName(item).StartsWith("_")) { Logger.Log(item + " have discard prefix (_) excluding from loader!"); continue; } if (!File.Exists(item)) { Logger.Error("File (" + item + ") is not exist somehow?"); continue; } if (_AddedFiles.Contains(item)) { Logger.Error("File (" + item + ") has loaded multiple times!"); continue; } _AddedFiles.Add(item); AllocateGUIDFromFile(item); Logger.Log(" - " + item); } _ = CheckFileChange; } public void AddToGame() { foreach (PartialDataCache dataCache in _DataCaches) { while (dataCache.JsonsToRead.Count > 0) { string json = dataCache.JsonsToRead.Dequeue(); dataCache.DataBlockType.AddJsonBlock(json); } } } public void WriteGameDataFile(string path) { if (!Directory.Exists(path)) { return; } foreach (PartialDataCache dataCache in _DataCaches) { string fullPath = Path.GetFullPath(Path.Combine(path, "GameData_" + dataCache.DataBlockType.GetFullName() + "_bin.json")); dataCache.DataBlockType.DoSaveToDisk(fullPath); } } private void AllocateGUIDFromFile(string file) { using JsonDocument jsonDocument = JsonDocument.Parse(File.ReadAllText(file), new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true }); JsonElement rootElement = jsonDocument.RootElement; switch (rootElement.ValueKind) { case JsonValueKind.Array: { foreach (JsonElement item in rootElement.EnumerateArray()) { Read(item, assignID: true, file); } break; } case JsonValueKind.Object: Read(rootElement, assignID: true, file); break; } } private void ReadChangedFile(string file) { using JsonDocument jsonDocument = JsonDocument.Parse(File.ReadAllText(file), new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip, AllowTrailingCommas = true }); JsonElement rootElement = jsonDocument.RootElement; switch (rootElement.ValueKind) { case JsonValueKind.Array: { foreach (JsonElement item in rootElement.EnumerateArray()) { Read(item, assignID: false, file); } break; } case JsonValueKind.Object: Read(rootElement, assignID: false, file); break; } } private void OnDatablockChanged() { foreach (PartialDataCache dataCache in _DataCaches) { bool flag = false; while (dataCache.JsonsToRead.Count > 0) { if (dataCache.Name.Equals("Rundown")) { dataCache.JsonsToRead.Clear(); Logger.Error("Editing Rundown DataBlock will leads to crash, Ignored"); } else { string json = dataCache.JsonsToRead.Dequeue(); dataCache.DataBlockType.AddJsonBlock(json); flag = true; } } if (flag) { dataCache.DataBlockType.OnChanged(); } } } private void Read(JsonElement objNode, bool assignID, string debugName) { if (!objNode.TryGetProperty("persistentID", out var value)) { Logger.Error("persistentID field is missing: " + debugName); return; } if (!objNode.TryGetProperty("datablock", out var value2)) { Logger.Error("datablock field is missing: " + debugName); return; } if (assignID && value.ValueKind == JsonValueKind.String) { if (!DataBlockTypeManager.TryGetNextID(value2.GetString(), out var id)) { Logger.Error($"datablock field is not valid: {debugName} {objNode}"); return; } PersistentIDManager.TryAssignId(value.GetString(), id); } string datablockName = DataBlockTypeManager.GetBlockName(value2.GetString()); if (!DataBlockTypeManager.TryFindCache(datablockName, out var cache)) { Logger.Error($"datablock field is not valid: {debugName} {objNode}"); return; } PartialDataCache partialDataCache = _DataCaches.FirstOrDefault((PartialDataCache x) => x.Name.Equals(datablockName)); if (partialDataCache == null) { partialDataCache = new PartialDataCache(cache); _DataCaches.Add(partialDataCache); } string text = objNode.ToString(); if (partialDataCache.DataBlockType.GetShortName() == "PlayerOfflineGear") { if (!objNode.TryGetProperty("GearJSON", out var value3)) { Logger.Warning("GearJSON field is missing, Ignore Stuff: " + debugName); } else if (value3.ValueKind == JsonValueKind.String) { string @string = value3.GetString(); if (GearJSONUtil.TryProcessGUID(@string, Namespace, out var processedJson)) { @string = @string.Replace("\"", "\\\""); processedJson = processedJson.Replace("\"", "\\\""); text = text.Replace(@string, processedJson); Logger.Warning(text); } } } partialDataCache.JsonsToRead.Enqueue(text); } } internal static class PersistentIDManager { private static readonly Dictionary<string, uint> _GUIDDict = new Dictionary<string, uint>(); public static bool TryAssignId(string guid, uint id) { if (_GUIDDict.ContainsKey(guid)) { Logger.Error("GUID is already used: " + guid); return false; } _GUIDDict.Add(guid, id); return true; } public static uint GetId(string guid) { if (!_GUIDDict.TryGetValue(guid, out var value)) { Logger.Error("GUID is Missing: " + guid); return 0u; } return value; } public static bool TryGetId(string guid, out uint id) { if (_GUIDDict.TryGetValue(guid, out id)) { return true; } id = 0u; return false; } public static void DumpToFile(string path) { string text = "[\n\t//AUTO-GENERATED PERSISTENT ID LIST\n"; foreach (KeyValuePair<string, uint> item in _GUIDDict) { text = text + "\t{ \"GUID\": \"" + item.Key + "\", \"ID\": " + item.Value + " },\n"; } if (text.Length > 2) { string text2 = text; text = text2.Substring(0, text2.Length - 2); } text += "\n]"; File.WriteAllText(path, text); } } } namespace MTFO.Ext.PartialData.Utils { public static class GearJSONUtil { private const string COMP_CHARS = "abcdefghijklmnopqrst"; public static bool TryProcessGUID(string gearjson, string namespaceStr, out string processedJson) { string text = gearjson; bool flag = false; using JsonDocument jsonDocument = JsonDocument.Parse(gearjson); if (!jsonDocument.RootElement.TryGetProperty("Packet", out var value)) { processedJson = string.Empty; return false; } if (!value.TryGetProperty("Comps", out var value2)) { processedJson = string.Empty; return false; } string text2 = "abcdefghijklmnopqrst"; for (int i = 0; i < text2.Length; i++) { if (value2.TryGetProperty(text2[i].ToString(), out var value3) && value3.TryGetProperty("v", out var value4) && value4.ValueKind == JsonValueKind.String) { string @string = value4.GetString(); Logger.Warning("Found String id: " + @string); uint id = PersistentIDManager.GetId(@string); if (id != 0) { text = new Regex("(\"v\")\\s*:\\s*(\"" + @string + "\")").Replace(text, $"\"v\":{id}"); flag = true; } } } if (flag) { Logger.Warning(gearjson); Logger.Warning(text); processedJson = text; return true; } processedJson = string.Empty; return false; } } public class IDBuffer { public uint CurrentID { get; set; } = 65535u; public IncrementMode IncrementMode { get; set; } public uint GetNext() { if (IncrementMode == IncrementMode.Increment) { return CurrentID++; } if (IncrementMode == IncrementMode.Decrement) { return CurrentID--; } return 0u; } } public enum IncrementMode { Decrement, Increment } internal static class JSON { private static readonly JsonSerializerOptions _Setting; static JSON() { _Setting = CreateSetting(); _Setting = CreateSetting(); _Setting.Converters.Add(new PersistentIDConverter()); } private static JsonSerializerOptions CreateSetting() { return new JsonSerializerOptions { ReadCommentHandling = JsonCommentHandling.Skip, IncludeFields = true, AllowTrailingCommas = true, WriteIndented = true, Converters = { (JsonConverter)new Il2CppListConverterFactory(), (JsonConverter)new ColorConverter(), (JsonConverter)new JsonStringEnumConverter(), (JsonConverter)new LocalizedTextConverter() } }; } public static T Deserialize<T>(string json) { return JsonSerializer.Deserialize<T>(json, _Setting); } public static object Deserialize(string json, Type type) { return JsonSerializer.Deserialize(json, type, _Setting); } } internal static class Logger { public static ManualLogSource LogInstance; public static bool UsingLog; public static void Log(string format, params object[] args) { Log(string.Format(format, args)); } public static void Log(string str) { if (UsingLog) { ManualLogSource logInstance = LogInstance; if (logInstance != null) { logInstance.Log((LogLevel)8, (object)str); } } } public static void Warning(string format, params object[] args) { Warning(string.Format(format, args)); } public static void Warning(string str) { ManualLogSource logInstance = LogInstance; if (logInstance != null) { logInstance.Log((LogLevel)4, (object)str); } } public static void Error(string format, params object[] args) { Error(string.Format(format, args)); } public static void Error(string str) { ManualLogSource logInstance = LogInstance; if (logInstance != null) { logInstance.Log((LogLevel)2, (object)str); } } public static void Debug(string format, params object[] args) { Debug(string.Format(format, args)); } public static void Debug(string str) { ManualLogSource logInstance = LogInstance; if (logInstance != null) { logInstance.Log((LogLevel)32, (object)str); } } } internal static class MTFOUtil { public const string MTFOGUID = "com.dak.MTFO"; public static string GameDataPath { get; private set; } public static string CustomPath { get; private set; } public static bool HasCustomContent { get; private set; } public static bool IsLoaded { get; private set; } static MTFOUtil() { GameDataPath = string.Empty; CustomPath = string.Empty; HasCustomContent = false; IsLoaded = false; if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("com.dak.MTFO", out var info)) { return; } try { Type obj = (AppDomain.CurrentDomain.GetAssemblies().First((Assembly a) => !a.IsDynamic && a.Location == info.Location) ?? throw new Exception("Assembly is Missing!")).GetTypes().First((Type t) => t.Name == "ConfigManager") ?? throw new Exception("Unable to Find ConfigManager Class"); FieldInfo field = obj.GetField("GameDataPath", BindingFlags.Static | BindingFlags.Public); FieldInfo field2 = obj.GetField("CustomPath", BindingFlags.Static | BindingFlags.Public); FieldInfo? field3 = obj.GetField("HasCustomContent", BindingFlags.Static | BindingFlags.Public); if ((object)field == null) { throw new Exception("Unable to Find Field: GameDataPath"); } if ((object)field2 == null) { throw new Exception("Unable to Find Field: CustomPath"); } if ((object)field3 == null) { throw new Exception("Unable to Find Field: HasCustomContent"); } GameDataPath = (string)field.GetValue(null); CustomPath = (string)field2.GetValue(null); HasCustomContent = (bool)field3.GetValue(null); IsLoaded = true; } catch (Exception value) { Console.WriteLine($"Exception thrown while reading path from Data Dumper (MTFO):\n{value}"); } } } } namespace MTFO.Ext.PartialData.JsonInjects { internal class UintConverter : Il2CppJsonUnmanagedTypeConverter<uint> { protected override uint Read(JToken jToken, uint existingValue, JsonSerializer serializer) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Invalid comparison between Unknown and I4 if ((int)jToken.Type == 6) { return (uint)jToken; } if ((int)jToken.Type == 8) { return PartialDataManager.GetID((string)jToken); } Logger.Error($"{jToken} is not valid!"); return existingValue; } protected override Object ToIl2CppObject(uint value) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) UInt32 val = default(UInt32); val.m_value = value; return ((UInt32)(ref val)).BoxIl2CppObject(); } protected override void Write(JsonWriter writer, uint value, JsonSerializer serializer) { writer.WriteValue(value); } } } namespace MTFO.Ext.PartialData.JsonConverters { internal class ColorConverter : JsonConverter<Color> { public override bool HandleNull => false; public override Color Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) Color result = default(Color); switch (reader.TokenType) { case JsonTokenType.StartObject: while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject) { return result; } if (reader.TokenType != JsonTokenType.PropertyName) { throw new JsonException("Expected PropertyName token"); } string? @string = reader.GetString(); reader.Read(); switch (@string.ToLower()) { case "r": result.r = reader.GetSingle(); break; case "g": result.g = reader.GetSingle(); break; case "b": result.b = reader.GetSingle(); break; case "a": result.a = reader.GetSingle(); break; } } throw new JsonException("Expected EndObject token"); case JsonTokenType.String: { string text = reader.GetString().Trim(); if (ColorUtility.TryParseHtmlString(text, ref result)) { return result; } throw new JsonException("Color format is not right: " + text); } default: throw new JsonException($"ColorJson type: {reader.TokenType} is not implemented!"); } } public override void Write(Utf8JsonWriter writer, Color value, JsonSerializerOptions options) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) JsonSerializer.Serialize<Color>(writer, value, options); } } internal class Il2CppListConverter<T> : JsonConverter<List<T>> { public override bool HandleNull => false; public override List<T> Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { List<T> val = new List<T>(); if (reader.TokenType == JsonTokenType.StartArray) { foreach (T item in JsonSerializer.Deserialize<List<T>>(ref reader, options)) { val.Add(item); } return val; } return null; } public override void Write(Utf8JsonWriter writer, List<T> value, JsonSerializerOptions options) { writer.WriteStartArray(); Enumerator<T> enumerator = value.GetEnumerator(); while (enumerator.MoveNext()) { T current = enumerator.Current; JsonSerializer.Serialize(writer, current, options); } writer.WriteEndArray(); } } internal class Il2CppListConverterFactory : JsonConverterFactory { public override bool CanConvert(Type typeToConvert) { if (!typeToConvert.IsGenericType) { return false; } if (typeToConvert.GetGenericTypeDefinition() != typeof(List<>)) { return false; } return true; } public override JsonConverter CreateConverter(Type typeToConvert, JsonSerializerOptions options) { Type type = typeToConvert.GetGenericArguments()[0]; return (JsonConverter)Activator.CreateInstance(typeof(Il2CppListConverter<>).MakeGenericType(type), BindingFlags.Instance | BindingFlags.Public, null, null, null); } } internal class LocalizedTextConverter : JsonConverter<LocalizedText> { public override bool HandleNull => false; public override LocalizedText Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { //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_0042: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Expected O, but got Unknown //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown //IL_004a: 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_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Expected O, but got Unknown switch (reader.TokenType) { case JsonTokenType.String: { string @string = reader.GetString(); if (!PersistentIDManager.TryGetId(@string, out var id)) { return new LocalizedText { Id = 0u, UntranslatedText = @string }; } return new LocalizedText { Id = id, UntranslatedText = null }; } case JsonTokenType.Number: return new LocalizedText { Id = reader.GetUInt32(), UntranslatedText = null }; default: throw new JsonException($"LocalizedTextJson type: {reader.TokenType} is not implemented!"); } } public override void Write(Utf8JsonWriter writer, LocalizedText value, JsonSerializerOptions options) { JsonSerializer.Serialize<LocalizedText>(writer, value, options); } } public class PersistentIDConverter : JsonConverter<uint> { public override uint Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { if (reader.TokenType == JsonTokenType.String) { return PersistentIDManager.GetId(reader.GetString()); } if (reader.TokenType == JsonTokenType.Number) { return reader.GetUInt32(); } throw new JsonException("TOKEN IS NOT VALID!"); } public override void Write(Utf8JsonWriter writer, uint value, JsonSerializerOptions options) { writer.WriteNumberValue(value); } } internal class Vector2Converter : JsonConverter<Vector2> { public override Vector2 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return JsonSerializer.Deserialize<Vector2>(ref reader); } public override void Write(Utf8JsonWriter writer, Vector2 value, JsonSerializerOptions options) { //IL_000c: 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) writer.WriteStartObject(); writer.WriteNumber("x", value.x); writer.WriteNumber("y", value.y); writer.WriteEndObject(); } } } namespace MTFO.Ext.PartialData.Injects { [HarmonyPatch(typeof(GearManager))] internal class Inject_GearManager { private const string COMP_CHARS = "abcdefghijklmnopqrst"; [HarmonyPrefix] [HarmonyWrapSafe] [HarmonyPatch("LoadOfflineGearDatas")] private static void Pre_LoadOfflineGearDatas() { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Invalid comparison between Unknown and I4 //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Invalid comparison between Unknown and I4 foreach (PlayerOfflineGearDataBlock allBlock in GameDataBlockBase<PlayerOfflineGearDataBlock>.GetAllBlocks()) { if (!((GameDataBlockBase<PlayerOfflineGearDataBlock>)(object)allBlock).internalEnabled || string.IsNullOrEmpty(allBlock.GearJSON) || ((int)allBlock.Type != 1 && (int)allBlock.Type != 2)) { continue; } string text = allBlock.GearJSON; bool flag = false; using JsonDocument jsonDocument = JsonDocument.Parse(allBlock.GearJSON); if (!jsonDocument.RootElement.TryGetProperty("Packet", out var value) || !value.TryGetProperty("Comps", out var value2)) { continue; } string text2 = "abcdefghijklmnopqrst"; for (int i = 0; i < text2.Length; i++) { if (value2.TryGetProperty(text2[i].ToString(), out var value3) && value3.TryGetProperty("v", out var value4) && value4.ValueKind == JsonValueKind.String) { string @string = value4.GetString(); Logger.Warning("Found String id: " + @string); uint id = PersistentIDManager.GetId(@string); if (id != 0) { text = new Regex("(\"v\")\\s*:\\s*(\"" + @string + "\")").Replace(text, $"\"v\":{id}"); flag = true; } } } if (flag) { Logger.Warning(allBlock.GearJSON); Logger.Warning(text); allBlock.GearJSON = text; } } } } } namespace MTFO.Ext.PartialData.DTO { internal class DataBlockDefinition { public string TypeName { get; set; } = "DataBlock?"; public uint StartFromID { get; set; } = 65535u; public IncrementMode IncrementMode { get; set; } } internal class DatapackConfig { public string PackName { get; set; } = string.Empty; public string Author { get; set; } = string.Empty; public string Namespace { get; set; } = string.Empty; } } namespace MTFO.Ext.PartialData.DataBlockTypes { internal static class DataBlockTypeManager { private static readonly List<IDataBlockType> _DataBlockCache = new List<IDataBlockType>(); private static readonly List<IDBuffer> _DataBlockIdBuffers = new List<IDBuffer>(); public static bool Initialize() { try { Assembly assembly = (from a in AppDomain.CurrentDomain.GetAssemblies() where !a.IsDynamic && a.Location.Contains("interop", StringComparison.InvariantCultureIgnoreCase) select a).First((Assembly a) => a.Location.EndsWith("Modules-ASM.dll", StringComparison.InvariantCultureIgnoreCase)); List<Type> list = new List<Type>(); foreach (Type exportedType in assembly.ExportedTypes) { if (!(exportedType == null) && !string.IsNullOrEmpty(exportedType.Namespace) && exportedType.Namespace.Equals("GameData")) { Type baseType = exportedType.BaseType; if (!(baseType == null) && baseType.Name.Equals("GameDataBlockBase`1")) { list.Add(exportedType); } } } Type typeFromHandle = typeof(DataBlockTypeWrapper<>); foreach (Type item in list) { IDataBlockType dataBlockType = (IDataBlockType)Activator.CreateInstance(typeFromHandle.MakeGenericType(item)); AssignForceChangeMethod(dataBlockType); _DataBlockCache.Add(dataBlockType); _DataBlockIdBuffers.Add(new IDBuffer()); } return true; } catch (Exception value) { Logger.Error($"Can't make cache from Modules-ASM.dll!: {value}"); return false; } } public static void AssignForceChangeMethod(IDataBlockType blockTypeCache) { switch (blockTypeCache.GetShortName().ToLower()) { case "rundown": blockTypeCache.RegisterOnChangeEvent(delegate { CM_PageRundown_New pageRundownNew = MainMenuGuiLayer.Current.PageRundownNew; pageRundownNew.m_dataIsSetup = false; try { clearIcon(pageRundownNew.m_expIconsTier1); clearIcon(pageRundownNew.m_expIconsTier2); clearIcon(pageRundownNew.m_expIconsTier3); clearIcon(pageRundownNew.m_expIconsTier4); clearIcon(pageRundownNew.m_expIconsTier5); clearIcon(pageRundownNew.m_expIconsTierExt); } catch (Exception value) { Logger.Error($"{value}"); } pageRundownNew.m_currentRundownData = GameDataBlockBase<RundownDataBlock>.GetBlock(Global.RundownIdToLoad); if (pageRundownNew.m_currentRundownData != null) { pageRundownNew.PlaceRundown(pageRundownNew.m_currentRundownData); pageRundownNew.m_dataIsSetup = true; } }); break; case "fogsettings": blockTypeCache.RegisterOnChangeEvent(delegate { if (Builder.CurrentFloor.IsBuilt) { pEnvironmentState state = EnvironmentStateManager.Current.m_stateReplicator.State; EnvironmentStateManager.Current.UpdateFogSettingsForState(state); } }); break; case "lightsettings": blockTypeCache.RegisterOnChangeEvent(delegate { if (Builder.CurrentFloor.IsBuilt) { Enumerator<LG_Zone> enumerator2 = Builder.CurrentFloor.allZones.GetEnumerator(); while (enumerator2.MoveNext()) { LG_Zone current2 = enumerator2.Current; Enumerator<AIG_CourseNode> enumerator3 = current2.m_courseNodes.GetEnumerator(); while (enumerator3.MoveNext()) { AIG_CourseNode current3 = enumerator3.Current; LG_BuildZoneLightsJob.ApplyLightSettings(0u, current3.m_lightsInNode, current2.m_lightSettings, false); } } } }); break; } static void clearIcon(List<CM_ExpeditionIcon_New> tier) { if (tier != null) { Enumerator<CM_ExpeditionIcon_New> enumerator = tier.GetEnumerator(); while (enumerator.MoveNext()) { CM_ExpeditionIcon_New current = enumerator.Current; if ((Object)(object)((Component)current).gameObject != (Object)null) { Object.Destroy((Object)(object)((Component)current).gameObject); } } } } } public static bool TryFindCache(string blockTypeName, out IDataBlockType cache) { int index = GetIndex(blockTypeName); if (index != -1) { cache = _DataBlockCache[index]; return true; } cache = null; return false; } public static bool TryGetNextID(string blockTypeName, out uint id) { int index = GetIndex(blockTypeName); if (index != -1) { id = _DataBlockIdBuffers[index].GetNext(); return true; } id = 0u; return false; } public static void SetIDBuffer(string blockTypeName, uint id) { int index = GetIndex(blockTypeName); if (index != -1) { _DataBlockIdBuffers[index].CurrentID = id; } } public static void SetIDBuffer(string blockTypeName, uint id, IncrementMode mode) { int index = GetIndex(blockTypeName); if (index != -1) { IDBuffer iDBuffer = _DataBlockIdBuffers[index]; iDBuffer.CurrentID = id; iDBuffer.IncrementMode = mode; } } private static int GetIndex(string blockTypeName) { blockTypeName = GetBlockName(blockTypeName); return _DataBlockCache.FindIndex((IDataBlockType x) => x.GetShortName().Equals(blockTypeName, StringComparison.OrdinalIgnoreCase)); } public static string GetBlockName(string blockTypeName) { blockTypeName = blockTypeName.Trim(); if (blockTypeName.EndsWith("DataBlock")) { string text = blockTypeName; blockTypeName = text.Substring(0, text.Length - 9); } return blockTypeName; } } internal class DataBlockTypeWrapper<T> : IDataBlockType where T : GameDataBlockBase<T> { public Action OnForceChange; public string FullName { get; private set; } public string ShortenName { get; private set; } public DataBlockTypeWrapper() { FullName = typeof(T).Name.Trim(); ShortenName = FullName.Replace("DataBlock", ""); } public void OnChanged() { OnForceChange?.Invoke(); } public void AddBlock(T block) { T block2 = GameDataBlockBase<T>.GetBlock(((GameDataBlockBase<T>)block).persistentID); if (block2 != null) { CopyProperties(block, block2); Logger.Warning($"Replaced Block: {((GameDataBlockBase<T>)block2).persistentID}, {((GameDataBlockBase<T>)block2).name}"); } else { GameDataBlockBase<T>.AddBlock(block, -1); Logger.Log($"Added Block: {((GameDataBlockBase<T>)block).persistentID}, {((GameDataBlockBase<T>)block).name}"); } } public void AddJsonBlock(string json) { try { switch (JsonDocument.Parse(json, new JsonDocumentOptions { CommentHandling = JsonCommentHandling.Skip }).RootElement.ValueKind) { case JsonValueKind.Array: { T[] array = (T[])JSON.Deserialize(json, typeof(T).MakeArrayType()); foreach (T block2 in array) { AddBlock(block2); } break; } case JsonValueKind.Object: { T block = (T)JSON.Deserialize(json, typeof(T)); AddBlock(block); break; } } } catch (Exception value) { Logger.Error($"Error While Adding Block: {value}"); } } public void DoSaveToDisk(string fullPath) { string filePathFull = GameDataBlockBase<T>.m_filePathFull; GameDataBlockBase<T>.m_filePathFull = fullPath; GameDataBlockBase<T>.DoSaveToDisk(false, false, true); GameDataBlockBase<T>.m_filePathFull = filePathFull; } private static object CopyProperties(object source, object target) { PropertyInfo[] properties = source.GetType().GetProperties(); foreach (PropertyInfo sourceProp in properties) { Type propertyType = sourceProp.PropertyType; PropertyInfo propertyInfo = target.GetType().GetProperties().FirstOrDefault((PropertyInfo x) => x.Name == sourceProp.Name && x.PropertyType == sourceProp.PropertyType && x.CanWrite); if (propertyInfo != null && !sourceProp.Name.Contains("_k__BackingField")) { if (propertyType == typeof(IntPtr)) { Logger.Error("Pointer has detected on CopyProperties!!!!"); } else { propertyInfo.SetValue(target, sourceProp.GetValue(source)); } } } return target; } public string GetShortName() { return ShortenName; } public string GetFullName() { return FullName; } public void RegisterOnChangeEvent(Action onChanged) { OnForceChange = (Action)Delegate.Combine(OnForceChange, onChanged); } } internal interface IDataBlockType { string GetShortName(); string GetFullName(); void DoSaveToDisk(string fullPath); void AddJsonBlock(string json); void OnChanged(); void RegisterOnChangeEvent(Action onChanged); } }
plugins/net6/NoDustParticles.dll
Decompiled a month agousing System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using HarmonyLib; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")] [assembly: AssemblyCompany("NoDustParticles")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("NoDustParticles")] [assembly: AssemblyTitle("NoDustParticles")] [assembly: AssemblyVersion("1.0.0.0")] namespace NoDustParticles; internal class DustPatches { [HarmonyPatch(typeof(AmbientParticles), "Update")] [HarmonyPrefix] private static bool SkipParticles() { return false; } } [BepInPlugin("com.Untilted.NoDustParticles", "NoDustParticles", "1.0.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Loader : BasePlugin { public const string MODNAME = "NoDustParticles"; public const string AUTHOR = "Untilted"; public const string GUID = "com.Untilted.NoDustParticles"; public const string VERSION = "1.0.0"; public static ManualLogSource Logger; public override void Load() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) Logger = ((BasePlugin)this).Log; ((BasePlugin)this).Log.LogMessage((object)"Loading NoDustParticles"); new Harmony("NoDustParticles").PatchAll(typeof(DustPatches)); ((BasePlugin)this).Log.LogMessage((object)"Loaded NoDustParticles"); } }
plugins/net6/ScanPosOverride.dll
Decompiled a month agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.Json; using System.Text.Json.Serialization; using System.Threading; using AIGraph; using Agents; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Core.Logging.Interpolation; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using ChainedPuzzles; using GTFO.API; using GTFO.API.Extensions; using GTFO.API.Utilities; using GameData; using HarmonyLib; using Il2CppInterop.Runtime.Injection; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.InteropTypes.Arrays; using Il2CppSystem; using Il2CppSystem.Collections.Generic; using Il2CppSystem.Text; using LevelGeneration; using Localization; using MTFO.API; using Microsoft.CodeAnalysis; using Player; using ScanPosOverride.Component; using ScanPosOverride.JSON; using ScanPosOverride.Managers; using ScanPosOverride.PuzzleOverrideData; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("ScanPosOverride")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("ScanPosOverride")] [assembly: AssemblyTitle("ScanPosOverride")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ScanPosOverride { internal static class SPOLogger { private static readonly ManualLogSource logger = Logger.CreateLogSource("ScanPosOverride"); public static void Log(string format, params object[] args) { Log(string.Format(format, args)); } public static void Log(string str) { if (logger != null) { logger.Log((LogLevel)8, (object)str); } } public static void Warning(string format, params object[] args) { Warning(string.Format(format, args)); } public static void Warning(string str) { if (logger != null) { logger.Log((LogLevel)4, (object)str); } } public static void Error(string format, params object[] args) { Error(string.Format(format, args)); } public static void Error(string str) { if (logger != null) { logger.Log((LogLevel)2, (object)str); } } public static void Debug(string format, params object[] args) { Debug(string.Format(format, args)); } public static void Debug(string str) { if (logger != null) { logger.Log((LogLevel)32, (object)str); } } public static void Log(BepInExDebugLogInterpolatedStringHandler logHandler) { logger.LogDebug(logHandler); } } [BepInPlugin("ScanPositionOverride", "ScanPositionOverride", "1.6.5")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] internal sealed class Plugin : BasePlugin { [CompilerGenerated] private static class <>O { public static LiveEditEventHandler <0>__LiveEdit_FileChanged; } private static Dictionary<uint, Dictionary<uint, PuzzleOverride>> PuzzleOverrides = new Dictionary<uint, Dictionary<uint, PuzzleOverride>>(); public static readonly string OVERRIDE_SCAN_POS_PATH = Path.Combine(MTFOPathAPI.CustomPath, "ScanPositionOverrides"); private static LiveEditListener listener = null; private static Harmony m_Harmony = null; public override void Load() { //IL_01f5: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Expected O, but got Unknown //IL_01e0: Unknown result type (might be due to invalid IL or missing references) //IL_01e5: Unknown result type (might be due to invalid IL or missing references) //IL_01eb: Expected O, but got Unknown SPOLogger.Error(OVERRIDE_SCAN_POS_PATH); if (!Directory.Exists(OVERRIDE_SCAN_POS_PATH)) { Directory.CreateDirectory(OVERRIDE_SCAN_POS_PATH); StreamWriter streamWriter = File.CreateText(Path.Combine(OVERRIDE_SCAN_POS_PATH, "Template.json")); streamWriter.WriteLine(Json.Serialize(new PuzzleOverrideJsonFile())); streamWriter.Flush(); streamWriter.Close(); return; } foreach (string item in Directory.EnumerateFiles(OVERRIDE_SCAN_POS_PATH, "*.json", SearchOption.AllDirectories)) { Json.Load<PuzzleOverrideJsonFile>(item, out var config); if (PuzzleOverrides.ContainsKey(config.MainLevelLayout)) { SPOLogger.Warning("Duplicate MainLevelLayout {0}, won't load.", config.MainLevelLayout); continue; } Dictionary<uint, PuzzleOverride> dictionary = new Dictionary<uint, PuzzleOverride>(); foreach (PuzzleOverride puzzle in config.Puzzles) { if (dictionary.ContainsKey(puzzle.Index)) { SPOLogger.Error("Duplicate Puzzle Override found. MainLevelLayout {0}, Index {1}.", config.MainLevelLayout, puzzle.Index); continue; } puzzle.EventsOnBioscanProgress.RemoveAll((BioscanProgressEvent e) => e.Progress <= 0f); puzzle.EventsOnBioscanProgress.Sort((BioscanProgressEvent e1, BioscanProgressEvent e2) => Mathf.RoundToInt(e1.Progress - e2.Progress)); dictionary.Add(puzzle.Index, puzzle); } PuzzleOverrides.Add(config.MainLevelLayout, dictionary); } listener = LiveEdit.CreateListener(OVERRIDE_SCAN_POS_PATH, "*.json", true); LiveEditListener obj = listener; object obj2 = <>O.<0>__LiveEdit_FileChanged; if (obj2 == null) { LiveEditEventHandler val = LiveEdit_FileChanged; <>O.<0>__LiveEdit_FileChanged = val; obj2 = (object)val; } obj.FileChanged += (LiveEditEventHandler)obj2; m_Harmony = new Harmony("ScanPosOverride.Patches"); m_Harmony.PatchAll(); } private static void LiveEdit_FileChanged(LiveEditEventArgs e) { SPOLogger.Warning("LiveEdit File Changed: " + e.FullPath + "."); LiveEdit.TryReadFileContent(e.FullPath, (Action<string>)delegate(string content) { PuzzleOverrideJsonFile puzzleOverrideJsonFile = Json.Deserialize<PuzzleOverrideJsonFile>(content); if (!PuzzleOverrides.ContainsKey(puzzleOverrideJsonFile.MainLevelLayout)) { SPOLogger.Warning("MainLevelLayout not found, which is now not supported. Will not replace."); } else { Dictionary<uint, PuzzleOverride> dictionary = PuzzleOverrides[puzzleOverrideJsonFile.MainLevelLayout]; dictionary.Clear(); foreach (PuzzleOverride puzzle in puzzleOverrideJsonFile.Puzzles) { if (dictionary.ContainsKey(puzzle.Index)) { SPOLogger.Error("Duplicate Puzzle Override found. MainLevelLayout {0}, Index {1}.", puzzleOverrideJsonFile.MainLevelLayout, puzzle.Index); } else { puzzle.EventsOnBioscanProgress.Sort((BioscanProgressEvent e1, BioscanProgressEvent e2) => Mathf.RoundToInt(e1.Progress - e2.Progress)); dictionary.Add(puzzle.Index, puzzle); } } SPOLogger.Warning("Replaced Override Puzzle with MainLevelLayout {0}", puzzleOverrideJsonFile.MainLevelLayout); } }); } internal static PuzzleOverride GetOverride(uint mainLevelLayout, uint puzzleIndex) { if (!PuzzleOverrides.ContainsKey(mainLevelLayout)) { return null; } Dictionary<uint, PuzzleOverride> dictionary = PuzzleOverrides[mainLevelLayout]; if (!dictionary.ContainsKey(puzzleIndex)) { return null; } return dictionary[puzzleIndex]; } } } namespace ScanPosOverride.PuzzleOverrideData { internal sealed class PuzzleOverrideJsonFile { public uint MainLevelLayout { get; set; } public List<PuzzleOverride> Puzzles { get; set; } = new List<PuzzleOverride> { new PuzzleOverride() }; } public class BioscanProgressEvent { public float Progress { get; set; } = -1f; public List<WardenObjectiveEventData> Events { get; set; } = new List<WardenObjectiveEventData>(); } public class ClusterProgressEvent { public int Count { get; set; } = -1; public List<WardenObjectiveEventData> Events { get; set; } = new List<WardenObjectiveEventData>(); } public class PuzzleOverride { public uint Index { get; set; } public Vec3 Position { get; set; } = new Vec3(); public Vec3 Rotation { get; set; } = new Vec3(); public bool HideSpline { get; set; } public Vec3 PrevPosOverride { get; set; } = new Vec3(); public uint PrevPosOverrideIndex { get; set; } public bool ConcurrentCluster { get; set; } public float TMoveSpeedMulti { get; set; } = -1f; public List<BioscanProgressEvent> EventsOnBioscanProgress { get; set; } = new List<BioscanProgressEvent> { new BioscanProgressEvent() }; public List<ClusterProgressEvent> EventsOnClusterProgress { get; set; } = new List<ClusterProgressEvent> { new ClusterProgressEvent() }; public List<Vec3> TPositions { get; set; } = new List<Vec3> { new Vec3() }; public List<int> RequiredItemsIndices { get; set; } = new List<int> { 0 }; public List<WardenObjectiveEventData> EventsOnPuzzleSolved { get; set; } = new List<WardenObjectiveEventData>(); } public class Vec3 { public float x { get; set; } public float y { get; set; } public float z { get; set; } public Vector3 ToVector3() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) return new Vector3(x, y, z); } public Quaternion ToQuaternion() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) return Quaternion.Euler(x, y, z); } } } namespace ScanPosOverride.Patches { [HarmonyPatch] internal class Patch_CP_Bioscan_Core_OnSyncStateChange { private static Dictionary<IntPtr, int> EOPIndex; static Patch_CP_Bioscan_Core_OnSyncStateChange() { EOPIndex = new Dictionary<IntPtr, int>(); LevelAPI.OnBuildStart += EOPIndex.Clear; LevelAPI.OnLevelCleanup += EOPIndex.Clear; } [HarmonyPostfix] [HarmonyPatch(typeof(CP_Bioscan_Core), "OnSyncStateChange")] private static void Post_OnSyncStateChanged_CheckEOPAndEventsOnPuzzleSolved(CP_Bioscan_Core __instance, float progress, eBioscanStatus status, List<PlayerAgent> playersInScan, bool isDropinState) { //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Invalid comparison between Unknown and I4 uint bioscanCoreOverrideIndex = PuzzleOverrideManager.Current.GetBioscanCoreOverrideIndex(__instance); PuzzleOverride def = Plugin.GetOverride(PuzzleOverrideManager.MainLevelLayout, bioscanCoreOverrideIndex); if (def != null) { if (def.EventsOnBioscanProgress.Count > 0) { CheckBioscanEventsOnProgress(); } if ((int)status == 4 && !isDropinState && def.EventsOnPuzzleSolved.Count > 0) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(ListExtensions.ToIl2Cpp<WardenObjectiveEventData>(def.EventsOnPuzzleSolved), (eWardenObjectiveEventTrigger)0, true, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null); } } void CheckBioscanEventsOnProgress() { if (!EOPIndex.ContainsKey(((Il2CppObjectBase)__instance).Pointer)) { EOPIndex[((Il2CppObjectBase)__instance).Pointer] = 0; } int i = EOPIndex[((Il2CppObjectBase)__instance).Pointer]; if (isDropinState) { for (; i < def.EventsOnBioscanProgress.Count && !(def.EventsOnBioscanProgress[i].Progress > progress); i++) { } } else if (i < def.EventsOnBioscanProgress.Count && def.EventsOnBioscanProgress[i].Progress < progress) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(ListExtensions.ToIl2Cpp<WardenObjectiveEventData>(def.EventsOnBioscanProgress[i].Events), (eWardenObjectiveEventTrigger)0, true, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null); EOPIndex[((Il2CppObjectBase)__instance).Pointer] = i + 1; } } } [HarmonyPostfix] [HarmonyPatch(typeof(CP_Bioscan_Core), "OnSyncStateChange")] private static void Post_OnSyncStateChanged_CheckReqItemAndConcurrentCluster(CP_Bioscan_Core __instance, float progress, eBioscanStatus status, List<PlayerAgent> playersInScan, bool isDropinState) { //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Invalid comparison between Unknown and I4 //IL_002f: 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_0077: Invalid comparison between Unknown and I4 //IL_0128: Unknown result type (might be due to invalid IL or missing references) //IL_0145: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Invalid comparison between Unknown and I4 //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Invalid comparison between Unknown and I4 //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_01d1: Unknown result type (might be due to invalid IL or missing references) //IL_01d7: Invalid comparison between Unknown and I4 //IL_01bb: Unknown result type (might be due to invalid IL or missing references) //IL_01c0: Unknown result type (might be due to invalid IL or missing references) //IL_0334: Unknown result type (might be due to invalid IL or missing references) //IL_02c0: Unknown result type (might be due to invalid IL or missing references) //IL_0223: Unknown result type (might be due to invalid IL or missing references) //IL_0228: Unknown result type (might be due to invalid IL or missing references) //IL_022a: Unknown result type (might be due to invalid IL or missing references) //IL_022f: Unknown result type (might be due to invalid IL or missing references) //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) bool flag = PlayerScannerManager.Current.IsConcurrentCluster(__instance); if (flag && __instance.m_reqItemsEnabled) { SPOLogger.Warning($"OnSyncStateChange: status - {status}, playersInScan - {playersInScan.Count}, progress: {progress}"); } if ((int)status != 3) { if (flag) { if ((int)status == 4) { CP_Cluster_Core val = ((Il2CppObjectBase)__instance.Owner).TryCast<CP_Cluster_Core>(); if ((Object)(object)val == (Object)null) { SPOLogger.Error("Cannot find parent cluster core! The concurrent cluster may fail!"); } else { PlayerScannerManager.Current.CompleteConcurrentCluster(val); } } else { PlayerScannerManager.Current.CCShouldProgress(__instance, IsThisScanShouldProgress: false); } } if (__instance.m_reqItemsEnabled) { __instance.m_graphics.SetColorMode((eChainedPuzzleGraphicsColorMode)((!__instance.m_hasAlarm) ? 1 : 4)); } } else { if (!__instance.IsMovable && !flag && !__instance.m_reqItemsEnabled) { return; } CP_PlayerScanner cacheScanner = PlayerScannerManager.Current.GetCacheScanner(__instance); if ((Object)(object)cacheScanner == (Object)null) { return; } int count = playersInScan.Count; List<PlayerAgent> playerAgentsInLevel = PlayerManager.PlayerAgentsInLevel; float num = 0f; float[] cacheOriginalScanSpeed = PlayerScannerManager.Current.GetCacheOriginalScanSpeed(__instance); if ((int)__instance.m_playerScanner.ScanPlayersRequired == 0) { num = ((count <= 0) ? 0f : cacheOriginalScanSpeed[count - 1]); } else if (((int)cacheScanner.m_playerRequirement == 1 && count == playerAgentsInLevel.Count) || ((int)cacheScanner.m_playerRequirement == 2 && count == 1)) { num = cacheOriginalScanSpeed[0]; } bool flag2 = num > 0f; if (flag2 && cacheScanner.m_reqItemsEnabled) { for (int i = 0; i < ((Il2CppArrayBase<iWardenObjectiveItem>)(object)cacheScanner.m_reqItems).Length; i++) { Vector3 val2 = Vector3.zero; if ((int)((Il2CppArrayBase<iWardenObjectiveItem>)(object)cacheScanner.m_reqItems)[i].PickupItemStatus == 0) { val2 = ((Il2CppArrayBase<iWardenObjectiveItem>)(object)cacheScanner.m_reqItems)[i].transform.position; } else if ((int)((Il2CppArrayBase<iWardenObjectiveItem>)(object)cacheScanner.m_reqItems)[i].PickupItemStatus == 1) { if ((Object)(object)((Il2CppArrayBase<iWardenObjectiveItem>)(object)cacheScanner.m_reqItems)[i].PickedUpByPlayer != (Object)null) { val2 = ((Agent)((Il2CppArrayBase<iWardenObjectiveItem>)(object)cacheScanner.m_reqItems)[i].PickedUpByPlayer).Position; } else { Debug.LogError(Object.op_Implicit("Playerscanner is looking for an item that has ePickupItemStatus.PickedUp but null player, how come!?")); } } Vector3 val3 = ((Component)cacheScanner).transform.position - val2; if (((Vector3)(ref val3)).sqrMagnitude >= cacheScanner.m_scanRadiusSqr) { flag2 = false; break; } } } if (flag) { if (flag2) { flag2 = PlayerScannerManager.Current.CCShouldProgress(__instance, IsThisScanShouldProgress: true); } else { PlayerScannerManager.Current.CCShouldProgress(__instance, IsThisScanShouldProgress: false); } } if (flag2) { if (flag) { CP_Cluster_Core parent = ((Il2CppObjectBase)__instance.Owner).Cast<CP_Cluster_Core>(); PlayerScannerManager.Current.RestoreCCScanSpeed(parent); } if (__instance.IsMovable) { __instance.m_movingComp.ResumeMovement(); } if (cacheScanner.m_reqItemsEnabled) { if ((int)cacheScanner.m_playerRequirement == 0) { ((Il2CppArrayBase<float>)(object)cacheScanner.m_scanSpeeds)[0] = ((count > 0) ? cacheOriginalScanSpeed[count - 1] : 0f); } __instance.m_graphics.SetColorMode((eChainedPuzzleGraphicsColorMode)(__instance.m_hasAlarm ? 5 : 2)); } return; } if (flag) { CP_Cluster_Core parent2 = ((Il2CppObjectBase)__instance.Owner).Cast<CP_Cluster_Core>(); PlayerScannerManager.Current.ZeroCCScanSpeed(parent2); } if (__instance.IsMovable) { __instance.m_movingComp.PauseMovement(); } if (cacheScanner.m_reqItemsEnabled) { if ((int)cacheScanner.m_playerRequirement == 0) { PlayerScannerManager.Current.GetCacheOriginalScanSpeed(__instance); ((Il2CppArrayBase<float>)(object)cacheScanner.m_scanSpeeds)[0] = 0f; } __instance.m_graphics.SetColorMode((eChainedPuzzleGraphicsColorMode)((!__instance.m_hasAlarm) ? 1 : 4)); } } } } [HarmonyPatch] internal class Patch_CP_Bioscan_Core_Setup { [HarmonyPrefix] [HarmonyPatch(typeof(CP_Bioscan_Core), "Setup")] private static void Pre_CP_Bioscan_Core_Setup(CP_Bioscan_Core __instance, int puzzleIndex, iChainedPuzzleOwner owner, ref Vector3 prevPuzzlePos, ref bool revealWithHoloPath, ref bool onlyShowHUDWhenPlayerIsClose) { //IL_021d: Unknown result type (might be due to invalid IL or missing references) //IL_0222: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0357: 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_0235: Unknown result type (might be due to invalid IL or missing references) //IL_023a: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0389: Unknown result type (might be due to invalid IL or missing references) //IL_038e: Unknown result type (might be due to invalid IL or missing references) //IL_0291: Unknown result type (might be due to invalid IL or missing references) //IL_03bd: Unknown result type (might be due to invalid IL or missing references) //IL_03c8: Unknown result type (might be due to invalid IL or missing references) //IL_03a0: Unknown result type (might be due to invalid IL or missing references) //IL_03a5: Unknown result type (might be due to invalid IL or missing references) //IL_018a: Unknown result type (might be due to invalid IL or missing references) //IL_018f: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_0296: Unknown result type (might be due to invalid IL or missing references) //IL_0298: Unknown result type (might be due to invalid IL or missing references) //IL_029a: Unknown result type (might be due to invalid IL or missing references) //IL_028a: Unknown result type (might be due to invalid IL or missing references) //IL_027e: Unknown result type (might be due to invalid IL or missing references) //IL_01fd: Unknown result type (might be due to invalid IL or missing references) //IL_0202: 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_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_0346: Unknown result type (might be due to invalid IL or missing references) //IL_0348: Unknown result type (might be due to invalid IL or missing references) //IL_0339: Unknown result type (might be due to invalid IL or missing references) //IL_033e: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_047c: Unknown result type (might be due to invalid IL or missing references) //IL_049f: Unknown result type (might be due to invalid IL or missing references) ChainedPuzzleInstance val = ((Il2CppObjectBase)owner).TryCast<ChainedPuzzleInstance>(); uint num = PuzzleOverrideManager.Current.Register(__instance); PuzzleOverride @override = Plugin.GetOverride(PuzzleOverrideManager.MainLevelLayout, num); if ((Object)(object)val != (Object)null) { bool flag = false; if (@override != null) { if (@override.PrevPosOverride.ToVector3() != Vector3.zero) { prevPuzzlePos = @override.PrevPosOverride.ToVector3(); flag = true; } else if (@override.PrevPosOverrideIndex != 0) { CP_Bioscan_Core bioscanCore = PuzzleOverrideManager.Current.GetBioscanCore(@override.PrevPosOverrideIndex); ? val2; if (bioscanCore == null) { CP_Cluster_Core clusterCore = PuzzleOverrideManager.Current.GetClusterCore(@override.PrevPosOverrideIndex); val2 = ((clusterCore != null) ? ((Component)clusterCore).transform.position : Vector3.zero); } else { val2 = bioscanCore.m_position; } Vector3 val3 = (Vector3)val2; if (val3 == Vector3.zero) { SPOLogger.Error($"PuzzleOverrideIndex: {num} - trying to use 'PrevPosOverrideIndex' ({@override.PrevPosOverrideIndex}) but the puzzle is not found."); SPOLogger.Error($"The puzzle is probably yet registered. NOTE: 'PrevPosOverrideIndex' could only be a integer that is less than PuzzleOverrideIndex({num})"); flag = false; } else { prevPuzzlePos = val3; flag = true; } } } if (!flag && puzzleIndex != 0) { CP_Bioscan_Core val4 = ((Il2CppObjectBase)((Il2CppArrayBase<iChainedPuzzleCore>)(object)val.m_chainedPuzzleCores)[puzzleIndex - 1]).TryCast<CP_Bioscan_Core>(); if ((Object)(object)val4 != (Object)null) { prevPuzzlePos = ((Component)val4).transform.position; } else { CP_Cluster_Core val5 = ((Il2CppObjectBase)((Il2CppArrayBase<iChainedPuzzleCore>)(object)val.m_chainedPuzzleCores)[puzzleIndex - 1]).TryCast<CP_Cluster_Core>(); if ((Object)(object)val5 == (Object)null) { SPOLogger.Error($"Cannot cast m_chainedPuzzleCores[{puzzleIndex - 1}] to neither CP_Bioscan_Core or CP_Cluster_Core! WTF???"); } else { prevPuzzlePos = ((Component)val5).transform.position; } } } } else { CP_Cluster_Core val6 = ((Il2CppObjectBase)owner).Cast<CP_Cluster_Core>(); if (@override != null && @override.PrevPosOverride.ToVector3() != Vector3.zero) { prevPuzzlePos = @override.PrevPosOverride.ToVector3(); } else if (@override != null && @override.PrevPosOverrideIndex != 0) { CP_Bioscan_Core bioscanCore2 = PuzzleOverrideManager.Current.GetBioscanCore(@override.PrevPosOverrideIndex); ? val7; if (bioscanCore2 == null) { CP_Cluster_Core clusterCore2 = PuzzleOverrideManager.Current.GetClusterCore(@override.PrevPosOverrideIndex); val7 = ((clusterCore2 != null) ? ((Component)clusterCore2).transform.position : Vector3.zero); } else { val7 = bioscanCore2.m_position; } Vector3 val8 = (Vector3)val7; if (val8 == Vector3.zero) { SPOLogger.Error($"PuzzleOverrideIndex: {num} - trying to use 'PrevPosOverrideIndex' ({@override.PrevPosOverrideIndex}) but the puzzle is not found."); SPOLogger.Error($"The puzzle is probably yet registered. NOTE: 'PrevPosOverrideIndex' could only be a integer that is less than PuzzleOverrideIndex({num})"); prevPuzzlePos = ((Component)val6).transform.position; } else { prevPuzzlePos = val8; } } else { prevPuzzlePos = ((Component)val6).transform.position; } val = ((Il2CppObjectBase)val6.m_owner).Cast<ChainedPuzzleInstance>(); if (val.Data.OnlyShowHUDWhenPlayerIsClose) { onlyShowHUDWhenPlayerIsClose = true; } } if (@override != null) { if (@override.Position.ToVector3() != Vector3.zero || @override.Rotation.ToVector3() != Vector3.zero) { ((Component)__instance).transform.SetPositionAndRotation(@override.Position.ToVector3(), @override.Rotation.ToQuaternion()); } if (@override.HideSpline || ((Object)(object)__instance.m_movingComp != (Object)null && __instance.m_movingComp.IsMoveConfigured)) { revealWithHoloPath = false; } if (@override.RequiredItemsIndices != null && @override.RequiredItemsIndices.Count > 0) { PuzzleReqItemManager.Current.QueueForAddingReqItems(__instance, @override.RequiredItemsIndices); } SPOLogger.Warning("Overriding CP_Bioscan_Core." + (((Object)(object)val == (Object)null) ? "" : $"Zone {val.m_sourceArea.m_zone.Alias}, Layer {val.m_sourceArea.m_zone.Layer.m_type}, Dim {val.m_sourceArea.m_zone.DimensionIndex}")); } } } [HarmonyPatch] internal class Patch_ChainedPuzzleInstance_SetupMovement { [HarmonyPrefix] [HarmonyPatch(typeof(ChainedPuzzleInstance), "SetupMovement")] private static bool Pre_SetupMovement(ChainedPuzzleInstance __instance, GameObject gameObject) { //IL_00b3: Unknown result type (might be due to invalid IL or missing references) iChainedPuzzleMovable movingComp = gameObject.GetComponent<iChainedPuzzleMovable>(); if (movingComp == null || !movingComp.UsingStaticBioscanPoints) { return true; } CP_BasicMovable val = ((Il2CppObjectBase)movingComp).Cast<CP_BasicMovable>(); CP_Bioscan_Core core = ((Il2CppObjectBase)gameObject.GetComponent<iChainedPuzzleCore>()).Cast<CP_Bioscan_Core>(); uint bioscanCoreOverrideIndex = PuzzleOverrideManager.Current.GetBioscanCoreOverrideIndex(core); if (bioscanCoreOverrideIndex == 0) { SPOLogger.Error("Did not find registered movable override for this movable scan."); return true; } PuzzleOverride @override = Plugin.GetOverride(PuzzleOverrideManager.MainLevelLayout, bioscanCoreOverrideIndex); if (@override == null || @override.TPositions.Count < 1) { SPOLogger.Error("No Override for this T-Scan, falling back to vanilla impl."); return true; } @override.TPositions.ForEach(delegate(Vec3 pos) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) movingComp.ScanPositions.Add(pos.ToVector3()); }); gameObject.transform.position = @override.TPositions[0].ToVector3(); val.m_amountOfPositions = @override.TPositions.Count; if (@override.TMoveSpeedMulti > 0f) { val.m_movementSpeed *= @override.TMoveSpeedMulti; } SPOLogger.Warning("Overriding T-Scan pos!"); return false; } } [HarmonyPatch] internal class Patch_CarryItemPickup_Core_Setup { [HarmonyPostfix] [HarmonyPatch(typeof(CarryItemPickup_Core), "Setup")] private static void Post_CarryItemPickup_Core_Setup(CarryItemPickup_Core __instance) { PuzzleReqItemManager.Current.Register(__instance); } } [HarmonyPatch] internal static class Patch_CP_Cluster_Core_OnSyncStateChaged { [HarmonyPostfix] [HarmonyPatch(typeof(CP_Cluster_Core), "OnSyncStateChange")] private static void Post_CheckEventsOnPuzzleSolved(CP_Cluster_Core __instance, eClusterStatus newStatus, bool isDropinState) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 if ((int)newStatus == 3) { uint clusterCoreOverrideIndex = PuzzleOverrideManager.Current.GetClusterCoreOverrideIndex(__instance); PuzzleOverride @override = Plugin.GetOverride(PuzzleOverrideManager.MainLevelLayout, clusterCoreOverrideIndex); if (@override != null && @override.EventsOnPuzzleSolved.Count > 0 && !isDropinState) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(ListExtensions.ToIl2Cpp<WardenObjectiveEventData>(@override.EventsOnPuzzleSolved), (eWardenObjectiveEventTrigger)0, true, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null); } } } } [HarmonyPatch] internal class Patch_CP_Cluster_Core_Setup { [HarmonyPrefix] [HarmonyPatch(typeof(CP_Cluster_Core), "Setup")] private static void Pre_CP_Cluster_Core_Setup(CP_Cluster_Core __instance, int puzzleIndex, iChainedPuzzleOwner owner, ref Vector3 prevPuzzlePos, ref bool revealWithHoloPath) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Unknown result type (might be due to invalid IL or missing references) //IL_0204: Unknown result type (might be due to invalid IL or missing references) //IL_0233: Unknown result type (might be due to invalid IL or missing references) //IL_023e: Unknown result type (might be due to invalid IL or missing references) //IL_0216: Unknown result type (might be due to invalid IL or missing references) //IL_021b: Unknown result type (might be due to invalid IL or missing references) //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_01eb: Unknown result type (might be due to invalid IL or missing references) //IL_01f0: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: 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_0096: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0142: 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) uint num = PuzzleOverrideManager.Current.Register(__instance); PuzzleOverride @override = Plugin.GetOverride(PuzzleOverrideManager.MainLevelLayout, num); ChainedPuzzleInstance val = ((Il2CppObjectBase)owner).Cast<ChainedPuzzleInstance>(); bool flag = false; if (@override != null) { if (@override.PrevPosOverride.ToVector3() != Vector3.zero) { prevPuzzlePos = @override.PrevPosOverride.ToVector3(); flag = true; } else if (@override.PrevPosOverrideIndex != 0) { CP_Bioscan_Core bioscanCore = PuzzleOverrideManager.Current.GetBioscanCore(@override.PrevPosOverrideIndex); ? val2; if (bioscanCore == null) { CP_Cluster_Core clusterCore = PuzzleOverrideManager.Current.GetClusterCore(@override.PrevPosOverrideIndex); val2 = ((clusterCore != null) ? ((Component)clusterCore).transform.position : Vector3.zero); } else { val2 = bioscanCore.m_position; } Vector3 val3 = (Vector3)val2; if (val3 == Vector3.zero) { SPOLogger.Error($"PuzzleOverrideIndex: {num} - trying to use 'PrevPosOverrideIndex' ({@override.PrevPosOverrideIndex}) but the puzzle is not found."); SPOLogger.Error($"The puzzle is probably yet registered. NOTE: 'PrevPosOverrideIndex' could only be a integer that is less than PuzzleOverrideIndex({num})"); flag = false; } else { prevPuzzlePos = val3; flag = true; } } } if (!flag && puzzleIndex != 0) { CP_Bioscan_Core val4 = ((Il2CppObjectBase)((Il2CppArrayBase<iChainedPuzzleCore>)(object)val.m_chainedPuzzleCores)[puzzleIndex - 1]).TryCast<CP_Bioscan_Core>(); if ((Object)(object)val4 != (Object)null) { prevPuzzlePos = ((Component)val4).transform.position; } else { CP_Cluster_Core val5 = ((Il2CppObjectBase)((Il2CppArrayBase<iChainedPuzzleCore>)(object)val.m_chainedPuzzleCores)[puzzleIndex - 1]).TryCast<CP_Cluster_Core>(); if ((Object)(object)val5 == (Object)null) { SPOLogger.Error($"Cannot cast m_chainedPuzzleCores[{puzzleIndex - 1}] to neither CP_Bioscan_Core or CP_Cluster_Core! WTF???"); } else { prevPuzzlePos = ((Component)val5).transform.position; } } } if (@override != null) { if (@override.Position.ToVector3() != Vector3.zero || @override.Rotation.ToVector3() != Vector3.zero) { ((Component)__instance).transform.SetPositionAndRotation(@override.Position.ToVector3(), @override.Rotation.ToQuaternion()); } if (@override.RequiredItemsIndices != null && @override.RequiredItemsIndices.Count > 0) { PuzzleReqItemManager.Current.QueueForAddingReqItems(__instance, @override.RequiredItemsIndices); } if (@override.HideSpline) { revealWithHoloPath = false; } SPOLogger.Warning("Overriding CP_Cluster_Core!"); } } [HarmonyPostfix] [HarmonyPatch(typeof(CP_Cluster_Core), "Setup")] private static void Post_CP_Cluster_Core_Setup(CP_Cluster_Core __instance) { ChainedPuzzleInstance val = ((Il2CppObjectBase)__instance.m_owner).Cast<ChainedPuzzleInstance>(); foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores) { if (item.IsMovable && PuzzleOverrideManager.Current.GetBioscanCoreOverrideIndex(((Il2CppObjectBase)item).Pointer) != 0) { val.SetupMovement(((Component)((Il2CppObjectBase)item).Cast<CP_Bioscan_Core>()).gameObject, val.m_sourceArea); } } uint clusterCoreOverrideIndex = PuzzleOverrideManager.Current.GetClusterCoreOverrideIndex(__instance); if (clusterCoreOverrideIndex == 0) { return; } PuzzleOverride def = Plugin.GetOverride(PuzzleOverrideManager.MainLevelLayout, clusterCoreOverrideIndex); if (def == null) { return; } if (def.ConcurrentCluster) { if (2 <= ((Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores).Count && ((Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores).Count <= 4) { CP_Cluster_Hud val2 = ((Il2CppObjectBase)__instance.m_hud).Cast<CP_Cluster_Hud>(); ConcurrentClusterHud concurrentClusterHud = ((Component)val2).gameObject.AddComponent<ConcurrentClusterHud>(); concurrentClusterHud.parent = __instance; concurrentClusterHud.parentHud = ((Il2CppObjectBase)val2.m_hud).Cast<CP_Bioscan_Hud>(); concurrentClusterHud.def = def; if (concurrentClusterHud.Setup()) { PlayerScannerManager.Current.RegisterConcurrentCluster(__instance); SPOLogger.Warning("Setting up CP_Cluster_Core as Concurrent Cluster!"); } else { SPOLogger.Warning("Concurrent Cluster: failed to setup"); } } else { SPOLogger.Error("Trying to setup concurrent cluster, " + $"but the cluster scan has {((Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores).Count}, which is senseless or is impossible for 4 players to complete"); } } if (def.EventsOnClusterProgress.Count <= 0) { return; } foreach (iChainedPuzzleCore item2 in (Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores) { item2.OnPuzzleDone += Action<int>.op_Implicit((Action<int>)CheckEventsOnClusterProgress); } void CheckEventsOnClusterProgress(int puzzleIndex) { int num = 0; for (int i = 0; i < ((Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores).Length; i++) { if (((Il2CppArrayBase<iChainedPuzzleCore>)(object)__instance.m_childCores)[i].IsFinished()) { num++; } } foreach (ClusterProgressEvent item3 in def.EventsOnClusterProgress) { if (item3.Count == num) { WardenObjectiveManager.CheckAndExecuteEventsOnTrigger(ListExtensions.ToIl2Cpp<WardenObjectiveEventData>(item3.Events), (eWardenObjectiveEventTrigger)0, true, 0f, (Il2CppStructArray<eWardenObjectiveEventType>)null); } } } } } [HarmonyPatch] internal class Patches_CP_Cluster_Hud_ReqItems { private static Dictionary<IntPtr, List<bool>> childrenReqItemEnabled { get; } private static Dictionary<IntPtr, List<string[]>> clustersChildrenReqItemNames { get; } private static Dictionary<IntPtr, List<Il2CppStructArray<bool>>> clustersChildrenReqItemsStatus { get; } [HarmonyPostfix] [HarmonyPatch(typeof(CP_Bioscan_Core), "AddRequiredItems")] private static void Post_CP_Bioscan_Core_AddRequiredItems(CP_Bioscan_Core __instance, Il2CppReferenceArray<iWardenObjectiveItem> requiredItems) { CP_Cluster_Core val = ((Il2CppObjectBase)__instance.Owner).TryCast<CP_Cluster_Core>(); if ((Object)(object)val == (Object)null) { return; } if (__instance.m_hud == null) { SPOLogger.Error("CP_Cluster_Hud_ReqItems: replacement Cluster_hud is null."); return; } CP_Cluster_Hud val2 = ((Il2CppObjectBase)__instance.m_hud).Cast<CP_Cluster_Hud>(); string[] array = new string[((Il2CppArrayBase<iWardenObjectiveItem>)(object)requiredItems).Count]; for (int i = 0; i < __instance.m_reqItems.Count; i++) { if (__instance.m_reqItems[i] != null) { array[i] = __instance.m_reqItems[i].PublicName; } else { SPOLogger.Error("Post_CP_Bioscan_Core_AddRequiredItems: CP_Bioscan_Core " + ((Object)__instance).name + " has a missing m_reqItem! " + i); } } List<bool> list; List<string[]> list2; if (childrenReqItemEnabled.ContainsKey(((Il2CppObjectBase)val2).Pointer)) { list = childrenReqItemEnabled[((Il2CppObjectBase)val2).Pointer]; list2 = clustersChildrenReqItemNames[((Il2CppObjectBase)val2).Pointer]; } else { list = Enumerable.Repeat(element: false, val.NRofPuzzles()).ToList(); list2 = Enumerable.Repeat(new string[0], val.NRofPuzzles()).ToList(); childrenReqItemEnabled.Add(((Il2CppObjectBase)val2).Pointer, list); clustersChildrenReqItemNames.Add(((Il2CppObjectBase)val2).Pointer, list2); } list[__instance.m_puzzleIndex] = __instance.m_reqItemsEnabled; list2[__instance.m_puzzleIndex] = array; } [HarmonyPrefix] [HarmonyPatch(typeof(CP_Cluster_Hud), "SetRequiredItemData")] private static bool Pre_CP_Cluster_Hud_SetRequiredItemData(CP_Cluster_Hud __instance, int puzzleIndex, Il2CppStructArray<bool> reqItemStatus) { List<Il2CppStructArray<bool>> list; if (!clustersChildrenReqItemsStatus.ContainsKey(((Il2CppObjectBase)__instance).Pointer)) { list = Enumerable.Repeat<Il2CppStructArray<bool>>(null, __instance.m_clusterSize).ToList(); clustersChildrenReqItemsStatus.Add(((Il2CppObjectBase)__instance).Pointer, list); } else { list = clustersChildrenReqItemsStatus[((Il2CppObjectBase)__instance).Pointer]; } list[puzzleIndex] = reqItemStatus; return false; } [HarmonyPostfix] [HarmonyPatch(typeof(CP_Cluster_Hud), "UpdateDataFor")] private static void Post_CP_Cluster_Hud_UpdateDataFor(CP_Cluster_Hud __instance, int index) { if (clustersChildrenReqItemsStatus.ContainsKey(((Il2CppObjectBase)__instance).Pointer)) { if (!childrenReqItemEnabled.ContainsKey(((Il2CppObjectBase)__instance).Pointer) || !clustersChildrenReqItemNames.ContainsKey(((Il2CppObjectBase)__instance).Pointer)) { SPOLogger.Error("CP_Cluster_Hud_UpdateDataFor: Found registered reqItemStatus but ReqItemEnabled or ReqItemNames is missing!"); return; } Il2CppStructArray<bool> val = clustersChildrenReqItemsStatus[((Il2CppObjectBase)__instance).Pointer][index]; __instance.m_hud.SetupRequiredItems(childrenReqItemEnabled[((Il2CppObjectBase)__instance).Pointer][index], Il2CppStringArray.op_Implicit(clustersChildrenReqItemNames[((Il2CppObjectBase)__instance).Pointer][index])); __instance.m_hud.SetRequiredItemData(__instance.m_puzzleIndex, val); } } private static void Clear() { clustersChildrenReqItemsStatus.Clear(); clustersChildrenReqItemNames.Clear(); childrenReqItemEnabled.Clear(); } static Patches_CP_Cluster_Hud_ReqItems() { childrenReqItemEnabled = new Dictionary<IntPtr, List<bool>>(); clustersChildrenReqItemNames = new Dictionary<IntPtr, List<string[]>>(); clustersChildrenReqItemsStatus = new Dictionary<IntPtr, List<Il2CppStructArray<bool>>>(); LevelAPI.OnLevelCleanup += Clear; } } } namespace ScanPosOverride.Managers { public class PlayerScannerManager { private static readonly float[] ZERO_SCAN_SPEED; private Mutex CCStateMutex; private Dictionary<IntPtr, CP_PlayerScanner> ChildScanners = new Dictionary<IntPtr, CP_PlayerScanner>(); public static PlayerScannerManager Current { get; } private Dictionary<IntPtr, List<CP_PlayerScanner>> CCCores { get; } = new Dictionary<IntPtr, List<CP_PlayerScanner>>(); private Dictionary<IntPtr, List<CP_Bioscan_Core>> CCChildren { get; } = new Dictionary<IntPtr, List<CP_Bioscan_Core>>(); private Dictionary<IntPtr, HashSet<IntPtr>> CCChildrenState { get; } = new Dictionary<IntPtr, HashSet<IntPtr>>(); private Dictionary<IntPtr, float[]> OriginalClusterScanSpeeds { get; } = new Dictionary<IntPtr, float[]>(); private Dictionary<IntPtr, float[]> OriginalScanSpeed { get; } = new Dictionary<IntPtr, float[]>(); internal bool RegisterConcurrentCluster(CP_Cluster_Core core) { if (CCCores.ContainsKey(((Il2CppObjectBase)core).Pointer)) { return false; } List<CP_PlayerScanner> list = Enumerable.Repeat<CP_PlayerScanner>(null, core.m_amountOfPuzzles).ToList(); List<CP_Bioscan_Core> list2 = Enumerable.Repeat<CP_Bioscan_Core>(null, core.m_amountOfPuzzles).ToList(); for (int i = 0; i < ((Il2CppArrayBase<iChainedPuzzleCore>)(object)core.m_childCores).Count; i++) { if ((Object)(object)list[i] != (Object)null) { SPOLogger.Error("SetupConcurrentClusterScanners: Duplicate child scanner for child scan. ??"); continue; } iChainedPuzzleCore val = ((Il2CppArrayBase<iChainedPuzzleCore>)(object)core.m_childCores)[i]; CP_Bioscan_Core val2 = ((Il2CppObjectBase)val).TryCast<CP_Bioscan_Core>(); if ((Object)(object)val2 == (Object)null) { SPOLogger.Error("SetupConcurrentClusterScanners: Failed to cast child to CP_Bioscan_Core"); continue; } CP_PlayerScanner val3 = ((Il2CppObjectBase)val2.PlayerScanner).TryCast<CP_PlayerScanner>(); if ((Object)(object)val3 == (Object)null) { SPOLogger.Error("SetupConcurrentClusterScanners: Failed to cast CP_Bioscan_Core.PlayerScanner to CP_PlayerScanner"); continue; } list[i] = val3; ChildScanners.Add(((Il2CppObjectBase)val).Pointer, val3); list2[i] = val2; if (!OriginalClusterScanSpeeds.ContainsKey(((Il2CppObjectBase)core).Pointer)) { Il2CppStructArray<float> scanSpeeds = val3.m_scanSpeeds; float[] array = new float[((Il2CppArrayBase<float>)(object)scanSpeeds).Length]; Array.Copy(Il2CppArrayBase<float>.op_Implicit((Il2CppArrayBase<float>)(object)scanSpeeds), array, ((Il2CppArrayBase<float>)(object)scanSpeeds).Length); OriginalClusterScanSpeeds.Add(((Il2CppObjectBase)core).Pointer, array); } } CCCores.Add(((Il2CppObjectBase)core).Pointer, list); CCChildren.Add(((Il2CppObjectBase)core).Pointer, list2); CCChildrenState.Add(((Il2CppObjectBase)core).Pointer, new HashSet<IntPtr>()); return true; } internal bool IsConcurrentCluster(CP_Cluster_Core core) { return CCCores.ContainsKey(((Il2CppObjectBase)core).Pointer); } internal bool IsConcurrentCluster(CP_Bioscan_Core core) { return CCCores.ContainsKey(((Il2CppObjectBase)core.Owner).Pointer); } internal void ZeroCCScanSpeed(CP_Cluster_Core parent) { if (!CCCores.ContainsKey(((Il2CppObjectBase)parent).Pointer)) { return; } foreach (CP_PlayerScanner item in CCCores[((Il2CppObjectBase)parent).Pointer]) { bool flag = true; for (int i = 0; i < 4; i++) { flag = flag && ((Il2CppArrayBase<float>)(object)item.m_scanSpeeds)[i] == 0f; ((Il2CppArrayBase<float>)(object)item.m_scanSpeeds)[i] = 0f; } if (flag) { break; } } } internal void RestoreCCScanSpeed(CP_Cluster_Core parent) { if (!CCCores.ContainsKey(((Il2CppObjectBase)parent).Pointer) || !OriginalClusterScanSpeeds.ContainsKey(((Il2CppObjectBase)parent).Pointer)) { return; } float[] array = OriginalClusterScanSpeeds[((Il2CppObjectBase)parent).Pointer]; foreach (CP_PlayerScanner item in CCCores[((Il2CppObjectBase)parent).Pointer]) { bool flag = false; for (int i = 0; i < 4; i++) { flag = flag || ((Il2CppArrayBase<float>)(object)item.m_scanSpeeds)[i] != 0f; ((Il2CppArrayBase<float>)(object)item.m_scanSpeeds)[i] = array[i]; } if (flag) { break; } } } internal float[] GetCacheOriginalScanSpeed(CP_Bioscan_Core core) { if (IsConcurrentCluster(core)) { if (!CCCores.ContainsKey(((Il2CppObjectBase)core.Owner).Pointer)) { return ZERO_SCAN_SPEED; } return OriginalClusterScanSpeeds[((Il2CppObjectBase)core.Owner).Pointer]; } if (OriginalScanSpeed.ContainsKey(((Il2CppObjectBase)core).Pointer)) { return OriginalScanSpeed[((Il2CppObjectBase)core).Pointer]; } CP_PlayerScanner cacheScanner = GetCacheScanner(core); if ((Object)(object)cacheScanner == (Object)null) { SPOLogger.Error("GetCacheOriginalScanSpeed: cannot get scanner for this CP_Bioscan_Core"); return ZERO_SCAN_SPEED; } float[] array = new float[4]; Array.Copy(Il2CppArrayBase<float>.op_Implicit((Il2CppArrayBase<float>)(object)cacheScanner.m_scanSpeeds), array, array.Length); OriginalScanSpeed.Add(((Il2CppObjectBase)core).Pointer, array); return array; } public CP_PlayerScanner GetCacheScanner(CP_Bioscan_Core core) { if (ChildScanners.ContainsKey(((Il2CppObjectBase)core).Pointer)) { return ChildScanners[((Il2CppObjectBase)core).Pointer]; } CP_PlayerScanner val = ((Il2CppObjectBase)core.PlayerScanner).TryCast<CP_PlayerScanner>(); if ((Object)(object)val == (Object)null) { return null; } ChildScanners.Add(((Il2CppObjectBase)core).Pointer, val); return val; } internal bool CCShouldProgress(CP_Bioscan_Core child, bool IsThisScanShouldProgress) { if (CCStateMutex == null) { CCStateMutex = new Mutex(); } if (CCStateMutex.WaitOne(2000)) { if (!CCCores.ContainsKey(((Il2CppObjectBase)child.Owner).Pointer)) { SPOLogger.Error("ConcurrentClusterShouldProgress: failed to find cluster parent!"); CCStateMutex.ReleaseMutex(); return false; } CP_Cluster_Core val = ((Il2CppObjectBase)child.Owner).Cast<CP_Cluster_Core>(); if (!CCChildrenState.ContainsKey(((Il2CppObjectBase)val).Pointer)) { SPOLogger.Error("ConcurrentClusterShouldProgress: ConcurrentClusterChildScanState initialization error!"); CCStateMutex.ReleaseMutex(); return false; } HashSet<IntPtr> hashSet = CCChildrenState[((Il2CppObjectBase)val).Pointer]; bool result; if (IsThisScanShouldProgress) { hashSet.Add(((Il2CppObjectBase)child).Pointer); result = hashSet.Count == val.m_amountOfPuzzles; } else { hashSet.Remove(((Il2CppObjectBase)child).Pointer); result = false; } CCStateMutex.ReleaseMutex(); return result; } SPOLogger.Debug("ConcurrentCluster: Failed to acquire scan mutex."); return false; } internal void CompleteConcurrentCluster(CP_Cluster_Core parent) { if (!CCChildren.ContainsKey(((Il2CppObjectBase)parent).Pointer)) { return; } List<CP_Bioscan_Core> list = CCChildren[((Il2CppObjectBase)parent).Pointer]; CCChildren.Remove(((Il2CppObjectBase)parent).Pointer); foreach (CP_Bioscan_Core item in list) { item.m_sync.SetStateData((eBioscanStatus)4, 0f, (List<PlayerAgent>)null, 0, (Il2CppStructArray<bool>)null); } } public List<CP_PlayerScanner> GetCCChildrenScanner(CP_Cluster_Core parent) { if (!CCCores.ContainsKey(((Il2CppObjectBase)parent).Pointer)) { return null; } return CCCores[((Il2CppObjectBase)parent).Pointer]; } public void Clear() { CCCores.Clear(); CCChildren.Clear(); CCChildrenState.Clear(); OriginalClusterScanSpeeds.Clear(); ChildScanners.Clear(); OriginalScanSpeed.Clear(); if (CCStateMutex != null) { CCStateMutex.Dispose(); } CCStateMutex = null; } static PlayerScannerManager() { ZERO_SCAN_SPEED = new float[4]; Current = new PlayerScannerManager(); LevelAPI.OnLevelCleanup += Current.Clear; } private PlayerScannerManager() { } } public class PuzzleReqItemManager { public static readonly PuzzleReqItemManager Current; private Dictionary<int, CarryItemPickup_Core> BigPickupItemsInLevel = new Dictionary<int, CarryItemPickup_Core>(); private int itemIndexCounter = 1; private List<(CP_Bioscan_Core, List<int>)> bioscanCoresToAddReqItems = new List<(CP_Bioscan_Core, List<int>)>(); private List<(CP_Cluster_Core, List<int>)> clusterCoresToAddReqItems = new List<(CP_Cluster_Core, List<int>)>(); private Dictionary<IntPtr, CP_Bioscan_Core> movableScansWithReqItems = new Dictionary<IntPtr, CP_Bioscan_Core>(); internal int Register(CarryItemPickup_Core item) { int num = itemIndexCounter; itemIndexCounter++; BigPickupItemsInLevel.Add(num, item); return num; } internal void QueueForAddingReqItems(CP_Bioscan_Core core, List<int> itemsIndices) { bioscanCoresToAddReqItems.Add((core, itemsIndices)); } internal void QueueForAddingReqItems(CP_Cluster_Core core, List<int> itemsIndices) { clusterCoresToAddReqItems.Add((core, itemsIndices)); } internal CP_Bioscan_Core GetMovableCoreWithReqItem(CP_PlayerScanner scanner) { if (!movableScansWithReqItems.ContainsKey(((Il2CppObjectBase)scanner).Pointer)) { return null; } return movableScansWithReqItems[((Il2CppObjectBase)scanner).Pointer]; } public CarryItemPickup_Core GetBigPickupItem(int bigPickupInLevelIndex) { if (!BigPickupItemsInLevel.ContainsKey(bigPickupInLevelIndex)) { return null; } return BigPickupItemsInLevel[bigPickupInLevelIndex]; } public bool AddReqItems(CP_Bioscan_Core puzzle, int itemIndex) { //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Expected O, but got Unknown if ((Object)(object)puzzle == (Object)null || itemIndex == 0L) { return false; } if (!BigPickupItemsInLevel.ContainsKey(itemIndex)) { SPOLogger.Error($"Unregistered BigPickup Item with index {itemIndex}"); return false; } CarryItemPickup_Core val = BigPickupItemsInLevel[itemIndex]; puzzle.AddRequiredItems(Il2CppReferenceArray<iWardenObjectiveItem>.op_Implicit((iWardenObjectiveItem[])(object)new iWardenObjectiveItem[1] { new iWardenObjectiveItem(((Il2CppObjectBase)val).Pointer) })); return true; } public bool AddReqItems(CP_Cluster_Core puzzle, int itemIndex) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Expected O, but got Unknown if ((Object)(object)puzzle == (Object)null || itemIndex == 0L) { return false; } if (!BigPickupItemsInLevel.ContainsKey(itemIndex)) { SPOLogger.Error($"Unregistered BigPickup Item with index {itemIndex}"); return false; } CarryItemPickup_Core val = BigPickupItemsInLevel[itemIndex]; foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)puzzle.m_childCores) { item.AddRequiredItems(Il2CppReferenceArray<iWardenObjectiveItem>.op_Implicit((iWardenObjectiveItem[])(object)new iWardenObjectiveItem[1] { new iWardenObjectiveItem(((Il2CppObjectBase)val).Pointer) })); } return true; } public bool AddReqItems(CP_Bioscan_Core puzzle, List<int> itemsIndices) { if ((Object)(object)puzzle == (Object)null || itemsIndices == null || itemsIndices.Count < 1) { return false; } bool flag = false; foreach (int item in itemsIndices.ToHashSet()) { flag |= AddReqItems(puzzle, item); } if (puzzle.IsMovable && flag) { movableScansWithReqItems.Add(((Il2CppObjectBase)puzzle.m_playerScanner).Pointer, puzzle); } return flag; } public void RemoveReqItem(CP_Bioscan_Core puzzle, int itemIndex) { //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Expected O, but got Unknown if (!((Object)(object)puzzle == (Object)null)) { if (!BigPickupItemsInLevel.ContainsKey(itemIndex) && itemIndex != 0L) { SPOLogger.Error($"Unregistered BigPickup Item with index {itemIndex}"); } else { CarryItemPickup_Core val = BigPickupItemsInLevel[itemIndex]; puzzle.RemoveRequiredItems((iWardenObjectiveItem[])(object)new iWardenObjectiveItem[1] { new iWardenObjectiveItem(((Il2CppObjectBase)val).Pointer) }); } } } public void RemoveReqItem(CP_Cluster_Core puzzle, int itemIndex) { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Expected O, but got Unknown if ((Object)(object)puzzle == (Object)null) { return; } if (!BigPickupItemsInLevel.ContainsKey(itemIndex) && itemIndex != 0L) { SPOLogger.Error($"Unregistered BigPickup Item with index {itemIndex}"); return; } CarryItemPickup_Core val = BigPickupItemsInLevel[itemIndex]; foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)puzzle.m_childCores) { item.RemoveRequiredItems((iWardenObjectiveItem[])(object)new iWardenObjectiveItem[1] { new iWardenObjectiveItem(((Il2CppObjectBase)val).Pointer) }); } } private void AddQueuedReqItems() { foreach (var (puzzle, itemsIndices) in bioscanCoresToAddReqItems) { AddReqItems(puzzle, itemsIndices); } foreach (var (val, itemsIndices2) in clusterCoresToAddReqItems) { foreach (iChainedPuzzleCore item in (Il2CppArrayBase<iChainedPuzzleCore>)(object)val.m_childCores) { CP_Bioscan_Core val2 = ((Il2CppObjectBase)item).TryCast<CP_Bioscan_Core>(); if ((Object)(object)val2 == (Object)null) { SPOLogger.Error("Failed to cast child core to CP_Bioscan_Core"); } else { AddReqItems(val2, itemsIndices2); } } } } public void OutputLevelBigPickupInfo() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_010a: 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) StringBuilder val = new StringBuilder(); val.AppendLine(); List<CarryItemPickup_Core> list = new List<CarryItemPickup_Core>(BigPickupItemsInLevel.Values); list.Sort(delegate(CarryItemPickup_Core b1, CarryItemPickup_Core b2) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0043: 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_002c: 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_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) AIG_CourseNode spawnNode = b1.SpawnNode; AIG_CourseNode spawnNode2 = b2.SpawnNode; if (spawnNode.m_dimension.DimensionIndex != spawnNode2.m_dimension.DimensionIndex) { if (spawnNode.m_dimension.DimensionIndex > spawnNode2.m_dimension.DimensionIndex) { return 1; } return -1; } if (spawnNode.LayerType != spawnNode2.LayerType) { if (spawnNode.LayerType >= spawnNode2.LayerType) { return 1; } return -1; } return (spawnNode.m_zone.LocalIndex != spawnNode2.m_zone.LocalIndex) ? ((spawnNode.m_zone.LocalIndex >= spawnNode2.m_zone.LocalIndex) ? 1 : (-1)) : 0; }); Dictionary<CarryItemPickup_Core, int> dictionary = new Dictionary<CarryItemPickup_Core, int>(); foreach (int key in BigPickupItemsInLevel.Keys) { dictionary.Add(BigPickupItemsInLevel[key], key); } foreach (CarryItemPickup_Core item in list) { val.AppendLine("Item Name: " + ((Item)item).ItemDataBlock.publicName); val.AppendLine($"Zone {item.SpawnNode.m_zone.Alias}, {item.SpawnNode.LayerType}, Dim {item.SpawnNode.m_dimension.DimensionIndex}"); val.AppendLine($"Item Index: {dictionary[item]}"); val.AppendLine(); } SPOLogger.Debug(((Object)val).ToString()); } internal void OnEnterLevel() { AddQueuedReqItems(); OutputLevelBigPickupInfo(); } public void Clear() { BigPickupItemsInLevel.Clear(); itemIndexCounter = 1; bioscanCoresToAddReqItems.Clear(); clusterCoresToAddReqItems.Clear(); movableScansWithReqItems.Clear(); } static PuzzleReqItemManager() { Current = new PuzzleReqItemManager(); LevelAPI.OnLevelCleanup += Current.Clear; LevelAPI.OnEnterLevel += Current.OnEnterLevel; } private PuzzleReqItemManager() { } } public class PuzzleOverrideManager { public static readonly PuzzleOverrideManager Current; private uint puzzleOverrideIndex = 1u; public static uint MainLevelLayout => RundownManager.ActiveExpedition.LevelLayoutData; private Dictionary<IntPtr, uint> bioscanIndex { get; } = new Dictionary<IntPtr, uint>(); private Dictionary<IntPtr, uint> clusterIndex { get; } = new Dictionary<IntPtr, uint>(); private Dictionary<uint, CP_Bioscan_Core> index2Bioscan { get; } = new Dictionary<uint, CP_Bioscan_Core>(); private Dictionary<uint, CP_Cluster_Core> index2Cluster { get; } = new Dictionary<uint, CP_Cluster_Core>(); public uint Register(CP_Bioscan_Core __instance) { if ((Object)(object)__instance == (Object)null) { return 0u; } uint num = puzzleOverrideIndex; puzzleOverrideIndex++; if (!bioscanIndex.ContainsKey(((Il2CppObjectBase)__instance).Pointer)) { bioscanIndex.Add(((Il2CppObjectBase)__instance).Pointer, num); index2Bioscan.Add(num, __instance); return num; } return GetBioscanCoreOverrideIndex(__instance); } public uint Register(CP_Cluster_Core __instance) { if ((Object)(object)__instance == (Object)null) { return 0u; } uint num = puzzleOverrideIndex; puzzleOverrideIndex++; if (!clusterIndex.ContainsKey(((Il2CppObjectBase)__instance).Pointer)) { clusterIndex.Add(((Il2CppObjectBase)__instance).Pointer, num); index2Cluster.Add(num, __instance); return num; } return GetClusterCoreOverrideIndex(__instance); } public void OutputLevelPuzzleInfo() { //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Unknown result type (might be due to invalid IL or missing references) //IL_0476: Unknown result type (might be due to invalid IL or missing references) List<ChainedPuzzleInstance> list = new List<ChainedPuzzleInstance>(); Enumerator<ChainedPuzzleInstance> enumerator = ChainedPuzzleManager.Current.m_instances.GetEnumerator(); while (enumerator.MoveNext()) { ChainedPuzzleInstance current = enumerator.Current; list.Add(current); } list.Sort(delegate(ChainedPuzzleInstance c1, ChainedPuzzleInstance c2) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0027: 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_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0056: 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) LG_Zone zone2 = c1.m_sourceArea.m_zone; LG_Zone zone3 = c2.m_sourceArea.m_zone; if (zone2.DimensionIndex != zone3.DimensionIndex) { if (zone2.DimensionIndex >= zone3.DimensionIndex) { return 1; } return -1; } if (zone2.Layer.m_type != zone3.Layer.m_type) { if (zone2.Layer.m_type >= zone3.Layer.m_type) { return 1; } return -1; } return (zone2.LocalIndex >= zone3.LocalIndex) ? 1 : (-1); }); StringBuilder stringBuilder = new StringBuilder(); foreach (ChainedPuzzleInstance item in list) { LG_Zone zone = item.m_sourceArea.m_zone; StringBuilder stringBuilder2 = stringBuilder; StringBuilder stringBuilder3 = stringBuilder2; StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(15, 3, stringBuilder2); handler.AppendLiteral("\nZone "); handler.AppendFormatted(zone.Alias); handler.AppendLiteral(", "); handler.AppendFormatted<LG_LayerType>(zone.m_layer.m_type); handler.AppendLiteral(", Dim "); handler.AppendFormatted<eDimensionIndex>(zone.DimensionIndex); handler.AppendLiteral("\n"); stringBuilder3.Append(ref handler); stringBuilder2 = stringBuilder; StringBuilder stringBuilder4 = stringBuilder2; handler = new StringBuilder.AppendInterpolatedStringHandler(14, 1, stringBuilder2); handler.AppendLiteral("Alarm name: "); handler.AppendFormatted(item.Data.PublicAlarmName); handler.AppendLiteral(":\n"); stringBuilder4.Append(ref handler); for (int i = 0; i < ((Il2CppArrayBase<iChainedPuzzleCore>)(object)item.m_chainedPuzzleCores).Count; i++) { iChainedPuzzleCore val = ((Il2CppArrayBase<iChainedPuzzleCore>)(object)item.m_chainedPuzzleCores)[i]; if (bioscanIndex.ContainsKey(((Il2CppObjectBase)val).Pointer)) { uint value = bioscanIndex[((Il2CppObjectBase)val).Pointer]; stringBuilder2 = stringBuilder; StringBuilder stringBuilder5 = stringBuilder2; handler = new StringBuilder.AppendInterpolatedStringHandler(15, 1, stringBuilder2); handler.AppendLiteral("puzzle index: "); handler.AppendFormatted(i); handler.AppendLiteral("\n"); stringBuilder5.Append(ref handler); stringBuilder.Append("type: CP_Bioscan_Core\n"); stringBuilder2 = stringBuilder; StringBuilder stringBuilder6 = stringBuilder2; handler = new StringBuilder.AppendInterpolatedStringHandler(22, 1, stringBuilder2); handler.AppendLiteral("PuzzleOverrideIndex: "); handler.AppendFormatted(value); handler.AppendLiteral("\n"); stringBuilder6.Append(ref handler); CP_Bioscan_Core val2 = ((Il2CppObjectBase)val).Cast<CP_Bioscan_Core>(); CP_PlayerScanner val3 = ((Il2CppObjectBase)val2.PlayerScanner).Cast<CP_PlayerScanner>(); stringBuilder2 = stringBuilder; StringBuilder stringBuilder7 = stringBuilder2; handler = new StringBuilder.AppendInterpolatedStringHandler(11, 1, stringBuilder2); handler.AppendLiteral("Position: "); handler.AppendFormatted<Vector3>(val2.m_position); handler.AppendLiteral("\n"); stringBuilder7.Append(ref handler); stringBuilder2 = stringBuilder; StringBuilder stringBuilder8 = stringBuilder2; handler = new StringBuilder.AppendInterpolatedStringHandler(9, 1, stringBuilder2); handler.AppendLiteral("Radius: "); handler.AppendFormatted(val3.Radius); handler.AppendLiteral("\n"); stringBuilder8.Append(ref handler); } else if (clusterIndex.ContainsKey(((Il2CppObjectBase)val).Pointer)) { uint value2 = clusterIndex[((Il2CppObjectBase)val).Pointer]; CP_Cluster_Core val4 = ((Il2CppObjectBase)val).TryCast<CP_Cluster_Core>(); if ((Object)(object)val4 == (Object)null) { SPOLogger.Error("Found cluster core Pointer, but TryCast failed."); continue; } stringBuilder2 = stringBuilder; StringBuilder stringBuilder9 = stringBuilder2; handler = new StringBuilder.AppendInterpolatedStringHandler(15, 1, stringBuilder2); handler.AppendLiteral("puzzle index: "); handler.AppendFormatted(i); handler.AppendLiteral("\n"); stringBuilder9.Append(ref handler); stringBuilder.Append("type: CP_Cluster_Core\n"); stringBuilder2 = stringBuilder; StringBuilder stringBuilder10 = stringBuilder2; handler = new StringBuilder.AppendInterpolatedStringHandler(22, 1, stringBuilder2); handler.AppendLiteral("PuzzleOverrideIndex: "); handler.AppendFormatted(value2); handler.AppendLiteral("\n"); stringBuilder10.Append(ref handler); stringBuilder.Append("=== Clustered puzzles info: ===\n"); for (int j = 0; j < val4.m_amountOfPuzzles; j++) { iChainedPuzzleCore val5 = ((Il2CppArrayBase<iChainedPuzzleCore>)(object)val4.m_childCores)[j]; if (!bioscanIndex.ContainsKey(((Il2CppObjectBase)val5).Pointer)) { SPOLogger.Error("Unregistered clustered iChainedPuzzleCore found..."); continue; } uint value3 = bioscanIndex[((Il2CppObjectBase)val5).Pointer]; stringBuilder2 = stringBuilder; StringBuilder stringBuilder11 = stringBuilder2; handler = new StringBuilder.AppendInterpolatedStringHandler(15, 1, stringBuilder2); handler.AppendLiteral("puzzle index: "); handler.AppendFormatted(j); handler.AppendLiteral("\n"); stringBuilder11.Append(ref handler); stringBuilder.Append("type: CP_Bioscan_Core\n"); stringBuilder2 = stringBuilder; StringBuilder stringBuilder12 = stringBuilder2; handler = new StringBuilder.AppendInterpolatedStringHandler(22, 1, stringBuilder2); handler.AppendLiteral("PuzzleOverrideIndex: "); handler.AppendFormatted(value3); handler.AppendLiteral("\n"); stringBuilder12.Append(ref handler); CP_Bioscan_Core val6 = ((Il2CppObjectBase)val5).Cast<CP_Bioscan_Core>(); CP_PlayerScanner val7 = ((Il2CppObjectBase)val6.PlayerScanner).Cast<CP_PlayerScanner>(); stringBuilder2 = stringBuilder; StringBuilder stringBuilder13 = stringBuilder2; handler = new StringBuilder.AppendInterpolatedStringHandler(11, 1, stringBuilder2); handler.AppendLiteral("Position: "); handler.AppendFormatted<Vector3>(val6.m_position); handler.AppendLiteral("\n"); stringBuilder13.Append(ref handler); stringBuilder2 = stringBuilder; StringBuilder stringBuilder14 = stringBuilder2; handler = new StringBuilder.AppendInterpolatedStringHandler(9, 1, stringBuilder2); handler.AppendLiteral("Radius: "); handler.AppendFormatted(val7.Radius); handler.AppendLiteral("\n"); stringBuilder14.Append(ref handler); } stringBuilder.Append("=== Clustered puzzles END ===\n"); } else { SPOLogger.Error("Unregistered iChainedPuzzleCore found..."); } } stringBuilder.Append('\n'); } SPOLogger.Debug(stringBuilder.ToString()); } public uint GetBioscanCoreOverrideIndex(CP_Bioscan_Core core) { if (bioscanIndex.ContainsKey(((Il2CppObjectBase)core).Pointer)) { return bioscanIndex[((Il2CppObjectBase)core).Pointer]; } return 0u; } public uint GetClusterCoreOverrideIndex(CP_Cluster_Core core) { if (clusterIndex.ContainsKey(((Il2CppObjectBase)core).Pointer)) { return clusterIndex[((Il2CppObjectBase)core).Pointer]; } return 0u; } public uint GetBioscanCoreOverrideIndex(IntPtr pointer) { if (bioscanIndex.ContainsKey(pointer)) { return bioscanIndex[pointer]; } return 0u; } public uint GetClusterCoreOverrideIndex(IntPtr pointer) { if (clusterIndex.ContainsKey(pointer)) { return clusterIndex[pointer]; } return 0u; } public CP_Bioscan_Core GetBioscanCore(uint puzzleOverrideIndex) { if (!index2Bioscan.ContainsKey(puzzleOverrideIndex)) { return null; } return index2Bioscan[puzzleOverrideIndex]; } public CP_Cluster_Core GetClusterCore(uint puzzleOverrideIndex) { if (!index2Cluster.ContainsKey(puzzleOverrideIndex)) { return null; } return index2Cluster[puzzleOverrideIndex]; } public void Clear() { puzzleOverrideIndex = 1u; bioscanIndex.Clear(); clusterIndex.Clear(); index2Bioscan.Clear(); index2Cluster.Clear(); } private PuzzleOverrideManager() { } static PuzzleOverrideManager() { Current = new PuzzleOverrideManager(); LevelAPI.OnEnterLevel += Current.OutputLevelPuzzleInfo; LevelAPI.OnBuildStart += Current.Clear; LevelAPI.OnLevelCleanup += Current.Clear; } public iChainedPuzzleOwner ChainedPuzzleInstanceOwner(CP_Bioscan_Core bioscanCore) { if ((Object)(object)bioscanCore == (Object)null) { return null; } iChainedPuzzleOwner owner = bioscanCore.Owner; if ((Object)(object)((Il2CppObjectBase)owner).TryCast<ChainedPuzzleInstance>() != (Object)null) { return owner; } CP_Cluster_Core val = ((Il2CppObjectBase)owner).TryCast<CP_Cluster_Core>(); if ((Object)(object)val != (Object)null) { return val.m_owner; } SPOLogger.Error("Failed to find CP_BioScan_Core owner (instance of ChainedPuzzleInstance)."); return null; } } } namespace ScanPosOverride.JSON { public static class InjectLibUtil { public const string PLUGIN_GUID = "GTFO.InjectLib"; public static JsonConverter InjectLibConnector { get; private set; } public static bool IsLoaded { get; private set; } static InjectLibUtil() { if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("GTFO.InjectLib", out var value)) { return; } try { Assembly obj = ((value == null) ? null : value.Instance?.GetType()?.Assembly) ?? null; if ((object)obj == null) { throw new Exception("Assembly is Missing!"); } InjectLibConnector = (JsonConverter)Activator.CreateInstance(obj.GetTypes().First((Type t) => t.Name == "InjectLibConnector") ?? throw new Exception("Unable to Find InjectLibConnector Class")); IsLoaded = true; } catch (Exception value2) { SPOLogger.Error($"Exception thrown while reading data from GTFO.AWO: {value2}"); } } } internal class LocalizedTextConverter : JsonConverter<LocalizedText> { public override bool HandleNull => false; public override LocalizedText Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Expected O, but got Unknown //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Expected O, but got Unknown switch (reader.TokenType) { case JsonTokenType.String: { string @string = reader.GetString(); return new LocalizedText { Id = 0u, UntranslatedText = @string }; } case JsonTokenType.Number: return new LocalizedText { Id = reader.GetUInt32(), UntranslatedText = null }; default: throw new JsonException($"LocalizedTextJson type: {reader.TokenType} is not implemented!"); } } public override void Write(Utf8JsonWriter writer, LocalizedText value, JsonSerializerOptions options) { JsonSerializer.Serialize<LocalizedText>(writer, value, options); } } public sealed class MyVector3Converter : JsonConverter<Vector3> { public override bool HandleNull => false; public override Vector3 Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) { //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_0114: 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_0065: Unknown result type (might be due to invalid IL or missing references) Vector3 vector = Vector3.zero; switch (reader.TokenType) { case JsonTokenType.StartObject: { int currentDepth = reader.CurrentDepth; while (reader.Read()) { if (reader.TokenType == JsonTokenType.EndObject && reader.CurrentDepth == currentDepth) { SPOLogger.Warning($"Parsed Vector3 : {vector}"); return vector; } if (reader.TokenType != JsonTokenType.PropertyName) { throw new JsonException("Expected PropertyName token"); } string? @string = reader.GetString(); reader.Read(); switch (@string.ToLowerInvariant()) { case "x": vector.x = reader.GetSingle(); break; case "y": vector.y = reader.GetSingle(); break; case "z": vector.z = reader.GetSingle(); break; } } throw new JsonException("Expected EndObject token"); } case JsonTokenType.String: { string text = reader.GetString().Trim(); if (TryParseVector3(text, out vector)) { return vector; } throw new JsonException("Vector3 format is not right: " + text); } default: throw new JsonException($"Vector3Json type: {reader.TokenType} is not implemented!"); } } private static bool TryParseVector3(string input, out Vector3 vector) { //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_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_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) float[] array = default(float[]); if (!RegexUtils.TryParseVectorString(input, ref array)) { vector = Vector3.zero; return false; } if (array.Length < 3) { vector = Vector3.zero; return false; } vector = new Vector3(array[0], array[1], array[2]); return true; } public override void Write(Utf8JsonWriter writer, Vector3 value, JsonSerializerOptions options) { //IL_0018: 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_004a: Unknown result type (might be due to invalid IL or missing references) writer.WriteStringValue($"({value.x} {value.y} {value.z})"); } } internal static class Json { private static readonly JsonSerializerOptions _setting; static Json() { _setting = new JsonSerializerOptions { ReadCommentHandling = JsonCommentHandling.Skip, IncludeFields = false, PropertyNameCaseInsensitive = true, WriteIndented = true, IgnoreReadOnlyProperties = true }; _setting.Converters.Add(new JsonStringEnumConverter()); _setting.Converters.Add(new MyVector3Converter()); if (MTFOPartialDataUtil.IsLoaded && MTFOPartialDataUtil.Initialized) { _setting.Converters.Add(MTFOPartialDataUtil.PersistentIDConverter); _setting.Converters.Add(MTFOPartialDataUtil.LocalizedTextConverter); SPOLogger.Log("PartialData Support Found!"); } else { _setting.Converters.Add(new LocalizedTextConverter()); } if (InjectLibUtil.IsLoaded) { _setting.Converters.Add(InjectLibUtil.InjectLibConnector); SPOLogger.Log("InjectLib (AWO) support found!"); } } public static T Deserialize<T>(string json) { return JsonSerializer.Deserialize<T>(json, _setting); } public static object Deserialize(Type type, string json) { return JsonSerializer.Deserialize(json, type, _setting); } public static string Serialize<T>(T value) { return JsonSerializer.Serialize(value, _setting); } public static void Load<T>(string file, out T config) where T : new() { if (file.Length < ".json".Length) { config = default(T); return; } if (file.Substring(file.Length - ".json".Length) != ".json") { file += ".json"; } file = File.ReadAllText(Path.Combine(Plugin.OVERRIDE_SCAN_POS_PATH, file)); config = Deserialize<T>(file); } } public static class MTFOPartialDataUtil { public const string PLUGIN_GUID = "MTFO.Extension.PartialBlocks"; public static JsonConverter PersistentIDConverter { get; private set; } public static JsonConverter LocalizedTextConverter { get; private set; } public static bool IsLoaded { get; private set; } public static bool Initialized { get; private set; } public static string PartialDataPath { get; private set; } public static string ConfigPath { get; private set; } static MTFOPartialDataUtil() { PersistentIDConverter = null; LocalizedTextConverter = null; IsLoaded = false; Initialized = false; PartialDataPath = string.Empty; ConfigPath = string.Empty; if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("MTFO.Extension.PartialBlocks", out var value)) { return; } try { Assembly obj = ((value == null) ? null : value.Instance?.GetType()?.Assembly) ?? null; if ((object)obj == null) { throw new Exception("Assembly is Missing!"); } Type[] types = obj.GetTypes(); Type type = types.First((Type t) => t.Name == "PersistentIDConverter"); if ((object)type == null) { throw new Exception("Unable to Find PersistentIDConverter Class"); } Type type2 = types.First((Type t) => t.Name == "PartialDataManager"); if ((object)type2 == null) { throw new Exception("Unable to Find PartialDataManager Class"); } Type type3 = types.First((Type t) => t.Name == "LocalizedTextConverter") ?? throw new Exception("Unable to Find LocalizedTextConverter Class"); PropertyInfo property = type2.GetProperty("Initialized", BindingFlags.Static | BindingFlags.Public); PropertyInfo property2 = type2.GetProperty("PartialDataPath", BindingFlags.Static | BindingFlags.Public); PropertyInfo? property3 = type2.GetProperty("ConfigPath", BindingFlags.Static | BindingFlags.Public); if ((object)property == null) { throw new Exception("Unable to Find Property: Initialized"); } if ((object)property2 == null) { throw new Exception("Unable to Find Property: PartialDataPath"); } if ((object)property3 == null) { throw new Exception("Unable to Find Field: ConfigPath"); } Initialized = (bool)property.GetValue(null); PartialDataPath = (string)property2.GetValue(null); ConfigPath = (string)property3.GetValue(null); PersistentIDConverter = (JsonConverter)Activator.CreateInstance(type); LocalizedTextConverter = (JsonConverter)Activator.CreateInstance(type3); IsLoaded = true; } catch (Exception value2) { SPOLogger.Error($"Exception thrown while reading data from MTFO_Extension_PartialData:\n{value2}"); } } } public static class MTFOUtil { public const string PLUGIN_GUID = "com.dak.MTFO"; public const BindingFlags PUBLIC_STATIC = BindingFlags.Static | BindingFlags.Public; public static string GameDataPath { get; private set; } public static string CustomPath { get; private set; } public static bool HasCustomContent { get; private set; } public static bool IsLoaded { get; private set; } static MTFOUtil() { GameDataPath = string.Empty; CustomPath = string.Empty; HasCustomContent = false; IsLoaded = false; if (!((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.TryGetValue("com.dak.MTFO", out var value)) { return; } try { Assembly obj = ((value == null) ? null : value.Instance?.GetType()?.Assembly) ?? null; if ((object)obj == null) { throw new Exception("Assembly is Missing!"); } Type obj2 = obj.GetTypes().First((Type t) => t.Name == "ConfigManager") ?? throw new Exception("Unable to Find ConfigManager Class"); FieldInfo field = obj2.GetField("GameDataPath", BindingFlags.Static | BindingFlags.Public); FieldInfo field2 = obj2.GetField("CustomPath", BindingFlags.Static | BindingFlags.Public); FieldInfo? field3 = obj2.GetField("HasCustomContent", BindingFlags.Static | BindingFlags.Public); if ((object)field == null) { throw new Exception("Unable to Find Field: GameDataPath"); } if ((object)field2 == null) { throw new Exception("Unable to Find Field: CustomPath"); } if ((object)field3 == null) { throw new Exception("Unable to Find Field: HasCustomContent"); } GameDataPath = (string)field.GetValue(null); CustomPath = (string)field2.GetValue(null); HasCustomContent = (bool)field3.GetValue(null); IsLoaded = true; } catch (Exception value2) { SPOLogger.Error($"Exception thrown while reading path from DataDumper (MTFO): \n{value2}"); } } } } namespace ScanPosOverride.Component { internal class ConcurrentClusterHud : MonoBehaviour { public enum PlayerCountRequirement { INVALID, ANY, SOLO, DUO } private StringBuilder displayText = new StringBuilder(); private bool m_isValid; private List<CP_Bioscan_Core> children; private float childRadius = -1f; private int[] playerInScanCount; private readonly string[] ROMAN = new string[4] { "I", "II", "III", "IV" }; internal CP_Cluster_Core parent { get; set; } internal CP_Bioscan_Hud parentHud { get; set; } internal PuzzleOverride def { get; set; } public PlayerCountRequirement playerCountReq { get; private set; } private PlayerCountRequirement ReqPlayerCount(iChainedPuzzleCore child) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Expected I4, but got Unknown CP_PlayerScanner obj = ((Il2CppObjectBase)((Il2CppObjectBase)child).Cast<CP_Bioscan_Core>().m_playerScanner).Cast<CP_PlayerScanner>(); PlayerRequirement playerRequirement = obj.m_playerRequirement; Il2CppStructArray<float> scanSpeeds = obj.m_scanSpeeds; switch ((int)playerRequirement) { case 2: if (!(((Il2CppArrayBase<float>)(object)scanSpeeds)[0] > 0f)) { return PlayerCountRequirement.INVALID; } return PlayerCountRequirement.SOLO; case 0: { int i; for (i = 0; i < ((Il2CppArrayBase<float>)(object)scanSpeeds).Count && ((Il2CppArrayBase<float>)(object)scanSpeeds)[i] == 0f; i++) { } if (i >= 2) { return PlayerCountRequirement.INVALID; } if (i == 1) { return PlayerCountRequirement.DUO; } if (!(((Il2CppArrayBase<float>)(object)scanSpeeds)[i + 1] > 0f)) { return PlayerCountRequirement.SOLO; } return PlayerCountRequirement.ANY; } default: return PlayerCountRequirement.INVALID; } } internal bool Setup() { if (((Il2CppArrayBase<iChainedPuzzleCore>)(object)parent.m_childCores).Count < 2 || ((Il2CppArrayBase<iChainedPuzzleCore>)(object)parent.m_childCores).Count > 4) { SPOLogger.Error($"ConcurrentClusterHud: got cluster scan with {((Il2CppArrayBase<iChainedPuzzleCore>)(object)parent.m_childCores).Count} children, which is invalid for concurrent cluster"); return false; } playerCountReq = ReqPlayerCount(((Il2CppArrayBase<iChainedPuzzleCore>)(object)parent.m_childCores)[0]); if (playerCountReq == PlayerCountRequirement.INVALID) { SPOLogger.Error($"ConcurrentCluster setup: playerRequirement is {1}, which is invalid for concurrent cluster"); return false; } switch (((Il2CppArrayBase<iChainedPuzzleCore>)(object)parent.m_childCores).Count) { case 2: switch (playerCountReq) { case PlayerCountRequirement.ANY: case PlayerCountRequirement.SOLO: m_isValid = true; break; case PlayerCountRequirement.DUO: m_isValid = true; break; } break; case 4: { PlayerCountRequirement playerCountRequirement = playerCountReq; if ((uint)(playerCountRequirement - 1) <= 1u) { m_isValid = true; } break; } case 3: { PlayerCountRequirement playerCountRequirement = playerCountReq; if ((uint)(playerCountRequirement - 1) <= 1u) { m_isValid = true; } break; } } if (!m_isValid) { SPOLogger.Error($"ConcurrentCluster setup: Something went wrong! PlayerCountRequirement: {playerCountReq}, children num: {((Il2CppArrayBase<iChainedPuzzleCore>)(object)parent.m_childCores).Count}"); return false; } playerInScanCount = new int[((Il2CppArrayBase<iChainedPuzzleCore>)(object)parent.m_childCores).Count]; Array.Fill(playerInScanCount, 0); children = ((IEnumerable<iChainedPuzzleCore>)parent.m_childCores).ToList().ConvertAll((iChainedPuzzleCore c) => ((Il2CppObjectBase)c).Cast<CP_Bioscan_Core>()); childRadius = ((Il2CppObjectBase)((Il2CppObjectBase)((Il2CppArrayBase<iChainedPuzzleCore>)(object)parent.m_childCores)[0]).Cast<CP_Bioscan_Core>().m_playerScanner).Cast<CP_PlayerScanner>().Radius; return true; } private void LateUpdate() { //IL_0326: 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_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) if (!m_isValid || !parentHud.m_visible || !parentHud.m_isClosestToPlayer) { return; } displayText.Clear(); displayText.AppendLine().Append("<color=white>"); for (int i = 0; i < children.Count; i++) { int num = 0; CP_Bioscan_Core val = children[i]; Enumerator<PlayerAgent> enumerator = PlayerManager.PlayerAgentsInLevel.GetEnumerator(); while (enumerator.MoveNext()) { Vector3 val2 = ((Agent)enumerator.Current).Position - val.m_position; if (((Vector3)(ref val2)).magnitude < childRadius) { num++; } } playerInScanCount[i] = num; string value = string.Empty; string value2 = string.Empty; switch (playerCountReq) { case PlayerCountRequirement.ANY: switch (num) { case 0: value = " "; break; case 1: value = "A"; break; case 2: value = "A,B"; break; case 3: value = "A,B,C"; break; case 4: value = "A,B,C,D"; break; } value2 = ((num > 0) ? "white" : "orange"); break; case PlayerCountRequirement.SOLO: switch (num) { case 0: value = " "; value2 = "orange"; break; case 1: value = "A"; value2 = "white"; break; case 2: value = "A,<color=red>B</color>"; value2 = "orange"; break; case 3: value = "A,<color=red>B</color>,<color=red>C</color>"; value2 = "orange"; break; case 4: value = "A,<color=red>B</color>,<color=red>C</color>,<color=red>D</color>"; value2 = "orange"; break; } break; case PlayerCountRequirement.DUO: switch (num) { case 0: value = " , "; value2 = "orange"; break; case 1: value = "A, "; value2 = "orange"; break; case 2: value = "A,B"; value2 = "white"; break; case 3: value = "A,B,<color=red>C</color>"; value2 = "orange"; break; case 4: value = "A,B,<color=red>C</color>,<color=red>D</color>"; value2 = "orange"; break; } break; } StringBuilder stringBuilder = displayText; StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(8, 1, stringBuilder); handler.AppendLiteral("<color="); handler.AppendFormatted(value2); handler.AppendLiteral(">"); StringBuilder stringBuilder2 = stringBuilder.Append(ref handler).Append(ROMAN[i]).Append(": ") .Append("[") .Append(value) .Append("]"); StringBuilder.AppendInterpolatedStringHandler handler2 = new StringBuilder.AppendInterpolatedStringHandler(9, 1, stringBuilder2); handler2.AppendLiteral("</color="); handler2.AppendFormatted(value2); handler2.AppendLiteral(">"); stringBuilder2.Append(ref handler2); if (i != children.Count - 1) { displayText.Append(" | "); } } displayText.Append("</color=white>"); parentHud.m_msgCharBuffer.Add(displayText.ToString()); GuiManager.InteractionLayer.SetMessage(parentHud.m_msgCharBuffer, parentHud.m_msgStyle, 0); } private void OnDestroy() { parent = null; parentHud = null; def = null; children.Clear(); children = null; m_isValid = false; playerInScanCount = null; displayText = null; } static ConcurrentClusterHud() { ClassInjector.RegisterTypeInIl2Cpp<ConcurrentClusterHud>(); } } }
plugins/net6/SecDoorTerminalInterface.dll
Decompiled a month agousing System; using System.CodeDom.Compiler; using System.Collections; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using AIGraph; using Agents; using BepInEx; using BepInEx.Core.Logging.Interpolation; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using BepInEx.Unity.IL2CPP.Utils.Collections; using ChainedPuzzles; using GTFO.API; using GameData; using HarmonyLib; using Il2CppInterop.Runtime.InteropTypes; using Il2CppInterop.Runtime.InteropTypes.Arrays; using Il2CppSystem; using LevelGeneration; using Localization; using Microsoft.CodeAnalysis; using Player; using SNetwork; using SecDoorTerminalInterface.Inject; using TMPro; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("SecDoorTerminalInterface")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+git6952937-master")] [assembly: AssemblyProduct("SecDoorTerminalInterface")] [assembly: AssemblyTitle("SecDoorTerminalInterface")] [assembly: TargetPlatform("Windows7.0")] [assembly: SupportedOSPlatform("Windows7.0")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace SecDoorTerminalInterface { internal static class Assets { public static GameObject SecDoorTerminalPrefab; public static void Init() { SecDoorTerminalPrefab = AssetAPI.GetLoadedAsset<GameObject>("Assets/Modding/SecDoorTerminal/Terminal_SecDoor.prefab"); } } public struct CommandDescriptor { public TERM_Command Type; public string Command; public string Description; public TERM_CommandRule Rule; } public enum CPSolvedBehaviour { OpenDoor, AddOpenCommand, Nothing } [BepInPlugin("SecDoorTerminalInterface", "SecDoorTerminalInterface", "1.0.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] internal class EntryPoint : BasePlugin { private Harmony _Harmony; public override void Load() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown AssetAPI.OnAssetBundlesLoaded += AssetAPI_OnAssetBundlesLoaded; _Harmony = new Harmony("SecDoorTerminalInterface.Harmony"); _Harmony.PatchAll(); } private void AssetAPI_OnAssetBundlesLoaded() { Assets.Init(); } } internal static class Logger { private static readonly ManualLogSource _Logger; static Logger() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Expected O, but got Unknown _Logger = new ManualLogSource("SecDoorTerminalInterface"); Logger.Sources.Add((ILogSource)(object)_Logger); } private static string Format(object msg) { return msg.ToString(); } public static void Info(BepInExInfoLogInterpolatedStringHandler handler) { _Logger.LogInfo(handler); } public static void Info(string str) { _Logger.LogMessage((object)str); } public static void Info(object data) { _Logger.LogMessage((object)Format(data)); } public static void Debug(BepInExDebugLogInterpolatedStringHandler handler) { _Logger.LogDebug(handler); } public static void Debug(string str) { _Logger.LogDebug((object)str); } public static void Debug(object data) { _Logger.LogDebug((object)Format(data)); } public static void Error(BepInExErrorLogInterpolatedStringHandler handler) { _Logger.LogError(handler); } public static void Error(string str) { _Logger.LogError((object)str); } public static void Error(object data) { _Logger.LogError((object)Format(data)); } public static void Fatal(BepInExFatalLogInterpolatedStringHandler handler) { _Logger.LogFatal(handler); } public static void Fatal(string str) { _Logger.LogFatal((object)str); } public static void Fatal(object data) { _Logger.LogFatal((object)Format(data)); } public static void Warn(BepInExWarningLogInterpolatedStringHandler handler) { _Logger.LogWarning(handler); } public static void Warn(string str) { _Logger.LogWarning((object)str); } public static void Warn(object data) { _Logger.LogWarning((object)Format(data)); } [Conditional("DEBUG")] public static void DebugOnly(object data) { } } public sealed class SecDoorTerminal { public const TERM_Command COMMAND_OPEN = 255; public const TERM_Command COMMAND_OVERRIDE = 254; private LocalizedText _GCTextHolder; private Vector3 _SavedIntOpenDoorPos; private Vector3 _SavedIntUseKeyPos; private Vector3 _SavedIntCustomMessagePos; private Vector3 _SavedIntHackPos; private SDT_StateBehaviour _StateBehaviour; private static readonly Vector3 BEGONE = Vector3.one * 10000f; public string OpenCommandName { get; set; } = "OPEN_LINKED"; public string OpenCommandDescription { get; set; } = "Open the linked security door"; public LG_SecurityDoor LinkedDoor { get; private set; } public LG_SecurityDoor_Locks LinkedDoorLocks { get; private set; } public LG_ComputerTerminal ComputerTerminal { get; private set; } public LG_ComputerTerminalCommandInterpreter CmdProcessor { get; private set; } public Interact_ComputerTerminal Interaction { get; private set; } public TextMeshPro IdleText { get; private set; } public SpriteRenderer IdleIcon { get; private set; } public AIG_CourseNode SpawnNode => ComputerTerminal.m_terminalItem.SpawnNode; public bool IsTerminalActive { get; private set; } = true; public CPSolvedBehaviour BioscanScanSolvedBehaviour { get; set; } = CPSolvedBehaviour.AddOpenCommand; public SDT_StateBehaviour StateBehaviour { get { return _StateBehaviour; } set { _StateBehaviour?.SetContext(null); _StateBehaviour = value; _StateBehaviour?.SetContext(this); } } public event Action<TERM_Command, string, string, string> OnCmdUsed; private void Setup_CommandModule() { Inject_Terminal_ReceiveCmd.OnCmdUsed_LevelInstanced += OnReceiveCommand; } private void OnReceiveCommand(LG_ComputerTerminalCommandInterpreter interpreter, TERM_Command cmd, string inputLine, string param1, string param2) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) if (interpreter.m_terminal.m_syncID == ComputerTerminal.m_syncID) { this.OnCmdUsed?.Invoke(cmd, inputLine, param1, param2); } } public void AddCommand(CommandDescriptor descriptor, Action<LG_ComputerTerminalCommandInterpreter> onCommandUsed = null) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Expected O, but got Unknown //IL_009e: 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_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown //IL_0053: Unknown result type (might be due to invalid IL or missing references) if (CmdProcessor.HasRegisteredCommand(descriptor.Type)) { bool flag = default(bool); BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(33, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Command Type: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<TERM_Command>(descriptor.Type); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" is Already Added!!"); } Logger.Error(val); return; } _GCTextHolder = new LocalizedText { UntranslatedText = descriptor.Description, Id = 0u }; CmdProcessor.AddCommand(descriptor.Type, descriptor.Command, _GCTextHolder, descriptor.Rule); OnCmdUsed += delegate(TERM_Command cmdType, string cmdStr, string param1, string param2) { //IL_0000: 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) if (cmdType == descriptor.Type) { onCommandUsed?.Invoke(CmdProcessor); } }; } public void AddOverrideCommand(string cmd, string helpText, Action<LG_ComputerTerminalCommandInterpreter> onCommandUsed = null) { //IL_0023: 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) CommandDescriptor commandDescriptor = default(CommandDescriptor); commandDescriptor.Type = (TERM_Command)254; commandDescriptor.Command = cmd; commandDescriptor.Description = helpText; commandDescriptor.Rule = (TERM_CommandRule)1; CommandDescriptor descriptor = commandDescriptor; AddCommand(descriptor, delegate(LG_ComputerTerminalCommandInterpreter interpreter) { onCommandUsed?.Invoke(CmdProcessor); interpreter.AddOutput((TerminalLineType)0, "Desired Action: <color=orange>OVERRIDE</color>", 0.5f, (TerminalSoundType)0, (TerminalSoundType)0); interpreter.AddOutput((TerminalLineType)4, "Decrypting Authorize ID..", 0.85f, (TerminalSoundType)0, (TerminalSoundType)0); interpreter.AddOutput((TerminalLineType)2, "Sending..", 1.2f, (TerminalSoundType)0, (TerminalSoundType)0); interpreter.AddOutput((TerminalLineType)5, "<color=orange>OVERRIDE</color> Action sent!", 0.65f, (TerminalSoundType)0, (TerminalSoundType)0); SetEndOfQueue(delegate { if (SNet.IsMaster) { LinkedDoorLocks.m_intOpenDoor.OnInteractionTriggered.Invoke(PlayerManager.GetLocalPlayerAgent()); } }); }); } public void AddOpenCommand(string cmd, string helpText, Action<LG_ComputerTerminalCommandInterpreter> onCommandUsed = null) { //IL_0023: 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) CommandDescriptor commandDescriptor = default(CommandDescriptor); commandDescriptor.Type = (TERM_Command)255; commandDescriptor.Command = cmd; commandDescriptor.Description = helpText; commandDescriptor.Rule = (TERM_CommandRule)1; CommandDescriptor descriptor = commandDescriptor; AddCommand(descriptor, delegate(LG_ComputerTerminalCommandInterpreter interpreter) { onCommandUsed?.Invoke(interpreter); interpreter.AddOutput((TerminalLineType)0, "Desired Action: <color=orange>OPEN</color>", 0.5f, (TerminalSoundType)0, (TerminalSoundType)0); interpreter.AddOutput((TerminalLineType)4, "Decrypting Authorize ID..", 0.85f, (TerminalSoundType)0, (TerminalSoundType)0); interpreter.AddOutput((TerminalLineType)2, "Sending..", 1.2f, (TerminalSoundType)0, (TerminalSoundType)0); interpreter.AddOutput((TerminalLineType)5, "<color=orange>OVERRIDE</color> Action sent!", 0.65f, (TerminalSoundType)0, (TerminalSoundType)0); SetEndOfQueue(delegate { if (SNet.IsMaster) { LinkedDoorLocks.m_intOpenDoor.OnInteractionTriggered.Invoke(PlayerManager.GetLocalPlayerAgent()); } }); }); } public void SetEndOfQueue(Action onEndOfQueue) { CmdProcessor.OnEndOfQueue = Action.op_Implicit(onEndOfQueue); } private void Setup() { Setup_GraphicModule(); Setup_DoorInteractModule(); Setup_DoorStateModule(); Setup_CommandModule(); } public void SetTerminalActive(bool active) { IsTerminalActive = active; ((Behaviour)ComputerTerminal).enabled = active; Interact_ComputerTerminal componentInChildren = ((Component)ComputerTerminal).GetComponentInChildren<Interact_ComputerTerminal>(true); if ((Object)(object)componentInChildren != (Object)null) { ((Behaviour)componentInChildren).enabled = active; ((Interact_Base)componentInChildren).SetActive(active); } if (!active) { PlayerAgent localInteractionSource = ComputerTerminal.m_localInteractionSource; if ((Object)(object)localInteractionSource != (Object)null && localInteractionSource.FPItemHolder.InTerminalTrigger) { ComputerTerminal.ExitFPSView(); } if (SNet.IsMaster) { ComputerTerminal.ChangeState((TERM_State)0); } } } public void SetSpawnNode(AIG_CourseNode node) { ComputerTerminal.m_terminalItem.SpawnNode = node; } public void SetLocationTextToSpawnZone() { SetLocationText(SpawnNode.m_zone.NavInfo.GetFormattedText((LG_NavInfoFormat)7)); } public void SetLocationText(string text) { ComputerTerminal.m_terminalItem.FloorItemLocation = text; } private SecDoorTerminal() { } public void SetOpenInteractActive(bool active) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) Interact_Timed intOpenDoor = LinkedDoorLocks.m_intOpenDoor; ((Component)intOpenDoor).transform.position = (active ? _SavedIntOpenDoorPos : BEGONE); ((Interact_Base)intOpenDoor).SetActive(active); } public void SetUseKeyInteractActive(bool active) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) Interact_RequireKeyItem intUseKeyItem = LinkedDoorLocks.m_intUseKeyItem; ((Component)intUseKeyItem).transform.position = (active ? _SavedIntUseKeyPos : BEGONE); ((Interact_Base)intUseKeyItem).SetActive(active); } public void SetHackingInteractActive(bool active) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) Interact_Hack intHack = LinkedDoorLocks.m_intHack; ((Component)intHack).transform.position = (active ? _SavedIntHackPos : BEGONE); ((Interact_Base)intHack).SetActive(active); } public void SetCustomMessageActive(bool active) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) Interact_MessageOnScreen intCustomMessage = LinkedDoorLocks.m_intCustomMessage; ((Component)intCustomMessage).transform.position = (active ? _SavedIntCustomMessagePos : BEGONE); ((Interact_Base)intCustomMessage).SetActive(active); } public void OpenOrStartChainPuzzle() { //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0035: 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) ChainedPuzzleInstance chainedPuzzleToSolve = LinkedDoorLocks.ChainedPuzzleToSolve; if ((Object)(object)chainedPuzzleToSolve != (Object)null && !chainedPuzzleToSolve.IsSolved) { LinkedDoor.m_sync.AttemptDoorInteraction((eDoorInteractionType)4, 0f, 0f, default(Vector3), (Agent)null); } else { LinkedDoor.m_sync.AttemptDoorInteraction((eDoorInteractionType)0, 0f, 0f, default(Vector3), (Agent)null); } } public void ForceOpenDoor(float delay) { if (delay > 0f) { CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(OpenDoorWithDelay(delay)), (Action)null); } else { ForceOpenDoor(); } } private IEnumerator OpenDoorWithDelay(float delay) { yield return (object)new WaitForSeconds(delay); LinkedDoor.m_sync.AttemptDoorInteraction((eDoorInteractionType)0, 0f, 0f, default(Vector3), (Agent)null); } public void ForceOpenDoor() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) LinkedDoor.m_sync.AttemptDoorInteraction((eDoorInteractionType)0, 0f, 0f, default(Vector3), (Agent)null); } private void Setup_DoorInteractModule() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) _SavedIntOpenDoorPos = ((Component)LinkedDoorLocks.m_intOpenDoor).transform.position; _SavedIntUseKeyPos = ((Component)LinkedDoorLocks.m_intUseKeyItem).transform.position; _SavedIntCustomMessagePos = ((Component)LinkedDoorLocks.m_intCustomMessage).transform.position; _SavedIntHackPos = ((Component)LinkedDoorLocks.m_intHack).transform.position; } private void Setup_DoorStateModule() { //IL_0054: Unknown result type (might be due to invalid IL or missing references) StateBehaviour = new SDT_StateBehaviour(); LinkedDoor.m_sync.OnDoorStateChange += Action<pDoorState, bool>.op_Implicit((Action<pDoorState, bool>)OnStateChange); LinkedDoorLocks.OnChainedPuzzleSolved += Action.op_Implicit((Action)OnChainedPuzzleSolved); OnStateChange(LinkedDoor.m_sync.GetCurrentSyncState(), isRecall: false); } private void OnChainedPuzzleSolved() { switch (BioscanScanSolvedBehaviour) { case CPSolvedBehaviour.OpenDoor: if (SNet.IsMaster) { ForceOpenDoor(0.25f); } break; case CPSolvedBehaviour.AddOpenCommand: CmdProcessor.AddOutput((TerminalLineType)5, "Bioscan Sequence Completed - <color=orange>" + OpenCommandName + "</color> Command is now accessible!", 0f, (TerminalSoundType)0, (TerminalSoundType)0); AddOpenCommand(OpenCommandName, OpenCommandDescription); break; } } private void OnStateChange(pDoorState state, bool isRecall) { //IL_002c: 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_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) if (StateBehaviour != null) { ActiveEnemyWaveData activeEnemyWaveData = LinkedDoor.ActiveEnemyWaveData; bool isBloodyDoor = activeEnemyWaveData != null && activeEnemyWaveData.HasActiveEnemyWave; SecDoorState secDoorState = default(SecDoorState); secDoorState.Status = state.status; secDoorState.State = state; secDoorState.IsBloodyDoor = isBloodyDoor; SecDoorState state2 = secDoorState; StateBehaviour.UpdateInteractionState(state2, isRecall); StateBehaviour.UpdateGraphicState(state2, isRecall); } } private void Setup_GraphicModule() { CoroutineManager.StartCoroutine(CollectionExtensions.WrapToIl2Cpp(ForceScreenOffOnDeactive()), (Action)null); } private IEnumerator ForceScreenOffOnDeactive() { while (true) { if (IsTerminalActive) { ((Behaviour)ComputerTerminal.m_text).enabled = true; } else { ((Behaviour)ComputerTerminal.m_text).enabled = false; ComputerTerminal.m_loginScreen.SetActive(true); ComputerTerminal.m_interfaceScreen.SetActive(true); } yield return null; } } public void SetIdleIconColor(Color color) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) IdleIcon.color = color; } public void SetIdleText(string text) { ((TMP_Text)IdleText).text = text; } public void SetIdleTextFontSize(float size) { ((TMP_Text)IdleText).fontSize = size; } public static SecDoorTerminal Place(LG_SecurityDoor secDoor, TerminalStartStateData startData = null, TerminalPlacementData placementData = null) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_0135: 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) if ((int)secDoor.m_securityDoorType != 0) { return null; } Transform val = CustomExtensions.FindChildRecursive(((Component)secDoor).transform, "InteractionInterface", true); if ((Object)(object)val == (Object)null) { return null; } ((Component)val).gameObject.SetActiveRecursively(false); ((Component)val).gameObject.SetActive(true); GameObject obj = Object.Instantiate<GameObject>(Assets.SecDoorTerminalPrefab, val); obj.transform.localPosition = (((int)secDoor.Gate.Type == 0) ? new Vector3(0f, -0.006f, 0f) : new Vector3(0f, -0.026f, 0f)); obj.transform.localRotation = Quaternion.identity; obj.transform.localScale = Vector3.one; iTerminalItem componentInChildren = obj.GetComponentInChildren<iTerminalItem>(); if (componentInChildren != null && TryGetSecDoorSpawnedNode(secDoor, out var spawnedNode)) { componentInChildren.SpawnNode = spawnedNode; } LG_ComputerTerminal component = obj.GetComponent<LG_ComputerTerminal>(); component.Setup(startData, placementData); MeshFilter[] array = Il2CppArrayBase<MeshFilter>.op_Implicit(((Component)secDoor).GetComponentsInChildren<MeshFilter>(true)); foreach (MeshFilter val2 in array) { if (!((Object)(object)val2.sharedMesh == (Object)null)) { string name = ((Object)val2.sharedMesh).name; if (!string.IsNullOrEmpty(name) && name.Equals("g_security_door_display")) { Transform transform = ((Component)val2).gameObject.transform; transform.localPosition += BEGONE; } } } SecDoorTerminal secDoorTerminal = new SecDoorTerminal(); secDoorTerminal.LinkedDoor = secDoor; secDoorTerminal.LinkedDoorLocks = ((Il2CppObjectBase)secDoor.m_locks).Cast<LG_SecurityDoor_Locks>(); secDoorTerminal.ComputerTerminal = component; secDoorTerminal.CmdProcessor = component.m_command; secDoorTerminal.Interaction = ((Component)component).GetComponentInChildren<Interact_ComputerTerminal>(true); secDoorTerminal.IdleIcon = component.m_loginScreen.GetComponent<SpriteRenderer>(); secDoorTerminal.IdleText = component.m_loginScreen.GetComponentInChildren<TextMeshPro>(); secDoorTerminal.Setup(); return secDoorTerminal; } private static bool TryGetSecDoorSpawnedNode(LG_SecurityDoor secDoor, out AIG_CourseNode spawnedNode) { if ((Object)(object)secDoor == (Object)null) { spawnedNode = null; return false; } if ((Object)(object)secDoor.Gate == (Object)null) { spawnedNode = null; return false; } if ((Object)(object)((LG_ZoneExpander)secDoor.Gate).m_linksFrom == (Object)null) { spawnedNode = null; return false; } spawnedNode = ((LG_ZoneExpander)secDoor.Gate).m_linksFrom.m_courseNode; return spawnedNode != null; } } public class SDT_StateBehaviour { public SecDoorTerminal Context { get; private set; } internal void SetContext(SecDoorTerminal secDoorTerminal) { Context = secDoorTerminal; } public virtual void UpdateInteractionState(SecDoorState state, bool isRecall) { //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_0051: Expected I4, but got Unknown eDoorStatus status = state.Status; switch ((int)status) { case 0: case 1: case 2: case 4: case 5: case 7: case 9: case 12: case 13: case 14: Context.SetTerminalActive(active: true); Context.SetOpenInteractActive(active: false); Context.SetHackingInteractActive(active: false); Context.SetUseKeyInteractActive(active: false); Context.SetCustomMessageActive(active: false); break; case 3: Context.SetTerminalActive(active: false); Context.SetOpenInteractActive(active: false); Context.SetHackingInteractActive(active: false); Context.SetUseKeyInteractActive(active: true); Context.SetCustomMessageActive(active: false); break; case 6: case 15: Context.SetTerminalActive(active: false); Context.SetOpenInteractActive(active: false); Context.SetHackingInteractActive(active: false); Context.SetUseKeyInteractActive(active: false); Context.SetCustomMessageActive(active: true); break; case 8: case 10: case 11: case 16: Context.SetTerminalActive(active: false); Context.SetOpenInteractActive(active: false); Context.SetHackingInteractActive(active: false); Context.SetUseKeyInteractActive(active: false); Context.SetCustomMessageActive(active: false); break; } } public virtual void UpdateGraphicState(SecDoorState state, bool isRecall) { //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_004f: Expected I4, but got Unknown //IL_0140: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Unknown result type (might be due to invalid IL or missing references) //IL_016f: Unknown result type (might be due to invalid IL or missing references) eDoorStatus status = state.Status; string text; Color? val; switch (status - 1) { case 14: text = "::<color=orange>Bulkhead Override</color> Required::"; val = Color.yellow; break; case 2: text = "::<color=orange>Keycard</color> Required::"; val = Color.red; break; case 4: text = "<color=orange>BIOSCAN Protocol</color> pending..."; val = Color.cyan; break; case 3: text = "<color=orange>BIOSCAN Protocol</color> pending..."; val = Color.red; break; case 5: text = "BOOT ERR://Power Level - <color=red>LOW</color>"; val = ColorExt.Hex("#FFA500"); break; case 6: text = "<color=orange>LOCKDOWN Protocol</color> engaged!"; val = Color.red; break; case 7: if (Context.LinkedDoorLocks.ChainedPuzzleToSolve.Data.TriggerAlarmOnActivate) { text = "<color=red>BIOSCAN Protocol</color> processing!"; val = Color.red; } else { text = "<color=blue>BIOSCAN Protocol</color> processing!"; val = Color.cyan; } break; case 9: case 15: text = "::DOOR OVERRIDING::"; val = Color.cyan; break; case 0: text = "::DOOR LOCKING::"; val = Color.cyan; break; default: text = "Waiting..."; val = Color.green; break; } if (val.HasValue) { Context.SetIdleIconColor(val.Value); } if (text != null) { Context.SetIdleText(text); } } } public struct SecDoorState { public eDoorStatus Status; public pDoorState State; public bool IsBloodyDoor; } [GeneratedCode("VersionInfoGenerator", "2.1.3+git35c0c2a-master")] [CompilerGenerated] internal static class VersionInfo { public const string RootNamespace = "SecDoorTerminalInterface"; public const string Version = "1.0.0"; public const string VersionPrerelease = null; public const string VersionMetadata = "git6952937-master"; public const string SemVer = "1.0.0+git6952937-master"; public const string GitRevShort = "6952937"; public const string GitRevLong = "69529374dcbe6b589a13bfc0c363675c5cd3e803"; public const string GitBranch = "master"; public const string GitTag = null; public const int GitCommitsSinceTag = 0; public const bool GitIsDirty = false; } } namespace SecDoorTerminalInterface.Inject { [HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "ReceiveCommand")] internal class Inject_Terminal_ReceiveCmd { public static event Action<LG_ComputerTerminalCommandInterpreter, TERM_Command, string, string, string> OnCmdUsed_LevelInstanced; static Inject_Terminal_ReceiveCmd() { LevelAPI.OnLevelCleanup += delegate { Inject_Terminal_ReceiveCmd.OnCmdUsed_LevelInstanced = null; }; } private static void Prefix(LG_ComputerTerminalCommandInterpreter __instance, TERM_Command cmd, string inputLine, string param1, string param2) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) Inject_Terminal_ReceiveCmd.OnCmdUsed_LevelInstanced?.Invoke(__instance, cmd, inputLine, param1, param2); } } }
plugins/net6/ShotgunCenterFire.dll
Decompiled a month agousing System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using BepInEx; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using Gear; using HarmonyLib; using Player; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = "")] [assembly: AssemblyCompany("ShotgunCenterFire")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("ShotgunCenterFire")] [assembly: AssemblyTitle("ShotgunCenterFire")] [assembly: AssemblyVersion("1.0.0.0")] namespace ShotgunCenterFire; internal class FirePatches { private static Transform muzzleAlign; private static PlayerAgent owner; [HarmonyPatch(typeof(Shotgun), "Fire")] [HarmonyPrefix] private static void ShotgunFire(Shotgun __instance) { muzzleAlign = ((ItemEquippable)__instance).MuzzleAlign; owner = ((Item)__instance).Owner; } [HarmonyPatch(/*Could not decode attribute arguments.*/)] [HarmonyPrefix] private static void CastWeaponRay(Transform alignTransform, ref WeaponHitData weaponRayData, ref Vector3 originPos) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004b: 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) if ((Object)(object)muzzleAlign != (Object)null && (Object)(object)alignTransform == (Object)(object)muzzleAlign) { originPos = owner.FPSCamera.Position; WeaponHitData obj = weaponRayData; Vector3 val = owner.FPSCamera.CameraRayPos - originPos; obj.fireDir = ((Vector3)(ref val)).normalized; } } } [BepInPlugin("com.Untilted.ShotgunCenterFire", "ShotgunCenterFire", "1.0.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class Loader : BasePlugin { public const string MODNAME = "ShotgunCenterFire"; public const string AUTHOR = "Untilted"; public const string GUID = "com.Untilted.ShotgunCenterFire"; public const string VERSION = "1.0.0"; public static ManualLogSource Logger; public override void Load() { //IL_0020: Unknown result type (might be due to invalid IL or missing references) Logger = ((BasePlugin)this).Log; ((BasePlugin)this).Log.LogMessage((object)"Loading ShotgunCenterFire"); new Harmony("ShotgunCenterFire").PatchAll(typeof(FirePatches)); ((BasePlugin)this).Log.LogMessage((object)"Loaded ShotgunCenterFire"); } }
plugins/net6/TerminalGames.dll
Decompiled a month agousing System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Core.Logging.Interpolation; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using GTFO.API; using HarmonyLib; using Il2CppSystem; using Il2CppSystem.Collections.Generic; using LevelGeneration; using Localization; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("TerminalGames")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("TerminalGames")] [assembly: AssemblyTitle("TerminalGames")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace TerminalGames { public struct CommandDescriptor { public TERM_Command Type; public string Command; public string Description; public TERM_CommandRule Rule; } public class Game { public enum GameType { Tictactoe, Connect4, Othello } public enum GameMode { Solo, Multi, Local } public static ManualLogSource Log; public List<int> symbols = new List<int> { 1, 2 }; private GameType type; private GameMode mode; private List<List<int>> board = new List<List<int>>(); private static List<Tuple<int, int>> placed_tokens = new List<Tuple<int, int>>(); private bool isActive; private int currentPlayer = 1; public string MakeAIMove() { if (!isActive) { return ""; } List<(int, int)> emptySpots = GetEmptySpots(); int value = ((currentPlayer != 1) ? 1 : 2); foreach (var item in emptySpots) { List<List<int>> list = CopyBoard(); list[item.Item1][item.Item2] = currentPlayer; if (CheckForWin(list)) { MakeMove(item.Item1, item.Item2, currentPlayer); return $"{(ushort)(item.Item2.ToString()[0] + 49)}{item.Item1 + 1}"; } } foreach (var item2 in emptySpots) { List<List<int>> list2 = CopyBoard(); list2[item2.Item1][item2.Item2] = value; if (CheckForWin(list2)) { MakeMove(item2.Item1, item2.Item2, currentPlayer); return $"{(ushort)(item2.Item2.ToString()[0] + 49)}{item2.Item1 + 1}"; } } int index = new Random().Next(emptySpots.Count); var (num, column) = emptySpots[index]; MakeMove(num, column, currentPlayer); return $"{(ushort)(column.ToString()[0] + 49)}{num + 1}"; } private List<(int row, int col)> GetEmptySpots() { List<(int, int)> list = new List<(int, int)>(); for (int i = 0; i < board.Count; i++) { for (int j = 0; j < board[i].Count; j++) { if (IsValidMove(i, j)) { list.Add((i, j)); } } } return list; } private List<List<int>> CopyBoard() { List<List<int>> list = new List<List<int>>(); foreach (List<int> item2 in board) { List<int> item = new List<int>(item2); list.Add(item); } return list; } public bool CheckForWin(List<List<int>>? board_used = null) { if (board_used == null) { board_used = board; } if (type == GameType.Connect4) { if (!CheckRows(4, board_used) && !CheckColumns(4, board_used)) { return CheckDiagonals(4, board_used); } return true; } if (type == GameType.Tictactoe) { if (!CheckRows(3, board_used) && !CheckColumns(3, board_used)) { return CheckDiagonals(3, board_used); } return true; } if (type == GameType.Othello) { bool flag = true; foreach (List<int> item in board) { foreach (int item2 in item) { if (item2 == 0) { flag = false; } } } bool flag2 = false; for (int i = 0; i < board.Count; i++) { for (int j = 0; j < board[0].Count; j++) { if (IsValidMove(i, j)) { flag2 = true; } } } int num = CountPieces(1); int num2 = CountPieces(2); if (flag || !flag2) { return num != num2; } return false; } return false; } private bool CheckRows(int consecutiveSymbols, List<List<int>> board_used) { foreach (int symbol in symbols) { for (int i = 0; i < board_used.Count; i++) { for (int j = 0; j <= board_used[i].Count - consecutiveSymbols; j++) { bool flag = true; for (int k = 0; k < consecutiveSymbols; k++) { if (board_used[i][j + k] != symbol) { flag = false; break; } } if (flag) { return true; } } } } return false; } private bool CheckColumns(int consecutiveSymbols, List<List<int>> board_used) { foreach (int symbol in symbols) { for (int i = 0; i < board_used[0].Count; i++) { for (int j = 0; j <= board_used.Count - consecutiveSymbols; j++) { bool flag = true; for (int k = 0; k < consecutiveSymbols; k++) { if (board_used[j + k][i] != symbol) { flag = false; break; } } if (flag) { return true; } } } } return false; } private bool CheckDiagonals(int consecutiveSymbols, List<List<int>> board_used) { foreach (int symbol in symbols) { for (int i = 0; i <= board_used.Count - consecutiveSymbols; i++) { for (int j = 0; j <= board_used[i].Count - consecutiveSymbols; j++) { bool flag = true; for (int k = 0; k < consecutiveSymbols; k++) { if (board_used[i + k][j + k] != symbol) { flag = false; break; } } if (flag) { return true; } } } for (int l = 0; l <= board_used.Count - consecutiveSymbols; l++) { for (int m = consecutiveSymbols - 1; m < board_used[l].Count; m++) { bool flag2 = true; for (int n = 0; n < consecutiveSymbols; n++) { if (board_used[l + n][m - n] != symbol) { flag2 = false; break; } } if (flag2) { return true; } } } } return false; } public bool CheckForDraw(List<List<int>>? board_used = null) { if (board_used == null) { board_used = board; } if (type == GameType.Othello) { bool flag = true; foreach (List<int> item in board) { foreach (int item2 in item) { if (item2 == 0) { flag = false; break; } } if (!flag) { break; } } bool flag2 = false; for (int i = 0; i < board.Count; i++) { for (int j = 0; j < board[0].Count; j++) { if (IsValidMove(i, j)) { flag2 = true; break; } } if (flag2) { break; } } int num = CountPieces(1); int num2 = CountPieces(2); if (flag || !flag2) { return num == num2; } return false; } for (int k = 0; k < board_used.Count; k++) { for (int l = 0; l < board_used[k].Count; l++) { if (board_used[k][l] == 0) { return false; } } } return true; } private int CountPieces(int player) { int num = 0; foreach (List<int> item in board) { foreach (int item2 in item) { if (item2 == player) { num++; } } } return num; } private void InitializeBoard(int rows, int columns) { board = new List<List<int>>(rows); for (int i = 0; i < rows; i++) { board.Add(new List<int>(columns)); for (int j = 0; j < columns; j++) { board[i].Add(0); } } } public void StopGame() { currentPlayer = 1; isActive = false; } public string SetGameType(string input, string input2) { if (isActive) { return "A game is already being played."; } if (Enum.TryParse<GameType>(input, ignoreCase: true, out var result)) { type = result; isActive = true; switch (type) { case GameType.Tictactoe: InitializeBoard(3, 3); break; case GameType.Connect4: InitializeBoard(6, 7); break; case GameType.Othello: InitializeBoard(8, 8); board[3][3] = 1; board[4][4] = 1; board[3][4] = 2; board[4][3] = 2; break; } if (Enum.TryParse<GameMode>(input2, ignoreCase: true, out var result2)) { mode = result2; } else { mode = GameMode.Solo; } return ""; } return "Invalid Game Type input."; } public static string ConvertCoordinate(string coordinate, out int row, out int column) { row = -1; column = -1; if (coordinate.Length < 1 || coordinate.Length > 2) { return "Invalid coordinate format. Please use a format like 'a2'."; } char c = coordinate[0]; if (coordinate.Length == 2) { if (!int.TryParse(coordinate[1].ToString(), out row)) { return "Invalid row coordinate. Please use a format like 'a2'."; } row--; } column = c - 97; return ""; } public List<string> MakeMove(string coordinate, int terminalPlayer) { if (isActive && ConvertCoordinate(coordinate, out var row, out var column) == "") { return MakeMove(row, column, terminalPlayer); } return new List<string> { "Invalid move. Please try again." }; } public List<string> MakeMove(int row, int column, int terminalPlayer) { if (terminalPlayer != currentPlayer) { return new List<string> { "This not your turn to play." }; } if (type == GameType.Connect4) { while (row < board.Count - 1 && board[row + 1][column] == 0) { row++; } } if (IsValidMove(row, column)) { placed_tokens = new List<Tuple<int, int>> { new Tuple<int, int>(row, column) }; board[row][column] = currentPlayer; if (type == GameType.Othello) { int num = ((currentPlayer != 1) ? 1 : 2); for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if (i == 0 && j == 0) { continue; } int num2 = row + i; int num3 = column + j; if (num2 < 0 || num2 >= board.Count || num3 < 0 || num3 >= board[0].Count || board[num2][num3] != num) { continue; } List<(int, int)> list = new List<(int, int)>(); while (num2 >= 0 && num2 < board.Count && num3 >= 0 && num3 < board[0].Count && board[num2][num3] == num) { list.Add((num2, num3)); num2 += i; num3 += j; } if (num2 < 0 || num2 >= board.Count || num3 < 0 || num3 >= board[0].Count || board[num2][num3] != currentPlayer) { continue; } foreach (var (num4, num5) in list) { board[num4][num5] = currentPlayer; placed_tokens.Add(new Tuple<int, int>(num4, num5)); } } } } if (currentPlayer == 1) { currentPlayer = 2; } else { currentPlayer = 1; } return DisplayBoard(); } return new List<string> { "Invalid move. Please try again." }; } private bool IsValidMove(int row, int column) { bool flag = row >= 0 && row < board.Count && column >= 0 && column < board[row].Count && board[row][column] == 0; if (type == GameType.Connect4) { bool flag2 = row == board.Count - 1; bool flag3 = row < board.Count - 1 && board[row + 1][column] != 0; flag = flag && (flag2 || flag3); } else if (flag && type == GameType.Othello) { int num = ((currentPlayer != 1) ? 1 : 2); for (int i = -1; i <= 1; i++) { for (int j = -1; j <= 1; j++) { if (i == 0 && j == 0) { continue; } int num2 = row + i; int num3 = column + j; if (num2 >= 0 && num2 < board.Count && num3 >= 0 && num3 < board[0].Count && board[num2][num3] == num) { while (num2 >= 0 && num2 < board.Count && num3 >= 0 && num3 < board[0].Count && board[num2][num3] == num) { num2 += i; num3 += j; } if (num2 >= 0 && num2 < board.Count && num3 >= 0 && num3 < board[0].Count && board[num2][num3] == currentPlayer) { return true; } } } } return false; } return flag; } public bool IsGameActive() { return isActive; } public GameMode GetGameMode() { return mode; } public GameType GetGameType() { return type; } public int GetCurrentPlayer() { return currentPlayer; } public Game Copy() { Game game = new Game { type = type, mode = mode, isActive = isActive, currentPlayer = currentPlayer, board = new List<List<int>>(board.Count) }; for (int i = 0; i < board.Count; i++) { game.board.Add(new List<int>(board[i])); } return game; } public List<string> DisplayBoard() { List<string> list = new List<string> { "", " " + string.Join(" ", GetColumnLetters(board[0].Count)) }; for (int i = 0; i < board.Count; i++) { list.Add($"{i + 1} |{string.Join(" ", GetRowSymbols(board[i], i))}|"); } list.Add(""); return list; } private static string[] GetRowSymbols(List<int> row, int rowIndex) { string[] array = new string[row.Count]; for (int i = 0; i < row.Count; i++) { string text = GetPlayerColor(row[i]); for (int j = 0; j < placed_tokens.Count; j++) { if (placed_tokens[j].Item1 == rowIndex && placed_tokens[j].Item2 == i) { text = "<color=green>"; break; } } array[i] = text + GetSymbol(row[i]) + "</color>"; } return array; } private static char[] GetColumnLetters(int columnCount) { char[] array = new char[columnCount]; for (int i = 0; i < columnCount; i++) { array[i] = (char)(97 + i); } return array; } private static string GetSymbol(int player) { return player switch { 1 => "X", 2 => "O", _ => " ", }; } public static string GetPlayerColor(int player) { return player switch { 1 => "<color=purple>", 2 => "<color=yellow>", _ => "", }; } } [HarmonyPatch(typeof(LG_ComputerTerminalCommandInterpreter), "ReceiveCommand")] internal class Inject_Terminal_ReceiveCmd { public static ManualLogSource Log; public static event Action<LG_ComputerTerminalCommandInterpreter, TERM_Command, string, string, string> OnCmdUsed_LevelInstanced; static Inject_Terminal_ReceiveCmd() { LevelAPI.OnLevelCleanup += delegate { Inject_Terminal_ReceiveCmd.OnCmdUsed_LevelInstanced = null; }; } private static void Postfix(LG_ComputerTerminalCommandInterpreter __instance, TERM_Command cmd, string inputLine, string param1, string param2) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) Inject_Terminal_ReceiveCmd.OnCmdUsed_LevelInstanced?.Invoke(__instance, cmd, inputLine, param1, param2); } } internal static class Patch { public class MonoPatch : MonoBehaviour { public static ManualLogSource? Log; public static List<EnrichedTerminal> enriched_terminals = new List<EnrichedTerminal>(); public static void Initialize() { List<LG_Zone> zones = Builder.Current.m_currentFloor.MainDimension.Layers[0].m_zones; for (int i = 0; i < zones.Count; i++) { List<LG_ComputerTerminal> terminalsSpawnedInZone = zones[i].TerminalsSpawnedInZone; for (int j = 0; j < terminalsSpawnedInZone.Count; j++) { LG_ComputerTerminal val = terminalsSpawnedInZone[j]; EnrichedTerminal enrichedTerminal = new EnrichedTerminal { ComputerTerminal = val, CmdProcessor = val.m_command, Interaction = ((Component)val).GetComponentInChildren<Interact_ComputerTerminal>(true) }; enrichedTerminal.SetTerminalListIndex(enriched_terminals.Count); enrichedTerminal.Setup(); enriched_terminals.Add(enrichedTerminal); } } } } } [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInPlugin("TerminalGames", "TerminalGames", "1.0.2")] public class Plugin : BasePlugin { private Harmony _Harmony; public override void Load() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Expected O, but got Unknown _Harmony = new Harmony("TerminalGames"); _Harmony.PatchAll(); Patch.MonoPatch.Log = ((BasePlugin)this).Log; EnrichedTerminal.Log = ((BasePlugin)this).Log; Game.Log = ((BasePlugin)this).Log; ((BasePlugin)this).AddComponent<Patch.MonoPatch>(); EventAPI.OnExpeditionStarted += Patch.MonoPatch.Initialize; ManualLogSource log = ((BasePlugin)this).Log; bool flag = default(bool); BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(35, 0, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Plugin TerminalGames is now loaded."); } log.LogInfo(val); } } public class EnrichedTerminal { public static ManualLogSource Log; private LocalizedText _GCTextHolder; private Game current_game = new Game(); private int player = 1; private int TerminalListIndex; private int OtherTerminalListIndex = -1; public const TERM_Command COMMAND_PLAY = 255; public const TERM_Command COMMAND_PLACE = 254; public const TERM_Command COMMAND_STOP = 253; public const TERM_Command COMMAND_JOIN = 252; public LG_ComputerTerminal ComputerTerminal { get; set; } public LG_ComputerTerminalCommandInterpreter CmdProcessor { get; set; } public Interact_ComputerTerminal Interaction { get; set; } public event Action<TERM_Command, string, string, string> OnCmdUsed; public void AddCommand(CommandDescriptor descriptor, Action<LG_ComputerTerminalCommandInterpreter, string, string>? onCommandUsed = null) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Expected O, but got Unknown //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Expected O, but got Unknown //IL_0058: Unknown result type (might be due to invalid IL or missing references) Action<LG_ComputerTerminalCommandInterpreter, string, string> onCommandUsed2 = onCommandUsed; if (CmdProcessor.HasRegisteredCommand(descriptor.Type)) { ManualLogSource log = Log; bool flag = default(bool); BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(33, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Command Type: "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<TERM_Command>(descriptor.Type); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" is Already Added!!"); } log.LogError(val); return; } _GCTextHolder = new LocalizedText { UntranslatedText = descriptor.Description, Id = 0u }; CmdProcessor.AddCommand(descriptor.Type, descriptor.Command, _GCTextHolder, descriptor.Rule); OnCmdUsed += delegate(TERM_Command cmdType, string cmdStr, string param1, string param2) { //IL_0000: 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) if (cmdType == descriptor.Type) { onCommandUsed2?.Invoke(CmdProcessor, param1, param2); } }; } public void AddPlayCommand(string cmd, string helpText, Action<LG_ComputerTerminalCommandInterpreter>? onCommandUsed = null) { //IL_002a: 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) Action<LG_ComputerTerminalCommandInterpreter> onCommandUsed2 = onCommandUsed; string cmd2 = cmd; CommandDescriptor commandDescriptor = default(CommandDescriptor); commandDescriptor.Type = (TERM_Command)255; commandDescriptor.Command = cmd2; commandDescriptor.Description = helpText; commandDescriptor.Rule = (TERM_CommandRule)0; CommandDescriptor descriptor = commandDescriptor; AddCommand(descriptor, delegate(LG_ComputerTerminalCommandInterpreter interpreter, string param1, string param2) { onCommandUsed2?.Invoke(interpreter); interpreter.AddOutput((TerminalLineType)0, $"Desired Action: <color=orange>{cmd2}</color> <color=yellow>{param1}</color>", 0.5f, (TerminalSoundType)0, (TerminalSoundType)0); if (param1 != null && param1.Length > 0) { string text = current_game.SetGameType(param1, param2); if (text.Length > 0) { interpreter.AddOutput((TerminalLineType)0, "<color=red>" + text + "</color>", 0.65f, (TerminalSoundType)0, (TerminalSoundType)0); } else { interpreter.AddOutput((TerminalLineType)4, "Preparing game..", 0.85f, (TerminalSoundType)0, (TerminalSoundType)0); interpreter.AddOutput((TerminalLineType)0, "<color=green>New game created!</color> " + Game.GetPlayerColor(player) + "You</color><color=green> can start playing!</color>", 0.65f, (TerminalSoundType)0, (TerminalSoundType)0); List<string> list = current_game.DisplayBoard(); list.Add("<color=green>PLACE {coordinates}</color> to place a move."); foreach (string item in list) { interpreter.AddOutput((TerminalLineType)0, item, 0.02f, (TerminalSoundType)0, (TerminalSoundType)0); } if (current_game.GetGameMode() == Game.GameMode.Multi) { OtherTerminalListIndex = -1; interpreter.AddOutput((TerminalLineType)0, $"The other player can join the game with <color=green>JOIN Terminal_{ComputerTerminal.m_serialNumber}</color>", 0.65f, (TerminalSoundType)0, (TerminalSoundType)0); } } } else { interpreter.AddOutput((TerminalLineType)0, "<color=red>You have to specify a game to play.</color>", 0.5f, (TerminalSoundType)0, (TerminalSoundType)0); } }); } public void AddPlaceCommand(string cmd, string helpText, Action<LG_ComputerTerminalCommandInterpreter>? onCommandUsed = null) { //IL_002a: 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) Action<LG_ComputerTerminalCommandInterpreter> onCommandUsed2 = onCommandUsed; string cmd2 = cmd; CommandDescriptor commandDescriptor = default(CommandDescriptor); commandDescriptor.Type = (TERM_Command)254; commandDescriptor.Command = cmd2; commandDescriptor.Description = helpText; commandDescriptor.Rule = (TERM_CommandRule)0; CommandDescriptor descriptor = commandDescriptor; AddCommand(descriptor, delegate(LG_ComputerTerminalCommandInterpreter interpreter, string param1, string param2) { LG_ComputerTerminalCommandInterpreter interpreter2 = interpreter; onCommandUsed2?.Invoke(interpreter2); if (!current_game.IsGameActive()) { interpreter2.AddOutput((TerminalLineType)0, "<color=red>There is no active game yet.</color>", 0.5f, (TerminalSoundType)0, (TerminalSoundType)0); } else if (current_game.GetGameMode() == Game.GameMode.Multi && OtherTerminalListIndex == -1) { interpreter2.AddOutput((TerminalLineType)0, "<color=red>You have to wait for a player to join the game.</color>", 0.02f, (TerminalSoundType)0, (TerminalSoundType)0); } else { interpreter2.AddOutput((TerminalLineType)0, $"Desired Action: <color=orange>{cmd2}</color> <color=yellow>{param1}</color>", 0.5f, (TerminalSoundType)0, (TerminalSoundType)0); List<string> list = current_game.MakeMove(param1, player); if (list.Count == 1) { interpreter2.AddOutput((TerminalLineType)0, "<color=red>" + list[0] + "</color>", 0.02f, (TerminalSoundType)0, (TerminalSoundType)0); } else { if (IsMultiJoined()) { Patch.MonoPatch.enriched_terminals[OtherTerminalListIndex].current_game.MakeMove(param1, player); } foreach (string item in list) { interpreter2.AddOutput((TerminalLineType)0, item, 0.02f, (TerminalSoundType)0, (TerminalSoundType)0); if (IsMultiJoined()) { Patch.MonoPatch.enriched_terminals[OtherTerminalListIndex].CmdProcessor.AddOutput((TerminalLineType)0, item, 0.02f, (TerminalSoundType)0, (TerminalSoundType)0); } } if (current_game.CheckForWin()) { interpreter2.AddOutput((TerminalLineType)0, $"<color=green>Hurray! The {Game.GetPlayerColor(player)}player {player}</color> <color=green>won! </color></color>", 0.7f, (TerminalSoundType)0, (TerminalSoundType)0); if (IsMultiJoined()) { Patch.MonoPatch.enriched_terminals[OtherTerminalListIndex].CmdProcessor.AddOutput((TerminalLineType)0, $"<color=green>Hurray! The {Game.GetPlayerColor(player)}player {player}</color> <color=green>won! </color></color>", 0.7f, (TerminalSoundType)0, (TerminalSoundType)0); StopMultiGame(); } player = 1; current_game.StopGame(); } else if (current_game.CheckForDraw()) { interpreter2.AddOutput((TerminalLineType)0, "<color=orange>No one won... Game's over.</color>", 0.7f, (TerminalSoundType)0, (TerminalSoundType)0); if (IsMultiJoined()) { Patch.MonoPatch.enriched_terminals[OtherTerminalListIndex].CmdProcessor.AddOutput((TerminalLineType)0, "<color=orange>No one won... Game's over.</color>", 0.7f, (TerminalSoundType)0, (TerminalSoundType)0); StopMultiGame(); } player = 1; current_game.StopGame(); } else { if (current_game.GetGameMode() == Game.GameMode.Local) { SetEndOfQueue(delegate { interpreter2.AddOutput((TerminalLineType)5, Game.GetPlayerColor(player) + "Player " + player + "</color>'s turn.", 1.2f, (TerminalSoundType)0, (TerminalSoundType)0); }); } else if (IsMultiJoined()) { SetEndOfQueue(delegate { interpreter2.AddOutput((TerminalLineType)5, Game.GetPlayerColor(current_game.GetCurrentPlayer()) + "Other player</color>'s turn.", 1.2f, (TerminalSoundType)0, (TerminalSoundType)0); }); Patch.MonoPatch.enriched_terminals[OtherTerminalListIndex].SetEndOfQueue(delegate { Patch.MonoPatch.enriched_terminals[OtherTerminalListIndex].CmdProcessor.AddOutput((TerminalLineType)5, Game.GetPlayerColor(current_game.GetCurrentPlayer()) + "Your turn</color>.", 1.2f, (TerminalSoundType)0, (TerminalSoundType)0); }); } if (current_game.GetGameMode() == Game.GameMode.Solo) { Random random = new Random(); interpreter2.AddOutput((TerminalLineType)4, Game.GetPlayerColor((player != 1) ? 1 : 2) + "AI</color> is thinking..", (float)(0.4 + random.NextDouble()), (TerminalSoundType)0, (TerminalSoundType)0); string text = current_game.MakeAIMove().ToUpper(); interpreter2.AddOutput((TerminalLineType)0, Game.GetPlayerColor((player != 1) ? 1 : 2) + "AI placed on</color> <color=orange>" + text + "</color>", 0.1f, (TerminalSoundType)0, (TerminalSoundType)0); foreach (string item2 in current_game.DisplayBoard()) { interpreter2.AddOutput((TerminalLineType)0, item2, 0.02f, (TerminalSoundType)0, (TerminalSoundType)0); } interpreter2.AddOutput((TerminalLineType)0, Game.GetPlayerColor(player) + "Your turn.</color>", 0.7f, (TerminalSoundType)0, (TerminalSoundType)0); if (current_game.CheckForWin()) { interpreter2.AddOutput((TerminalLineType)0, "<color=red>The AI won.</color>", 0.7f, (TerminalSoundType)0, (TerminalSoundType)0); player = 1; current_game.StopGame(); } else if (current_game.CheckForDraw()) { interpreter2.AddOutput((TerminalLineType)0, "<color=orange>No one won... Game's over.</color>", 0.7f, (TerminalSoundType)0, (TerminalSoundType)0); player = 1; current_game.StopGame(); } } if (current_game.GetGameMode() == Game.GameMode.Local) { if (player == 1) { player = 2; } else { player = 1; } } } } } }); } public void AddStopCommand(string cmd, string helpText, Action<LG_ComputerTerminalCommandInterpreter>? onCommandUsed = null) { //IL_002a: 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) Action<LG_ComputerTerminalCommandInterpreter> onCommandUsed2 = onCommandUsed; string cmd2 = cmd; CommandDescriptor commandDescriptor = default(CommandDescriptor); commandDescriptor.Type = (TERM_Command)253; commandDescriptor.Command = cmd2; commandDescriptor.Description = helpText; commandDescriptor.Rule = (TERM_CommandRule)0; CommandDescriptor descriptor = commandDescriptor; AddCommand(descriptor, delegate(LG_ComputerTerminalCommandInterpreter interpreter, string param1, string param2) { onCommandUsed2?.Invoke(interpreter); interpreter.AddOutput((TerminalLineType)0, "Desired Action: <color=orange>" + cmd2 + "</color>", 0.5f, (TerminalSoundType)0, (TerminalSoundType)0); if (current_game.IsGameActive()) { if (IsMultiJoined()) { Patch.MonoPatch.enriched_terminals[OtherTerminalListIndex].CmdProcessor.AddOutput((TerminalLineType)4, "Stopping game from remote terminal..", 0.85f, (TerminalSoundType)0, (TerminalSoundType)0); Patch.MonoPatch.enriched_terminals[OtherTerminalListIndex].CmdProcessor.AddOutput((TerminalLineType)0, "<color=orange>The game has been stopped.</color>", 0.65f, (TerminalSoundType)0, (TerminalSoundType)0); StopMultiGame(); } interpreter.AddOutput((TerminalLineType)4, "Stopping game..", 0.85f, (TerminalSoundType)0, (TerminalSoundType)0); interpreter.AddOutput((TerminalLineType)0, "<color=orange>The game has been stopped.</color>", 0.65f, (TerminalSoundType)0, (TerminalSoundType)0); player = 1; current_game.StopGame(); } else { interpreter.AddOutput((TerminalLineType)0, "<color=red>There is no game currently played.</color>", 0.5f, (TerminalSoundType)0, (TerminalSoundType)0); } }); } public void AddJoinCommand(string cmd, string helpText, Action<LG_ComputerTerminalCommandInterpreter>? onCommandUsed = null) { //IL_002a: 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) Action<LG_ComputerTerminalCommandInterpreter> onCommandUsed2 = onCommandUsed; string cmd2 = cmd; CommandDescriptor commandDescriptor = default(CommandDescriptor); commandDescriptor.Type = (TERM_Command)252; commandDescriptor.Command = cmd2; commandDescriptor.Description = helpText; commandDescriptor.Rule = (TERM_CommandRule)0; CommandDescriptor descriptor = commandDescriptor; AddCommand(descriptor, delegate(LG_ComputerTerminalCommandInterpreter interpreter, string param1, string param2) { LG_ComputerTerminalCommandInterpreter interpreter2 = interpreter; onCommandUsed2?.Invoke(interpreter2); interpreter2.AddOutput((TerminalLineType)0, "Desired Action: <color=orange>" + cmd2 + "</color>", 0.5f, (TerminalSoundType)0, (TerminalSoundType)0); if (current_game.IsGameActive()) { interpreter2.AddOutput((TerminalLineType)0, "<color=red>There is already a game currently being played.</color>", 0.5f, (TerminalSoundType)0, (TerminalSoundType)0); } else { interpreter2.AddOutput((TerminalLineType)4, "Finding game..", 0.85f, (TerminalSoundType)0, (TerminalSoundType)0); if (param1 != null) { param1 = param1.ToLower(); } if (param1 != null && param1.Length > 0 && param1.Contains("terminal_")) { param1 = param1.Split("terminal_")[1]; if (param1 == ComputerTerminal.m_serialNumber.ToString()) { interpreter2.AddOutput((TerminalLineType)0, "<color=red>You cannot play as the other player on the same terminal.</color>", 0.5f, (TerminalSoundType)0, (TerminalSoundType)0); } else { OtherTerminalListIndex = -1; for (int i = 0; i < Patch.MonoPatch.enriched_terminals.Count; i++) { EnrichedTerminal enrichedTerminal = Patch.MonoPatch.enriched_terminals[i]; if (i != TerminalListIndex && enrichedTerminal.ComputerTerminal.m_serialNumber.ToString() == param1) { if (enrichedTerminal.OtherTerminalListIndex != -1) { interpreter2.AddOutput((TerminalLineType)0, "<color=red>A player has already joined the game on this terminal.</color>", 0.5f, (TerminalSoundType)0, (TerminalSoundType)0); } else { if (enrichedTerminal.current_game.IsGameActive() && enrichedTerminal.current_game.GetGameMode() == Game.GameMode.Multi) { current_game = enrichedTerminal.current_game.Copy(); if (enrichedTerminal.player == 1) { player = 2; } else { player = 2; } OtherTerminalListIndex = i; enrichedTerminal.OtherTerminalListIndex = TerminalListIndex; enrichedTerminal.CmdProcessor.AddOutput((TerminalLineType)0, $"<color=orange>A player has joined you from </color><color=green>Terminal_{ComputerTerminal.m_serialNumber}</color><color=orange>!</color>", 0.5f, (TerminalSoundType)0, (TerminalSoundType)0); enrichedTerminal.CmdProcessor.AddOutput((TerminalLineType)5, Game.GetPlayerColor(current_game.GetCurrentPlayer()) + "Your turn</color>.", 1.2f, (TerminalSoundType)0, (TerminalSoundType)0); break; } interpreter2.AddOutput((TerminalLineType)0, "<color=red>No multiplayer game found on that terminal.</color>", 0.5f, (TerminalSoundType)0, (TerminalSoundType)0); } return; } } if (OtherTerminalListIndex == -1) { interpreter2.AddOutput((TerminalLineType)0, "<color=red>No other terminal found with that ID.</color>", 0.5f, (TerminalSoundType)0, (TerminalSoundType)0); } else { interpreter2.AddOutput((TerminalLineType)4, "Fetching board..", 0.85f, (TerminalSoundType)0, (TerminalSoundType)0); foreach (string item in current_game.DisplayBoard()) { interpreter2.AddOutput((TerminalLineType)0, item, 0.02f, (TerminalSoundType)0, (TerminalSoundType)0); } SetEndOfQueue(delegate { interpreter2.AddOutput((TerminalLineType)5, Game.GetPlayerColor(current_game.GetCurrentPlayer()) + "Other player</color>'s turn.", 1.2f, (TerminalSoundType)0, (TerminalSoundType)0); }); } } } else { interpreter2.AddOutput((TerminalLineType)0, "<color=red>Wrong syntax for JOIN command.</color>", 0.5f, (TerminalSoundType)0, (TerminalSoundType)0); } } }); } public void Setup() { Inject_Terminal_ReceiveCmd.OnCmdUsed_LevelInstanced += OnReceiveCommand; AddPlayCommand("play", "{<color=orange>TICTACTOE</color>, <color=orange>CONNECT4</color>, <color=orange>OTHELLO</color>}</color> {<color=green>SOLO</color>, <color=green>MULTI</color>, <color=green>LOCAL</color>}"); AddPlaceCommand("place", "Once a game is started, place on given <color=orange>{coordinates}</color>. <color=blue> Ex: PLACE A2</color>"); AddStopCommand("stop", "Once a game is started, <color=red>stops</color> the current game"); AddJoinCommand("join", "Joins the game from its {<color=orange>Terminal ID</color>}. <color=blue> Ex: JOIN Terminal_284</color>"); } private void OnReceiveCommand(LG_ComputerTerminalCommandInterpreter interpreter, TERM_Command cmd, string inputLine, string param1, string param2) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) if (interpreter.m_terminal.m_syncID == ComputerTerminal.m_syncID) { this.OnCmdUsed?.Invoke(cmd, inputLine, param1, param2); } } public void SetEndOfQueue(Action onEndOfQueue) { CmdProcessor.OnEndOfQueue = Action.op_Implicit(onEndOfQueue); } public bool IsMultiJoined() { if (OtherTerminalListIndex != -1) { return current_game.GetGameMode() == Game.GameMode.Multi; } return false; } public void StopMultiGame() { Patch.MonoPatch.enriched_terminals[OtherTerminalListIndex].current_game.StopGame(); Patch.MonoPatch.enriched_terminals[OtherTerminalListIndex].OtherTerminalListIndex = -1; Patch.MonoPatch.enriched_terminals[OtherTerminalListIndex].player = 1; OtherTerminalListIndex = -1; } public void SetTerminalListIndex(int index) { TerminalListIndex = index; } } [GeneratedCode("VersionInfoGenerator", "2.0.0+git50a4b1a-master")] [CompilerGenerated] internal static class VersionInfo { public const string RootNamespace = "TerminalGames"; public const string Version = "1.0.0"; public const string VersionPrerelease = null; public const string VersionMetadata = null; public const string SemVer = "1.0.0"; public const string GitRevShort = null; public const string GitRevLong = null; public const string GitBranch = null; public const string GitTag = null; public const bool GitIsDirty = false; } }
plugins/net6/WardenIntelOhBehave.dll
Decompiled a month agousing System; using System.CodeDom.Compiler; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Core.Logging.Interpolation; using BepInEx.Logging; using BepInEx.Unity.IL2CPP; using Il2CppSystem; using LevelGeneration; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("WardenIntelOhBehave")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0")] [assembly: AssemblyInformationalVersion("1.0.0")] [assembly: AssemblyProduct("WardenIntelOhBehave")] [assembly: AssemblyTitle("WardenIntelOhBehave")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace WardenIntelOhBehave { [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInPlugin("WardenIntelOhBehave", "WardenIntelOhBehave", "0.0.1")] public class Plugin : BasePlugin { public class WardenIntelOhBehave : MonoBehaviour { public static ManualLogSource? Log; public static void Initialize() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected O, but got Unknown if (DropCount > 0) { GuiManager.PlayerLayer.m_wardenIntel.ResetSubObjectiveMesssagQueue(); ManualLogSource? log = Log; bool flag = default(bool); BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(37, 1, ref flag); if (flag) { ((BepInExLogInterpolatedStringHandler)val).AppendLiteral("drop "); ((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(DropCount); ((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" : wardenintel revival attempted"); } log.LogInfo(val); } DropCount++; } } public static int DropCount; public static bool BehaveRunning; public override void Load() { ((BasePlugin)this).AddComponent<WardenIntelOhBehave>(); WardenIntelOhBehave.Log = ((BasePlugin)this).Log; LG_Factory.OnFactoryBuildDone += Action.op_Implicit((Action)WardenIntelOhBehave.Initialize); } } [GeneratedCode("VersionInfoGenerator", "2.0.0+git50a4b1a-master")] [CompilerGenerated] internal static class VersionInfo { public const string RootNamespace = "WardenIntelOhBehave"; public const string Version = "1.0.0"; public const string VersionPrerelease = null; public const string VersionMetadata = null; public const string SemVer = "1.0.0"; public const string GitRevShort = null; public const string GitRevLong = null; public const string GitBranch = null; public const string GitTag = null; public const bool GitIsDirty = false; } }