Decompiled source of DailyCaravan v0.1.0

plugins/DailyCaravan.dll

Decompiled 38 minutes ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using SuperFantasyKingdom;
using SuperFantasyKingdom.Spawner;
using SuperFantasyKingdom.UI;
using UnityEngine;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("DailyCaravan")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+9d0cc6e7cff38870fb3d13346bdaae6095eac7bc")]
[assembly: AssemblyProduct("DailyCaravan")]
[assembly: AssemblyTitle("DailyCaravan")]
[assembly: AssemblyVersion("0.1.0.0")]
namespace DailyCaravan;

internal enum ArrivalAction
{
	Wait,
	Complete,
	RestoreItem,
	StartVisit
}
internal sealed class Arrival
{
	private bool pending;

	internal bool Dispatched { get; private set; }

	internal bool Pending => pending;

	internal void Request(Visit visit, int? kingdom = null, VisitOrigin origin = VisitOrigin.Unknown)
	{
		if (Dispatched)
		{
			return;
		}
		pending = true;
		if (!visit.Finished)
		{
			if (kingdom.HasValue && (visit.kingdom < 0 || (origin == VisitOrigin.Invitation && (visit.origin == VisitOrigin.Daily || visit.origin == VisitOrigin.Booking))))
			{
				visit.kingdom = kingdom.Value;
			}
			if (origin > visit.origin)
			{
				visit.origin = origin;
			}
		}
	}

	internal ArrivalAction Take(Visit visit, bool busy)
	{
		if (!pending || busy)
		{
			return ArrivalAction.Wait;
		}
		pending = false;
		Dispatched = true;
		if (visit.declined || visit.rewardInSave)
		{
			return ArrivalAction.Complete;
		}
		if (!visit.Finished)
		{
			return ArrivalAction.StartVisit;
		}
		return ArrivalAction.RestoreItem;
	}
}
[HarmonyPatch(typeof(GuestCaravan), "OnCaravan")]
internal static class CaravanFaithBonus
{
	private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions)
	{
		MethodInfo spawn = AccessTools.Method(typeof(DroppedShardSpawner), "Spawn", (Type[])null, (Type[])null);
		MethodInfo grant = AccessTools.Method(typeof(CaravanFaithBonus), "Grant", (Type[])null, (Type[])null);
		foreach (CodeInstruction instruction in instructions)
		{
			if (CodeInstructionExtensions.Calls(instruction, spawn))
			{
				yield return CodeInstructionExtensions.MoveLabelsFrom(new CodeInstruction(OpCodes.Ldarg_0, (object)null), instruction);
				instruction.opcode = OpCodes.Call;
				instruction.operand = grant;
			}
			yield return instruction;
		}
	}

	private static void Grant(DroppedShardSpawner spawner, Vector3 position, int amount, ResourceType resource, bool onScreen, GuestCaravan guest)
	{
		//IL_0027: 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_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_001d: Unknown result type (might be due to invalid IL or missing references)
		DailyCaravanPlugin instance = DailyCaravanPlugin.Instance;
		if ((Object)(object)instance != (Object)null && instance.Owns(guest))
		{
			instance.GrantFaithBonus(spawner, position, amount, resource, onScreen);
		}
		else
		{
			spawner.Spawn(position, amount, resource, onScreen);
		}
	}
}
[HarmonyPatch(typeof(UICard), "DisplayKeywords")]
internal sealed class CaravanKeywordLayout : MonoBehaviour
{
	private static readonly FieldRef<UIOverlayMerchant, Action<int, ResourceAmount[]>> Callback = AccessTools.FieldRefAccess<UIOverlayMerchant, Action<int, ResourceAmount[]>>("m_Callback");

	private static readonly FieldRef<UICardItem, Image> Kingdom = AccessTools.FieldRefAccess<UICardItem, Image>("kingdom");

	private RectTransform panel;

	private RectTransform canvas;

	private RectTransform resourceCounter;

	private RectTransform[] obstacles;

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

	private float shift;

