Decompiled source of Pressure v0.1.1

REPOPressure/REPOPressure.dll

Decompiled 8 hours ago
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using REPOLib;
using REPOLib.Modules;
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: AssemblyVersion("0.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace REPOMod
{
	[HarmonyPatch(typeof(ItemAttributes), "ShowInfo")]
	public static class ItemAttributes_ShowInfo_DiagnosticPatch
	{
		private static void Prefix(ItemAttributes __instance)
		{
			Debug.Log((object)("[REPO Pressure DIAGNOSTIC] ShowInfo() вызван для предмета: '" + ((Object)((Component)__instance).gameObject).name + "'"));
		}
	}
	public class ItemMedkitRechargeable : MonoBehaviour, IPunObservable
	{
		[Header("Запас HP")]
		public float maxStoredHP = 55f;

		public float healPerTick = 1f;

		public float healTickInterval = 0.5f;

		[Header("Саморегенерация запаса")]
		public float idleTimeBeforeRecharge = 10f;

		public float rechargePerTick = 1f;

		public float rechargeTickInterval = 5f;

		[Header("Анимация открытия/закрытия (опционально)")]
		[Tooltip("Animator с контроллером, где есть состояния Open и Close")]
		public Animator animator;

		public string openStateName = "Open";

		public string closeStateName = "Close";

		[Header("Индикатор запаса - смена материала (опционально)")]
		[Tooltip("Renderer, на котором меняется материал в зависимости от запаса HP")]
		public Renderer indicatorRenderer;

		[Tooltip("100% запаса")]
		public Material material100;

		[Tooltip("75-99% запаса")]
		public Material material75;

		[Tooltip("50-74% запаса")]
		public Material material50;

		[Tooltip("11-49% запаса")]
		public Material material11;

		[Tooltip("0-10% запаса")]
		public Material material0;

		[Header("Неразрушимость")]
		[Tooltip("Если включено - предмет никогда не сломается/не будет уничтожен от урона")]
		public bool indestructible = true;

		private float storedHP;

		private bool _previousToggleState;

		private Material _currentIndicatorMaterial;

		private ItemToggle itemToggle;

		private PhysGrabObject physGrabObject;

		private float healTimer;

		private float rechargeTimer;

		private float idleTimer;

		private void Start()
		{
			itemToggle = ((Component)this).GetComponent<ItemToggle>();
			physGrabObject = ((Component)this).GetComponent<PhysGrabObject>();
			storedHP = maxStoredHP;
		}

		private void Update()
		{
			UpdateIndicatorMaterial();
			if (indestructible)
			{
				ApplyIndestructible();
			}
			if (SemiFunc.IsMasterClientOrSingleplayer() && !SemiFunc.RunIsShop())
			{
				if (itemToggle.toggleState)
				{
					idleTimer = 0f;
					HealLogic();
				}
				else
				{
					IdleAndRechargeLogic();
				}
				if (itemToggle.toggleState != _previousToggleState)
				{
					PlayToggleAnimation(itemToggle.toggleState);
					_previousToggleState = itemToggle.toggleState;
				}
			}
		}

		private void ApplyIndestructible()
		{
			if (!((Object)(object)physGrabObject == (Object)null))
			{
				physGrabObject.dead = false;
				physGrabObject.lightBreakImpulse = false;
				physGrabObject.mediumBreakImpulse = false;
				physGrabObject.heavyBreakImpulse = false;
			}
		}

		private void PlayToggleAnimation(bool opening)
		{
			if (!((Object)(object)animator == (Object)null))
			{
				animator.Play(opening ? openStateName : closeStateName);
			}
		}

		private void UpdateIndicatorMaterial()
		{
			if (!((Object)(object)indicatorRenderer == (Object)null))
			{
				float num = ((maxStoredHP > 0f) ? (storedHP / maxStoredHP * 100f) : 0f);
				Material val = ((num >= 100f) ? material100 : ((num >= 75f) ? material75 : ((num >= 50f) ? material50 : ((!(num >= 11f)) ? material0 : material11))));
				if (!((Object)(object)val == (Object)null) && !((Object)(object)val == (Object)(object)_currentIndicatorMaterial))
				{
					indicatorRenderer.material = val;
					_currentIndicatorMaterial = val;
				}
			}
		}

		private void HealLogic()
		{
			PlayerAvatar val = physGrabObject.playerGrabbing.Select((PhysGrabber grabber) => grabber.playerAvatar).FirstOrDefault((Func<PlayerAvatar, bool>)((PlayerAvatar avatar) => (Object)(object)avatar != (Object)null));
			if ((Object)(object)val == (Object)null)
			{
				itemToggle.ToggleItem(false, -1);
				return;
			}
			PlayerHealth playerHealth = val.playerHealth;
			int value = Traverse.Create((object)playerHealth).Field<int>("health").Value;
			int value2 = Traverse.Create((object)playerHealth).Field<int>("maxHealth").Value;
			if (storedHP <= 0f || value >= value2)
			{
				itemToggle.ToggleItem(false, -1);
				return;
			}
			healTimer += Time.deltaTime;
			if (!(healTimer < healTickInterval))
			{
				healTimer -= healTickInterval;
				float num = Mathf.Min(healPerTick, storedHP);
				playerHealth.HealOther((int)num, true);
				storedHP -= num;
			}
		}

		private void IdleAndRechargeLogic()
		{
			if (storedHP >= maxStoredHP)
			{
				return;
			}
			idleTimer += Time.deltaTime;
			if (!(idleTimer < idleTimeBeforeRecharge))
			{
				rechargeTimer += Time.deltaTime;
				if (!(rechargeTimer < rechargeTickInterval))
				{
					rechargeTimer -= rechargeTickInterval;
					storedHP = Mathf.Min(maxStoredHP, storedHP + rechargePerTick);
				}
			}
		}

		public void OnPhotonSerializeView(PhotonStream stream, PhotonMessageInfo info)
		{
			if (stream.IsWriting)
			{
				stream.SendNext((object)storedHP);
			}
			else
			{
				storedHP = (float)stream.ReceiveNext();
			}
		}
	}
	[BepInPlugin("com.yourname.repopressure", "REPO Pressure", "1.0.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "com.yourname.repopressure";

		public const string PluginName = "REPO Pressure";

		public const string PluginVersion = "1.0.0";

		private Harmony _harmony;

		private void Awake()
		{
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			((BaseUnityPlugin)this).Logger.LogInfo((object)"REPO Pressure v1.0.0 loaded!");
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			_harmony = new Harmony("com.yourname.repopressure");
			_harmony.PatchAll();
			LoadContent();
		}

		private void LoadContent()
		{
			string text = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "pressure");
			if (!File.Exists(text))
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("AssetBundle не найден: " + text));
				return;
			}
			BundleLoader.LoadBundle(text, (Action<AssetBundle>)delegate(AssetBundle assetBundle)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)"AssetBundle 'pressure' успешно загружен.");
				RegisterValuable(assetBundle, "Forbidden Box");
				RegisterValuable(assetBundle, "N.O.S.T Classified Document");
				RegisterValuable(assetBundle, "Currency1");
				RegisterValuable(assetBundle, "Currency2");
				RegisterValuable(assetBundle, "Currency3");
				RegisterValuable(assetBundle, "CurVHS");
				RegisterValuable(assetBundle, "DNA");
				RegisterValuable(assetBundle, "DVD Case");
				RegisterValuable(assetBundle, "Rat");
				RegisterMedkit(assetBundle);
			}, false);
		}

		private void RegisterValuable(AssetBundle assetBundle, string prefabNameOrPath)
		{
			GameObject val = assetBundle.LoadAsset<GameObject>(prefabNameOrPath);
			if ((Object)(object)val == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("Valuable '" + prefabNameOrPath + "' не найден в бандле."));
				return;
			}
			Valuables.RegisterValuable(val);
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Valuable '" + ((Object)val).name + "' good."));
		}

		private void RegisterMedkit(AssetBundle assetBundle)
		{
			Item val = assetBundle.LoadAsset<Item>("Item Medkit Data");
			if ((Object)(object)val == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"Item 'Item Medkit Data' не найден в бандле.");
				return;
			}
			((PrefabRef<GameObject>)(object)val.prefab).SetPrefab(assetBundle, "Item Medkit");
			if (val.prefab == null || (Object)(object)((PrefabRef<GameObject>)(object)val.prefab).Prefab == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"У Item медкита не назначен PrefabRef/Prefab.");
				return;
			}
			GameObject prefab = ((PrefabRef<GameObject>)(object)val.prefab).Prefab;
			ItemAttributes component = prefab.GetComponent<ItemAttributes>();
			if ((Object)(object)component == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)"На префабе медкита нет ItemAttributes.");
				return;
			}
			if ((Object)(object)component.item == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"ItemAttributes.item не назначен в Unity.");
			}
			if ((Object)(object)prefab.GetComponent<ItemMedkitRechargeable>() == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"На префабе нет ItemMedkitRechargeable - добавь компонент в Unity.");
			}
			PrefabRef val2 = Items.RegisterItem(component);
			if (val2 == null)
			{
				((BaseUnityPlugin)this).Logger.LogError((object)("RegisterItem вернул null для '" + val.itemName + "'."));
				return;
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Item '" + val.itemName + "' зарегистрирован, PrefabRef: " + ((PrefabRef<GameObject>)(object)val2).PrefabName + "."));
		}

		private void WireUpMedkitReferences(GameObject prefab, AssetBundle assetBundle)
		{
			ItemMedkitRechargeable component = prefab.GetComponent<ItemMedkitRechargeable>();
			Transform val = prefab.transform.Find("MedkitP");
			if ((Object)(object)val == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"Не нашёл дочерний объект 'MedkitP' - проверь точное имя в иерархии.");
				return;
			}
			Animator val2 = ((Component)val).GetComponent<Animator>();
			if ((Object)(object)val2 == (Object)null)
			{
				val2 = ((Component)val).gameObject.AddComponent<Animator>();
			}
			RuntimeAnimatorController val3 = assetBundle.LoadAsset<RuntimeAnimatorController>("Medkit Animator");
			if ((Object)(object)val3 == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"Не нашёл 'Medkit Animator' в бандле - проверь, что у самого .controller файла в инспекторе внизу выставлено AssetBundle 'pressure'.");
			}
			else
			{
				val2.runtimeAnimatorController = val3;
			}
			component.animator = val2;
			Transform val4 = val.Find("Main");
			if ((Object)(object)val4 == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"Не нашёл дочерний объект 'Main' внутри 'MedkitP'.");
				return;
			}
			Renderer component2 = ((Component)val4).GetComponent<Renderer>();
			if ((Object)(object)component2 == (Object)null)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)"На объекте 'Main' нет компонента Renderer.");
				return;
			}
			component.indicatorRenderer = component2;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Animator и Indicator Renderer настроены кодом.");
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "REPOPressure";

		public const string PLUGIN_NAME = "REPOPressure";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}