Decompiled source of BackpackMod v1.0.3

RockMod.dll

Decompiled 15 hours ago
using System;
using System.Collections;
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 BepInEx;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.Rendering;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETFramework,Version=v4.6", FrameworkDisplayName = ".NET Framework 4.6")]
[assembly: AssemblyCompany("RockMod")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("RockMod")]
[assembly: AssemblyTitle("RockMod")]
[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 RockMod
{
	[HarmonyPatch(typeof(PlayerMovement))]
	public static class BackpackGive
	{
		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void UpdatePostfix(PlayerMovement __instance)
		{
			if (Input.GetKeyDown((KeyCode)98))
			{
				Debug.Log((object)"[Backpack Mod] B key detected.");
				InventoryItem backpackItem = BackpackItem.GetBackpackItem();
				if ((Object)(object)backpackItem == (Object)null)
				{
					Debug.LogWarning((object)"[Backpack Mod] Backpack object is null.");
					return;
				}
				if ((Object)(object)InventoryUI.Instance == (Object)null)
				{
					Debug.LogWarning((object)"[Backpack Mod] InventoryUI.Instance is null.");
					return;
				}
				InventoryUI.Instance.AddItemToInventory(backpackItem);
				Debug.Log((object)"[Backpack Mod] Gave player a Backpack.");
			}
		}
	}
	[HarmonyPatch(typeof(InventoryCell))]
	public static class BackpackInventoryPatch
	{
		[HarmonyPatch("SetItem")]
		[HarmonyPrefix]
		private static bool SetItemPrefix(InventoryCell __instance, InventoryItem pointerItem, ref InventoryItem __result)
		{
			if ((Object)(object)pointerItem == (Object)null)
			{
				return true;
			}
			if (pointerItem.id != BackpackItem.BackpackID)
			{
				return true;
			}
			InventoryItem currentItem = __instance.currentItem;
			__instance.currentItem = pointerItem;
			__instance.UpdateCell();
			__result = currentItem;
			return false;
		}
	}
	[HarmonyPatch(typeof(ItemManager))]
	public static class BackpackItem
	{
		public static int BackpackID = -30;

		private static InventoryItem backpackItem;

		private static bool registered;

		public static InventoryItem GetBackpackItem()
		{
			return backpackItem;
		}

		[HarmonyPatch("Awake")]
		[HarmonyPostfix]
		private static void AwakePostfix(ItemManager __instance)
		{
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Expected O, but got Unknown
			try
			{
				if ((Object)(object)__instance == (Object)null || registered || __instance.allScriptableItems == null)
				{
					return;
				}
				string directoryName = Path.GetDirectoryName(typeof(BackpackItem).Assembly.Location);
				if (string.IsNullOrEmpty(directoryName))
				{
					return;
				}
				string path = Path.Combine(directoryName, "Assets", "Backpack");
				string path2 = Path.Combine(path, "Backpack.obj");
				string text = Path.Combine(path, "Backpack.png");
				if (!File.Exists(path2) || !File.Exists(text))
				{
					return;
				}
				BackpackID = __instance.allScriptableItems.Length;
				Mesh val = ObjLoader.Load(path2);
				if ((Object)(object)val == (Object)null)
				{
					return;
				}
				Shader val2 = Shader.Find("Standard");
				if ((Object)(object)val2 == (Object)null)
				{
					val2 = Shader.Find("Diffuse");
				}
				if (!((Object)(object)val2 == (Object)null))
				{
					Material val3 = new Material(val2);
					((Object)val3).name = "BackpackMaterial";
					backpackItem = ScriptableObject.CreateInstance<InventoryItem>();
					backpackItem.name = "Backpack";
					backpackItem.description = "A backpack that increases inventory space.";
					backpackItem.id = BackpackID;
					backpackItem.amount = 1;
					backpackItem.max = 1;
					backpackItem.stackable = false;
					backpackItem.mesh = val;
					backpackItem.material = val3;
					backpackItem.scale = 1f;
					if (!RegisterItem(__instance, backpackItem))
					{
						backpackItem = null;
						return;
					}
					registered = true;
					((MonoBehaviour)__instance).StartCoroutine(LoadBackpackIcon(text, backpackItem));
				}
			}
			catch
			{
			}
		}

		private static bool RegisterItem(ItemManager itemManager, InventoryItem item)
		{
			try
			{
				FieldInfo field = typeof(ItemManager).GetField("allItems", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				if (field == null)
				{
					return false;
				}
				object value = field.GetValue(itemManager);
				if (value == null)
				{
					return false;
				}
				MethodInfo method = value.GetType().GetMethod("Add");
				if (method == null)
				{
					return false;
				}
				method.Invoke(value, new object[2] { BackpackID, item });
				return true;
			}
			catch
			{
				return false;
			}
		}

		private static IEnumerator LoadBackpackIcon(string pngPath, InventoryItem item)
		{
			string fileUrl = "file:///" + pngPath.Replace("\\", "/");
			WWW www;
			try
			{
				www = new WWW(fileUrl);
			}
			catch
			{
				yield break;
			}
			while (!www.isDone)
			{
				yield return null;
			}
			if (!string.IsNullOrEmpty(www.error))
			{
				www.Dispose();
				yield break;
			}
			Texture2D texture = www.texture;
			if ((Object)(object)texture == (Object)null)
			{
				www.Dispose();
				yield break;
			}
			((Object)texture).name = "BackpackIcon";
			((Texture)texture).wrapMode = (TextureWrapMode)1;
			((Texture)texture).filterMode = (FilterMode)1;
			Sprite backpackSprite = Sprite.Create(texture, new Rect(0f, 0f, (float)((Texture)texture).width, (float)((Texture)texture).height), new Vector2(0.5f, 0.5f), 100f);
			((Object)backpackSprite).name = "BackpackIcon";
			item.sprite = backpackSprite;
			www.Dispose();
		}
	}
	public static class ObjLoader
	{
		private struct FaceVertex
		{
			public int vertex;

			public int uv;

			public int normal;
		}

		public static Mesh Load(string path)
		{
			//IL_039b: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a2: Expected O, but got Unknown
			//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_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ed: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				string[] array = File.ReadAllLines(path);
				Vector3[] array2 = (Vector3[])(object)new Vector3[256];
				Vector2[] array3 = (Vector2[])(object)new Vector2[256];
				Vector3[] array4 = (Vector3[])(object)new Vector3[256];
				Vector3[] finalVertices = (Vector3[])(object)new Vector3[512];
				Vector2[] finalUVs = (Vector2[])(object)new Vector2[512];
				Vector3[] finalNormals = (Vector3[])(object)new Vector3[512];
				int[] triangles = new int[512];
				int num = 0;
				int num2 = 0;
				int num3 = 0;
				int finalVertexCount = 0;
				int finalTriangleCount = 0;
				for (int i = 0; i < array.Length; i++)
				{
					string text = array[i].Trim();
					if (text.Length == 0 || text.StartsWith("#"))
					{
						continue;
					}
					string[] array5 = text.Split(new char[2] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
					if (array5.Length == 0)
					{
						continue;
					}
					if (array5[0] == "v")
					{
						if (array5.Length >= 4)
						{
							EnsureVector3Capacity(ref array2, num + 1);
							array2[num] = new Vector3(ParseFloat(array5[1]), ParseFloat(array5[2]), ParseFloat(array5[3]));
							num++;
						}
					}
					else if (array5[0] == "vt")
					{
						if (array5.Length >= 3)
						{
							EnsureVector2Capacity(ref array3, num2 + 1);
							array3[num2] = new Vector2(ParseFloat(array5[1]), ParseFloat(array5[2]));
							num2++;
						}
					}
					else if (array5[0] == "vn")
					{
						if (array5.Length >= 4)
						{
							EnsureVector3Capacity(ref array4, num3 + 1);
							array4[num3] = new Vector3(ParseFloat(array5[1]), ParseFloat(array5[2]), ParseFloat(array5[3]));
							num3++;
						}
					}
					else
					{
						if (!(array5[0] == "f") || array5.Length < 4)
						{
							continue;
						}
						FaceVertex[] array6 = new FaceVertex[array5.Length - 1];
						int num4 = 0;
						for (int j = 1; j < array5.Length; j++)
						{
							if (ParseFaceVertex(array5[j], num, num2, num3, out var result))
							{
								array6[num4] = result;
								num4++;
							}
						}
						if (num4 >= 3)
						{
							for (int k = 1; k < num4 - 1; k++)
							{
								AddFaceVertex(array6[0], array2, num, array3, num2, array4, num3, ref finalVertices, ref finalVertexCount, ref finalUVs, ref finalNormals, ref triangles, ref finalTriangleCount);
								AddFaceVertex(array6[k], array2, num, array3, num2, array4, num3, ref finalVertices, ref finalVertexCount, ref finalUVs, ref finalNormals, ref triangles, ref finalTriangleCount);
								AddFaceVertex(array6[k + 1], array2, num, array3, num2, array4, num3, ref finalVertices, ref finalVertexCount, ref finalUVs, ref finalNormals, ref triangles, ref finalTriangleCount);
							}
						}
					}
				}
				if (finalVertexCount == 0)
				{
					return null;
				}
				Vector3[] array7 = (Vector3[])(object)new Vector3[finalVertexCount];
				Vector2[] array8 = (Vector2[])(object)new Vector2[finalVertexCount];
				Vector3[] array9 = (Vector3[])(object)new Vector3[finalVertexCount];
				int[] array10 = new int[finalTriangleCount];
				Array.Copy(finalVertices, array7, finalVertexCount);
				Array.Copy(finalUVs, array8, finalVertexCount);
				Array.Copy(finalNormals, array9, finalVertexCount);
				Array.Copy(triangles, array10, finalTriangleCount);
				Mesh val = new Mesh();
				((Object)val).name = "BackpackMesh";
				if (finalVertexCount > 65535)
				{
					val.indexFormat = (IndexFormat)1;
				}
				val.vertices = array7;
				if (num2 > 0)
				{
					val.uv = array8;
				}
				if (num3 > 0)
				{
					val.normals = array9;
				}
				else
				{
					val.RecalculateNormals();
				}
				val.triangles = array10;
				val.RecalculateBounds();
				return val;
			}
			catch
			{
				return null;
			}
		}

		private static void EnsureVector3Capacity(ref Vector3[] array, int required)
		{
			if (required > array.Length)
			{
				int num = array.Length * 2;
				if (num < required)
				{
					num = required;
				}
				Vector3[] array2 = (Vector3[])(object)new Vector3[num];
				Array.Copy(array, array2, array.Length);
				array = array2;
			}
		}

		private static void EnsureVector2Capacity(ref Vector2[] array, int required)
		{
			if (required > array.Length)
			{
				int num = array.Length * 2;
				if (num < required)
				{
					num = required;
				}
				Vector2[] array2 = (Vector2[])(object)new Vector2[num];
				Array.Copy(array, array2, array.Length);
				array = array2;
			}
		}

		private static void AddFaceVertex(FaceVertex faceVertex, Vector3[] positions, int positionCount, Vector2[] uvs, int uvCount, Vector3[] normals, int normalCount, ref Vector3[] finalVertices, ref int finalVertexCount, ref Vector2[] finalUVs, ref Vector3[] finalNormals, ref int[] triangles, ref int finalTriangleCount)
		{
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_0097: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			int num = ResolveIndex(faceVertex.vertex, positionCount);
			if (num < 0 || num >= positionCount)
			{
				return;
			}
			EnsureFinalCapacity(ref finalVertices, ref finalUVs, ref finalNormals, ref triangles, finalVertexCount + 1, finalTriangleCount + 1);
			int num2 = finalVertexCount;
			finalVertices[num2] = positions[num];
			if (faceVertex.uv != 0 && uvCount > 0)
			{
				int num3 = ResolveIndex(faceVertex.uv, uvCount);
				if (num3 >= 0 && num3 < uvCount)
				{
					finalUVs[num2] = uvs[num3];
				}
			}
			if (faceVertex.normal != 0 && normalCount > 0)
			{
				int num4 = ResolveIndex(faceVertex.normal, normalCount);
				if (num4 >= 0 && num4 < normalCount)
				{
					finalNormals[num2] = normals[num4];
				}
			}
			triangles[finalTriangleCount] = num2;
			finalVertexCount++;
			finalTriangleCount++;
		}

		private static void EnsureFinalCapacity(ref Vector3[] vertices, ref Vector2[] uvs, ref Vector3[] normals, ref int[] triangles, int requiredVertices, int requiredTriangles)
		{
			if (requiredVertices > vertices.Length)
			{
				int num = vertices.Length * 2;
				if (num < requiredVertices)
				{
					num = requiredVertices;
				}
				Vector3[] array = (Vector3[])(object)new Vector3[num];
				Vector2[] array2 = (Vector2[])(object)new Vector2[num];
				Vector3[] array3 = (Vector3[])(object)new Vector3[num];
				Array.Copy(vertices, array, vertices.Length);
				Array.Copy(uvs, array2, uvs.Length);
				Array.Copy(normals, array3, normals.Length);
				vertices = array;
				uvs = array2;
				normals = array3;
			}
			if (requiredTriangles > triangles.Length)
			{
				int num2 = triangles.Length * 2;
				if (num2 < requiredTriangles)
				{
					num2 = requiredTriangles;
				}
				int[] array4 = new int[num2];
				Array.Copy(triangles, array4, triangles.Length);
				triangles = array4;
			}
		}

		private static bool ParseFaceVertex(string value, int vertexCount, int uvCount, int normalCount, out FaceVertex result)
		{
			result = default(FaceVertex);
			string[] array = value.Split(new char[1] { '/' });
			if (array.Length == 0)
			{
				return false;
			}
			if (!int.TryParse(array[0], out var result2))
			{
				return false;
			}
			result.vertex = result2;
			if (array.Length > 1 && array[1].Length > 0 && int.TryParse(array[1], out var result3))
			{
				result.uv = result3;
			}
			if (array.Length > 2 && array[2].Length > 0 && int.TryParse(array[2], out var result4))
			{
				result.normal = result4;
			}
			return true;
		}

		private static int ResolveIndex(int index, int count)
		{
			if (index > 0)
			{
				return index - 1;
			}
			if (index < 0)
			{
				return count + index;
			}
			return -1;
		}

		private static float ParseFloat(string value)
		{
			if (float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
			{
				return result;
			}
			return 0f;
		}
	}
	[HarmonyPatch(typeof(Chest))]
	public static class ChestLootPatch
	{
		private const float BACKPACK_CHANCE = 25f;

		[HarmonyPatch("InitChest")]
		[HarmonyPrefix]
		private static void InitChestPrefix(Chest __instance, List<InventoryItem> items)
		{
			if (items != null)
			{
				InventoryItem backpackItem = BackpackItem.GetBackpackItem();
				if (!((Object)(object)backpackItem == (Object)null) && !(Random.Range(0f, 100f) >= 25f))
				{
					InventoryItem val = ScriptableObject.CreateInstance<InventoryItem>();
					val.Copy(backpackItem, 1);
					val.amount = 1;
					val.max = 1;
					val.stackable = false;
					items.Add(val);
				}
			}
		}
	}
	[HarmonyPatch(typeof(InventoryUI))]
	public static class InventoryUIPatch
	{
		private const int EXTRA_SLOTS = 7;

		private static float nextCheckTime;

		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void StartPostfix(InventoryUI __instance)
		{
			nextCheckTime = Time.time + 0.5f;
		}

		[HarmonyPatch("Update")]
		[HarmonyPostfix]
		private static void UpdatePostfix(InventoryUI __instance)
		{
			if (Time.time < nextCheckTime)
			{
				return;
			}
			nextCheckTime = Time.time + 0.5f;
			if ((Object)(object)__instance.inventoryParent == (Object)null || BackpackItem.BackpackID < 0)
			{
				return;
			}
			InventoryCell[] componentsInChildren = ((Component)__instance.inventoryParent).GetComponentsInChildren<InventoryCell>(true);
			bool flag = false;
			foreach (InventoryCell val in componentsInChildren)
			{
				if (!((Object)(object)val == (Object)null) && !((Object)(object)val.currentItem == (Object)null) && val.currentItem.id == BackpackItem.BackpackID)
				{
					flag = true;
					break;
				}
			}
			int num = 0;
			foreach (InventoryCell val2 in componentsInChildren)
			{
				if (!((Object)(object)val2 == (Object)null) && ((Object)((Component)val2).gameObject).name.StartsWith("BackpackCell_"))
				{
					num++;
				}
			}
			if (flag && num == 0)
			{
				AddBackpackSlots(__instance, componentsInChildren);
			}
			else if (!flag && num > 0)
			{
				RemoveBackpackSlots(__instance, componentsInChildren);
			}
		}

		private static void AddBackpackSlots(InventoryUI inventoryUI, InventoryCell[] existingCells)
		{
			if (existingCells.Length == 0)
			{
				return;
			}
			InventoryCell val = existingCells[0];
			for (int i = 0; i < 7; i++)
			{
				GameObject val2 = Object.Instantiate<GameObject>(((Component)val).gameObject, inventoryUI.inventoryParent);
				((Object)val2).name = "BackpackCell_" + i;
				InventoryCell component = val2.GetComponent<InventoryCell>();
				if ((Object)(object)component != (Object)null)
				{
					component.currentItem = null;
					component.spawnItem = null;
					component.cellId = existingCells.Length + i;
					component.UpdateCell();
				}
			}
			((Component)inventoryUI).SendMessage("FillCellList", (SendMessageOptions)1);
		}

		private static void RemoveBackpackSlots(InventoryUI inventoryUI, InventoryCell[] cells)
		{
			bool flag = false;
			foreach (InventoryCell val in cells)
			{
				if (!((Object)(object)val == (Object)null) && ((Object)((Component)val).gameObject).name.StartsWith("BackpackCell_"))
				{
					if ((Object)(object)val.currentItem != (Object)null)
					{
						flag = true;
					}
					else
					{
						Object.Destroy((Object)(object)((Component)val).gameObject);
					}
				}
			}
			if (!flag)
			{
				((Component)inventoryUI).SendMessage("FillCellList", (SendMessageOptions)1);
			}
		}
	}
	[BepInPlugin("com.synewave.rockmod", "Rock Mod", "1.0.0")]
	public class Plugin : BaseUnityPlugin
	{
		private void Awake()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Expected O, but got Unknown
			Harmony val = new Harmony("com.synewave.rockmod");
			val.PatchAll();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"loaded backpack mod");
		}
	}
}