Decompiled source of Kratyr Companions v0.4.2

BepInEx/plugins/KratyrCompanions.dll

Decompiled 2 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Utilities;
using YamlDotNet.RepresentationModel;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("KratyrCompanions")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("KratyrCompanions")]
[assembly: AssemblyTitle("KratyrCompanions")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace Kratyr.Companions
{
	internal static class CompanionBond
	{
		internal const int Capacity = 8;

		private static readonly int[] Players = Keys("Player");

		private static readonly int[] Values = Keys("Value");

		private static readonly int[] Updated = Keys("Updated");

		private static readonly int CombatKey = StringExtensionMethods.GetStableHashCode("KratyrCompanions.BondCombat");

		private static int[] Keys(string field)
		{
			int[] array = new int[8];
			for (int i = 0; i < array.Length; i++)
			{
				array[i] = StringExtensionMethods.GetStableHashCode("KratyrCompanions.Bond." + field + "." + i);
			}
			return array;
		}

		internal static bool IsPartner(CompanionState state, long player)
		{
			if (player != 0L && state.Owner != 0L)
			{
				if (player != state.Owner)
				{
					return player == state.Borrower;
				}
				return true;
			}
			return false;
		}

		internal static float Value(ZDO data, long player)
		{
			if (player == 0L)
			{
				return 0f;
			}
			for (int i = 0; i < 8; i++)
			{
				if (data.GetLong(Players[i], 0L) == player)
				{
					return Effective(data, i, Loyalty.Now);
				}
			}
			return 0f;
		}

		private static float Effective(ZDO data, int slot, long now)
		{
			float num = data.GetFloat(Values[slot], 0f);
			long num2 = data.GetLong(Updated[slot], now);
			EnvMan instance = EnvMan.instance;
			if (!Object.op_Implicit((Object)(object)instance) || instance.m_dayLengthSec <= 0 || !TamedStatRules.Finite(num))
			{
				if (!TamedStatRules.Finite(num))
				{
					return 0f;
				}
				return Math.Max(0f, Math.Min(100f, num));
			}
			var (graceDays, dailyLoss) = TamedProgression.BondDecay;
			return TamedStatRules.BondAfterAbsence(num, (double)(now - num2) / (double)instance.m_dayLengthSec, graceDays, dailyLoss);
		}

		internal static bool Gain(ZDO data, CompanionState state, long player, float amount, long now)
		{
			if (!IsPartner(state, player) || !(amount > 0f))
			{
				return false;
			}
			int num = -1;
			long num2 = long.MaxValue;
			for (int i = 0; i < 8; i++)
			{
				long num3 = data.GetLong(Players[i], 0L);
				if (num3 == player)
				{
					float num4 = data.GetFloat(Values[i], 0f);
					float num5 = Math.Min(100f, Effective(data, i, now) + amount);
					if (num4 != num5)
					{
						data.Set(Values[i], num5);
					}
					if (num4 != num5 || now - data.GetLong(Updated[i], 0L) >= 60)
					{
						data.Set(Updated[i], now);
					}
					return true;
				}
				if (num3 == 0L)
				{
					num = i;
					num2 = long.MinValue;
				}
				else if (!IsPartner(state, num3))
				{
					long num6 = data.GetLong(Updated[i], 0L);
					if (num6 < num2)
					{
						num = i;
						num2 = num6;
					}
				}
			}
			if (num < 0)
			{
				return false;
			}
			data.Set(Values[num], Math.Min(100f, amount));
			data.Set(Updated[num], now);
			data.Set(Players[num], player);
			return true;
		}

		internal static void Hurt(ZDO data, long player, float lostFraction, long now)
		{
			if (player == 0L)
			{
				return;
			}
			for (int i = 0; i < 8; i++)
			{
				if (data.GetLong(Players[i], 0L) == player)
				{
					if (!(Effective(data, i, now) <= 0f))
					{
						float num = data.GetFloat(Values[i], 0f);
						data.Set(Values[i], Math.Max(0f, num - (3f + 20f * Math.Min(1f, lostFraction))));
					}
					break;
				}
			}
		}

		internal static void Combat(ZDO data, CompanionState state, long player, long now)
		{
			long num = data.GetLong(CombatKey, 0L);
			if (now > 0 && (num <= 0 || now - num >= 30) && Gain(data, state, player, 0.25f, now))
			{
				data.Set(CombatKey, now);
			}
		}

		internal static void Copy(ZDO from, ZDO to)
		{
			for (int i = 0; i < 8; i++)
			{
				long num = from.GetLong(Players[i], 0L);
				if (num != 0L)
				{
					to.Set(Values[i], from.GetFloat(Values[i], 0f));
					to.Set(Updated[i], from.GetLong(Updated[i], 0L));
					to.Set(Players[i], num);
				}
			}
			to.Set(CombatKey, from.GetLong(CombatKey, 0L));
		}

		internal static void Clear(ZDO data)
		{
			for (int i = 0; i < 8; i++)
			{
				if (data.GetLong(Players[i], 0L) != 0L)
				{
					data.Set(Players[i], 0L);
				}
			}
			data.Set(CombatKey, 0L);
		}
	}
	internal sealed class CompanionConfig
	{
		internal readonly ConfigEntry<bool> Enabled;

		internal readonly ConfigEntry<bool> Claiming;

		internal readonly ConfigEntry<bool> UnclaimedFollow;

		internal readonly ConfigEntry<bool> Hover;

		internal readonly ConfigEntry<bool> Menu;

		internal readonly ConfigEntry<bool> Summons;

		internal readonly ConfigEntry<bool> Combat;

		internal readonly ConfigEntry<bool> IndividualDistance;

		internal readonly ConfigEntry<bool> DebugCreatures;

		internal readonly ConfigEntry<bool> SummonSlotLimit;

		internal readonly ConfigEntry<bool> LeadershipEnabled;

		internal readonly ConfigEntry<bool> KeepFollowerCollision;

		internal readonly ConfigEntry<int> MaxClaims;

		internal readonly ConfigEntry<int> MaxFollowers;

		internal readonly ConfigEntry<int> NearbyRange;

		internal readonly ConfigEntry<int> LeadershipBaseSlots;

		internal readonly ConfigEntry<int> LeadershipClaimStep;

		internal readonly ConfigEntry<int> ClaimsPerStep;

		internal readonly ConfigEntry<float> DefaultDistance;

		internal readonly ConfigEntry<float> MinDistance;

		internal readonly ConfigEntry<float> MaxDistance;

		internal readonly ConfigEntry<float> NeckMealHealPercent;

		internal readonly ConfigEntry<float> NeckPassiveHealPercentPerDay;

		internal readonly ConfigEntry<float> RecallHealthCost;

		internal readonly ConfigEntry<float> RecallEitrCost;

		internal readonly ConfigEntry<float> FollowerXpPerMinute;

		internal readonly ConfigEntry<float> XpPerTamingLevel;

		internal readonly ConfigEntry<float> XpPerCompanionKill;

		internal readonly ConfigEntry<KeyboardShortcut> OpenMenu;

		internal readonly ConfigEntry<KeyboardShortcut> Inspect;

		internal readonly ConfigEntry<KeyboardShortcut> QuickFollow;

		internal readonly LoyaltyConfig Loyalty;

		internal HashSet<string> ExcludedPrefabs { get; private set; }

		internal HashSet<string> ExtraSummonPrefabs { get; private set; }

		internal FollowerProgression FollowerLimits { get; private set; } = FollowerProgression.Default;

		internal CompanionConfig(ConfigFile config)
		{
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Expected O, but got Unknown
			//IL_00c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Expected O, but got Unknown
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ff: Expected O, but got Unknown
			//IL_01cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d9: Expected O, but got Unknown
			//IL_0208: Unknown result type (might be due to invalid IL or missing references)
			//IL_0212: Expected O, but got Unknown
			//IL_0241: Unknown result type (might be due to invalid IL or missing references)
			//IL_024b: Expected O, but got Unknown
			//IL_027a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0284: Expected O, but got Unknown
			//IL_02c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d1: Expected O, but got Unknown
			//IL_0333: Unknown result type (might be due to invalid IL or missing references)
			//IL_033d: Expected O, but got Unknown
			//IL_0361: Unknown result type (might be due to invalid IL or missing references)
			//IL_036b: Expected O, but got Unknown
			//IL_039a: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a4: Expected O, but got Unknown
			//IL_03d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_03dd: Expected O, but got Unknown
			//IL_040c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0416: Expected O, but got Unknown
			//IL_04d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_04e0: Expected O, but got Unknown
			//IL_050f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0519: Expected O, but got Unknown
			//IL_0548: Unknown result type (might be due to invalid IL or missing references)
			//IL_0552: Expected O, but got Unknown
			//IL_05be: Unknown result type (might be due to invalid IL or missing references)
			//IL_05e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_060c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0648: Unknown result type (might be due to invalid IL or missing references)
			//IL_064d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0665: Unknown result type (might be due to invalid IL or missing references)
			//IL_066a: Unknown result type (might be due to invalid IL or missing references)
			//IL_071c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0721: Unknown result type (might be due to invalid IL or missing references)
			//IL_072e: Unknown result type (might be due to invalid IL or missing references)
			//IL_069c: Unknown result type (might be due to invalid IL or missing references)
			//IL_06a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_06b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_06be: Unknown result type (might be due to invalid IL or missing references)
			//IL_068c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0752: Unknown result type (might be due to invalid IL or missing references)
			//IL_06e0: Unknown result type (might be due to invalid IL or missing references)
			CompanionConfig companionConfig = this;
			Enabled = config.Bind<bool>("General", "Enabled", true, "Enable on startup. Restart all peers after changing.");
			Claiming = config.Bind<bool>("Ownership", "EnableClaiming", true, "Host: permit new claims and releasing existing claims.");
			UnclaimedFollow = config.Bind<bool>("Ownership", "AllowUnclaimedFollowers", true, "Host: allow unclaimed permanent tames to follow.");
			MaxClaims = config.Bind<int>("Limits", "MaxClaimedCreatures", 10, new ConfigDescription("Host: -1 unlimited, 0 none.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(-1, 10000), Array.Empty<object>()));
			MaxFollowers = config.Bind<int>("Limits", "MaxTameFollowers", 6, new ConfigDescription("Host: maximum active followers when Leadership is disabled. -1 unlimited.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(-1, 10000), Array.Empty<object>()));
			NearbyRange = config.Bind<int>("General", "NearbyRange", 60, new ConfigDescription("Host: command distance in meters.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(5, 100), Array.Empty<object>()));
			ConfigEntry<string> excluded = config.Bind<string>("Compatibility", "ExcludedPrefabs", "", "Host and clients: comma-separated exact prefab names to exclude. Restart after changing; use same list on all peers.");
			ExcludedPrefabs = ParsePrefabNames(excluded.Value);
			excluded.SettingChanged += delegate
			{
				companionConfig.ExcludedPrefabs = ParsePrefabNames(excluded.Value);
			};
			KeepFollowerCollision = config.Bind<bool>("Compatibility", "KeepFollowerCollision", true, "Local: keep physical contact and hit detection on replicated tames and summons. Also turns off Zephyrfit follower pass-through.");
			Summons = config.Bind<bool>("Summons", "EnableSummonCommands", true, "Host: manage native-pattern summons without changing their staff limits. Restart all peers after changing.");
			SummonSlotLimit = config.Bind<bool>("Summons", "RequireFollowerSlotOnCast", true, "Host: when full, newly cast summons roam. Staff casting and replacement still work.");
			NeckMealHealPercent = config.Bind<float>("Summons", "NeckMealHealPercent", 20f, new ConfigDescription("Host: percent of max health restored when a hungry Neck Totem summon eats.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			NeckPassiveHealPercentPerDay = config.Bind<float>("Summons", "NeckPassiveHealPercentPerDay", 0f, new ConfigDescription("Host: percent of max health restored over one game day's worth of loaded time outside combat. 0 disables passive healing.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			RecallHealthCost = config.Bind<float>("Recall", "StaffBaseHealthCost", 20f, new ConfigDescription("Host: Staff of Recall health cost at Blood Magic 0.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 250f), Array.Empty<object>()));
			RecallEitrCost = config.Bind<float>("Recall", "StaffBaseEitrCost", 40f, new ConfigDescription("Host: Staff of Recall Eitr cost at Blood Magic 0.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 250f), Array.Empty<object>()));
			LeadershipEnabled = config.Bind<bool>("Leadership", "Enabled", true, "Host: enable Leadership XP and slot bonuses. Requires Jotunn for the Leadership skill.");
			LeadershipBaseSlots = config.Bind<int>("Leadership", "BaseFollowerSlots", 1, new ConfigDescription("Host: follower slots at level zero or below. -1 unlimited.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(-1, 10000), Array.Empty<object>()));
			ConfigEntry<string> milestones = config.Bind<string>("Leadership", "FollowerMilestones", "3:2, 6:3, 10:4, 15:5, 20:6, 30:7, 40:8, 50:9, 60:10, 70:11, 80:12, 90:13, 100:14, 120:15", "Host: comma-separated level:total-slots pairs, ordered by increasing positive level. An empty list uses the base cap at every level.");
			UpdateMilestones();
			milestones.SettingChanged += delegate
			{
				UpdateMilestones();
			};
			LeadershipClaimStep = config.Bind<int>("Leadership", "LevelsPerClaimBonus", 20, new ConfigDescription("Host: skill levels between claim capacity bonuses.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 100), Array.Empty<object>()));
			ClaimsPerStep = config.Bind<int>("Leadership", "ClaimSlotsPerBonus", 1, new ConfigDescription("Host: claim slots gained at each milestone.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 10), Array.Empty<object>()));
			FollowerXpPerMinute = config.Bind<float>("Leadership", "XpPerMinuteWithFollower", 1f, new ConfigDescription("Host: base Leadership XP per minute near an active follower. 0 disables this source.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			XpPerTamingLevel = config.Bind<float>("Leadership", "XpPerTamingLevel", 2f, new ConfigDescription("Host: base Leadership XP per level earned in Balrond's Taming skill. 0 disables this source.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			XpPerCompanionKill = config.Bind<float>("Leadership", "XpPerCompanionKill", 0.25f, new ConfigDescription("Host: base Leadership XP when a companion kills a wild creature. 0 disables this source.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			Loyalty = new LoyaltyConfig(config);
			ConfigEntry<string> extraSummons = config.Bind<string>("Summons", "ExtraSummonPrefabs", "", "Exact prefab names, comma-separated, for summons without native indicators. Same list on every peer; restart.");
			ExtraSummonPrefabs = ParsePrefabNames(extraSummons.Value);
			extraSummons.SettingChanged += delegate
			{
				companionConfig.ExtraSummonPrefabs = ParsePrefabNames(extraSummons.Value);
			};
			Combat = config.Bind<bool>("Combat", "EnableCombatModes", true, "Host: allow aggressive, passive and defensive commands.");
			IndividualDistance = config.Bind<bool>("Movement", "EnableIndividualFollowDistance", true, "Host: allow per-creature distance overrides.");
			MinDistance = config.Bind<float>("Movement", "MinimumFollowDistance", 2f, new ConfigDescription("Host: minimum follow distance in meters; synchronized to peers.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 100f), Array.Empty<object>()));
			MaxDistance = config.Bind<float>("Movement", "MaximumFollowDistance", 20f, new ConfigDescription("Host: maximum follow distance in meters; synchronized to peers. Keep at or above minimum.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 100f), Array.Empty<object>()));
			DefaultDistance = config.Bind<float>("Movement", "DefaultFollowDistance", 3f, new ConfigDescription("Host: default follow distance, clamped to host bounds.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.5f, 100f), Array.Empty<object>()));
			DebugCreatures = config.Bind<bool>("Compatibility", "LogCreatureInspection", false, "Local: log prefab and summon evidence when inspecting a creature.");
			Hover = config.Bind<bool>("Interface", "ShowHoverHelp", true, "Local: show companion controls in hover text.");
			Menu = config.Bind<bool>("Interface", "EnableMenu", true, "Local: enable the two menus.");
			OpenMenu = config.Bind<KeyboardShortcut>("Keybinds", "CompanionMenu", new KeyboardShortcut((KeyCode)99, Array.Empty<KeyCode>()), "Local: open roster.");
			Inspect = config.Bind<KeyboardShortcut>("Keybinds", "InspectCreature", new KeyboardShortcut((KeyCode)105, Array.Empty<KeyCode>()), "Local: open targeted creature actions.");
			QuickFollow = config.Bind<KeyboardShortcut>("Keybinds", "ToggleFollow", new KeyboardShortcut((KeyCode)110, Array.Empty<KeyCode>()), "Local: toggle follow or stay without a menu.");
			ConfigEntry<bool> val = config.Bind<bool>("Interface", "KeybindDefaults022Applied", false, "Internal one-time migration from F6/F7 to C/I; leave true after updating.");
			if (!val.Value)
			{
				if (((object)OpenMenu.Value/*cast due to .constrained prefix*/).ToString() == ((object)new KeyboardShortcut((KeyCode)287, Array.Empty<KeyCode>())/*cast due to .constrained prefix*/).ToString())
				{
					OpenMenu.Value = new KeyboardShortcut((KeyCode)99, Array.Empty<KeyCode>());
				}
				if (((object)Inspect.Value/*cast due to .constrained prefix*/).ToString() == ((object)new KeyboardShortcut((KeyCode)288, Array.Empty<KeyCode>())/*cast due to .constrained prefix*/).ToString())
				{
					Inspect.Value = new KeyboardShortcut((KeyCode)105, Array.Empty<KeyCode>());
				}
				val.Value = true;
				config.Save();
			}
			ConfigEntry<bool> val2 = config.Bind<bool>("Interface", "KeybindDefaults023Applied", false, "One-time migration from F8 to N.");
			if (!val2.Value)
			{
				if (((object)QuickFollow.Value/*cast due to .constrained prefix*/).Equals((object)new KeyboardShortcut((KeyCode)289, Array.Empty<KeyCode>())))
				{
					QuickFollow.Value = new KeyboardShortcut((KeyCode)110, Array.Empty<KeyCode>());
				}
				val2.Value = true;
				config.Save();
			}
			void UpdateMilestones()
			{
				FollowerProgression followerProgression = FollowerProgression.Parse(milestones.Value);
				if (followerProgression != null)
				{
					companionConfig.FollowerLimits = followerProgression;
				}
				else
				{
					ManualLogSource log = Plugin.Log;
					if (log != null)
					{
						log.LogWarning((object)"Invalid Leadership FollowerMilestones. Keeping the last valid progression.");
					}
				}
			}
		}

		private static HashSet<string> ParsePrefabNames(string value)
		{
			HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
			string[] array = value.Split(new char[1] { ',' });
			for (int i = 0; i < array.Length; i++)
			{
				string text = array[i].Trim();
				if (text.Length != 0)
				{
					hashSet.Add(text);
				}
			}
			return hashSet;
		}
	}
	internal static class CompanionMood
	{
		private sealed class Search
		{
			internal float Next;
		}

		private static readonly int MoodKey = StringExtensionMethods.GetStableHashCode("KratyrCompanions.Mood");

		private static readonly int UntilKey = StringExtensionMethods.GetStableHashCode("KratyrCompanions.MoodUntil");

		private const string TargetKey = "KratyrCompanions.MoodTarget";

		private static readonly int DestinationKey = StringExtensionMethods.GetStableHashCode("KratyrCompanions.MoodDestination");

		private static readonly int RecoveryKey = StringExtensionMethods.GetStableHashCode("KratyrCompanions.NextSoothe");

		private static readonly int ContentKey = StringExtensionMethods.GetStableHashCode("KratyrCompanions.ContentUntil");

		private static readonly int ContentCooldownKey = StringExtensionMethods.GetStableHashCode("KratyrCompanions.NextContent");

		private static readonly int SwingKey = StringExtensionMethods.GetStableHashCode("KratyrCompanions.MoodSwing");

		private static readonly int StaggerKey = StringExtensionMethods.GetStableHashCode("KratyrCompanions.MoodStaggerTried");

		private const float VictimRange = 16f;

		private static readonly ConditionalWeakTable<Character, Search> searches = new ConditionalWeakTable<Character, Search>();

		internal static CreatureMood Current(ZDO data)
		{
			if (data == null)
			{
				return CreatureMood.Normal;
			}
			CreatureMood creatureMood = (CreatureMood)data.GetInt(MoodKey, 0);
			if (creatureMood != CreatureMood.Normal)
			{
				LoyaltyRules loyaltyRules = CompanionNetwork.LoyaltyRules;
				if (loyaltyRules != null && loyaltyRules.Enabled)
				{
					return MoodRules.Active(creatureMood, data.GetLong(UntilKey, 0L), Loyalty.Now);
				}
			}
			return CreatureMood.Normal;
		}

		internal static bool Content(ZDO data, long now)
		{
			return data.GetLong(ContentKey, 0L) > now;
		}

		internal static Vector3 Destination(ZDO data, Vector3 fallback)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			return data.GetVec3(DestinationKey, fallback);
		}

		internal static bool HasSwung(ZDO data)
		{
			return data.GetLong(SwingKey, 0L) != 0;
		}

		internal static void MarkSwing(ZDO data)
		{
			long now = Loyalty.Now;
			data.Set(SwingKey, now + 1);
			data.Set(UntilKey, Math.Max(data.GetLong(UntilKey, 0L), now + 8));
		}

		internal static void FinishSingleSwing(ZDO data, Character creature)
		{
			long num = data.GetLong(SwingKey, 0L);
			if (num != 0L && Loyalty.Now >= num && !creature.InAttack())
			{
				Clear(data);
			}
		}

		internal static void Clear(ZDO data)
		{
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			data.Set(MoodKey, 0, false);
			data.Set(UntilKey, 0L);
			data.Set("KratyrCompanions.MoodTarget", ZDOID.None);
			data.Set(RecoveryKey, 0L);
			data.Set(SwingKey, 0L);
			data.Set(StaggerKey, false);
		}

		internal static void ResetBond(ZDO data)
		{
			Clear(data);
			data.Set(ContentKey, 0L);
			data.Set(ContentCooldownKey, 0L);
		}

		internal static string Text(Character creature, ZDO data)
		{
			return MoodRules.Description(Current(data), Loyalty.Display(creature, data).GetValueOrDefault(), Content(data, Loyalty.Now));
		}

		internal static void Start(ZDO data, Character creature, CreatureMood mood, Character threat)
		{
			//IL_0036: 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)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: 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_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			Clear(data);
			(int, int) tuple = MoodRules.Duration(mood);
			data.Set(UntilKey, Loyalty.Now + Random.Range(tuple.Item1, tuple.Item2 + 1));
			if (mood == CreatureMood.Distracted)
			{
				Vector2 val = Random.insideUnitCircle * 5f;
				data.Set(DestinationKey, ((Component)creature).transform.position + new Vector3(val.x, 0f, val.y));
			}
			Character val2 = ((mood == CreatureMood.Scared) ? threat : (MoodRules.IsHostile(mood) ? ChooseVictim(creature, mood) : null));
			if (Object.op_Implicit((Object)(object)val2))
			{
				data.Set("KratyrCompanions.MoodTarget", val2.GetZDOID());
			}
			data.Set(MoodKey, (int)mood, false);
		}

		internal static void OfferedMeal(ZDO data, float effectiveness, MoodOptions options)
		{
			long now = Loyalty.Now;
			if (MoodRules.CanStartContent(Current(data), data.GetLong(ContentKey, 0L), data.GetLong(ContentCooldownKey, 0L), now))
			{
				int num = MoodRules.ContentSeconds(options, effectiveness);
				if (num > 0)
				{
					data.Set(ContentKey, now + num);
					data.Set(ContentCooldownKey, now + Math.Max(num, options.ContentCooldown));
				}
			}
		}

		internal static bool Soothe(ZDO data, bool pet, float loyalty, float effectiveness, out bool attempted)
		{
			attempted = false;
			CreatureMood mood = Current(data);
			float num = MoodRules.RecoveryChance(mood, pet, loyalty, effectiveness);
			long now = Loyalty.Now;
			if (num <= 0f || now < data.GetLong(RecoveryKey, 0L))
			{
				return false;
			}
			data.Set(RecoveryKey, now + MoodRules.RecoveryCooldown(mood));
			attempted = true;
			if (Random.value >= num)
			{
				return false;
			}
			Clear(data);
			return true;
		}

		internal static bool ReactToHandlerHit(ZDO data, float loyalty, bool staggered)
		{
			if (Current(data) != CreatureMood.Angry)
			{
				return false;
			}
			if (loyalty <= 10f && Random.value < 0.08f)
			{
				return true;
			}
			if (staggered && !data.GetBool(StaggerKey, false))
			{
				data.Set(StaggerKey, true);
				if (Random.value < 0.25f)
				{
					Clear(data);
				}
			}
			return false;
		}

		internal static Character Target(ZDO data)
		{
			//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)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			ZDOID zDOID = data.GetZDOID("KratyrCompanions.MoodTarget");
			if (zDOID == ZDOID.None)
			{
				return null;
			}
			GameObject val = GameAccess.Instance(zDOID);
			if (!Object.op_Implicit((Object)(object)val))
			{
				return null;
			}
			return val.GetComponent<Character>();
		}

		internal static bool IsVictim(ZDO data, Character victim)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			if (Object.op_Implicit((Object)(object)victim))
			{
				return data.GetZDOID("KratyrCompanions.MoodTarget") == victim.GetZDOID();
			}
			return false;
		}

		internal static Character HostileTarget(ZDO data, Character creature, CreatureMood mood)
		{
			//IL_008a: 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)
			Character val = Target(data);
			if (CanAttack(creature, val, mood))
			{
				return val;
			}
			if (mood == CreatureMood.Vicious && HasSwung(data))
			{
				return null;
			}
			Search value = searches.GetValue(creature, (Character _) => new Search());
			if (Time.time < value.Next)
			{
				return null;
			}
			value.Next = Time.time + 0.75f;
			val = ChooseVictim(creature, mood);
			data.Set("KratyrCompanions.MoodTarget", Object.op_Implicit((Object)(object)val) ? val.GetZDOID() : ZDOID.None);
			return val;
		}

		private static Character ChooseVictim(Character creature, CreatureMood mood)
		{
			Character result = null;
			int num = 0;
			foreach (Character allCharacter in Character.GetAllCharacters())
			{
				if (CanAttack(creature, allCharacter, mood) && Random.Range(0, ++num) == 0)
				{
					result = allCharacter;
				}
			}
			return result;
		}

		private static bool CanAttack(Character creature, Character target, CreatureMood mood)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: 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_00a6: 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)
			if (Object.op_Implicit((Object)(object)target) && !((Object)(object)target == (Object)(object)creature) && !target.IsDead() && !(target.GetZDOID() == ZDOID.None))
			{
				Vector3 val = ((Component)target).transform.position - ((Component)creature).transform.position;
				if (!(((Vector3)(ref val)).sqrMagnitude > 256f))
				{
					if (target.IsPlayer())
					{
						return true;
					}
					ZDO val2 = GameAccess.Data((Component)(object)target);
					if (GameAccess.Tamed(val2))
					{
						if (val2.GetLong(CompanionState.ControllerKey, 0L) == 0L)
						{
							if (val2.GetLong(CompanionState.RevisionKey, 0L) == 0L)
							{
								return GameAccess.SavedFollow(val2).Length > 0;
							}
							return false;
						}
						return true;
					}
					if (mood == CreatureMood.Angry)
					{
						return target.GetFaction() != creature.GetFaction();
					}
					return false;
				}
			}
			return false;
		}

		internal static Character ScaryEnemy(Character creature)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//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_0066: Unknown result type (might be due to invalid IL or missing references)
			Character result = null;
			float num = 196f;
			foreach (Character allCharacter in Character.GetAllCharacters())
			{
				if (Object.op_Implicit((Object)(object)allCharacter) && !((Object)(object)allCharacter == (Object)(object)creature) && !allCharacter.IsDead() && !allCharacter.IsPlayer() && !GameAccess.Tamed(GameAccess.Data((Component)(object)allCharacter)))
				{
					Vector3 val = ((Component)allCharacter).transform.position - ((Component)creature).transform.position;
					float sqrMagnitude = ((Vector3)(ref val)).sqrMagnitude;
					if (!(sqrMagnitude >= num) && BaseAI.IsEnemy(creature, allCharacter))
					{
						result = allCharacter;
						num = sqrMagnitude;
					}
				}
			}
			return result;
		}
	}
	internal enum Command
	{
		Claim = 1,
		Release,
		Follow,
		Wander,
		Aggressive,
		Passive,
		SetDistance,
		Defensive,
		OfferLoan,
		RecallLoan,
		ReturnLoan,
		Guard,
		Reassure,
		Transfer
	}
	internal enum CombatMode
	{
		Aggressive,
		Passive,
		Defensive,
		Guard
	}
	internal enum FollowMovement
	{
		Hold,
		Approach,
		BackOff
	}
	internal struct CompanionState
	{
		internal static readonly int OwnerKey = StringExtensionMethods.GetStableHashCode("KratyrCompanions.Owner");

		internal static readonly int ControllerKey = StringExtensionMethods.GetStableHashCode("KratyrCompanions.Controller");

		internal static readonly int RevisionKey = StringExtensionMethods.GetStableHashCode("KratyrCompanions.Revision");

		internal static readonly int CombatKey = StringExtensionMethods.GetStableHashCode("KratyrCompanions.Combat");

		internal static readonly int DistanceKey = StringExtensionMethods.GetStableHashCode("KratyrCompanions.DistanceCm");

		internal static readonly int SummonKey = StringExtensionMethods.GetStableHashCode("KratyrCompanions.Summon");

		internal static readonly int LoanableKey = StringExtensionMethods.GetStableHashCode("KratyrCompanions.Loanable");

		internal static readonly int BorrowerKey = StringExtensionMethods.GetStableHashCode("KratyrCompanions.Borrower");

		internal static readonly int OwnerNameKey = StringExtensionMethods.GetStableHashCode("KratyrCompanions.OwnerName");

		internal static readonly int BorrowerNameKey = StringExtensionMethods.GetStableHashCode("KratyrCompanions.BorrowerName");

		internal static readonly int AwaitingSlotKey = StringExtensionMethods.GetStableHashCode("KratyrCompanions.AwaitingSlot");

		internal long Owner;

		internal long Controller;

		internal long Revision;

		internal long Combat;

		internal long DistanceCm;

		internal long Summon;

		internal long Borrower;

		internal bool Loanable;

		internal bool AwaitingSlot;

		internal string OwnerName;

		internal string BorrowerName;

		internal bool IsSummon => Summon == 1;

		internal long Handler
		{
			get
			{
				if (Controller == 0L)
				{
					if (Borrower == 0L)
					{
						return Owner;
					}
					return Borrower;
				}
				return Controller;
			}
		}

		internal CombatMode Mode => (CombatMode)Combat;

		internal bool IsPassive => Mode == CombatMode.Passive;

		internal bool ClearOrphanedLoan()
		{
			if (Owner != 0L || Borrower == 0L)
			{
				return false;
			}
			if (Controller == Borrower)
			{
				Controller = 0L;
			}
			Borrower = 0L;
			BorrowerName = "";
			Loanable = false;
			return true;
		}

		internal static CompanionState Read(ZDO zdo, bool readNames = true)
		{
			return new CompanionState
			{
				Owner = zdo.GetLong(OwnerKey, 0L),
				Controller = zdo.GetLong(ControllerKey, 0L),
				Revision = zdo.GetLong(RevisionKey, 0L),
				Combat = zdo.GetLong(CombatKey, 0L),
				DistanceCm = zdo.GetLong(DistanceKey, 0L),
				Summon = zdo.GetLong(SummonKey, 0L),
				Borrower = zdo.GetLong(BorrowerKey, 0L),
				Loanable = (zdo.GetLong(LoanableKey, 0L) == 1),
				AwaitingSlot = (zdo.GetLong(AwaitingSlotKey, 0L) == 1),
				OwnerName = (readNames ? zdo.GetString(OwnerNameKey, "") : null),
				BorrowerName = (readNames ? zdo.GetString(BorrowerNameKey, "") : null)
			};
		}

		internal void Write(ZDO zdo)
		{
			zdo.Set(OwnerKey, Owner);
			zdo.Set(ControllerKey, Controller);
			zdo.Set(CombatKey, Combat);
			zdo.Set(DistanceKey, DistanceCm);
			zdo.Set(SummonKey, Summon);
			zdo.Set(BorrowerKey, Borrower);
			zdo.Set(LoanableKey, (long)(Loanable ? 1 : 0));
			zdo.Set(AwaitingSlotKey, (long)(AwaitingSlot ? 1 : 0));
			zdo.Set(OwnerNameKey, OwnerName ?? "");
			zdo.Set(BorrowerNameKey, BorrowerName ?? "");
			zdo.Set(RevisionKey, Revision);
		}

		internal bool CanControl(long player)
		{
			if (player != 0L)
			{
				bool num;
				if (Borrower == 0L)
				{
					if (Owner == 0L)
					{
						goto IL_002c;
					}
					num = Owner == player;
				}
				else
				{
					num = Borrower == player;
				}
				if (num)
				{
					goto IL_002c;
				}
			}
			return false;
			IL_002c:
			if (Controller != 0L)
			{
				return Controller == player;
			}
			return true;
		}

		internal bool CanFollow(long player, bool unclaimedFollow)
		{
			if (player != 0L)
			{
				if (!CanControl(player) || !(Owner != 0 || unclaimedFollow))
				{
					if (Owner != 0L && Borrower == 0L && Controller == 0L)
					{
						return Loanable;
					}
					return false;
				}
				return true;
			}
			return false;
		}
	}
	internal struct DistanceBounds
	{
		internal readonly int Min;

		internal readonly int Max;

		internal readonly int Default;

		internal readonly bool Enabled;

		internal DistanceBounds(int min, int max, int defaultCm, bool enabled = true)
		{
			Min = Math.Max(50, Math.Min(10000, min));
			Max = Math.Max(Min, Math.Min(10000, max));
			Default = Math.Max(Min, Math.Min(Max, defaultCm));
			Enabled = enabled;
		}

		internal int Clamp(long value)
		{
			return (int)Math.Max(Min, Math.Min(Max, value));
		}

		internal int Effective(long value)
		{
			if (value != 0L)
			{
				return Clamp(value);
			}
			return Default;
		}
	}
	internal sealed class FollowerProgression
	{
		internal const string DefaultMilestones = "3:2, 6:3, 10:4, 15:5, 20:6, 30:7, 40:8, 50:9, 60:10, 70:11, 80:12, 90:13, 100:14, 120:15";

		internal static readonly FollowerProgression Default = Parse("3:2, 6:3, 10:4, 15:5, 20:6, 30:7, 40:8, 50:9, 60:10, 70:11, 80:12, 90:13, 100:14, 120:15");

		private readonly (int Level, int Slots)[] milestones;

		private FollowerProgression((int Level, int Slots)[] milestones)
		{
			this.milestones = milestones;
		}

		internal static FollowerProgression Parse(string value)
		{
			if (string.IsNullOrWhiteSpace(value))
			{
				return new FollowerProgression(Array.Empty<(int, int)>());
			}
			string[] array = value.Split(new char[1] { ',' });
			(int, int)[] array2 = new(int, int)[array.Length];
			int num = 0;
			int num2 = 0;
			for (int i = 0; i < array.Length; i++)
			{
				string[] array3 = array[i].Split(new char[1] { ':' });
				if (array3.Length != 2 || !int.TryParse(array3[0], NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) || result <= num || !int.TryParse(array3[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out var result2) || result2 < num2 || result2 > 10000)
				{
					return null;
				}
				array2[i] = (result, result2);
				num = result;
				num2 = result2;
			}
			return new FollowerProgression(array2);
		}

		internal int Limit(int level, int baseSlots)
		{
			if (baseSlots < 0)
			{
				return baseSlots;
			}
			int result = baseSlots;
			(int, int)[] array = milestones;
			for (int i = 0; i < array.Length; i++)
			{
				(int, int) tuple = array[i];
				if (level < tuple.Item1)
				{
					break;
				}
				result = Math.Max(baseSlots, tuple.Item2);
			}
			return result;
		}
	}
	internal static class Rules
	{
		internal static bool Full(int count, int limit)
		{
			if (limit >= 0)
			{
				return count >= limit;
			}
			return false;
		}

		internal static bool IsCombatOrder(Command command)
		{
			if (command != Command.Aggressive && command != Command.Passive && command != Command.Defensive)
			{
				return command == Command.Guard;
			}
			return true;
		}

		internal static bool IsFollowerOrder(Command command)
		{
			if (command != Command.Follow && command != Command.Wander)
			{
				return IsCombatOrder(command);
			}
			return true;
		}

		internal static bool CanAutoFill(long actor, CompanionState state)
		{
			if (actor != 0L && state.Owner == actor && state.Controller == 0L && state.Borrower == 0L && !state.Loanable)
			{
				return !state.AwaitingSlot;
			}
			return false;
		}

		internal static bool NeedsFollowerOrder(Command command, long actor, CompanionState state)
		{
			if (state.Controller != actor || !state.CanControl(actor) || (state.IsSummon && (state.AwaitingSlot || state.Owner == 0L)))
			{
				return false;
			}
			return command switch
			{
				Command.Wander => true, 
				Command.Aggressive => state.Mode != CombatMode.Aggressive, 
				Command.Passive => state.Mode != CombatMode.Passive, 
				Command.Defensive => state.Mode != CombatMode.Defensive, 
				Command.Guard => state.Mode != CombatMode.Guard, 
				_ => false, 
			};
		}

		internal static float NeckHealingAmount(float health, float maximum, float percent)
		{
			return Math.Max(0f, Math.Min(maximum - health, maximum * percent / 100f));
		}

		internal static FollowMovement FollowSpacing(float distance, float desired)
		{
			if (distance > desired + 0.5f)
			{
				return FollowMovement.Approach;
			}
			if (!(distance < desired - 0.5f))
			{
				return FollowMovement.Hold;
			}
			return FollowMovement.BackOff;
		}

		internal static float NeckCooldownFactor(float bloodMagic)
		{
			return 1f - 0.5f * Math.Max(0f, Math.Min(100f, bloodMagic)) / 100f;
		}

		internal static bool SameSummoner(long original, long actor, string savedName, string legacyName)
		{
			if (actor != 0L)
			{
				if (original == 0L)
				{
					if (!string.IsNullOrEmpty(legacyName))
					{
						return savedName == legacyName;
					}
					return false;
				}
				return original == actor;
			}
			return false;
		}

		internal static int LeadershipClaimLimit(int limit, int level, int levelsPerBonus, int slotsPerBonus)
		{
			if (limit >= 0)
			{
				return limit + Math.Min(500, Math.Max(0, level)) / levelsPerBonus * slotsPerBonus;
			}
			return limit;
		}

		internal static CompanionState AssignSummonSlot(CompanionState summon, int followers, int limit)
		{
			summon.Controller = (Full(followers, limit) ? 0 : summon.Owner);
			summon.AwaitingSlot = false;
			summon.Revision++;
			return summon;
		}

		internal static string Decide(Command action, long actor, CompanionState current, bool claiming, bool unclaimedFollow, int claims, int followers, int maxClaims, int maxFollowers, out CompanionState next, int distanceCm = 0, bool combatEnabled = true, bool distanceEnabled = true, int minDistanceCm = 200, int maxDistanceCm = 2000, string actorName = "", long recipient = 0L, string recipientName = "")
		{
			next = current;
			bool flag = actor != 0L && current.Owner == actor;
			if (action == Command.Release && flag && current.Borrower != 0L)
			{
				return "Recall the loan before releasing this claim.";
			}
			bool num;
			switch (action)
			{
			default:
				num = current.CanControl(actor);
				break;
			case Command.Follow:
				num = current.CanFollow(actor, unclaimedFollow);
				break;
			case Command.RecallLoan:
			case Command.Transfer:
				num = flag;
				break;
			}
			if (!num)
			{
				return "This creature is unavailable to you.";
			}
			if (current.IsSummon && (current.Owner == 0L || action == Command.Claim || action == Command.Release || action == Command.Transfer))
			{
				return "Summon ownership comes from the summoning staff.";
			}
			if (current.IsSummon && current.AwaitingSlot)
			{
				return "This summon is waiting for its staff limit check.";
			}
			switch (action)
			{
			case Command.Claim:
				if (!claiming)
				{
					return "Claiming is disabled by the host.";
				}
				if (current.Owner != 0L)
				{
					return "Already claimed.";
				}
				if (Full(claims, maxClaims))
				{
					return "Claim limit reached.";
				}
				next.Owner = actor;
				next.OwnerName = actorName;
				break;
			case Command.Release:
				if (current.Owner != actor)
				{
					return "Only the owner can release a claim.";
				}
				if (!claiming)
				{
					return "Claiming is disabled by the host.";
				}
				next.Owner = 0L;
				next.OwnerName = "";
				next.Borrower = 0L;
				next.BorrowerName = "";
				next.Loanable = false;
				if (!unclaimedFollow)
				{
					next.Controller = 0L;
				}
				break;
			case Command.Transfer:
				if (!claiming)
				{
					return "Claiming is disabled by the host.";
				}
				if (recipient == 0L || recipient == actor || current.Borrower != recipient || (current.Controller != 0L && current.Controller != recipient))
				{
					return "The active loan changed.";
				}
				if (Full(claims, maxClaims))
				{
					return "The borrower has no free claim slot.";
				}
				next.Owner = recipient;
				next.OwnerName = recipientName;
				next.Borrower = 0L;
				next.BorrowerName = "";
				next.Loanable = false;
				break;
			case Command.Follow:
				if (current.Controller == actor)
				{
					return "Already following you.";
				}
				if (Full(followers, maxFollowers))
				{
					return "Follower limit reached. Free a slot first.";
				}
				next.Controller = actor;
				if (current.Owner != 0L && !flag)
				{
					next.Borrower = actor;
					next.BorrowerName = actorName;
				}
				else
				{
					next.Loanable = false;
				}
				break;
			case Command.Aggressive:
			case Command.Passive:
			case Command.Defensive:
			case Command.Guard:
				if (!combatEnabled)
				{
					return "Combat mode changes are disabled by the host.";
				}
				next.Combat = action switch
				{
					Command.Guard => 3, 
					Command.Defensive => 2, 
					Command.Passive => 1, 
					_ => 0, 
				};
				break;
			case Command.SetDistance:
				if (!distanceEnabled)
				{
					return "Individual follow distance is disabled by the host.";
				}
				if (distanceCm != 0 && (distanceCm < minDistanceCm || distanceCm > maxDistanceCm))
				{
					return $"Follow distance must be {(float)minDistanceCm / 100f:0.##}–{(float)maxDistanceCm / 100f:0.##} m, or use Default.";
				}
				next.DistanceCm = distanceCm;
				break;
			case Command.Wander:
				if (current.Controller != actor)
				{
					return "This creature is already staying.";
				}
				next.Controller = 0L;
				break;
			case Command.OfferLoan:
				if (!flag)
				{
					return "Only the owner can make a companion loanable.";
				}
				next.Loanable = true;
				next.Controller = 0L;
				break;
			case Command.ReturnLoan:
				if (current.Borrower != actor)
				{
					return "Only the borrower can return a loan.";
				}
				goto case Command.RecallLoan;
			case Command.RecallLoan:
				if (current.Borrower != 0L)
				{
					next.Controller = 0L;
				}
				next.Borrower = 0L;
				next.BorrowerName = "";
				next.Loanable = action == Command.ReturnLoan;
				break;
			default:
				return "Unknown command.";
			case Command.Reassure:
				break;
			}
			if (next.Owner == actor && !string.IsNullOrEmpty(actorName))
			{
				next.OwnerName = actorName;
			}
			if (action == Command.Follow || action == Command.OfferLoan)
			{
				next.AwaitingSlot = false;
			}
			next.Revision++;
			return null;
		}
	}
	internal static class GameAccess
	{
		private const string RuntimeTameableKey = "KratyrCompanions.RuntimeTameable";

		internal const string OriginalSummonerKey = "KratyrCompanions.OriginalSummoner";

		internal const string StaffCastLimitKey = "KratyrCompanions.StaffCastLimit";

		internal static readonly FieldInfo ObjectsField = AccessTools.Field(typeof(ZDOMan), "m_objectsByID");

		private static readonly FieldRef<Character, ZNetView> CharacterView = AccessTools.FieldRefAccess<Character, ZNetView>("m_nview");

		private static readonly FieldRef<BaseAI, ZNetView> AiView = AccessTools.FieldRefAccess<BaseAI, ZNetView>("m_nview");

		private static readonly FieldRef<Tameable, ZNetView> TameView = AccessTools.FieldRefAccess<Tameable, ZNetView>("m_nview");

		private static readonly FieldRef<Tameable, MonsterAI> MonsterField = AccessTools.FieldRefAccess<Tameable, MonsterAI>("m_monsterAI");

		private static readonly FieldRef<BaseAI, Tameable> TameField = AccessTools.FieldRefAccess<BaseAI, Tameable>("m_tamable");

		internal static bool Ready => ObjectsField != null;

		internal static Dictionary<ZDOID, ZDO> Objects
		{
			get
			{
				if (ZDOMan.instance != null)
				{
					return ObjectsField?.GetValue(ZDOMan.instance) as Dictionary<ZDOID, ZDO>;
				}
				return null;
			}
		}

		internal static MonsterAI Monster(Tameable tame)
		{
			MonsterAI val = MonsterField.Invoke(tame);
			if (!Object.op_Implicit((Object)(object)val))
			{
				return ((Component)tame).GetComponent<MonsterAI>();
			}
			return val;
		}

		internal static Tameable Tame(BaseAI ai)
		{
			Tameable val = TameField.Invoke(ai);
			if (!Object.op_Implicit((Object)(object)val))
			{
				return ((Component)ai).GetComponent<Tameable>();
			}
			return val;
		}

		internal static bool Tamed(ZDO zdo)
		{
			if (zdo != null)
			{
				return zdo.GetBool(ZDOVars.s_tamed, false);
			}
			return false;
		}

		internal static string SavedFollow(ZDO zdo)
		{
			return zdo.GetString(ZDOVars.s_follow, "");
		}

		internal static long PlayerId(ZDO zdo)
		{
			if (zdo == null)
			{
				return 0L;
			}
			return zdo.GetLong(ZDOVars.s_playerID, 0L);
		}

		internal static long SummonerId(ZDO data)
		{
			long num = data.GetLong("KratyrCompanions.OriginalSummoner", 0L);
			if (num == 0L && data.GetLong(CompanionState.SummonKey, 0L) == 1)
			{
				return data.GetLong(CompanionState.OwnerKey, 0L);
			}
			return num;
		}

		internal static bool SummonedBy(ZDO data, long actor, string legacyName)
		{
			long num = SummonerId(data);
			return Rules.SameSummoner(num, actor, (num == 0L) ? SavedFollow(data) : "", legacyName);
		}

		internal static string StaffSummonFamily(ZDO data)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = Instance(data.m_uid);
			GameObject val2 = (Object.op_Implicit((Object)(object)val) ? val : Prefab(data));
			Character val3 = (Object.op_Implicit((Object)(object)val2) ? val2.GetComponent<Character>() : null);
			if (!Object.op_Implicit((Object)(object)val3))
			{
				return "";
			}
			return val3.m_name;
		}

		internal static GameObject Instance(ZDOID id)
		{
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			if (!Object.op_Implicit((Object)(object)ZNetScene.instance))
			{
				return null;
			}
			return ZNetScene.instance.FindInstance(id);
		}

		internal static GameObject Prefab(ZDO zdo)
		{
			if (!Object.op_Implicit((Object)(object)ZNetScene.instance))
			{
				return null;
			}
			return ZNetScene.instance.GetPrefab(zdo.GetPrefab());
		}

		internal static Character Target(Player player)
		{
			GameObject hoverObject = ((Humanoid)player).GetHoverObject();
			Character val = (Object.op_Implicit((Object)(object)hoverObject) ? hoverObject.GetComponentInParent<Character>() : null);
			if (!Object.op_Implicit((Object)(object)val))
			{
				return player.GetHoverCreature();
			}
			return val;
		}

		internal static ZNetView View(Component creature)
		{
			if (!Object.op_Implicit((Object)(object)creature))
			{
				return null;
			}
			Character val = (Character)(object)((creature is Character) ? creature : null);
			ZNetView val4;
			if (val == null)
			{
				BaseAI val2 = (BaseAI)(object)((creature is BaseAI) ? creature : null);
				if (val2 == null)
				{
					Tameable val3 = (Tameable)(object)((creature is Tameable) ? creature : null);
					if (val3 == null)
					{
						return creature.GetComponent<ZNetView>();
					}
					val4 = TameView.Invoke(val3);
				}
				else
				{
					val4 = AiView.Invoke(val2);
				}
			}
			else
			{
				val4 = CharacterView.Invoke(val);
			}
			if (!Object.op_Implicit((Object)(object)val4))
			{
				return creature.GetComponent<ZNetView>();
			}
			return val4;
		}

		internal static ZDO Data(Component creature)
		{
			ZNetView val = View(creature);
			if (!Object.op_Implicit((Object)(object)val) || !val.IsValid())
			{
				return null;
			}
			return val.GetZDO();
		}

		internal static bool IsSummon(Tameable tame, ZDO data = null)
		{
			data = data ?? Data((Component)(object)tame);
			if (data == null || (data.GetInt(ZDOVars.s_maxInstances, 0) <= 0 && data.GetInt("KratyrCompanions.StaffCastLimit", 0) <= 0 && data.GetLong(CompanionState.SummonKey, 0L) != 1))
			{
				if (Object.op_Implicit((Object)(object)tame))
				{
					if (!(tame.m_unsummonDistance > 0f) && !(tame.m_unsummonOnOwnerLogoutSeconds > 0f))
					{
						return Listed(((Component)tame).gameObject, Plugin.Settings.ExtraSummonPrefabs);
					}
					return true;
				}
				return false;
			}
			return true;
		}

		internal static bool Eligible(Tameable tame)
		{
			if (!Object.op_Implicit((Object)(object)tame) || !Object.op_Implicit((Object)(object)Monster(tame)))
			{
				return false;
			}
			return !Listed(((Component)tame).gameObject, Plugin.Settings.ExcludedPrefabs);
		}

		internal static bool AllowsCommands(Tameable tame, CompanionState state, string nativeFollow, long actor)
		{
			if (Eligible(tame) && (!state.IsSummon || (Plugin.Settings.Summons.Value && state.Owner != 0L && !state.AwaitingSlot)))
			{
				if (state.Revision == 0L && state.Controller != actor)
				{
					return string.IsNullOrEmpty(nativeFollow);
				}
				return true;
			}
			return false;
		}

		private static bool Listed(GameObject obj, HashSet<string> list)
		{
			if (list.Count != 0)
			{
				return list.Contains(((Object)obj).name.Replace("(Clone)", "").Trim());
			}
			return false;
		}

		internal static bool Eligible(ZDO zdo)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			if (zdo == null || !Tamed(zdo))
			{
				return false;
			}
			GameObject val = Instance(zdo.m_uid);
			if (Object.op_Implicit((Object)(object)val))
			{
				return Eligible(val.GetComponent<Tameable>());
			}
			GameObject val2 = Prefab(zdo);
			if (Object.op_Implicit((Object)(object)val2))
			{
				if (!Eligible(val2.GetComponent<Tameable>()))
				{
					if (zdo.GetInt("KratyrCompanions.RuntimeTameable", 0) != 0 && Object.op_Implicit((Object)(object)val2.GetComponent<MonsterAI>()))
					{
						return !Listed(val2, Plugin.Settings.ExcludedPrefabs);
					}
					return false;
				}
				return true;
			}
			return false;
		}

		internal static void RecordRuntimeTameable(Tameable tame, ZDO data)
		{
			if (Tamed(data) && Eligible(tame))
			{
				GameObject val = Prefab(data);
				if (Object.op_Implicit((Object)(object)val) && !Object.op_Implicit((Object)(object)val.GetComponent<Tameable>()))
				{
					data.Set("KratyrCompanions.RuntimeTameable", (!IsSummon(tame, data)) ? 1 : 2);
				}
			}
		}

		internal static bool IsSummon(ZDO zdo)
		{
			//IL_0046: Unknown result type (might be due to invalid IL or missing references)
			if (zdo == null)
			{
				return false;
			}
			if (zdo.GetLong(CompanionState.SummonKey, 0L) == 1 || zdo.GetInt(ZDOVars.s_maxInstances, 0) > 0 || zdo.GetInt("KratyrCompanions.StaffCastLimit", 0) > 0 || zdo.GetInt("KratyrCompanions.RuntimeTameable", 0) == 2)
			{
				return true;
			}
			GameObject val = Instance(zdo.m_uid);
			GameObject val2 = Prefab(zdo);
			if (!Object.op_Implicit((Object)(object)val) || !IsSummon(val.GetComponent<Tameable>(), zdo))
			{
				if (Object.op_Implicit((Object)(object)val2))
				{
					return IsSummon(val2.GetComponent<Tameable>(), zdo);
				}
				return false;
			}
			return true;
		}

		internal static void ApplyMovement(Tameable tame, Player player, bool summon, bool patrol = true)
		{
			MonsterAI val = Monster(tame);
			ZDO val2 = Data((Component)(object)tame);
			if (!Object.op_Implicit((Object)(object)val) || val2 == null)
			{
				throw new InvalidOperationException("Missing creature AI or ZDO");
			}
			val.SetFollowTarget(Object.op_Implicit((Object)(object)player) ? ((Component)player).gameObject : null);
			if (Object.op_Implicit((Object)(object)player) || !patrol)
			{
				((BaseAI)val).ResetPatrolPoint();
			}
			else
			{
				((BaseAI)val).SetPatrolPoint();
			}
			if (!summon)
			{
				val2.Set(ZDOVars.s_follow, Object.op_Implicit((Object)(object)player) ? player.GetPlayerName() : "");
			}
		}

		internal static CompanionState ControlState(CompanionState stored, bool summon, string nativeFollow, long actor, string actorName)
		{
			if (stored.Revision != 0L && (!summon || stored.IsSummon))
			{
				return stored;
			}
			if (summon)
			{
				stored.Summon = 1L;
				stored.Owner = (stored.Controller = (stored.Borrower = 0L));
				stored.Loanable = false;
				stored.OwnerName = nativeFollow;
				stored.BorrowerName = "";
			}
			if (!string.IsNullOrEmpty(nativeFollow) && nativeFollow == actorName && UniqueNativeName(actorName, actor))
			{
				stored.Controller = actor;
				if (summon)
				{
					stored.Owner = actor;
				}
			}
			return stored;
		}

		internal static bool UniqueNativeName(string name, long playerId)
		{
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: 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_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			foreach (Player allPlayer in Player.GetAllPlayers())
			{
				if (Object.op_Implicit((Object)(object)allPlayer) && allPlayer.GetPlayerID() != playerId && allPlayer.GetPlayerName() == name)
				{
					return false;
				}
			}
			if (Object.op_Implicit((Object)(object)ZNet.instance) && ZDOMan.instance != null)
			{
				foreach (PlayerInfo player in ZNet.instance.GetPlayerList())
				{
					if (player.m_name == name && PlayerId(ZDOMan.instance.GetZDO(player.m_characterID)) != playerId)
					{
						return false;
					}
				}
			}
			return true;
		}

		internal static string PlayerName(long playerId, string saved)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: 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)
			Player val = FindPlayer(playerId);
			if (Object.op_Implicit((Object)(object)val))
			{
				return val.GetPlayerName();
			}
			if (!string.IsNullOrEmpty(saved))
			{
				return saved;
			}
			if (Object.op_Implicit((Object)(object)ZNet.instance) && ZDOMan.instance != null)
			{
				foreach (PlayerInfo player in ZNet.instance.GetPlayerList())
				{
					if (PlayerId(ZDOMan.instance.GetZDO(player.m_characterID)) == playerId)
					{
						return player.m_name;
					}
				}
			}
			return "player " + playerId;
		}

		internal static void LogInspection(Tameable tame)
		{
			if (Plugin.Settings.DebugCreatures.Value)
			{
				ZDO val = Data((Component)(object)tame);
				if (val != null)
				{
					Plugin.Log.LogInfo((object)$"Inspect {((Object)((Component)tame).gameObject).name}: summon={IsSummon(tame)}, maxInstances={val.GetInt(ZDOVars.s_maxInstances, 0)}, unsummonDistance={tame.m_unsummonDistance}, logout={tame.m_unsummonOnOwnerLogoutSeconds}, savedFollow={SavedFollow(val)}, owner={CompanionState.Read(val).Owner}");
				}
			}
		}

		internal static Player FindPlayer(long id)
		{
			foreach (Player allPlayer in Player.GetAllPlayers())
			{
				if (Object.op_Implicit((Object)(object)allPlayer) && allPlayer.GetPlayerID() == id)
				{
					return allPlayer;
				}
			}
			return null;
		}

		internal static string OwnershipText(CompanionState state)
		{
			if (state.IsSummon)
			{
				if (state.Owner == 0L)
				{
					if (!string.IsNullOrEmpty(state.OwnerName))
					{
						return "Summoned by " + state.OwnerName;
					}
					return "Summoner unknown";
				}
				return "Summoned by " + PlayerName(state.Owner, state.OwnerName);
			}
			if (state.Owner != 0L)
			{
				return "Claimed by " + PlayerName(state.Owner, state.OwnerName);
			}
			return "Unclaimed";
		}

		internal static string LoanText(CompanionState state)
		{
			if (state.Borrower == 0L)
			{
				if (!state.Loanable)
				{
					return "";
				}
				return "Loanable";
			}
			return "Loaned to " + PlayerName(state.Borrower, state.BorrowerName);
		}

		internal static string CommandLabel(Tameable tame, ZDO data)
		{
			if (Object.op_Implicit((Object)(object)tame))
			{
				try
				{
					return Label(tame);
				}
				catch
				{
				}
			}
			string text = data.GetString(ZDOVars.s_tamedName, "");
			if (!string.IsNullOrEmpty(text))
			{
				return text;
			}
			GameObject val = Prefab(data);
			if (!Object.op_Implicit((Object)(object)val))
			{
				return "Creature";
			}
			return ((Object)val).name.Replace("(Clone)", "").Trim();
		}

		internal static string Diet(Character creature)
		{
			MonsterAI component = ((Component)creature).GetComponent<MonsterAI>();
			if (!Object.op_Implicit((Object)(object)component))
			{
				return "Unknown (custom AI)";
			}
			List<ItemDrop> consumeItems = component.m_consumeItems;
			if (consumeItems == null)
			{
				return "No standard foods configured";
			}
			List<string> list = new List<string>();
			Localization instance = Localization.instance;
			foreach (ItemDrop item in consumeItems)
			{
				if (Object.op_Implicit((Object)(object)item))
				{
					string text = item.m_itemData?.m_shared?.m_name;
					list.Add(string.IsNullOrEmpty(text) ? ((Object)item).name : (((instance != null) ? instance.Localize(text) : null) ?? text));
				}
			}
			if (list.Count != 0)
			{
				return string.Join(", ", list.Distinct());
			}
			return "No standard foods configured";
		}

		internal static string Label(Tameable tame)
		{
			return tame.GetHoverName();
		}
	}
	internal static class Leadership
	{
		internal const string BalrondGuid = "balrond.astafaraios.BalrondExtraSkills";

		private const string LevelKey = "KratyrCompanions.Leadership";

		private static readonly FieldInfo SkillData = AccessTools.Field(typeof(Skills), "m_skillData");

		private static SkillType skill;

		private static SkillType tamingSkill;

		private static Player trackedPlayer;

		private static float nextSync;

		private static float lastSample;

		internal static void Register(Harmony harmony)
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Expected O, but got Unknown
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(Character), "OnDeath", Type.EmptyTypes, (Type[])null);
			if (methodInfo == null)
			{
				Plugin.Log.LogWarning((object)"Companion kill XP is unavailable. Character.OnDeath was not found.");
			}
			else
			{
				harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(typeof(Leadership), "BeforeCreatureDeath", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			}
			Type type = Type.GetType("Jotunn.Managers.SkillManager, Jotunn", throwOnError: false);
			if (type == null)
			{
				return;
			}
			try
			{
				object obj = type.GetProperty("Instance", BindingFlags.Static | BindingFlags.Public)?.GetValue(null);
				MethodInfo method = type.GetMethod("AddSkill", new Type[5]
				{
					typeof(string),
					typeof(string),
					typeof(string),
					typeof(float),
					typeof(Sprite)
				});
				if (obj != null && method != null)
				{
					skill = (SkillType)method.Invoke(obj, new object[5] { "kratyr_leadership", "Leadership", "Earn experience with nearby followers, companion kills, and Taming. Higher Leadership can increase your companion limits.", 1f, null });
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Leadership registration: " + ex));
			}
			if ((int)skill != 0)
			{
				HookTaming(harmony);
			}
		}

		private static void BeforeCreatureDeath(Character __instance, HitData ___m_lastHit)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: 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)
			if (!Plugin.Active || ___m_lastHit == null || ___m_lastHit.m_attacker == ZDOID.None || __instance.IsPlayer() || !CompanionNetwork.TracksCompanionKills)
			{
				return;
			}
			ZDOMan instance = ZDOMan.instance;
			ZDO val = ((instance != null) ? instance.GetZDO(___m_lastHit.m_attacker) : null);
			if (!GameAccess.Tamed(val))
			{
				return;
			}
			ZDO val2 = GameAccess.Data((Component)(object)__instance);
			if (val2 == null || val2 == val || !val2.IsOwner() || __instance.GetHealth() > 0f || GameAccess.Tamed(val2))
			{
				return;
			}
			try
			{
				CompanionNetwork.ReportCompanionKill(val2, val);
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Could not report a companion kill: " + ex));
			}
		}

		internal static void AwardCompanionKill(long actor, float xp)
		{
			//IL_0006: 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)
			Player localPlayer = Player.m_localPlayer;
			if ((int)skill != 0 && xp > 0f && Object.op_Implicit((Object)(object)localPlayer) && localPlayer.GetPlayerID() == actor)
			{
				((Character)localPlayer).RaiseSkill(skill, xp);
			}
		}

		internal static int Level(ZDO player)
		{
			if (player == null)
			{
				return 0;
			}
			return player.GetInt("KratyrCompanions.Leadership", 0);
		}

		internal static int Level(Player player)
		{
			//IL_0000: 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)
			if ((int)skill == 0 || !Object.op_Implicit((Object)(object)player))
			{
				return 0;
			}
			return RawLevel(((Character)player).GetSkills(), skill);
		}

		internal static int RawLevel(Skills skills, SkillType type)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<SkillType, Skill> dictionary = (Object.op_Implicit((Object)(object)skills) ? (SkillData?.GetValue(skills) as Dictionary<SkillType, Skill>) : null);
			if (dictionary == null || !dictionary.TryGetValue(type, out var value))
			{
				return 0;
			}
			return Mathf.FloorToInt(value.m_level);
		}

		private static void HookTaming(Harmony harmony)
		{
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Expected O, but got Unknown
			//IL_00eb: Expected O, but got Unknown
			if (!Chainloader.PluginInfos.TryGetValue("balrond.astafaraios.BalrondExtraSkills", out var value) || !Object.op_Implicit((Object)(object)value.Instance))
			{
				return;
			}
			try
			{
				if (((object)value.Instance).GetType().Assembly.GetType("BalrondExtraSkills.TamingIntegrationApi")?.GetField("SkillId")?.GetRawConstantValue() is int num && num != 0)
				{
					tamingSkill = (SkillType)num;
					MethodInfo methodInfo = AccessTools.Method(typeof(Skills), "RaiseSkill", new Type[2]
					{
						typeof(SkillType),
						typeof(float)
					}, (Type[])null);
					harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(AccessTools.Method(typeof(Leadership), "BeforeTamingXp", (Type[])null, (Type[])null)), new HarmonyMethod(AccessTools.Method(typeof(Leadership), "AfterTamingXp", (Type[])null, (Type[])null)), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogWarning((object)("Leadership Taming integration: " + ex));
			}
		}

		private static void BeforeTamingXp(Skills __instance, SkillType __0, float __1, out int? __state)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			__state = null;
			if (Plugin.Active && __0 == tamingSkill && __1 > 0f && CompanionNetwork.LeadershipTraining.Taming > 0f)
			{
				Player localPlayer = Player.m_localPlayer;
				if (Object.op_Implicit((Object)(object)localPlayer) && ((Character)localPlayer).GetSkills() == __instance)
				{
					__state = RawLevel(__instance, tamingSkill);
				}
			}
		}

		private static void AfterTamingXp(Skills __instance, int? __state)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			if (__state.HasValue)
			{
				int num = RawLevel(__instance, tamingSkill) - __state.Value;
				Player localPlayer = Player.m_localPlayer;
				float item = CompanionNetwork.LeadershipTraining.Taming;
				if (num > 0 && item > 0f && Object.op_Implicit((Object)(object)localPlayer))
				{
					((Character)localPlayer).RaiseSkill(skill, (float)num * item);
				}
			}
		}

		internal static void Tick()
		{
			//IL_0000: 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)
			if ((int)skill == 0)
			{
				return;
			}
			Player localPlayer = Player.m_localPlayer;
			float time = Time.time;
			if ((Object)(object)localPlayer != (Object)(object)trackedPlayer)
			{
				trackedPlayer = localPlayer;
				nextSync = 0f;
				lastSample = time;
			}
			if (!Object.op_Implicit((Object)(object)localPlayer) || Time.unscaledTime < nextSync)
			{
				return;
			}
			nextSync = Time.unscaledTime + 2f;
			float num = Mathf.Clamp(time - lastSample, 0f, 3f);
			lastSample = time;
			float item = CompanionNetwork.LeadershipTraining.Nearby;
			if (!((Character)localPlayer).IsDead() && item > 0f && num > 0f && HasNearbyFollower(localPlayer))
			{
				((Character)localPlayer).RaiseSkill(skill, item * num / 60f);
			}
			ZNetView val = GameAccess.View((Component)(object)localPlayer);
			if (Object.op_Implicit((Object)(object)val) && val.IsValid() && val.IsOwner())
			{
				ZDO zDO = val.GetZDO();
				int num2 = Level(localPlayer);
				if (Level(zDO) != num2)
				{
					zDO.Set("KratyrCompanions.Leadership", num2);
				}
			}
		}

		private static bool HasNearbyFollower(Player player)
		{
			//IL_0066: 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_007b: Unknown result type (might be due to invalid IL or missing references)
			long playerID = player.GetPlayerID();
			string playerName = player.GetPlayerName();
			float num = CompanionNetwork.CommandRange;
			foreach (Character allCharacter in Character.GetAllCharacters())
			{
				if (!Object.op_Implicit((Object)(object)allCharacter) || (Object)(object)allCharacter == (Object)(object)player || allCharacter.IsDead() || !allCharacter.IsTamed())
				{
					continue;
				}
				Vector3 val = ((Component)allCharacter).transform.position - ((Component)player).transform.position;
				if (!(((Vector3)(ref val)).sqrMagnitude > num * num))
				{
					ZDO val2 = GameAccess.Data((Component)(object)allCharacter);
					if (val2 != null && (val2.GetLong(CompanionState.ControllerKey, 0L) == playerID || (val2.GetLong(CompanionState.RevisionKey, 0L) == 0L && GameAccess.SavedFollow(val2) == playerName)) && GameAccess.Eligible(((Component)allCharacter).GetComponent<Tameable>()))
					{
						return true;
					}
				}
			}
			return false;
		}
	}
	internal static class Loyalty
	{
		private sealed class Runtime
		{
			internal float NextUpdate;
		}

		private const string ValueKey = "KratyrCompanions.Loyalty";

		private const string CareKey = "KratyrCompanions.LastCare";

		private const string UpdateKey = "KratyrCompanions.LoyaltyUpdated";

		private const string PetKey = "KratyrCompanions.LastPet";

		private const string FollowSecondsKey = "KratyrCompanions.ActiveMoodSeconds";

		private const string EffectivenessKey = "KratyrCompanions.LoyaltyEffectiveness";

		private const string NoticeRpc = "KC_LoyaltyNotice_v8";

		private const string PetRpc = "KC_LoyaltyPet_v8";

		private const string BrokenKey = "KratyrCompanions.BondBroken";

		private static readonly ConditionalWeakTable<Tameable, Runtime> timers = new ConditionalWeakTable<Tameable, Runtime>();

		internal static long Now
		{
			get
			{
				if (!Object.op_Implicit((Object)(object)ZNet.instance))
				{
					return 0L;
				}
				return (long)ZNet.instance.GetTimeSeconds();
			}
		}

		internal static bool BondBroken(ZDO data)
		{
			if (data != null)
			{
				return data.GetBool("KratyrCompanions.BondBroken", false);
			}
			return false;
		}

		internal static float ProgressionValue(ZDO data)
		{
			LoyaltyRules loyaltyRules = CompanionNetwork.LoyaltyRules;
			if (loyaltyRules == null || !loyaltyRules.Enabled)
			{
				return 0f;
			}
			return Mathf.Clamp(data.GetFloat("KratyrCompanions.Loyalty", 0f), 0f, 100f);
		}

		internal static (float Value, float Effectiveness, long LastCare) GrowthSnapshot(ZDO data)
		{
			return (Value: data.GetFloat("KratyrCompanions.Loyalty", -1f), Effectiveness: data.GetFloat("KratyrCompanions.LoyaltyEffectiveness", -1f), LastCare: data.GetLong("KratyrCompanions.LastCare", 0L));
		}

		internal static void InitializeOffspring(Character child)
		{
			ZDO val = GameAccess.Data((Component)(object)child);
			LoyaltyRules loyaltyRules = CompanionNetwork.LoyaltyRules;
			if (val != null && loyaltyRules != null && loyaltyRules.Enabled && val.GetFloat("KratyrCompanions.Loyalty", -1f) < 0f)
			{
				Initialize(val, loyaltyRules, child);
			}
		}

		internal static void TransferGrowth((float Value, float Effectiveness, long LastCare) previous, ZDO next)
		{
			if (!(previous.Value < 0f))
			{
				next.Set("KratyrCompanions.Loyalty", previous.Value);
				next.Set("KratyrCompanions.LoyaltyEffectiveness", previous.Effectiveness);
				next.Set("KratyrCompanions.LastCare", previous.LastCare);
				next.Set("KratyrCompanions.LoyaltyUpdated", Now);
			}
		}

		internal static bool RogueSummon(ZDO data)
		{
			if (BondBroken(data))
			{
				return data.GetLong(CompanionState.SummonKey, 0L) == 1;
			}
			return false;
		}

		internal static Player OriginalSummoner(ZDO data)
		{
			long num = GameAccess.SummonerId(data);
			if (num != 0L)
			{
				return GameAccess.FindPlayer(num);
			}
			string text = GameAccess.SavedFollow(data);
			foreach (Player allPlayer in Player.GetAllPlayers())
			{
				if (Object.op_Implicit((Object)(object)allPlayer) && text == allPlayer.GetPlayerName() && GameAccess.UniqueNativeName(text, allPlayer.GetPlayerID()))
				{
					return allPlayer;
				}
			}
			return null;
		}

		private static LoyaltyProfile Profile(LoyaltyRules rules, ZDO data, Character creature)
		{
			GameObject val = GameAccess.Prefab(data);
			string prefab = (Object.op_Implicit((Object)(object)val) ? ((Object)val).name : (Object.op_Implicit((Object)(object)creature) ? ((Object)((Component)creature).gameObject).name.Replace("(Clone)", "").Trim() : ""));
			Character val2 = (Object.op_Implicit((Object)(object)val) ? val.GetComponent<Character>() : null);
			Tameable tame = (Object.op_Implicit((Object)(object)creature) ? ((Component)creature).GetComponent<Tameable>() : null);
			bool summon = (Object.op_Implicit((Object)(object)creature) ? GameAccess.IsSummon(tame, data) : GameAccess.IsSummon(data));
			float health = (Object.op_Implicit((Object)(object)val2) ? val2.m_health : (Object.op_Implicit((Object)(object)creature) ? creature.m_health : 0f));
			return rules.Profile(prefab, summon, LoyaltyRules.IsDomesticated(prefab), health);
		}

		private static int Stars(Character creature)
		{
			if (!Object.op_Implicit((Object)(object)creature))
			{
				return 0;
			}
			return Mathf.Max(0, creature.GetLevel() - 1);
		}

		private static float Value(ZDO data, LoyaltyProfile profile, int stars)
		{
			float num = data.GetFloat("KratyrCompanions.Loyalty", -1f);
			if (!(num >= 0f))
			{
				return LoyaltyRules.Initial(profile, stars);
			}
			return Math.Min(100f, num);
		}

		internal static int? Display(Character creature, ZDO data)
		{
			LoyaltyRules loyaltyRules = CompanionNetwork.LoyaltyRules;
			if (loyaltyRules == null || !loyaltyRules.Enabled)
			{
				return null;
			}
			float num = data.GetFloat("KratyrCompanions.Loyalty", -1f);
			if (num >= 0f)
			{
				return Mathf.CeilToInt(Math.Min(100f, num));
			}
			if (!GameAccess.Eligible(((Component)creature).GetComponent<Tameable>()))
			{
				return null;
			}
			return Mathf.CeilToInt(Value(data, Profile(loyaltyRules, data, creature), Stars(creature)));
		}

		internal static int? DisplayEffectiveness(ZDO data)
		{
			float num = data.GetFloat("KratyrCompanions.LoyaltyEffectiveness", -1f);
			if (!(num >= 0f))
			{
				return null;
			}
			return Mathf.RoundToInt(Math.Min(100f, num));
		}

		internal static bool RefusesFollow(ZDO data)
		{
			LoyaltyRules loyaltyRules = CompanionNetwork.LoyaltyRules;
			if (loyaltyRules != null && loyaltyRules.Enabled)
			{
				if (data.GetFloat("KratyrCompanions.Loyalty", -1f) != 0f)
				{
					return MoodRules.RefusesFollow(CompanionMood.Current(data));
				}
				return true;
			}
			return false;
		}

		internal static void SootheByCommand(ZDO data, Command command)
		{
			if (MoodRules.CanSootheByCommand(command) && MoodRules.IsMild(CompanionMood.Current(data)))
			{
				CompanionMood.Soothe(data, pet: false, data.GetFloat("KratyrCompanions.Loyalty", 50f), data.GetFloat("KratyrCompanions.LoyaltyEffectiveness", 50f), out var _);
			}
		}

		private static int Skill(Player player)
		{
			if (!((Object)(object)player == (Object)(object)Player.m_localPlayer))
			{
				return Leadership.Level(GameAccess.Data((Component)(object)player));
			}
			return Leadership.Level(player);
		}

		private static bool CanCare(CompanionState state, long player)
		{
			if (player != 0L)
			{
				if (state.Owner != player && state.Borrower != player && state.Controller != player)
				{
					if (state.Owner == 0L)
					{
						return state.Controller == 0;
					}
					return false;
				}
				return true;
			}
			return false;
		}

		internal static void OnTamed(Tameable tame, ZDO data)
		{
			if (GameAccess.Tamed(data) && !RogueSummon(data))
			{
				if (BondBroken(data))
				{
					data.Set("KratyrCompanions.BondBroken", false);
					data.Set("KratyrCompanions.Loyalty", -1f);
					data.Set("KratyrCompanions.LoyaltyEffectiveness", -1f);
					CompanionMood.ResetBond(data);
					CompanionBond.Clear(data);
					CompanionState companionState = CompanionState.Read(data);
					companionState.Revision++;
					companionState.Write(data);
				}
				LoyaltyRules loyaltyRules = CompanionNetwork.LoyaltyRules;
				if (loyaltyRules != null && loyaltyRules.Enabled && GameAccess.Eligible(tame))
				{
					Initialize(data, loyaltyRules, ((Component)tame).GetComponent<Character>());
				}
			}
		}

		private static void Initialize(ZDO data, LoyaltyRules rules, Character creature)
		{
			long now = Now;
			LoyaltyProfile profile = Profile(rules, data, creature);
			data.Set("KratyrCompanions.Loyalty", LoyaltyRules.Initial(profile, Stars(creature), Random.value));
			data.Set("KratyrCompanions.LoyaltyEffectiveness", LoyaltyRules.InitialEffectiveness(profile, Random.value));
			data.Set("KratyrCompanions.LastCare", now);
			data.Set("KratyrCompanions.LoyaltyUpdated", now);
			data.Set("KratyrCompanions.LastPet", 0L);
			data.Set("KratyrCompanions.ActiveMoodSeconds", 0L);
		}

		internal static void RegisterPet(Tameable tame, ZNetView view)
		{
			view.Register<string>("KC_LoyaltyNotice_v8", (Action<long, string>)delegate(long sender, string message)
			{
				if (Plugin.Active && view.IsValid() && sender == view.GetZDO().GetOwner() && message.Length <= 250)
				{
					Plugin.Notify(message);
				}
			});
			view.Register<ZDOID>("KC_LoyaltyPet_v8", (Action<long, ZDOID>)delegate(long sender, ZDOID playerId)
			{
				//IL_004c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0060: Unknown result type (might be due to invalid IL or missing references)
				//IL_0066: Unknown result type (might be due to invalid IL or missing references)
				if (Plugin.Active && view.IsValid() && view.IsOwner())
				{
					LoyaltyRules loyaltyRules = CompanionNetwork.LoyaltyRules;
					if (loyaltyRules != null && loyaltyRules.Enabled)
					{
						ZDO zDO = view.GetZDO();
						ZDOMan instance = ZDOMan.instance;
						ZDO val = ((instance != null) ? instance.GetZDO(playerId) : null);
						if (val != null && val.GetOwner() == sender && !(Vector3.Distance(val.GetPosition(), zDO.GetPosition()) > 6f) && GameAccess.Tamed(zDO) && GameAccess.Eligible(tame))
						{
							long num = GameAccess.PlayerId(val);
							CompanionState stored = CompanionState.Read(zDO);
							bool summon = GameAccess.IsSummon(tame, zDO);
							string nativeFollow = GameAccess.SavedFollow(zDO);
							Player obj = GameAccess.FindPlayer(num);
							CompanionState state = GameAccess.ControlState(stored, summon, nativeFollow, num, ((obj != null) ? obj.GetPlayerName() : null) ?? "");
							if (CanCare(state, num) && (state.Revision != 0L || state.Controller != 0L || GameAccess.SavedFollow(zDO).Length == 0))
							{
								Character component = ((Component)tame).GetComponent<Character>();
								if (Object.op_Implicit((Object)(object)component) && !component.IsDead())
								{
									if (zDO.GetFloat("KratyrCompanions.Loyalty", -1f) < 0f)
									{
										Initialize(zDO, loyaltyRules, component);
									}
									long now = Now;
									long num2 = zDO.GetLong("KratyrCompanions.LastPet", 0L);
									if (loyaltyRules.Pet > 0f && (num2 == 0L || now - num2 >= loyaltyRules.PetSeconds) && Change(tame, zDO, loyaltyRules, loyaltyRules.Pet))
									{
										zDO.Set("KratyrCompanions.LastPet", now);
										CompanionBond.Gain(zDO, state, num, 0.75f, now);
									}
									bool attempted;
									string text = (CompanionMood.Soothe(zDO, pet: true, zDO.GetFloat("KratyrCompanions.Loyalty", 50f), zDO.GetFloat("KratyrCompanions.LoyaltyEffectiveness", 50f), out attempted) ? "settles down" : (attempted ? "pulls away" : CompanionMood.Text(component, zDO)));
									view.InvokeRPC(sender, "KC_LoyaltyNotice_v8", new object[1] { GameAccess.CommandLabel(tame, zDO) + " " + text + "." });
								}
							}
						}
					}
				}
			});
		}

		internal static void Pet(Tameable tame, Player player)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			LoyaltyRules loyaltyRules = CompanionNetwork.LoyaltyRules;
			if (loyaltyRules != null && loyaltyRules.Enabled && !((Object)(object)player != (Object)(object)Player.m_localPlayer))
			{
				ZNetView val = GameAccess.View((Component)(object)tame);
				ZDO val2 = GameAccess.Data((Component)(object)player);
				if (Object.op_Implicit((Object)(object)val) && val.IsValid() && val2 != null)
				{
					val.InvokeRPC("KC_LoyaltyPet_v8", new object[1] { val2.m_uid });
				}
			}
		}

		internal static void Feed(Tameable tame, long feeder)
		{
			LoyaltyRules loyaltyRules = CompanionNetwork.LoyaltyRules;
			if (loyaltyRules == null || !loyaltyRules.Enabled)
			{
				return;
			}
			ZNetView val = GameAccess.View((Component)(object)tame);
			if (!Object.op_Implicit((Object)(object)val) || !val.IsValid() || !val.IsOwner() || !GameAccess.Eligible(tame))
			{
				return;
			}
			ZDO zDO = val.GetZDO();
			if (GameAccess.Tamed(zDO) && Change(tame, zDO, loyaltyRules, loyaltyRules.Feed))
			{
				CompanionMood.OfferedMeal(zDO, zDO.GetFloat("KratyrCompanions.LoyaltyEffectiveness", 50f), loyaltyRules.Moods);
				if (feeder != 0L)
				{
					CompanionBond.Gain(zDO, CompanionState.Read(zDO, readNames: false), feeder, 0.5f, Now);
				}
			}
		}

		internal static bool NearbyPartner(long player, Vector3 position)
		{
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: 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)
			Player val = ((player == 0L) ? null : GameAccess.FindPlayer(player));
			if (Object.op_Implicit((Object)(object)val) && !((Character)val).IsDead())
			{
				Vector3 val2 = ((Component)val).transform.position - position;
				return ((Vector3)(ref val2)).sqrMagnitude <= 256f;
			}
			return false;
		}

		internal static void Attacked(Character creature, Character target, HitData hit)
		{
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			LoyaltyRules loyaltyRules = CompanionNetwork.LoyaltyRules;
			if (loyaltyRules == null || !loyaltyRules.Enabled || !Object.op_Implicit((Object)(object)creature) || !creature.IsTamed() || target.IsPlayer() || target.IsTamed() || target.IsDead() || hit.GetTotalDamage() <= 0f)
			{
				return;
			}
			ZNetView val = GameAccess.View((Component)(object)creature);
			if (Object.op_Implicit((Object)(object)val) && val.IsValid() && val.IsOwner())
			{
				ZDO zDO = val.GetZDO();
				CompanionState state = CompanionState.Read(zDO, readNames: false);
				long handler = state.Handler;
				if (CompanionBond.IsPartner(state, handler) && !state.AwaitingSlot && !BondBroken(zDO) && !MoodRules.IsHostile(CompanionMood.Current(zDO)) && NearbyPartner(handler, ((Component)creature).transform.position) && BaseAI.IsEnemy(creature, target))
				{
					CompanionBond.Combat(zDO, state, handler, Now);
				}
			}
		}

		private static bool Change(Tameable tame, ZDO data, LoyaltyRules rules, float gain)
		{
			Character component = ((Component)tame).GetComponent<Character>();
			if (!Object.op_Implicit((Object)(object)component) || component.IsDead() || BondBroken(data))
			{
				return false;
			}
			if (data.GetFloat("KratyrCompanions.Loyalty", -1f) < 0f)
			{
				Initialize(data, rules, component);
			}
			float num = data.GetFloat("KratyrCompanions.Loyalty", 0f);
			if (num <= 0f)
			{
				return false;
			}
			LoyaltyProfile loyaltyProfile = Profile(rules, data, component);
			data.Set("KratyrCompanions.LastCare", Now);
			data.Set("KratyrCompanions.Loyalty", LoyaltyRules.Clamp(num + gain * loyaltyProfile.GainScale, 0f, 100f));
			return true;
		}

		internal static void Damaged(Character creature, ZDO data, Character attacker, float healthLost, bool staggered)
		{
			LoyaltyRules loyaltyRules = CompanionNetwork.LoyaltyRules;
			if (loyaltyRules == null || !loyaltyRules.Enabled || !GameAccess.Tamed(data) || creature.IsDead() || creature.GetHealth() <= 0f || BondBroken(data) || data.GetLong(CompanionState.AwaitingSlotKey, 0L) != 0L)
			{
				return;
			}
			Tameable component = ((Component)creature).GetComponent<Tameable>();
			if (GameAccess.Eligible(component))
			{
				CompanionState companionState = CompanionState.Read(data);
				bool flag = false;
				Player val = (Player)(object)((attacker is Player) ? attacker : null);
				if (val != null)
				{
					long playerID = val.GetPlayerID();
					companionState = GameAccess.ControlState(companionState, GameAccess.IsSummon(component, data), GameAccess.SavedFollow(data), playerID, val.GetPlayerName());
					flag = playerID != 0L && (playerID == companionState.Owner || playerID == companionState.Handler);
					CompanionBond.Hurt(data, playerID, healthLost / Math.Max(1f, creature.GetMaxHealth()), Now);
				}
				if (data.GetFloat("KratyrCompanions.Loyalty", -1f) < 0f)
				{
					Initialize(data, loyaltyRules, creature);
				}
				LoyaltyProfile profile = Profile(loyaltyRules, data, creature);
				float num = data.GetFloat("KratyrCompanions.Loyalty", 0f) - loyaltyRules.Hurt(healthLost, creature.GetMaxHealth(), flag, profile);
				if (flag && CompanionMood.ReactToHandlerHit(data, num, staggered))
				{
					num = 0f;
				}
				data.Set("KratyrCompanions.Loyalty", Math.Max(0f, num));
				if (num <= 0f)
				{
					Break(component, creature, data, companionState);
				}
			}
		}

		internal static void Update(Tameable tame, ZDO data)
		{
			//IL_01cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ca: Unknown result type (might be due to invalid IL or missing references)
			LoyaltyRules loyaltyRules = CompanionNetwork.LoyaltyRules;
			if (!GameAccess.Tamed(data) || BondBroken(data))
			{
				return;
			}
			bool flag = loyaltyRules?.Enabled ?? false;
			if (!flag && (data.GetLong(CompanionState.BorrowerKey, 0L) == 0L || data.GetLong(CompanionState.OwnerKey, 0L) != 0L))
			{
				return;
			}
			Runtime value = timers.GetValue(tame, (Tameable _) => new Runtime());
			if (Time.time < value.NextUpdate)
			{
				return;
			}
			value.NextUpdate = Time.time + 10f;
			Character component = ((Component)tame).GetComponent<Character>();
			if (!Object.op_Implicit((Object)(object)component) || component.IsDead() || !GameAccess.Eligible(tame))
			{
				return;
			}
			CompanionState companionState = CompanionState.Read(data);
			long controller = companionState.Controller;
			if (companionState.ClearOrphanedLoan())
			{
				if (controller != companionState.Controller)
				{
					GameAccess.ApplyMovement(tame, null, companionState.IsSummon);
				}
				companionState.Revision++;
				companionState.Write(data);
			}
			if (!flag)
			{
				return;
			}
			if (data.GetFloat("KratyrCompanions.Loyalty", -1f) < 0f)
			{
				Initialize(data, loyaltyRules, component);
			}
			float num = data.GetFloat("KratyrCompanions.Loyalty", 0f);
			if (num <= 0f)
			{
				Break(tame, component, data, companionState);
				return;
			}
			long now = Now;
			long num2 = data.GetLong("KratyrCompanions.LoyaltyUpdated", now);
			long num3 = data.GetLong("KratyrCompanions.LastCare", now);
			data.Set("KratyrCompanions.LoyaltyUpdated", now);
			LoyaltyProfile profile = Profile(loyaltyRules, data, component);
			float num4 = data.GetFloat("KratyrCompanions.LoyaltyEffectiveness", -1f);
			float num5 = (float)Math.Min(20L, Math.Max(0L, now - num2)) / 60f * 0.3f;
			if (companionState.Owner != 0L && num5 > 0f)
			{
				Vector3 position = ((Component)component).transform.position;
				if (NearbyPartner(companionState.Owner, position))
				{
					CompanionBond.Gain(data, companionState, companionState.Owner, num5, now);
				}
				if (companionState.Borrower != 0L && companionState.Borrower != companionState.Owner && NearbyPartner(companionState.Borrower, position))
				{
					CompanionBond.Gain(data, companionState, companionState.Borrower, num5, now);
				}
			}
			if (num4 < 0f)
			{
				num4 = LoyaltyRules.InitialEffectiveness(profile, Random.value);
				data.Set("KratyrCompanions.LoyaltyEffectiveness", num4);
			}
			MonsterAI component2 = ((Component)tame).GetComponent<MonsterAI>();
			GameObject followTarget = component2.GetFollowTarget();
			Player val = ((companionState.Controller != 0L) ? GameAccess.FindPlayer(companionState.Controller) : ((companionState.Revision == 0L && Object.op_Implicit((Object)(object)followTarget)) ? followTarget.GetComponent<Player>() : null));
			bool flag2 = tame.HaveRider();
			bool flag3 = Object.op_Implicit((Object)(object)val) && !((Character)val).IsDead() && Vector3.Distance(((Component)val).transform.position, ((Component)component).transform.position) <= (float)CompanionNetwork.CommandRange;
			double hours = (double)(now - Math.Max(num2, num3 + (long)loyaltyRules.GraceMinutes * 60L)) / 3600.0;
			num -= loyaltyRules.Neglect(num, hours, profile);
			if (flag3 || flag2)
			{
				num += Math.Min(20f, Math.Max(0L, now - num2)) / 60f * loyaltyRules.BondPerMinute * profile.GainScale * (1f + LoyaltyRules.LeadershipFactor(flag3 ? Skill(val) : 0));
				data.Set("KratyrCompanions.LastCare", now);
			}
			num = LoyaltyRules.Clamp(num, 0f, 100f);
			if (num != data.GetFloat("KratyrCompanions.Loyalty", 0f))
			{
				data.Set("KratyrCompanions.Loyalty", num);
			}
			if (!MoodRules.CountsTime(flag3, flag2, CompanionMood.Current(data)) || loyaltyRules.RiskPercent <= 0f)
			{
				return;
			}
			long num6 = data.GetLong("KratyrCompanions.ActiveMoodSeconds", 0L) + Math.Min(10L, Math.Max(0L, now - num2));
			if (num6 < loyaltyRules.CheckSeconds)
			{
				data.Set("KratyrCompanions.ActiveMoodSeconds", num6);
				return;
			}
			data.Set("KratyrCompanions.ActiveMoodSeconds", 0L);
			float num7 = MoodRules.Chance(num, num4, loyaltyRules.RiskPercent / 12f * profile.Difficulty, Stars(component), Skill(val), CompanionMood.Content(data, now));
			if (Random.value >= num7)
			{
				return;
			}
			companionState = GameAccess.ControlState(companionState, GameAccess.IsSummon(tame, data), GameAccess.SavedFollow(data), val.GetPlayerID(), val.GetPlayerName());
			if (companionState.Controller == val.GetPlayerID() && (!companionState.IsSummon || companionState.Owner != 0L))
			{
				Character val2 = ((companionState.Mode == CombatMode.Passive) ? null : CompanionMood.ScaryEnemy(component));
				CreatureMood creatureMood = MoodRules.Roll(num, Random.Range(0, 100), Object.op_Implicit((Object)(object)val2), loyaltyRules.Moods.DestructiveEnabled);
				if (MoodRules.IsHostile(creatureMood) && ProviderCompatibility.UsesPassiveAnimalAi(component2))
				{
					creatureMood = CreatureMood.Independent;
				}
				if (creatureMood == CreatureMood.Independent)
				{
					GameAccess.ApplyMovement(tame, null, companionState.IsSummon, patrol: false);
					companionState.Controller = 0L;
					companionState.AwaitingSlot = false;
				}
				if (creatureMood == CreatureMood.Independent || companionState.Revision == 0L)
				{
					companionState.Revision++;
					companionState.Write(data);
				}
				CompanionMood.Start(data, component, creatureMood, val2);
				Notify(tame, companionState, val.GetPlayerID(), GameAccess.CommandLabel(tame, data) + " " + CompanionMood.Text(component, data) + ".");
			}
		}

		private static void Break(Tameable tame, Character creature, ZDO data, CompanionState state)
		{
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: 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)
			if (tame.HaveRider() || BondBroken(data))
			{
				return;
			}
			bool flag = GameAccess.IsSummon(tame, data);
			GameObject val = GameAccess.Prefab(data);
			Character val2 = (Object.op_Implicit((Object)(object)val) ? val.GetComponent<Character>() : null);
			string text = GameAccess.CommandLabel(tame, data);
			if (Object.op_Implicit((Object)(object)tame.m_saddleItem))
			{
				tame.DropSaddle(((Component)creature).transform.position);
			}
			GameAccess.ApplyMovement(tame, null, flag, patrol: false);
			if (Object.op_Implicit((Object)(object)val2))
			{
				creature.m_faction = val2.m_faction;
				creature.m_group = val2.m_group;
			}
			data.Set("KratyrCompanions.BondBroken", true);
			CompanionMood.ResetBond(data);
			if (flag)
			{
				long num = GameAccess.SummonerId(data);
				if (num == 0L)
				{
					long num2;
					if (state.Owner == 0L)
					{
						Player obj = OriginalSummoner(data);
						num2 = ((obj != null) ? obj.GetPlayerID() : 0);
					}
					else
					{
						num2 = state.Owner;
					}
					num = num2;
				}
				data.Set("KratyrCompanions.OriginalSummoner", num);
			}
			data.Set(ZDOVars.s_tameTimeLeft, tame.m_tamingTime);
			tame.m_startsTamed = false;
			creature.SetTamed(false);
			CompanionState companionState = default(CompanionState);
			companionState.Revision = state.Revision + 1;
			companionState.Summon = (flag ? 1 : 0);
			companionState.Write(data);
			Notify(tame, state, 0L, text + " broke its bond and went wild.");
		}

		private static void Notify(Tameable tame, CompanionState state, long handler, string message)
		{
			ZNetView val = GameAccess.View((Component)(object)tame);
			foreach (Player allPlayer in Player.GetAllPlayers())
			{
				if (!Object.op_Implicit((Object)(object)allPlayer))
				{
					continue;
				}
				long playerID = allPlayer.GetPlayerID();
				if (playerID == 0L || (playerID != handler && playerID != state.Owner && playerID != state.Borrower && playerID != state.Controller))
				{
					continue;
				}
				if ((Object)(object)allPlayer == (Object)(object)Player.m_localPlayer)
				{
					Plugin.Notify(message);
				}
				else if (Object.op_Implicit((Object)(object)val) && val.IsValid())
				{
					ZDO obj = GameAccess.Data((Component)(object)allPlayer);
					long num = ((obj != null) ? obj.GetOwner() : 0);
					if (num != 0L)
					{
						val.InvokeRPC(num, "KC_LoyaltyNotice_v8", new object[1] { message });
					}
				}
			}
		}
	}
	internal sealed class LoyaltyConfig
	{
		internal LoyaltyRules Rules { get; private set; }

		internal static void Write(ZPackage packet, LoyaltyRules rules)
		{
			packet.Write(rules.Enabled);
			packet.Write(rules.Species);
			packet.Write(rules.BondPerMinute);
			packet.Write(rules.Feed);
			packet.Write(rules.Pet);
			packet.Write(rules.PetSeconds);
			packet.Write(rules.BattleLoss);
			packet.Write(rules.HandlerLoss);
			packet.Write(rules.GraceMinutes);
			packet.Write(rules.NeglectPerHour);
			packet.Write(rules.CheckSeconds);
			packet.Write(rules.RiskPercent);
			packet.Write(rules.Moods.DestructiveEnabled);
			packet.Write((int)rules.Moods.Targets);
			packet.Write(rules.Moods.ContentMin);
			packet.Write(rules.Moods.ContentMax);
			packet.Write(rules.Moods.ContentCooldown);
		}

		internal static LoyaltyRules Read(ZPackage packet)
		{
			return new LoyaltyRules(packet.ReadBool(), packet.ReadString(), packet.ReadSingle(), packet.ReadSingle(), packet.ReadSingle(), packet.ReadInt(), packet.ReadSingle(), packet.ReadSingle(), packet.ReadInt(), packet.ReadSingle(), packet.ReadInt(), packet.ReadSingle(), new MoodOptions(packet.ReadBool(), (DestructiveTargets)packet.ReadInt(), packet.ReadInt(), packet.ReadInt(), packet.ReadInt()));
		}

		internal LoyaltyConfig(ConfigFile config)
		{
			LoyaltyConfig loyaltyConfig = this;
			ConfigEntry<bool> enabled = config.Bind<bool>("Loyalty", "Enabled", true, "Host: track companion loyalty, care and behavior.");
			ConfigEntry<string> species = config.Bind<string>("Loyalty", "Species", "", "Host: prefab:starting-min,starting-max,effectiveness-min,effectiveness-max,gain,loss[,risk-multiplier]. Separate entries with a semicolon. Empty uses the built-in roster. Legacy four-number overrides are accepted.");
			ConfigEntry<bool> val = config.Bind<bool>("Loyalty", "MoodRosterDefaultsApplied", false, "Internal one-time update of the old generated species defaults.");
			if (!val.Value)
			{
				if (species.Value == "Troll:42,3,0.65,1.35")
				{
					species.Value = "";
				}
				val.Value = true;
			}
			ConfigEntry<float> bond = Float("GainPerActiveMinute", 0.35f, 20f, "Host: loyalty percentage points per minute following nearby.");
			ConfigEntry<float> feed = Float("GainPerFeeding", 0.75f, 20f, "Host: points for eating a meal.");
			ConfigEntry<float> pet = Float("GainPerPet", 0.4f, 20f, "Host: points per pet after the cooldown.");
			ConfigEntry<int> petSeconds = Int("PetCooldownSeconds", 600, 5, 86400, "Host: shared cooldown per creature.");
			ConfigEntry<float> hurt = Float("LossPerHealthBar", 0.8f, 20f, "Host: points lost per maximum-health equivalent of actual damage.");
			ConfigEntry<float> handler = Float("LossPerHandlerHit", 6f, 100f, "Host: additional loss per damaging hit from owner, borrower or active handler.");
			ConfigEntry<int> grace = Int("NeglectGraceMinutes", 120, 0, 10080, "Host: time without care before neglect starts.");
			ConfigEntry<float> neglect = Float("NeglectLossPerHour", 1f, 20f, "Host: points lost per hour of neglect. Neglect alone stops at 30%.");
			ConfigEntry<int> interval = Int("BehaviorCheckSeconds", 180, 15, 86400, "Host: active following seconds between mood rolls.");
			ConfigEntry<float> chance = Float("BaseMisbehaviorChance", 12f, 100f, "Host: scale the mood risk curve. 12 is normal strength and 0 disables new moods.");
			ConfigEntry<bool> destructive = config.Bind<bool>("Moods", "EnableDestructiveMood", true, "Host: allow occasional destructive moods.");
			ConfigEntry<DestructiveTargets> destructiveTargets = config.Bind<DestructiveTargets>("Moods", "DestructiveTargets", DestructiveTargets.EnvironmentOnly, "Host: EnvironmentOnly preserves player builds. CraftingStations adds player-placed crafting stations. PlayerStructures allows other player-built pieces too.");
			ConfigEntry<int> contentMin = MoodSeconds("ContentMinSeconds", 30, 0, "Host: duration with zero Effectiveness.");
			ConfigEntry<int> contentMax = MoodSeconds("ContentMaxSeconds", 120, 0, "Host: duration with 100 Effectiveness. Set both durations to 0 to disable Content.");
			ConfigEntry<int> contentCooldown = MoodSeconds("ContentCooldownSeconds", 600, 15, "Host: minimum time between Content starts.");
			Refresh();
			config.SettingChanged += delegate(object _, SettingChangedEventArgs args)
			{
				if (args.ChangedSetting.Definition.Section == "Loyalty" || args.ChangedSetting.Definition.Section == "Moods")
				{
					Refresh();
				}
			};
			ConfigEntry<float> Float(string name, float value, float ma