Decompiled source of VikingHorse v1.1.0

VikingHorse.dll

Decompiled 6 days ago
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using CreatureManager;
using HarmonyLib;
using ItemManager;
using JetBrains.Annotations;
using LocalizationManager;
using M2Core.Assets;
using M2Core.Config;
using M2Core.Content;
using M2Core.Patching;
using M2Horse.Core;
using M2Horse.Horse;
using M2Horse.Horse.Cart;
using Microsoft.CodeAnalysis;
using ServerSync;
using SoftReferenceableAssets;
using TMPro;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Rendering;
using UnityEngine.SceneManagement;
using UnityEngine.U2D;
using UnityEngine.UI;
using YamlDotNet.Core;
using YamlDotNet.Core.Events;
using YamlDotNet.Core.Tokens;
using YamlDotNet.Helpers;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.Converters;
using YamlDotNet.Serialization.EventEmitters;
using YamlDotNet.Serialization.NamingConventions;
using YamlDotNet.Serialization.NodeDeserializers;
using YamlDotNet.Serialization.NodeTypeResolvers;
using YamlDotNet.Serialization.ObjectFactories;
using YamlDotNet.Serialization.ObjectGraphTraversalStrategies;
using YamlDotNet.Serialization.ObjectGraphVisitors;
using YamlDotNet.Serialization.Schemas;
using YamlDotNet.Serialization.TypeInspectors;
using YamlDotNet.Serialization.TypeResolvers;
using YamlDotNet.Serialization.Utilities;
using YamlDotNet.Serialization.ValueDeserializers;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: <a308c4ea-864e-4b39-9631-13b77b9a075b>IgnoresAccessChecksTo("assembly_guiutils")]
[assembly: <a308c4ea-864e-4b39-9631-13b77b9a075b>IgnoresAccessChecksTo("assembly_utils")]
[assembly: <a308c4ea-864e-4b39-9631-13b77b9a075b>IgnoresAccessChecksTo("assembly_valheim")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("VikingHorse")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+7997e67a74f926b8e6ed1ffdc95db8819958dddf")]
[assembly: AssemblyProduct("VikingHorse")]
[assembly: AssemblyTitle("VikingHorse")]
[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.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace M2Horse
{
	internal enum ControllerButton
	{
		None,
		HideWeapon,
		SecondaryAttack,
		Run,
		A,
		B,
		X,
		Y,
		LeftBumper,
		RightBumper,
		LeftTrigger,
		RightTrigger,
		LeftStickPress,
		RightStickPress,
		DPadUp,
		DPadDown,
		DPadLeft,
		DPadRight,
		Select
	}
	internal sealed class ControllerBinding
	{
		public readonly ConfigEntry<ControllerButton> Button;

		public readonly ConfigEntry<bool> WithBlock;

		public string ZInputName
		{
			get
			{
				ControllerButton value = Button.Value;
				if (1 == 0)
				{
				}
				string result = value switch
				{
					ControllerButton.HideWeapon => "JoyHide", 
					ControllerButton.SecondaryAttack => "JoySecondaryAttack", 
					ControllerButton.Run => "JoyRun", 
					ControllerButton.A => "JoyButtonA", 
					ControllerButton.B => "JoyButtonB", 
					ControllerButton.X => "JoyButtonX", 
					ControllerButton.Y => "JoyButtonY", 
					ControllerButton.LeftBumper => "JoyLBumper", 
					ControllerButton.RightBumper => "JoyRBumper", 
					ControllerButton.LeftTrigger => "JoyLTrigger", 
					ControllerButton.RightTrigger => "JoyRTrigger", 
					ControllerButton.LeftStickPress => "JoyLStick", 
					ControllerButton.RightStickPress => "JoyRStick", 
					ControllerButton.DPadUp => "JoyDPadUp", 
					ControllerButton.DPadDown => "JoyDPadDown", 
					ControllerButton.DPadLeft => "JoyDPadLeft", 
					ControllerButton.DPadRight => "JoyDPadRight", 
					ControllerButton.Select => "JoyBack", 
					_ => null, 
				};
				if (1 == 0)
				{
				}
				return result;
			}
		}

		private ControllerBinding(ConfigEntry<ControllerButton> button, ConfigEntry<bool> withBlock)
		{
			Button = button;
			WithBlock = withBlock;
		}

		public static ControllerBinding Bind(ConfigFile config, string section, string name, string does, ControllerButton button, bool withBlock)
		{
			return new ControllerBinding(config.Bind<ControllerButton>(section, name + "Controller", button, "Controller button that " + does + ". HideWeapon, SecondaryAttack and Run are Valheim's own actions and follow the controller layout chosen in the game's settings; the others are fixed buttons, which may also do something else in the game. None: no controller button."), config.Bind<bool>(section, name + "ControllerWithBlock", withBlock, "Whether the block button has to be held together with the controller button above (the button Valheim uses for its own controller combinations)."));
		}

		public bool Down()
		{
			return Ready() && ZInput.GetButtonDown(ZInputName);
		}

		public bool Held()
		{
			return Ready() && ZInput.GetButton(ZInputName);
		}

		public void Consume()
		{
			string zInputName = ZInputName;
			if (WithBlock.Value && zInputName != null && ZInput.GetButtonDown(zInputName))
			{
				ZInput.ResetButtonStatus(zInputName);
			}
		}

		public string Glyphs()
		{
			string zInputName = ZInputName;
			if (zInputName == null)
			{
				return string.Empty;
			}
			return WithBlock.Value ? GamepadHints.Glyphs(" + ", "JoyAltKeys", zInputName) : GamepadHints.Glyph(zInputName);
		}

		private bool Ready()
		{
			return ZInputName != null && ZInput.IsGamepadActive() && (!WithBlock.Value || ZInput.GetButton("JoyAltKeys"));
		}
	}
	internal static class GamepadHints
	{
		public static UIGamePad Bind(Button button, string zinputKey, string glyph = null, KeyCode keyCode = (KeyCode)0)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)button == (Object)null)
			{
				return null;
			}
			UIGamePad val = ((Component)button).GetComponent<UIGamePad>();
			if ((Object)(object)val == (Object)null)
			{
				val = ((Component)button).gameObject.AddComponent<UIGamePad>();
			}
			val.m_zinputKey = zinputKey ?? string.Empty;
			val.m_keyCode = keyCode;
			if ((Object)(object)val.m_hint == (Object)null)
			{
				val.m_hint = CreateHint(((Component)button).transform, glyph ?? zinputKey);
			}
			return val;
		}

		public static GameObject CreateHint(Transform parent, params string[] glyphs)
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Expected O, but got Unknown
			GameObject val = FindTemplate();
			if ((Object)(object)val == (Object)null || (Object)(object)parent == (Object)null)
			{
				return null;
			}
			GameObject val2 = Object.Instantiate<GameObject>(val, parent, false);
			((Object)val2).name = "gamepad_hint";
			UIInputHint component = val2.GetComponent<UIInputHint>();
			if ((Object)(object)component != (Object)null)
			{
				Object.DestroyImmediate((Object)(object)component);
			}
			foreach (Transform item in val2.transform)
			{
				Transform val3 = item;
				((Component)val3).gameObject.SetActive(true);
			}
			Graphic[] componentsInChildren = val2.GetComponentsInChildren<Graphic>(true);
			foreach (Graphic val4 in componentsInChildren)
			{
				val4.raycastTarget = false;
			}
			val2.AddComponent<GamepadGlyph>().Set(string.Empty, glyphs);
			val2.SetActive(false);
			return val2;
		}

		public static TMP_Text CreateText(Transform parent, string name)
		{
			GameObject val = FindTemplate();
			TMP_Text val2 = (((Object)(object)val != (Object)null) ? val.GetComponentInChildren<TMP_Text>(true) : null);
			if ((Object)(object)val2 == (Object)null || (Object)(object)parent == (Object)null)
			{
				return null;
			}
			TMP_Text val3 = Object.Instantiate<TMP_Text>(val2, parent, false);
			((Object)val3).name = name;
			((Graphic)val3).raycastTarget = false;
			((Component)val3).gameObject.SetActive(true);
			return val3;
		}

		public static string Glyphs(string separator, params string[] names)
		{
			if (names == null || names.Length == 0)
			{
				return string.Empty;
			}
			string[] array = new string[names.Length];
			for (int i = 0; i < names.Length; i++)
			{
				array[i] = Glyph(names[i]);
			}
			return string.Join(separator, array);
		}

		public static string Glyph(string name)
		{
			if (ZInput.instance == null || string.IsNullOrEmpty(name))
			{
				return string.Empty;
			}
			if (!ZInput.s_gamepadSpriteMap.TryGetValue(name, out var value))
			{
				return ZInput.instance.GetBoundKeyString(name, true);
			}
			string[] array = ZInput.instance.GetBoundKeyString("JoyButtonA", true).Split(new char[1] { '"' });
			string value2;
			return (array.Length > 1 && value.TryGetValue(array[1], out value2)) ? ("<sprite=\"" + array[1] + "\" name=\"" + value2 + "\">") : string.Empty;
		}

		private static GameObject FindTemplate()
		{
			SkillsDialog val = (((Object)(object)InventoryGui.instance != (Object)null) ? InventoryGui.instance.m_skillsDialog : null);
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			UIGamePad[] componentsInChildren = ((Component)val).GetComponentsInChildren<UIGamePad>(true);
			foreach (UIGamePad val2 in componentsInChildren)
			{
				GameObject hint = val2.m_hint;
				if ((Object)(object)hint != (Object)null && (Object)(object)hint.GetComponent<UIInputHint>() != (Object)null && (Object)(object)hint.GetComponentInChildren<TMP_Text>(true) != (Object)null)
				{
					return hint;
				}
			}
			return null;
		}
	}
	internal sealed class GamepadGlyph : MonoBehaviour
	{
		private string _separator = string.Empty;

		private string[] _glyphs;

		private TMP_Text _text;

		public void Set(string separator, params string[] glyphs)
		{
			_separator = separator ?? string.Empty;
			_glyphs = glyphs;
			Refresh();
		}

		private void OnEnable()
		{
			ZInput.OnInputLayoutChanged += Refresh;
			Refresh();
		}

		private void OnDisable()
		{
			ZInput.OnInputLayoutChanged -= Refresh;
		}

		private void Refresh()
		{
			if (_glyphs != null)
			{
				if ((Object)(object)_text == (Object)null)
				{
					_text = ((Component)this).GetComponentInChildren<TMP_Text>(true);
				}
				if ((Object)(object)_text != (Object)null)
				{
					_text.text = GamepadHints.Glyphs(_separator, _glyphs);
				}
			}
		}
	}
	[BepInPlugin("M2Valheim.VikingHorse", "Viking Horse", "1.1.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "M2Valheim.VikingHorse";

		public const string PluginName = "Viking Horse";

		public const string PluginVersion = "1.1.0";

		internal static ManualLogSource Log;

		internal static readonly ConfigSync Sync = new ConfigSync("M2Valheim.VikingHorse")
		{
			DisplayName = "Viking Horse",
			CurrentVersion = "1.1.0",
			MinimumRequiredVersion = ModVersion.SameMinorMinimum("1.1.0"),
			ModRequired = true,
			IsLocked = true
		};

		internal static ConfigEntry<bool> EnableRunChopDamage;

		internal static ConfigEntry<bool> SuppressRunChopWood;

		internal static ConfigEntry<KeyCode> CycleSaddlePartsKey;

		internal static ConfigEntry<KeyCode> CycleSaddlePartsModifier;

		internal static ControllerBinding CycleSaddlePartsController;

		private void Awake()
		{
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			Localizer.Load();
			EnableRunChopDamage = ((BaseUnityPlugin)this).Config.Bind<bool>("Horse", "EnableRunChopDamage", true, "Enables the horse's run-chop damage (clears small vegetation while riding at speed, Asksvin-style). Disable to stop the horse from damaging/destroying vegetation entirely.");
			SuppressRunChopWood = ((BaseUnityPlugin)this).Config.Bind<bool>("Horse", "SuppressRunChopWood", true, "Suppresses wood/item drops from bushes etc. destroyed by the horse's run-chop damage while riding. Vegetation is still destroyed (path stays clear), just without loot.");
			CycleSaddlePartsKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Client", "CycleSaddlePartsKey", (KeyCode)113, "Key to cycle through the horse's optional saddle parts (fur carpet / pad) while looking at the saddle, next to the existing Use/Remove saddle prompts.");
			CycleSaddlePartsModifier = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Client", "CycleSaddlePartsModifier", (KeyCode)304, "Modifier key that must be held together with CycleSaddlePartsKey. Set to 'None' to use CycleSaddlePartsKey alone.");
			CycleSaddlePartsController = ControllerBinding.Bind(((BaseUnityPlugin)this).Config, "Client", "CycleSaddleParts", "cycles through the horse's optional saddle parts while looking at the saddle", ControllerButton.HideWeapon, withBlock: true);
			new Harmony("M2Valheim.VikingHorse").PatchAll();
			HorseCreature.Register();
		}

		private void Update()
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: 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)
			bool flag = ZInput.GetKeyDown(CycleSaddlePartsKey.Value, true) && ((int)CycleSaddlePartsModifier.Value == 0 || Input.GetKey(CycleSaddlePartsModifier.Value));
			bool flag2 = CycleSaddlePartsController.Down();
			if ((!flag && !flag2) || (Object)(object)Player.m_localPlayer == (Object)null || !((Character)Player.m_localPlayer).TakeInput())
			{
				return;
			}
			GameObject hoverObject = ((Humanoid)Player.m_localPlayer).GetHoverObject();
			Sadle val = (((Object)(object)hoverObject != (Object)null) ? hoverObject.GetComponentInParent<Sadle>() : null);
			if (!((Object)(object)val == (Object)null))
			{
				if (flag2)
				{
					CycleSaddlePartsController.Consume();
				}
				ZNetView componentInParent = ((Component)val).GetComponentInParent<ZNetView>();
				if ((Object)(object)componentInParent != (Object)null && componentInParent.IsValid())
				{
					componentInParent.InvokeRPC("M2Horse_RequestCycleSaddleVariant", Array.Empty<object>());
				}
			}
		}

		internal static string FormatCycleSaddlePartsKey()
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Invalid comparison between Unknown and I4
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			if (ZInput.IsGamepadActive())
			{
				string text = CycleSaddlePartsController.Glyphs();
				if (!string.IsNullOrEmpty(text))
				{
					return text;
				}
			}
			string text2 = FormatKeyName(CycleSaddlePartsKey.Value);
			if ((int)CycleSaddlePartsModifier.Value == 0)
			{
				return text2;
			}
			return FormatKeyName(CycleSaddlePartsModifier.Value) + " + " + text2;
		}

		private unsafe static string FormatKeyName(KeyCode key)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Expected I4, but got Unknown
			KeyCode val = key;
			KeyCode val2 = val;
			switch (val2 - 303)
			{
			case 0:
			case 1:
				return "Shift";
			case 2:
			case 3:
				return "Ctrl";
			case 4:
			case 5:
				return "Alt";
			default:
				return ((object)(*(KeyCode*)(&key))/*cast due to .constrained prefix*/).ToString();
			}
		}
	}
}
namespace M2Horse.Horse
{
	internal static class HorseCoatVariants
	{
		private static readonly (string Body, string Hair)[] Profiles = new(string, string)[25]
		{
			("Viking_Body_Base", "Viking_Hair_White"),
			("Viking_Body_Base", "Viking_Hair_Blond"),
			("Viking_Body_Brown", "Viking_Hair_Black"),
			("Viking_Body_Brown", "Viking_Hair_Brown"),
			("Viking_Body_Brown", "Viking_Hair_Blond"),
			("Viking_Body_DarkHead", "Viking_Hair_Black"),
			("Viking_Body_DarkHead", "Viking_Hair_White"),
			("Viking_Body_DirtyGray", "Viking_Hair_White"),
			("Viking_Body_DirtyGray", "Viking_Hair_Black"),
			("Viking_Body_DirtyGray", "Viking_Hair_Blond"),
			("Viking_Body_Gray", "Viking_Hair_White"),
			("Viking_Body_Gray", "Viking_Hair_Black"),
			("Viking_Body_Gray", "Viking_Hair_Blond"),
			("Viking_Body_Palmolino", "Viking_Hair_White"),
			("Viking_Body_Palmolino", "Viking_Hair_Blond"),
			("Viking_Body_Palmolino", "Viking_Hair_Black"),
			("Viking_Body_Palmolino", "Viking_Hair_Brown"),
			("Viking_Body_Palmolino", "Viking_Hair_Red"),
			("Viking_Body_Red", "Viking_Hair_Brown"),
			("Viking_Body_Red", "Viking_Hair_Red"),
			("Viking_Body_Red", "Viking_Hair_Black"),
			("Viking_Body_Red", "Viking_Hair_Blond"),
			("Viking_Body_Red", "Viking_Hair_White"),
			("Viking_Body_Spotted", "Viking_Hair_White"),
			("Viking_Body_Spotted", "Viking_Hair_Blond")
		};