	private static void Postfix(UICard __instance, UIEffectKeywordDictionary ___m_KeywordDictionary)
	{
		//IL_0073: Unknown result type (might be due to invalid IL or missing references)
		//IL_007d: Expected O, but got Unknown
		if (!(__instance is UICardItem) || !Object.op_Implicit((Object)(object)___m_KeywordDictionary) || !((Behaviour)___m_KeywordDictionary).isActiveAndEnabled)
		{
			return;
		}
		UIOverlayMerchant componentInParent = ((Component)__instance).GetComponentInParent<UIOverlayMerchant>();
		if (!Object.op_Implicit((Object)(object)componentInParent))
		{
			return;
		}
		object? obj = Callback.Invoke(componentInParent)?.Target;
		GuestCaravan val = (GuestCaravan)((obj is GuestCaravan) ? obj : null);
		if (val != null && DailyCaravanPlugin.Instance.Owns(val))
		{
			CaravanKeywordLayout obj2 = ((Component)___m_KeywordDictionary).GetComponent<CaravanKeywordLayout>() ?? ((Component)___m_KeywordDictionary).gameObject.AddComponent<CaravanKeywordLayout>();
			obj2.panel = (RectTransform)((Component)obj2).transform;
			ref RectTransform reference = ref obj2.canvas;
			Transform transform = ((Component)((Component)obj2).GetComponentInParent<Canvas>().rootCanvas).transform;
			reference = (RectTransform)(object)((transform is RectTransform) ? transform : null);
			GameObject resourceAmount = UIManager.Instance.GetResourceAmount((ResourceType)15);
			ref RectTransform reference2 = ref obj2.resourceCounter;
			Transform obj3 = ((resourceAmount != null) ? resourceAmount.transform : null);
			reference2 = (RectTransform)(object)((obj3 is RectTransform) ? obj3 : null);
			obj2.obstacles = (from rect in ((Component)componentInParent).GetComponentsInChildren<UICardItem>().SelectMany(delegate(UICardItem card)
				{
					RectTransform[] obj4 = new RectTransform[2]
					{
						(RectTransform)/*isinst with value type is only supported in some contexts*/,
						default(RectTransform)
					};
					Image obj5 = Kingdom.Invoke(card);
					ref RectTransform reference3 = ref obj4[1];
					Transform obj6 = ((obj5 != null) ? ((Component)obj5).transform.parent : null);
					reference3 = (RectTransform)((obj6 is RectTransform) ? obj6 : null);
					return (IEnumerable<RectTransform>)(object)obj4;
				})
				where (Object)(object)rect != (Object)null
				select rect).ToArray();
		}
	}

	private Rect Bounds(RectTransform rect)
	{
		//IL_001e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_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_0046: 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_0058: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Unknown result type (might be due to invalid IL or missing references)
		rect.GetWorldCorners(corners);
		Vector3 val = ((Transform)panel).parent.InverseTransformPoint(corners[0]);
		Vector3 val2 = ((Transform)panel).parent.InverseTransformPoint(corners[2]);
		return Rect.MinMaxRect(val.x, val.y, val2.x, val2.y);
	}

