Decompiled source of SkinnedRendererPatch v1.1.3

DarthLilo.SkinnedRendererPatch.dll

Decompiled 2 weeks ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Logging;
using DarthLilo.SkinnedRendererPatch.NetcodePatcher;
using HarmonyLib;
using JetBrains.Annotations;
using LilosScrapExtension.Scripts;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using SkinnedRendererPatch.Helpers;
using SkinnedRendererPatch.ModCompatability;
using SkinnedRendererPatch.Patches;
using Unity.Netcode;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("DarthLilo.SkinnedRendererPatch")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.1.3.0")]
[assembly: AssemblyInformationalVersion("1.1.3+6612e91fba934d891e92b476bd9d10c7abec11f2")]
[assembly: AssemblyProduct("SkinnedRendererPatch")]
[assembly: AssemblyTitle("DarthLilo.SkinnedRendererPatch")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.3.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
internal class <Module>
{
	static <Module>()
	{
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace SkinnedRendererPatch
{
	[BepInPlugin("DarthLilo.SkinnedRendererPatch", "SkinnedRendererPatch", "1.1.3")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class SkinnedRendererPatch : BaseUnityPlugin
	{
		public static bool LilosScrapExtensionPresent;

		public static SkinnedRendererPatch Instance { get; private set; }

		internal static ManualLogSource Logger { get; private set; }

		internal static Harmony? Harmony { get; set; }

		private void Awake()
		{
			Logger = ((BaseUnityPlugin)this).Logger;
			Instance = this;
			Logger.LogInfo((object)"DarthLilo.SkinnedRendererPatch has started, patching gamecode");
			LilosScrapExtensionPresent = IsPluginInstalled("DarthLilo.LilosScrapExtension");
			Patch();
			Logger.LogInfo((object)"Running netcode patchers");
			Type[] types = Assembly.GetExecutingAssembly().GetTypes();
			Type[] array = types;
			foreach (Type type in array)
			{
				MethodInfo[] methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.NonPublic);
				MethodInfo[] array2 = methods;
				foreach (MethodInfo methodInfo in array2)
				{
					object[] customAttributes = methodInfo.GetCustomAttributes(typeof(RuntimeInitializeOnLoadMethodAttribute), inherit: false);
					if (customAttributes.Length != 0)
					{
						methodInfo.Invoke(null, null);
					}
				}
			}
			Logger.LogInfo((object)"DarthLilo.SkinnedRendererPatch v1.1.3 has loaded!");
			Logger.LogInfo((object)"If you see errors relating to objects not containing a grabbable object during level loading, these are safe to ignore and won't affect gameplay");
		}

		private static bool IsPluginInstalled(string targetPlugin)
		{
			return Chainloader.PluginInfos.ContainsKey(targetPlugin);
		}

		internal static void Patch()
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			if (Harmony == null)
			{
				Harmony = new Harmony("DarthLilo.SkinnedRendererPatch");
			}
			Logger.LogDebug((object)"Patching...");
			Harmony.PatchAll();
			Logger.LogDebug((object)"Finished patching!");
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "DarthLilo.SkinnedRendererPatch";

		public const string PLUGIN_NAME = "SkinnedRendererPatch";

		public const string PLUGIN_VERSION = "1.1.3";
	}
}
namespace SkinnedRendererPatch.Patches
{
	[HarmonyPatch(typeof(GameNetworkManager))]
	public class GameNetworkManagerPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void StartPatch(GameNetworkManager __instance)
		{
			((Component)__instance).gameObject.AddComponent<SRPNetworkHelper>();
			((Component)__instance).gameObject.AddComponent<NetworkObject>();
			SkinnedRendererPatch.Logger.LogInfo((object)"Network Helper Added!");
		}
	}
	[HarmonyPatch(typeof(StartOfRound))]
	public class ItemStateLoading
	{
		public static class HierarchicalSorting
		{
			private sealed class RelayComparer<T> : Comparer<T>
			{
				[NotNull]
				private Func<T, T, int> Func { get; }

				public RelayComparer([NotNull] Func<T, T, int> func)
				{
					Func = func ?? throw new ArgumentNullException("func");
				}

				public override int Compare(T x, T y)
				{
					return Func(x, y);
				}
			}

			private static int Compare([CanBeNull] Component x, [CanBeNull] Component y)
			{
				return Compare(((Object)(object)x != (Object)null) ? x.transform : null, ((Object)(object)y != (Object)null) ? y.transform : null);
			}

			private static int Compare([CanBeNull] GameObject x, [CanBeNull] GameObject y)
			{
				return Compare(((Object)(object)x != (Object)null) ? x.transform : null, ((Object)(object)y != (Object)null) ? y.transform : null);
			}

			private static int Compare([CanBeNull] Transform x, [CanBeNull] Transform y)
			{
				if ((Object)(object)x == (Object)null && (Object)(object)y == (Object)null)
				{
					return 0;
				}
				if ((Object)(object)x == (Object)null)
				{
					return -1;
				}
				if ((Object)(object)y == (Object)null)
				{
					return 1;
				}
				Stack<int> hierarchy = GetHierarchy(x);
				Stack<int> hierarchy2 = GetHierarchy(y);
				int num2;
				do
				{
					if (!hierarchy.Any())
					{
						return -1;
					}
					int num = hierarchy.Pop();
					if (!hierarchy2.Any())
					{
						return 1;
					}
					int value = hierarchy2.Pop();
					num2 = num.CompareTo(value);
				}
				while (num2 == 0);
				return num2;
			}

			[NotNull]
			private static Stack<int> GetHierarchy([NotNull] Transform transform)
			{
				if ((Object)(object)transform == (Object)null)
				{
					throw new ArgumentNullException("transform");
				}
				Stack<int> stack = new Stack<int>();
				Transform val = transform;
				while ((Object)(object)val != (Object)null)
				{
					int siblingIndex = val.GetSiblingIndex();
					stack.Push(siblingIndex);
					val = val.parent;
				}
				return stack;
			}

			[PublicAPI]
			[NotNull]
			[ItemNotNull]
			public static T[] Sort<T>([NotNull][ItemNotNull] T[] components) where T : Component
			{
				if (components == null)
				{
					throw new ArgumentNullException("components");
				}
				Array.Sort(components, new RelayComparer<T>(Compare));
				return components;
			}

			[PublicAPI]
			[NotNull]
			[ItemNotNull]
			public static GameObject[] Sort([NotNull][ItemNotNull] GameObject[] gameObjects)
			{
				if (gameObjects == null)
				{
					throw new ArgumentNullException("gameObjects");
				}
				Array.Sort(gameObjects, new RelayComparer<GameObject>(Compare));
				return gameObjects;
			}

			[PublicAPI]
			[NotNull]
			[ItemNotNull]
			public static Transform[] Sort([NotNull][ItemNotNull] Transform[] transforms)
			{
				if (transforms == null)
				{
					throw new ArgumentNullException("transforms");
				}
				Array.Sort(transforms, new RelayComparer<Transform>(Compare));
				return transforms;
			}
		}

		public static ClientRpcParams clientParamData;

		public static Dictionary<ulong, int> MeshIndexesDICT = new Dictionary<ulong, int>();

		public static Dictionary<ulong, int> MatIndexesDICT = new Dictionary<ulong, int>();

		public static Dictionary<ulong, bool> LSEAIndexesDICT = new Dictionary<ulong, bool>();

		[HarmonyPatch("LoadShipGrabbableItems")]
		[HarmonyPostfix]
		public static void LoadItemState(StartOfRound __instance)
		{
			DetermineItemStatesOnSaveData();
		}

		[HarmonyPatch("OnClientConnect")]
		[HarmonyPrefix]
		public static void OnClientConnectPatch(StartOfRound __instance, ulong clientId)
		{
			//IL_0024: 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_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			if (((NetworkBehaviour)__instance).IsServer && (Object)(object)SRPNetworkHelper.Instance != (Object)null)
			{
				ClientRpcParams val = default(ClientRpcParams);
				val.Send = new ClientRpcSendParams
				{
					TargetClientIds = new ulong[1] { clientId }
				};
				clientParamData = val;
				SkinnedRendererPatch.Logger.LogInfo((object)"Syncing Item State Data");
				SRPNetworkHelper.Instance.SyncItemDataClientRpc(JsonConvert.SerializeObject((object)MeshIndexesDICT) ?? "", JsonConvert.SerializeObject((object)MatIndexesDICT) ?? "", JsonConvert.SerializeObject((object)LSEAIndexesDICT) ?? "", clientParamData);
			}
		}

		public static void DetermineItemStatesOnSaveData()
		{
			SkinnedRendererPatch.Logger.LogInfo((object)"Started item syncing");
			if (!ES3.KeyExists("shipGrabbableItemIDs", GameNetworkManager.Instance.currentSaveFileName))
			{
				return;
			}
			bool flag = ES3.KeyExists("shipGrabbableMeshIndexes", GameNetworkManager.Instance.currentSaveFileName);
			bool flag2 = ES3.KeyExists("shipGrabbableMaterialIndexes", GameNetworkManager.Instance.currentSaveFileName);
			bool flag3 = ES3.KeyExists("lilosScrapExtensionTriggered", GameNetworkManager.Instance.currentSaveFileName);
			GrabbableObject[] components = Object.FindObjectsByType<GrabbableObject>((FindObjectsInactive)0, (FindObjectsSortMode)0);
			int[] array = null;
			int[] array2 = null;
			bool[] array3 = null;
			if (flag)
			{
				array = ES3.Load<int[]>("shipGrabbableMeshIndexes", GameNetworkManager.Instance.currentSaveFileName);
			}
			if (flag2)
			{
				array2 = ES3.Load<int[]>("shipGrabbableMaterialIndexes", GameNetworkManager.Instance.currentSaveFileName);
			}
			if (SkinnedRendererPatch.LilosScrapExtensionPresent && flag3)
			{
				array3 = ES3.Load<bool[]>("lilosScrapExtensionTriggered", GameNetworkManager.Instance.currentSaveFileName);
			}
			int num = 0;
			int num2 = 0;
			int num3 = 0;
			GrabbableObject[] array4 = HierarchicalSorting.Sort<GrabbableObject>(components);
			MeshIndexesDICT.Clear();
			MatIndexesDICT.Clear();
			LSEAIndexesDICT.Clear();
			SkinnedRendererPatch.Logger.LogInfo((object)"Beginning heiracrhy search");
			for (int i = 0; i < array4.Length; i++)
			{
				GrabbableObject val = array4[i];
				if (!array4[i].itemProperties.isScrap)
				{
					continue;
				}
				try
				{
					if (array != null && array.Length != 0)
					{
						if (array[num] != -1)
						{
							MeshIndexesDICT.Add(((Component)val).gameObject.GetComponent<NetworkObject>().NetworkObjectId, array[num]);
							MeshFilter component = ((Component)val).gameObject.GetComponent<MeshFilter>();
							if ((Object)(object)component != (Object)null)
							{
								component.mesh = val.itemProperties.meshVariants[array[num]];
							}
							foreach (GameObject skinnedChild in ItemStateSaving.GetSkinnedChildren(((Component)val).gameObject.transform))
							{
								skinnedChild.GetComponent<SkinnedMeshRenderer>().sharedMesh = val.itemProperties.meshVariants[array[num]];
							}
						}
						num++;
					}
				}
				catch (Exception ex)
				{
					SkinnedRendererPatch.Logger.LogError((object)("Error when updating item states, most likely due to a removed mod! " + ex));
				}
				try
				{
					if (array2 != null && array2.Length != 0)
					{
						if (array2[num2] != -1)
						{
							MatIndexesDICT.Add(((Component)val).gameObject.GetComponent<NetworkObject>().NetworkObjectId, array2[num2]);
							MeshRenderer component2 = ((Component)val).gameObject.GetComponent<MeshRenderer>();
							if ((Object)(object)component2 != (Object)null)
							{
								((Renderer)component2).sharedMaterial = val.itemProperties.materialVariants[array2[num2]];
							}
							foreach (GameObject skinnedChild2 in ItemStateSaving.GetSkinnedChildren(((Component)val).gameObject.transform))
							{
								((Renderer)skinnedChild2.GetComponent<SkinnedMeshRenderer>()).sharedMaterial = val.itemProperties.materialVariants[array2[num2]];
							}
						}
						num2++;
					}
				}
				catch (Exception ex2)
				{
					SkinnedRendererPatch.Logger.LogError((object)("Error when updating item states, most likely due to a removed mod! " + ex2));
				}
				if (SkinnedRendererPatch.LilosScrapExtensionPresent && array3 != null && array3.Length != 0)
				{
					if (array3[num3])
					{
						LSEAIndexesDICT.Add(((Component)val).gameObject.GetComponent<NetworkObject>().NetworkObjectId, array3[num3]);
						LilosScrapExtensionCompat.ApplyCustomLSEAData(val, array3[num3]);
					}
					num3++;
				}
			}
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager))]
	public class ItemStateSaving
	{
		[HarmonyPatch("SaveItemsInShip")]
		[HarmonyPrefix]
		public static void SaveItemState(GameNetworkManager __instance)
		{
			GrabbableObject[] array = Object.FindObjectsByType<GrabbableObject>((FindObjectsInactive)0, (FindObjectsSortMode)0);
			if (array == null || StartOfRound.Instance.isChallengeFile)
			{
				return;
			}
			List<int> list = new List<int>();
			List<int> list2 = new List<int>();
			List<int> list3 = new List<int>();
			List<bool> list4 = new List<bool>();
			for (int i = 0; i < array.Length && i <= StartOfRound.Instance.maxShipItemCapacity; i++)
			{
				if (!StartOfRound.Instance.allItemsList.itemsList.Contains(array[i].itemProperties) || array[i].deactivated)
				{
					continue;
				}
				if ((Object)(object)array[i].itemProperties.spawnPrefab == (Object)null)
				{
					SkinnedRendererPatch.Logger.LogDebug((object)(((Object)array[i].itemProperties).name + " has no spawn prefab set, please fix this!"));
				}
				else
				{
					if (array[i].itemUsedUp)
					{
						continue;
					}
					for (int j = 0; j < StartOfRound.Instance.allItemsList.itemsList.Count; j++)
					{
						if (!((Object)(object)StartOfRound.Instance.allItemsList.itemsList[j] == (Object)(object)array[i].itemProperties))
						{
							continue;
						}
						list.Add(j);
						MeshFilter component = ((Component)array[i]).gameObject.GetComponent<MeshFilter>();
						MeshRenderer component2 = ((Component)array[i]).gameObject.GetComponent<MeshRenderer>();
						int item = -1;
						int item2 = -1;
						if (array[i].itemProperties.meshVariants.Length != 0)
						{
							if ((Object)(object)component != (Object)null)
							{
								item = Array.IndexOf(array[i].itemProperties.meshVariants, component.mesh);
							}
							foreach (GameObject skinnedChild in GetSkinnedChildren(((Component)array[i]).gameObject.transform))
							{
								item = Array.IndexOf(array[i].itemProperties.meshVariants, skinnedChild.GetComponent<SkinnedMeshRenderer>().sharedMesh);
							}
							list2.Add(item);
						}
						else
						{
							list2.Add(item);
						}
						if (array[i].itemProperties.materialVariants.Length != 0)
						{
							if ((Object)(object)component2 != (Object)null)
							{
								item2 = Array.IndexOf(array[i].itemProperties.materialVariants, ((Renderer)component2).sharedMaterial);
							}
							foreach (GameObject skinnedChild2 in GetSkinnedChildren(((Component)array[i]).gameObject.transform))
							{
								item2 = Array.IndexOf(array[i].itemProperties.materialVariants, ((Renderer)skinnedChild2.GetComponent<SkinnedMeshRenderer>()).sharedMaterial);
							}
							list3.Add(item2);
						}
						else
						{
							list3.Add(item2);
						}
						if (SkinnedRendererPatch.LilosScrapExtensionPresent)
						{
							list4.Add(LilosScrapExtensionCompat.DetermineTriggered(array[i]));
						}
						break;
					}
				}
			}
			ES3.Save<int[]>("shipGrabbableMeshIndexes", list2.ToArray(), __instance.currentSaveFileName);
			ES3.Save<int[]>("shipGrabbableMaterialIndexes", list3.ToArray(), __instance.currentSaveFileName);
			if (SkinnedRendererPatch.LilosScrapExtensionPresent)
			{
				ES3.Save<bool[]>("lilosScrapExtensionTriggered", list4.ToArray(), __instance.currentSaveFileName);
			}
			else if (ES3.KeyExists("lilosScrapExtensionTriggered", __instance.currentSaveFileName))
			{
				ES3.DeleteKey("lilosScrapExtensionTriggered", __instance.currentSaveFileName);
			}
		}

		public static List<GameObject> GetSkinnedChildren(Transform itemTransform)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Expected O, but got Unknown
			List<GameObject> list = new List<GameObject>();
			foreach (Transform item in itemTransform)
			{
				Transform val = item;
				if (Object.op_Implicit((Object)(object)((Component)val).gameObject.GetComponent<SkinnedMeshRenderer>()) && !Object.op_Implicit((Object)(object)((Component)val).gameObject.GetComponent<ScanNodeProperties>()) && !list.Contains(((Component)val).gameObject))
				{
					list.Add(((Component)val).gameObject);
				}
			}
			return list;
		}
	}
	[HarmonyPatch(typeof(RoundManager))]
	[HarmonyPatch("SyncScrapValuesClientRpc")]
	public class MeshRendererPatch
	{
		public static bool Prefix(RoundManager __instance, ref NetworkObjectReference[] spawnedScrap)
		{
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Expected O, but got Unknown
			//IL_02bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c6: Expected O, but got Unknown
			Random random = new Random(StartOfRound.Instance.randomMapSeed + 210);
			NetworkObject val = default(NetworkObject);
			for (int i = 0; i < spawnedScrap.Length; i++)
			{
				if (!((NetworkObjectReference)(ref spawnedScrap[i])).TryGet(ref val, (NetworkManager)null))
				{
					continue;
				}
				GrabbableObject component = ((Component)val).GetComponent<GrabbableObject>();
				if (!((Object)(object)component != (Object)null))
				{
					continue;
				}
				try
				{
					if (component.itemProperties.meshVariants.Length != 0)
					{
						MeshFilter component2 = ((Component)component).gameObject.GetComponent<MeshFilter>();
						if ((Object)(object)component2 != (Object)null)
						{
							((Component)component).gameObject.GetComponent<MeshFilter>().mesh = component.itemProperties.meshVariants[random.Next(0, component.itemProperties.meshVariants.Length)];
							SkinnedRendererPatch.Logger.LogDebug((object)("Changed " + ((Object)((Component)component).gameObject).name + " material using MeshRenderer"));
						}
						List<GameObject> list = new List<GameObject>();
						foreach (Transform item in ((Component)component).gameObject.transform)
						{
							Transform val2 = item;
							if (Object.op_Implicit((Object)(object)((Component)val2).gameObject.GetComponent<SkinnedMeshRenderer>()) && !Object.op_Implicit((Object)(object)((Component)val2).gameObject.GetComponent<ScanNodeProperties>()) && !list.Contains(((Component)val2).gameObject))
							{
								list.Add(((Component)val2).gameObject);
							}
						}
						foreach (GameObject item2 in list)
						{
							SkinnedMeshRenderer component3 = item2.gameObject.GetComponent<SkinnedMeshRenderer>();
							component3.sharedMesh = component.itemProperties.meshVariants[random.Next(0, component.itemProperties.meshVariants.Length)];
							SkinnedRendererPatch.Logger.LogDebug((object)("Changed " + ((Object)item2.gameObject).name + " mesh using SkinnedMeshRenderer"));
						}
					}
					if (component.itemProperties.materialVariants.Length == 0)
					{
						continue;
					}
					MeshRenderer component4 = ((Component)component).gameObject.GetComponent<MeshRenderer>();
					if ((Object)(object)component4 != (Object)null)
					{
						((Renderer)component4).sharedMaterial = component.itemProperties.materialVariants[random.Next(0, component.itemProperties.materialVariants.Length)];
						SkinnedRendererPatch.Logger.LogDebug((object)("Changed " + ((Object)((Component)component).gameObject).name + " material using MeshRenderer"));
					}
					List<GameObject> list2 = new List<GameObject>();
					foreach (Transform item3 in ((Component)component).gameObject.transform)
					{
						Transform val3 = item3;
						if (Object.op_Implicit((Object)(object)((Component)val3).gameObject.GetComponent<SkinnedMeshRenderer>()) && !Object.op_Implicit((Object)(object)((Component)val3).gameObject.GetComponent<ScanNodeProperties>()) && !list2.Contains(((Component)val3).gameObject))
						{
							list2.Add(((Component)val3).gameObject);
						}
					}
					foreach (GameObject item4 in list2)
					{
						SkinnedMeshRenderer component5 = item4.gameObject.GetComponent<SkinnedMeshRenderer>();
						((Renderer)component5).sharedMaterial = component.itemProperties.materialVariants[random.Next(0, component.itemProperties.materialVariants.Length)];
						SkinnedRendererPatch.Logger.LogDebug((object)("Changed " + ((Object)item4.gameObject).name + " material using SkinnedMeshRenderer"));
					}
				}
				catch (Exception arg)
				{
					SkinnedRendererPatch.Logger.LogError((object)$"Error when adjusting material on {((Object)((Component)component).gameObject).name}; {arg}");
				}
			}
			return true;
		}
	}
}
namespace SkinnedRendererPatch.ModCompatability
{
	public static class LilosScrapExtensionCompat
	{
		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static void ApplyCustomLSEAData(GrabbableObject component, bool curTriggerState)
		{
			CollectedScrapTrigger component2 = ((Component)component).gameObject.GetComponent<CollectedScrapTrigger>();
			MeshFilter component3 = ((Component)component).gameObject.GetComponent<MeshFilter>();
			MeshRenderer component4 = ((Component)component).gameObject.GetComponent<MeshRenderer>();
			if (!((Object)(object)component2 != (Object)null))
			{
				return;
			}
			component2.Triggered = curTriggerState;
			Mesh newMesh = component2.newMesh;
			Material newMaterial = component2.newMaterial;
			if ((Object)(object)component3 != (Object)null && (Object)(object)newMesh != (Object)null)
			{
				component3.mesh = newMesh;
			}
			if ((Object)(object)component4 != (Object)null && (Object)(object)newMaterial != (Object)null)
			{
				((Renderer)component4).sharedMaterial = newMaterial;
			}
			foreach (GameObject skinnedChild in ItemStateSaving.GetSkinnedChildren(((Component)component).gameObject.transform))
			{
				if ((Object)(object)newMesh != (Object)null)
				{
					skinnedChild.GetComponent<SkinnedMeshRenderer>().sharedMesh = newMesh;
				}
				if ((Object)(object)newMaterial != (Object)null)
				{
					((Renderer)skinnedChild.GetComponent<SkinnedMeshRenderer>()).sharedMaterial = newMaterial;
				}
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
		public static bool DetermineTriggered(GrabbableObject component)
		{
			bool flag = false;
			CollectedScrapTrigger component2 = ((Component)component).gameObject.GetComponent<CollectedScrapTrigger>();
			if ((Object)(object)component2 != (Object)null)
			{
				if (component2.Triggered)
				{
					return true;
				}
				return false;
			}
			return false;
		}
	}
}
namespace SkinnedRendererPatch.Helpers
{
	internal class SRPNetworkHelper : NetworkBehaviour
	{
		public static SRPNetworkHelper Instance { get; private set; }