		private const string BodyRendererName = "Viking_Horse_LOD0";

		private const string HairMatPrefix = "Viking_Hair_";

		private static readonly int s_coatProfileHash = StringExtensionMethods.GetStableHashCode("m2horse_coatprofile");

		private static Dictionary<string, Material> s_bodyMats;

		private static Dictionary<string, Material> s_hairMats;

		private const string ReinsRopeMaterialName = "ReinsRope";

		internal static IEnumerable<Material> AllMaterials
		{
			get
			{
				IEnumerable<Material> enumerable = s_bodyMats?.Values;
				IEnumerable<Material> first = enumerable ?? Enumerable.Empty<Material>();
				enumerable = s_hairMats?.Values;
				return first.Concat(enumerable ?? Enumerable.Empty<Material>());
			}
		}

		public static Material ReinsRopeMaterial { get; private set; }

		public static void LoadMaterials(AssetBundle bundle)
		{
			s_bodyMats = LoadUnique(bundle, Profiles.Select(((string Body, string Hair) p) => p.Body), "Coat");
			s_hairMats = LoadUnique(bundle, Profiles.Select(((string Body, string Hair) p) => p.Hair), "Hair");
			ReinsRopeMaterial = bundle.LoadAsset<Material>("ReinsRope");
			if ((Object)(object)ReinsRopeMaterial == (Object)null)
			{
				Plugin.Log.LogError((object)"[M2Horse] Reins-Material 'ReinsRope' nicht im Bundle gefunden.");
			}
		}

		private static Dictionary<string, Material> LoadUnique(AssetBundle bundle, IEnumerable<string> names, string kind)
		{
			Dictionary<string, Material> dictionary = new Dictionary<string, Material>();
			foreach (string item in names.Distinct())
			{
				Material val = bundle.LoadAsset<Material>(item);
				if ((Object)(object)val == (Object)null)
				{
					Plugin.Log.LogError((object)("[M2Horse] " + kind + "-Material '" + item + "' nicht im Bundle gefunden."));
				}
				else
				{
					dictionary[item] = val;
				}
			}
			return dictionary;
		}

		public static void Apply(Character character)
		{
			ZNetView component = ((Component)character).GetComponent<ZNetView>();
			if ((Object)(object)component == (Object)null || !component.IsValid())
			{
				return;
			}
			ZDO zDO = component.GetZDO();
			int? num = GetIndex(zDO);
			if (!num.HasValue)
			{
				if (!component.IsOwner())
				{
					return;
				}
				num = Random.Range(0, Profiles.Length);
				SetIndex(zDO, num.Value);
			}
			Transform root = ((Component)character).transform.Find("Visual");
			ApplyToRenderers(root, num.Value);
		}

		public static void ApplyToRagdoll(Ragdoll ragdoll, int index)
		{
			ApplyToRenderers(((Component)ragdoll).transform, index);
		}

		public static int? GetIndex(ZDO zdo)
		{
			if (zdo == null)
			{
				return null;
			}
			int num = zdo.GetInt(s_coatProfileHash, -1);
			return (num < 0) ? ((int?)null) : new int?(num);
		}

		public static void SetIndex(ZDO zdo, int index)
		{
			if (zdo != null)
			{
				zdo.Set(s_coatProfileHash, index, false);
			}
		}

		private static void ApplyToRenderers(Transform root, int index)
		{
			if ((Object)(object)root == (Object)null || s_bodyMats == null || s_hairMats == null || index < 0 || index >= Profiles.Length)
			{
				return;
			}
			(string, string) tuple = Profiles[index];
			if (!s_bodyMats.TryGetValue(tuple.Item1, out var value) || !s_hairMats.TryGetValue(tuple.Item2, out var value2))
			{
				return;
			}
			SkinnedMeshRenderer[] componentsInChildren = ((Component)root).GetComponentsInChildren<SkinnedMeshRenderer>();
			foreach (SkinnedMeshRenderer val in componentsInChildren)
			{
				if (((Object)val).name == "Viking_Horse_LOD0")
				{
					Material[] sharedMaterials = ((Renderer)val).sharedMaterials;
					sharedMaterials[0] = value;
					((Renderer)val).sharedMaterials = sharedMaterials;
					continue;
				}
				Material[] sharedMaterials2 = ((Renderer)val).sharedMaterials;
				bool flag = false;
				for (int j = 0; j < sharedMaterials2.Length; j++)
				{
					if ((Object)(object)sharedMaterials2[j] != (Object)null && ((Object)sharedMaterials2[j]).name.StartsWith("Viking_Hair_"))
					{
						sharedMaterials2[j] = value2;
						flag = true;
					}
				}
				if (flag)
				{
					((Renderer)val).sharedMaterials = sharedMaterials2;
				}
			}
		}
	}
	internal static class HorseCreature
	{
		private const string BundleName = "m2horse";

		private const string PrefabName = "M2Horse";

		private const string CreatureName = "$m2_horse";

		private const string SaddlePrefabName = "SaddleM2Horse";

		private const string RagdollPrefabName = "M2Horse_Ragdoll";

		internal const float SpawnDistance = 30f;

		private static readonly List<GameObject> s_withPlaceholders = new List<GameObject>();

		private static bool s_placeholdersResolved;

		private const string CreatureShaderName = "Custom/Creature";

		private const string CreatureShaderSource = "lox";

		private static bool s_creatureShaderApplied;

		internal static GameObject Prefab { get; private set; }

		public static void Register()
		{
			Item.DefaultConfigurability = Configurability.Disabled;
			AssetBundle val = EmbeddedResources.LoadBundle(Assembly.GetExecutingAssembly(), "m2horse");
			if ((Object)(object)val == (Object)null)
			{
				Plugin.Log.LogError((object)"[M2Horse] Embedded resource 'm2horse' nicht gefunden oder nicht ladbar.");
				return;
			}
			GameObject val2 = val.LoadAsset<GameObject>("M2Horse");
			if ((Object)(object)val2 == (Object)null)
			{
				Plugin.Log.LogError((object)"[M2Horse] Prefab 'M2Horse' nicht im Bundle gefunden.");
				val.Unload(false);
				return;
			}
			RegisterCreature(val, val2);
			RegisterSaddleItem(val);
			RegisterRagdollPrefab(val);
			HorseCoatVariants.LoadMaterials(val);
			val.Unload(false);
			GameData.ObjectDbReady += ResolvePlaceholders;
		}