	private void LateUpdate()
	{
		//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)
		//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)
		//IL_009f: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a6: Expected O, but got Unknown
		//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
		//IL_0102: Unknown result type (might be due to invalid IL or missing references)
		//IL_0107: Unknown result type (might be due to invalid IL or missing references)
		//IL_010b: Unknown result type (might be due to invalid IL or missing references)
		if (obstacles == null || !Object.op_Implicit((Object)(object)canvas))
		{
			return;
		}
		float num = 0f;
		float num2 = float.PositiveInfinity;
		Rect val = Bounds(canvas);
		float num3 = ((Rect)(ref val)).yMax - ((Rect)(ref val)).height * 0.1f;
		if (Object.op_Implicit((Object)(object)resourceCounter) && ((Component)resourceCounter).gameObject.activeInHierarchy)
		{
			float num4 = num3;
			Rect val2 = Bounds(resourceCounter);
			num3 = Mathf.Min(num4, ((Rect)(ref val2)).yMin - 4f);
		}
		foreach (RectTransform item in (Transform)panel)
		{
			RectTransform rect = item;
			Rect val3 = Bounds(rect);
			((Rect)(ref val3)).y = ((Rect)(ref val3)).y - shift;
			num2 = Mathf.Min(num2, num3 - ((Rect)(ref val3)).yMax);
			RectTransform[] array = obstacles;
			foreach (RectTransform val4 in array)
			{
				if (Object.op_Implicit((Object)(object)val4) && ((Component)val4).gameObject.activeInHierarchy)
				{
					Rect val5 = Bounds(val4);
					if (((Rect)(ref val3)).Overlaps(val5))
					{
						num = Mathf.Max(num, ((Rect)(ref val5)).yMax + 4f - ((Rect)(ref val3)).yMin);
					}
				}
			}
		}
		SetShift((num <= num2) ? num : 0f);
	}

	private void SetShift(float value)
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0028: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		if (!Mathf.Approximately(value, shift))
		{
			RectTransform obj = panel;
			obj.anchoredPosition += Vector2.up * (value - shift);
			shift = value;
		}
	}

	private void OnDisable()
	{
		SetShift(0f);
		obstacles = null;
	}
}
internal static class CaravanPatches
{
	[HarmonyPatch(typeof(GameDataManager), "Load")]
	private static class Load
	{
		private static void Prefix(GameData ___m_GameData)
		{
			Plugin.BeginLoad(___m_GameData);
		}
	}

	[HarmonyPatch(typeof(GameDataManager), "GenerateGameData")]
	private static class Save
	{
		private static void Postfix(GameData __result)
		{
			Plugin.Snapshot(__result);
		}
	}

	[HarmonyPatch(typeof(WorldManager), "SetGuest")]
	private static class ActiveGuest
	{
		private static void Postfix(Guest __0)
		{
			if ((Object)(object)__0 != (Object)null)
			{
				Plugin.LastGuest = __0;
			}
		}
	}

	[HarmonyPatch(typeof(GuestCaravan), "CheckDay")]
	private static class Scheduled
	{
		private static void Postfix(ref bool __result)
		{
			if (__result && DaytimeManager.Instance.IsLoading() && RaceDataManager.Instance.HasRaceEventFlag((RaceEvent)13) && Plugin.Request(VisitOrigin.Booking))
			{
				__result = false;
			}
		}
	}

	[HarmonyPatch(typeof(WorldManager), "TriggerCaravan")]
	private static class Tokens
	{
		[HarmonyPriority(0)]
		private static bool Prefix(Races __0, bool __runOriginal)
		{
			//IL_0009: Unknown result type (might be due to invalid IL or missing references)
			if (__runOriginal)
			{
				return !Plugin.Request(VisitOrigin.Invitation, __0);
			}
			return false;
		}
	}