		private void Start()
		{
			Instance = this;
			SkinnedRendererPatch.Logger.LogInfo((object)"SRPNetworkHelper.Start() initialized!");
		}

		[ClientRpc]
		public void SyncItemDataClientRpc(string meshIndexes, string matIndexes, string LSEAIndexes, ClientRpcParams clientParams)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Invalid comparison between Unknown and I4
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_0150: Invalid comparison between Unknown and I4
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = ((NetworkBehaviour)this).NetworkManager;
			if (networkManager == null || !networkManager.IsListening)
			{
				return;
			}
			if ((int)base.__rpc_exec_stage != 2 && (networkManager.IsServer || networkManager.IsHost))
			{
				FastBufferWriter val = ((NetworkBehaviour)this).__beginSendClientRpc(2591958224u, clientParams, (RpcDelivery)0);
				bool flag = meshIndexes != null;
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref flag, default(ForPrimitives));
				if (flag)
				{
					((FastBufferWriter)(ref val)).WriteValueSafe(meshIndexes, false);
				}
				bool flag2 = matIndexes != null;
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref flag2, default(ForPrimitives));
				if (flag2)
				{
					((FastBufferWriter)(ref val)).WriteValueSafe(matIndexes, false);
				}
				bool flag3 = LSEAIndexes != null;
				((FastBufferWriter)(ref val)).WriteValueSafe<bool>(ref flag3, default(ForPrimitives));
				if (flag3)
				{
					((FastBufferWriter)(ref val)).WriteValueSafe(LSEAIndexes, false);
				}
				((NetworkBehaviour)this).__endSendClientRpc(ref val, 2591958224u, clientParams, (RpcDelivery)0);
			}
			if ((int)base.__rpc_exec_stage != 2 || (!networkManager.IsClient && !networkManager.IsHost))
			{
				return;
			}
			GrabbableObject[] array = Object.FindObjectsByType<GrabbableObject>((FindObjectsInactive)0, (FindObjectsSortMode)0);
			Dictionary<ulong, GrabbableObject> dictionary = new Dictionary<ulong, GrabbableObject>();
			if (array.Length == 0)
			{
				return;
			}
			GrabbableObject[] array2 = array;
			foreach (GrabbableObject val2 in array2)
			{
				ulong networkObjectId = ((Component)val2).gameObject.GetComponent<NetworkObject>().NetworkObjectId;
				dictionary.Add(networkObjectId, val2);
			}
			SkinnedRendererPatch.Logger.LogDebug((object)"DEBUGGING:");
			SkinnedRendererPatch.Logger.LogDebug((object)("MESH INDEXES: " + meshIndexes));
			SkinnedRendererPatch.Logger.LogDebug((object)("MATERIAL INDEXES: " + matIndexes));
			SkinnedRendererPatch.Logger.LogDebug((object)("LSEA INDEXES: " + LSEAIndexes));
			if (meshIndexes != null && meshIndexes != "")
			{
				SkinnedRendererPatch.Logger.LogInfo((object)"Recieved valid mesh indexes, applying changes");
				ApplyMeshChanges(dictionary, meshIndexes);
			}
			else
			{
				SkinnedRendererPatch.Logger.LogInfo((object)"No valid mesh changes recieved, skipping");
			}
			if (matIndexes != null && matIndexes != "")
			{
				SkinnedRendererPatch.Logger.LogInfo((object)"Recieved valid material indexes, applying changes");
				ApplyMatChanges(dictionary, matIndexes);
			}
			else
			{
				SkinnedRendererPatch.Logger.LogInfo((object)"No valid material changes recieved, skipping");
			}
			if (SkinnedRendererPatch.LilosScrapExtensionPresent)
			{
				SkinnedRendererPatch.Logger.LogInfo((object)"DarthLilo.LilosScrapExtention is present, checking for extra changes");
				if (LSEAIndexes != null && LSEAIndexes != "")
				{
					SkinnedRendererPatch.Logger.LogInfo((object)"Recieved valid DarthLilo.LilosScrapExtention indexes, applying changes");
					ApplyLSEAChanges(dictionary, LSEAIndexes);
				}
				else
				{
					SkinnedRendererPatch.Logger.LogInfo((object)"No valid DarthLilo.LilosScrapExtention changes recieved, skipping");
				}
			}
		}