		private static void RegisterCreature(AssetBundle bundle, GameObject prefab)
		{
			//IL_0015: 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)
			Character component = prefab.GetComponent<Character>();
			component.m_name = "$m2_horse";
			component.m_faction = (Faction)1;
			Prefab = prefab;
			s_withPlaceholders.Add(prefab);
			Creature creature = new Creature(bundle, "M2Horse")
			{
				ConfigurationEnabled = false,
				FoodItems = "Dandelion",
				Biome = (Biome)1,
				SpecificSpawnArea = SpawnArea.Center,
				RequiredAltitude = new CreatureManager.Range(2f, 1000f),
				SpawnChance = 5f,
				CheckSpawnInterval = 600,
				Maximum = 1,
				CanHaveStars = false
			};
			string[] array = new string[2] { "DeerMeat", "DeerHide" };
			foreach (string prefabName in array)
			{
				Creature.Drop drop = creature.Drops[prefabName];
				drop.Amount = new CreatureManager.Range(1f, 2f);
				drop.DropChance = 100f;
				drop.MultiplyDropByLevel = false;
			}
		}

		private static void RegisterSaddleItem(AssetBundle bundle)
		{
			GameObject val = bundle.LoadAsset<GameObject>("SaddleM2Horse");
			if ((Object)(object)val == (Object)null)
			{
				Plugin.Log.LogError((object)"[M2Horse] Prefab 'SaddleM2Horse' nicht im Bundle gefunden.");
				return;
			}
			SharedData shared = val.GetComponent<ItemDrop>().m_itemData.m_shared;
			if (string.IsNullOrEmpty(shared.m_name))
			{
				shared.m_name = "$" + ((Object)val).name;
			}
			s_withPlaceholders.Add(val);
			Item item = new Item(val);
			item.Crafting.Add(CraftingTable.Workbench, 3);
			item.RequiredItems.Add("LeatherScraps", 10);
			item.RequiredItems.Add("DeerHide", 5);
			item.RequiredItems.Add("Bronze", 3);
		}

		private static void RegisterRagdollPrefab(AssetBundle bundle)
		{
			GameObject val = bundle.LoadAsset<GameObject>("M2Horse_Ragdoll");
			if ((Object)(object)val == (Object)null)
			{
				Plugin.Log.LogError((object)"[M2Horse] Prefab 'M2Horse_Ragdoll' nicht im Bundle gefunden.");
				return;
			}
			Prefabs.Register(val);
			s_withPlaceholders.Add(val);
		}

		private static void ResolvePlaceholders()
		{
			ApplyCreatureShader();
			if (s_placeholdersResolved)
			{
				return;
			}
			int num = 0;
			foreach (GameObject s_withPlaceholder in s_withPlaceholders)
			{
				num += MockReferences.Resolve(s_withPlaceholder);
			}
			s_placeholdersResolved = num == 0;
		}

		private static void ApplyCreatureShader()
		{
			if (s_creatureShaderApplied || (Object)(object)Prefab == (Object)null)
			{
				return;
			}
			Material val = AssetLookup.Find<Material>("lox");
			if ((Object)(object)val == (Object)null || (Object)(object)val.shader == (Object)null || ((Object)val.shader).name != "Custom/Creature")
			{
				Plugin.Log.LogWarning((object)"[M2Horse] Valheims 'Custom/Creature' ueber 'lox' nicht gefunden -- naechster Versuch beim naechsten Weltstart.");
				return;
			}
			HashSet<Material> hashSet = new HashSet<Material>(HorseCoatVariants.AllMaterials);
			foreach (GameObject s_withPlaceholder in s_withPlaceholders)
			{
				Renderer[] componentsInChildren = s_withPlaceholder.GetComponentsInChildren<Renderer>(true);
				foreach (Renderer val2 in componentsInChildren)
				{
					hashSet.UnionWith(val2.sharedMaterials);
				}
			}
			int num = 0;
			foreach (Material item in hashSet)
			{
				if (!((Object)(object)item == (Object)null) && !((Object)item).name.StartsWith("M2mock_") && NeedsCreatureShader(item.shader))
				{
					item.shader = val.shader;
					num++;
				}
			}
			s_creatureShaderApplied = true;
			Plugin.Log.LogInfo((object)string.Format("[M2Horse] {0} Materialien auf Valheims '{1}' umgestellt.", num, "Custom/Creature"));
		}

		private static bool NeedsCreatureShader(Shader shader)
		{
			return (Object)(object)shader == (Object)null || ((Object)shader).name == "Custom/Creature" || ((Object)shader).name == "Hidden/InternalErrorShader";
		}
	}
	[DefaultExecutionOrder(10000)]
	internal class HorseReinsLine : MonoBehaviour
	{
		private Transform _bitL;

		private Transform _bitR;

		private Transform _handL;

		private Transform _handR;

		private Transform _horse;

		private LineRenderer _line;

		private const int PointsPerSegment = 10;

		private const float SagBitHand = 0.3f;

		private const float SagHandHand = 0.04f;

		private const float Width = 0.02f;

		private const float HandOutward = 0.06f;

		private const float SideBow = 0.1f;

		private const float Smoothness = 0.26f;

		private static readonly Color ReinsTint = new Color(0.502f, 0.1804f, 0f, 1f);

		public Transform HorseRoot => _horse;

		public static void Setup(GameObject playerGo, Transform horseRoot, Transform handL, Transform handR)
		{
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Expected O, but got Unknown
			if ((Object)(object)playerGo == (Object)null || (Object)(object)horseRoot == (Object)null || (Object)(object)handL == (Object)null || (Object)(object)handR == (Object)null || (Object)(object)playerGo.GetComponent<HorseReinsLine>() != (Object)null)
			{
				return;
			}
			Transform val = Find(horseRoot, "Reins_Root_L") ?? Find(horseRoot, "DEF-Bit_L");
			Transform val2 = Find(horseRoot, "Reins_Root_R") ?? Find(horseRoot, "DEF-Bit_R");
			if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null)
			{
				Plugin.Log.LogWarning((object)"[M2Horse] Bit-Anker fuer Zuegel nicht gefunden -- LineRenderer-Zuegel deaktiviert.");
				return;
			}
			HorseReinsLine horseReinsLine = playerGo.AddComponent<HorseReinsLine>();
			horseReinsLine._bitL = val;
			horseReinsLine._bitR = val2;
			horseReinsLine._handL = handL;
			horseReinsLine._handR = handR;
			horseReinsLine._horse = horseRoot;
			GameObject val3 = new GameObject("M2Horse_ReinsLine");
			val3.transform.SetParent(playerGo.transform, false);
			LineRenderer val4 = val3.AddComponent<LineRenderer>();
			val4.useWorldSpace = true;
			val4.alignment = (LineAlignment)0;
			val4.textureMode = (LineTextureMode)0;
			val4.numCornerVertices = 2;
			val4.numCapVertices = 2;
			val4.widthMultiplier = 0.02f;
			((Renderer)val4).shadowCastingMode = (ShadowCastingMode)1;
			((Renderer)val4).receiveShadows = true;
			val4.generateLightingData = true;
			Material val5 = CreateReinsMaterial(horseRoot);
			if ((Object)(object)val5 != (Object)null)
			{
				((Renderer)val4).material = val5;
			}
			horseReinsLine._line = val4;
		}