	[HarmonyPatch(typeof(GuestCaravan), "TriggerManually", new Type[] { typeof(Races) })]
	private static class Invitation
	{
		[HarmonyPriority(0)]
		private static bool Prefix(Races __0, bool __runOriginal)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			if (__runOriginal)
			{
				if (!Plugin.Launching)
				{
					return !Plugin.Request(VisitOrigin.Invitation, __0);
				}
				return true;
			}
			return false;
		}
	}

	[HarmonyPatch(typeof(GuestCaravan), "TriggerManually", new Type[] { })]
	private static class DirectOpen
	{
		[HarmonyPriority(0)]
		private static bool Prefix(GuestCaravan __instance, Races ___m_Kingdom, bool __runOriginal)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			if (__runOriginal)
			{
				if (!Plugin.Owns(__instance))
				{
					return !Plugin.Request(VisitOrigin.Invitation, ___m_Kingdom);
				}
				return true;
			}
			return false;
		}
	}

	[HarmonyPatch(typeof(GuestCaravan), "OnCaravan")]
	private static class Open
	{
		private static bool Prefix(GuestCaravan __instance)
		{
			if (Plugin.Owns(__instance))
			{
				return !Plugin.Visit.Finished;
			}
			return true;
		}
	}

	[HarmonyPatch(typeof(GuestCaravan), "Cancel")]
	private static class Decline
	{
		private static void Postfix(GuestCaravan __instance, bool __runOriginal)
		{
			if (__runOriginal && Plugin.Owns(__instance) && !Plugin.Visit.Finished)
			{
				Plugin.Visit.declined = true;
				Plugin.Persist();
			}
		}
	}

	[HarmonyPatch(typeof(UICardItem), "Select")]
	private static class Select
	{
		private static bool Prefix(UICardItem __instance, bool ___m_CanBeClicked, out int? __state)
		{
			__state = null;
			if (!IsCaravanCard(__instance))
			{
				return true;
			}
			if (!Plugin.Visit.CanSelect)
			{
				return false;
			}
			if (___m_CanBeClicked)
			{
				__state = ItemManager.Instance.GetDragItems().Count;
			}
			return true;
		}

		[HarmonyPriority(0)]
		private static void Postfix(int? __state, string ___m_ItemIdentifier)
		{
			if (__state.HasValue)
			{
				List<DragItem> dragItems = ItemManager.Instance.GetDragItems();
				int num = dragItems.Count - __state.Value;
				if (num > 0)
				{
					string singleDrop = ((num == 1) ? dragItems[__state.Value].GetItemIdentifier() : null);
					Plugin.RecordGrant(___m_ItemIdentifier, num, singleDrop);
				}
			}
		}
	}

	private static readonly FieldRef<UIOverlayMerchant, Action<int, ResourceAmount[]>> Callback = AccessTools.FieldRefAccess<UIOverlayMerchant, Action<int, ResourceAmount[]>>("m_Callback");

	private static readonly FieldRef<UICard, bool> Ready = AccessTools.FieldRefAccess<UICard, bool>("m_CanBeClicked");

	private static readonly FieldRef<UICardItem, string> CardId = AccessTools.FieldRefAccess<UICardItem, string>("m_ItemIdentifier");

	private static DailyCaravanPlugin Plugin => DailyCaravanPlugin.Instance;

	internal static bool HasGrantHooks()
	{
		if (!HasForeignHooks(typeof(UICardItem), "Select"))
		{
			return HasForeignHooks(typeof(ItemManager), "SpawnDragItem");
		}
		return true;
	}

	private static bool HasForeignHooks(Type type, string name)
	{
		Patches patchInfo = Harmony.GetPatchInfo((MethodBase)AccessTools.Method(type, name, (Type[])null, (Type[])null));
		if (patchInfo == null)
		{
			return false;
		}
		return patchInfo.Owners.Any((string id) => id != "sfk.dailycaravan");
	}

	private static bool IsCaravanCard(UICardItem card)
	{
		UIOverlayMerchant val = (((Object)(object)card == (Object)null) ? null : ((Component)card).GetComponentInParent<UIOverlayMerchant>());
		if ((Object)(object)val != (Object)null)
		{
			object? obj = Callback.Invoke(val)?.Target;
			GuestCaravan val2 = (GuestCaravan)((obj is GuestCaravan) ? obj : null);
			if (val2 != null)
			{
				return Plugin.Owns(val2);
			}
		}
		return false;
	}

	internal static bool CanGrant(UICardItem card, out string id)
	{
		id = ((IsCaravanCard(card) && Ready.Invoke((UICard)(object)card)) ? CardId.Invoke(card) : null);
		return !string.IsNullOrEmpty(id);
	}
}
[BepInPlugin("sfk.dailycaravan", "Daily Caravan", "0.1.0")]
public sealed class DailyCaravanPlugin : BaseUnityPlugin
{
	internal static DailyCaravanPlugin Instance;

	private ConfigEntry<int> firstDay;

	private Harmony patches;

	private GameDataManager scene;

	private int day;

	private bool rewardPresent;

	private string dawnHash;

	private string directory;