		public void ApplyMeshChanges(Dictionary<ulong, GrabbableObject> grabbableObjs, string meshChangesString)
		{
			Dictionary<ulong, int> dictionary = JsonConvert.DeserializeObject<Dictionary<ulong, int>>(meshChangesString);
			if (dictionary == null || dictionary.Count == 0)
			{
				return;
			}
			foreach (KeyValuePair<ulong, int> item in dictionary)
			{
				try
				{
					SkinnedRendererPatch.Logger.LogDebug((object)$"[MESH APPLY] - GameObject: [{((Object)((Component)grabbableObjs[item.Key]).gameObject).name}] - NetworkObjectID: [{item.Key}] - Mesh Variants: [{grabbableObjs[item.Key].itemProperties.meshVariants}] - Selected Mesh Index: [{item.Value}]");
					GrabbableObject val = grabbableObjs[item.Key];
					MeshFilter component = ((Component)val).gameObject.GetComponent<MeshFilter>();
					Mesh val2 = val.itemProperties.meshVariants[item.Value];
					if ((Object)(object)component != (Object)null)
					{
						component.mesh = val2;
					}
					foreach (GameObject skinnedChild in ItemStateSaving.GetSkinnedChildren(((Component)val).gameObject.transform))
					{
						skinnedChild.GetComponent<SkinnedMeshRenderer>().sharedMesh = val2;
					}
				}
				catch (Exception arg)
				{
					SkinnedRendererPatch.Logger.LogError((object)$"ERROR WHEN APPLYING MESH FOR [{((Object)((Component)grabbableObjs[item.Key]).gameObject).name}]: {arg}");
				}
			}
		}