		private void LateUpdate()
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: 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_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: 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)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_019a: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: 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_01cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0207: Unknown result type (might be due to invalid IL or missing references)
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			//IL_0209: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)_bitL == (Object)null || (Object)(object)_bitR == (Object)null || (Object)(object)_handL == (Object)null || (Object)(object)_handR == (Object)null || (Object)(object)_line == (Object)null)
			{
				return;
			}
			Vector3 position = _bitL.position;
			Vector3 position2 = _handL.position;
			Vector3 position3 = _handR.position;
			Vector3 position4 = _bitR.position;
			Vector3 val = (((Object)(object)_horse != (Object)null) ? _horse.right : Vector3.right);
			float num = 0.06f;
			position2 -= val * num;
			position3 += val * num;
			int num2 = 31;
			if (_line.positionCount != num2)
			{
				_line.positionCount = num2;
			}
			_line.widthMultiplier = 0.02f;
			Material material = ((Renderer)_line).material;
			if ((Object)(object)material != (Object)null)
			{
				if (material.HasProperty("_Color"))
				{
					material.color = ReinsTint;
				}
				float num3 = 0.26f;
				if (material.HasProperty("_Glossiness"))
				{
					material.SetFloat("_Glossiness", num3);
				}
				if (material.HasProperty("_Smoothness"))
				{
					material.SetFloat("_Smoothness", num3);
				}
			}
			float num4 = 0.3f;
			float num5 = 0.1f;
			Vector3 bulge = Vector3.down * num4 - val * num5;
			Vector3 bulge2 = Vector3.down * num4 + val * num5;
			Vector3 bulge3 = Vector3.down * 0.04f;
			int idx = 0;
			idx = WriteSegment(idx, position, position2, bulge, includeStart: true);
			idx = WriteSegment(idx, position2, position3, bulge3, includeStart: false);
			idx = WriteSegment(idx, position3, position4, bulge2, includeStart: false);
		}

		private int WriteSegment(int idx, Vector3 a, Vector3 b, Vector3 bulge, bool includeStart)
		{
			//IL_0018: 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_001b: 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)
			//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_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_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			int num = ((!includeStart) ? 1 : 0);
			for (int i = num; i <= 10; i++)
			{
				float num2 = (float)i / 10f;
				Vector3 val = Vector3.Lerp(a, b, num2);
				float num3 = 1f - Mathf.Pow(Mathf.Abs(0.5f - num2) * 2f, 2f);
				val += bulge * num3;
				_line.SetPosition(idx++, val);
			}
			return idx;
		}

		private void OnDestroy()
		{
			if ((Object)(object)_line != (Object)null)
			{
				if ((Object)(object)((Renderer)_line).material != (Object)null)
				{
					Object.Destroy((Object)(object)((Renderer)_line).material);
				}
				Object.Destroy((Object)(object)((Component)_line).gameObject);
			}
		}

		private static Transform Find(Transform root, string name)
		{
			if ((Object)(object)root == (Object)null)
			{
				return null;
			}
			Transform[] componentsInChildren = ((Component)root).GetComponentsInChildren<Transform>(true);
			foreach (Transform val in componentsInChildren)
			{
				if (((Object)val).name == name)
				{
					return val;
				}
			}
			return null;
		}

		private static Material CreateReinsMaterial(Transform horseRoot)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Expected O, but got Unknown
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)HorseCoatVariants.ReinsRopeMaterial != (Object)null)
			{
				return new Material(HorseCoatVariants.ReinsRopeMaterial);
			}
			Plugin.Log.LogWarning((object)"[M2Horse] ReinsRope-Material fehlt -- falle auf Belt-Material zurueck.");
			Material val = FindBeltMaterial(horseRoot);
			return (!((Object)(object)val != (Object)null)) ? ((Material)null) : new Material(val);
		}

		private static Material FindBeltMaterial(Transform root)
		{
			Renderer val = null;
			Renderer[] componentsInChildren = ((Component)root).GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val2 in componentsInChildren)
			{
				if (((Object)val2).name.IndexOf("Belt", StringComparison.OrdinalIgnoreCase) >= 0)
				{
					return val2.sharedMaterial;
				}
				if ((Object)(object)val == (Object)null && (((Object)val2).name.IndexOf("Bridle", StringComparison.OrdinalIgnoreCase) >= 0 || ((Object)val2).name.IndexOf("Saddle", StringComparison.OrdinalIgnoreCase) >= 0))
				{
					val = val2;
				}
			}
			return ((Object)(object)val != (Object)null) ? val.sharedMaterial : null;
		}
	}
	internal static class HorseSaddleVariant
	{
		private const string FurCarpetRendererName = "Fur_Carpet_LOD0";

		private const string PadRendererName = "Pad_LOD0";

		private static readonly int s_variantHash = StringExtensionMethods.GetStableHashCode("m2horse_saddlevariant");

		private static readonly (bool furCarpet, bool pad)[] Variants = new(bool, bool)[4]
		{
			(true, true),
			(true, false),
			(false, true),
			(false, false)
		};

		public static int GetVariant(ZDO zdo)
		{
			return (zdo != null) ? zdo.GetInt(s_variantHash, 0) : 0;
		}

		public static int NextVariant(ZDO zdo)
		{
			return (GetVariant(zdo) + 1) % Variants.Length;
		}

		public static void SetVariant(ZDO zdo, int variant)
		{
			if (zdo != null)
			{
				zdo.Set(s_variantHash, variant, false);
			}
		}

		public static void Apply(Character character)
		{
			ZNetView component = ((Component)character).GetComponent<ZNetView>();
			ZDO zdo = ((component != null) ? component.GetZDO() : null);
			ApplyVariant(((Component)character).transform, GetVariant(zdo));
		}

		public static void ApplyVariant(Transform characterRoot, int variant)
		{
			Transform val = characterRoot.Find("Visual");
			if (!((Object)(object)val == (Object)null))
			{
				int num = (variant % Variants.Length + Variants.Length) % Variants.Length;
				var (active, active2) = Variants[num];
				SetActiveByName(val, "Fur_Carpet_LOD0", active);
				SetActiveByName(val, "Pad_LOD0", active2);
			}
		}

		private static void SetActiveByName(Transform root, string name, bool active)
		{
			Transform[] componentsInChildren = ((Component)root).GetComponentsInChildren<Transform>(true);
			foreach (Transform val in componentsInChildren)
			{
				if (((Object)val).name == name)
				{
					((Component)val).gameObject.SetActive(active);
					break;
				}
			}
		}
	}
}
namespace M2Horse.Horse.Patches
{
	[HarmonyPatch(typeof(Sadle), "UseStamina")]
	internal static class SadleCartStaminaPatch
	{
		private static void Prefix(Sadle __instance, ref float v)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Invalid comparison between Unknown and I4
			if ((int)__instance.m_speed == 2 && (Object)(object)HorseCart.CartOf(__instance.GetCharacter()) != (Object)null)
			{
				v *= 1.5f;
			}
		}
	}
	[HarmonyPatch(typeof(BaseAI), "IdleMovement")]
	internal static class HorseCartIdlePatch
	{
		private static bool Prefix(BaseAI __instance)
		{
			Character character = __instance.m_character;
			if ((Object)(object)HorseCart.CartOf(character) == (Object)null || HorseCart.IsRidden(character))
			{
				return true;
			}
			__instance.StopMoving();
			return false;
		}
	}
	[HarmonyPatch(typeof(Sadle), "RPC_RequestControl")]
	internal static class SadleCartInUsePatch
	{
		private static bool Prefix(Sadle __instance, long sender)
		{
			if (!__instance.m_nview.IsOwner())
			{
				return true;
			}
			Vagon val = HorseCart.CartOf(__instance.GetCharacter());
			if ((Object)(object)val == (Object)null || !HorseCart.ContainerOpen(val))
			{
				return true;
			}
			__instance.m_nview.InvokeRPC(sender, "RequestRespons", new object[1] { false });
			return false;
		}
	}
	[HarmonyPatch(typeof(Character), "OnDeath")]
	internal static class HorseCartDeathPatch
	{
		private static void Postfix(Character __instance)
		{
			HorseCartAnchors.UnhitchIfOwner(__instance);
		}
	}
	[HarmonyPatch(typeof(Tameable), "DropSaddle")]
	internal static class HorseCartSaddlePatch
	{
		private static void Postfix(Tameable __instance, bool __result)
		{
			if (__result)
			{
				HorseCartAnchors.UnhitchIfOwner(((Component)__instance).GetComponent<Character>());
			}
		}
	}
	internal static class HorseCartAnchors
	{
		internal static void UnhitchIfOwner(Character horse)
		{
			Vagon val = HorseCart.CartOf(horse);
			if ((Object)(object)val != (Object)null && val.m_nview.IsOwner())
			{
				HorseCart.Unhitch(val);
			}
		}
	}
	[HarmonyPatch(typeof(Character), "Awake")]
	internal static class HorseCoatVariantsPatch
	{
		private const string PrefabName = "M2Horse";

		private const string RequestCycleSaddleVariantRpc = "M2Horse_RequestCycleSaddleVariant";

		private const string SetSaddleVariantRpc = "M2Horse_SetSaddleVariant";

		private static void Postfix(Character __instance)
		{
			if (!(Utils.GetPrefabName(((Component)__instance).gameObject) != "M2Horse"))
			{
				HorseCoatVariants.Apply(__instance);
				RegisterSaddleVariantRpcs(__instance);
				HorseSaddleVariant.Apply(__instance);
			}
		}

		private static void RegisterSaddleVariantRpcs(Character character)
		{
			ZNetView nview = ((Component)character).GetComponent<ZNetView>();
			if ((Object)(object)nview == (Object)null || !nview.IsValid() || nview.m_functions.ContainsKey(StringExtensionMethods.GetStableHashCode("M2Horse_RequestCycleSaddleVariant")))
			{
				return;
			}
			nview.Register("M2Horse_RequestCycleSaddleVariant", (Action<long>)delegate
			{
				if (nview.IsOwner())
				{
					ZDO zDO = nview.GetZDO();
					int num = HorseSaddleVariant.NextVariant(zDO);
					HorseSaddleVariant.SetVariant(zDO, num);
					nview.InvokeRPC(ZNetView.Everybody, "M2Horse_SetSaddleVariant", new object[1] { num });
				}
			});
			nview.Register<int>("M2Horse_SetSaddleVariant", (Action<long, int>)delegate(long sender, int variant)
			{
				HorseSaddleVariant.ApplyVariant(((Component)character).transform, variant);
			});
		}
	}
	[HarmonyPatch(typeof(EffectList), "Create")]
	internal static class HorseRagdollColorPatch
	{
		private const string PrefabName = "M2Horse_Ragdoll";

		private static void Postfix(GameObject[] __result, Transform baseParent)
		{
			if ((Object)(object)baseParent == (Object)null || __result == null)
			{
				return;
			}
			foreach (GameObject val in __result)
			{
				Ragdoll component = val.GetComponent<Ragdoll>();
				if (!((Object)(object)component == (Object)null) && !(Utils.GetPrefabName(val) != "M2Horse_Ragdoll"))
				{
					ZNetView component2 = ((Component)baseParent).GetComponent<ZNetView>();
					ZDO zdo = ((component2 != null) ? component2.GetZDO() : null);
					int? index = HorseCoatVariants.GetIndex(zdo);
					if (index.HasValue)
					{
						ZNetView component3 = ((Component)component).GetComponent<ZNetView>();
						ZDO zdo2 = ((component3 != null) ? component3.GetZDO() : null);
						HorseCoatVariants.SetIndex(zdo2, index.Value);
						HorseCoatVariants.ApplyToRagdoll(component, index.Value);
					}
				}
			}
		}
	}
	[HarmonyPatch(typeof(Ragdoll), "Awake")]
	internal static class HorseRagdollColorAwakePatch
	{
		private const string PrefabName = "M2Horse_Ragdoll";

		private static void Postfix(Ragdoll __instance)
		{
			if (!(Utils.GetPrefabName(((Component)__instance).gameObject) != "M2Horse_Ragdoll"))
			{
				ZNetView component = ((Component)__instance).GetComponent<ZNetView>();
				ZDO zdo = ((component != null) ? component.GetZDO() : null);
				int? index = HorseCoatVariants.GetIndex(zdo);
				if (index.HasValue)
				{
					HorseCoatVariants.ApplyToRagdoll(__instance, index.Value);
				}
			}
		}
	}
	internal static class HorseRidingShared
	{
		internal static bool s_tiltChanged;

		internal static bool s_originalCameraTilt;
	}
	[HarmonyPatch(typeof(Player), "AttachStart")]
	internal static class HorseAttachStartPatch
	{
		private static void Postfix(Player __instance, Transform attachPoint)
		{
			if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer || (Object)(object)attachPoint == (Object)null)
			{
				return;
			}
			Transform root = attachPoint.root;
			if (HorseCart.IsHorse(((Component)root).GetComponent<Character>()))
			{
				GameCamera instance = GameCamera.instance;
				if ((Object)(object)instance != (Object)null && !HorseRidingShared.s_tiltChanged)
				{
					HorseRidingShared.s_originalCameraTilt = instance.m_shipCameraTilt;
					instance.m_shipCameraTilt = false;
					HorseRidingShared.s_tiltChanged = true;
				}
				VisEquipment component = ((Component)__instance).GetComponent<VisEquipment>();
				if ((Object)(object)component != (Object)null)
				{
					HorseReinsLine.Setup(((Component)__instance).gameObject, root, component.m_leftHand, component.m_rightHand);
				}
			}
		}
	}
	[HarmonyPatch(typeof(Player), "AttachStop")]
	internal static class HorseAttachStopPatch
	{
		private static void Postfix(Player __instance)
		{
			if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer)
			{
				return;
			}
			if (HorseRidingShared.s_tiltChanged)
			{
				if ((Object)(object)GameCamera.instance != (Object)null)
				{
					GameCamera.instance.m_shipCameraTilt = HorseRidingShared.s_originalCameraTilt;
				}
				HorseRidingShared.s_tiltChanged = false;
			}
			HorseReinsLine component = ((Component)__instance).GetComponent<HorseReinsLine>();
			if ((Object)(object)component != (Object)null)
			{
				Object.Destroy((Object)(object)component);
			}
		}
	}
	[HarmonyPatch(typeof(Sadle), "GetHoverText")]
	internal static class SadleSaddlePartsHintPatch
	{
		private const string PrefabName = "M2Horse";

		private static void Postfix(Sadle __instance, ref string __result)
		{
			//IL_003d: 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)
			if (!(Utils.GetPrefabName(((Component)((Component)__instance).transform.root).gameObject) != "M2Horse") && !((Object)(object)Player.m_localPlayer == (Object)null) && !(Vector3.Distance(((Component)__instance).transform.position, ((Component)Player.m_localPlayer).transform.position) > __instance.m_maxUseRange))
			{
				string text = Plugin.FormatCycleSaddlePartsKey();
				__result += Localization.instance.Localize("\n[<color=yellow><b>" + text + "</b></color>] $m2horse_cyclesaddleparts");
			}
		}
	}
	[HarmonyPatch(typeof(Destructible), "Destroy")]
	internal static class HorseRunChopNoDropPatch
	{
		private const string HorsePrefabNamePrefix = "M2Horse";

		internal static bool s_suppressDrop;

		private static void Prefix(HitData hit)
		{
			s_suppressDrop = false;
			if (Plugin.SuppressRunChopWood.Value)
			{
				Character val = ((hit != null) ? hit.GetAttacker() : null);
				s_suppressDrop = (Object)(object)val != (Object)null && ((Object)val).name.StartsWith("M2Horse");
			}
		}

		private static void Postfix()
		{
			s_suppressDrop = false;
		}
	}
	[HarmonyPatch(typeof(DropOnDestroyed), "OnDestroyed")]
	internal static class HorseRunChopNoDropOnDestroyedPatch
	{
		private static bool Prefix()
		{
			return !HorseRunChopNoDropPatch.s_suppressDrop;
		}
	}
	[HarmonyPatch(typeof(MovementDamage), "Update")]
	internal static class HorseRunChopEnabledPatch
	{
		private const string HorsePrefabNamePrefix = "M2Horse";

		private static void Postfix(MovementDamage __instance)
		{
			if (!Plugin.EnableRunChopDamage.Value && ((Object)((Component)__instance).gameObject).name.StartsWith("M2Horse") && (Object)(object)__instance.m_runDamageObject != (Object)null)
			{
				__instance.m_runDamageObject.SetActive(false);
			}
		}
	}
	[HarmonyPatch(typeof(SpawnSystem), "Awake")]
	internal static class HorseSpawnDistancePatch
	{
		[HarmonyPriority(200)]
		private static void Postfix(SpawnSystem __instance)
		{
			if ((Object)(object)HorseCreature.Prefab == (Object)null)
			{
				return;
			}
			foreach (SpawnSystemList spawnList in __instance.m_spawnLists)
			{
				foreach (SpawnData spawner in spawnList.m_spawners)
				{
					if ((Object)(object)spawner.m_prefab == (Object)(object)HorseCreature.Prefab)
					{
						spawner.m_spawnDistance = 30f;
					}
				}
			}
		}
	}
	[HarmonyPatch(typeof(Vagon), "Awake")]
	internal static class VagonAwakePatch
	{
		private static void Postfix(Vagon __instance)
		{
			if ((Object)(object)__instance.m_nview != (Object)null && __instance.m_nview.GetZDO() != null)
			{
				((Component)__instance).gameObject.AddComponent<HorseCartLink>();
			}
		}
	}
	[HarmonyPatch(typeof(Vagon), "Update")]
	internal static class VagonUpdatePatch
	{
		private static bool Prefix(Vagon __instance)
		{
			if (!__instance.m_nview.IsValid())
			{
				return true;
			}
			HorseCartLink horseCartLink = HorseCartLink.Of(__instance);
			if ((Object)(object)horseCartLink == (Object)null || !horseCartLink.Tick(Time.deltaTime))
			{
				return true;
			}
			__instance.UpdateAudio(Time.fixedDeltaTime);
			__instance.UpdateSnow();
			return false;
		}
	}
	[HarmonyPatch(typeof(Vagon), "InUse")]
	internal static class VagonInUsePatch
	{
		private static bool Prefix(Vagon __instance, ref bool __result)
		{
			if (!HorseCart.IsOnHorse(__instance))
			{
				return true;
			}
			HorseCartLink horseCartLink = HorseCartLink.Of(__instance);
			__result = CartRules.InUse(onHorse: true, HorseCart.ContainerOpen(__instance), HorseCart.IsRidden(((Object)(object)horseCartLink != (Object)null) ? horseCartLink.Horse : null), vanillaInUse: false);
			return false;
		}
	}
	[HarmonyPatch(typeof(Vagon), "UpdateMass")]
	internal static class VagonMassPatch
	{
		private static bool Prefix(Vagon __instance)
		{
			return !HorseCart.IsOnHorse(__instance);
		}
	}
	[HarmonyPatch(typeof(Vagon), "DetachAll")]
	internal static class VagonDetachAllPatch
	{
		private static bool Prefix()
		{
			foreach (Vagon instance in Vagon.m_instances)
			{
				if (!HorseCart.IsOnHorse(instance))
				{
					instance.Detach();
				}
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(Vagon), "Interact")]
	internal static class VagonInteractPatch
	{
		private static bool Prefix(Vagon __instance, Humanoid character, bool hold, bool alt, ref bool __result)
		{
			if (hold)
			{
				return true;
			}
			HorseCartLink horseCartLink = HorseCartLink.Of(__instance);
			if ((Object)(object)horseCartLink == (Object)null || HorseCart.IsSiegeMachine(__instance))
			{
				return true;
			}
			bool flag = HorseCart.IsOnHorse(__instance);
			if (alt && (flag || (Object)(object)HorseCart.FindHitchableHorse(__instance, out var _) != (Object)null))
			{
				horseCartLink.PendingAltRequester = character;
				if (!__instance.m_nview.IsOwner())
				{
					__instance.m_nview.InvokeRPC("RPC_RequestOwn", Array.Empty<object>());
				}
				__result = false;
				return false;
			}
			if (flag)
			{
				__result = false;
				return false;
			}
			return true;
		}
	}
	[HarmonyPatch(typeof(Vagon), "RPC_RequestDenied")]
	internal static class VagonRequestDeniedPatch
	{
		private static void Postfix(Vagon __instance)
		{
			HorseCartLink horseCartLink = HorseCartLink.Of(__instance);
			if (!((Object)(object)horseCartLink == (Object)null) && !((Object)(object)horseCartLink.PendingAltRequester == (Object)null))
			{
				((Character)horseCartLink.PendingAltRequester).Message((MessageType)2, __instance.m_name + " is in use by someone else", 0, (Sprite)null, false);
				horseCartLink.PendingAltRequester = null;
			}
		}
	}
	[HarmonyPatch(typeof(Vagon), "GetHoverText")]
	internal static class VagonHoverTextPatch
	{
		private static void Postfix(Vagon __instance, ref string __result)
		{
			HorseCartLink horseCartLink = HorseCartLink.Of(__instance);
			if ((Object)(object)horseCartLink == (Object)null || HorseCart.IsSiegeMachine(__instance))
			{
				return;
			}
			bool flag = HorseCart.IsOnHorse(__instance);
			bool horseRidden = flag && HorseCart.IsRidden(horseCartLink.Horse);
			CartRules.HitchBlock block;
			bool hitchableHorseNearby = !flag && (Object)(object)HorseCart.FindHitchableHorse(__instance, out block) != (Object)null;
			switch (CartRules.ChooseHover(isSiegeMachine: false, flag, horseRidden, hitchableHorseNearby))
			{
			case CartRules.HoverLine.Hitch:
				__result += AltUseLine("$m2horse_cart_hitch");
				return;
			case CartRules.HoverLine.Unhitch:
				__result = Localization.instance.Localize(__instance.m_name) + AltUseLine("$m2horse_cart_unhitch");
				return;
			}
			if (flag)
			{
				__result = Localization.instance.Localize(__instance.m_name);
			}
		}

		private static string AltUseLine(string textKey)
		{
			string text = ((ZInput.IsNonClassicFunctionality() && ZInput.IsGamepadActive()) ? "$KEY_AltKeys + $KEY_Use" : "$KEY_AltPlace + $KEY_Use");
			return Localization.instance.Localize("\n[<color=yellow><b>" + text + "</b></color>] " + textKey);
		}
	}
	[HarmonyPatch(typeof(Vagon), "LateUpdate")]
	internal static class VagonRopePatch
	{
		private static void Postfix(Vagon __instance)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			HorseCartLink horseCartLink = HorseCartLink.Of(__instance);
			if (!((Object)(object)horseCartLink == (Object)null) && !((Object)(object)horseCartLink.Horse == (Object)null) && !((Object)(object)__instance.m_lineRenderer == (Object)null))
			{
				((Renderer)__instance.m_lineRenderer).enabled = true;
				__instance.m_lineRenderer.SetPosition(0, __instance.m_lineAttachPoints0.position);
				__instance.m_lineRenderer.SetPosition(1, HorseCart.HarnessPoint(horseCartLink.Horse));
				__instance.m_lineRenderer.SetPosition(2, __instance.m_lineAttachPoints1.position);
			}
		}
	}
}
namespace M2Horse.Horse.Cart
{
	internal static class HorseCart
	{
		internal const string HorsePrefabName = "M2Horse";