	private string recordPath;

	internal Visit Visit;

	internal Guest LastGuest;

	private Arrival arrival = new Arrival();

	internal bool Launching { get; private set; }

	private void Awake()
	{
		//IL_002e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0038: Expected O, but got Unknown
		//IL_0043: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: Expected O, but got Unknown
		Instance = this;
		firstDay = ((BaseUnityPlugin)this).Config.Bind<int>("Schedule", "FirstDay", 16, new ConfigDescription("First ordinary kingdom day for supplemental caravans. Native unlocks and challenge schedules still apply.", (AcceptableValueBase)(object)new AcceptableValueRange<int>(1, 999), Array.Empty<object>()));
		patches = new Harmony("sfk.dailycaravan");
		try
		{
			patches.PatchAll(typeof(DailyCaravanPlugin).Assembly);
			DaytimeManager.OnMorningStart += Morning;
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Daily Caravan 0.1.0 ready.");
		}
		catch
		{
			patches.UnpatchSelf();
			throw;
		}
	}

	private void OnDestroy()
	{
		DaytimeManager.OnMorningStart -= Morning;
		Harmony obj = patches;
		if (obj != null)
		{
			obj.UnpatchSelf();
		}
		Instance = null;
	}

	internal void BeginLoad(GameData data)
	{
		LastGuest = null;
		scene = null;
		Visit = null;
		recordPath = null;
		arrival = new Arrival();
		dawnHash = Fingerprint(data);
	}

	internal static string Fingerprint(GameData data)
	{
		if (data != null)
		{
			return Helper.GenerateHash(JsonUtility.ToJson((object)data));
		}
		return "new";
	}

	internal void RecordGrant(string card, int added, string singleDrop)
	{
		if (Visit.RecordDrops(card, added, singleDrop, CaravanPatches.HasGrantHooks()))
		{
			rewardPresent = true;
			Persist();
		}
	}

	public static bool TryGrantProviderReward(UICardItem card, Func<bool> grant)
	{
		DailyCaravanPlugin instance = Instance;
		if ((Object)(object)instance == (Object)null || !CaravanPatches.CanGrant(card, out var id) || !instance.Visit.GrantProviderReward(id, grant))
		{
			return false;
		}
		instance.rewardPresent = true;
		instance.Persist();
		return true;
	}

	internal void GrantFaithBonus(DroppedShardSpawner spawner, Vector3 position, int amount, ResourceType resource, bool onScreen)
	{
		//IL_0038: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Expected I4, but got Unknown
		//IL_0040: 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_0058: Unknown result type (might be due to invalid IL or missing references)
		if (amount > 0)
		{
			if (Visit.bonus == null || Visit.bonus.amount <= 0)
			{
				Visit.bonus = new FaithBonus
				{
					amount = amount,
					resource = (int)resource,
					x = position.x,
					y = position.y,
					z = position.z,
					onScreen = onScreen
				};
			}
			DeliverBonus(spawner);
		}
	}

