Decompiled source of OxxickTweaks v1.0.0

BepInEx/plugins/AmmoCheckHandsFix/AmmoCheckHandsFix.dll

Decompiled 12 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("AmmoCheckHandsFix")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0")]
[assembly: AssemblyProduct("Ammo Check Hands Fix")]
[assembly: AssemblyTitle("AmmoCheckHandsFix")]
[assembly: AssemblyVersion("1.1.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace AmmoCheckHandsFix
{
	internal static class ControllerGuard
	{
		internal const string ReloadClipName = "ShotgunReloadOneShell";

		private const string AmmoCheckPluginType = "LCAmmoCheck.LCAmmoCheckPlugin";

		private static AnimationClip _genuineClip;

		private static AnimationClip _inspectClip;

		private static bool _inspectLookupDone;

		private static bool _clipMissingReported;

		internal static AnimationClip GenuineClip => _genuineClip;

		internal static AnimationClip InspectClip
		{
			get
			{
				if (_inspectLookupDone)
				{
					return _inspectClip;
				}
				_inspectLookupDone = true;
				Type type = AccessTools.TypeByName("LCAmmoCheck.LCAmmoCheckPlugin");
				PropertyInfo propertyInfo = ((type != null) ? AccessTools.Property(type, "ShotgunInspectClip") : null);
				if (propertyInfo == null)
				{
					Plugin.Log.LogWarning((object)"Не нашёл клип проверки патронов у LCAmmoCheck — мод обновился?");
					return null;
				}
				try
				{
					object? value = propertyInfo.GetValue(null);
					_inspectClip = (AnimationClip)((value is AnimationClip) ? value : null);
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("Не смог прочитать клип проверки патронов: " + ex.Message));
				}
				return _inspectClip;
			}
		}

		internal static bool Apply(Harmony harmony)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(typeof(StartOfRound), "Awake", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				Plugin.Log.LogWarning((object)"Не нашёл StartOfRound.Awake.");
				return false;
			}
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(ControllerGuard), "AfterStartOfRoundAwake", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Plugin.Log.LogInfo((object)"Пропатчен StartOfRound.Awake");
			return true;
		}

		private static void AfterStartOfRoundAwake(StartOfRound __instance)
		{
			if (!((Object)(object)__instance == (Object)null))
			{
				__instance.localClientAnimatorController = Prepare(__instance.localClientAnimatorController, "локального игрока");
				__instance.otherClientsAnimatorController = Prepare(__instance.otherClientsAnimatorController, "остальных игроков");
			}
		}

		private static RuntimeAnimatorController Prepare(RuntimeAnimatorController source, string whose)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			if ((Object)(object)source == (Object)null)
			{
				return null;
			}
			RememberGenuineClip(source);
			AnimatorOverrideController val = (AnimatorOverrideController)(object)((source is AnimatorOverrideController) ? source : null);
			if (val != null)
			{
				PinReloadClip(val);
				return source;
			}
			if (!Plugin.PreWrapControllers.Value)
			{
				Plugin.Log.LogInfo((object)"Предварительная обёртка контроллеров выключена в конфиге.");
				return source;
			}
			AnimatorOverrideController val2;
			try
			{
				val2 = new AnimatorOverrideController(source);
				((Object)val2).name = ((Object)source).name + " + AmmoCheckHandsFix";
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Не смог обернуть контроллер анимаций " + whose + ": " + ex.Message));
				return source;
			}
			PinReloadClip(val2);
			Plugin.Log.LogInfo((object)("Контроллер анимаций " + whose + " обёрнут заранее — подмены на ходу больше не будет."));
			return (RuntimeAnimatorController)(object)val2;
		}

		private static void PinReloadClip(AnimatorOverrideController controller)
		{
			if ((Object)(object)_genuineClip == (Object)null)
			{
				return;
			}
			try
			{
				controller["ShotgunReloadOneShell"] = _genuineClip;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Не смог закрепить клип перезарядки: " + ex.Message));
			}
		}

		private static void RememberGenuineClip(RuntimeAnimatorController controller)
		{
			if ((Object)(object)_genuineClip != (Object)null)
			{
				return;
			}
			AnimationClip[] animationClips;
			try
			{
				animationClips = controller.animationClips;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Не смог прочитать список клипов: " + ex.Message));
				return;
			}
			if (animationClips != null)
			{
				AnimationClip[] array = animationClips;
				foreach (AnimationClip val in array)
				{
					if ((Object)(object)val != (Object)null && ((Object)val).name == "ShotgunReloadOneShell")
					{
						_genuineClip = val;
						return;
					}
				}
			}
			if (!_clipMissingReported)
			{
				_clipMissingReported = true;
				Plugin.Log.LogWarning((object)"Клип ShotgunReloadOneShell не найден — восстанавливать пропавшую анимацию будет нечем.");
			}
		}
	}
	internal static class HandsWatchdog
	{
		private const string ReloadBool = "ReloadShotgun";

		private const string ReloadBool2 = "ReloadShotgun2";

		private const float ClipCheckInterval = 0.25f;

		private static float stuckFlagTime;

		private static float stuckReloadTime;

		private static float stuckInspectTime;

		private static float clipCheckTimer;

		private static readonly Dictionary<Type, FieldInfo> reloadFields = new Dictionary<Type, FieldInfo>();

		internal static bool Apply(Harmony harmony)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(typeof(PlayerControllerB), "Update", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				Plugin.Log.LogWarning((object)"Не нашёл PlayerControllerB.Update.");
				return false;
			}
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(HandsWatchdog), "AfterUpdate", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Plugin.Log.LogInfo((object)"Пропатчен PlayerControllerB.Update");
			return true;
		}

		private static void AfterUpdate(PlayerControllerB __instance)
		{
			if (!((Object)(object)__instance == (Object)null) && ((NetworkBehaviour)__instance).IsOwner && __instance.isPlayerControlled)
			{
				Animator playerBodyAnimator = __instance.playerBodyAnimator;
				if (!((Object)(object)playerBodyAnimator == (Object)null))
				{
					GrabbableObject currentlyHeldObjectServer = __instance.currentlyHeldObjectServer;
					WatchFlag(playerBodyAnimator, currentlyHeldObjectServer);
					WatchGun(playerBodyAnimator, currentlyHeldObjectServer);
					WatchClip(playerBodyAnimator, currentlyHeldObjectServer);
				}
			}
		}

		private static void WatchFlag(Animator animator, GrabbableObject held)
		{
			bool flag;
			try
			{
				flag = animator.GetBool("ReloadShotgun");
			}
			catch
			{
				return;
			}
			if (!flag || IsActuallyReloading(held))
			{
				stuckFlagTime = 0f;
				return;
			}
			stuckFlagTime += Time.deltaTime;
			if (!(stuckFlagTime < Mathf.Max(0.1f, Plugin.GraceSeconds.Value)))
			{
				stuckFlagTime = 0f;
				animator.SetBool("ReloadShotgun", false);
				animator.SetBool("ReloadShotgun2", false);
				Plugin.Log.LogInfo((object)(((Object)(object)held == (Object)null) ? "Руки залипли в позе перезарядки с пустыми руками — поза сброшена." : ("Руки залипли в позе перезарядки с предметом " + ItemName(held) + " — поза сброшена.")));
			}
		}

		private static void WatchGun(Animator animator, GrabbableObject held)
		{
			float value = Plugin.StuckReloadSeconds.Value;
			if (value <= 0f)
			{
				stuckReloadTime = 0f;
				return;
			}
			FieldInfo fieldInfo = (((Object)(object)held != (Object)null) ? ReloadingField(held) : null);
			if (fieldInfo == null)
			{
				stuckReloadTime = 0f;
				return;
			}
			bool flag;
			try
			{
				flag = (bool)fieldInfo.GetValue(held);
			}
			catch
			{
				stuckReloadTime = 0f;
				return;
			}
			if (!flag)
			{
				stuckReloadTime = 0f;
				return;
			}
			stuckReloadTime += Time.deltaTime;
			if (!(stuckReloadTime < value))
			{
				stuckReloadTime = 0f;
				try
				{
					fieldInfo.SetValue(held, false);
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("Не смог снять зависшую перезарядку: " + ex.Message));
					return;
				}
				animator.SetBool("ReloadShotgun", false);
				animator.SetBool("ReloadShotgun2", false);
				Plugin.Log.LogInfo((object)(ItemName(held) + " завис в перезарядке дольше " + value.ToString("0.#") + " с — состояние сброшено, из ствола снова можно стрелять."));
			}
		}

		private static void WatchClip(Animator animator, GrabbableObject held)
		{
			clipCheckTimer += Time.deltaTime;
			if (clipCheckTimer < 0.25f)
			{
				return;
			}
			float num = clipCheckTimer;
			clipCheckTimer = 0f;
			AnimationClip genuineClip = ControllerGuard.GenuineClip;
			if ((Object)(object)genuineClip == (Object)null)
			{
				return;
			}
			RuntimeAnimatorController runtimeAnimatorController = animator.runtimeAnimatorController;
			AnimatorOverrideController val = (AnimatorOverrideController)(object)((runtimeAnimatorController is AnimatorOverrideController) ? runtimeAnimatorController : null);
			if ((Object)(object)val == (Object)null)
			{
				stuckInspectTime = 0f;
				return;
			}
			AnimationClip val2;
			try
			{
				val2 = val["ShotgunReloadOneShell"];
			}
			catch
			{
				stuckInspectTime = 0f;
				return;
			}
			if ((Object)(object)val2 == (Object)null)
			{
				stuckInspectTime = 0f;
				if (Restore(val, genuineClip))
				{
					Plugin.Log.LogInfo((object)"Анимация перезарядки дробовика пропала — клип возвращён на место.");
				}
				return;
			}
			if ((Object)(object)val2 != (Object)(object)ControllerGuard.InspectClip || IsActuallyReloading(held))
			{
				stuckInspectTime = 0f;
				return;
			}
			stuckInspectTime += num;
			if (!(stuckInspectTime < Mathf.Max(0.5f, Plugin.GraceSeconds.Value) + 4f))
			{
				stuckInspectTime = 0f;
				if (Restore(val, genuineClip))
				{
					Plugin.Log.LogInfo((object)"Клип проверки патронов остался вместо перезарядки — возвращён настоящий.");
				}
			}
		}

		private static bool Restore(AnimatorOverrideController overrides, AnimationClip genuine)
		{
			try
			{
				overrides["ShotgunReloadOneShell"] = genuine;
				return true;
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Не смог вернуть клип перезарядки: " + ex.Message));
				return false;
			}
		}

		private static bool IsActuallyReloading(GrabbableObject held)
		{
			if ((Object)(object)held == (Object)null)
			{
				return false;
			}
			FieldInfo fieldInfo = ReloadingField(held);
			if (fieldInfo == null)
			{
				return false;
			}
			try
			{
				return (bool)fieldInfo.GetValue(held);
			}
			catch
			{
				return false;
			}
		}

		private static FieldInfo ReloadingField(GrabbableObject held)
		{
			Type type = ((object)held).GetType();
			if (reloadFields.TryGetValue(type, out var value))
			{
				return value;
			}
			FieldInfo fieldInfo = null;
			Type type2 = type;
			while (type2 != null && type2 != typeof(MonoBehaviour))
			{
				fieldInfo = type2.GetField("isReloading", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (fieldInfo != null)
				{
					break;
				}
				type2 = type2.BaseType;
			}
			if (fieldInfo != null && fieldInfo.FieldType != typeof(bool))
			{
				fieldInfo = null;
			}
			reloadFields[type] = fieldInfo;
			return fieldInfo;
		}

		private static string ItemName(GrabbableObject held)
		{
			if ((Object)(object)held == (Object)null)
			{
				return "ничего";
			}
			Item itemProperties = held.itemProperties;
			if (!((Object)(object)itemProperties != (Object)null))
			{
				return ((object)held).GetType().Name;
			}
			return itemProperties.itemName;
		}
	}
	[BepInPlugin("oxxick.ammocheckhandsfix", "Ammo Check Hands Fix", "1.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "oxxick.ammocheckhandsfix";

		public const string PluginName = "Ammo Check Hands Fix";

		public const string PluginVersion = "1.1.0";

		internal const string AmmoCheckGuid = "me.axd1x8a.lcammocheck";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<bool> PreWrapControllers;

		internal static ConfigEntry<float> GraceSeconds;

		internal static ConfigEntry<float> StuckReloadSeconds;

		private void Awake()
		{
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bf: Expected O, but got Unknown
			//IL_00c5: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Общее", "Enabled", true, "Чинить поломанные руки после проверки патронов. false — полный откат, плагин ничего не патчит.");
			PreWrapControllers = ((BaseUnityPlugin)this).Config.Bind<bool>("Общее", "PreWrapControllers", true, "Главная починка: заранее обернуть эталонные контроллеры анимаций игры, чтобы мод не подменял контроллер игрока на ходу. Именно подмена ребиндит аниматор посреди игры и ломает руки и походку. false — оставить как есть и чинить только последствия.");
			GraceSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Общее", "GraceSeconds", 1f, "Сколько секунд терпеть поднятый флаг перезарядки, прежде чем считать его залипшим. Нужна выдержка, а не мгновенная проверка: в начале настоящей перезарядки флаг и состояние оружия выставляются не в один и тот же кадр. Меньше 0.5 ставить не стоит.");
			StuckReloadSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Общее", "StuckReloadSeconds", 8f, "Сколько секунд терпеть, что дробовик считает себя перезаряжающимся. Анимация проверки патронов занимает около 2.6 секунды, так что всё, что длится дольше восьми, — это зависшее состояние. 0 — не следить за этим вовсе.");
			if (!Enabled.Value)
			{
				Log.LogInfo((object)"Ammo Check Hands Fix 1.1.0: выключен в конфиге.");
				return;
			}
			Harmony val = new Harmony("oxxick.ammocheckhandsfix");
			bool flag = ControllerGuard.Apply(val);
			bool flag2 = HandsWatchdog.Apply(val);
			if (!flag && !flag2)
			{
				Log.LogWarning((object)"Ammo Check Hands Fix 1.1.0: ничего не встало, чинить руки будет некому.");
				return;
			}
			if (!flag)
			{
				Log.LogWarning((object)"Обёртка контроллеров не встала — останутся только сторожа, подмена на ходу продолжится.");
			}
			if (!flag2)
			{
				Log.LogWarning((object)"Сторожа не встали — останется только обёртка контроллеров.");
			}
			Log.LogInfo((object)"Ammo Check Hands Fix 1.1.0 загружен.");
		}
	}
}

BepInEx/plugins/ChuteQuickStore/ChuteQuickStore.dll