		internal static readonly int OnHorseKey = StringExtensionMethods.GetStableHashCode("M2Horse_CartOnHorse");

		internal static readonly Vector3 RearLocal = new Vector3(0f, 0.8f, -1f);

		private const float MessageRange = 20f;

		private static readonly Dictionary<Character, Sadle> s_sadles = new Dictionary<Character, Sadle>();

		internal static bool IsHorse(Character c)
		{
			return (Object)(object)c != (Object)null && Utils.GetPrefabName(((Component)c).gameObject) == "M2Horse";
		}

		internal static bool IsRidden(Character horse)
		{
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)horse == (Object)null || (Object)(object)horse.m_nview == (Object)null || !horse.m_nview.IsValid())
			{
				return false;
			}
			long num = horse.m_nview.GetZDO().GetLong(ZDOVars.s_user, 0L);
			if (num == 0)
			{
				return false;
			}
			Sadle val = SadleOf(horse);
			Vector3 position;
			return (Object)(object)val != (Object)null && TryPlayerPosition(num, out position) && Vector3.Distance(position, ((Component)val).transform.position) < val.m_maxUseRange;
		}

		private static Sadle SadleOf(Character horse)
		{
			if (!s_sadles.TryGetValue(horse, out var value))
			{
				if (s_sadles.Count > 64)
				{
					s_sadles.Clear();
				}
				value = (s_sadles[horse] = ((Component)horse).GetComponentInChildren<Sadle>(true));
			}
			return value;
		}

		internal static bool IsOnHorse(Vagon cart)
		{
			return (Object)(object)cart != (Object)null && (Object)(object)cart.m_nview != (Object)null && cart.m_nview.IsValid() && cart.m_nview.GetZDO().GetBool(OnHorseKey, false);
		}

		internal static bool IsSiegeMachine(Vagon cart)
		{
			return (Object)(object)((Component)cart).GetComponentInChildren<SiegeMachine>() != (Object)null;
		}

		internal static bool LegsDown(Vagon cart)
		{
			Catapult component = ((Component)cart).GetComponent<Catapult>();
			return (Object)(object)component != (Object)null && component.m_lockedLegs;
		}

		internal static Vector3 RearPoint(Character horse)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			return ((Component)horse).transform.TransformPoint(RearLocal);
		}

		internal static Vector3 HitchPoint(Vagon cart, Character horse)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			return ((Component)horse).transform.TransformPoint(cart.m_attachOffset);
		}

		internal static bool ContainerOpen(Vagon cart)
		{
			return (Object)(object)cart.m_container != (Object)null && cart.m_nview.IsValid() && cart.m_nview.GetZDO().GetInt(ZDOVars.s_inUse, 0) == 1;
		}

		internal static bool ShaftAreaLoaded(Vagon cart)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: 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_003d: 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_0050: 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_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: 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_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position = cart.m_attachPoint.position;
			float num = 4f;
			Vector2s zone = ZoneSystem.GetZone(ZNet.instance.GetReferencePosition());
			return ZNetScene.InActiveArea(position + new Vector3(num, 0f, num), zone) && ZNetScene.InActiveArea(position + new Vector3(0f - num, 0f, num), zone) && ZNetScene.InActiveArea(position + new Vector3(num, 0f, 0f - num), zone) && ZNetScene.InActiveArea(position + new Vector3(0f - num, 0f, 0f - num), zone);
		}

		internal static bool OwnerHolds(long owner, Vector3 a, Vector3 b)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: 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_002f: 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_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			Vector3 position;
			if (owner == ZDOMan.GetSessionID())
			{
				position = ZNet.instance.GetReferencePosition();
			}
			else if (!TryPlayerPosition(owner, out position))
			{
				return false;
			}
			Vector2s zone = ZoneSystem.GetZone(position);
			return ZNetScene.InActiveArea(a, zone) && ZNetScene.InActiveArea(b, zone);
		}

		private static bool TryPlayerPosition(long sessionId, out Vector3 position)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: 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)
			//IL_0074: 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_004a: Unknown result type (might be due to invalid IL or missing references)
			foreach (Player allPlayer in Player.GetAllPlayers())
			{
				if (!((Object)(object)allPlayer == (Object)null))
				{
					ZDOID zDOID = ((Character)allPlayer).GetZDOID();
					if (((ZDOID)(ref zDOID)).UserID == sessionId)
					{
						position = ((Component)allPlayer).transform.position;
						return true;
					}
				}
			}
			position = Vector3.zero;
			return false;
		}

		internal static Vector3 HarnessPoint(Character horse)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			Sadle val = SadleOf(horse);
			return ((Object)(object)val != (Object)null) ? ((Component)val).transform.position : (((Component)horse).transform.position + Vector3.up);
		}

		internal static Character FindHitchableHorse(Vagon cart, out CartRules.HitchBlock block)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			float distance;
			Character val = NearestHorse(cart, out distance);
			CartRules.HitchCandidate c = new CartRules.HitchCandidate
			{
				IsSiegeMachine = IsSiegeMachine(cart),
				LegsDown = LegsDown(cart),
				CartUpY = ((Component)cart).transform.up.y,
				Distance = (((Object)(object)val != (Object)null) ? distance : float.MaxValue)
			};
			if ((Object)(object)val != (Object)null)
			{
				Vagon val2 = CartOf(val);
				c.Tamed = val.IsTamed();
				c.Saddled = HasSaddle(val);
				c.Ridden = IsRidden(val);
				c.HorseBusy = (Object)(object)val2 != (Object)null && (Object)(object)val2 != (Object)(object)cart;
			}
			block = CartRules.CheckHitch(c);
			return (block == CartRules.HitchBlock.None) ? val : null;
		}

		internal static Character FindLinkedHorse(Vagon cart)
		{
			float distance;
			Character val = NearestHorse(cart, out distance);
			if ((Object)(object)val == (Object)null || distance > 2f || !val.IsTamed() || !HasSaddle(val))
			{
				return null;
			}
			Vagon val2 = CartOf(val);
			return ((Object)(object)val2 == (Object)null || (Object)(object)val2 == (Object)(object)cart) ? val : null;
		}

		internal static Vagon CartOf(Character horse)
		{
			if ((Object)(object)horse == (Object)null)
			{
				return null;
			}
			foreach (Vagon instance in Vagon.m_instances)
			{
				HorseCartLink horseCartLink = (((Object)(object)instance != (Object)null) ? HorseCartLink.Of(instance) : null);
				if ((Object)(object)horseCartLink != (Object)null && (Object)(object)horseCartLink.Horse == (Object)(object)horse)
				{
					return instance;
				}
			}
			return null;
		}

		internal static void Hitch(Vagon cart, Character horse)
		{
			if ((Object)(object)cart.m_attachJoin != (Object)null)
			{
				cart.Detach();
			}
			ZDO zDO = cart.m_nview.GetZDO();
			zDO.Set(ZDOVars.s_attachJointHash, true);
			zDO.Set(OnHorseKey, true);
			HorseCartLink.Of(cart)?.Link(horse);
		}

		internal static void Unhitch(Vagon cart, string messageKey = null)
		{
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			cart.m_nview.GetZDO().Set(OnHorseKey, false);
			cart.Detach();
			HorseCartLink.Of(cart)?.Release();
			if (messageKey != null)
			{
				Player.MessageAllInRange(((Component)cart).transform.position, 20f, (MessageType)2, messageKey, (Sprite)null);
			}
		}

		private static Character NearestHorse(Vagon cart, out float distance)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			Character result = null;
			distance = float.MaxValue;
			Vector3 position = cart.m_attachPoint.position;
			foreach (Character allCharacter in Character.GetAllCharacters())
			{
				if (IsHorse(allCharacter) && !allCharacter.IsDead())
				{
					float num = Vector3.Distance(RearPoint(allCharacter), position);
					if (num < distance)
					{
						distance = num;
						result = allCharacter;
					}
				}
			}
			return result;
		}

		private static bool HasSaddle(Character horse)
		{
			Tameable component = ((Component)horse).GetComponent<Tameable>();
			return (Object)(object)component != (Object)null && component.HaveSaddle();
		}
	}
	internal class HorseCartLink : MonoBehaviour
	{
		private const float CartMassHitched = 150f;

		private const float HorseExtraMassHitched = 400f;

		private const float RollLimit = 25f;

		private const float PitchLimit = 35f;

		private const float YawLimit = 70f;

		private Vagon _cart;

		private float _missingSeconds;

		private Collider[] _ignoredCartColliders;

		private Collider[] _ignoredHorseColliders;

		private float[] _cartMassesBefore;

		private Character _extraMassHorse;

		internal Humanoid PendingAltRequester;

		private static readonly Dictionary<Vagon, HorseCartLink> s_byCart = new Dictionary<Vagon, HorseCartLink>();

		internal Character Horse { get; private set; }

		internal static HorseCartLink Of(Vagon cart)
		{
			HorseCartLink value;
			return s_byCart.TryGetValue(cart, out value) ? value : null;
		}

		private void Awake()
		{
			_cart = ((Component)this).GetComponent<Vagon>();
			s_byCart[_cart] = this;
		}

		internal void Link(Character horse)
		{
			Horse = horse;
			_missingSeconds = 0f;
			if ((Object)(object)horse != (Object)null)
			{
				horse.m_runSpeed = 8f;
				IgnoreCollisions(horse);
			}
		}

		private void OnDestroy()
		{
			Release();
			s_byCart.Remove(_cart);
		}

		internal bool Tick(float dt)
		{
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d3: Unknown result type (might be due to invalid IL or missing references)
			ZNetView nview = _cart.m_nview;
			ZDO zDO = nview.GetZDO();
			if ((Object)(object)PendingAltRequester != (Object)null && nview.IsOwner())
			{
				HandleAltRequest(zDO);
			}
			if (!zDO.GetBool(HorseCart.OnHorseKey, false))
			{
				if ((Object)(object)Horse != (Object)null)
				{
					Release();
				}
				return false;
			}
			if ((Object)(object)Horse == (Object)null)
			{
				Character val = HorseCart.FindLinkedHorse(_cart);
				if ((Object)(object)val != (Object)null)
				{
					Link(val);
				}
			}
			else if (!CartRules.KeepLink((Object)(object)_cart.m_attachJoin != (Object)null, Vector3.Distance(HorseCart.HitchPoint(_cart, Horse), _cart.m_attachPoint.position)))
			{
				Release();
			}
			_missingSeconds = CartRules.AdvanceMissing(_missingSeconds, (Object)(object)Horse != (Object)null, HorseCart.ShaftAreaLoaded(_cart), dt);
			if ((Object)(object)Horse != (Object)null)
			{
				SyncOwnerAndJoint(zDO);
			}
			else if ((Object)(object)_cart.m_attachJoin != (Object)null)
			{
				DropJointLocal();
			}
			if (nview.IsOwner())
			{
				CheckUnhitch();
			}
			return true;
		}

		internal void Release()
		{
			if ((Object)(object)_cart != (Object)null && (Object)(object)_cart.m_attachJoin != (Object)null)
			{
				DropJointLocal();
			}
			RestoreMasses();
			RestoreCollisions();
			if ((Object)(object)Horse != (Object)null && (Object)(object)HorseCreature.Prefab != (Object)null)
			{
				Horse.m_runSpeed = HorseCreature.Prefab.GetComponent<Character>().m_runSpeed;
			}
			Horse = null;
			_missingSeconds = 0f;
		}

		private void IgnoreCollisions(Character horse)
		{
			RestoreCollisions();
			_ignoredCartColliders = ((Component)_cart).GetComponentsInChildren<Collider>();
			_ignoredHorseColliders = ((Component)horse).GetComponentsInChildren<Collider>();
			SetIgnored(ignore: true);
		}

		private void RestoreCollisions()
		{
			SetIgnored(ignore: false);
			_ignoredCartColliders = null;
			_ignoredHorseColliders = null;
		}

		private void SetIgnored(bool ignore)
		{
			if (_ignoredCartColliders == null || _ignoredHorseColliders == null)
			{
				return;
			}
			Collider[] ignoredCartColliders = _ignoredCartColliders;
			foreach (Collider val in ignoredCartColliders)
			{
				Collider[] ignoredHorseColliders = _ignoredHorseColliders;
				foreach (Collider val2 in ignoredHorseColliders)
				{
					if ((Object)(object)val != (Object)null && (Object)(object)val2 != (Object)null)
					{
						Physics.IgnoreCollision(val, val2, ignore);
					}
				}
			}
		}

		private void ApplyMasses()
		{
			_cartMassesBefore = new float[_cart.m_bodies.Length];
			for (int i = 0; i < _cart.m_bodies.Length; i++)
			{
				_cartMassesBefore[i] = _cart.m_bodies[i].mass;
			}
			_cart.SetMass(150f);
			_extraMassHorse = Horse;
			Horse.SetExtraMass(400f);
		}

		private void RestoreMasses()
		{
			if (_cartMassesBefore != null && (Object)(object)_cart != (Object)null)
			{
				for (int i = 0; i < _cart.m_bodies.Length && i < _cartMassesBefore.Length; i++)
				{
					if ((Object)(object)_cart.m_bodies[i] != (Object)null)
					{
						_cart.m_bodies[i].mass = _cartMassesBefore[i];
					}
				}
			}
			_cartMassesBefore = null;
			if ((Object)(object)_extraMassHorse != (Object)null)
			{
				_extraMassHorse.SetExtraMass(0f);
			}
			_extraMassHorse = null;
		}

		private void HandleAltRequest(ZDO zdo)
		{
			Humanoid pendingAltRequester = PendingAltRequester;
			PendingAltRequester = null;
			if (zdo.GetBool(HorseCart.OnHorseKey, false))
			{
				HorseCart.Unhitch(_cart);
				return;
			}
			CartRules.HitchBlock block;
			Character val = HorseCart.FindHitchableHorse(_cart, out block);
			if ((Object)(object)val != (Object)null)
			{
				HorseCart.Hitch(_cart, val);
			}
			else if ((Object)(object)pendingAltRequester != (Object)null)
			{
				((Character)pendingAltRequester).Message((MessageType)2, "$msg_cart_incorrectposition", 0, (Sprite)null, false);
			}
		}

		private void SyncOwnerAndJoint(ZDO zdo)
		{
			//IL_005d: 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_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_0079: Unknown result type (might be due to invalid IL or missing references)
			//IL_0083: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			ZDO zDO = Horse.m_nview.GetZDO();
			if (zDO != null)
			{
				long sessionID = ZDOMan.GetSessionID();
				long owner = zdo.GetOwner();
				long owner2 = zDO.GetOwner();
				bool cartOwnerHolds = false;
				bool horseOwnerHolds = false;
				if (owner != 0L && owner2 != 0L && owner != owner2)
				{
					Vector3 position = ((Component)_cart).transform.position;
					Vector3 position2 = ((Component)Horse).transform.position;
					cartOwnerHolds = HorseCart.OwnerHolds(owner, position, position2);
					horseOwnerHolds = HorseCart.OwnerHolds(owner2, position, position2);
				}
				switch (CartRules.ResolveOwner(sessionID, owner, owner2, HorseCart.IsRidden(Horse), cartOwnerHolds, horseOwnerHolds))
				{
				case CartRules.OwnerAction.GiveCartToHorseOwner:
					zdo.SetOwner(zDO.GetOwner());
					break;
				case CartRules.OwnerAction.GiveHorseToCartOwner:
					zDO.SetOwner(zdo.GetOwner());
					break;
				}
				bool flag = CartRules.ShouldHaveJoint(sessionID, zdo.GetOwner(), zDO.GetOwner());
				if (flag && (Object)(object)_cart.m_attachJoin == (Object)null)
				{
					BuildJoint();
				}
				else if (!flag && (Object)(object)_cart.m_attachJoin != (Object)null)
				{
					DropJointLocal();
				}
			}
		}

		private void CheckUnhitch()
		{
			switch (CartRules.CheckWhileHitched((Object)(object)Horse != (Object)null, (Object)(object)Horse != (Object)null && Horse.IsSwimming(), HorseCart.LegsDown(_cart), _missingSeconds))
			{
			case CartRules.UnhitchReason.Swimming:
				HorseCart.Unhitch(_cart, "$m2horse_cart_unhitched_water");
				break;
			case CartRules.UnhitchReason.LegsDown:
			case CartRules.UnhitchReason.MissingHorse:
				HorseCart.Unhitch(_cart);
				break;
			}
		}

		private void BuildJoint()
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: 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_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f8: 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_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_011c: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			ConfigurableJoint val = ((Component)_cart).gameObject.AddComponent<ConfigurableJoint>();
			((Joint)val).autoConfigureConnectedAnchor = false;
			((Joint)val).anchor = _cart.m_attachPoint.localPosition;
			((Joint)val).connectedAnchor = _cart.m_attachOffset;
			((Joint)val).breakForce = float.PositiveInfinity;
			((Joint)val).breakTorque = float.PositiveInfinity;
			val.xMotion = (ConfigurableJointMotion)0;
			val.yMotion = (ConfigurableJointMotion)0;
			val.zMotion = (ConfigurableJointMotion)0;
			val.angularXMotion = (ConfigurableJointMotion)1;
			val.angularYMotion = (ConfigurableJointMotion)1;
			val.angularZMotion = (ConfigurableJointMotion)1;
			SoftJointLimit val2 = default(SoftJointLimit);
			((SoftJointLimit)(ref val2)).limit = -35f;
			val.lowAngularXLimit = val2;
			val2 = default(SoftJointLimit);
			((SoftJointLimit)(ref val2)).limit = 35f;
			val.highAngularXLimit = val2;
			val2 = default(SoftJointLimit);
			((SoftJointLimit)(ref val2)).limit = 70f;
			val.angularYLimit = val2;
			val2 = default(SoftJointLimit);
			((SoftJointLimit)(ref val2)).limit = 25f;
			val.angularZLimit = val2;
			Quaternion rotation = ((Component)_cart).transform.rotation;
			((Component)_cart).transform.rotation = RestRotation();
			Physics.SyncTransforms();
			((Joint)val).connectedBody = Horse.m_body;
			((Component)_cart).transform.rotation = rotation;
			Physics.SyncTransforms();
			_cart.m_attachJoin = val;
			_cart.m_attachedObject = ((Component)Horse).gameObject;
			ApplyMasses();
		}

		private Quaternion RestRotation()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: 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_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: 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_008d: 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_00ae: Unknown result type (might be due to invalid IL or missing references)
			Vector3 val = ((Component)_cart).transform.InverseTransformPoint(_cart.m_attachPoint.position);
			val.y = 0f;
			Vector3 forward = ((Component)Horse).transform.forward;
			forward.y = 0f;
			if (((Vector3)(ref val)).sqrMagnitude < 0.0001f || ((Vector3)(ref forward)).sqrMagnitude < 0.0001f)
			{
				return Quaternion.Euler(0f, ((Component)Horse).transform.eulerAngles.y, 0f);
			}
			return Quaternion.LookRotation(forward) * Quaternion.Inverse(Quaternion.LookRotation(val));
		}

		private void DropJointLocal()
		{
			Object.Destroy((Object)(object)_cart.m_attachJoin);
			_cart.m_attachJoin = null;
			_cart.m_attachedObject = null;
			RestoreMasses();
		}
	}
}
namespace M2Horse.Core
{
	public static class CartRules
	{
		public enum OwnerAction
		{
			None,
			GiveCartToHorseOwner,
			GiveHorseToCartOwner
		}