		public void ApplyMatChanges(Dictionary<ulong, GrabbableObject> grabbableObjs, string matChangesString)
		{
			Dictionary<ulong, int> dictionary = JsonConvert.DeserializeObject<Dictionary<ulong, int>>(matChangesString);
			if (dictionary == null || dictionary.Count == 0)
			{
				return;
			}
			foreach (KeyValuePair<ulong, int> item in dictionary)
			{
				try
				{
					SkinnedRendererPatch.Logger.LogDebug((object)$"[MATERIAL APPLY] - GameObject: [{((Object)((Component)grabbableObjs[item.Key]).gameObject).name}] - NetworkObjectID: [{item.Key}] - Material Variants: [{grabbableObjs[item.Key].itemProperties.materialVariants}] - Selected Material Index: [{item.Value}]");
					GrabbableObject val = grabbableObjs[item.Key];
					MeshRenderer component = ((Component)val).gameObject.GetComponent<MeshRenderer>();
					Material sharedMaterial = val.itemProperties.materialVariants[item.Value];
					if ((Object)(object)component != (Object)null)
					{
						((Renderer)component).sharedMaterial = sharedMaterial;
					}
					foreach (GameObject skinnedChild in ItemStateSaving.GetSkinnedChildren(((Component)val).gameObject.transform))
					{
						((Renderer)skinnedChild.GetComponent<SkinnedMeshRenderer>()).sharedMaterial = sharedMaterial;
					}
				}
				catch (Exception arg)
				{
					SkinnedRendererPatch.Logger.LogError((object)$"ERROR WHEN APPLYING MATERIAL FOR [{((Object)((Component)grabbableObjs[item.Key]).gameObject).name}]: {arg}");
				}
			}
		}

