Decompiled source of Lama Pen v0.1.0

SpellBrigadeLamaPen.dll

Decompiled 7 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppSystem.Reflection;
using SpellBrigadeLamaPen.Core;
using SpellBrigadeLamaPen.Game;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("SpellBrigadeLamaPen")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+6f998c7dce1828d64a3cecc3c9a3a949afd08d02")]
[assembly: AssemblyProduct("SpellBrigadeLamaPen")]
[assembly: AssemblyTitle("SpellBrigadeLamaPen")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.0.0")]
[module: UnverifiableCode]
namespace SpellBrigadeLamaPen
{
	internal static class ModConfig
	{
		public static ConfigEntry<bool> Enabled;

		public static ConfigEntry<bool> LogLamas;

		public static ConfigEntry<bool> TestHotkeys;

		public static void Init(ConfigFile cfg)
		{
			Enabled = cfg.Bind<bool>("General", "Enabled", true, "Charmed lamas lose their charm once they are inside the herding pen, so they stop following you back out. Only works for the host. Can be switched off while playing.");
			LogLamas = cfg.Bind<bool>("Debug", "LogLamas", false, "Write a line to BepInEx/SpellBrigadeLamaPen.log whenever a lama changes what it is doing. Handy for bug reports. Decharms are always logged.");
			TestHotkeys = cfg.Bind<bool>("Debug", "TestHotkeys", false, "For testing, as host inside a run: Ctrl+1 starts a herding objective (when no objective is running), Ctrl+2 charms that objective's lamas that are still outside the pen.");
		}
	}
	internal static class ModLog
	{
		private static ManualLogSource? _log;

		private static StreamWriter? _file;

		private static readonly HashSet<string> Once = new HashSet<string>();

		private static readonly Dictionary<string, float> Throttle = new Dictionary<string, float>();

		public const string CleanExit = "clean exit";

		public static string FilePath => Path.Combine(Paths.BepInExRootPath, "SpellBrigadeLamaPen.log");

		public static string PreviousFilePath => Path.Combine(Paths.BepInExRootPath, "SpellBrigadeLamaPen.prev.log");

		public static string? PreviousCrashStep { get; private set; }

		public static void Init(ManualLogSource log)
		{
			//IL_0096: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Expected O, but got Unknown
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0181: Expected O, but got Unknown
			_log = log;
			bool flag = default(bool);
			try
			{
				if (File.Exists(FilePath))
				{
					File.Copy(FilePath, PreviousFilePath, overwrite: true);
					string text = null;
					string[] array = File.ReadAllLines(FilePath);
					foreach (string text2 in array)
					{
						int num = text2.IndexOf(" STEP  ", StringComparison.Ordinal);
						if (num >= 0)
						{
							string text3 = text2;
							int num2 = num + 7;
							text = text3.Substring(num2, text3.Length - num2).Trim();
						}
					}
					if (text != null && text != "clean exit")
					{
						PreviousCrashStep = text;
					}
				}
			}
			catch (Exception ex)
			{
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(30, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Could not read the previous ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(FilePath);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex.Message);
				}
				log.LogWarning(val);
			}
			try
			{
				_file = new StreamWriter(new FileStream(FilePath, FileMode.Create, FileAccess.Write, FileShare.ReadWrite))
				{
					AutoFlush = true
				};
				_file.WriteLine($"SpellBrigadeLamaPen {"0.1.0"} log, started {DateTime.Now:yyyy-MM-dd HH:mm:ss}");
				if (PreviousCrashStep != null)
				{
					_file.WriteLine("Previous session did not exit cleanly; its last step was: " + PreviousCrashStep + " (log kept as SpellBrigadeLamaPen.prev.log)");
				}
			}
			catch (Exception ex2)
			{
				BepInExWarningLogInterpolatedStringHandler val = new BepInExWarningLogInterpolatedStringHandler(17, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Could not open ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(FilePath);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(": ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(ex2.Message);
				}
				log.LogWarning(val);
			}
		}

		public static void Info(string msg)
		{
			ManualLogSource? log = _log;
			if (log != null)
			{
				log.LogInfo((object)msg);
			}
			ToFile("INFO ", msg);
		}

		public static void Warn(string msg)
		{
			ManualLogSource? log = _log;
			if (log != null)
			{
				log.LogWarning((object)msg);
			}
			ToFile("WARN ", msg);
		}

		public static void Error(string msg)
		{
			ManualLogSource? log = _log;
			if (log != null)
			{
				log.LogError((object)msg);
			}
			ToFile("ERROR", msg);
		}

		public static void Debug(string msg)
		{
			ManualLogSource? log = _log;
			if (log != null)
			{
				log.LogDebug((object)msg);
			}
			ToFile("DEBUG", msg);
		}

		public static void Step(string msg)
		{
			ToFile("STEP ", msg);
		}

		public static void StepOnce(string key, string msg)
		{
			if (Once.Add("step:" + key))
			{
				Step(msg);
			}
		}

		public static void InfoOnce(string key, string msg)
		{
			if (Once.Add(key))
			{
				Info(msg);
			}
		}

		public static void WarnOnce(string key, string msg)
		{
			if (Once.Add(key))
			{
				Warn(msg);
			}
		}

		public static void ErrorThrottled(string key, Exception ex, float now, float seconds = 10f)
		{
			if (!Throttle.TryGetValue(key, out var value) || !(now - value < seconds))
			{
				Throttle[key] = now;
				Error($"[{key}] {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
			}
		}

		private static void ToFile(string level, string msg)
		{
			if (_file == null)
			{
				return;
			}
			try
			{
				lock (_file)
				{
					_file.WriteLine($"{DateTime.Now:HH:mm:ss.fff} {level} {msg}");
				}
			}
			catch
			{
			}
		}
	}
	[BepInPlugin("com.stefanws0.spellbrigadelamapen", "SpellBrigadeLamaPen", "0.1.0")]
	public class Plugin : BasePlugin
	{
		public const string Guid = "com.stefanws0.spellbrigadelamapen";

		public const string Name = "SpellBrigadeLamaPen";

		public const string Version = "0.1.0";

		public override void Load()
		{
			ModLog.Init(((BasePlugin)this).Log);
			ModLog.Step("Load: config");
			ModConfig.Init(((BasePlugin)this).Config);
			ModLog.Step("Load: registering LamaPenRunner");
			((BasePlugin)this).AddComponent<LamaPenRunner>();
			ModLog.Step("Load: done");
			string value = (ModConfig.Enabled.Value ? "" : " (General.Enabled is off: lamas are left alone)");
			ModLog.Info($"{"SpellBrigadeLamaPen"} {"0.1.0"} loaded{value}.");
		}
	}
}
namespace SpellBrigadeLamaPen.Game
{
	internal static class Decharmer
	{
		private static readonly Random Rng = new Random();

		public static bool Decharm(HerdingTarget target, LamaInfo before)
		{
			bool flag = Run(before.Id, "SetWillFollowHerders(false)", delegate
			{
				target.SetWillFollowHerders(false);
			});
			bool flag2 = Run(before.Id, "walk into the pen", delegate
			{
				WalkIntoPen(target, before.Id);
			});
			flag = flag && flag2;
			if (!flag2)
			{
				flag &= Run(before.Id, "TransitionToIdleState() fallback", delegate
				{
					if (LamaSnapshot.Read(target).State == "Follow")
					{
						target.TransitionToIdleState();
					}
				});
			}
			return flag & Run(before.Id, "GetAnimationPlayer().SetIsLoving(false)", delegate
			{
				HerdingTargetAnimationPlayer animationPlayer = target.GetAnimationPlayer();
				if ((Object)(object)animationPlayer != (Object)null)
				{
					animationPlayer.SetIsLoving(false);
				}
			});
		}

		private static void WalkIntoPen(HerdingTarget target, int lamaId)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: 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_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0019: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0125: Unknown result type (might be due to invalid IL or missing references)
			//IL_0132: Unknown result type (might be due to invalid IL or missing references)
			Vector3 zonePosition = target.GetZonePosition();
			Vector3 position = ((Component)target).transform.position;
			float zoneRadius = HerdingObjectiveManager.ZoneRadius;
			FlatPoint flatPoint = PenSpot.Pick(new FlatPoint(position.x, position.z), new FlatPoint(zonePosition.x, zonePosition.z), zoneRadius, (float)Rng.NextDouble(), (float)Rng.NextDouble());
			Vector3 val = default(Vector3);
			((Vector3)(ref val))..ctor(flatPoint.X, position.y, flatPoint.Z);
			ModLog.StepOnce("walk-transition", "first walk: TransitionToWalkingState()");
			target.TransitionToWalkingState();
			ModLog.StepOnce("walk-transition-ok", "first walk: TransitionToWalkingState() ok");
			HerdingTargetBaseState currentState = target.currentState;
			HerdingTargetWalkingState obj = ((currentState == null) ? null : ((Il2CppObjectBase)currentState).TryCast<HerdingTargetWalkingState>()) ?? throw new InvalidOperationException("the lama is not in the walking state after TransitionToWalkingState()");
			ModLog.StepOnce("walk-target", "first walk: walking state targetPosition");
			obj.targetPosition = val;
			ModLog.StepOnce("walk-target-ok", "first walk: walking state targetPosition ok");
			ModLog.StepOnce("walk-towards", "first walk: WalkTowards()");
			target.WalkTowards(val);
			ModLog.StepOnce("walk-towards-ok", "first walk: WalkTowards() ok");
			float value = MathF.Sqrt((flatPoint.X - zonePosition.x) * (flatPoint.X - zonePosition.x) + (flatPoint.Z - zonePosition.z) * (flatPoint.Z - zonePosition.z));
			ModLog.Info($"lama {lamaId}: walking to a spot {value:0.0} from the pen center (pen radius {zoneRadius:0.0}).");
		}

		private static bool Run(int lamaId, string step, Action call)
		{
			ModLog.StepOnce("decharm " + step, "first decharm: " + step);
			try
			{
				call();
				ModLog.StepOnce("decharm-ok " + step, "first decharm: " + step + " ok");
				return true;
			}
			catch (Exception ex)
			{
				ModLog.Warn($"lama {lamaId}: {step} failed: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
				return false;
			}
		}
	}
	public class LamaPenRunner : MonoBehaviour
	{
		public LamaPenRunner(IntPtr ptr)
			: base(ptr)
		{
		}

		public void Update()
		{
			float unscaledTime = Time.unscaledTime;
			try
			{
				LamaWatcher.Update(unscaledTime);
			}
			catch (Exception ex)
			{
				ModLog.ErrorThrottled("runner", ex, unscaledTime);
			}
			try
			{
				TestHotkeys.Update(unscaledTime);
			}
			catch (Exception ex2)
			{
				ModLog.ErrorThrottled("hotkeys", ex2, unscaledTime);
			}
		}

		public void OnApplicationQuit()
		{
			ModLog.Step("clean exit");
		}
	}
	internal static class LamaSnapshot
	{
		public static LamaInfo Read(HerdingTarget target)
		{
			HerdingTargetBaseState currentState = target.currentState;
			return new LamaInfo
			{
				Id = ((Object)target).GetInstanceID(),
				IsOwner = ((NetworkBehaviour)target).IsOwner,
				InPen = target.IsInZone,
				Charmed = target.WillFollowHerders,
				Despawning = target.isDespawning,
				State = StateNames.Short((currentState == null) ? null : ((MemberInfo)((Object)currentState).GetIl2CppType()).Name)
			};
		}
	}
	internal static class LamaWatcher
	{
		private const float TickSeconds = 0.25f;

		private const float LookupSeconds = 2f;

		private static readonly HashSet<int> Decharmed = new HashSet<int>();

		private static readonly LamaChanges Changes = new LamaChanges();

		private static readonly WalkWatchdog Walks = new WalkWatchdog();

		private static HerdingObjectiveManager? _herd;

		private static float _nextTick;

		private static float _nextLookup;

		public static void Update(float now)
		{
			if (now < _nextTick)
			{
				return;
			}
			_nextTick = now + 0.25f;
			if (!ModConfig.Enabled.Value)
			{
				return;
			}
			HerdingObjectiveManager val = CurrentObjective(now);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			List<HerdingTarget> currentHerdingTargets = val.currentHerdingTargets;
			if (currentHerdingTargets == null)
			{
				return;
			}
			for (int i = 0; i < currentHerdingTargets.Count; i++)
			{
				HerdingTarget val2 = currentHerdingTargets[i];
				if (!((Object)(object)val2 == (Object)null) && ((Behaviour)val2).isActiveAndEnabled)
				{
					Visit(val2, now);
				}
			}
		}

		public static void CharmForTest(float now)
		{
			_nextLookup = 0f;
			HerdingObjectiveManager val = CurrentObjective(now);
			if ((Object)(object)val == (Object)null)
			{
				ModLog.Info("Ctrl+2: no running herding objective.");
				return;
			}
			List<HerdingTarget> currentHerdingTargets = val.currentHerdingTargets;
			if (currentHerdingTargets == null)
			{
				ModLog.Info("Ctrl+2: the herding objective has no lama list yet; press again in a moment.");
				return;
			}
			int num = 0;
			for (int i = 0; i < currentHerdingTargets.Count; i++)
			{
				HerdingTarget val2 = currentHerdingTargets[i];
				if ((Object)(object)val2 == (Object)null || !((Behaviour)val2).isActiveAndEnabled)
				{
					continue;
				}
				try
				{
					ModLog.StepOnce("read", "first read of a HerdingTarget");
					LamaInfo lamaInfo = LamaSnapshot.Read(val2);
					ModLog.StepOnce("read-done", "first read of a HerdingTarget done");
					if (TestCharmRule.ShouldCharm(lamaInfo))
					{
						ModLog.StepOnce("test-charm", "first test charm: SetWillFollowHerders(true) + SetIsLoving(true)");
						val2.SetWillFollowHerders(true);
						HerdingTargetAnimationPlayer animationPlayer = val2.GetAnimationPlayer();
						if ((Object)(object)animationPlayer != (Object)null)
						{
							animationPlayer.SetIsLoving(true);
						}
						ModLog.StepOnce("test-charm-ok", "first test charm ok");
						Decharmed.Remove(lamaInfo.Id);
						num++;
					}
				}
				catch (Exception ex)
				{
					ModLog.Warn($"Ctrl+2: charming a lama failed: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
				}
			}
			ModLog.Info($"Ctrl+2: charmed {num} of {currentHerdingTargets.Count} lama(s); the others are in the pen, already charmed or " + "not ours. No lamas yet? They spawn a moment after the objective starts: press again.");
		}

		private static HerdingObjectiveManager? CurrentObjective(float now)
		{
			if (Running(_herd))
			{
				return _herd;
			}
			if (_herd != null)
			{
				ObjectiveEnded();
			}
			if (now < _nextLookup)
			{
				return null;
			}
			_nextLookup = now + 2f;
			ModLog.StepOnce("lookup", "first FindObjectsOfType<HerdingObjectiveManager>");
			Il2CppArrayBase<HerdingObjectiveManager> val = Object.FindObjectsOfType<HerdingObjectiveManager>();
			ModLog.StepOnce("lookup-done", "first FindObjectsOfType<HerdingObjectiveManager> done");
			HerdingObjectiveManager val2 = null;
			if (val != null)
			{
				for (int i = 0; i < val.Length; i++)
				{
					if (Running(val[i]))
					{
						val2 = val[i];
						break;
					}
				}
			}
			if ((Object)(object)val2 == (Object)null)
			{
				return null;
			}
			_herd = val2;
			ModLog.Info("Herding objective found.");
			return _herd;
		}

		private static bool Running(HerdingObjectiveManager? herd)
		{
			if ((Object)(object)herd != (Object)null && ((Behaviour)herd).isActiveAndEnabled)
			{
				return !herd.isDespawning;
			}
			return false;
		}

		private static void ObjectiveEnded()
		{
			ModLog.Info($"Herding objective ended ({Decharmed.Count} lama(s) decharmed).");
			_herd = null;
			Decharmed.Clear();
			Changes.Clear();
			Walks.Clear();
		}

		private static void Visit(HerdingTarget target, float now)
		{
			LamaInfo lamaInfo;
			try
			{
				ModLog.StepOnce("read", "first read of a HerdingTarget");
				lamaInfo = LamaSnapshot.Read(target);
				ModLog.StepOnce("read-done", "first read of a HerdingTarget done");
			}
			catch (Exception ex)
			{
				ModLog.ErrorThrottled("read-lama", ex, now);
				return;
			}
			if (ModConfig.LogLamas.Value)
			{
				string text = Changes.Describe(lamaInfo);
				if (text != null)
				{
					ModLog.Info(text);
				}
			}
			if (!lamaInfo.IsOwner)
			{
				ModLog.InfoOnce("not-host", "Not the host: the lamas' AI runs on the host's PC, so this mod leaves them alone here.");
			}
			if (Walks.ShouldStop(lamaInfo.Id, lamaInfo.State, now))
			{
				StopStuckWalk(target, lamaInfo.Id);
			}
			if (!DecharmRule.ShouldDecharm(lamaInfo, Decharmed.Contains(lamaInfo.Id)))
			{
				return;
			}
			Decharmed.Add(lamaInfo.Id);
			try
			{
				bool flag = Decharmer.Decharm(target, lamaInfo);
				Walks.Started(lamaInfo.Id, now);
				ModLog.Info($"lama {lamaInfo.Id}: decharmed in the pen (was {lamaInfo.State}){(flag ? "" : ", with errors (see the WARN lines above)")}.");
			}
			catch (Exception ex2)
			{
				ModLog.ErrorThrottled("decharm", ex2, now);
			}
		}

		private static void StopStuckWalk(HerdingTarget target, int lamaId)
		{
			try
			{
				ModLog.StepOnce("stuck-walk", "first stuck walk: TransitionToIdleState()");
				target.TransitionToIdleState();
				ModLog.StepOnce("stuck-walk-ok", "first stuck walk: TransitionToIdleState() ok");
				ModLog.Info($"lama {lamaId}: still walking {10f:0} s after its decharm, so it was " + "stopped (its spot was probably unreachable).");
			}
			catch (Exception ex)
			{
				ModLog.Warn($"lama {lamaId}: stopping a stuck walk failed: {ex.GetType().Name}: {ex.Message}\n{ex.StackTrace}");
			}
		}
	}
	internal static class TestHotkeys
	{
		private static bool _keyboardRead;

		public static void Update(float now)
		{
			if (!ModConfig.TestHotkeys.Value)
			{
				return;
			}
			bool num = !_keyboardRead;
			_keyboardRead = true;
			if (num)
			{
				ModLog.Step("first Keyboard.current read");
			}
			Keyboard current = Keyboard.current;
			if (num)
			{
				ModLog.Step("first Keyboard.current read done");
			}
			if (current != null && (((ButtonControl)current.leftCtrlKey).isPressed || ((ButtonControl)current.rightCtrlKey).isPressed))
			{
				if (((ButtonControl)current.digit1Key).wasPressedThisFrame)
				{
					StartHerding();
				}
				else if (((ButtonControl)current.digit2Key).wasPressedThisFrame)
				{
					LamaWatcher.CharmForTest(now);
				}
			}
		}

		private static void StartHerding()
		{
			ModLog.StepOnce("director", "first Ctrl+1: reading ObjectiveDirector");
			ObjectiveDirector instance = NetworkSingleton<ObjectiveDirector>.Instance;
			if ((Object)(object)instance == (Object)null)
			{
				ModLog.Info("Ctrl+1: not in a run (no ObjectiveDirector).");
				return;
			}
			bool isServer = ((NetworkBehaviour)instance).IsServer;
			IAmObjective activeObjective = instance.ActiveObjective;
			ModLog.StepOnce("director-done", "first Ctrl+1: reading ObjectiveDirector done");
			if (!isServer)
			{
				ModLog.Info("Ctrl+1: only the host can start objectives.");
				return;
			}
			if (activeObjective != null)
			{
				ModLog.Info("Ctrl+1: an objective is already running; finish it first.");
				return;
			}
			if (HerdingStillOnTheField())
			{
				ModLog.Info("Ctrl+1: the previous herding objective is still ending; try again in a few seconds.");
				return;
			}
			ModLog.Step("Ctrl+1: ObjectiveDirector.StartObjective(Herding)");
			IAmObjective obj = instance.StartObjective((Objective)10);
			ModLog.Step("Ctrl+1: StartObjective done");
			ModLog.Info((obj == null) ? "Ctrl+1: the game started no objective (StartObjective returned nothing)." : "Ctrl+1: started a herding objective.");
		}

		private static bool HerdingStillOnTheField()
		{
			Il2CppArrayBase<HerdingObjectiveManager> val = Object.FindObjectsOfType<HerdingObjectiveManager>();
			if (val == null)
			{
				return false;
			}
			for (int i = 0; i < val.Length; i++)
			{
				if ((Object)(object)val[i] != (Object)null && ((Behaviour)val[i]).isActiveAndEnabled)
				{
					return true;
				}
			}
			return false;
		}
	}
}
namespace SpellBrigadeLamaPen.Core
{
	internal static class DecharmRule
	{
		public static bool ShouldDecharm(LamaInfo lama, bool alreadyDecharmed)
		{
			if (lama.IsOwner && lama.InPen && lama.Charmed && !lama.Despawning)
			{
				return !alreadyDecharmed;
			}
			return false;
		}
	}
	internal sealed class LamaChanges
	{
		private readonly Dictionary<int, string> _last = new Dictionary<int, string>();

		public string? Describe(LamaInfo lama)
		{
			string text = lama.Summary();
			if (!_last.TryGetValue(lama.Id, out string value))
			{
				_last[lama.Id] = text;
				return $"lama {lama.Id}: new, {text}";
			}
			if (value == text)
			{
				return null;
			}
			_last[lama.Id] = text;
			return $"lama {lama.Id}: {value} -> {text}";
		}

		public void Clear()
		{
			_last.Clear();
		}
	}
	internal sealed class LamaInfo
	{
		public int Id;

		public bool IsOwner;

		public bool InPen;

		public bool Charmed;

		public bool Despawning;

		public string State = "";

		public string Summary()
		{
			return $"{State}, {(InPen ? "in pen" : "outside")}, {(Charmed ? "charmed" : "not charmed")}" + (IsOwner ? "" : ", not host") + (Despawning ? ", despawning" : "");
		}
	}
	internal struct FlatPoint
	{
		public float X;

		public float Z;

		public FlatPoint(float x, float z)
		{
			X = x;
			Z = z;
		}
	}
	internal static class PenSpot
	{
		public const float MinFraction = 0.15f;

		public const float MaxFraction = 0.45f;

		public const float MaxTurnDegrees = 60f;

		public static FlatPoint Pick(FlatPoint lama, FlatPoint center, float penRadius, float distanceRandom, float turnRandom)
		{
			float num = lama.X - center.X;
			float num2 = lama.Z - center.Z;
			float num3 = MathF.Sqrt(num * num + num2 * num2);
			if (num3 < 0.001f)
			{
				num = 1f;
				num2 = 0f;
				num3 = 1f;
			}
			float x = (Clamp01(turnRandom) * 2f - 1f) * 60f * (float)Math.PI / 180f;
			float num4 = MathF.Cos(x);
			float num5 = MathF.Sin(x);
			float num6 = num / num3;
			float num7 = num2 / num3;
			float num8 = penRadius * (0.15f + 0.29999998f * Clamp01(distanceRandom));
			return new FlatPoint(center.X + (num6 * num4 - num7 * num5) * num8, center.Z + (num6 * num5 + num7 * num4) * num8);
		}

		private static float Clamp01(float v)
		{
			if (!(v < 0f))
			{
				if (!(v > 1f))
				{
					return v;
				}
				return 1f;
			}
			return 0f;
		}
	}
	internal static class StateNames
	{
		private const string Prefix = "HerdingTarget";

		private const string Suffix = "State";

		public const string Follow = "Follow";

		public const string Walking = "Walking";

		public static string Short(string? typeName)
		{
			if (string.IsNullOrEmpty(typeName))
			{
				return "none";
			}
			int num = typeName.Length - "HerdingTarget".Length - "State".Length;
			if (num <= 0 || !typeName.StartsWith("HerdingTarget", StringComparison.Ordinal) || !typeName.EndsWith("State", StringComparison.Ordinal))
			{
				return typeName;
			}
			return typeName.Substring("HerdingTarget".Length, num);
		}
	}
	internal static class TestCharmRule
	{
		public static bool ShouldCharm(LamaInfo lama)
		{
			if (lama.IsOwner && !lama.InPen && !lama.Charmed)
			{
				return !lama.Despawning;
			}
			return false;
		}
	}
	internal sealed class WalkWatchdog
	{
		public const float MaxWalkSeconds = 10f;

		private readonly Dictionary<int, float> _since = new Dictionary<int, float>();

		public void Started(int lamaId, float now)
		{
			_since[lamaId] = now;
		}

		public bool ShouldStop(int lamaId, string state, float now)
		{
			if (!_since.TryGetValue(lamaId, out var value))
			{
				return false;
			}
			if (state != "Walking")
			{
				_since.Remove(lamaId);
				return false;
			}
			if (now - value < 10f)
			{
				return false;
			}
			_since.Remove(lamaId);
			return true;
		}

		public void Clear()
		{
			_since.Clear();
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte flag)
		{
			Flag = flag;
		}
	}
}