		public enum HitchBlock
		{
			None,
			SiegeMachine,
			LegsDown,
			Tipped,
			NotTamed,
			NoSaddle,
			Ridden,
			HorseBusy,
			TooFar
		}

		public struct HitchCandidate
		{
			public bool IsSiegeMachine;

			public bool LegsDown;

			public bool Tamed;

			public bool Saddled;

			public bool Ridden;

			public bool HorseBusy;

			public float CartUpY;

			public float Distance;
		}

		public enum UnhitchReason
		{
			None,
			Swimming,
			LegsDown,
			MissingHorse
		}

		public enum HoverLine
		{
			None,
			Hitch,
			Unhitch
		}

		public const float HitchedRunSpeed = 8f;

		public const float HitchedGallopStaminaFactor = 1.5f;

		public const float MaxHitchDistance = 2f;

		public const float MinUprightY = 0.1f;

		public const float MissingHorseGraceSeconds = 10f;

		public const float MaxLinkDistance = 4f;

		public static OwnerAction ResolveOwner(long local, long cartOwner, long horseOwner, bool horseRidden, bool cartOwnerHolds, bool horseOwnerHolds)
		{
			if (cartOwner == 0L || horseOwner == 0L || cartOwner == horseOwner)
			{
				return OwnerAction.None;
			}
			bool flag;
			if (horseRidden)
			{
				flag = true;
			}
			else if (cartOwnerHolds)
			{
				flag = false;
			}
			else
			{
				if (!horseOwnerHolds)
				{
					return OwnerAction.None;
				}
				flag = true;
			}
			if (flag)
			{
				return (local == cartOwner) ? OwnerAction.GiveCartToHorseOwner : OwnerAction.None;
			}
			return (local == horseOwner) ? OwnerAction.GiveHorseToCartOwner : OwnerAction.None;
		}