		public void ApplyLSEAChanges(Dictionary<ulong, GrabbableObject> grabbableObjs, string LSEAChangesString)
		{
			Dictionary<ulong, bool> dictionary = JsonConvert.DeserializeObject<Dictionary<ulong, bool>>(LSEAChangesString);
			if (dictionary == null || dictionary.Count == 0)
			{
				return;
			}
			foreach (KeyValuePair<ulong, bool> item in dictionary)
			{
				try
				{
					SkinnedRendererPatch.Logger.LogDebug((object)$"[LSEA APPLY] - GameObject: [{((Object)((Component)grabbableObjs[item.Key]).gameObject).name}] - NetworkObjectID: [{item.Key}]");
					GrabbableObject component = grabbableObjs[item.Key];
					LilosScrapExtensionCompat.ApplyCustomLSEAData(component, curTriggerState: true);
				}
				catch (Exception arg)
				{
					SkinnedRendererPatch.Logger.LogError((object)$"ERROR WHEN APPLYING LSEA FOR [{((Object)((Component)grabbableObjs[item.Key]).gameObject).name}]: {arg}");
				}
			}
		}

		protected override void __initializeVariables()
		{
			((NetworkBehaviour)this).__initializeVariables();
		}

		[RuntimeInitializeOnLoadMethod]
		internal static void InitializeRPCS_SRPNetworkHelper()
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			NetworkManager.__rpc_func_table.Add(2591958224u, new RpcReceiveHandler(__rpc_handler_2591958224));
		}

		private static void __rpc_handler_2591958224(NetworkBehaviour target, FastBufferReader reader, __RpcParams rpcParams)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: 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_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00db: 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_0101: Unknown result type (might be due to invalid IL or missing references)
			NetworkManager networkManager = target.NetworkManager;
			if (networkManager != null && networkManager.IsListening)
			{
				bool flag = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag, default(ForPrimitives));
				string meshIndexes = null;
				if (flag)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref meshIndexes, false);
				}
				bool flag2 = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag2, default(ForPrimitives));
				string matIndexes = null;
				if (flag2)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref matIndexes, false);
				}
				bool flag3 = default(bool);
				((FastBufferReader)(ref reader)).ReadValueSafe<bool>(ref flag3, default(ForPrimitives));
				string lSEAIndexes = null;
				if (flag3)
				{
					((FastBufferReader)(ref reader)).ReadValueSafe(ref lSEAIndexes, false);
				}
				ClientRpcParams client = rpcParams.Client;
				target.__rpc_exec_stage = (__RpcExecStage)2;
				((SRPNetworkHelper)(object)target).SyncItemDataClientRpc(meshIndexes, matIndexes, lSEAIndexes, client);
				target.__rpc_exec_stage = (__RpcExecStage)0;
			}
		}

		protected internal override string __getTypeName()
		{
			return "SRPNetworkHelper";
		}
	}
}
namespace DarthLilo.SkinnedRendererPatch.NetcodePatcher
{
	[AttributeUsage(AttributeTargets.Module)]
	internal class NetcodePatchedAssemblyAttribute : Attribute
	{
	}
}