using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.Localization;
using UnityEngine.Localization.Settings;
using UnityEngine.Localization.Tables;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.UIElements;
[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.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("ItemAPI")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("ItemAPI")]
[assembly: AssemblyTitle("ItemAPI")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
[CompilerGenerated]
[Embedded]
internal sealed class EmbeddedAttribute : Attribute
{
}
}
namespace System.Runtime.CompilerServices
{
[CompilerGenerated]
[Embedded]
[AttributeUsage(AttributeTargets.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.Module, AllowMultiple = false, Inherited = false)]
internal sealed class RefSafetyRulesAttribute : Attribute
{
public readonly int Version;
public RefSafetyRulesAttribute(int P_0)
{
Version = P_0;
}
}
}
namespace ItemAPI
{
[BepInPlugin("com.mattcy.itemapi", "ItemAPI", "1.0.0")]
public class ItemAPIPlugin : BaseUnityPlugin
{
internal static ManualLogSource Log;
private static ItemAPIPlugin _instance;
private void Awake()
{
_instance = this;
Log = ((BaseUnityPlugin)this).Logger;
ItemAPI.Init(((BaseUnityPlugin)this).Logger);
Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
}
private void Update()
{
ItemAPI.OnUpdate();
}
}
public class ItemAPI
{
public enum RoomsToSpawn
{
ALL,
Kitchen,
LivingRoom,
DiningRoom,
Bedroom,
Bathroom,
Sauna,
DefaultRoom,
ArtRoom,
KidsRoom,
HallwayRoom
}
private class PlayerState
{
public readonly List<int> InHotbar = new List<int>();
public readonly Dictionary<int, float> TrackedItemDurability = new Dictionary<int, float>();
public float LeftClickHoldTimer = 0f;
public bool HasSentLeftHoldTrue = false;
}
[HarmonyPatch(typeof(NetworkManager), "StartHost")]
internal static class NetworkManagerInitializationPatch
{
[CompilerGenerated]
private static class <>O
{
public static HandleNamedMessageDelegate <0>__ReceiveDurabilityRequestOnServer;
public static HandleNamedMessageDelegate <1>__ReceiveSpawnRequest;
public static HandleNamedMessageDelegate <2>__ReceiveInventoryItemRequest;
}
private static void Postfix(NetworkManager __instance)
{
//IL_0053: Unknown result type (might be due to invalid IL or missing references)
//IL_0058: Unknown result type (might be due to invalid IL or missing references)
//IL_005e: Expected O, but got Unknown
//IL_007f: Unknown result type (might be due to invalid IL or missing references)
//IL_0084: Unknown result type (might be due to invalid IL or missing references)
//IL_008a: Expected O, but got Unknown
//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
//IL_00b6: Expected O, but got Unknown
if (!((Object)(object)__instance == (Object)null) && __instance.CustomMessagingManager != null && (__instance.IsServer || __instance.IsHost))
{
CustomMessagingManager customMessagingManager = __instance.CustomMessagingManager;
object obj = <>O.<0>__ReceiveDurabilityRequestOnServer;
if (obj == null)
{
HandleNamedMessageDelegate val = ReceiveDurabilityRequestOnServer;
<>O.<0>__ReceiveDurabilityRequestOnServer = val;
obj = (object)val;
}
customMessagingManager.RegisterNamedMessageHandler("RequestConsumeDurability", (HandleNamedMessageDelegate)obj);
CustomMessagingManager customMessagingManager2 = __instance.CustomMessagingManager;
object obj2 = <>O.<1>__ReceiveSpawnRequest;
if (obj2 == null)
{
HandleNamedMessageDelegate val2 = ReceiveSpawnRequest;
<>O.<1>__ReceiveSpawnRequest = val2;
obj2 = (object)val2;
}
customMessagingManager2.RegisterNamedMessageHandler("ModdedRequestItemSpawn", (HandleNamedMessageDelegate)obj2);
CustomMessagingManager customMessagingManager3 = __instance.CustomMessagingManager;
object obj3 = <>O.<2>__ReceiveInventoryItemRequest;
if (obj3 == null)
{
HandleNamedMessageDelegate val3 = ReceiveInventoryItemRequest;
<>O.<2>__ReceiveInventoryItemRequest = val3;
obj3 = (object)val3;
}
customMessagingManager3.RegisterNamedMessageHandler("ModdedRequestInventoryItem", (HandleNamedMessageDelegate)obj3);
}
}
}
public static class NetworkSpawner
{
public unsafe static void RequestSpawn(string itemName, Vector3 position, string? uniqueId)
{
//IL_0044: 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)
lastUniqueId = uniqueId ?? "";
if ((Object)(object)NetworkManager.Singleton == (Object)null)
{
return;
}
if (NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost)
{
ExecuteSpawn(itemName, position, uniqueId);
return;
}
FastBufferWriter val = default(FastBufferWriter);
((FastBufferWriter)(ref val))..ctor(128, (Allocator)2, -1);
try
{
((FastBufferWriter)(ref val)).WriteValueSafe(itemName, false);
((FastBufferWriter)(ref val)).WriteValueSafe(ref position);
((FastBufferWriter)(ref val)).WriteValueSafe(uniqueId ?? "", false);
NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("ModdedRequestItemSpawn", 0uL, val, (NetworkDelivery)3);
}
finally
{
((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
}
}
public static void ExecuteSpawn(string itemName, Vector3 position, string UniqueId)
{
//IL_00db: Unknown result type (might be due to invalid IL or missing references)
//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
//IL_00f2: 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)
NetworkManager singleton = NetworkManager.Singleton;
object obj;
if (singleton == null)
{
obj = null;
}
else
{
NetworkConfig networkConfig = singleton.NetworkConfig;
if (networkConfig == null)
{
obj = null;
}
else
{
NetworkPrefabs prefabs = networkConfig.Prefabs;
obj = ((prefabs != null) ? prefabs.Prefabs : null);
}
}
if (obj == null)
{
return;
}
GameObject val = ((IEnumerable<NetworkPrefab>)NetworkManager.Singleton.NetworkConfig.Prefabs.Prefabs).FirstOrDefault((Func<NetworkPrefab, bool>)((NetworkPrefab p) => (Object)(object)p.Prefab != (Object)null && ((Object)p.Prefab).name.Equals(itemName, StringComparison.OrdinalIgnoreCase)))?.Prefab;
if ((Object)(object)val == (Object)null)
{
try
{
GetAllItems().SpawnItemInstance(itemName, position);
return;
}
catch
{
try
{
AiDirector val2 = Object.FindFirstObjectByType<AiDirector>();
if ((Object)(object)val2 == (Object)null)
{
return;
}
PlayerNetworking localPlayer = GetLocalPlayer();
if (!((Object)(object)localPlayer == (Object)null))
{
val2.SpawnEnemy(itemName, position);
return;
}
}
catch
{
return;
}
}
}
GameObject val3 = Object.Instantiate<GameObject>(val, position, Quaternion.identity);
NetworkObject component = val3.GetComponent<NetworkObject>();
if ((Object)(object)component != (Object)null)
{
component.Spawn(false);
onItemSpawnedViaRequest(val3, UniqueId);
}
else
{
Object.Destroy((Object)(object)val3);
}
}
}
[HarmonyPatch]
internal static class OnSpawnedPrivatePatch
{
[HarmonyTargetMethod]
private static MethodBase TargetMethod()
{
Type nestedType = typeof(AiDirector).GetNestedType("RuntimeEntityCollection", BindingFlags.Public | BindingFlags.NonPublic);
if (nestedType == null)
{
return null;
}
return nestedType.GetMethod("OnSpawned", BindingFlags.Instance | BindingFlags.NonPublic);
}
[HarmonyPostfix]
private static void Postfix(object __instance, object instance)
{
if (instance == null)
{
return;
}
PropertyInfo property = instance.GetType().GetProperty("gameObject", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
if (property != null)
{
object? value = property.GetValue(instance);
GameObject val = (GameObject)((value is GameObject) ? value : null);
if ((Object)(object)val != (Object)null)
{
onEnnemySpawnedViaRequest(val, lastUniqueId);
}
}
}
}
[HarmonyPatch(typeof(NetworkBehaviour), "OnNetworkSpawn")]
internal static class PlayerNetworkingSpawnPatch
{
private static void Postfix(NetworkBehaviour __instance)
{
PlayerNetworking val = (PlayerNetworking)(object)((__instance is PlayerNetworking) ? __instance : null);
if (!((Object)(object)val == (Object)null))
{
playersById[((NetworkBehaviour)val).OwnerClientId] = val;
if (((NetworkBehaviour)val).IsLocalPlayer)
{
localPlayer = val;
}
}
}
}
[HarmonyPatch(typeof(NetworkBehaviour), "OnNetworkDespawn")]
internal static class PlayerNetworkingDespawnPatch
{
private static void Postfix(NetworkBehaviour __instance)
{
PlayerNetworking val = (PlayerNetworking)(object)((__instance is PlayerNetworking) ? __instance : null);
if ((Object)(object)val == (Object)null)
{
return;
}
ulong ownerClientId = ((NetworkBehaviour)val).OwnerClientId;
playersById.Remove(ownerClientId);
itemsEquipped.Remove(ownerClientId);
slotItemName.Remove(ownerClientId);
if (_slotVisual.TryGetValue(ownerClientId, out var value))
{
for (int i = 0; i < value.Length; i++)
{
if ((Object)(object)value[i] != (Object)null)
{
Object.Destroy((Object)(object)value[i]);
}
}
_slotVisual.Remove(ownerClientId);
}
if ((Object)(object)localPlayer == (Object)(object)val)
{
localPlayer = null;
}
}
}
[HarmonyPatch]
internal static class EquipmentSlotTrackingPatch
{
[HarmonyTargetMethod]
private static MethodBase TargetMethod()
{
return AccessTools.Method(typeof(EquipmentController), "<UpdateEquipmentState>g__UpdateHandlerState|32_0", (Type[])null, (Type[])null);
}
[HarmonyPrefix]
private static void Prefix(EquipmentController __instance, int inventorySlotIndex, Action<string> activationFunction)
{
//IL_0045: Unknown result type (might be due to invalid IL or missing references)
//IL_004a: Unknown result type (might be due to invalid IL or missing references)
int slotType = GetSlotType(activationFunction);
if (slotType == -1)
{
return;
}
PlayerNetworking component = ((Component)__instance).GetComponent<PlayerNetworking>();
if ((Object)(object)component == (Object)null)
{
return;
}
string newItemName = null;
if (inventorySlotIndex != -1)
{
InventoryItem itemInSlot = ((InventoryBase)component.Inventory).GetItemInSlot(inventorySlotIndex);
if (((InventoryItem)(ref itemInSlot)).IsValidItem && (Object)(object)AllItems != (Object)null && ((InventoryItem)(ref itemInSlot)).ItemIndex >= 0 && ((InventoryItem)(ref itemInSlot)).ItemIndex < AllItems.items.Length)
{
ItemData obj = AllItems.items[((InventoryItem)(ref itemInSlot)).ItemIndex];
newItemName = ((obj != null) ? ((Object)obj).name : null);
}
}
UpdateSlotTracking(component, slotType, newItemName);
}
private static int GetSlotType(Action<string> activationFunction)
{
return activationFunction.Method.Name switch
{
"SetHandEquipment" => 0,
"SetWearedEquipment" => 1,
"SetOtherWearedEquipment" => 2,
_ => -1,
};
}
private static void UpdateSlotTracking(PlayerNetworking player, int slotType, string newItemName)
{
ulong ownerClientId = ((NetworkBehaviour)player).OwnerClientId;
if (!slotItemName.TryGetValue(ownerClientId, out var value))
{
value = new string[3];
slotItemName[ownerClientId] = value;
}
string text = value[slotType];
if (text == newItemName)
{
return;
}
if (!_slotVisual.TryGetValue(ownerClientId, out var value2))
{
value2 = (GameObject[])(object)new GameObject[3];
_slotVisual[ownerClientId] = value2;
}
if (!itemsEquipped.TryGetValue(ownerClientId, out var value3))
{
value3 = new HashSet<string>();
itemsEquipped[ownerClientId] = value3;
}
if (!string.IsNullOrEmpty(text))
{
value3.Remove(text);
if ((Object)(object)value2[slotType] != (Object)null)
{
Object.Destroy((Object)(object)value2[slotType]);
value2[slotType] = null;
}
if (RegisteredEquipment.TryGetValue(text, out var value4))
{
value4.OnUnequip(player);
}
}
if (!string.IsNullOrEmpty(newItemName))
{
value3.Add(newItemName);
if (RegisteredEquipment.TryGetValue(newItemName, out var value5))
{
GameObject val = null;
if ((Object)(object)value5.Prefab != (Object)null)
{
val = Object.Instantiate<GameObject>(value5.Prefab, ((Component)player).transform, false);
((Object)val).name = $"CustomItemVisual_{ownerClientId}_{slotType}";
value2[slotType] = val;
}
value5.OnEquip(val ?? ((Component)player).gameObject, player);
}
}
value[slotType] = newItemName;
}
}
[HarmonyPatch(typeof(InventoryBase), "OnNetworkSpawn")]
internal static class InventoryOnNetworkSpawnPatch
{
private static void Postfix(InventoryBase __instance)
{
AllItems = __instance.BoundItems;
RegisterItems(AllItems);
RebuildItemNameIndex();
}
}
[HarmonyPatch(typeof(GnomiumDeposit), "OnNetworkSpawn")]
internal static class GnomiumDepositOnNetworkSpawnPatch
{
private static void Postfix(GnomiumDeposit __instance)
{
((MonoBehaviour)__instance).StartCoroutine(RegisterRecipesCoroutine(__instance));
}
}
[HarmonyPatch(typeof(ItemInstance), "OnNetworkSpawn")]
internal static class ItemInstanceStartPatch
{
private static void Postfix(ItemInstance __instance)
{
//IL_0014: Unknown result type (might be due to invalid IL or missing references)
if (!((Object)(object)__instance == (Object)null) && RegisteredEquipmentByIndex.TryGetValue(__instance.InstanceData.itemIndex, out var value))
{
ApplyWorldVisuals(__instance, value);
}
}
}
[HarmonyPatch(typeof(ItemInstance), "OnDropped")]
internal static class ItemInstanceOnDroppedPatch
{
[HarmonyPostfix]
private static void Postfix(ItemInstance __instance, Vector3 velocity, InventoryBase droppedFrom)
{
//IL_004e: Unknown result type (might be due to invalid IL or missing references)
if ((Object)(object)droppedFrom == (Object)null)
{
return;
}
PlayerNetworking val = ((IEnumerable<PlayerNetworking>)playersById.Values).FirstOrDefault((Func<PlayerNetworking, bool>)((PlayerNetworking p) => (Object)(object)p.Inventory == (Object)(object)droppedFrom));
if (!((Object)(object)val == (Object)null))
{
int itemIndex = __instance.InstanceData.itemIndex;
if (RegisteredEquipmentByIndex.TryGetValue(itemIndex, out var value))
{
value.OnLost(val);
}
}
}
}
[HarmonyPatch(typeof(ItemInstance), "OnInstanceDataChange")]
internal static class ItemInstanceOnInstanceDataChangePatch
{
private static void Postfix(ItemInstance __instance)
{
//IL_0014: Unknown result type (might be due to invalid IL or missing references)
if (!((Object)(object)__instance == (Object)null) && RegisteredEquipmentByIndex.TryGetValue(__instance.InstanceData.itemIndex, out var value))
{
ApplyWorldVisuals(__instance, value);
}
}
}
[HarmonyPatch(typeof(ItemInstance), "Interact")]
internal static class ItemInstanceInteract
{
private static void Postfix(ItemInstance __instance, PlayerNetworking player)
{
//IL_0002: Unknown result type (might be due to invalid IL or missing references)
int itemIndex = __instance.InstanceData.itemIndex;
if (RegisteredEquipmentByIndex.TryGetValue(itemIndex, out var value))
{
value.OnPickup(player);
}
}
}
[HarmonyPatch(typeof(CabinetDrawer), "OnCabinetOpen")]
public static class Patch_CabinetDrawer_OnCabinetOpen
{
[HarmonyPrefix]
public static void Prefix(CabinetDrawer __instance)
{
//IL_005b: Unknown result type (might be due to invalid IL or missing references)
//IL_0060: Unknown result type (might be due to invalid IL or missing references)
//IL_0062: Unknown result type (might be due to invalid IL or missing references)
//IL_017c: Unknown result type (might be due to invalid IL or missing references)
//IL_017d: Unknown result type (might be due to invalid IL or missing references)
//IL_01c6: Unknown result type (might be due to invalid IL or missing references)
//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
//IL_01b5: Unknown result type (might be due to invalid IL or missing references)
//IL_01b7: Unknown result type (might be due to invalid IL or missing references)
//IL_01bc: Unknown result type (might be due to invalid IL or missing references)
if (!((NetworkBehaviour)__instance).IsServer)
{
return;
}
Traverse val = Traverse.Create((object)__instance);
if (val.Field("wasInit").GetValue<bool>())
{
return;
}
RoomManager instance = RoomManager.Instance;
if ((Object)(object)instance == (Object)null)
{
return;
}
Vector3 position = ((Component)__instance).transform.position;
RoomTriggerListener val2 = default(RoomTriggerListener);
if (!instance.TryGetRoomEnvelopingPoint(position, ref val2))
{
return;
}
string roomName = ((Object)((Component)val2).gameObject).name;
SpawnRectangle[] value = val.Field("spawnAreas").GetValue<SpawnRectangle[]>();
Random random = new Random();
foreach (KeyValuePair<int, Equipment> item in RegisteredEquipmentByIndex)
{
Equipment value2 = item.Value;
if (value2.SpawnChance.HasValue && value2.RoomsToSpawn != null && value2.RoomsToSpawn.Length != 0 && (value2.RoomsToSpawn.Contains(RoomsToSpawn.ALL) || value2.RoomsToSpawn.Any((RoomsToSpawn r) => roomName.Contains(r.ToString()))) && !(random.NextDouble() * 100.0 >= (double)value2.SpawnChance.Value))
{
Vector3 position2 = position;
if (value != null && value.Length != 0)
{
SpawnRectangle val3 = value[random.Next(0, value.Length)];
Vector3 randomPoint = val3.GetRandomPoint(random);
position2 = ((Component)__instance).transform.TransformPoint(randomPoint);
}
RequestSpawn(value2.Name, position2, "Spawn" + value2.Name);
}
}
}
}
public abstract class Equipment
{
public abstract string Name { get; }
public abstract string Description { get; }
public abstract EquipmentType ItemType { get; }
public virtual Sprite Icon { get; set; }
public virtual GameObject Prefab { get; set; }
public virtual int? maxDurability { get; set; }
public virtual int? maxStackSize { get; set; }
public virtual Vector3? DroppedSize { get; set; } = null;
public virtual Vector3? DroppedOffset { get; set; } = null;
public virtual RoomsToSpawn[] RoomsToSpawn { get; set; } = null;
public virtual float? SpawnChance { get; set; } = null;
public int ItemIndex { get; internal set; }
public virtual void OnEquip(GameObject visualObject, PlayerNetworking player)
{
}
public virtual void OnUnequip(PlayerNetworking player)
{
}
public virtual void OnLeftClick(bool isHolding, PlayerNetworking player)
{
}
public virtual void OnLost(PlayerNetworking player)
{
}
public virtual void OnBreak(PlayerNetworking player)
{
}
public virtual void OnDurabilityChange(float Durability, PlayerNetworking player)
{
}
public virtual void OnPickup(PlayerNetworking player)
{
}
}
public readonly struct CraftingCost
{
public readonly ResourceTypes? ResourceType;
public readonly ItemData Item;
public readonly int Amount;
private CraftingCost(ResourceTypes? resourceType, ItemData item, int amount)
{
ResourceType = resourceType;
Item = item;
Amount = amount;
}
public static implicit operator CraftingCost((ResourceTypes Resource, int Amount) tuple)
{
//IL_0002: Unknown result type (might be due to invalid IL or missing references)
return new CraftingCost(tuple.Resource, null, tuple.Amount);
}
public static implicit operator CraftingCost((ItemData Item, int Amount) tuple)
{
return new CraftingCost(null, tuple.Item, tuple.Amount);
}
}
public abstract class CraftingRecipe
{
public virtual bool TakeItemFromInventory { get; set; }
public virtual int? itemAmount { get; set; }
public abstract Equipment Equipment { get; }
public abstract CraftingCost[] CostTable { get; }
}
[HarmonyPatch(typeof(CraftinPanelControl), "UpdateCraftingPreview")]
public static class CraftinPanelControlPatch
{
private static readonly FieldInfo craftingPanelDataField = AccessTools.Field(typeof(CraftinPanelControl), "craftingPanelData");
private static readonly FieldInfo currentCraftingRecipeIndexField = AccessTools.Field(typeof(CraftinPanelControl), "currentCraftingRecipeIndex");
private static readonly FieldInfo craftingCostElementParentField = AccessTools.Field(typeof(CraftinPanelControl), "craftingCostElementParent");
private static readonly FieldInfo craftTargetInventoryField = AccessTools.Field(typeof(CraftinPanelControl), "craftTargetInventory");
[HarmonyPostfix]
public static void Postfix(CraftinPanelControl __instance)
{
//IL_0216: Unknown result type (might be due to invalid IL or missing references)
object? value = craftingPanelDataField.GetValue(__instance);
CraftingPanelData val = (CraftingPanelData)((value is CraftingPanelData) ? value : null);
if (val == null)
{
return;
}
int num = (int)currentCraftingRecipeIndexField.GetValue(__instance);
if (num < 0 || num >= val.equipmentCraftingRecipes.Count)
{
return;
}
Recipe val2 = val.equipmentCraftingRecipes[num];
ItemData itemData = default(ItemData);
ref ItemData reference = ref itemData;
CraftableItemBase craftResult = val2.CraftResult;
reference = (ItemData)(object)((craftResult is ItemData) ? craftResult : null);
if ((Object)(object)itemData == (Object)null)
{
return;
}
CraftingRecipe craftingRecipe = RegisteredRecipesList.FirstOrDefault((CraftingRecipe r) => r.Equipment != null && r.Equipment.Name.Equals(((CraftableItemBase)itemData).Name, StringComparison.OrdinalIgnoreCase));
if (craftingRecipe == null || !craftingRecipe.TakeItemFromInventory)
{
return;
}
object? value2 = craftingCostElementParentField.GetValue(__instance);
VisualElement val3 = (VisualElement)((value2 is VisualElement) ? value2 : null);
object? value3 = craftTargetInventoryField.GetValue(__instance);
InventoryBase val4 = (InventoryBase)((value3 is InventoryBase) ? value3 : null);
if (val3 == null || (Object)(object)val4 == (Object)null)
{
return;
}
HashSet<string> hashSet = new HashSet<string>(from c in craftingRecipe.CostTable
where (Object)(object)c.Item != (Object)null && !IsResourceOrDepositableCost(c)
select ((Object)c.Item).name, StringComparer.OrdinalIgnoreCase);
for (int num2 = 0; num2 < val2.cost.Length; num2++)
{
if (val2.cost[num2].amount > 0 && !((Object)(object)val2.cost[num2].item == (Object)null) && hashSet.Contains(((Object)val2.cost[num2].item).name))
{
VisualElement obj = val3[num2];
ItemDisplayView val5 = (ItemDisplayView)(object)((obj is ItemDisplayView) ? obj : null);
if (val5 != null)
{
int itemIndex = GetItemIndex(((Object)val2.cost[num2].item).name);
int num3 = CountItemInInventory(val4, itemIndex);
((VisualElement)val5).style.display = StyleEnum<DisplayStyle>.op_Implicit((DisplayStyle)0);
val5.Bind(val2.cost[num2].item, num3, val2.cost[num2].amount, "Items");
}
}
}
}
}
[HarmonyPatch(typeof(PlayerController), "UpdateInventoryCraftingContext")]
public static class UpdateInventoryCraftingContextPatch
{
[HarmonyPostfix]
public static void Postfix(CraftingPanelData craftingPanelData, Recipe recipe, InventoryBase resourceInventory, InventoryBase targetInventory)
{
ItemData itemData = default(ItemData);
ref ItemData reference = ref itemData;
CraftableItemBase craftResult = recipe.CraftResult;
reference = (ItemData)(object)((craftResult is ItemData) ? craftResult : null);
if ((Object)(object)itemData == (Object)null)
{
return;
}
CraftingRecipe craftingRecipe = RegisteredRecipesList.FirstOrDefault((CraftingRecipe r) => r.Equipment != null && r.Equipment.Name.Equals(((CraftableItemBase)itemData).Name, StringComparison.OrdinalIgnoreCase));
if (craftingRecipe == null || !craftingRecipe.TakeItemFromInventory)
{
return;
}
bool flag = true;
CraftingCost[] costTable = craftingRecipe.CostTable;
for (int num = 0; num < costTable.Length; num++)
{
CraftingCost cost = costTable[num];
int ownedCountForCost = GetOwnedCountForCost(cost, targetInventory, resourceInventory);
if (ownedCountForCost < cost.Amount)
{
flag = false;
break;
}
}
if (flag && !targetInventory.CanFitItem(itemData))
{
craftingPanelData.canCraftCurrentItem = false;
craftingPanelData.craftingInfo = "Inventory full";
}
else
{
craftingPanelData.canCraftCurrentItem = flag;
craftingPanelData.craftingInfo = (flag ? "" : "Can't afford");
}
}
}
[HarmonyPatch(typeof(CraftingRecipes), "TryCraftItem")]
public static class TryCraftItemPatch
{
[HarmonyPrefix]
public static bool Prefix(Recipe recipe, InventoryBase craftedItemTargetInventory, InventoryBase resourceSourceInventory, HomeManager homeManager, ref bool craftEvenIfMissingResources, ref bool __result, out bool __state)
{
__state = false;
if (craftEvenIfMissingResources)
{
return true;
}
ItemData itemData = default(ItemData);
ref ItemData reference = ref itemData;
CraftableItemBase craftResult = recipe.CraftResult;
reference = (ItemData)(object)((craftResult is ItemData) ? craftResult : null);
if ((Object)(object)itemData == (Object)null)
{
return true;
}
CraftingRecipe craftingRecipe = RegisteredRecipesList.FirstOrDefault((CraftingRecipe r) => r.Equipment != null && r.Equipment.Name.Equals(((CraftableItemBase)itemData).Name, StringComparison.OrdinalIgnoreCase));
if (craftingRecipe == null || !craftingRecipe.TakeItemFromInventory)
{
return true;
}
bool flag = true;
CraftingCost[] costTable = craftingRecipe.CostTable;
for (int num = 0; num < costTable.Length; num++)
{
CraftingCost cost = costTable[num];
int ownedCountForCost = GetOwnedCountForCost(cost, craftedItemTargetInventory, resourceSourceInventory);
if (ownedCountForCost < cost.Amount)
{
flag = false;
break;
}
}
if (!flag)
{
__result = false;
return false;
}
__state = true;
craftEvenIfMissingResources = true;
return true;
}
[HarmonyPostfix]
public static void Postfix(Recipe recipe, InventoryBase craftedItemTargetInventory, InventoryBase resourceSourceInventory, HomeManager homeManager, bool craftEvenIfMissingResources, ref bool __result)
{
if (!__result)
{
return;
}
ItemData itemData = default(ItemData);
ref ItemData reference = ref itemData;
CraftableItemBase craftResult = recipe.CraftResult;
reference = (ItemData)(object)((craftResult is ItemData) ? craftResult : null);
if ((Object)(object)itemData == (Object)null)
{
return;
}
CraftingRecipe craftingRecipe = RegisteredRecipesList.FirstOrDefault((CraftingRecipe r) => r.Equipment != null && r.Equipment.Name.Equals(((CraftableItemBase)itemData).Name, StringComparison.OrdinalIgnoreCase));
if (craftingRecipe == null)
{
return;
}
CraftingCost[] costTable = craftingRecipe.CostTable;
for (int num = 0; num < costTable.Length; num++)
{
CraftingCost cost = costTable[num];
if (IsResourceOrDepositableCost(cost) || (Object)(object)cost.Item == (Object)null)
{
continue;
}
string name = ((Object)cost.Item).name;
if (!craftedItemTargetInventory.TryRemoveItem(name, cost.Amount))
{
PlayerNetworking localPlayer = GetLocalPlayer();
if (localPlayer != null)
{
((InventoryBase)localPlayer.Inventory).TryRemoveItem(name, cost.Amount);
}
}
}
if (craftingRecipe.itemAmount.HasValue)
{
int num2 = craftingRecipe.itemAmount.Value - 1;
if (num2 > 0)
{
craftedItemTargetInventory.TryAddItem(craftingRecipe.Equipment.Name, num2);
}
}
}
}
private static ManualLogSource logger;
public static Dictionary<string, Equipment> RegisteredEquipment = new Dictionary<string, Equipment>();
public static Dictionary<int, Equipment> RegisteredEquipmentByIndex = new Dictionary<int, Equipment>();
private static List<Assembly> registeredAssemblies = new List<Assembly>();
private static AllItems AllItems;
private static bool isInitialized = false;
private static Dictionary<string, Sprite> _spriteCache = new Dictionary<string, Sprite>();
private static Dictionary<string, AssetBundle> _bundleCache = new Dictionary<string, AssetBundle>();
private static readonly FieldInfo RecipeItemField = AccessTools.Field(typeof(Recipe), "item");
private static string VisualRootName = "CustomItemWorldVisual";
private static bool itemRegistered = false;
private static readonly Dictionary<ulong, PlayerNetworking> playersById = new Dictionary<ulong, PlayerNetworking>();
private static PlayerNetworking localPlayer;
private static readonly Dictionary<ulong, string[]> slotItemName = new Dictionary<ulong, string[]>();
private static readonly Dictionary<ulong, GameObject[]> _slotVisual = new Dictionary<ulong, GameObject[]>();
private static readonly Dictionary<ulong, HashSet<string>> itemsEquipped = new Dictionary<ulong, HashSet<string>>();
private static readonly Dictionary<string, int> itemNameToIndex = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase);
public static Action<GameObject, string?> onItemSpawnedViaRequest = delegate
{
};
public static Action<GameObject, string?> onEnnemySpawnedViaRequest = delegate
{
};
private static readonly PlayerState playerState = new PlayerState();
private static string lastUniqueId = "";
private static readonly List<CraftingRecipe> RegisteredRecipesList = new List<CraftingRecipe>();
public static void Init(ManualLogSource source)
{
//IL_0045: Unknown result type (might be due to invalid IL or missing references)
//IL_005f: Unknown result type (might be due to invalid IL or missing references)
//IL_0064: Unknown result type (might be due to invalid IL or missing references)
logger = source;
Assembly callingAssembly = Assembly.GetCallingAssembly();
if (!registeredAssemblies.Contains(callingAssembly))
{
registeredAssemblies.Add(callingAssembly);
}
if (!isInitialized)
{
isInitialized = true;
new Harmony("ItemAPI_Core").PatchAll(typeof(ItemAPI).Assembly);
AsyncOperationHandle<LocalizationSettings> initializationOperation = LocalizationSettings.InitializationOperation;
initializationOperation.Completed += OnLocalizationInitialized;
LogInfo("ItemAPI Initialized.");
}
}
public static void ReceiveSpawnRequest(ulong senderClientId, FastBufferReader reader)
{
//IL_0036: Unknown result type (might be due to invalid IL or missing references)
if (NetworkManager.Singleton.IsServer)
{
string itemName = default(string);
((FastBufferReader)(ref reader)).ReadValueSafe(ref itemName, false);
Vector3 position = default(Vector3);
((FastBufferReader)(ref reader)).ReadValueSafe(ref position);
string uniqueId = default(string);
((FastBufferReader)(ref reader)).ReadValueSafe(ref uniqueId, false);
NetworkSpawner.ExecuteSpawn(itemName, position, uniqueId);
}
}
public static void ReceiveInventoryItemRequest(ulong senderClientId, FastBufferReader reader)
{
//IL_0025: Unknown result type (might be due to invalid IL or missing references)
//IL_002b: Unknown result type (might be due to invalid IL or missing references)
if (NetworkManager.Singleton.IsServer)
{
string itemName = default(string);
((FastBufferReader)(ref reader)).ReadValueSafe(ref itemName, false);
int count = default(int);
((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref count, default(ForPrimitives));
ExecuteGiveInventoryItem(senderClientId, itemName, count);
}
}
public unsafe static void RequestInventoryItem(string itemName, int count)
{
//IL_0065: Unknown result type (might be due to invalid IL or missing references)
//IL_006b: Unknown result type (might be due to invalid IL or missing references)
//IL_0083: Unknown result type (might be due to invalid IL or missing references)
if ((Object)(object)NetworkManager.Singleton == (Object)null)
{
return;
}
if (NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost)
{
ExecuteGiveInventoryItem(NetworkManager.Singleton.LocalClientId, itemName, count);
return;
}
FastBufferWriter val = default(FastBufferWriter);
((FastBufferWriter)(ref val))..ctor(64, (Allocator)2, -1);
try
{
((FastBufferWriter)(ref val)).WriteValueSafe(itemName, false);
((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref count, default(ForPrimitives));
NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("ModdedRequestInventoryItem", 0uL, val, (NetworkDelivery)3);
}
finally
{
((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
}
}
public static void ExecuteGiveInventoryItem(ulong clientId, string itemName, int count)
{
if (playersById.TryGetValue(clientId, out var value) && !((Object)(object)value.Inventory == (Object)null))
{
((InventoryBase)value.Inventory).TryAddItem(itemName, count);
}
}
public unsafe static void ConsumeItemDurability(int index, int amount)
{
//IL_005a: Unknown result type (might be due to invalid IL or missing references)
//IL_0060: Unknown result type (might be due to invalid IL or missing references)
//IL_006d: Unknown result type (might be due to invalid IL or missing references)
//IL_0073: Unknown result type (might be due to invalid IL or missing references)
//IL_008b: Unknown result type (might be due to invalid IL or missing references)
if ((Object)(object)NetworkManager.Singleton == (Object)null)
{
return;
}
if (NetworkManager.Singleton.IsServer || NetworkManager.Singleton.IsHost)
{
ApplyDurabilityDamage(NetworkManager.Singleton.LocalClientId, index, amount);
return;
}
FastBufferWriter val = default(FastBufferWriter);
((FastBufferWriter)(ref val))..ctor(8, (Allocator)2, -1);
try
{
((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref index, default(ForPrimitives));
((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref amount, default(ForPrimitives));
NetworkManager.Singleton.CustomMessagingManager.SendNamedMessage("RequestConsumeDurability", 0uL, val, (NetworkDelivery)3);
}
finally
{
((IDisposable)(*(FastBufferWriter*)(&val))/*cast due to .constrained prefix*/).Dispose();
}
}
private static void ReceiveDurabilityRequestOnServer(ulong senderClientId, FastBufferReader reader)
{
//IL_0007: Unknown result type (might be due to invalid IL or missing references)
//IL_000d: Unknown result type (might be due to invalid IL or missing references)
//IL_001a: Unknown result type (might be due to invalid IL or missing references)
//IL_0020: Unknown result type (might be due to invalid IL or missing references)
int index = default(int);
((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref index, default(ForPrimitives));
int amount = default(int);
((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref amount, default(ForPrimitives));
ApplyDurabilityDamage(senderClientId, index, amount);
}
public static void ApplyDurabilityDamage(ulong clientId, int index, int amount)
{
//IL_0047: Unknown result type (might be due to invalid IL or missing references)
//IL_004c: Unknown result type (might be due to invalid IL or missing references)
//IL_0089: Unknown result type (might be due to invalid IL or missing references)
//IL_008b: Unknown result type (might be due to invalid IL or missing references)
//IL_0105: Unknown result type (might be due to invalid IL or missing references)
//IL_010f: Unknown result type (might be due to invalid IL or missing references)
//IL_0111: Unknown result type (might be due to invalid IL or missing references)
//IL_00b4: Unknown result type (might be due to invalid IL or missing references)
//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
if (!playersById.TryGetValue(clientId, out var value))
{
return;
}
PlayerInventory inventory = value.Inventory;
if (((inventory != null) ? ((InventoryBase)inventory).Contents : null) == null)
{
return;
}
NetworkList<InventoryItem> contents = ((InventoryBase)value.Inventory).Contents;
for (int i = 0; i < contents.Count; i++)
{
InventoryItem val = contents[i];
if (!((InventoryItem)(ref val)).IsValidItem || ((InventoryItem)(ref val)).ItemIndex != index)
{
continue;
}
if (!RegisteredEquipmentByIndex.TryGetValue(index, out var value2))
{
break;
}
if (val.data.durability <= (float)amount)
{
if (((InventoryItem)(ref val)).ItemCount > 1)
{
InventoryItem val2 = val;
ushort itemCount = ((InventoryItem)(ref val2)).ItemCount;
((InventoryItem)(ref val2)).ItemCount = (ushort)(itemCount - 1);
contents[i] = val2;
}
else
{
contents.RemoveAt(i);
}
value2.OnBreak(value);
}
else
{
val.data.durability -= amount;
contents[i] = val;
value2.OnDurabilityChange(val.data.durability, value);
}
break;
}
}
public static void OnUpdate()
{
if (isInitialized && !((Object)(object)NetworkManager.Singleton == (Object)null) && !((Object)(object)localPlayer == (Object)null) && !((Object)(object)localPlayer.Inventory == (Object)null))
{
ProcessLocalPlayerMechanics(localPlayer);
}
}
private static void ProcessLocalPlayerMechanics(PlayerNetworking player)
{
//IL_0016: Unknown result type (might be due to invalid IL or missing references)
//IL_001b: Unknown result type (might be due to invalid IL or missing references)
//IL_007e: Unknown result type (might be due to invalid IL or missing references)
//IL_007f: Unknown result type (might be due to invalid IL or missing references)
PlayerState playerState = ItemAPI.playerState;
for (int i = 0; i < ((InventoryBase)player.Inventory).SlotCount; i++)
{
InventoryItem itemInSlot = ((InventoryBase)player.Inventory).GetItemInSlot(i);
if (((InventoryItem)(ref itemInSlot)).IsValidItem && RegisteredEquipmentByIndex.TryGetValue(((InventoryItem)(ref itemInSlot)).ItemIndex, out var value))
{
if (!playerState.InHotbar.Contains(((InventoryItem)(ref itemInSlot)).ItemIndex))
{
playerState.InHotbar.Add(((InventoryItem)(ref itemInSlot)).ItemIndex);
}
float durability = itemInSlot.data.durability;
if (playerState.TrackedItemDurability.TryGetValue(((InventoryItem)(ref itemInSlot)).ItemIndex, out var value2) && durability != value2)
{
value.OnDurabilityChange(durability, player);
}
playerState.TrackedItemDurability[((InventoryItem)(ref itemInSlot)).ItemIndex] = durability;
}
}
if (!slotItemName.TryGetValue(((NetworkBehaviour)player).OwnerClientId, out var value3) || (value3[0] == null && value3[1] == null && value3[2] == null))
{
return;
}
if (Input.GetMouseButton(0))
{
playerState.LeftClickHoldTimer += Time.deltaTime;
if (playerState.LeftClickHoldTimer >= 0.2f && !playerState.HasSentLeftHoldTrue)
{
LeftClick(isHolding: true, player, value3);
playerState.HasSentLeftHoldTrue = true;
}
}
if (Input.GetMouseButtonUp(0))
{
if (!playerState.HasSentLeftHoldTrue)
{
LeftClick(isHolding: false, player, value3);
}
playerState.LeftClickHoldTimer = 0f;
playerState.HasSentLeftHoldTrue = false;
}
}
private static void LeftClick(bool isHolding, PlayerNetworking player, string[] slots)
{
for (int i = 0; i < slots.Length; i++)
{
if (slots[i] != null && RegisteredEquipment.TryGetValue(slots[i], out var value))
{
value.OnLeftClick(isHolding, player);
}
}
}
public static bool isItemEquipped(string Name)
{
return (Object)(object)localPlayer != (Object)null && isItemEquipped(((NetworkBehaviour)localPlayer).OwnerClientId, Name);
}
public static bool isItemEquipped(ulong clientId, string Name)
{
HashSet<string> value;
return itemsEquipped.TryGetValue(clientId, out value) && value.Contains(Name);
}
public static IReadOnlyCollection<string> GetEquippedItems(ulong clientId)
{
IReadOnlyCollection<string> result;
if (!itemsEquipped.TryGetValue(clientId, out var value))
{
IReadOnlyCollection<string> readOnlyCollection = (IReadOnlyCollection<string>)(object)Array.Empty<string>();
result = readOnlyCollection;
}
else
{
IReadOnlyCollection<string> readOnlyCollection = value;
result = readOnlyCollection;
}
return result;
}
public static IReadOnlyCollection<string> GetEquippedItems()
{
IReadOnlyCollection<string> result;
if (!((Object)(object)localPlayer != (Object)null))
{
IReadOnlyCollection<string> readOnlyCollection = (IReadOnlyCollection<string>)(object)Array.Empty<string>();
result = readOnlyCollection;
}
else
{
result = GetEquippedItems(((NetworkBehaviour)localPlayer).OwnerClientId);
}
return result;
}
public static GameObject LoadGameObject(string bundleName, string prefabName)
{
if (!_bundleCache.TryGetValue(bundleName, out var value))
{
Assembly callingAssembly = Assembly.GetCallingAssembly();
using Stream stream = callingAssembly.GetManifestResourceStream(bundleName);
if (stream == null)
{
ManualLogSource obj = logger;
if (obj != null)
{
obj.LogError((object)("Could not find embedded bundle resource: " + bundleName + " in assembly " + callingAssembly.GetName().Name));
}
return null;
}
value = AssetBundle.LoadFromStream(stream);
if ((Object)(object)value == (Object)null)
{
ManualLogSource obj2 = logger;
if (obj2 != null)
{
obj2.LogError((object)("Failed to load AssetBundle from stream: " + bundleName));
}
return null;
}
_bundleCache[bundleName] = value;
}
GameObject val = value.LoadAsset<GameObject>(prefabName);
if ((Object)(object)val == (Object)null)
{
ManualLogSource obj3 = logger;
if (obj3 != null)
{
obj3.LogError((object)("Could not find prefab '" + prefabName + "' inside bundle '" + bundleName + "'"));
}
return null;
}
return val;
}
public static void LogEmbeddedResources(Assembly assembly)
{
string[] manifestResourceNames = assembly.GetManifestResourceNames();
if (manifestResourceNames.Length == 0)
{
ManualLogSource obj = logger;
if (obj != null)
{
obj.LogInfo((object)("[" + assembly.GetName().Name + "] No embedded resources found."));
}
return;
}
string[] array = manifestResourceNames;
foreach (string text in array)
{
ManualLogSource obj2 = logger;
if (obj2 != null)
{
obj2.LogInfo((object)("[" + assembly.GetName().Name + "] Embedded resource: " + text));
}
}
}
public static List<PlayerNetworking> GetAllPlayers()
{
return new List<PlayerNetworking>(playersById.Values);
}
public static PlayerNetworking GetLocalPlayer()
{
return localPlayer;
}
public static AllItems GetAllItems()
{
return AllItems ?? null;
}
public static Transform FindChildRecursive(Transform parent, string name)
{
if (((Object)parent).name == name)
{
return parent;
}
for (int i = 0; i < parent.childCount; i++)
{
Transform val = FindChildRecursive(parent.GetChild(i), name);
if ((Object)(object)val != (Object)null)
{
return val;
}
}
return null;
}
public static int GetItemIndex(string name)
{
if (string.IsNullOrEmpty(name))
{
return -1;
}
if (RegisteredEquipment.TryGetValue(name, out var value))
{
return value.ItemIndex;
}
if (itemNameToIndex.TryGetValue(name, out var value2))
{
return value2;
}
LogInfo("Equipment not found: " + name);
return -1;
}
public static ItemData GetItemData(string name)
{
return ((IEnumerable<ItemData>)AllItems.items).FirstOrDefault((Func<ItemData, bool>)((ItemData item) => ((Object)item).name.Equals(name, StringComparison.OrdinalIgnoreCase)));
}
public static InventoryItem GetItemInInventory(int index)
{
//IL_0027: Unknown result type (might be due to invalid IL or missing references)
//IL_002d: Unknown result type (might be due to invalid IL or missing references)
//IL_002e: 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_004a: Unknown result type (might be due to invalid IL or missing references)
//IL_004f: Unknown result type (might be due to invalid IL or missing references)
//IL_008b: Unknown result type (might be due to invalid IL or missing references)
//IL_0091: Unknown result type (might be due to invalid IL or missing references)
//IL_0092: 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_006f: Unknown result type (might be due to invalid IL or missing references)
PlayerNetworking obj = localPlayer;
object obj2;
if (obj == null)
{
obj2 = null;
}
else
{
PlayerInventory inventory = obj.Inventory;
obj2 = ((inventory != null) ? ((InventoryBase)inventory).Contents : null);
}
if (obj2 == null)
{
return default(InventoryItem);
}
NetworkList<InventoryItem> contents = ((InventoryBase)localPlayer.Inventory).Contents;
for (int i = 0; i < contents.Count; i++)
{
InventoryItem result = contents[i];
if (((InventoryItem)(ref result)).IsValidItem && ((InventoryItem)(ref result)).ItemIndex == index)
{
return result;
}
}
return default(InventoryItem);
}
public static bool HasItemInInventory(int index)
{
//IL_0040: Unknown result type (might be due to invalid IL or missing references)
//IL_0045: Unknown result type (might be due to invalid IL or missing references)
PlayerNetworking obj = localPlayer;
object obj2;
if (obj == null)
{
obj2 = null;
}
else
{
PlayerInventory inventory = obj.Inventory;
obj2 = ((inventory != null) ? ((InventoryBase)inventory).Contents : null);
}
if (obj2 == null)
{
return false;
}
NetworkList<InventoryItem> contents = ((InventoryBase)localPlayer.Inventory).Contents;
for (int i = 0; i < contents.Count; i++)
{
InventoryItem val = contents[i];
if (((InventoryItem)(ref val)).IsValidItem && ((InventoryItem)(ref val)).ItemIndex == index)
{
return true;
}
}
return false;
}
public static void RegisterEquipment(int index, Equipment equipment)
{
equipment.ItemIndex = index;
RegisteredEquipmentByIndex[index] = equipment;
}
public static void RequestSpawn(string itemName, Vector3 position, string? uniqueId)
{
//IL_0002: Unknown result type (might be due to invalid IL or missing references)
NetworkSpawner.RequestSpawn(itemName, position, uniqueId ?? "");
}
private static void LogInfo(string mess)
{
ManualLogSource obj = logger;
if (obj != null)
{
obj.LogInfo((object)mess);
}
}
private static void OnLocalizationInitialized(AsyncOperationHandle<LocalizationSettings> handle)
{
LoadItemsNames();
}
private static void LoadItemsNames()
{
//IL_0086: Unknown result type (might be due to invalid IL or missing references)
//IL_008c: Unknown result type (might be due to invalid IL or missing references)
//IL_0091: Unknown result type (might be due to invalid IL or missing references)
//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
List<Type> equipmentTypes = new List<Type>();
foreach (Assembly registeredAssembly in registeredAssemblies)
{
equipmentTypes.AddRange(from t in registeredAssembly.GetTypes()
where t.IsSubclassOf(typeof(Equipment)) && !t.IsAbstract
select t);
}
AsyncOperationHandle<StringTable> tableAsync = ((LocalizedDatabase<StringTable, StringTableEntry>)(object)LocalizationSettings.StringDatabase).GetTableAsync(TableReference.op_Implicit("Items"), (Locale)null);
tableAsync.Completed += delegate(AsyncOperationHandle<StringTable> handle)
{
//IL_0003: Unknown result type (might be due to invalid IL or missing references)
//IL_0009: Invalid comparison between Unknown and I4
if ((int)handle.Status != 1)
{
return;
}
StringTable result = handle.Result;
foreach (Type item in equipmentTypes)
{
Equipment equipment = (Equipment)Activator.CreateInstance(item);
((DetailedLocalizationTable<StringTableEntry>)(object)result).AddEntry(equipment.Name, equipment.Name);
}
};
AsyncOperationHandle<StringTable> tableAsync2 = ((LocalizedDatabase<StringTable, StringTableEntry>)(object)LocalizationSettings.StringDatabase).GetTableAsync(TableReference.op_Implicit("Items Descriptions"), (Locale)null);
tableAsync2.Completed += delegate(AsyncOperationHandle<StringTable> handle)
{
//IL_0003: Unknown result type (might be due to invalid IL or missing references)
//IL_0009: Invalid comparison between Unknown and I4
if ((int)handle.Status != 1)
{
return;
}
StringTable result = handle.Result;
foreach (Type item2 in equipmentTypes)
{
Equipment equipment = (Equipment)Activator.CreateInstance(item2);
((DetailedLocalizationTable<StringTableEntry>)(object)result).AddEntry(equipment.Description, equipment.Description);
}
};
}
private static void RebuildItemNameIndex()
{
itemNameToIndex.Clear();
if (AllItems?.items == null)
{
return;
}
for (int i = 0; i < AllItems.items.Length; i++)
{
if ((Object)(object)AllItems.items[i] != (Object)null)
{
itemNameToIndex[((Object)AllItems.items[i]).name] = i;
}
}
}
private static void ApplyWorldVisuals(ItemInstance itemInstance, Equipment equipment)
{
//IL_0132: Unknown result type (might be due to invalid IL or missing references)
//IL_0121: Unknown result type (might be due to invalid IL or missing references)
//IL_0062: Unknown result type (might be due to invalid IL or missing references)
//IL_0051: Unknown result type (might be due to invalid IL or missing references)
//IL_0160: Unknown result type (might be due to invalid IL or missing references)
//IL_014f: Unknown result type (might be due to invalid IL or missing references)
//IL_0090: Unknown result type (might be due to invalid IL or missing references)
//IL_007f: Unknown result type (might be due to invalid IL or missing references)
//IL_016c: Unknown result type (might be due to invalid IL or missing references)
if ((Object)(object)equipment.Prefab == (Object)null)
{
return;
}
Transform transform = ((Component)itemInstance).transform;
Transform val = FindExistingVisual(transform);
HideDefaultVisualsAndColliders(transform, val);
if ((Object)(object)val != (Object)null)
{
val.localScale = (equipment.DroppedSize.HasValue ? equipment.DroppedSize.Value : Vector3.one);
val.localPosition = (equipment.DroppedOffset.HasValue ? equipment.DroppedOffset.Value : Vector3.zero);
if (!equipment.DroppedSize.HasValue && !equipment.DroppedOffset.HasValue)
{
SetupVisualTransform(val);
}
EnableColliders(val);
return;
}
GameObject val2 = Object.Instantiate<GameObject>(equipment.Prefab, transform, false);
((Object)val2).name = VisualRootName;
SetLayerRecursively(val2, ((Component)transform).gameObject.layer);
Transform transform2 = val2.transform;
transform2.localScale = (equipment.DroppedSize.HasValue ? equipment.DroppedSize.Value : Vector3.one);
transform2.localPosition = (equipment.DroppedOffset.HasValue ? equipment.DroppedOffset.Value : Vector3.zero);
transform2.localRotation = Quaternion.identity;
if (!equipment.DroppedSize.HasValue && !equipment.DroppedOffset.HasValue)
{
SetupVisualTransform(transform2);
}
EnableColliders(transform2);
}
private static void SetLayerRecursively(GameObject obj, int layer)
{
//IL_001e: Unknown result type (might be due to invalid IL or missing references)
//IL_0024: Expected O, but got Unknown
obj.layer = layer;
foreach (Transform item in obj.transform)
{
Transform val = item;
SetLayerRecursively(((Component)val).gameObject, layer);
}
}
private static void HideDefaultVisualsAndColliders(Transform root, Transform existingVisual)
{
Renderer[] componentsInChildren = ((Component)root).GetComponentsInChildren<Renderer>(true);
foreach (Renderer val in componentsInChildren)
{
if (!((Object)(object)val == (Object)null) && !IsInsideVisual(((Component)val).transform, existingVisual))
{
val.enabled = false;
}
}
Collider[] componentsInChildren2 = ((Component)root).GetComponentsInChildren<Collider>(true);
foreach (Collider val2 in componentsInChildren2)
{
if (!((Object)(object)val2 == (Object)null) && !IsInsideVisual(((Component)val2).transform, existingVisual))
{
val2.enabled = false;
}
}
}
private static void EnableColliders(Transform visual)
{
Collider[] componentsInChildren = ((Component)visual).GetComponentsInChildren<Collider>(true);
if (componentsInChildren.Length != 0)
{
for (int i = 0; i < componentsInChildren.Length; i++)
{
componentsInChildren[i].enabled = true;
}
}
else
{
AddBoxCollider(visual);
}
}
private static void AddBoxCollider(Transform visual)
{
//IL_0043: Unknown result type (might be due to invalid IL or missing references)
//IL_0048: Unknown result type (might be due to invalid IL or missing references)
//IL_0055: Unknown result type (might be due to invalid IL or missing references)
//IL_0077: Unknown result type (might be due to invalid IL or missing references)
//IL_007c: Unknown result type (might be due to invalid IL or missing references)
//IL_0081: Unknown result type (might be due to invalid IL or missing references)
//IL_0085: Unknown result type (might be due to invalid IL or missing references)
//IL_008a: Unknown result type (might be due to invalid IL or missing references)
//IL_008f: Unknown result type (might be due to invalid IL or missing references)
//IL_0092: Unknown result type (might be due to invalid IL or missing references)
//IL_009d: Unknown result type (might be due to invalid IL or missing references)
//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
Renderer[] componentsInChildren = ((Component)visual).GetComponentsInChildren<Renderer>(true);
if (componentsInChildren.Length == 0)
{
ManualLogSource obj = logger;
if (obj != null)
{
obj.LogWarning((object)("No renderers found under '" + ((Object)visual).name + "' to generate a collider from."));
}
return;
}
Bounds bounds = componentsInChildren[0].bounds;
for (int i = 1; i < componentsInChildren.Length; i++)
{
((Bounds)(ref bounds)).Encapsulate(componentsInChildren[i].bounds);
}
Vector3 center = visual.InverseTransformPoint(((Bounds)(ref bounds)).center);
Vector3 val = visual.InverseTransformVector(((Bounds)(ref bounds)).size);
((Vector3)(ref val))..ctor(Mathf.Abs(val.x), Mathf.Abs(val.y), Mathf.Abs(val.z));
BoxCollider val2 = ((Component)visual).gameObject.AddComponent<BoxCollider>();
val2.center = center;
val2.size = val;
}
private static void SetupVisualTransform(Transform visual)
{
//IL_0002: Unknown result type (might be due to invalid IL or missing references)
//IL_000e: Unknown result type (might be due to invalid IL or missing references)
//IL_001a: Unknown result type (might be due to invalid IL or missing references)
visual.localPosition = Vector3.zero;
visual.localRotation = Quaternion.identity;
visual.localScale = Vector3.one;
}
private static bool IsInsideVisual(Transform candidate, Transform existingVisual)
{
if ((Object)(object)existingVisual == (Object)null)
{
return false;
}
return (Object)(object)candidate == (Object)(object)existingVisual || candidate.IsChildOf(existingVisual);
}
private static Transform FindExistingVisual(Transform root)
{
Transform[] componentsInChildren = ((Component)root).GetComponentsInChildren<Transform>(true);
for (int i = 0; i < componentsInChildren.Length; i++)
{
if ((Object)(object)componentsInChildren[i] != (Object)(object)root && ((Object)componentsInChildren[i]).name == VisualRootName)
{
return componentsInChildren[i];
}
}
return null;
}
private static ItemData CreateItem(string name, string description, Sprite icon, EquipmentType itemType, int? maxDura, int? maxStackSize, GameObject prefab, AllItems allItems)
{
//IL_002e: Unknown result type (might be due to invalid IL or missing references)
//IL_0034: Unknown result type (might be due to invalid IL or missing references)
//IL_0039: Unknown result type (might be due to invalid IL or missing references)
//IL_0043: Expected O, but got Unknown
//IL_0049: Unknown result type (might be due to invalid IL or missing references)
//IL_004f: Unknown result type (might be due to invalid IL or missing references)
//IL_0054: Unknown result type (might be due to invalid IL or missing references)
//IL_005e: Expected O, but got Unknown
//IL_0066: 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_007c: 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)
ItemData val = ScriptableObject.CreateInstance<ItemData>();
((Object)val).name = name;
((CraftableItemBase)val).icon = icon ?? ((CraftableItemBase)allItems.items[0]).icon;
((CraftableItemBase)val).localizedName = new LocalizedString(TableReference.op_Implicit("Items"), TableEntryReference.op_Implicit(name));
((CraftableItemBase)val).localizedDesc = new LocalizedString(TableReference.op_Implicit("Items Descriptions"), TableEntryReference.op_Implicit(description));
val.description = description;
val.equipmentType = itemType;
val.maxStackSize = maxStackSize ?? 1;
val.usageType = (UsageType)0;
val.durabilityLoss = (EquipmentDurabilityLossType)2;
val.maxDurability = maxDura ?? 100;
val.prefab = allItems.defaultPrefab;
val.dontAllowEquipTogetherWith = (ItemData[])(object)new ItemData[0];
((Object)val).hideFlags = (HideFlags)32;
return val;
}
private static void RegisterItems(AllItems allItems)
{
//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
List<Type> list = new List<Type>();
foreach (Assembly registeredAssembly in registeredAssemblies)
{
list.AddRange(from t in registeredAssembly.GetTypes()
where t.IsSubclassOf(typeof(Equipment)) && !t.IsAbstract
select t);
}
List<ItemData> list2 = new List<ItemData>();
Dictionary<ItemData, Equipment> dictionary = new Dictionary<ItemData, Equipment>();
foreach (Type item in list)
{
Equipment equipment = (Equipment)Activator.CreateInstance(item);
if (!((Object)(object)FindExisting(allItems, equipment.Name) != (Object)null))
{
ItemData val = CreateItem(equipment.Name, equipment.Description, equipment.Icon, equipment.ItemType, equipment.maxDurability, equipment.maxStackSize, equipment.Prefab, allItems);
list2.Add(val);
dictionary.Add(val, equipment);
if (!RegisteredEquipment.ContainsKey(equipment.Name))
{
RegisteredEquipment.Add(equipment.Name, equipment);
}
}
}
if (list2.Count <= 0)
{
return;
}
int num = allItems.items.Length;
Array.Resize(ref allItems.items, num + list2.Count);
for (int num2 = 0; num2 < list2.Count; num2++)
{
int num3 = num + num2;
allItems.items[num3] = list2[num2];
if (dictionary.TryGetValue(list2[num2], out var value) && !RegisteredEquipmentByIndex.ContainsKey(num3))
{
RegisterEquipment(num3, value);
}
LogInfo("Registered item: " + ((Object)list2[num2]).name + " Item Index: " + num3);
}
itemRegistered = true;
}
private static ItemData FindExisting(AllItems allItems, string itemName)
{
ItemData[] items = allItems.items;
foreach (ItemData val in items)
{
if ((Object)(object)val != (Object)null && ((Object)val).name == itemName)
{
return val;
}
}
return null;
}
public static Sprite LoadSpriteFromEmbedded(string resourcePath)
{
return LoadSpriteFromEmbedded(resourcePath, Assembly.GetCallingAssembly());
}
public static Sprite LoadSpriteFromEmbedded(string resourcePath, Assembly assembly)
{
//IL_007e: Unknown result type (might be due to invalid IL or missing references)
//IL_0085: Expected O, but got Unknown
//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
if (_spriteCache.TryGetValue(resourcePath, out var value))
{
return value;
}
using Stream stream = assembly.GetManifestResourceStream(resourcePath);
if (stream == null)
{
ManualLogSource obj = logger;
if (obj != null)
{
obj.LogError((object)("Could not find embedded resource: " + resourcePath + " in assembly " + assembly.GetName().Name));
}
return null;
}
byte[] array = new byte[stream.Length];
stream.Read(array, 0, array.Length);
Texture2D val = new Texture2D(2, 2);
ImageConversion.LoadImage(val, array);
Sprite val2 = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), 100f);
_spriteCache[resourcePath] = val2;
return val2;
}
public static void AddRecipe(CraftingRecipe recipe)
{
if (recipe != null && !RegisteredRecipesList.Contains(recipe))
{
RegisteredRecipesList.Add(recipe);
}
}
private static bool HasRecipe(CraftingRecipes recipes, ItemData result)
{
Recipe[] recipes2 = recipes.recipes;
foreach (Recipe val in recipes2)
{
if (val != null && (Object)(object)val.CraftResult == (Object)(object)result)
{
return true;
}
}
return false;
}
private static int CountItemInInventory(InventoryBase inventory, int itemIndex)
{
//IL_0014: Unknown result type (might be due to invalid IL or missing references)
//IL_0019: Unknown result type (might be due to invalid IL or missing references)
//IL_0024: 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)
int num = 0;
foreach (InventoryItem inventoryItem in inventory.GetInventoryItems())
{
InventoryItem current = inventoryItem;
if (((InventoryItem)(ref current)).IsValidItem && current.data.itemIndex == itemIndex)
{
num += ((InventoryItem)(ref current)).ItemCount;
}
}
return num;
}
private static bool IsResourceOrDepositableCost(CraftingCost cost)
{
if (cost.ResourceType.HasValue)
{
return true;
}
if ((Object)(object)cost.Item != (Object)null && ((Object)cost.Item).name.Equals("Gnomium", StringComparison.OrdinalIgnoreCase))
{
return true;
}
return false;
}
private static int GetOwnedCountForCost(CraftingCost cost, InventoryBase targetInventory, InventoryBase resourceInventory)
{
//IL_0019: Unknown result type (might be due to invalid IL or missing references)
//IL_0023: Expected I4, but got Unknown
if (cost.ResourceType.HasValue)
{
string resourceName = ResourceStorage.GetResourceName((int)cost.ResourceType.Value);
return resourceInventory.GetItemCount(resourceName);
}
if ((Object)(object)cost.Item == (Object)null)
{
return 0;
}
if (((Object)cost.Item).name.Equals("Gnomium", StringComparison.OrdinalIgnoreCase))
{
return resourceInventory.GetItemCount(((Object)cost.Item).name);
}
int itemIndex = GetItemIndex(((Object)cost.Item).name);
return CountItemInInventory(targetInventory, itemIndex);
}
private static IEnumerator RegisterRecipesCoroutine(GnomiumDeposit gnomiumDeposit)
{
while (!itemRegistered)
{
yield return (object)new WaitForEndOfFrame();
}
if ((Object)(object)gnomiumDeposit == (Object)null || (Object)(object)gnomiumDeposit.Recipes == (Object)null || (Object)(object)gnomiumDeposit.ResourceInventory == (Object)null)
{
yield break;
}
foreach (Assembly assembly in registeredAssemblies)
{
IEnumerable<Type> recipeTypes = from t in assembly.GetTypes()
where t.IsSubclassOf(typeof(CraftingRecipe)) && !t.IsAbstract
select t;
foreach (Type type in recipeTypes)
{
if (!RegisteredRecipesList.Any((CraftingRecipe r) => r.GetType() == type))
{
CraftingRecipe recipeInstance = (CraftingRecipe)Activator.CreateInstance(type);
RegisteredRecipesList.Add(recipeInstance);
}
}
}
int num2 = default(int);
foreach (CraftingRecipe customRecipe in RegisteredRecipesList)
{
if (customRecipe.Equipment == null)
{
continue;
}
ItemData resultItem = FindExisting(gnomiumDeposit.ResourceInventory.BoundItems, customRecipe.Equipment.Name);
if ((Object)(object)resultItem == (Object)null || HasRecipe(gnomiumDeposit.Recipes, resultItem))
{
continue;
}
List<ItemCost> costs = new List<ItemCost>();
CraftingCost[] costTable = customRecipe.CostTable;
for (int num = 0; num < costTable.Length; num++)
{
CraftingCost costEntry = costTable[num];
ItemData ingredientItem;
if (costEntry.ResourceType.HasValue)
{
string resourceName = ResourceStorage.GetResourceName((int)costEntry.ResourceType.Value);
ingredientItem = gnomiumDeposit.ResourceInventory.BoundItems.GetItem(resourceName, ref num2);
}
else
{
ingredientItem = costEntry.Item;
}
if ((Object)(object)ingredientItem != (Object)null)
{
costs.Add(new ItemCost
{
item = ingredientItem,
amount = costEntry.Amount
});
}
else
{
LogInfo("Could not resolve cost ingredient for recipe: " + customRecipe.Equipment.Name);
}
}
if (costs.Count != 0)
{
Recipe recipe = new Recipe
{
craftResultType = (CraftResultType)0,
cost = costs.ToArray()
};
RecipeItemField?.SetValue(recipe, resultItem);
Array.Resize(ref gnomiumDeposit.Recipes.recipes, gnomiumDeposit.Recipes.recipes.Length + 1);
gnomiumDeposit.Recipes.recipes[gnomiumDeposit.Recipes.recipes.Length - 1] = recipe;
LogInfo("Registered custom recipe for item: " + customRecipe.Equipment.Name);
}
}
}
}
public static class MyPluginInfo
{
public const string PLUGIN_GUID = "ItemAPI";
public const string PLUGIN_NAME = "ItemAPI";
public const string PLUGIN_VERSION = "1.0.0";
}
}