		public static float AdvanceMissing(float missingSeconds, bool horseFound, bool areaLoaded, float dt)
		{
			if (horseFound)
			{
				return 0f;
			}
			return areaLoaded ? (missingSeconds + dt) : missingSeconds;
		}

		public static bool KeepLink(bool hasJoint, float distance)
		{
			return hasJoint || distance <= 4f;
		}

		public static bool ShouldHaveJoint(long local, long cartOwner, long horseOwner)
		{
			return local != 0L && cartOwner == local && horseOwner == local;
		}

		public static bool InUse(bool onHorse, bool containerInUse, bool horseRidden, bool vanillaInUse)
		{
			return onHorse ? (containerInUse || horseRidden) : vanillaInUse;
		}

		public static HitchBlock CheckHitch(HitchCandidate c)
		{
			if (c.IsSiegeMachine)
			{
				return HitchBlock.SiegeMachine;
			}
			if (c.LegsDown)
			{
				return HitchBlock.LegsDown;
			}
			if (c.CartUpY < 0.1f)
			{
				return HitchBlock.Tipped;
			}
			if (!c.Tamed)
			{
				return HitchBlock.NotTamed;
			}
			if (!c.Saddled)
			{
				return HitchBlock.NoSaddle;
			}
			if (c.Ridden)
			{
				return HitchBlock.Ridden;
			}
			if (c.HorseBusy)
			{
				return HitchBlock.HorseBusy;
			}
			if (c.Distance > 2f)
			{
				return HitchBlock.TooFar;
			}
			return HitchBlock.None;
		}

		public static UnhitchReason CheckWhileHitched(bool horseFound, bool horseSwimming, bool legsDown, float missingSeconds)
		{
			if (!horseFound)
			{
				return (missingSeconds >= 10f) ? UnhitchReason.MissingHorse : UnhitchReason.None;
			}
			if (horseSwimming)
			{
				return UnhitchReason.Swimming;
			}
			if (legsDown)
			{
				return UnhitchReason.LegsDown;
			}
			return UnhitchReason.None;
		}

		public static HoverLine ChooseHover(bool isSiegeMachine, bool onHorse, bool horseRidden, bool hitchableHorseNearby)
		{
			if (isSiegeMachine)
			{
				return HoverLine.None;
			}
			if (onHorse)
			{
				return (!horseRidden) ? HoverLine.Unhitch : HoverLine.None;
			}
			return hitchableHorseNearby ? HoverLine.Hitch : HoverLine.None;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class <a308c4ea-864e-4b39-9631-13b77b9a075b>IgnoresAccessChecksToAttribute : Attribute
	{
		public <a308c4ea-864e-4b39-9631-13b77b9a075b>IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}
namespace M2Core
{
	internal static class CoreInfo
	{
		public const string Version = "0.12.0";
	}
}
namespace M2Core.UI
{
	internal static class UiButton
	{
		public static Button Create(Transform parent, string label, UiPlacement placement, Action onClick = null, UiTextStyle? text = null)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0043: Unknown result type (might be due to invalid IL or missing references)
			//IL_004d: Expected O, but got Unknown
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Expected O, but got Unknown
			GameObject val = DefaultControls.CreateButton(new Resources
			{
				standard = UiSprites.Get("button")
			});
			val.transform.SetParent(parent, false);
			placement.ApplyTo((RectTransform)val.transform);
			Button component = val.GetComponent<Button>();
			Style(component, text);
			Text componentInChildren = val.GetComponentInChildren<Text>(true);
			if ((Object)(object)componentInChildren != (Object)null)
			{
				componentInChildren.text = label;
			}
			if (onClick != null)
			{
				((UnityEvent)component.onClick).AddListener((UnityAction)delegate
				{
					onClick();
				});
			}
			return component;
		}

		public static void Style(Button button, UiTextStyle? text = null)
		{
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			GameObject gameObject = ((Component)button).gameObject;
			Image component = gameObject.GetComponent<Image>();
			if ((Object)(object)component != (Object)null)
			{
				component.sprite = UiSprites.Get("button");
				component.type = (Type)1;
				component.pixelsPerUnitMultiplier = UiScene.SlicedPixelsPerUnit;
				((Selectable)button).image = component;
			}
			ButtonSfx val = gameObject.GetComponent<ButtonSfx>();
			if ((Object)(object)val == (Object)null)
			{
				val = gameObject.AddComponent<ButtonSfx>();
			}
			val.m_sfxPrefab = AssetLookup.Find<GameObject>("sfx_gui_button");
			val.m_selectSfxPrefab = null;
			((Selectable)button).colors = UiTheme.ButtonColors;
			Text componentInChildren = gameObject.GetComponentInChildren<Text>(true);
			if ((Object)(object)componentInChildren != (Object)null)
			{
				UiText.Style(componentInChildren, text ?? UiTextStyle.Button);
			}
		}
	}
	internal static class UiContextMenu
	{
		private sealed class Row
		{
			public RectTransform Rect;

			public Button Button;

			public Image Highlight;

			public Text Caption;
		}

		private sealed class MenuOwner
		{
			public override string ToString()
			{
				return "UiContextMenu (" + typeof(MenuOwner).Assembly.GetName().Name + ")";
			}
		}

		public const int GroupPriority = 7;

		private static readonly object Owner = new MenuOwner();

		private static readonly Action<bool> Back = delegate
		{
			Close();
		};

		private static readonly List<UiMenuItem> Items = new List<UiMenuItem>();

		private static readonly List<Row> Rows = new List<Row>();

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

		private static GameObject _catcher;

		private static RectTransform _panel;

		private static Image _background;

		private static GameObject _gamepadGroup;

		private static UiMenuStyle _style = UiMenuStyle.Default;

		private static int _highlighted = -1;

		private static bool _open;

		public static bool IsOpen
		{
			get
			{
				if (_open)
				{
					return (Object)(object)_catcher != (Object)null;
				}
				return false;
			}
		}

		public static void Open(IReadOnlyList<UiMenuItem> items, Vector2 screenPoint, UiMenuStyle style = null)
		{
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001a: Expected O, but got Unknown
			//IL_001b: 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)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			if (Show(items, style))
			{
				RectTransform val = (RectTransform)_catcher.transform;
				Vector2 point = default(Vector2);
				RectTransformUtility.ScreenPointToLocalPointInRectangle(val, screenPoint, (Camera)null, ref point);
				_panel.anchoredPosition = UiContextMenuLogic.TopLeftAt(val.rect, point, _panel.sizeDelta);
				Register();
			}
		}

		public static void Open(IReadOnlyList<UiMenuItem> items, RectTransform anchor, UiMenuStyle style = null)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_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)
			if ((Object)(object)anchor == (Object)null)
			{
				throw new ArgumentNullException("anchor");
			}
			if (Show(items, style))
			{
				RectTransform val = (RectTransform)_catcher.transform;
				_panel.anchoredPosition = UiContextMenuLogic.TopLeftBeside(val.rect, RectIn(val, anchor), _panel.sizeDelta);
				Register();
			}
		}