Decompiled 12 hours ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("ChuteQuickStore")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("Chute Quick Store")]
[assembly: AssemblyTitle("ChuteQuickStore")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ChuteQuickStore
{
	internal static class ChutePatch
	{
		private const string ChuteStoreTypeName = "ShipInventoryUpdated.Scripts.ChuteStore";

		private static FieldInfo _triggerField;

		internal static bool Apply(Harmony harmony)
		{
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Expected O, but got Unknown
			Type type = AccessTools.TypeByName("ShipInventoryUpdated.Scripts.ChuteStore");
			if (type == null)
			{
				Plugin.Log.LogWarning((object)"Не нашёл тип ShipInventoryUpdated.Scripts.ChuteStore — мод обновился и переименовал класс?");
				return false;
			}
			MethodInfo methodInfo = AccessTools.Method(type, "Start", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				Plugin.Log.LogWarning((object)"У ShipInventoryUpdated.Scripts.ChuteStore нет метода Start.");
				return false;
			}
			_triggerField = AccessTools.Field(type, "trigger");
			if (_triggerField == null)
			{
				Plugin.Log.LogWarning((object)"Не нашёл поле trigger — возьму триггер поиском по объекту.");
			}
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(ChutePatch), "AfterStart", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			return true;
		}

		private static void AfterStart(MonoBehaviour __instance)
		{
			if ((Object)(object)__instance == (Object)null)
			{
				return;
			}
			InteractTrigger val = null;
			if (_triggerField != null)
			{
				object? value = _triggerField.GetValue(__instance);
				val = (InteractTrigger)((value is InteractTrigger) ? value : null);
			}
			if ((Object)(object)val == (Object)null)
			{
				val = ((Component)__instance).GetComponentInChildren<InteractTrigger>(true);
			}
			if ((Object)(object)val == (Object)null)
			{
				Plugin.Log.LogWarning((object)"У люка не нашёлся InteractTrigger — пауза останется.");
				return;
			}
			float num = Mathf.Max(0f, Plugin.CooldownSeconds.Value);
			val.interactCooldown = num > 0f;
			val.cooldownTime = num;
			val.currentCooldownValue = -1f;
			if (Plugin.HoldSeconds.Value >= 0f)
			{
				val.timeToHold = Plugin.HoldSeconds.Value;
			}
			Plugin.Log.LogInfo((object)$"Люк настроен: кулдаун {num:0.##} с, удержание {val.timeToHold:0.##} с.");
		}
	}
	[BepInPlugin("oxxick.chutequickstore", "Chute Quick Store", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "oxxick.chutequickstore";

		public const string PluginName = "Chute Quick Store";

		public const string PluginVersion = "1.0.0";

		internal const string ShipInventoryGuid = "org.lethalcompanymodding.shipinventoryupdated";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<float> CooldownSeconds;

		internal static ConfigEntry<float> HoldSeconds;

		private void Awake()
		{
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Общее", "Enabled", true, "Убирать простой между закладками предметов в люк.\nfalse — патч не ставится, люк ведёт себя как задумано модом.");
			CooldownSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Общее", "CooldownSeconds", 0f, "Сколько секунд триггер люка простаивает после каждой закладки.\nМод ставит 1. При 0 зажатая E закладывает предметы подряд без пауз.");
			HoldSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Общее", "HoldSeconds", -1f, "Сколько держать E на один предмет, в секундах.\n-1 — не трогать, берётся TimeToStore из конфига самого ShipInventoryUpdated.\nСтавить сюда число нужно только если хочется значение, отличное от мода.");
			if (!Enabled.Value)
			{
				Log.LogInfo((object)"Chute Quick Store 1.0.0: выключен в конфиге, патч не ставится.");
			}
			else if (!ChutePatch.Apply(new Harmony("oxxick.chutequickstore")))
			{
				Log.LogWarning((object)"Chute Quick Store 1.0.0: патч не встал, люк останется с паузой.");
			}
			else
			{
				Log.LogInfo((object)"Chute Quick Store 1.0.0 загружен.");
			}
		}
	}
}

BepInEx/plugins/ChuteScrapKeeper/ChuteScrapKeeper.dll

Decompiled 12 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("ChuteScrapKeeper")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.3.1.0")]
[assembly: AssemblyInformationalVersion("1.3.1")]
[assembly: AssemblyProduct("Chute Scrap Keeper")]
[assembly: AssemblyTitle("ChuteScrapKeeper")]
[assembly: AssemblyVersion("1.3.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ChuteScrapKeeper
{
	internal static class History
	{
		private const int MaxBytes = 262144;

		private static string _path;

		private static bool _failed;

		private static string Path
		{
			get
			{
				if (_path == null)
				{
					_path = System.IO.Path.Combine(Paths.ConfigPath, "oxxick.chutescrapkeeper.history.txt");
				}
				return _path;
			}
		}

		internal static void Write(string what, string contents)
		{
			if (_failed || !Plugin.KeepHistory.Value)
			{
				return;
			}
			try
			{
				Trim();
				File.AppendAllText(Path, DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "  " + what + ": " + contents + Environment.NewLine);
			}
			catch (Exception ex)
			{
				_failed = true;
				Plugin.Log.LogWarning((object)("Не смог записать журнал люка, дальше не пробую: " + ex.Message));
			}
		}

		private static void Trim()
		{
			try
			{
				FileInfo fileInfo = new FileInfo(Path);
				if (fileInfo.Exists && fileInfo.Length >= 262144)
				{
					string[] array = File.ReadAllLines(Path);
					int num = array.Length / 2;
					string[] array2 = new string[array.Length - num];
					Array.Copy(array, num, array2, 0, array2.Length);
					File.WriteAllLines(Path, array2);
				}
			}
			catch
			{
			}
		}
	}
	internal static class Injector
	{
		private const string InventoryTypeName = "ShipInventoryUpdated.Scripts.Inventory";

		private const string ItemDataTypeName = "ShipInventoryUpdated.Objects.ItemData";

		private const string IdentifierTypeName = "ShipInventoryUpdated.Helpers.API.ItemIdentifier";

		private static int _stage;

		private static float _timer;

		internal static void Schedule()
		{
			if (Plugin.InjectEnabled.Value)
			{
				if (_stage != 0)
				{
					Plugin.Log.LogInfo((object)"Доливка уже запланирована в этой сессии.");
					return;
				}
				_stage = 1;
				_timer = 0f;
				Plugin.Log.LogWarning((object)($"Доливка запланирована, жду {Mathf.Max(1f, Plugin.InjectDelaySeconds.Value):0.#} с, " + "пока уляжется загрузка люка."));
			}
		}

		internal static void Tick()
		{
			if (_stage == 0 || _stage >= 3)
			{
				return;
			}
			_timer += Time.deltaTime;
			if (_stage == 1)
			{
				if (!(_timer < Mathf.Max(1f, Plugin.InjectDelaySeconds.Value)))
				{
					_timer = 0f;
					string text = WipePatch.Snapshot();
					Plugin.Log.LogWarning((object)("Перед доливкой в люке " + text));
					History.Write("перед доливкой", text);
					if (!Run())
					{
						_stage = 3;
						History.Write("доливка не выполнена", text);
					}
					else
					{
						_stage = 2;
					}
				}
			}
			else if (!(_timer < 3f))
			{
				_stage = 3;
				string text2 = WipePatch.Snapshot();
				Plugin.Log.LogWarning((object)("После доливки в люке " + text2));
				History.Write("после доливки", text2);
			}
		}

		private static bool Run()
		{
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsServer)
			{
				Plugin.Log.LogInfo((object)"Доливка пропущена: эта машина не хост.");
				return false;
			}
			int num = Mathf.Max(1, Plugin.InjectCount.Value);
			int num2 = Mathf.Max(0, Plugin.InjectTotalValue.Value);
			if (num2 == 0)
			{
				Plugin.Log.LogWarning((object)"Доливка пропущена: сумма равна нулю.");
				return false;
			}
			Item val = FindItem(Plugin.InjectItemName.Value);
			if ((Object)(object)val == (Object)null)
			{
				Plugin.Log.LogError((object)("Доливка не выполнена: предмет «" + Plugin.InjectItemName.Value + "» не найден среди предметов игры."));
				return false;
			}
			Type type = AccessTools.TypeByName("ShipInventoryUpdated.Scripts.Inventory");
			Type type2 = AccessTools.TypeByName("ShipInventoryUpdated.Objects.ItemData");
			Type type3 = AccessTools.TypeByName("ShipInventoryUpdated.Helpers.API.ItemIdentifier");
			MethodInfo methodInfo = ((type != null) ? AccessTools.Method(type, "Add", (Type[])null, (Type[])null) : null);
			MethodInfo methodInfo2 = ((type3 != null) ? AccessTools.Method(type3, "GetID", (Type[])null, (Type[])null) : null);
			if (type2 == null || methodInfo == null || methodInfo2 == null)
			{
				Plugin.Log.LogError((object)"Доливка не выполнена: не нашёл внутренности ShipInventoryUpdated.");
				return false;
			}
			string text;
			try
			{
				text = (string)methodInfo2.Invoke(null, new object[1] { val });
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Доливка не выполнена: не смог получить идентификатор предмета. " + ex.Message));
				return false;
			}
			int num3 = num2 / num;
			int num4 = num2 - num3 * (num - 1);
			Array array = Array.CreateInstance(type2, num);
			FieldInfo fieldInfo = AccessTools.Field(type2, "ID");
			FieldInfo fieldInfo2 = AccessTools.Field(type2, "SCRAP_VALUE");
			FieldInfo fieldInfo3 = AccessTools.Field(type2, "PERSISTED_THROUGH_ROUNDS");
			if (fieldInfo == null || fieldInfo2 == null || fieldInfo3 == null)
			{
				Plugin.Log.LogError((object)"Доливка не выполнена: у ItemData изменились поля.");
				return false;
			}
			for (int i = 0; i < num; i++)
			{
				object obj = Activator.CreateInstance(type2);
				fieldInfo.SetValue(obj, Activator.CreateInstance(fieldInfo.FieldType, text));
				fieldInfo2.SetValue(obj, (i == num - 1) ? num4 : num3);
				fieldInfo3.SetValue(obj, true);
				array.SetValue(obj, i);
			}
			try
			{
				methodInfo.Invoke(null, new object[1] { array });
			}
			catch (Exception ex2)
			{
				Plugin.Log.LogError((object)("Доливка не выполнена: " + ex2.Message));
				return false;
			}
			Plugin.Log.LogWarning((object)($"ДОЛИВКА: в люк добавлено {num} шт. «{val.itemName}» на общую сумму {num2} кр. " + $"(по {num3}, последний {num4}). То, что лежало раньше, осталось на месте."));
			Plugin.InjectEnabled.Value = false;
			Plugin.Log.LogWarning((object)"Выключатель доливки сброшен в false — повторно не сработает.");
			return true;
		}

		private static Item FindItem(string name)
		{
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)instance.allItemsList == (Object)null)
			{
				return null;
			}
			Item val = null;
			foreach (Item items in instance.allItemsList.itemsList)
			{
				if (!((Object)(object)items == (Object)null))
				{
					if (string.Equals(items.itemName, name, StringComparison.OrdinalIgnoreCase))
					{
						return items;
					}
					if ((Object)(object)val == (Object)null && items.isScrap)
					{
						val = items;
					}
				}
			}
			if ((Object)(object)val != (Object)null)
			{
				Plugin.Log.LogWarning((object)("Предмет «" + name + "» не найден, беру первый попавшийся лут: «" + val.itemName + "»."));
			}
			return val;
		}
	}
	[BepInPlugin("oxxick.chutescrapkeeper", "Chute Scrap Keeper", "1.3.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "oxxick.chutescrapkeeper";

		public const string PluginName = "Chute Scrap Keeper";

		public const string PluginVersion = "1.3.1";

		internal const string ShipInventoryGuid = "org.lethalcompanymodding.shipinventoryupdated";

		internal const string LguGuid = "com.malco.lethalcompany.moreshipupgrades";

		internal static ManualLogSource Log;

		internal static Plugin Instance;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<bool> InjectEnabled;

		internal static ConfigEntry<string> InjectItemName;

		internal static ConfigEntry<int> InjectCount;

		internal static ConfigEntry<int> InjectTotalValue;

		internal static ConfigEntry<float> InjectDelaySeconds;

		internal static ConfigEntry<bool> KeepHistory;

		private void Awake()
		{
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Instance = this;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Общее", "Enabled", true, "Распространять апгрейд Scrap Keeper на содержимое люка.\nfalse — патчи не ставятся, при вайпе команды хранилище стирается целиком,\nкак задумано самим ShipInventoryUpdated.\nНужен всем игрокам: без плагина у кого-то одного хранилище сотрётся всем.");
			InjectEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Восстановление", "InjectItemsOnLoad", false, "Разовая доливка предметов в люк при следующей загрузке сохранения. Нужна, чтобы вернуть потерю: править сам файл сохранения нельзя, он зашифрован. Срабатывает ОДИН раз и сама гасит этот выключатель обратно в false. Работает только у хоста и только на том сохранении, которое загрузишь.");
			InjectItemName = ((BaseUnityPlugin)this).Config.Bind<string>("Восстановление", "InjectItemName", "Gold bar", "Какой предмет класть. Имя как в игре. Если не найдётся — возьмётся первый попавшийся лут, о чём будет написано в лог.");
			InjectCount = ((BaseUnityPlugin)this).Config.Bind<int>("Восстановление", "InjectCount", 5, "Сколько предметов положить.");
			InjectTotalValue = ((BaseUnityPlugin)this).Config.Bind<int>("Восстановление", "InjectTotalValue", 53203, "Суммарная стоимость всех предметов в кредитах. Делится поровну, остаток уходит в последний предмет.");
			InjectDelaySeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Восстановление", "InjectDelaySeconds", 8f, "Сколько секунд ждать после загрузки корабля, прежде чем доливать. Пауза обязательна: мод люка грузит своё содержимое через сетевые вызовы, которые выполняются не сразу. Положить предметы раньше — значит положить их в список, который вот-вот перезапишется загрузкой.");
			KeepHistory = ((BaseUnityPlugin)this).Config.Bind<bool>("Общее", "KeepHistory", true, "Вести отдельный журнал по люку в файле oxxick.chutescrapkeeper.history.txt рядом с конфигами. BepInEx перезаписывает свой лог при каждом запуске, и разобрать пропажу задним числом нечем. Журнал только дописывается, пара строк за сессию.");
			if (!Enabled.Value)
			{
				Log.LogInfo((object)"Chute Scrap Keeper 1.3.1: выключен в конфиге, патчи не ставятся.");
			}
			else if (!WipePatch.Apply(new Harmony("oxxick.chutescrapkeeper")))
			{
				Log.LogWarning((object)"Chute Scrap Keeper 1.3.1: патчи не встали, люк будет стираться целиком.");
			}
			else
			{
				Log.LogInfo((object)"Chute Scrap Keeper 1.3.1 загружен.");
			}
		}
	}
	internal static class WipePatch
	{
		private const string PatchesTypeName = "ShipInventoryUpdated.Patches.StartOfRound_Patches";

		private const string InventoryTypeName = "ShipInventoryUpdated.Scripts.Inventory";

		private const string ItemDataTypeName = "ShipInventoryUpdated.Objects.ItemData";

		private const string ScrapKeeperTypeName = "MoreShipUpgrades.UpgradeComponents.TierUpgrades.Items.ScrapKeeper";

		private static bool _insideWipe;

		private static Type _itemDataType;

		private static PropertyInfo _itemsProperty;

		private static MethodInfo _removeMethod;

		private static MethodInfo _checkIfKeptScrap;

		private static MethodInfo _computeChance;

		internal static bool Apply(Harmony harmony)
		{
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Expected O, but got Unknown
			//IL_017a: Expected O, but got Unknown
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_019c: Expected O, but got Unknown
			Type type = AccessTools.TypeByName("ShipInventoryUpdated.Patches.StartOfRound_Patches");
			Type type2 = AccessTools.TypeByName("ShipInventoryUpdated.Scripts.Inventory");
			_itemDataType = AccessTools.TypeByName("ShipInventoryUpdated.Objects.ItemData");
			Type type3 = AccessTools.TypeByName("MoreShipUpgrades.UpgradeComponents.TierUpgrades.Items.ScrapKeeper");
			if (type == null || type2 == null || _itemDataType == null)
			{
				Plugin.Log.LogWarning((object)"Не нашёл типы ShipInventoryUpdated — мод обновился и что-то переименовал?");
				return false;
			}
			if (type3 == null)
			{
				Plugin.Log.LogWarning((object)"Не нашёл MoreShipUpgrades.UpgradeComponents.TierUpgrades.Items.ScrapKeeper — LGU обновился и переименовал класс?");
				return false;
			}
			MethodInfo methodInfo = AccessTools.Method(type, "ReviveDeadPlayers_Prefix", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(type2, "Clear", (Type[])null, (Type[])null);
			_itemsProperty = AccessTools.Property(type2, "Items");
			_removeMethod = AccessTools.Method(type2, "Remove", (Type[])null, (Type[])null);
			_checkIfKeptScrap = AccessTools.Method(type3, "CheckIfKeptScrap", (Type[])null, (Type[])null);
			_computeChance = AccessTools.Method(type3, "ComputeScrapKeeperKeepScrapChance", (Type[])null, (Type[])null);
			if (methodInfo == null || methodInfo2 == null || _itemsProperty == null || _removeMethod == null)
			{
				Plugin.Log.LogWarning((object)"Не нашёл нужные методы у ShipInventoryUpdated.");
				return false;
			}
			if (_checkIfKeptScrap == null || _computeChance == null)
			{
				Plugin.Log.LogWarning((object)"Не нашёл методы Scrap Keeper у LGU.");
				return false;
			}
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(WipePatch), "EnterWipe", (Type[])null), new HarmonyMethod(typeof(WipePatch), "ExitWipe", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)methodInfo2, new HarmonyMethod(typeof(WipePatch), "BeforeClear", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			AttachWatchers(harmony);
			return true;
		}

		private static void AttachWatchers(Harmony harmony)
		{
			Watch(harmony, AccessTools.Method(typeof(GameNetworkManager), "SaveItemsInShip", (Type[])null, (Type[])null), "AfterSave");
			Watch(harmony, AccessTools.Method(typeof(StartOfRound), "LoadShipGrabbableItems", (Type[])null, (Type[])null), "AfterLoad");
			if (Plugin.InjectEnabled.Value)
			{
				Watch(harmony, AccessTools.Method(typeof(StartOfRound), "Update", (Type[])null, (Type[])null), "DriveInjector");
			}
		}

		private static void Watch(Harmony harmony, MethodInfo target, string handler)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Expected O, but got Unknown
			if (target == null)
			{
				Plugin.Log.LogWarning((object)("Не нашёл метод для слежения: " + handler));
				return;
			}
			try
			{
				harmony.Patch((MethodBase)target, (HarmonyMethod)null, new HarmonyMethod(typeof(WipePatch), handler, (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Не удалось повесить слежение " + handler + ": " + ex.Message));
			}
		}

		internal static string Snapshot()
		{
			try
			{
				if (!(_itemsProperty.GetValue(null) is Array array))
				{
					return "не прочитать";
				}
				if (array.Length == 0)
				{
					return "пусто";
				}
				int num = 0;
				FieldInfo fieldInfo = AccessTools.Field(_itemDataType, "SCRAP_VALUE");
				if (fieldInfo != null)
				{
					for (int i = 0; i < array.Length; i++)
					{
						num += (int)fieldInfo.GetValue(array.GetValue(i));
					}
				}
				return $"{array.Length} шт. на {num} кр.";
			}
			catch (Exception ex)
			{
				return "ошибка чтения: " + ex.Message;
			}
		}

		private static void DriveInjector()
		{
			Injector.Tick();
		}

		private static void Report(string message)
		{
			Plugin.Log.LogInfo((object)message);
			History.Write("вайп", message);
		}

		private static void AfterSave()
		{
			string text = Snapshot();
			Plugin.Log.LogInfo((object)("Сохранение игры: в люке " + text));
			History.Write("сохранение игры", text);
		}

		private static void AfterLoad()
		{
			string text = Snapshot();
			Plugin.Log.LogInfo((object)("Загрузка корабля: в люке " + text + " (список ещё не применён, это ожидаемо)"));
			History.Write("загрузка корабля", text);
			Injector.Schedule();
		}

		private static void EnterWipe()
		{
			_insideWipe = true;
		}

		private static void ExitWipe()
		{
			_insideWipe = false;
		}

		private static bool BeforeClear()
		{
			if (!_insideWipe)
			{
				string text = Snapshot();
				Plugin.Log.LogInfo((object)("Люк стирается вне вайпа (сброс корабля или загрузка). Было: " + text));
				History.Write("стирание вне вайпа", text);
				return true;
			}
			bool flag;
			try
			{
				flag = (bool)_checkIfKeptScrap.Invoke(null, null);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Не смог спросить у LGU про Scrap Keeper: " + ex.Message));
				return true;
			}
			if (!flag)
			{
				return true;
			}
			NetworkManager singleton = NetworkManager.Singleton;
			if ((Object)(object)singleton == (Object)null || !singleton.IsServer)
			{
				return false;
			}
			float num;
			try
			{
				num = Mathf.Clamp01((float)_computeChance.Invoke(null, null));
			}
			catch (Exception ex2)
			{
				Plugin.Log.LogWarning((object)("Не смог посчитать шанс Scrap Keeper: " + ex2.Message));
				return true;
			}
			Array array;
			try
			{
				array = _itemsProperty.GetValue(null) as Array;
			}
			catch (Exception ex3)
			{
				Plugin.Log.LogWarning((object)("Не смог прочитать содержимое люка: " + ex3.Message));
				return true;
			}
			if (array == null || array.Length == 0)
			{
				return true;
			}
			int length = array.Length;
			List<object> list = new List<object>(length);
			for (int i = 0; i < length; i++)
			{
				if (Random.Range(0f, 1f) > num)
				{
					list.Add(array.GetValue(i));
				}
			}
			if (list.Count == 0)
			{
				Report($"Вайп: Scrap Keeper ({num:P0}) сохранил все {length} предметов в люке.");
				return false;
			}
			if (list.Count == length)
			{
				Report($"Вайп: Scrap Keeper ({num:P0}) не сохранил ничего, люк стирается целиком.");
				return true;
			}
			Array array2 = Array.CreateInstance(_itemDataType, list.Count);
			for (int j = 0; j < list.Count; j++)
			{
				array2.SetValue(list[j], j);
			}
			try
			{
				_removeMethod.Invoke(null, new object[1] { array2 });
			}
			catch (Exception ex4)
			{
				Plugin.Log.LogWarning((object)("Не смог убрать предметы из люка: " + ex4.Message));
				return true;
			}
			Report($"Вайп: Scrap Keeper ({num:P0}) сохранил {length - list.Count} из {length} предметов в люке.");
			return false;
		}
	}
}

BepInEx/plugins/CyrillicFontFallback/CyrillicFontFallback.dll

Decompiled 12 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("CyrillicFontFallback")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0")]
[assembly: AssemblyProduct("Cyrillic Font Fallback")]
[assembly: AssemblyTitle("CyrillicFontFallback")]
[assembly: AssemblyVersion("1.1.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace CyrillicFontFallback
{
	[BepInPlugin("oxxick.cyrillicfontfallback", "Cyrillic Font Fallback", "1.1.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string GUID = "oxxick.cyrillicfontfallback";

		public const string NAME = "Cyrillic Font Fallback";

		public const string VERSION = "1.1.0";

		internal static ManualLogSource Log;

		private ConfigEntry<bool> _enabled;

		private ConfigEntry<string> _preferredFonts;

		private ConfigEntry<bool> _tryAnyLoadedFont;

		private ConfigEntry<float> _timeoutSeconds;

		private const string ProbeChars = "АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя";

		private void Awake()
		{
			Log = ((BaseUnityPlugin)this).Logger;
			_enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Подключать запасной шрифт с кириллицей. Выключи, если ставишь другой мод-патчер шрифтов.");
			_preferredFonts = ((BaseUnityPlugin)this).Config.Bind<string>("General", "Preferred Fonts", "3270-Regular,LiberationSans,NotInter-Regular", "Имена шрифтов ИЗ САМОЙ ИГРЫ через запятую, пробуются по порядку. 3270-Regular стоит первым, потому что это шрифт ванильного HUD — русский текст будет выглядеть роднее всего. Системные шрифты Windows сюда вписывать бесполезно: у них нет встроенных данных, и TMP их не соберёт.");
			_tryAnyLoadedFont = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Try Any Loaded Font", true, "Если ни один из предпочитаемых не подошёл — перебрать вообще все шрифты, загруженные игрой и модами.");
			_timeoutSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("General", "Timeout Seconds", 30f, "Сколько ждать инициализации TextMeshPro, прежде чем сдаться. TMP поднимается не сразу.");
			if (!_enabled.Value)
			{
				Log.LogInfo((object)"Выключен в конфиге — запасной шрифт не подключается.");
			}
			else
			{
				((MonoBehaviour)this).StartCoroutine(InstallWhenReady());
			}
		}

		private IEnumerator InstallWhenReady()
		{
			float waited = 0f;
			List<TMP_FontAsset> fallbacks = null;
			while (waited < _timeoutSeconds.Value)
			{
				try
				{
					fallbacks = TMP_Settings.fallbackFontAssets;
				}
				catch (Exception)
				{
					fallbacks = null;
				}
				if (fallbacks != null)
				{
					break;
				}
				waited += Time.unscaledDeltaTime;
				yield return null;
			}
			if (fallbacks == null)
			{
				Log.LogWarning((object)($"TextMeshPro не поднялся за {_timeoutSeconds.Value:0} с — " + "запасной шрифт не подключён, русский текст будет пустым."));
			}
			else
			{
				Install(fallbacks);
			}
		}

		private void Install(List<TMP_FontAsset> fallbacks)
		{
			Dictionary<string, Font> dictionary = CollectFonts();
			Log.LogDebug((object)string.Format("Шрифтов в памяти: {0} — {1}", dictionary.Count, string.Join(", ", dictionary.Keys)));
			string[] array = _preferredFonts.Value.Split(',');
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length != 0)
				{
					if (!dictionary.TryGetValue(text, out var value))
					{
						Log.LogInfo((object)("Шрифт '" + text + "' в памяти не найден."));
					}
					else if (TryInstall(value, fallbacks))
					{
						return;
					}
				}
			}
			if (_tryAnyLoadedFont.Value)
			{
				Log.LogInfo((object)"Предпочитаемые шрифты не подошли — перебираю все загруженные.");
				foreach (KeyValuePair<string, Font> item in dictionary)
				{
					if (TryInstall(item.Value, fallbacks))
					{
						return;
					}
				}
			}
			Log.LogWarning((object)"Ни один шрифт не дал кириллицу. Русский текст будет пустым. Список найденных шрифтов — выше в логе на уровне Debug.");
		}

		private Dictionary<string, Font> CollectFonts()
		{
			Dictionary<string, Font> dictionary = new Dictionary<string, Font>();
			Font[] array = Resources.FindObjectsOfTypeAll<Font>();
			foreach (Font val in array)
			{
				if ((Object)(object)val != (Object)null && !string.IsNullOrEmpty(((Object)val).name) && !dictionary.ContainsKey(((Object)val).name))
				{
					dictionary[((Object)val).name] = val;
				}
			}
			TMP_FontAsset[] array2 = Resources.FindObjectsOfTypeAll<TMP_FontAsset>();
			foreach (TMP_FontAsset val2 in array2)
			{
				Font val3 = (((Object)(object)val2 != (Object)null) ? val2.sourceFontFile : null);
				if ((Object)(object)val3 != (Object)null && !string.IsNullOrEmpty(((Object)val3).name) && !dictionary.ContainsKey(((Object)val3).name))
				{
					dictionary[((Object)val3).name] = val3;
				}
			}
			return dictionary;
		}

		private bool TryInstall(Font font, List<TMP_FontAsset> fallbacks)
		{
			try
			{
				TMP_FontAsset val = TMP_FontAsset.CreateFontAsset(font);
				if ((Object)(object)val == (Object)null)
				{
					Log.LogInfo((object)("Из '" + ((Object)font).name + "' не удалось собрать TMP-шрифт (скорее всего, нет встроенных данных шрифта)."));
					return false;
				}
				((Object)val).name = "CyrillicFallback_" + ((Object)font).name;
				string empty = default(string);
				val.TryAddCharacters("АБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя", ref empty, false);
				if (empty == null)
				{
					empty = string.Empty;
				}
				if (empty.Length != 0)
				{
					Log.LogInfo((object)("Шрифт '" + ((Object)font).name + "' не покрывает кириллицу целиком " + $"(нет {empty.Length} символов) — пробую следующий."));
					return false;
				}
				fallbacks.Add(val);
				Log.LogInfo((object)("Подключён запасной шрифт с кириллицей: '" + ((Object)font).name + "'. " + $"Всего запасных шрифтов в TMP: {fallbacks.Count}."));
				return true;
			}
			catch (Exception ex)
			{
				Log.LogInfo((object)("Шрифт '" + ((Object)font).name + "' не подошёл: " + ex.Message));
				return false;
			}
		}
	}
}

BepInEx/plugins/DissonanceLoadFix/DissonanceLoadFix.dll

Decompiled 12 hours ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("DissonanceLoadFix")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("Dissonance Load Fix")]
[assembly: AssemblyTitle("DissonanceLoadFix")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace DissonanceLoadFix
{
	internal static class LoadWindow
	{
		private static bool active;

		private static float deadline;

		private static float closeAt;

		private static float startedAt;

		private static int suppressed;

		internal static bool IsOpen
		{
			get
			{
				if (!active)
				{
					return false;
				}
				float realtimeSinceStartup = Time.realtimeSinceStartup;
				if (realtimeSinceStartup > deadline || realtimeSinceStartup > closeAt)
				{
					Close();
					return false;
				}
				return true;
			}
		}

		internal static void Begin(string reason)
		{
			float realtimeSinceStartup = Time.realtimeSinceStartup;
			if (!active)
			{
				active = true;
				suppressed = 0;
				startedAt = realtimeSinceStartup;
				Plugin.Log.LogInfo((object)("Загрузка началась (" + reason + ") — микрофон не будет переоткрываться."));
			}
			closeAt = float.MaxValue;
			deadline = realtimeSinceStartup + Plugin.MaxWindowSeconds.Value;
		}

		internal static void ScheduleClose()
		{
			if (active)
			{
				closeAt = Time.realtimeSinceStartup + Plugin.TailSeconds.Value;
			}
		}

		internal static void CountSuppressed()
		{
			suppressed++;
		}

		internal static void Tick()
		{
			if (active)
			{
				_ = IsOpen;
			}
		}

		private static void Close()
		{
			float num = Time.realtimeSinceStartup - startedAt;
			active = false;
			if (Plugin.LogSummary.Value && suppressed > 0)
			{
				Plugin.Log.LogInfo((object)$"Загрузка заняла {num:0.0} с, подавлено пересозданий конвейера микрофона: {suppressed}.");
			}
			suppressed = 0;
		}
	}
	internal static class LevelLoadPatches
	{
		public static void StartGamePrefix()
		{
			LoadWindow.Begin("посадка");
		}

		public static void GenerateLevelPrefix()
		{
			LoadWindow.Begin("генерация уровня");
		}

		public static void FinishGeneratingPostfix()
		{
			LoadWindow.ScheduleClose();
		}
	}
	internal static class DissonancePatches
	{
		public static bool RestartPrefix()
		{
			if (!Plugin.Enabled.Value)
			{
				return true;
			}
			if (!LoadWindow.IsOpen)
			{
				return true;
			}
			LoadWindow.CountSuppressed();
			return false;
		}
	}
	[BepInPlugin("oxxick.dissonance.loadfix", "Dissonance Load Fix", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "oxxick.dissonance.loadfix";

		public const string PluginName = "Dissonance Load Fix";

		public const string PluginVersion = "1.0.0";

		private const string CaptureManagerType = "Dissonance.Audio.Capture.CapturePipelineManager";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<float> TailSeconds;

		internal static ConfigEntry<float> MaxWindowSeconds;

		internal static ConfigEntry<bool> LogSummary;

		private void Awake()
		{
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Запрещать ли Dissonance пересоздавать конвейер захвата микрофона во время загрузки луны.");
			TailSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("General", "TailSeconds", 5f, "Сколько секунд после окончания генерации уровня ещё считать загрузкой. Последние подвисания обычно приходятся именно на этот хвост.");
			MaxWindowSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("General", "MaxWindowSeconds", 180f, "Предохранитель: максимальная длина окна загрузки. Если генерация почему-то не завершилась, окно закроется само и микрофон вернётся к обычному поведению.");
			LogSummary = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "LogSummary", true, "Писать в лог одну строку с итогом: сколько пересозданий подавлено за загрузку.");
			Type type = AccessTools.TypeByName("Dissonance.Audio.Capture.CapturePipelineManager");
			if (type == null)
			{
				Log.LogError((object)"Тип Dissonance.Audio.Capture.CapturePipelineManager не найден. Патчи не применены — вероятно, изменилась версия Dissonance в игре.");
				return;
			}
			MethodInfo methodInfo = AccessTools.Method(type, "RestartTransmissionPipeline", new Type[1] { typeof(string) }, (Type[])null);
			if (methodInfo == null)
			{
				Log.LogError((object)"Метод CapturePipelineManager.RestartTransmissionPipeline(string) не найден — патч пропущен.");
				return;
			}
			Harmony harmony = new Harmony("oxxick.dissonance.loadfix");
			if (TryPatch(harmony, methodInfo, "RestartPrefix", prefix: true) & TryPatch(harmony, AccessTools.Method(typeof(StartOfRound), "StartGame", (Type[])null, (Type[])null), "StartGamePrefix", prefix: true) & TryPatch(harmony, AccessTools.Method(typeof(RoundManager), "GenerateNewLevelClientRpc", (Type[])null, (Type[])null), "GenerateLevelPrefix", prefix: true) & TryPatch(harmony, AccessTools.Method(typeof(RoundManager), "FinishGeneratingNewLevelClientRpc", (Type[])null, (Type[])null), "FinishGeneratingPostfix", prefix: false))
			{
				Log.LogInfo((object)"Dissonance Load Fix 1.0.0 загружен, все патчи применены.");
			}
			else
			{
				Log.LogWarning((object)"Dissonance Load Fix 1.0.0 загружен частично, часть патчей не встала — подробности выше.");
			}
		}

		private void Update()
		{
			LoadWindow.Tick();
		}

		private static bool TryPatch(Harmony harmony, MethodInfo original, string patchName, bool prefix)
		{
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Expected O, but got Unknown
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Expected O, but got Unknown
			if (original == null)
			{
				Log.LogError((object)("Не найден патчимый метод для " + patchName + " — патч пропущен."));
				return false;
			}
			MethodInfo methodInfo = AccessTools.Method((patchName == "RestartPrefix") ? typeof(DissonancePatches) : typeof(LevelLoadPatches), patchName, (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				Log.LogError((object)("Метод-патч " + patchName + " не найден — патч пропущен."));
				return false;
			}
			try
			{
				if (prefix)
				{
					harmony.Patch((MethodBase)original, new HarmonyMethod(methodInfo), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				else
				{
					harmony.Patch((MethodBase)original, (HarmonyMethod)null, new HarmonyMethod(methodInfo), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"Не удалось пропатчить {original.DeclaringType?.Name}.{original.Name}: {arg}");
				return false;
			}
			Log.LogInfo((object)("Пропатчен " + original.DeclaringType?.Name + "." + original.Name));
			return true;
		}
	}
}

BepInEx/plugins/EmoteSoloAudio/EmoteSoloAudio.dll

Decompiled 12 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Microsoft.CodeAnalysis;
using TooManyEmotes;
using TooManyEmotes.Audio;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("EmoteSoloAudio")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("Emote Solo Audio")]
[assembly: AssemblyTitle("EmoteSoloAudio")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace EmoteSoloAudio
{
	internal class EmoteSoloWatcher : MonoBehaviour
	{
		private readonly HashSet<EmoteAudioSource> _mutedByUs = new HashSet<EmoteAudioSource>();

		private readonly Dictionary<EmoteAudioSource, EmoteController> _ownerCache = new Dictionary<EmoteAudioSource, EmoteController>();

		private readonly List<EmoteAudioSource> _snapshot = new List<EmoteAudioSource>(32);

		private bool _wasSoloing;

		private void LateUpdate()
		{
			if (!Plugin.Enabled.Value)
			{
				Restore();
				return;
			}
			EmoteControllerPlayer emoteControllerLocal = EmoteControllerPlayer.emoteControllerLocal;
			if (!((Object)(object)emoteControllerLocal != (Object)null) || !((EmoteController)emoteControllerLocal).IsPerformingCustomEmote())
			{
				Restore();
				return;
			}
			EmoteSyncGroup emoteSyncGroup = ((EmoteController)emoteControllerLocal).emoteSyncGroup;
			_snapshot.Clear();
			foreach (EmoteAudioSource allEmoteAudioSource in EmoteAudioSource.allEmoteAudioSources)
			{
				_snapshot.Add(allEmoteAudioSource);
			}
			int num = 0;
			foreach (EmoteAudioSource item in _snapshot)
			{
				if (!((Object)(object)item == (Object)null) && !(item is EmoteAudioPlayer) && !((Object)(object)item == (Object)(object)((EmoteController)emoteControllerLocal).personalEmoteAudioSource))
				{
					if (!Plugin.MuteMaskedEnemies.Value && OwnerOf(item) is EmoteControllerMaskedEnemy)
					{
						Unmute(item);
						continue;
					}
					if (emoteSyncGroup != null && item.currentEmoteSyncGroup == emoteSyncGroup)
					{
						Unmute(item);
						continue;
					}
					Mute(item);
					num++;
				}
			}
			if (!_wasSoloing)
			{
				_wasSoloing = true;
				if (Plugin.LogSummary.Value)
				{
					Plugin.Log.LogInfo((object)$"Своя эмоция пошла — заглушено чужих источников: {num}.");
				}
			}
		}

		private EmoteController OwnerOf(EmoteAudioSource source)
		{
			if (_ownerCache.TryGetValue(source, out var value))
			{
				return value;
			}
			EmoteController componentInParent = ((Component)source).GetComponentInParent<EmoteController>();
			_ownerCache[source] = componentInParent;
			return componentInParent;
		}

		private void Mute(EmoteAudioSource source)
		{
			if ((Object)(object)source.audioSource != (Object)null)
			{
				source.audioSource.mute = true;
			}
			if ((Object)(object)source.audioLoopSource != (Object)null)
			{
				source.audioLoopSource.mute = true;
			}
			_mutedByUs.Add(source);
		}

		private void Unmute(EmoteAudioSource source)
		{
			if (_mutedByUs.Remove(source))
			{
				if ((Object)(object)source.audioSource != (Object)null)
				{
					source.audioSource.mute = false;
				}
				if ((Object)(object)source.audioLoopSource != (Object)null)
				{
					source.audioLoopSource.mute = false;
				}
			}
		}

		private void Restore()
		{
			if (_mutedByUs.Count > 0)
			{
				foreach (EmoteAudioSource mutedByU in _mutedByUs)
				{
					if (!((Object)(object)mutedByU == (Object)null))
					{
						if ((Object)(object)mutedByU.audioSource != (Object)null)
						{
							mutedByU.audioSource.mute = false;
						}
						if ((Object)(object)mutedByU.audioLoopSource != (Object)null)
						{
							mutedByU.audioLoopSource.mute = false;
						}
					}
				}
				_mutedByUs.Clear();
				if (Plugin.LogSummary.Value)
				{
					Plugin.Log.LogInfo((object)"Своя эмоция кончилась — чужой звук возвращён.");
				}
			}
			_wasSoloing = false;
			if (_ownerCache.Count > 64)
			{
				_ownerCache.Clear();
			}
		}

		private void OnDestroy()
		{
			Restore();
		}
	}
	[BepInPlugin("oxxick.emotesoloaudio", "Emote Solo Audio", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "oxxick.emotesoloaudio";

		public const string PluginName = "Emote Solo Audio";

		public const string PluginVersion = "1.0.0";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<bool> MuteMaskedEnemies;

		internal static ConfigEntry<bool> LogSummary;

		private void Awake()
		{
			//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_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Общее", "Enabled", true, "Пока играет ваша эмоция, музыка чужих эмоций не слышна. Касается только вас: у каждого игрока своя картина.");
			MuteMaskedEnemies = ((BaseUnityPlugin)this).Config.Bind<bool>("Общее", "MuteMaskedEnemies", true, "Глушить ли заодно эмоции, которые включают маски (Masked). Выключите, если хотите слышать их как предупреждение об опасности.");
			LogSummary = ((BaseUnityPlugin)this).Config.Bind<bool>("Общее", "LogSummary", false, "Писать в лог строку при каждом включении и снятии глушения. Нужно только для отладки.");
			GameObject val = new GameObject("EmoteSoloAudioWatcher")
			{
				hideFlags = (HideFlags)61
			};
			Object.DontDestroyOnLoad((Object)val);
			val.AddComponent<EmoteSoloWatcher>();
			Log.LogInfo((object)"Emote Solo Audio 1.0.0 загружен.");
		}
	}
}

BepInEx/plugins/EnemyAggroFix/EnemyAggroFix.dll

Decompiled 12 hours ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("EnemyAggroFix")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("Enemy Aggro Fix")]
[assembly: AssemblyTitle("EnemyAggroFix")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace EnemyAggroFix
{
	internal static class HoarderBugPatch
	{
		private const float SightWidth = 70f;

		private const int SightRange = 30;

		private const float ProximityCheck = 1.2f;

		private static Func<HoarderBugAI, bool> isAngry;

		internal static bool Prepare()
		{
			MethodInfo methodInfo = AccessTools.Method(typeof(HoarderBugAI), "IsHoarderBugAngry", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				return false;
			}
			try
			{
				isAngry = AccessTools.MethodDelegate<Func<HoarderBugAI, bool>>(methodInfo, (object)null, true);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("Не смог связаться с IsHoarderBugAngry: " + ex.Message));
				return false;
			}
			return isAngry != null;
		}

		[HarmonyPatch(typeof(HoarderBugAI), "DetectAndLookAtPlayers")]
		[HarmonyPostfix]
		private static void KeepAttackerAsTarget(HoarderBugAI __instance)
		{
			if (!Plugin.FixHoarderBug.Value || isAngry == null || !((NetworkBehaviour)__instance).IsOwner)
			{
				return;
			}
			PlayerControllerB angryAtPlayer = __instance.angryAtPlayer;
			if (!((Object)(object)angryAtPlayer == (Object)null) && isAngry(__instance) && CanSee(__instance, angryAtPlayer))
			{
				__instance.watchingPlayer = angryAtPlayer;
				if (((EnemyAI)__instance).currentBehaviourStateIndex == 2)
				{
					((EnemyAI)__instance).targetPlayer = angryAtPlayer;
				}
			}
		}

		private static bool CanSee(HoarderBugAI bug, PlayerControllerB player)
		{
			//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_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_0066: 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)
			//IL_0077: 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_0083: 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_00a1: 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_00d5: 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)
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)((EnemyAI)bug).eye == (Object)null || (Object)(object)player.gameplayCamera == (Object)null)
			{
				return false;
			}
			if (!((EnemyAI)bug).PlayerIsTargetable(player, false, false, true))
			{
				return false;
			}
			Vector3 position = ((Component)player.gameplayCamera).transform.position;
			if (Vector3.Distance(((EnemyAI)bug).eye.position, position) >= 30f)
			{
				return false;
			}
			Vector3 val = position - ((EnemyAI)bug).eye.position;
			if (!(Vector3.Angle(((EnemyAI)bug).eye.forward, val) < 70f) && !(Vector3.Distance(((Component)bug).transform.position, ((Component)player).transform.position) < 1.2f))
			{
				return false;
			}
			int collidersAndRoomMaskAndDefault = instance.collidersAndRoomMaskAndDefault;
			if (!Physics.Linecast(((EnemyAI)bug).eye.position, position, collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1))
			{
				return !Physics.Linecast(position, ((EnemyAI)bug).eye.position, collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1);
			}
			return false;
		}
	}
	internal static class LineOfSightPatch
	{
		[HarmonyPatch(typeof(EnemyAI), "CheckLineOfSightForPlayer")]
		[HarmonyPostfix]
		private static void PreferClosestPlayer(EnemyAI __instance, float width, int range, int proximityAwareness, ref PlayerControllerB __result)
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: 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_00f3: 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_00fb: 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_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_0125: 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_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			if (!Plugin.FixLineOfSight.Value || (Object)(object)__result == (Object)null || (Object)(object)__result.gameplayCamera == (Object)null)
			{
				return;
			}
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null || instance.allPlayerScripts == null)
			{
				return;
			}
			Transform eye = __instance.eye;
			if ((Object)(object)eye == (Object)null)
			{
				return;
			}
			int num = EffectiveRange(__instance, range);
			int collidersAndRoomMaskAndDefault = instance.collidersAndRoomMaskAndDefault;
			float num2 = Vector3.Distance(((Component)__result.gameplayCamera).transform.position, eye.position);
			PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts;
			foreach (PlayerControllerB val in allPlayerScripts)
			{
				if ((Object)(object)val == (Object)null || (Object)(object)val == (Object)(object)__result || (Object)(object)val.gameplayCamera == (Object)null)
				{
					continue;
				}
				Vector3 position = ((Component)val.gameplayCamera).transform.position;
				float num3 = Vector3.Distance(position, eye.position);
				if (!(num3 >= num2) && !(num3 >= (float)num))
				{
					Vector3 val2 = position - eye.position;
					if ((Vector3.Angle(eye.forward, val2) < width || (proximityAwareness != -1 && num3 < (float)proximityAwareness)) && !Physics.Linecast(eye.position, position, collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1) && !Physics.Linecast(position, eye.position, collidersAndRoomMaskAndDefault, (QueryTriggerInteraction)1))
					{
						num2 = num3;
						__result = val;
					}
				}
			}
		}

		private static int EffectiveRange(EnemyAI enemy, int range)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Invalid comparison between Unknown and I4
			if (!enemy.isOutside)
			{
				return range;
			}
			if ((Object)(object)enemy.enemyType == (Object)null || enemy.enemyType.canSeeThroughFog)
			{
				return range;
			}
			TimeOfDay instance = TimeOfDay.Instance;
			if ((Object)(object)instance == (Object)null || (int)instance.currentLevelWeather != 3)
			{
				return range;
			}
			return Mathf.Clamp(range, 0, 30);
		}
	}
	[BepInPlugin("oxxick.enemyaggrofix", "Enemy Aggro Fix", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "oxxick.enemyaggrofix";

		public const string PluginName = "Enemy Aggro Fix";

		public const string PluginVersion = "1.0.0";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> FixLineOfSight;

		internal static ConfigEntry<bool> FixHoarderBug;

		private void Awake()
		{
			//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)
			Log = ((BaseUnityPlugin)this).Logger;
			FixLineOfSight = ((BaseUnityPlugin)this).Config.Bind<bool>("Общее", "ClosestPlayerWins", true, "Моб выбирает БЛИЖАЙШЕГО из видимых игроков, а не первого по порядку слотов в лобби.\nЗатрагивает тампера, дворецкого, мантикойла, лесного великана, LassoMan, споровую ящерицу, пчёл и Stingray,\nа также мобов из модов, если они пользуются тем же игровым методом.\nУсловия видимости (угол обзора, дальность, стены, туман) не меняются — только выбор между теми, кто уже виден.");
			FixHoarderBug = ((BaseUnityPlugin)this).Config.Bind<bool>("Общее", "HoarderBugRemembersAttacker", true, "Жук (Hoarding Bug) держится того, кто его ударил, пока видит его.\nИгра и так запоминает обидчика на 18 секунд, но теряет его, как только в поле зрения попадает кто-то ещё.");
			if (!HoarderBugPatch.Prepare())
			{
				Log.LogError((object)"Правка жука отключена: не нашёл нужные члены HoarderBugAI. Остальное работает.");
				FixHoarderBug.Value = false;
			}
			try
			{
				Harmony val = new Harmony("oxxick.enemyaggrofix");
				val.PatchAll(typeof(LineOfSightPatch));
				val.PatchAll(typeof(HoarderBugPatch));
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"Патчи не применились, поведение мобов остаётся ванильным: {arg}");
				return;
			}
			Log.LogInfo((object)"Enemy Aggro Fix 1.0.0 загружен.");
		}
	}
}

BepInEx/plugins/FastPickup/FastPickup.dll

Decompiled 12 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("FastPickup")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("Fast Pickup")]
[assembly: AssemblyTitle("FastPickup")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace FastPickup
{
	internal static class GrabPatches
	{
		private static FieldRef<PlayerControllerB, float> slotTimer;

		internal static void Apply(Harmony harmony)
		{
			PatchSlotLock(harmony);
			PatchAnimationTail(harmony);
			PatchInitialWait(harmony);
		}

		private static void PatchSlotLock(Harmony harmony)
		{
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Expected O, but got Unknown
			try
			{
				slotTimer = AccessTools.FieldRefAccess<PlayerControllerB, float>("timeSinceSwitchingSlots");
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Не нашёл поле timeSinceSwitchingSlots, замок по слоту останется: " + ex.Message));
				return;
			}
			MethodInfo methodInfo = AccessTools.Method(typeof(PlayerControllerB), "Interact_performed", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				Plugin.Log.LogWarning((object)"Не нашёл Interact_performed, замок по слоту останется.");
				return;
			}
			harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(GrabPatches), "BeforeInteract", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Plugin.Log.LogInfo((object)"Пропатчен PlayerControllerB.Interact_performed");
		}

		private static void BeforeInteract(PlayerControllerB __instance)
		{
			if (Plugin.SkipSlotSwitchLock.Value && !((Object)(object)__instance == (Object)null) && ((NetworkBehaviour)__instance).IsOwner)
			{
				ref float reference = ref slotTimer.Invoke(__instance);
				if (reference < 0.2f)
				{
					reference = 0.2f;
				}
			}
		}

		private static void PatchAnimationTail(Harmony harmony)
		{
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(typeof(PlayerControllerB), "BeginGrabObject", (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				Plugin.Log.LogWarning((object)"Не нашёл BeginGrabObject, хвост анимации останется.");
				return;
			}
			harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(typeof(GrabPatches), "AfterBeginGrab", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Plugin.Log.LogInfo((object)"Пропатчен PlayerControllerB.BeginGrabObject");
		}

		private static void AfterBeginGrab(PlayerControllerB __instance)
		{
			if (!(Plugin.AnimationTimeOverride.Value < 0f) && !((Object)(object)__instance == (Object)null) && ((NetworkBehaviour)__instance).IsOwner && __instance.isGrabbingObjectAnimation)
			{
				__instance.grabObjectAnimationTime = Plugin.AnimationTimeOverride.Value;
			}
		}

		private static void PatchInitialWait(Harmony harmony)
		{
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Expected O, but got Unknown
			if (Plugin.InitialWaitSeconds.Value < 0f)
			{
				Plugin.Log.LogInfo((object)"Стартовая пауза оставлена ванильной по настройке.");
				return;
			}
			MethodInfo methodInfo = AccessTools.Method(typeof(PlayerControllerB), "GrabObject", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = ((methodInfo != null) ? AccessTools.EnumeratorMoveNext((MethodBase)methodInfo) : null);
			if (methodInfo2 == null)
			{
				Plugin.Log.LogWarning((object)"Не нашёл тело корутины GrabObject, стартовая пауза останется ванильной.");
				return;
			}
			try
			{
				harmony.Patch((MethodBase)methodInfo2, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(GrabPatches), "InitialWaitTranspiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
				Plugin.Log.LogInfo((object)"Пропатчено тело корутины PlayerControllerB.GrabObject");
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Не удалось пропатчить корутину подбора: " + ex.Message));
			}
		}

		public static float InitialWait()
		{
			float value = Plugin.InitialWaitSeconds.Value;
			if (!(value < 0f))
			{
				return value;
			}
			return 0.1f;
		}

		private static IEnumerable<CodeInstruction> InitialWaitTranspiler(IEnumerable<CodeInstruction> instructions)
		{
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			ConstructorInfo constructorInfo = AccessTools.Constructor(typeof(WaitForSeconds), new Type[1] { typeof(float) }, false);
			MethodInfo methodInfo = AccessTools.Method(typeof(GrabPatches), "InitialWait", (Type[])null, (Type[])null);
			int num = 0;
			if (constructorInfo != null && methodInfo != null)
			{
				for (int i = 0; i < list.Count - 1; i++)
				{
					if (!(list[i].opcode != OpCodes.Ldc_R4) && list[i].operand is float num2 && !(Mathf.Abs(num2 - 0.1f) > 0.0001f) && !(list[i + 1].opcode != OpCodes.Newobj) && list[i + 1].operand is ConstructorInfo constructorInfo2 && !(constructorInfo2 != constructorInfo))
					{
						list[i] = CodeInstructionExtensions.MoveLabelsFrom(new CodeInstruction(OpCodes.Call, (object)methodInfo), list[i]);
						num++;
					}
				}
			}
			if (num == 0)
			{
				Plugin.Log.LogWarning((object)"В корутине подбора не нашлась пауза 0.1 с — код игры отдан без изменений.");
			}
			return list;
		}
	}
	[BepInPlugin("oxxick.fastpickup", "Fast Pickup", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "oxxick.fastpickup";

		public const string PluginName = "Fast Pickup";

		public const string PluginVersion = "1.0.0";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<float> InitialWaitSeconds;

		internal static ConfigEntry<float> AnimationTimeOverride;

		internal static ConfigEntry<bool> SkipSlotSwitchLock;

		private void Awake()
		{
			//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Общее", "Enabled", true, "Главный выключатель. false — подбор возвращается к ванильному, это полный откат.");
			InitialWaitSeconds = ((BaseUnityPlugin)this).Config.Bind<float>("Общее", "InitialWaitSeconds", 0f, "Первая пауза внутри подбора, в секундах. В ванили 0.1.\n0 — предмет прыгает в руку сразу, это самая заметная часть выигрыша.\n-1 — не трогать эту паузу вообще.");
			AnimationTimeOverride = ((BaseUnityPlugin)this).Config.Bind<float>("Общее", "AnimationTimeOverride", 0.2f, "Чем подменять grabObjectAnimationTime. В ванили 0.4, а у некоторых предметов своё значение.\nИгра ждёт это ЗА ВЫЧЕТОМ 0.2 секунды перед тем, как разрешить следующий подбор,\nпоэтому 0.2 означает нулевое ожидание. Меньше 0.2 ставить смысла нет.\n-1 — не трогать, оставить родное время предмета.");
			SkipSlotSwitchLock = ((BaseUnityPlugin)this).Config.Bind<bool>("Общее", "SkipSlotSwitchLock", true, "Снимать отдельный замок на 0.2 секунды, который вешается при смене слота.\nПодбор предмета переключает слот и тем самым запирает клавишу E, даже когда\nсам подбор уже закончен. Без этого пункта предметы будут браться не чаще пяти в секунду.");
			if (!Enabled.Value)
			{
				Log.LogInfo((object)"Fast Pickup 1.0.0: выключен в конфиге, подбор остаётся ванильным.");
				return;
			}
			GrabPatches.Apply(new Harmony("oxxick.fastpickup"));
			Log.LogInfo((object)"Fast Pickup 1.0.0 загружен.");
		}
	}
}

BepInEx/plugins/LguBetterScannerTweak/LguBetterScannerTweak.dll

Decompiled 12 hours ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using MoreShipUpgrades.Misc.Upgrades;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("LguBetterScannerTweak")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("LGU Better Scanner Tweak")]
[assembly: AssemblyTitle("LguBetterScannerTweak")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LguBetterScannerTweak
{
	internal static class BetterScannerPatches
	{
		private const string UpgradeName = "Better Scanner";

		private const int ScrapNodeType = 2;

		public static bool RangePrefix(int defaultValue, ScanNodeProperties scanNode, ref int __result)
		{
			__result = defaultValue;
			if ((Object)(object)scanNode == (Object)null)
			{
				return false;
			}
			if (!BaseUpgrade.GetActiveUpgrade("Better Scanner"))
			{
				return false;
			}
			if (scanNode.nodeType != 2)
			{
				return false;
			}
			float num = ((BaseUpgrade.GetUpgradeLevel("Better Scanner") <= 0) ? Plugin.Level1Bonus.Value : Plugin.Level2Bonus.Value);
			__result = Mathf.CeilToInt((float)defaultValue + num);
			return false;
		}

		public static bool EntranceNodePrefix()
		{
			return false;
		}
	}
	[BepInPlugin("oxxick.lgu.betterscannertweak", "LGU Better Scanner Tweak", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "oxxick.lgu.betterscannertweak";

		public const string PluginName = "LGU Better Scanner Tweak";

		public const string PluginVersion = "1.0.0";

		private const string LguGuid = "com.malco.lethalcompany.moreshipupgrades";

		private const string BetterScannerType = "MoreShipUpgrades.UpgradeComponents.TierUpgrades.Player.BetterScanner";

		internal static ManualLogSource Log;

		internal static ConfigEntry<float> Level1Bonus;

		internal static ConfigEntry<float> Level2Bonus;

		private void Awake()
		{
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Expected O, but got Unknown
			//IL_00a3: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Level1Bonus = ((BaseUnityPlugin)this).Config.Bind<float>("Better Scanner", "Level1ScrapBonus", 10f, "Прибавка к дальности скана лута на 1-м тире. Продублируй это значение в 'Node distance boost' конфига Lategame Upgrades, чтобы описание в магазине не врало.");
			Level2Bonus = ((BaseUnityPlugin)this).Config.Bind<float>("Better Scanner", "Level2ScrapBonus", 20f, "Прибавка к дальности скана лута на 2-м и 3-м тире. Значение итоговое, а не добавка к 1-му тиру.");
			Type type = AccessTools.TypeByName("MoreShipUpgrades.UpgradeComponents.TierUpgrades.Player.BetterScanner");
			if (type == null)
			{
				Log.LogError((object)"Тип MoreShipUpgrades.UpgradeComponents.TierUpgrades.Player.BetterScanner не найден. Патчи не применены — вероятно, изменилась версия Lategame Upgrades.");
				return;
			}
			Harmony val = new Harmony("oxxick.lgu.betterscannertweak");
			bool flag = TryPatch(val, type, "GetAdditionalMaximumScanNodeRange", "RangePrefix");
			bool flag2 = TryPatch(val, type, "AddScannerNodeToEntrance", "EntranceNodePrefix");
			if (flag && flag2)
			{
				Log.LogInfo((object)"LGU Better Scanner Tweak 1.0.0 загружен, оба патча применены.");
				return;
			}
			Log.LogWarning((object)string.Format("{0} {1} загружен частично. Дальность: {2}, нода входа: {3}.", "LGU Better Scanner Tweak", "1.0.0", flag, flag2));
		}

		private static bool TryPatch(Harmony harmony, Type target, string methodName, string prefixName)
		{
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(target, methodName, (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				Log.LogError((object)("Метод " + target.Name + "." + methodName + " не найден — патч пропущен."));
				return false;
			}
			MethodInfo methodInfo2 = AccessTools.Method(typeof(BetterScannerPatches), prefixName, (Type[])null, (Type[])null);
			if (methodInfo2 == null)
			{
				Log.LogError((object)("Префикс " + prefixName + " не найден — патч пропущен."));
				return false;
			}
			try
			{
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"Не удалось пропатчить {target.Name}.{methodName}: {arg}");
				return false;
			}
			Log.LogInfo((object)("Пропатчен " + target.Name + "." + methodName));
			return true;
		}
	}
}

BepInEx/plugins/LguBiggerLungsRework/LguBiggerLungsRework.dll

Decompiled 12 hours ago
using System;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using CSync.Lib;
using GameNetcodeStuff;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using MoreShipUpgrades.Configuration.Upgrades.Abstractions;
using MoreShipUpgrades.Misc.Upgrades;
using MoreShipUpgrades.UI.TerminalNodes;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("LguBiggerLungsRework")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("LGU Bigger Lungs Rework")]
[assembly: AssemblyTitle("LguBiggerLungsRework")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LguBiggerLungsRework
{
	internal static class BiggerLungsPatches
	{
		private const string UpgradeName = "Bigger Lungs";

		private const float StandingRegenOffset = 4f;

		private const float WalkingRegenOffset = 9f;

		private static readonly FieldRef<PlayerControllerB, bool> IsWalkingRef = ResolveIsWalking();

		private static FieldRef<PlayerControllerB, bool> ResolveIsWalking()
		{
			try
			{
				return AccessTools.FieldRefAccess<PlayerControllerB, bool>("isWalking");
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Поле PlayerControllerB.isWalking не найдено, компенсация регена будет считаться как для стоящего игрока: " + ex.Message));
				return null;
			}
		}

		private static int Level()
		{
			return Mathf.Clamp(BaseUpgrade.GetUpgradeLevel("Bigger Lungs"), 0, 3);
		}

		private static bool Active()
		{
			return BaseUpgrade.GetActiveUpgrade("Bigger Lungs");
		}

		private static float SprintBonus(int level)
		{
			return Plugin.SprintSeconds[level].Value;
		}

		private static float RegenPercent(int level)
		{
			return Plugin.RegenPercent[level].Value;
		}

		private static float RegenMultiplier(int level)
		{
			return 1f + RegenPercent(level) / 100f;
		}

		public static bool SprintTimePrefix(float defaultValue, ref float __result)
		{
			__result = defaultValue;
			if (!Active())
			{
				return false;
			}
			__result = defaultValue + SprintBonus(Level());
			return false;
		}

		public static bool RegenPrefix(float regenValue, ref float __result)
		{
			__result = regenValue;
			if (!Active())
			{
				return false;
			}
			int level = Level();
			__result = regenValue * RegenMultiplier(level) * RateCorrection(SprintBonus(level));
			return false;
		}

		private static float RateCorrection(float sprintBonus)
		{
			PlayerControllerB val = GameNetworkManager.Instance?.localPlayerController;
			if ((Object)(object)val == (Object)null)
			{
				return 1f;
			}
			float num = ((IsWalkingRef != null && IsWalkingRef.Invoke(val)) ? 9f : 4f);
			float num2 = (Plugin.SameRegenWhileWalking.Value ? 4f : num);
			float num3 = (Plugin.CompensateRegenPenalty.Value ? val.sprintTime : (val.sprintTime + sprintBonus)) + num2;
			if (num3 <= 0f)
			{
				return 1f;
			}
			return (val.sprintTime + sprintBonus + num) / num3;
		}

		public static bool JumpCostPrefix(float jumpCost, ref float __result)
		{
			if (Plugin.KeepJumpStaminaReduction.Value)
			{
				return true;
			}
			__result = jumpCost;
			return false;
		}

		public static bool DisplayInfoPrefix(int initialPrice, int maxLevels, int[] incrementalPrices, ref string __result)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append(DescribeLevel(1, initialPrice));
			if (incrementalPrices != null)
			{
				for (int i = 0; i < maxLevels && i < incrementalPrices.Length; i++)
				{
					stringBuilder.Append(DescribeLevel(i + 2, incrementalPrices[i]));
				}
			}
			__result = stringBuilder.ToString();
			return false;
		}

		private static string DescribeLevel(int tier, int price)
		{
			int num = Mathf.Clamp(tier - 1, 0, 3);
			string arg = "Total sprint time is increased by " + Number(Plugin.SprintSeconds[num].Value) + " seconds, stamina regeneration is increased by " + Number(Plugin.RegenPercent[num].Value) + "%";
			return $"LVL {tier} - {FormatPrice(price)}: {arg}\n";
		}

		private static string FormatPrice(int price)
		{
			//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_0016: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				PurchaseMode val = SyncedEntry<PurchaseMode>.op_Implicit(((UpgradeConfiguration)BaseUpgrade.GetConfiguration().BiggerLungsConfiguration).PurchaseMode);
				return BaseUpgrade.GetUpgradePrice(price, val);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Не удалось получить формат цены у Lategame Upgrades, подставляю простой: " + ex.Message));
				return "$" + price.ToString(CultureInfo.InvariantCulture);
			}
		}

		private static string Number(float value)
		{
			return value.ToString("0.##", CultureInfo.InvariantCulture);
		}
	}
	[BepInPlugin("oxxick.lgu.biggerlungsrework", "LGU Bigger Lungs Rework", "1.3.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "oxxick.lgu.biggerlungsrework";

		public const string PluginName = "LGU Bigger Lungs Rework";

		public const string PluginVersion = "1.3.0";

		private const string LguGuid = "com.malco.lethalcompany.moreshipupgrades";

		private const string BiggerLungsType = "MoreShipUpgrades.UpgradeComponents.TierUpgrades.BiggerLungs";

		internal static ManualLogSource Log;

		internal static ConfigEntry<float>[] SprintSeconds = new ConfigEntry<float>[4];

		internal static ConfigEntry<float>[] RegenPercent = new ConfigEntry<float>[4];

		internal static ConfigEntry<bool> SameRegenWhileWalking;

		internal static ConfigEntry<bool> CompensateRegenPenalty;

		internal static ConfigEntry<bool> KeepJumpStaminaReduction;

		private static readonly float[] DefaultSprint = new float[4] { 2f, 4f, 7f, 9f };

		private static readonly float[] DefaultRegen = new float[4] { 35f, 50f, 75f, 90f };

		private void Awake()
		{
			//IL_0134: 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_014a: Expected O, but got Unknown
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_015c: Expected O, but got Unknown
			//IL_015d: Unknown result type (might be due to invalid IL or missing references)
			//IL_016e: Expected O, but got Unknown
			//IL_017f: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			for (int i = 0; i < 4; i++)
			{
				int num = i + 1;
				SprintSeconds[i] = ((BaseUnityPlugin)this).Config.Bind<float>("Bigger Lungs", $"Level{num}SprintSeconds", DefaultSprint[i], $"Прибавка к общему времени бега на {num}-м тире, в секундах. Значение итоговое, а не добавка к предыдущему тиру.");
				RegenPercent[i] = ((BaseUnityPlugin)this).Config.Bind<float>("Bigger Lungs", $"Level{num}RegenPercent", DefaultRegen[i], $"Прибавка к скорости восстановления стамины на {num}-м тире, в процентах. Значение итоговое, а не добавка к предыдущему тиру.");
			}
			SameRegenWhileWalking = ((BaseUnityPlugin)this).Config.Bind<bool>("Bigger Lungs", "SameRegenWhileWalking", true, "В ванили стамина на ходу восстанавливается примерно в полтора раза медленнее, чем когда стоишь на месте. При true эта разница убирается: с купленным апгрейдом реген на ходу идёт с той же скоростью, что и стоя. При false остаётся ванильное поведение.");
			CompensateRegenPenalty = ((BaseUnityPlugin)this).Config.Bind<bool>("Bigger Lungs", "CompensateRegenPenalty", true, "Ванильная формула делит восстановление на то же самое время бега, поэтому длинный бег сам по себе замедляет реген. При true плагин это компенсирует, и обещанные проценты регена остаются верными на всех тирах. При false реген на старших тирах просядет.");
			KeepJumpStaminaReduction = ((BaseUnityPlugin)this).Config.Bind<bool>("Bigger Lungs", "KeepJumpStaminaReduction", false, "Оставить ли родную скидку на стамину при прыжке. По умолчанию выключена: её нет в новом описании апгрейда.");
			Type type = AccessTools.TypeByName("MoreShipUpgrades.UpgradeComponents.TierUpgrades.BiggerLungs");
			if (type == null)
			{
				Log.LogError((object)"Тип MoreShipUpgrades.UpgradeComponents.TierUpgrades.BiggerLungs не найден. Патчи не применены — вероятно, изменилась версия Lategame Upgrades.");
				return;
			}
			Harmony val = new Harmony("oxxick.lgu.biggerlungsrework");
			bool flag = TryPatch(val, type, "GetAdditionalStaminaTime", "SprintTimePrefix");
			bool flag2 = TryPatch(val, type, "ApplyPossibleIncreasedStaminaRegen", "RegenPrefix");
			bool flag3 = TryPatch(val, type, "ApplyPossibleReducedJumpStaminaCost", "JumpCostPrefix");
			bool flag4 = TryPatch(val, type, "GetDisplayInfo", "DisplayInfoPrefix");
			if (flag && flag2 && flag3 && flag4)
			{
				Log.LogInfo((object)"LGU Bigger Lungs Rework 1.3.0 загружен, все четыре патча применены.");
				return;
			}
			Log.LogWarning((object)string.Format("{0} {1} загружен частично. Время бега: {2}, реген: {3}, прыжок: {4}, описание: {5}.", "LGU Bigger Lungs Rework", "1.3.0", flag, flag2, flag3, flag4));
		}

		private static bool TryPatch(Harmony harmony, Type target, string methodName, string prefixName)
		{
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Expected O, but got Unknown
			MethodInfo methodInfo = AccessTools.Method(target, methodName, (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				Log.LogError((object)("Метод " + target.Name + "." + methodName + " не найден — патч пропущен."));
				return false;
			}
			MethodInfo methodInfo2 = AccessTools.Method(typeof(BiggerLungsPatches), prefixName, (Type[])null, (Type[])null);
			if (methodInfo2 == null)
			{
				Log.LogError((object)("Префикс " + prefixName + " не найден — патч пропущен."));
				return false;
			}
			try
			{
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"Не удалось пропатчить {target.Name}.{methodName}: {arg}");
				return false;
			}
			Log.LogInfo((object)("Пропатчен " + target.Name + "." + methodName));
			return true;
		}
	}
}

BepInEx/plugins/LguCheapFuel/LguCheapFuel.dll

Decompiled 12 hours ago
using System;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using CSync.Lib;
using HarmonyLib;
using LethalLevelLoader;
using Microsoft.CodeAnalysis;
using MoreShipUpgrades.Configuration.Upgrades.Interfaces;
using MoreShipUpgrades.Misc.Upgrades;
using MoreShipUpgrades.UI.TerminalNodes;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("LguCheapFuel")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("LGU Cheap Fuel")]
[assembly: AssemblyTitle("LguCheapFuel")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LguCheapFuel
{
	internal static class MoonListPrices
	{
		private static readonly Regex TrailingPrice = new Regex("-\\s*\\D?(\\d+)\\s*$", RegexOptions.Compiled);

		internal static string Rewrite(string text, Func<ExtendedLevel, int> priceFor)
		{
			string[] array = text.Split('\n');
			bool flag = false;
			for (int i = 0; i < array.Length; i++)
			{
				string text2 = array[i];
				if (text2.IndexOf('*') < 0)
				{
					continue;
				}
				Match match = TrailingPrice.Match(text2);
				if (!match.Success)
				{
					continue;
				}
				ExtendedLevel val = FindLevel(text2);
				if (!((Object)(object)val == (Object)null))
				{
					int num = priceFor(val);
					Group obj = match.Groups[1];
					if (!(obj.Value == num.ToString(CultureInfo.InvariantCulture)))
					{
						array[i] = text2.Substring(0, obj.Index) + num.ToString(CultureInfo.InvariantCulture) + text2.Substring(obj.Index + obj.Length);
						flag = true;
					}
				}
			}
			if (!flag)
			{
				return text;
			}
			return string.Join("\n", array);
		}

		private static ExtendedLevel FindLevel(string line)
		{
			ExtendedLevel result = null;
			int num = 0;
			foreach (ExtendedLevel extendedLevel in PatchedContent.ExtendedLevels)
			{
				string text = ((extendedLevel != null) ? extendedLevel.NumberlessPlanetName : null);
				if (!string.IsNullOrEmpty(text) && text.Length > num && line.IndexOf(text, StringComparison.OrdinalIgnoreCase) >= 0)
				{
					result = extendedLevel;
					num = text.Length;
				}
			}
			return result;
		}
	}
	internal static class Patches
	{
		private const string UpgradeKey = "Efficient Engines";

		private static int Level()
		{
			return Mathf.Clamp(BaseUpgrade.GetUpgradeLevel("Efficient Engines"), 0, 3);
		}

		public static bool DiscountPrefix(int defaultPrice, ref int __result)
		{
			__result = defaultPrice;
			if (!BaseUpgrade.GetActiveUpgrade("Efficient Engines"))
			{
				return false;
			}
			float num = Mathf.Clamp(Plugin.Discount[Level()].Value, 0f, 100f);
			float num2 = (float)defaultPrice * (1f - num / 100f);
			__result = Mathf.CeilToInt(Mathf.Clamp(num2, 0f, (float)defaultPrice));
			return false;
		}

		public static void TerminalTextPostfix(ref string __result)
		{
			if (string.IsNullOrEmpty(__result) || !BaseUpgrade.GetActiveUpgrade("Efficient Engines") || __result.IndexOf('*') < 0)
			{
				return;
			}
			try
			{
				__result = MoonListPrices.Rewrite(__result, RouteDisplayPrice);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Не удалось пересчитать цены в списке лун: " + ex.Message));
			}
		}

		private static int RouteDisplayPrice(ExtendedLevel level)
		{
			float num = Mathf.Clamp(Plugin.Discount[Level()].Value, 0f, 100f);
			int routePrice = level.RoutePrice;
			return Mathf.CeilToInt(Mathf.Clamp((float)routePrice * (1f - num / 100f), 0f, (float)routePrice));
		}

		public static bool DisplayInfoPrefix(ref string __result)
		{
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < 4; i++)
			{
				stringBuilder.Append(DescribeLevel(i));
			}
			__result = stringBuilder.ToString();
			return false;
		}

		public static void TerminalNodePostfix(CustomTerminalNode __result)
		{
			if (__result != null)
			{
				__result.Name = Plugin.UpgradeName.Value;
				__result.UnlockPrice = Plugin.Price[0].Value;
				__result.Prices = new int[3]
				{
					Plugin.Price[1].Value,
					Plugin.Price[2].Value,
					Plugin.Price[3].Value
				};
				__result.MaxUpgrade = 3;
				__result.Description = DisplayAll();
			}
		}

		private static string DisplayAll()
		{
			StringBuilder stringBuilder = new StringBuilder();
			for (int i = 0; i < 4; i++)
			{
				stringBuilder.Append(DescribeLevel(i));
			}
			return stringBuilder.ToString();
		}

		private static string DescribeLevel(int index)
		{
			string arg = FormatPrice(Plugin.Price[index].Value);
			string arg2 = Plugin.Discount[index].Value.ToString("0.##", CultureInfo.InvariantCulture);
			return $"LVL {index + 1} - {arg}: Moon routing is {arg2}% cheaper\n";
		}

		private static string FormatPrice(int price)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				IUpgradeConfiguration efficientEnginesConfiguration = (IUpgradeConfiguration)(object)BaseUpgrade.GetConfiguration().EfficientEnginesConfiguration;
				return BaseUpgrade.GetUpgradePrice(price, SyncedEntry<PurchaseMode>.op_Implicit(efficientEnginesConfiguration.PurchaseMode));
			}
			catch (Exception)
			{
				return "$" + price.ToString(CultureInfo.InvariantCulture);
			}
		}
	}
	[BepInPlugin("oxxick.lgu.cheapfuel", "LGU Cheap Fuel", "1.2.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "oxxick.lgu.cheapfuel";

		public const string PluginName = "LGU Cheap Fuel";

		public const string PluginVersion = "1.2.0";

		private const string LguGuid = "com.malco.lethalcompany.moreshipupgrades";

		private const string EnginesType = "MoreShipUpgrades.UpgradeComponents.TierUpgrades.EfficientEngines";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<string> UpgradeName;

		internal static ConfigEntry<float>[] Discount = new ConfigEntry<float>[4];

		internal static ConfigEntry<int>[] Price = new ConfigEntry<int>[4];

		private static readonly float[] DefaultDiscount = new float[4] { 15f, 30f, 50f, 65f };

		private static readonly int[] DefaultPrice = new int[4] { 600, 700, 800, 900 };

		private void Awake()
		{
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Главный выключатель. При false плагин не патчит ничего: Efficient Engines возвращается к родному имени, ценам и линейной скидке. Это и есть полный откат, конфиг Lategame Upgrades при этом никогда не менялся.");
			UpgradeName = ((BaseUnityPlugin)this).Config.Bind<string>("General", "UpgradeName", "Cheap Fuel", "Как апгрейд называется в магазине терминала.");
			for (int i = 0; i < 4; i++)
			{
				int num = i + 1;
				Discount[i] = ((BaseUnityPlugin)this).Config.Bind<float>("Cheap Fuel", $"Level{num}DiscountPercent", DefaultDiscount[i], $"Скидка на стоимость полёта на {num}-м тире, в процентах. Значение итоговое, а не добавка к предыдущему тиру.");
				Price[i] = ((BaseUnityPlugin)this).Config.Bind<int>("Cheap Fuel", $"Level{num}Price", DefaultPrice[i], $"Цена {num}-го тира в кредитах.");
			}
			if (!Enabled.Value)
			{
				Log.LogInfo((object)"LGU Cheap Fuel 1.2.0: выключен настройкой Enabled, Efficient Engines остаётся в родном виде.");
				return;
			}
			Type type = AccessTools.TypeByName("MoreShipUpgrades.UpgradeComponents.TierUpgrades.EfficientEngines");
			if (type == null)
			{
				Log.LogError((object)"Тип MoreShipUpgrades.UpgradeComponents.TierUpgrades.EfficientEngines не найден. Патчи не применены — вероятно, изменилась версия Lategame Upgrades.");
				return;
			}
			Harmony harmony = new Harmony("oxxick.lgu.cheapfuel");
			if ((1u & (Patch(harmony, AccessTools.Method(type, "GetDiscountedMoonPrice", (Type[])null, (Type[])null), "DiscountPrefix", prefix: true) ? 1u : 0u) & (Patch(harmony, AccessTools.Method(type, "GetDisplayInfo", (Type[])null, (Type[])null), "DisplayInfoPrefix", prefix: true) ? 1u : 0u) & (Patch(harmony, AccessTools.Method(type, "RegisterTerminalNode", (Type[])null, (Type[])null), "TerminalNodePostfix", prefix: false) ? 1u : 0u) & (Patch(harmony, AccessTools.Method(typeof(Terminal), "TextPostProcess", (Type[])null, (Type[])null), "TerminalTextPostfix", prefix: false) ? 1u : 0u)) != 0)
			{
				Log.LogInfo((object)string.Format("{0} {1} загружен: Efficient Engines переделан в «{2}», скидки {3}/{4}/{5}/{6}%.", "LGU Cheap Fuel", "1.2.0", UpgradeName.Value, Discount[0].Value, Discount[1].Value, Discount[2].Value, Discount[3].Value));
			}
			else
			{
				Log.LogWarning((object)"LGU Cheap Fuel 1.2.0 загружен частично, часть патчей не встала — подробности выше.");
			}
		}

		private static bool Patch(Harmony harmony, MethodInfo original, string patchName, bool prefix)
		{
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Expected O, but got Unknown
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Expected O, but got Unknown
			if (original == null)
			{
				Log.LogError((object)("Не найден патчимый метод для " + patchName + " — патч пропущен."));
				return false;
			}
			MethodInfo methodInfo = AccessTools.Method(typeof(Patches), patchName, (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				Log.LogError((object)("Метод-патч " + patchName + " не найден — патч пропущен."));
				return false;
			}
			try
			{
				if (prefix)
				{
					harmony.Patch((MethodBase)original, new HarmonyMethod(methodInfo), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				else
				{
					harmony.Patch((MethodBase)original, (HarmonyMethod)null, new HarmonyMethod(methodInfo), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"Не удалось пропатчить {original.DeclaringType?.Name}.{original.Name}: {arg}");
				return false;
			}
			Log.LogInfo((object)("Пропатчен " + original.DeclaringType?.Name + "." + original.Name));
			return true;
		}
	}
}

BepInEx/plugins/LguExtraDayUpgrade/LguExtraDayUpgrade.dll

Decompiled 12 hours ago
using System;
using System.Collections;
using System.Diagnostics;
using System.Globalization;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using CSync.Lib;
using HarmonyLib;
using LethalNetworkAPI;
using Microsoft.CodeAnalysis;
using MoreShipUpgrades.Configuration.Upgrades.Interfaces;
using MoreShipUpgrades.Configuration.Upgrades.Interfaces.OneTimeUpgrades;
using MoreShipUpgrades.Misc.Upgrades;
using MoreShipUpgrades.UI.TerminalNodes;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("LguExtraDayUpgrade")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("LGU Extra Day Upgrade")]
[assembly: AssemblyTitle("LguExtraDayUpgrade")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LguExtraDayUpgrade
{
	internal static class Patches
	{
		private const string UpgradeKey = "Fedora Suit";

		private const float MinimumRate = 0.3f;

		private static bool wasUnlockedBeforePurchase;

		private static LNetworkEvent refreshDeadlineDisplay;

		private static MonoBehaviour coroutineHost;

		public static void TerminalNodePostfix(CustomTerminalNode __result)
		{
			if (__result != null)
			{
				__result.Name = Plugin.UpgradeName.Value;
				__result.UnlockPrice = Plugin.Price.Value;
				__result.Description = BuildDescription(Plugin.Price.Value);
			}
		}

		public static bool DisplayInfoPrefix(ref string __result)
		{
			__result = BuildDescription(Plugin.Price.Value);
			return false;
		}

		private static string BuildDescription(int price)
		{
			int num = Mathf.Max(0, Plugin.ExtraDays.Value);
			string arg = ((num == 1) ? "day" : "days");
			return $"{FormatPrice(price)} - Adds {num} extra {arg} to the deadline of every new quota.";
		}

		private static string FormatPrice(int price)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				IOneTimeUpgradeConfiguration fedoraSuitConfiguration = BaseUpgrade.GetConfiguration().FedoraSuitConfiguration;
				return BaseUpgrade.GetUpgradePrice(price, SyncedEntry<PurchaseMode>.op_Implicit(((IUpgradeConfiguration)fedoraSuitConfiguration).PurchaseMode));
			}
			catch (Exception)
			{
				return "$" + price.ToString(CultureInfo.InvariantCulture);
			}
		}

		public static bool FedoraEffectPrefix(ref bool __result)
		{
			__result = false;
			return false;
		}

		internal static void SetupNetworking(MonoBehaviour host)
		{
			coroutineHost = host;
			try
			{
				refreshDeadlineDisplay = LNetworkEvent.Connect("oxxick.extraday.refresh", (Action<ulong>)null, (Action)OnRefreshRequested, (Action<ulong>)null);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Не удалось поднять сетевое событие, табло у клиентов обновится только на следующий день: " + ex.Message));
			}
		}

		private static void OnRefreshRequested()
		{
			RefreshDeadlineText();
			if ((Object)(object)coroutineHost != (Object)null)
			{
				coroutineHost.StartCoroutine(RefreshAgainSoon());
			}
		}

		private static IEnumerator RefreshAgainSoon()
		{
			yield return (object)new WaitForSeconds(1f);
			RefreshDeadlineText();
		}

		private static void RefreshDeadlineText()
		{
			if ((Object)(object)TimeOfDay.Instance == (Object)null || (Object)(object)StartOfRound.Instance == (Object)null)
			{
				return;
			}
			try
			{
				TimeOfDay.Instance.UpdateProfitQuotaCurrentTime();
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Не удалось обновить табло дедлайна: " + ex.Message));
			}
		}

		public static void NewQuotaPostfix(TimeOfDay __instance)
		{
			if (BaseUpgrade.GetActiveUpgrade("Fedora Suit"))
			{
				GrantDays(__instance, "Новая квота");
			}
		}

		public static void PurchasePrefix(CustomTerminalNode node)
		{
			wasUnlockedBeforePurchase = node != null && node.Unlocked;
		}

		public static void PurchasePostfix(CustomTerminalNode node)
		{
			if (node == null || node.OriginalName != "Fedora Suit" || wasUnlockedBeforePurchase)
			{
				return;
			}
			TimeOfDay instance = TimeOfDay.Instance;
			if (!((Object)(object)instance == (Object)null))
			{
				if (!((NetworkBehaviour)instance).IsServer)
				{
					Plugin.Log.LogInfo((object)"Апгрейд куплен клиентом: временем распоряжается хост, поэтому лишний день начнёт действовать со следующей квоты.");
				}
				else
				{
					GrantDays(instance, "Покупка апгрейда");
				}
			}
		}

		public static void BuyingRatePostfix(TimeOfDay __instance)
		{
			if ((Object)(object)__instance == (Object)null || (Object)(object)StartOfRound.Instance == (Object)null || !BaseUpgrade.GetActiveUpgrade("Fedora Suit"))
			{
				return;
			}
			int num = Mathf.Max(0, Plugin.ExtraDays.Value);
			if (num == 0)
			{
				return;
			}
			int daysUntilDeadline = __instance.daysUntilDeadline;
			if (daysUntilDeadline > 0)
			{
				int num2 = __instance.quotaVariables.deadlineDaysAmount + num;
				if (num2 > 0)
				{
					float num3 = 0.7f / (float)num2 * (float)(num2 - daysUntilDeadline) + 0.3f;
					StartOfRound.Instance.companyBuyingRate = Mathf.Clamp(num3, 0.3f, 1f);
				}
			}
		}

		private static void GrantDays(TimeOfDay time, string reason)
		{
			if ((Object)(object)time == (Object)null || !((NetworkBehaviour)time).IsServer)
			{
				return;
			}
			int num = Mathf.Max(0, Plugin.ExtraDays.Value);
			if (num == 0)
			{
				return;
			}
			time.timeUntilDeadline += time.totalTime * (float)num;
			try
			{
				time.UpdateProfitQuotaCurrentTime();
				time.SyncTimeClientRpc(time.globalTime, (int)time.timeUntilDeadline);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Дедлайн продлён, но обновить табло или разослать время не удалось: " + ex.Message));
			}
			try
			{
				LNetworkEvent obj = refreshDeadlineDisplay;
				if (obj != null)
				{
					obj.InvokeClients();
				}
			}
			catch (Exception ex2)
			{
				Plugin.Log.LogWarning((object)("Не удалось попросить клиентов обновить табло: " + ex2.Message));
			}
			Plugin.Log.LogInfo((object)$"{reason}: дедлайн продлён на {num} дн., до дедлайна теперь {time.daysUntilDeadline} дн.");
		}
	}
	[BepInPlugin("oxxick.lgu.extradayupgrade", "LGU Extra Day Upgrade", "1.3.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "oxxick.lgu.extradayupgrade";

		public const string PluginName = "LGU Extra Day Upgrade";

		public const string PluginVersion = "1.3.0";

		private const string LguGuid = "com.malco.lethalcompany.moreshipupgrades";

		private const string NetworkApiGuid = "LethalNetworkAPI";

		private const string FedoraType = "MoreShipUpgrades.UpgradeComponents.OneTimeUpgrades.Enemies.FedoraSuit";

		private const string UpgradeApiType = "MoreShipUpgrades.API.UpgradeApi";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<string> UpgradeName;

		internal static ConfigEntry<int> Price;

		internal static ConfigEntry<int> ExtraDays;

		internal static ConfigEntry<bool> GrantDayOnPurchase;

		internal static ConfigEntry<bool> DisableFedoraEffect;

		private void Awake()
		{
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Главный выключатель. При false плагин не патчит ничего: Fedora Suit возвращается к родному имени, цене и эффекту. Это и есть полный откат — правки в конфиге самого Lategame Upgrades не нужны.");
			UpgradeName = ((BaseUnityPlugin)this).Config.Bind<string>("General", "UpgradeName", "Extra Day", "Как апгрейд называется в магазине терминала.");
			Price = ((BaseUnityPlugin)this).Config.Bind<int>("General", "Price", 5000, "Цена апгрейда в кредитах. Подменяется прямо в узле терминала, конфиг Lategame Upgrades не трогается.");
			ExtraDays = ((BaseUnityPlugin)this).Config.Bind<int>("General", "ExtraDays", 1, "Сколько дней прибавляется к дедлайну каждой новой квоты.");
			GrantDayOnPurchase = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "GrantDayOnPurchase", true, "Прибавлять день сразу при покупке, к текущей квоте, а не только к следующим. Работает, когда апгрейд покупает хост: только он управляет временем. Если купил клиент, бонус начнёт действовать со следующей квоты.");
			DisableFedoraEffect = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "DisableFedoraEffect", true, "Отключать ли родной эффект Fedora Suit (дворецкие не нападают). По умолчанию отключён: апгрейд теперь про другое.");
			if (!Enabled.Value)
			{
				Log.LogInfo((object)"LGU Extra Day Upgrade 1.3.0: выключен настройкой Enabled, Fedora Suit остаётся в родном виде.");
				return;
			}
			Type type = AccessTools.TypeByName("MoreShipUpgrades.UpgradeComponents.OneTimeUpgrades.Enemies.FedoraSuit");
			Type type2 = AccessTools.TypeByName("MoreShipUpgrades.API.UpgradeApi");
			if (type == null)
			{
				Log.LogError((object)"Тип MoreShipUpgrades.UpgradeComponents.OneTimeUpgrades.Enemies.FedoraSuit не найден. Патчи не применены — вероятно, изменилась версия Lategame Upgrades.");
				return;
			}
			Harmony harmony = new Harmony("oxxick.lgu.extradayupgrade");
			bool flag = true;
			flag &= Patch(harmony, AccessTools.Method(type, "RegisterTerminalNode", (Type[])null, (Type[])null), "TerminalNodePostfix", prefix: false);
			flag &= Patch(harmony, AccessTools.Method(type, "GetDisplayInfo", (Type[])null, (Type[])null), "DisplayInfoPrefix", prefix: true);
			flag &= Patch(harmony, AccessTools.Method(typeof(TimeOfDay), "SetNewProfitQuota", (Type[])null, (Type[])null), "NewQuotaPostfix", prefix: false);
			flag &= Patch(harmony, AccessTools.Method(typeof(TimeOfDay), "SetBuyingRateForDay", (Type[])null, (Type[])null), "BuyingRatePostfix", prefix: false);
			if (DisableFedoraEffect.Value)
			{
				flag &= Patch(harmony, AccessTools.Method(type, "IsWearingFedoraSuit", (Type[])null, (Type[])null), "FedoraEffectPrefix", prefix: true);
			}
			if (GrantDayOnPurchase.Value)
			{
				MethodInfo original = ((type2 == null) ? null : AccessTools.Method(type2, "TriggerUpgradeRankup", new Type[1] { AccessTools.TypeByName("MoreShipUpgrades.UI.TerminalNodes.CustomTerminalNode") }, (Type[])null));
				flag &= Patch(harmony, original, "PurchasePrefix", prefix: true);
				flag &= Patch(harmony, original, "PurchasePostfix", prefix: false);
			}
			Patches.SetupNetworking((MonoBehaviour)(object)this);
			if (flag)
			{
				Log.LogInfo((object)string.Format("{0} {1} загружен: Fedora Suit переделан в «{2}» за {3}, +{4} дн. к каждой новой квоте.", "LGU Extra Day Upgrade", "1.3.0", UpgradeName.Value, Price.Value, ExtraDays.Value));
			}
			else
			{
				Log.LogWarning((object)"LGU Extra Day Upgrade 1.3.0 загружен частично, часть патчей не встала — подробности выше.");
			}
		}

		private static bool Patch(Harmony harmony, MethodInfo original, string patchName, bool prefix)
		{
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Expected O, but got Unknown
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Expected O, but got Unknown
			if (original == null)
			{
				Log.LogError((object)("Не найден патчимый метод для " + patchName + " — патч пропущен."));
				return false;
			}
			MethodInfo methodInfo = AccessTools.Method(typeof(Patches), patchName, (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				Log.LogError((object)("Метод-патч " + patchName + " не найден — патч пропущен."));
				return false;
			}
			try
			{
				if (prefix)
				{
					harmony.Patch((MethodBase)original, new HarmonyMethod(methodInfo), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				else
				{
					harmony.Patch((MethodBase)original, (HarmonyMethod)null, new HarmonyMethod(methodInfo), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"Не удалось пропатчить {original.DeclaringType?.Name}.{original.Name}: {arg}");
				return false;
			}
			Log.LogInfo((object)("Пропатчен " + original.DeclaringType?.Name + "." + original.Name));
			return true;
		}
	}
}

BepInEx/plugins/LguRoutePass/LguRoutePass.dll

Decompiled 12 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using CSync.Lib;
using HarmonyLib;
using LethalLevelLoader;
using LethalNetworkAPI;
using Microsoft.CodeAnalysis;
using MoreShipUpgrades.Configuration.Upgrades.Interfaces;
using MoreShipUpgrades.Misc.Upgrades;
using MoreShipUpgrades.UI.TerminalNodes;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("LguRoutePass")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.4.1.0")]
[assembly: AssemblyInformationalVersion("1.4.1")]
[assembly: AssemblyProduct("LGU Route Pass")]
[assembly: AssemblyTitle("LguRoutePass")]
[assembly: AssemblyVersion("1.4.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace LguRoutePass
{
	internal static class MoonListPrices
	{
		private static readonly Regex TrailingPrice = new Regex("-\\s*\\D?(\\d+)\\s*$", RegexOptions.Compiled);

		internal static string RewritePaid(string text, Func<ExtendedLevel, bool> isPaid)
		{
			string[] array = text.Split('\n');
			bool flag = false;
			for (int i = 0; i < array.Length; i++)
			{
				string text2 = array[i];
				if (text2.IndexOf('*') < 0)
				{
					continue;
				}
				Match match = TrailingPrice.Match(text2);
				if (!match.Success)
				{
					continue;
				}
				ExtendedLevel val = FindLevel(text2);
				if (!((Object)(object)val == (Object)null) && isPaid(val))
				{
					int num = 0;
					Group obj = match.Groups[1];
					if (!(obj.Value == num.ToString(CultureInfo.InvariantCulture)))
					{
						array[i] = text2.Substring(0, obj.Index) + num.ToString(CultureInfo.InvariantCulture) + text2.Substring(obj.Index + obj.Length);
						flag = true;
					}
				}
			}
			if (!flag)
			{
				return text;
			}
			return string.Join("\n", array);
		}

		private static ExtendedLevel FindLevel(string line)
		{
			ExtendedLevel result = null;
			int num = 0;
			foreach (ExtendedLevel extendedLevel in PatchedContent.ExtendedLevels)
			{
				string text = ((extendedLevel != null) ? extendedLevel.NumberlessPlanetName : null);
				if (!string.IsNullOrEmpty(text) && text.Length > num && line.IndexOf(text, StringComparison.OrdinalIgnoreCase) >= 0)
				{
					result = extendedLevel;
					num = text.Length;
				}
			}
			return result;
		}
	}
	internal static class PaidRoutes
	{
		private static readonly HashSet<int> paid = new HashSet<int>();

		private static string context;

		private static string FilePath => Path.Combine(Paths.ConfigPath, "oxxick.lgu.routepass.paid.txt");

		private static string CurrentContext()
		{
			if (!((Object)(object)GameNetworkManager.Instance != (Object)null))
			{
				return "unknown";
			}
			return GameNetworkManager.Instance.currentSaveFileName;
		}

		private static void EnsureContext()
		{
			string text = CurrentContext();
			if (!(context == text))
			{
				context = text;
				paid.Clear();
				if (Plugin.RememberBetweenSessions.Value)
				{
					LoadFromDisk(text);
				}
			}
		}

		internal static bool IsPaid(int levelId)
		{
			EnsureContext();
			return paid.Contains(levelId);
		}

		internal static void Remember(int levelId)
		{
			EnsureContext();
			if (paid.Add(levelId))
			{
				Plugin.Log.LogInfo((object)$"Маршрут на луну {levelId} оплачен, до конца квоты она бесплатна.");
				SaveToDisk();
				Broadcast();
			}
		}

		internal static void Reset(string reason)
		{
			paid.Clear();
			context = CurrentContext();
			SaveToDisk();
			Broadcast();
			Plugin.Log.LogInfo((object)(reason + ": список бесплатных лун очищен, все луны снова платные."));
		}

		internal static void Broadcast()
		{
			if (!Sync.IsServer || Sync.Push == null)
			{
				return;
			}
			try
			{
				Sync.Push.SendClients(Serialize());
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Не удалось разослать список оплаченных лун: " + ex.Message));
			}
		}

		internal static void SendTo(ulong clientId)
		{
			if (!Sync.IsServer || Sync.Push == null)
			{
				return;
			}
			try
			{
				Sync.Push.SendClient(Serialize(), clientId);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Не удалось отправить список клиенту: " + ex.Message));
			}
		}

		internal static void RequestFromHost()
		{
			if (Sync.IsServer || Sync.Pull == null)
			{
				return;
			}
			try
			{
				Sync.Pull.SendServer(string.Empty);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Не удалось запросить список у хоста: " + ex.Message));
			}
		}

		internal static string Serialize()
		{
			EnsureContext();
			return context + "|" + string.Join(",", paid);
		}

		internal static void ApplyFromHost(string payload)
		{
			if (string.IsNullOrEmpty(payload))
			{
				return;
			}
			string[] array = payload.Split('|');
			if (array.Length != 2 || Sync.IsServer)
			{
				return;
			}
			paid.Clear();
			context = array[0];
			string[] array2 = array[1].Split(',');
			for (int i = 0; i < array2.Length; i++)
			{
				if (int.TryParse(array2[i], NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
				{
					paid.Add(result);
				}
			}
			SaveToDisk();
			Plugin.Log.LogInfo((object)$"Список оплаченных лун получен от хоста: {paid.Count} шт.");
		}

		private static void SaveToDisk()
		{
			if (!Plugin.RememberBetweenSessions.Value)
			{
				return;
			}
			try
			{
				File.WriteAllText(FilePath, context + "|" + string.Join(",", paid));
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Не удалось сохранить список оплаченных лун: " + ex.Message));
			}
		}

		private static void LoadFromDisk(string expectedContext)
		{
			try
			{
				if (!File.Exists(FilePath))
				{
					return;
				}
				string[] array = File.ReadAllText(FilePath).Split('|');
				if (array.Length != 2 || array[0] != expectedContext)
				{
					return;
				}
				string[] array2 = array[1].Split(',');
				for (int i = 0; i < array2.Length; i++)
				{
					if (int.TryParse(array2[i], NumberStyles.Integer, CultureInfo.InvariantCulture, out var result))
					{
						paid.Add(result);
					}
				}
				if (paid.Count > 0)
				{
					Plugin.Log.LogInfo((object)$"Восстановлено оплаченных лун в этой квоте: {paid.Count}.");
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Не удалось прочитать список оплаченных лун: " + ex.Message));
			}
		}
	}
	internal static class Sync
	{
		internal static LNetworkMessage<string> Push;

		internal static LNetworkMessage<string> Pull;

		internal static bool IsServer
		{
			get
			{
				if ((Object)(object)NetworkManager.Singleton != (Object)null)
				{
					return NetworkManager.Singleton.IsServer;
				}
				return false;
			}
		}

		internal static void Init()
		{
			try
			{
				Push = LNetworkMessage<string>.Connect("oxxick.routepass.push", (Action<string, ulong>)null, (Action<string>)PaidRoutes.ApplyFromHost, (Action<string, ulong>)null);
				Pull = LNetworkMessage<string>.Connect("oxxick.routepass.pull", (Action<string, ulong>)delegate(string _, ulong clientId)
				{
					PaidRoutes.SendTo(clientId);
				}, (Action<string>)null, (Action<string, ulong>)null);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Не удалось поднять сетевые сообщения, список будет только локальным: " + ex.Message));
			}
		}
	}
	internal static class Patches
	{
		private const string UpgradeKey = "Fast Encryption";

		private static TerminalNode zeroedNode;

		private static int savedCost;

		private static readonly FieldRef<Terminal, int> TotalCostRef = ResolveTotalCost();

		public static void TerminalNodePostfix(CustomTerminalNode __result)
		{
			if (__result != null)
			{
				__result.Name = Plugin.UpgradeName.Value;
				__result.UnlockPrice = Plugin.Price.Value;
				__result.Description = Description();
			}
		}

		public static bool DisplayInfoPrefix(ref string __result)
		{
			__result = Description();
			return false;
		}

		private static string Description()
		{
			return FormatPrice(Plugin.Price.Value) + " - Any moon you have already paid for stays free to fly back to until the quota resets.";
		}

		private static string FormatPrice(int price)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				IUpgradeConfiguration fastEncryptionConfiguration = (IUpgradeConfiguration)(object)BaseUpgrade.GetConfiguration().FastEncryptionConfiguration;
				return BaseUpgrade.GetUpgradePrice(price, SyncedEntry<PurchaseMode>.op_Implicit(fastEncryptionConfiguration.PurchaseMode));
			}
			catch (Exception)
			{
				return "$" + price.ToString(CultureInfo.InvariantCulture);
			}
		}

		public static void RoutePricePrefix(TerminalNode node)
		{
			zeroedNode = null;
			if (!((Object)(object)node == (Object)null))
			{
				int buyRerouteToMoon = node.buyRerouteToMoon;
				if (buyRerouteToMoon >= 0 && BaseUpgrade.GetActiveUpgrade("Fast Encryption") && PaidRoutes.IsPaid(buyRerouteToMoon))
				{
					zeroedNode = node;
					savedCost = node.itemCost;
					node.itemCost = 0;
				}
			}
		}

		public static void RoutePricePostfix()
		{
			if (!((Object)(object)zeroedNode == (Object)null))
			{
				zeroedNode.itemCost = savedCost;
				zeroedNode = null;
			}
		}

		private static FieldRef<Terminal, int> ResolveTotalCost()
		{
			try
			{
				return AccessTools.FieldRefAccess<Terminal, int>("totalCostOfItems");
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Поле Terminal.totalCostOfItems не найдено, цена на экране маршрута останется прежней: " + ex.Message));
				return null;
			}
		}

		public static void RouteScreenPrefix(Terminal __instance, TerminalNode node)
		{
			if (!((Object)(object)__instance == (Object)null) && !((Object)(object)node == (Object)null) && TotalCostRef != null && node.buyRerouteToMoon == -2 && BaseUpgrade.GetActiveUpgrade("Fast Encryption") && PaidRoutes.IsPaid(node.displayPlanetInfo))
			{
				TotalCostRef.Invoke(__instance) = 0;
			}
		}

		public static void TerminalTextPostfix(ref string __result)
		{
			if (string.IsNullOrEmpty(__result) || !BaseUpgrade.GetActiveUpgrade("Fast Encryption") || __result.IndexOf('*') < 0)
			{
				return;
			}
			try
			{
				__result = MoonListPrices.RewritePaid(__result, IsLevelPaid);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Не удалось проставить нули в списке лун: " + ex.Message));
			}
		}

		private static bool IsLevelPaid(ExtendedLevel level)
		{
			SelectableLevel val = ((level != null) ? level.SelectableLevel : null);
			if ((Object)(object)val != (Object)null)
			{
				return PaidRoutes.IsPaid(val.levelID);
			}
			return false;
		}

		public static void LevelChangedPostfix(int levelID)
		{
			if (BaseUpgrade.GetActiveUpgrade("Fast Encryption"))
			{
				PaidRoutes.Remember(levelID);
			}
		}

		public static void NewQuotaPrefix()
		{
			if (!((Object)(object)NetworkManager.Singleton == (Object)null) && NetworkManager.Singleton.IsServer)
			{
				int num = (((Object)(object)TimeOfDay.Instance != (Object)null) ? TimeOfDay.Instance.daysUntilDeadline : 0);
				if (Plugin.KeepPassWhenQuotaClosedEarly.Value && num > 0)
				{
					Plugin.Log.LogInfo((object)$"Квота закрыта досрочно, в запасе дней: {num}. Список бесплатных лун сохранён.");
				}
				else
				{
					PaidRoutes.Reset("Срок квоты вышел");
				}
			}
		}

		public static void ShipResetPostfix()
		{
			PaidRoutes.Reset("Корабль сброшен");
		}

		public static void StartGamePostfix()
		{
			PaidRoutes.Broadcast();
		}

		public static void TerminalOpenedPostfix()
		{
			PaidRoutes.RequestFromHost();
		}

		public static bool CharacterLimitPrefix(int defaultLimit, ref int __result)
		{
			__result = defaultLimit;
			return false;
		}

		public static bool SignalTimerPrefix(float defaultMultiplier, ref float __result)
		{
			__result = defaultMultiplier;
			return false;
		}
	}
	[BepInPlugin("oxxick.lgu.routepass", "LGU Route Pass", "1.4.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "oxxick.lgu.routepass";

		public const string PluginName = "LGU Route Pass";

		public const string PluginVersion = "1.4.1";

		private const string LguGuid = "com.malco.lethalcompany.moreshipupgrades";

		private const string NetworkApiGuid = "LethalNetworkAPI";

		private const string DonorType = "MoreShipUpgrades.UpgradeComponents.OneTimeUpgrades.Ship.FastEncryption";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<string> UpgradeName;

		internal static ConfigEntry<int> Price;

		internal static ConfigEntry<bool> DisableDonorEffect;

		internal static ConfigEntry<bool> RememberBetweenSessions;

		internal static ConfigEntry<bool> KeepPassWhenQuotaClosedEarly;

		private void Awake()
		{
			//IL_0118: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Главный выключатель. При false плагин не патчит ничего: Fast Encryption возвращается к родному имени, цене и эффекту. Это и есть полный откат.");
			UpgradeName = ((BaseUnityPlugin)this).Config.Bind<string>("General", "UpgradeName", "Route Pass", "Как апгрейд называется в магазине терминала.");
			Price = ((BaseUnityPlugin)this).Config.Bind<int>("General", "Price", 300, "Цена апгрейда в кредитах.");
			DisableDonorEffect = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "DisableDonorEffect", false, "Отключать ли родной эффект Fast Encryption — быстрый набор букв передатчиком без лимита символов. По умолчанию false: эффект остаётся скрытым бонусом к апгрейду, хотя в описании про него не написано.");
			RememberBetweenSessions = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "RememberBetweenSessions", true, "Сохранять список оплаченных лун на диск, чтобы после перезапуска игры посреди квоты не платить за них заново.");
			KeepPassWhenQuotaClosedEarly = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "KeepPassWhenQuotaClosedEarly", false, "Что делать с пропуском, если квоту закрыли досрочно.\nfalse (по умолчанию): пропуск сгорает вместе с квотой, как и задумано — новая квота, новые цены.\ntrue: пропуск переживает досрочную сдачу и сгорает только когда дедлайн действительно истёк.\nВключать true осторожно: если квоту всегда закрывать досрочно, дедлайн не истекает никогда и купленная луна остаётся бесплатной бессрочно.");
			if (!Enabled.Value)
			{
				Log.LogInfo((object)"LGU Route Pass 1.4.1: выключен настройкой Enabled, Fast Encryption остаётся в родном виде.");
				return;
			}
			Type type = AccessTools.TypeByName("MoreShipUpgrades.UpgradeComponents.OneTimeUpgrades.Ship.FastEncryption");
			if (type == null)
			{
				Log.LogError((object)"Тип MoreShipUpgrades.UpgradeComponents.OneTimeUpgrades.Ship.FastEncryption не найден. Патчи не применены — вероятно, изменилась версия Lategame Upgrades.");
				return;
			}
			Harmony harmony = new Harmony("oxxick.lgu.routepass");
			bool flag = true;
			flag &= Patch(harmony, AccessTools.Method(type, "RegisterTerminalNode", (Type[])null, (Type[])null), "TerminalNodePostfix", prefix: false);
			flag &= Patch(harmony, AccessTools.Method(type, "GetDisplayInfo", (Type[])null, (Type[])null), "DisplayInfoPrefix", prefix: true);
			flag &= Patch(harmony, AccessTools.Method(typeof(Terminal), "LoadNewNodeIfAffordable", (Type[])null, (Type[])null), "RoutePricePrefix", prefix: true);
			flag &= Patch(harmony, AccessTools.Method(typeof(Terminal), "LoadNewNodeIfAffordable", (Type[])null, (Type[])null), "RoutePricePostfix", prefix: false);
			flag &= Patch(harmony, AccessTools.Method(typeof(StartOfRound), "ChangeLevelClientRpc", (Type[])null, (Type[])null), "LevelChangedPostfix", prefix: false);
			flag &= Patch(harmony, AccessTools.Method(typeof(TimeOfDay), "SetNewProfitQuota", (Type[])null, (Type[])null), "NewQuotaPrefix", prefix: true);
			flag &= Patch(harmony, AccessTools.Method(typeof(StartOfRound), "ResetShip", (Type[])null, (Type[])null), "ShipResetPostfix", prefix: false);
			flag &= Patch(harmony, AccessTools.Method(typeof(StartOfRound), "StartGame", (Type[])null, (Type[])null), "StartGamePostfix", prefix: false);
			flag &= Patch(harmony, AccessTools.Method(typeof(Terminal), "BeginUsingTerminal", (Type[])null, (Type[])null), "TerminalOpenedPostfix", prefix: false);
			flag &= Patch(harmony, AccessTools.Method(typeof(Terminal), "LoadNewNode", (Type[])null, (Type[])null), "RouteScreenPrefix", prefix: true);
			flag &= PatchLast(harmony, AccessTools.Method(typeof(Terminal), "TextPostProcess", (Type[])null, (Type[])null), "TerminalTextPostfix");
			if (DisableDonorEffect.Value)
			{
				flag &= Patch(harmony, AccessTools.Method(type, "GetLimitOfCharactersTransmit", (Type[])null, (Type[])null), "CharacterLimitPrefix", prefix: true);
				flag &= Patch(harmony, AccessTools.Method(type, "GetMultiplierOnSignalTextTimer", (Type[])null, (Type[])null), "SignalTimerPrefix", prefix: true);
			}
			Sync.Init();
			if (flag)
			{
				Log.LogInfo((object)string.Format("{0} {1} загружен: Fast Encryption переделан в «{2}» за {3}.", "LGU Route Pass", "1.4.1", UpgradeName.Value, Price.Value));
			}
			else
			{
				Log.LogWarning((object)"LGU Route Pass 1.4.1 загружен частично, часть патчей не встала — подробности выше.");
			}
		}

		private static bool PatchLast(Harmony harmony, MethodInfo original, string patchName)
		{
			//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_0076: Expected O, but got Unknown
			if (original == null)
			{
				Log.LogError((object)("Не найден патчимый метод для " + patchName + " — патч пропущен."));
				return false;
			}
			MethodInfo methodInfo = AccessTools.Method(typeof(Patches), patchName, (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				Log.LogError((object)("Метод-патч " + patchName + " не найден — патч пропущен."));
				return false;
			}
			try
			{
				harmony.Patch((MethodBase)original, (HarmonyMethod)null, new HarmonyMethod(methodInfo)
				{
					priority = 0
				}, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"Не удалось пропатчить {original.DeclaringType?.Name}.{original.Name}: {arg}");
				return false;
			}
			Log.LogInfo((object)("Пропатчен " + original.DeclaringType?.Name + "." + original.Name + " (последним)"));
			return true;
		}

		private static bool Patch(Harmony harmony, MethodInfo original, string patchName, bool prefix)
		{
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Expected O, but got Unknown
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Expected O, but got Unknown
			if (original == null)
			{
				Log.LogError((object)("Не найден патчимый метод для " + patchName + " — патч пропущен."));
				return false;
			}
			MethodInfo methodInfo = AccessTools.Method(typeof(Patches), patchName, (Type[])null, (Type[])null);
			if (methodInfo == null)
			{
				Log.LogError((object)("Метод-патч " + patchName + " не найден — патч пропущен."));
				return false;
			}
			try
			{
				if (prefix)
				{
					harmony.Patch((MethodBase)original, new HarmonyMethod(methodInfo), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
				else
				{
					harmony.Patch((MethodBase)original, (HarmonyMethod)null, new HarmonyMethod(methodInfo), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"Не удалось пропатчить {original.DeclaringType?.Name}.{original.Name}: {arg}");
				return false;
			}
			Log.LogInfo((object)("Пропатчен " + original.DeclaringType?.Name + "." + original.Name));
			return true;
		}
	}
}

BepInEx/plugins/NavMeshFix/NavMeshFix.dll

Decompiled 12 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using Microsoft.CodeAnalysis;
using Unity.AI.Navigation;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.AI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("NavMeshFix")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.3.0.0")]
[assembly: AssemblyInformationalVersion("1.3.0")]
[assembly: AssemblyProduct("NavMesh Fix")]
[assembly: AssemblyTitle("NavMeshFix")]
[assembly: AssemblyVersion("1.3.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace NavMeshFix
{
	internal class Fixer : MonoBehaviour
	{
		private const float RetryEvery = 0.5f;

		private const float NodeCheckRadius = 5f;

		private float sinceRetry;

		private float sinceRescue;

		private bool checkedThisRound;

		private readonly List<NavMeshDataInstance> added = new List<NavMeshDataInstance>();

		private void Update()
		{
			if (!Plugin.Enabled.Value)
			{
				return;
			}
			StartOfRound instance = StartOfRound.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				return;
			}
			if (instance.inShipPhase)
			{
				sinceRetry = 0f;
				sinceRescue = 0f;
				checkedThisRound = false;
				DropAdded();
				return;
			}
			if (!checkedThisRound)
			{
				sinceRetry += Time.deltaTime;
				if (sinceRetry < 0.5f)
				{
					return;
				}
				sinceRetry = 0f;
				RoundManager instance2 = RoundManager.Instance;
				if ((Object)(object)instance2 == (Object)null || instance2.outsideAINodes == null || instance2.outsideAINodes.Length == 0)
				{
					return;
				}
				checkedThisRound = true;
				try
				{
					TryRepair();
				}
				catch (Exception ex)
				{
					Plugin.Log.LogError((object)("Починка навигации упала, оставляю как было: " + ex));
				}
			}
			if (!Plugin.RescueEnemies.Value)
			{
				return;
			}
			sinceRescue += Time.deltaTime;
			if (sinceRescue < Plugin.RescueInterval.Value)
			{
				return;
			}
			sinceRescue = 0f;
			try
			{
				RescueStuckEnemies();
			}
			catch (Exception ex2)
			{
				Plugin.Log.LogError((object)("Подбор застрявших мобов упал: " + ex2));
			}
		}

		private void TryRepair()
		{
			int total;
			int num = CountNodesWithoutMesh(out total);
			if (total == 0)
			{
				Plugin.Log.LogInfo((object)"Точек спавна снаружи нет, проверять нечего.");
				return;
			}
			Plugin.Log.LogInfo((object)$"Наружные точки спавна без сетки: {num} из {total}.");
			if (Plugin.OnlyWhenBroken.Value && num * 2 <= total)
			{
				Plugin.Log.LogInfo((object)"Навигация в порядке, не вмешиваюсь.");
				return;
			}
			ListEverything();
			int current = num;
			current = TryOrphanAssets(current, total);
			Plugin.Log.LogWarning((object)$"Итог: точек без сетки было {num} из {total}, стало {current}.");
		}

		private static void ListEverything()
		{
			//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_004e: 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)
			NavMeshData[] array = Resources.FindObjectsOfTypeAll<NavMeshData>();
			Plugin.Log.LogInfo((object)$"Найдено объектов навигационных данных: {array.Length}");
			NavMeshData[] array2 = array;
			foreach (NavMeshData val in array2)
			{
				if (!((Object)(object)val == (Object)null))
				{
					Bounds sourceBounds = val.sourceBounds;
					Plugin.Log.LogInfo((object)$"   «{((Object)val).name}» позиция {val.position}, охват {((Bounds)(ref sourceBounds)).size}");
				}
			}
			NavMeshSurface[] array3 = Object.FindObjectsOfType<NavMeshSurface>(true);
			foreach (NavMeshSurface val2 in array3)
			{
				Plugin.Log.LogInfo((object)("   поверхность " + ((Object)val2).name + ": данные «" + (((Object)(object)val2.navMeshData != (Object)null) ? ((Object)val2.navMeshData).name : "нет") + "»"));
			}
		}

		private int TryOrphanAssets(int current, int total)
		{
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0160: Unknown result type (might be due to invalid IL or missing references)
			NavMeshData[] array = Resources.FindObjectsOfTypeAll<NavMeshData>();
			NavMeshSurface[] array2 = Object.FindObjectsOfType<NavMeshSurface>(true);
			HashSet<NavMeshData> hashSet = new HashSet<NavMeshData>();
			List<NavMeshData> list = new List<NavMeshData>();
			NavMeshSurface[] array3 = array2;
			foreach (NavMeshSurface val in array3)
			{
				if (!((Object)(object)val.navMeshData == (Object)null))
				{
					hashSet.Add(val.navMeshData);
					list.Add(val.navMeshData);
				}
			}
			NavMeshData[] array4 = array;
			foreach (NavMeshData val2 in array4)
			{
				if ((Object)(object)val2 == (Object)null || hashSet.Contains(val2))
				{
					continue;
				}
				if (!MatchesThisLevel(val2, list))
				{
					Plugin.Log.LogInfo((object)("   «" + ((Object)val2).name + "» не от этой луны, пропускаю."));
					continue;
				}
				Plugin.Log.LogWarning((object)("Пробую подключить ничейные данные «" + ((Object)val2).name + "»..."));
				NavMeshDataInstance val3;
				try
				{
					val3 = NavMesh.AddNavMeshData(val2, val2.position, val2.rotation);
				}
				catch (Exception ex)
				{
					Plugin.Log.LogWarning((object)("   не вышло: " + ex.Message));
					continue;
				}
				if (!((NavMeshDataInstance)(ref val3)).valid)
				{
					Plugin.Log.LogWarning((object)"   игра не приняла эти данные.");
					continue;
				}
				int num = CountNodesWithoutMesh(out total);
				if (num < current)
				{
					Plugin.Log.LogWarning((object)$"   ПОМОГЛО: без сетки было {current}, стало {num}. Оставляю.");
					added.Add(val3);
					current = num;
				}
				else
				{
					Plugin.Log.LogWarning((object)$"   не помогло ({num} из {total}), снимаю обратно.");
					NavMesh.RemoveNavMeshData(val3);
				}
			}
			return current;
		}

		private static bool MatchesThisLevel(NavMeshData candidate, List<NavMeshData> surfaceData)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0049: Unknown result type (might be due to invalid IL or missing references)
			foreach (NavMeshData surfaceDatum in surfaceData)
			{
				if (!((Object)(object)surfaceDatum == (Object)null) && !(Vector3.Distance(candidate.position, surfaceDatum.position) > 0.5f))
				{
					Bounds sourceBounds = candidate.sourceBounds;
					Vector3 size = ((Bounds)(ref sourceBounds)).size;
					sourceBounds = surfaceDatum.sourceBounds;
					if (!(Vector3.Distance(size, ((Bounds)(ref sourceBounds)).size) > 1f))
					{
						return true;
					}
				}
			}
			return false;
		}

		private void DropAdded()
		{
			//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_002d: Unknown result type (might be due to invalid IL or missing references)
			if (added.Count == 0)
			{
				return;
			}
			foreach (NavMeshDataInstance item in added)
			{
				NavMeshDataInstance current = item;
				if (((NavMeshDataInstance)(ref current)).valid)
				{
					NavMesh.RemoveNavMeshData(current);
				}
			}
			added.Clear();
		}

		private static int CountNodesWithoutMesh(out int total)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			total = 0;
			RoundManager instance = RoundManager.Instance;
			GameObject[] array = (((Object)(object)instance != (Object)null) ? instance.outsideAINodes : null);
			if (array == null)
			{
				return 0;
			}
			int num = 0;
			GameObject[] array2 = array;
			NavMeshHit val2 = default(NavMeshHit);
			foreach (GameObject val in array2)
			{
				if (!((Object)(object)val == (Object)null))
				{
					total++;
					if (!NavMesh.SamplePosition(val.transform.position, ref val2, 5f, -1))
					{
						num++;
					}
				}
			}
			return num;
		}

		private static void RescueStuckEnemies()
		{
			//IL_0096: 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)
			RoundManager instance = RoundManager.Instance;
			List<EnemyAI> list = (((Object)(object)instance != (Object)null) ? instance.SpawnedEnemies : null);
			if (list == null)
			{
				return;
			}
			float value = Plugin.RescueRadius.Value;
			int num = 0;
			NavMeshHit val = default(NavMeshHit);
			foreach (EnemyAI item in list)
			{
				if ((Object)(object)item == (Object)null || item.isEnemyDead || !((NetworkBehaviour)item).IsOwner)
				{
					continue;
				}
				NavMeshAgent agent = item.agent;
				if (!((Object)(object)agent == (Object)null) && ((Behaviour)agent).enabled && ((Component)agent).gameObject.activeInHierarchy && !agent.isOnNavMesh && NavMesh.SamplePosition(((Component)item).transform.position, ref val, value, -1))
				{
					agent.Warp(((NavMeshHit)(ref val)).position);
					if (agent.isOnNavMesh)
					{
						num++;
					}
				}
			}
			if (num > 0)
			{
				Plugin.Log.LogInfo((object)$"Поставил на сетку застрявших мобов: {num}.");
			}
		}
	}
	[BepInPlugin("oxxick.navmeshfix", "NavMesh Fix", "1.3.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "oxxick.navmeshfix";

		public const string PluginName = "NavMesh Fix";

		public const string PluginVersion = "1.3.0";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<bool> OnlyWhenBroken;

		internal static ConfigEntry<float> RescueRadius;

		internal static ConfigEntry<float> RescueInterval;

		internal static ConfigEntry<bool> RescueEnemies;

		private void Awake()
		{
			Log = ((BaseUnityPlugin)this).Logger;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Общее", "Enabled", true, "Чинить наружную навигацию на лунах, где она не подключилась.");
			OnlyWhenBroken = ((BaseUnityPlugin)this).Config.Bind<bool>("Общее", "OnlyWhenBroken", true, "Вмешиваться только если больше половины наружных точек спавна остались без сетки.\nВыключать не советую: так плагин гарантированно не трогает здоровые луны.");
			RescueRadius = ((BaseUnityPlugin)this).Config.Bind<float>("Общее", "RescueRadius", 30f, "На каком расстоянии искать сетку для застрявшего моба, в метрах.\n30 подобрано намеренно: на CaltPrime пол подземелья лежит в 217 метрах под землёй,\nи с таким радиусом моба туда не утащит.");
			RescueInterval = ((BaseUnityPlugin)this).Config.Bind<float>("Общее", "RescueIntervalSeconds", 10f, "Как часто подбирать мобов, застрявших вне сетки. Мобы спавнятся весь день,\nпоэтому одного прохода после посадки мало.");
			RescueEnemies = ((BaseUnityPlugin)this).Config.Bind<bool>("Общее", "RescueStuckEnemies", true, "Ставить застрявших мобов на ближайшую сетку.\nНужно тем, кто успел заспавниться до починки: агент, которого не приняли на сетку,\nсам на неё потом не встаёт и стоит столбом.\nИмеет смысл ТОЛЬКО когда наружная сетка на месте — иначе ближайшей окажется\nпятачок у корабля и все мобы соберутся у трапа (так и вышло на CaltPrime до починки).");
			((Component)this).gameObject.AddComponent<Fixer>();
			Log.LogInfo((object)"NavMesh Fix 1.3.0 загружен.");
		}
	}
}

BepInEx/plugins/ShipInfoHud/ShipInfoHud.dll

Decompiled 12 hours ago
using System;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using DunGen;
using HarmonyLib;
using Microsoft.CodeAnalysis;
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("ShipInfoHud")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.1.0")]
[assembly: AssemblyInformationalVersion("1.1.1")]
[assembly: AssemblyProduct("Ship Info HUD")]
[assembly: AssemblyTitle("ShipInfoHud")]
[assembly: AssemblyVersion("1.1.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ShipInfoHud
{
	internal static class DungeonInfo
	{
		private const string ManagerTypeName = "LethalLevelLoader.DungeonManager";

		private const string CurrentFlowPropertyName = "CurrentExtendedDungeonFlow";

		private const string DungeonNamePropertyName = "DungeonName";

		private const string NoNamePlaceholder = "Unknown";

		private static bool probed;

		private static bool levelLoaderUnavailable;

		private static PropertyInfo currentFlowProperty;

		private static PropertyInfo dungeonNameProperty;

		internal static void Read(out string friendlyName, out string flowName)
		{
			friendlyName = string.Empty;
			flowName = string.Empty;
			StartOfRound instance = StartOfRound.Instance;
			if (!((Object)(object)instance == (Object)null) && !instance.inShipPhase)
			{
				flowName = ReadFlowName();
				string text = ReadLevelLoaderName();
				if (string.Equals(text, "Unknown", StringComparison.OrdinalIgnoreCase))
				{
					text = string.Empty;
				}
				friendlyName = ((!string.IsNullOrEmpty(text)) ? text : flowName);
			}
		}

		private static string ReadFlowName()
		{
			RoundManager instance = RoundManager.Instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)instance.dungeonGenerator == (Object)null)
			{
				return string.Empty;
			}
			DungeonGenerator generator = instance.dungeonGenerator.Generator;
			if (generator == null || (Object)(object)generator.DungeonFlow == (Object)null)
			{
				return string.Empty;
			}
			return ((Object)generator.DungeonFlow).name;
		}

		private static string ReadLevelLoaderName()
		{
			//IL_008f: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Expected O, but got Unknown
			if (levelLoaderUnavailable)
			{
				return string.Empty;
			}
			if (!probed)
			{
				probed = true;
				Type type = AccessTools.TypeByName("LethalLevelLoader.DungeonManager");
				if (type == null)
				{
					levelLoaderUnavailable = true;
					Plugin.Log.LogInfo((object)"LethalLevelLoader не найден — в строке интерьера будет имя ассета из самой игры.");
					return string.Empty;
				}
				currentFlowProperty = AccessTools.Property(type, "CurrentExtendedDungeonFlow");
				if (currentFlowProperty == null)
				{
					levelLoaderUnavailable = true;
					Plugin.Log.LogWarning((object)"У LethalLevelLoader.DungeonManager нет свойства CurrentExtendedDungeonFlow — видимо, мод обновился. Показываю имя ассета из игры.");
					return string.Empty;
				}
			}
			try
			{
				object value = currentFlowProperty.GetValue(null);
				if ((Object)value == (Object)null)
				{
					return string.Empty;
				}
				if (dungeonNameProperty == null)
				{
					dungeonNameProperty = AccessTools.Property(value.GetType(), "DungeonName");
					if (dungeonNameProperty == null)
					{
						levelLoaderUnavailable = true;
						Plugin.Log.LogWarning((object)("У " + value.GetType().FullName + " нет свойства DungeonName. Показываю имя ассета из игры."));
						return string.Empty;
					}
				}
				return (dungeonNameProperty.GetValue(value) as string) ?? string.Empty;
			}
			catch (Exception ex)
			{
				levelLoaderUnavailable = true;
				Plugin.Log.LogWarning((object)("Не смог прочитать имя интерьера у LethalLevelLoader, дальше беру имя ассета: " + ex.Message));
				return string.Empty;
			}
		}
	}
	internal class InfoHud : MonoBehaviour
	{
		private struct Info
		{
			internal int Day;

			internal int DaysLeft;

			internal int QuotaNumber;

			internal int Quota;

			internal int Loot;

			internal string Moon;

			internal string Dungeon;

			internal string DungeonFlow;
		}

		internal const string ObjectName = "ShipInfoHudText";

		private const string RequiredCharacters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789$():.,-/ ";

		private TextMeshProUGUI label;

		private RectTransform rect;

		private Color fallbackColor = Color.white;

		private float timer;

		private readonly StringBuilder builder = new StringBuilder(160);

		private TextMeshProUGUI[] controlTips;

		private Vector2[] controlTipsHome;

		private float controlTipsHomeTop;

		private bool controlTipsMeasured;

		private static readonly Vector3[] cornerBuffer = (Vector3[])(object)new Vector3[4];

		private string loggedDungeon;

		internal static void Create(HUDManager hud)
		{
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: Expected O, but got Unknown
			//IL_00be: 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_00e8: 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_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0183: Unknown result type (might be due to invalid IL or missing references)
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			TextMeshProUGUI val = PickFontSource(hud);
			if ((Object)(object)val == (Object)null)
			{
				Plugin.Log.LogError((object)"Не нашёл ни одной ванильной надписи со шрифтом — блок не создан.");
				return;
			}
			Canvas componentInParent = ((Component)val).GetComponentInParent<Canvas>();
			if ((Object)(object)componentInParent == (Object)null)
			{
				Plugin.Log.LogError((object)("У надписи " + ((Object)val).name + " нет родительского Canvas — блок не создан."));
				return;
			}
			if ((Object)(object)((Component)componentInParent).transform.Find("ShipInfoHudText") != (Object)null)
			{
				Plugin.Log.LogInfo((object)"Блок уже существует, второй раз не создаём.");
				return;
			}
			GameObject val2 = new GameObject("ShipInfoHudText", new Type[1] { typeof(RectTransform) });
			val2.transform.SetParent(((Component)componentInParent).transform, false);
			RectTransform val3 = (RectTransform)val2.transform;
			val3.anchorMin = new Vector2(1f, 1f);
			val3.anchorMax = new Vector2(1f, 1f);
			val3.pivot = new Vector2(1f, 1f);
			val3.sizeDelta = new Vector2(640f, 200f);
			((Transform)val3).localScale = Vector3.one;
			((Transform)val3).localRotation = Quaternion.identity;
			TextMeshProUGUI val4 = val2.AddComponent<TextMeshProUGUI>();
			((TMP_Text)val4).font = ((TMP_Text)val).font;
			((TMP_Text)val4).fontSharedMaterial = ((TMP_Text)val).fontSharedMaterial;
			((TMP_Text)val4).alignment = (TextAlignmentOptions)260;
			((TMP_Text)val4).enableWordWrapping = false;
			((TMP_Text)val4).overflowMode = (TextOverflowModes)0;
			((TMP_Text)val4).richText = false;
			((Graphic)val4).raycastTarget = false;
			((TMP_Text)val4).text = string.Empty;
			InfoHud infoHud = val2.AddComponent<InfoHud>();
			infoHud.label = val4;
			infoHud.rect = val3;
			infoHud.fallbackColor = ((Graphic)val).color;
			infoHud.CaptureControlTips(hud);
			infoHud.ApplyAppearance();
			Plugin.Log.LogInfo((object)("Блок создан, шрифт взят у надписи " + ((Object)val).name + " (" + ((Object)((TMP_Text)val).font).name + ")."));
		}

		private static TextMeshProUGUI PickFontSource(HUDManager hud)
		{
			TextMeshProUGUI[] obj = new TextMeshProUGUI[5]
			{
				hud.HUDQuotaNumerator,
				hud.totalValueText,
				hud.weightCounter,
				hud.clockNumber,
				(hud.controlTipLines != null && hud.controlTipLines.Length != 0) ? hud.controlTipLines[0] : null
			};
			TextMeshProUGUI val = null;
			string text = null;
			TextMeshProUGUI[] array = (TextMeshProUGUI[])(object)obj;
			foreach (TextMeshProUGUI val2 in array)
			{
				if (!((Object)(object)val2 == (Object)null) && !((Object)(object)((TMP_Text)val2).font == (Object)null))
				{
					string text2 = MissingCharacters(((TMP_Text)val2).font);
					Plugin.Log.LogInfo((object)((text2.Length == 0) ? ("Шрифт-кандидат " + ((Object)val2).name + " (" + ((Object)((TMP_Text)val2).font).name + "): подходит полностью.") : ("Шрифт-кандидат " + ((Object)val2).name + " (" + ((Object)((TMP_Text)val2).font).name + "): не хватает символов «" + text2 + "».")));
					if (text2.Length == 0)
					{
						return val2;
					}
					if ((Object)(object)val == (Object)null || text2.Length < text.Length)
					{
						val = val2;
						text = text2;
					}
				}
			}
			if ((Object)(object)val != (Object)null)
			{
				Plugin.Log.LogWarning((object)("Полностью подходящего шрифта нет, беру " + ((Object)val).name + " — не хватает «" + text + "»."));
			}
			return val;
		}

		private static string MissingCharacters(TMP_FontAsset font)
		{
			StringBuilder stringBuilder = new StringBuilder();
			string text = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789$():.,-/ ";
			foreach (char c in text)
			{
				if (c != ' ' && !font.HasCharacter(c, false, false))
				{
					stringBuilder.Append(c);
				}
			}
			return stringBuilder.ToString();
		}

		private void CaptureControlTips(HUDManager hud)
		{
			//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)
			if (hud.controlTipLines == null || hud.controlTipLines.Length == 0)
			{
				return;
			}
			controlTips = hud.controlTipLines;
			controlTipsHome = (Vector2[])(object)new Vector2[controlTips.Length];
			for (int i = 0; i < controlTips.Length; i++)
			{
				if ((Object)(object)controlTips[i] != (Object)null)
				{
					controlTipsHome[i] = ((TMP_Text)controlTips[i]).rectTransform.anchoredPosition;
				}
			}
		}

		private void ApplyAppearance()
		{
			//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_0047: 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)
			((TMP_Text)label).fontSize = Plugin.FontSize.Value;
			Color color = ParseColor(Plugin.TextColor.Value, fallbackColor);
			color.a = Mathf.Clamp01(Plugin.Opacity.Value);
			((Graphic)label).color = color;
			rect.anchoredPosition = new Vector2(0f - Plugin.OffsetX.Value, 0f - Plugin.OffsetY.Value);
		}

		private static Color ParseColor(string hex, Color fallback)
		{
			//IL_0008: 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_002c: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(hex))
			{
				return fallback;
			}
			if (hex[0] != '#')
			{
				hex = "#" + hex;
			}
			Color result = default(Color);
			if (!ColorUtility.TryParseHtmlString(hex, ref result))
			{
				return fallback;
			}
			return result;
		}

		private void PositionControlTips()
		{
			//IL_009e: 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_010a: 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_013a: Unknown result type (might be due to invalid IL or missing references)
			if (controlTips == null || controlTips.Length == 0)
			{
				return;
			}
			if (!controlTipsMeasured)
			{
				float num = float.NegativeInfinity;
				for (int i = 0; i < controlTips.Length; i++)
				{
					if ((Object)(object)controlTips[i] != (Object)null)
					{
						num = Mathf.Max(num, WorldTop(((TMP_Text)controlTips[i]).rectTransform));
					}
				}
				if (float.IsNegativeInfinity(num))
				{
					return;
				}
				controlTipsHomeTop = num;
				controlTipsMeasured = true;
			}
			float num2 = 0f;
			if (Plugin.PushControlTips.Value && ((TMP_Text)label).text.Length > 0)
			{
				float num3 = ((Transform)rect).lossyScale.y;
				if (num3 <= 0f)
				{
					num3 = 1f;
				}
				num2 = (WorldTop(rect) - ((TMP_Text)label).preferredHeight * num3 - Plugin.ControlTipsGap.Value * num3 - controlTipsHomeTop) / num3;
			}
			for (int j = 0; j < controlTips.Length; j++)
			{
				if (!((Object)(object)controlTips[j] == (Object)null))
				{
					Vector2 val = controlTipsHome[j];
					val.y += num2;
					RectTransform rectTransform = ((TMP_Text)controlTips[j]).rectTransform;
					if (rectTransform.anchoredPosition != val)
					{
						rectTransform.anchoredPosition = val;
					}
				}
			}
		}

		private static float WorldTop(RectTransform target)
		{
			target.GetWorldCorners(cornerBuffer);
			return Mathf.Max(cornerBuffer[1].y, cornerBuffer[2].y);
		}

		private void Update()
		{
			if (!Plugin.Enabled.Value)
			{
				if (((TMP_Text)label).text.Length > 0)
				{
					((TMP_Text)label).text = string.Empty;
					PositionControlTips();
				}
				return;
			}
			timer -= Time.unscaledDeltaTime;
			if (!(timer > 0f))
			{
				timer = Plugin.UpdateInterval.Value;
				ApplyAppearance();
				Refresh();
				PositionControlTips();
			}
		}

		private void Refresh()
		{
			StartOfRound instance = StartOfRound.Instance;
			TimeOfDay instance2 = TimeOfDay.Instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)instance2 == (Object)null)
			{
				((TMP_Text)label).text = string.Empty;
				return;
			}
			Info info = new Info
			{
				Day = ((instance.gameStats != null) ? instance.gameStats.daysSpent : 0) + 1,
				DaysLeft = instance2.daysUntilDeadline,
				Moon = (((Object)(object)instance.currentLevel != (Object)null) ? instance.currentLevel.PlanetName : "?"),
				QuotaNumber = instance2.timesFulfilledQuota + 1,
				Quota = instance2.profitQuota,
				Loot = SumShipLoot()
			};
			DungeonInfo.Read(out var friendlyName, out var flowName);
			info.Dungeon = (string.IsNullOrEmpty(friendlyName) ? Plugin.NoDungeonText.Value : friendlyName);
			info.DungeonFlow = (string.IsNullOrEmpty(flowName) ? Plugin.NoDungeonText.Value : flowName);
			LogDungeonOnce(friendlyName, flowName, info.Moon);
			builder.Length = 0;
			AppendLine(Plugin.LineDay.Value, info);
			AppendLine(Plugin.LineMoon.Value, info);
			AppendLine(Plugin.LineQuota.Value, info);
			AppendLine(Plugin.LineLoot.Value, info);
			((TMP_Text)label).text = builder.ToString();
		}

		private void LogDungeonOnce(string dungeon, string dungeonFlow, string moon)
		{
			if (string.IsNullOrEmpty(dungeonFlow))
			{
				loggedDungeon = null;
			}
			else if (!(dungeonFlow == loggedDungeon))
			{
				loggedDungeon = dungeonFlow;
				Plugin.Log.LogInfo((object)("Интерьер: " + dungeon + " (ассет " + dungeonFlow + "), луна " + moon + "."));
			}
		}

		private void AppendLine(string format, Info info)
		{
			if (!string.IsNullOrEmpty(format))
			{
				if (builder.Length > 0)
				{
					builder.Append('\n');
				}
				string value = format.Replace("{day}", info.Day.ToString()).Replace("{daysLeft}", info.DaysLeft.ToString()).Replace("{moon}", info.Moon)
					.Replace("{dungeon}", info.Dungeon)
					.Replace("{dungeonFlow}", info.DungeonFlow)
					.Replace("{quotaNum}", info.QuotaNumber.ToString())
					.Replace("{quota}", info.Quota.ToString())
					.Replace("{loot}", info.Loot.ToString());
				builder.Append(value);
			}
		}

		private static int SumShipLoot()
		{
			int num = 0;
			GrabbableObject[] array = Object.FindObjectsByType<GrabbableObject>((FindObjectsSortMode)0);
			foreach (GrabbableObject val in array)
			{
				if (!((Object)(object)val == (Object)null) && !val.deactivated && !((Object)(object)val.itemProperties == (Object)null) && val.itemProperties.isScrap && val.isInShipRoom)
				{
					num += val.scrapValue;
				}
			}
			return num;
		}
	}
	[HarmonyPatch(typeof(HUDManager), "Start")]
	internal static class HudManagerPatch
	{
		[HarmonyPostfix]
		private static void Postfix(HUDManager __instance)
		{
			if (!Plugin.Enabled.Value)
			{
				return;
			}
			try
			{
				InfoHud.Create(__instance);
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Не удалось создать надпись: {arg}");
			}
		}
	}
	[BepInPlugin("oxxick.shipinfohud", "Ship Info HUD", "1.1.1")]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "oxxick.shipinfohud";

		public const string PluginName = "Ship Info HUD";

		public const string PluginVersion = "1.1.1";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<float> UpdateInterval;

		internal static ConfigEntry<float> FontSize;

		internal static ConfigEntry<float> OffsetX;

		internal static ConfigEntry<float> OffsetY;

		internal static ConfigEntry<float> Opacity;

		internal static ConfigEntry<string> TextColor;

		internal static ConfigEntry<bool> PushControlTips;

		internal static ConfigEntry<float> ControlTipsGap;

		internal static ConfigEntry<string> NoDungeonText;

		internal static ConfigEntry<string> LineDay;

		internal static ConfigEntry<string> LineMoon;

		internal static ConfigEntry<string> LineQuota;

		internal static ConfigEntry<string> LineLoot;

		private void Awake()
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Expected O, but got Unknown
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Expected O, but got Unknown
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Expected O, but got Unknown
			//IL_024b: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			Enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Показывать блок информации в правом верхнем углу.");
			UpdateInterval = ((BaseUnityPlugin)this).Config.Bind<float>("General", "UpdateInterval", 0.5f, new ConfigDescription("Как часто пересчитывать данные, в секундах. Подсчёт лута перебирает все предметы на сцене, поэтому каждый кадр это делать не стоит.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.05f, 5f), Array.Empty<object>()));
			FontSize = ((BaseUnityPlugin)this).Config.Bind<float>("Appearance", "FontSize", 16f, new ConfigDescription("Размер шрифта.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(6f, 48f), Array.Empty<object>()));
			OffsetX = ((BaseUnityPlugin)this).Config.Bind<float>("Appearance", "OffsetX", 14f, "Отступ от правого края экрана в пикселях.");
			OffsetY = ((BaseUnityPlugin)this).Config.Bind<float>("Appearance", "OffsetY", 10f, "Отступ от верхнего края экрана в пикселях.");
			Opacity = ((BaseUnityPlugin)this).Config.Bind<float>("Appearance", "Opacity", 1f, new ConfigDescription("Непрозрачность текста.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.1f, 1f), Array.Empty<object>()));
			TextColor = ((BaseUnityPlugin)this).Config.Bind<string>("Appearance", "TextColor", "FFFFFF", "Цвет текста в виде HEX без решётки. FFFFFF — белый, как на образце. C86400 — оранжевый под остальной HUD.");
			PushControlTips = ((BaseUnityPlugin)this).Config.Bind<bool>("Layout", "PushControlTipsDown", true, "Сдвигать вниз ванильные подсказки управления (Walk / Sprint / Scan), чтобы блок на них не наезжал.");
			ControlTipsGap = ((BaseUnityPlugin)this).Config.Bind<float>("Layout", "ControlTipsGap", 8f, "Зазор между блоком и сдвинутыми подсказками, в пикселях.");
			NoDungeonText = ((BaseUnityPlugin)this).Config.Bind<string>("Lines", "NoDungeonText", "-", "Что подставлять вместо интерьера, пока корабль на орбите.");
			LineDay = ((BaseUnityPlugin)this).Config.Bind<string>("Lines", "Line1", "Day: {day} ({daysLeft} left)", "Первая строка. Плейсхолдеры: {day}, {daysLeft}, {moon}, {dungeon}, {dungeonFlow}, {quotaNum}, {quota}, {loot}.\n{dungeon} — имя интерьера так, как оно записано в LethalLevelLoader.cfg (Grand Armory).\n{dungeonFlow} — имя ассета из самой игры (Level1Flow). Нужно, чтобы различать три варианта ванильной Facility.");
			LineMoon = ((BaseUnityPlugin)this).Config.Bind<string>("Lines", "Line2", "Interior: {dungeon}", "Вторая строка. Плейсхолдеры: {day}, {daysLeft}, {moon}, {dungeon}, {dungeonFlow}, {quotaNum}, {quota}, {loot}.\n{dungeon} — имя интерьера так, как оно записано в LethalLevelLoader.cfg (Grand Armory).\n{dungeonFlow} — имя ассета из самой игры (Level1Flow). Нужно, чтобы различать три варианта ванильной Facility.");
			LineQuota = ((BaseUnityPlugin)this).Config.Bind<string>("Lines", "Line3", "Quota {quotaNum}: ${quota}", "Третья строка. Плейсхолдеры: {day}, {daysLeft}, {moon}, {dungeon}, {dungeonFlow}, {quotaNum}, {quota}, {loot}.\n{dungeon} — имя интерьера так, как оно записано в LethalLevelLoader.cfg (Grand Armory).\n{dungeonFlow} — имя ассета из самой игры (Level1Flow). Нужно, чтобы различать три варианта ванильной Facility.");
			LineLoot = ((BaseUnityPlugin)this).Config.Bind<string>("Lines", "Line4", "Ship Loot: ${loot}", "Четвёртая строка. Плейсхолдеры: {day}, {daysLeft}, {moon}, {dungeon}, {dungeonFlow}, {quotaNum}, {quota}, {loot}.\n{dungeon} — имя интерьера так, как оно записано в LethalLevelLoader.cfg (Grand Armory).\n{dungeonFlow} — имя ассета из самой игры (Level1Flow). Нужно, чтобы различать три варианта ванильной Facility.");
			new Harmony("oxxick.shipinfohud").PatchAll(typeof(HudManagerPatch));
			Log.LogInfo((object)"Ship Info HUD 1.1.1 загружен.");
		}
	}
}

BepInEx/plugins/VanillaLogSpamFix/VanillaLogSpamFix.dll

Decompiled 12 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("VanillaLogSpamFix")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.2.0.0")]
[assembly: AssemblyInformationalVersion("1.2.0")]
[assembly: AssemblyProduct("Vanilla Log Spam Fix")]
[assembly: AssemblyTitle("VanillaLogSpamFix")]
[assembly: AssemblyVersion("1.2.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace VanillaLogSpamFix
{
	internal static class Patches
	{
		private static readonly MethodInfo DebugLogObject = AccessTools.Method(typeof(Debug), "Log", new Type[1] { typeof(object) }, (Type[])null);

		private static readonly Dictionary<MethodBase, string[]> Targets = new Dictionary<MethodBase, string[]>();

		private static readonly HashSet<MethodBase> AlreadySilenced = new HashSet<MethodBase>();

		internal static void ApplyAll(Harmony harmony)
		{
			if (DebugLogObject == null)
			{
				throw new InvalidOperationException("не найден UnityEngine.Debug.Log(object)");
			}
			if (Plugin.FixTargetable.Value)
			{
				Silence(harmony, AccessTools.Method(typeof(EnemyAI), "PlayerIsTargetable", (Type[])null, (Type[])null), "EnemyAI.PlayerIsTargetable", "Targetable A");
			}
			if (Plugin.FixHoarderBug.Value)
			{
				Silence(harmony, AccessTools.Method(typeof(HoarderBugAI), "SetGoTowardsTargetObject", (Type[])null, (Type[])null), "HoarderBugAI.SetGoTowardsTargetObject", ": Setting target object and going towards it.");
			}
			if (Plugin.FixHoarderBugHit.Value)
			{
				Silence(harmony, AccessTools.DeclaredMethod(typeof(HoarderBugAI), "HitEnemy", (Type[])null, (Type[])null), "HoarderBugAI.HitEnemy", "HA", "HB", "HC");
			}
			if (Plugin.FixOutsideEnemyPrediction.Value)
			{
				Silence(harmony, AccessTools.Method(typeof(RoundManager), "PredictAllOutsideEnemies", (Type[])null, (Type[])null), "RoundManager.PredictAllOutsideEnemies", "G", "H", "I", "J");
			}
			if (Plugin.FixExitPath.Value)
			{
				Silence(harmony, AccessTools.Method(typeof(ManualCameraRenderer), "SetLineToExitFromRadarTarget", (Type[])null, (Type[])null), "ManualCameraRenderer.SetLineToExitFromRadarTarget", "Path to exit could not be calculated");
			}
		}

		private static void Silence(Harmony harmony, MethodBase target, string label, params string[] literals)
		{
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			if (target == null)
			{
				Plugin.Log.LogError((object)("Метод " + label + " не найден, правка не применена."));
				return;
			}
			Targets[target] = literals;
			try
			{
				harmony.Patch(target, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(AccessTools.Method(typeof(Patches), "Transpiler", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null);
			}
			catch (Exception ex)
			{
				Targets.Remove(target);
				Plugin.Log.LogError((object)("Не удалось заглушить " + label + ": " + ex.Message));
			}
		}

		private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase original)
		{
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Expected O, but got Unknown
			List<CodeInstruction> list = new List<CodeInstruction>(instructions);
			if (original == null || !Targets.TryGetValue(original, out var value) || value == null)
			{
				return list;
			}
			int num = 0;
			for (int i = 0; i < list.Count; i++)
			{
				if (list[i].opcode != OpCodes.Ldstr || !IsWantedLiteral(value, list[i].operand))
				{
					continue;
				}
				for (int j = i + 1; j < Math.Min(list.Count, i + 6); j++)
				{
					if (CodeInstructionExtensions.Calls(list[j], DebugLogObject))
					{
						CodeInstruction val = new CodeInstruction(OpCodes.Pop, (object)null);
						CodeInstructionExtensions.MoveLabelsTo(list[j], val);
						CodeInstructionExtensions.MoveBlocksTo(list[j], val);
						list[j] = val;
						num++;
						break;
					}
				}
			}
			if (num > 0)
			{
				AlreadySilenced.Add(original);
				Plugin.Log.LogInfo((object)$"{original.Name}: заглушено вызовов — {num}.");
			}
			else if (!AlreadySilenced.Contains(original))
			{
				Plugin.Log.LogError((object)(original.Name + ": вызов лога не найден — игра, похоже, обновилась, правка не применилась."));
			}
			return list;
		}

		private static bool IsWantedLiteral(string[] literals, object operand)
		{
			for (int i = 0; i < literals.Length; i++)
			{
				if (literals[i].Equals(operand))
				{
					return true;
				}
			}
			return false;
		}
	}
	[BepInPlugin("oxxick.vanillalogspamfix", "Vanilla Log Spam Fix", "1.2.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "oxxick.vanillalogspamfix";

		public const string PluginName = "Vanilla Log Spam Fix";

		public const string PluginVersion = "1.2.0";

		internal static ManualLogSource Log;

		internal static ConfigEntry<bool> FixTargetable;

		internal static ConfigEntry<bool> FixHoarderBug;

		internal static ConfigEntry<bool> FixHoarderBugHit;

		internal static ConfigEntry<bool> FixOutsideEnemyPrediction;

		internal static ConfigEntry<bool> FixExitPath;

		private void Awake()
		{
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Expected O, but got Unknown
			Log = ((BaseUnityPlugin)this).Logger;
			FixTargetable = ((BaseUnityPlugin)this).Config.Bind<bool>("Заглушить", "PlayerIsTargetable", true, "Убрать Debug.Log(\"Targetable A\") из EnemyAI.PlayerIsTargetable. Срабатывает на каждую пару «моб — игрок в корабле», то есть постоянно во время взлёта, посадки и загрузки луны. Замерено 204 строки в секунду, на пике 314.");
			FixHoarderBug = ((BaseUnityPlugin)this).Config.Bind<bool>("Заглушить", "HoarderBugTarget", true, "Убрать Debug.Log из HoarderBugAI.SetGoTowardsTargetObject («...: Setting target object and going towards it.»).");
			FixHoarderBugHit = ((BaseUnityPlugin)this).Config.Bind<bool>("Заглушить", "HoarderBugHit", true, "Убрать три отладочные метки «HA», «HB», «HC» из HoarderBugAI.HitEnemy. Пишутся на каждый удар по жуку, у каждого клиента.");
			FixOutsideEnemyPrediction = ((BaseUnityPlugin)this).Config.Bind<bool>("Заглушить", "OutsideEnemyPrediction", true, "Убрать метки «G», «H», «I», «J» из RoundManager.PredictAllOutsideEnemies. За девятидневную сессию — 7 620 строк.");
			FixExitPath = ((BaseUnityPlugin)this).Config.Bind<bool>("Заглушить", "RadarExitPath", true, "Убрать «Path to exit could not be calculated» из радара (ManualCameraRenderer). Второй по объёму ванильный спам после «Targetable A»: 25 611 строк за ту же сессию.");
			try
			{
				Patches.ApplyAll(new Harmony("oxxick.vanillalogspamfix"));
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"Патчи не применились, спам остаётся: {arg}");
				return;
			}
			Log.LogInfo((object)"Vanilla Log Spam Fix 1.2.0 загружен.");
		}
	}
}