	private void DeliverBonus(DroppedShardSpawner spawner)
	{
		if (Visit.bonus.Deliver(delegate(FaithBonus b)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			spawner.Spawn(new Vector3(b.x, b.y, b.z), b.amount, (ResourceType)b.resource, b.onScreen);
		}))
		{
			Persist();
		}
	}

	private bool EnterDay()
	{
		GameDataManager instance = GameDataManager.Instance;
		if ((Object)(object)instance == (Object)null || (Object)(object)DaytimeManager.Instance == (Object)null || string.IsNullOrEmpty(instance.GetRunID()))
		{
			return false;
		}
		int num = DaytimeManager.Instance.CurrentDay();
		if ((Object)(object)instance == (Object)(object)scene && day == num && Visit != null)
		{
			return true;
		}
		scene = instance;
		day = num;
		rewardPresent = false;
		arrival = new Arrival();
		directory = Path.Combine(Paths.ConfigPath, "DailyCaravan", SettingsManager.Instance.GetProfile().ToString(), Helper.GenerateHash(instance.GetRunID()), day.ToString());
		recordPath = Path.Combine(directory, (dawnHash ?? "new") + ".json");
		Visit = new Visit();
		try
		{
			if (File.Exists(recordPath))
			{
				Visit visit = JsonUtility.FromJson<Visit>(File.ReadAllText(recordPath));
				if (visit != null && visit.kingdom >= 0)
				{
					visit.items = null;
					Visit = visit;
					rewardPresent = visit.rewardInSave;
					if (visit.ResumeWithoutBooking)
					{
						arrival.Request(Visit);
					}
				}
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not read caravan record: " + ex.Message));
		}
		return true;
	}

	internal bool Request(VisitOrigin origin, Races? invitation = null)
	{
		//IL_003b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0045: Expected I4, but got Unknown
		if (!EnterDay())
		{
			return false;
		}
		if (!arrival.Dispatched)
		{
			arrival.Request(Visit, (int?)invitation, origin);
			if (origin == VisitOrigin.Invitation)
			{
				Persist();
			}
		}
		return true;
	}

	private void Morning(int today)
	{
		if (EnterDay() && Visit.AddsVisit(today, firstDay.Value, RaceDataManager.Instance.HasRaceEventFlag((RaceEvent)13), WorldManager.Instance.HasUnlockedCaravans(), MainManager.Instance.IsChallenge()))
		{
			Request(VisitOrigin.Daily);
		}
	}

	private void Update()
	{
		//IL_0255: Unknown result type (might be due to invalid IL or missing references)
		//IL_025f: Expected I4, but got Unknown
		//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
		Visit visit = Visit;
		bool flag = visit != null && visit.bonus?.NeedsRestore == true;
		if ((!arrival.Pending && !flag) || (Object)(object)scene == (Object)null || (Object)(object)scene != (Object)(object)GameDataManager.Instance || (Object)(object)GameManager.Instance == (Object)null || !GameManager.Instance.IsGameRunning() || GameManager.Instance.IsUnloading() || GameManager.Instance.IsGameOver() || day != DaytimeManager.Instance.CurrentDay())
		{
			return;
		}
		WorldManager instance = WorldManager.Instance;
		OverlayManager instance2 = OverlayManager.Instance;
		bool flag2 = (Object)(object)instance == (Object)null || (Object)(object)instance.GetCaravan() == (Object)null || (Object)(object)instance.GetGuest() != (Object)null || ((Object)(object)LastGuest != (Object)null && ((Component)LastGuest).gameObject.activeInHierarchy) || (Object)(object)instance2 == (Object)null || instance2.IsOpen() || instance2.HasMinimizedOverlay() || GameManager.Instance.IsForcedPause() || GameCamera.Instance.IsCutscene() || DialogueManager.Instance.IsInDialogue() || (Object)(object)UIManager.Instance == (Object)null || !UIManager.Instance.IsWorldInteractable();
		if (!flag2 && flag)
		{
			DeliverBonus(DroppedShardSpawner.Instance);
		}
		switch (arrival.Take(Visit, flag2))
		{
		case ArrivalAction.Wait:
		case ArrivalAction.Complete:
			return;
		case ArrivalAction.RestoreItem:
			if (!Visit.providerGrant && !CaravanPatches.HasGrantHooks() && (Object)(object)AddressablesManager.Instance.GetItem(Visit.selected) != (Object)null)
			{
				List<DragItem> dragItems = ItemManager.Instance.GetDragItems();
				int count = dragItems.Count;
				ItemManager.Instance.SpawnDragItem(Visit.selected, new Vector2(0f, 3f), false);
				rewardPresent = dragItems.Count == count + 1;
				return;
			}
			Visit.selected = null;
			Visit.providerGrant = false;
			break;
		}
		if (Visit.kingdom < 0)
		{
			Visit.kingdom = Visit.VisitingKingdom(GameManager.Instance.GetSeed(), day, (int)RaceManager.Instance.GetRace());
		}
		Persist();
		Launching = true;
		try
		{
			instance.GetCaravan().TriggerManually((Races)Visit.kingdom);
		}
		finally
		{
			Launching = false;
		}
	}

	internal bool Owns(GuestCaravan guest)
	{
		if (arrival.Dispatched && (Object)(object)scene != (Object)null && (Object)(object)scene == (Object)(object)GameDataManager.Instance && day == DaytimeManager.Instance.CurrentDay() && (Object)(object)WorldManager.Instance != (Object)null && (Object)(object)guest != (Object)null)
		{
			return (Object)(object)guest == (Object)(object)WorldManager.Instance.GetCaravan();
		}
		return false;
	}

	internal void Persist()
	{
		WriteRecord(recordPath, Visit);
	}

	internal void Snapshot(GameData data)
	{
		if (Visit != null && Visit.kingdom >= 0 && !((Object)(object)scene == (Object)null) && !((Object)(object)scene != (Object)(object)GameDataManager.Instance) && !(data.runID != scene.GetRunID()) && data.day + 1 == day)
		{
			Visit visit = JsonUtility.FromJson<Visit>(JsonUtility.ToJson((object)Visit));
			visit.rewardInSave = rewardPresent;
			if (visit.bonus != null)
			{
				visit.bonus.inSave = Visit.bonus?.Present ?? false;
			}
			WriteRecord(Path.Combine(directory, Fingerprint(data) + ".json"), visit);
		}
	}

	private void WriteRecord(string path, Visit visit)
	{
		if (path == null || visit == null)
		{
			return;
		}
		try
		{
			Directory.CreateDirectory(directory);
			string text = path + ".tmp";
			File.WriteAllText(text, JsonUtility.ToJson((object)visit));
			if (File.Exists(path))
			{
				File.Replace(text, path, null);
			}
			else
			{
				File.Move(text, path);
			}
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not save caravan record: " + ex.Message));
		}
	}
}
[HarmonyPatch(typeof(GuestCaravan), "Reroll")]
internal static class NativeDraw
{
	private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, ILGenerator il)
	{
		//IL_0116: Unknown result type (might be due to invalid IL or missing references)
		//IL_011c: Expected O, but got Unknown
		//IL_0158: Unknown result type (might be due to invalid IL or missing references)
		//IL_015e: Expected O, but got Unknown
		//IL_0176: Unknown result type (might be due to invalid IL or missing references)
		//IL_017c: Expected O, but got Unknown
		//IL_0199: Unknown result type (might be due to invalid IL or missing references)
		//IL_019f: Expected O, but got Unknown
		List<CodeInstruction> list = new List<CodeInstruction>(instructions);
		MethodInfo getItems = AccessTools.Method(typeof(GuestCaravan), "GetItems", (Type[])null, (Type[])null);
		int num = list.FindIndex((CodeInstruction op) => CodeInstructionExtensions.Calls(op, getItems));
		if (num < 0)
		{
			return list;
		}
		FieldInfo fieldInfo = AccessTools.Field(typeof(GuestCaravan), "m_Chosen");
		MethodInfo methodInfo = AccessTools.PropertyGetter(typeof(List<string>), "Count");
		int num2;
		for (num2 = num + 3; num2 + 1 < list.Count && (!CodeInstructionExtensions.LoadsField(list[num2 - 2], fieldInfo, false) || !CodeInstructionExtensions.Calls(list[num2 - 1], methodInfo) || (!(list[num2 + 1].opcode == OpCodes.Blt) && !(list[num2 + 1].opcode == OpCodes.Blt_S))); num2++)
		{
		}
		if (num2 + 1 >= list.Count)
		{
			return list;
		}
		LocalBuilder localBuilder = il.DeclareLocal(typeof(int));
		list.InsertRange(num2 + 1, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[2]
		{
			new CodeInstruction(OpCodes.Ldloc, (object)localBuilder),
			new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(Math), "Min", new Type[2]
			{
				typeof(int),
				typeof(int)
			}, (Type[])null))
		});
		list.InsertRange(num + 1, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[2]
		{
			new CodeInstruction(OpCodes.Ldloca, (object)localBuilder),
			new CodeInstruction(OpCodes.Call, (object)AccessTools.Method(typeof(NativeDraw), "Registered", (Type[])null, (Type[])null))
		});
		return list;
	}

	private static List<string> Registered(List<string> items, out int distinct)
	{
		return OfferPool.Registered(items, (string id) => (Object)(object)AddressablesManager.Instance.GetItem(id) != (Object)null, out distinct);
	}
}
internal static class OfferPool
{
	internal static List<string> Registered(List<string> pool, Func<string, bool> resolves, out int distinct)
	{
		List<string> list = new List<string>();
		Dictionary<string, bool> dictionary = new Dictionary<string, bool>(StringComparer.Ordinal);
		distinct = 0;
		if (pool == null)
		{
			return list;
		}
		foreach (string item in pool)
		{
			if (string.IsNullOrEmpty(item))
			{
				continue;
			}
			if (!dictionary.TryGetValue(item, out var value))
			{
				dictionary.Add(item, value = resolves(item));
				if (value)
				{
					distinct++;
				}
			}
			if (value)
			{
				list.Add(item);
			}
		}
		return list;
	}
}
public enum VisitOrigin
{
	Unknown,
	Daily,
	Booking,
	Invitation
}
[Serializable]
public sealed class FaithBonus
{
	public int amount;