		public static void Close()
		{
			Release();
			if ((Object)(object)_catcher != (Object)null)
			{
				_catcher.SetActive(false);
			}
		}

		private static bool Show(IReadOnlyList<UiMenuItem> items, UiMenuStyle style)
		{
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
			if (items == null || items.Count == 0 || !EnsureBuilt())
			{
				Close();
				return false;
			}
			_style = style ?? UiMenuStyle.Default;
			Items.Clear();
			for (int i = 0; i < items.Count; i++)
			{
				Items.Add(items[i]);
			}
			_catcher.SetActive(true);
			_background.sprite = (((Object)(object)_style.Background != (Object)null) ? _style.Background : UiSprites.Get("text_field"));
			_background.type = (Type)1;
			_background.pixelsPerUnitMultiplier = UiScene.SlicedPixelsPerUnit;
			((Graphic)_background).color = _style.BackgroundColor;
			_panel.sizeDelta = UiContextMenuLogic.Size(_style, Items.Count, FillRows());
			return true;
		}

		private static void Register()
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Expected O, but got Unknown
			_open = true;
			ZInput.ResetButtonStatus("JoyButtonA");
			UiWindowStack.Open(Owner, (RectTransform)_catcher.transform, Back);
			UiInputBlock.Push(Owner);
			SetHighlight(ZInput.IsGamepadActive() ? UiContextMenuLogic.FirstEnabled(Items) : (-1));
			UpdateGamepadGroup(UiWindowStack.IsTop(Owner));
		}

		private static void Release()
		{
			if (_open)
			{
				_open = false;
				_highlighted = -1;
				UiWindowStack.Close(Owner);
				UiInputBlock.Pop(Owner);
			}
		}

		internal static void Tick()
		{
			if (!_open)
			{
				return;
			}
			bool num = UiWindowStack.IsTop(Owner);
			UpdateGamepadGroup(num);
			if (!num || !ZInput.IsGamepadActive())
			{
				return;
			}
			if (ZInput.GetButtonDown("JoyDPadDown") || ZInput.GetButtonDown("JoyLStickDown"))
			{
				Move(1);
			}
			else if (ZInput.GetButtonDown("JoyDPadUp") || ZInput.GetButtonDown("JoyLStickUp"))
			{
				Move(-1);
			}
			else if (ZInput.GetButtonDown("JoyButtonA"))
			{
				ZInput.ResetButtonStatus("JoyButtonA");
				if (UiContextMenuLogic.CanPick(Items, _highlighted))
				{
					((UnityEvent)Rows[_highlighted].Button.onClick).Invoke();
				}
			}
		}

		private static void Pick(int index)
		{
			if (!_open || !UiContextMenuLogic.CanPick(Items, index))
			{
				return;
			}
			UiMenuItem uiMenuItem = Items[index];
			Close();
			try
			{
				uiMenuItem.Action?.Invoke();
			}
			catch (Exception arg)
			{
				Debug.LogError((object)$"[M2Core] UiContextMenu: Fehler in der Aktion „{uiMenuItem.Caption}“: {arg}");
			}
		}

		private static void Move(int direction)
		{
			int num = UiContextMenuLogic.Step(Items, _highlighted, direction);
			if (num != _highlighted)
			{
				SetHighlight(num);
				if ((Object)(object)GamepadRumble.instance != (Object)null)
				{
					GamepadRumble.instance.PlayGlobalSelectVibration();
				}
			}
		}

		internal static void PointerEntered(int index)
		{
			if (_open && !ZInput.IsExclusiveGamepadActive())
			{
				SetHighlight(UiContextMenuLogic.Hover(Items, index));
			}
		}

		internal static void PointerExited(int index)
		{
			if (_open && !ZInput.IsExclusiveGamepadActive() && _highlighted == index)
			{
				SetHighlight(-1);
			}
		}

		internal static void CatcherDestroyed(GameObject catcher)
		{
			if (catcher == _catcher)
			{
				Release();
			}
		}

		private static void SetHighlight(int index)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			_highlighted = index;
			for (int i = 0; i < Rows.Count; i++)
			{
				((Graphic)Rows[i].Highlight).color = ((i == index) ? _style.HighlightColor : Color.clear);
			}
		}

		private static void UpdateGamepadGroup(bool top)
		{
			bool flag = top && ZInput.IsGamepadActive();
			if ((Object)(object)_gamepadGroup != (Object)null && _gamepadGroup.activeSelf != flag)
			{
				_gamepadGroup.SetActive(flag);
			}
		}

		private static float FillRows()
		{
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			UiTextStyle uiTextStyle = UiTextStyle.Body.WithSize(_style.FontSize);
			float num = _style.PaddingX - _style.PaddingY;
			float num2 = 0f;
			for (int i = 0; i < Items.Count; i++)
			{
				if (i == Rows.Count)
				{
					Rows.Add(CreateRow(i));
				}
				Row row = Rows[i];
				UiMenuItem uiMenuItem = Items[i];
				((Component)row.Rect).gameObject.SetActive(true);
				row.Rect.offsetMin = new Vector2(_style.PaddingY, 0f - (_style.PaddingY + (float)(i + 1) * _style.RowHeight));
				row.Rect.offsetMax = new Vector2(0f - _style.PaddingY, 0f - (_style.PaddingY + (float)i * _style.RowHeight));
				((Selectable)row.Button).interactable = uiMenuItem.Enabled;
				row.Caption.text = uiMenuItem.Caption ?? "";
				UiText.Style(row.Caption, uiTextStyle.WithColor(uiMenuItem.Enabled ? _style.TextColor : _style.DisabledTextColor));
				((Graphic)row.Caption).rectTransform.offsetMin = new Vector2(num, 0f);
				((Graphic)row.Caption).rectTransform.offsetMax = new Vector2(0f - num, 0f);
				num2 = Mathf.Max(num2, row.Caption.preferredWidth);
			}
			for (int j = Items.Count; j < Rows.Count; j++)
			{
				((Component)Rows[j].Rect).gameObject.SetActive(false);
			}
			return num2;
		}

		private static Row CreateRow(int index)
		{
			//IL_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: 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_0079: 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_0085: Expected O, but got Unknown
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_009b: 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_00ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: 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_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0109: Expected O, but got Unknown
			//IL_0109: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("Row" + index, new Type[4]
			{
				typeof(RectTransform),
				typeof(Image),
				typeof(Button),
				typeof(UiContextMenuRow)
			})
			{
				layer = 5
			};
			val.transform.SetParent((Transform)(object)_panel, false);
			RectTransform val2 = (RectTransform)val.transform;
			val2.anchorMin = new Vector2(0f, 1f);
			val2.anchorMax = Vector2.one;
			val2.pivot = new Vector2(0.5f, 1f);
			Image component = val.GetComponent<Image>();
			((Graphic)component).color = Color.clear;
			Button component2 = val.GetComponent<Button>();
			((Selectable)component2).transition = (Transition)0;
			Navigation navigation = default(Navigation);
			((Navigation)(ref navigation)).mode = (Mode)0;
			((Selectable)component2).navigation = navigation;
			((UnityEvent)component2.onClick).AddListener((UnityAction)delegate
			{
				Pick(index);
			});
			ButtonSfx obj = val.AddComponent<ButtonSfx>();
			obj.m_sfxPrefab = AssetLookup.Find<GameObject>("sfx_gui_button");
			obj.m_selectSfxPrefab = null;
			val.GetComponent<UiContextMenuRow>().Index = index;
			Text val3 = UiText.Create(val.transform, "", UiPlacement.Stretch(), UiTextStyle.Body);
			((Graphic)val3).raycastTarget = false;
			val3.supportRichText = false;
			val3.horizontalOverflow = (HorizontalWrapMode)1;
			val3.verticalOverflow = (VerticalWrapMode)1;
			return new Row
			{
				Rect = val2,
				Button = component2,
				Highlight = component,
				Caption = val3
			};
		}

		private static bool EnsureBuilt()
		{
			//IL_0082: Unknown result type (might be due to invalid IL or missing references)
			//IL_0088: Expected O, but got Unknown
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Expected O, but got Unknown
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0110: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_012f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Expected O, but got Unknown
			//IL_0143: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Unknown result type (might be due to invalid IL or missing references)
			//IL_0159: Unknown result type (might be due to invalid IL or missing references)
			//IL_0165: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Expected O, but got Unknown
			RectTransform front = UiRoot.Front;
			if ((Object)(object)front == (Object)null)
			{
				return false;
			}
			if ((Object)(object)_catcher != (Object)null && (Object)(object)_catcher.transform.parent == (Object)(object)front)
			{
				return true;
			}
			if ((Object)(object)_catcher != (Object)null)
			{
				Release();
				Object.Destroy((Object)(object)_catcher);
			}
			Rows.Clear();
			GameObject val = new GameObject("UiContextMenu", new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			});
			val.layer = 5;
			val.transform.SetParent((Transform)(object)front, false);
			val.SetActive(false);
			UiPlacement.Stretch().ApplyTo((RectTransform)val.transform);
			((Graphic)val.GetComponent<Image>()).color = Color.clear;
			val.AddComponent<UiContextMenuCatcher>();
			GameObject val2 = new GameObject("Panel", new Type[2]
			{
				typeof(RectTransform),
				typeof(Image)
			})
			{
				layer = 5
			};
			val2.transform.SetParent(val.transform, false);
			_panel = (RectTransform)val2.transform;
			Vector2 anchor = new Vector2(0.5f, 0.5f);
			Vector2 zero = Vector2.zero;
			Vector2? pivot = new Vector2(0f, 1f);
			UiPlacement.At(anchor, zero, default(Vector2), pivot).ApplyTo(_panel);
			_background = val2.GetComponent<Image>();
			_gamepadGroup = new GameObject("GamepadGroup", new Type[1] { typeof(RectTransform) });
			_gamepadGroup.transform.SetParent(val.transform, false);
			_gamepadGroup.SetActive(false);
			_gamepadGroup.AddComponent<UIGroupHandler>().m_groupPriority = 7;
			_catcher = val;
			return true;
		}

		private static Rect R