	public int resource;

	public float x;

	public float y;

	public float z;

	public bool onScreen;

	public bool inSave;

	[NonSerialized]
	private bool delivered;

	internal bool Present
	{
		get
		{
			if (!inSave)
			{
				return delivered;
			}
			return true;
		}
	}

	internal bool NeedsRestore
	{
		get
		{
			if (amount > 0)
			{
				return !Present;
			}
			return false;
		}
	}

	internal bool Deliver(Action<FaithBonus> spawn)
	{
		if (!NeedsRestore)
		{
			return false;
		}
		delivered = true;
		try
		{
			spawn(this);
		}
		catch
		{
			delivered = false;
			throw;
		}
		return true;
	}
}
[Serializable]
public sealed class Visit
{
	public int kingdom = -1;

	public string[] items;

	public bool providerGrant;

	public string selected;

	public bool declined;

	public bool rewardInSave;

	public VisitOrigin origin;

	public FaithBonus bonus;

	private bool granting;

	public bool Finished
	{
		get
		{
			if (!declined)
			{
				return !string.IsNullOrEmpty(selected);
			}
			return true;
		}
	}

	internal bool CanSelect
	{
		get
		{
			if (!Finished)
			{
				return !granting;
			}
			return false;
		}
	}

	internal bool ResumeWithoutBooking
	{
		get
		{
			if (!Finished && !rewardInSave)
			{
				return origin == VisitOrigin.Invitation;
			}
			return true;
		}
	}

	internal bool GrantProviderReward(string card, Func<bool> grant)
	{
		if (!CanSelect || string.IsNullOrEmpty(card) || grant == null)
		{
			return false;
		}
		granting = true;
		try
		{
			if (!grant())
			{
				return false;
			}
			selected = card;
			providerGrant = true;
			return true;
		}
		finally
		{
			granting = false;
		}
	}

	internal bool RecordDrops(string card, int added, string singleDrop, bool grantHook)
	{
		if (!CanSelect || added <= 0)
		{
			return false;
		}
		selected = ((added == 1) ? singleDrop : card);
		providerGrant = grantHook || added != 1 || selected != card;
		return true;
	}

	internal static bool AddsVisit(int day, int firstDay, bool gateOpen, bool caravansUnlocked, bool challenge)
	{
		if (!challenge && gateOpen && caravansUnlocked)
		{
			return day >= firstDay;
		}
		return false;
	}

	internal static int VisitingKingdom(int seed, int day, int home)
	{
		int num = new Random((seed * 397) ^ day).Next(8);
		if (num < home || home < 0 || home >= 9)
		{
			return num;
		}
		return num + 1;
	}
}