Decompiled source of TimbnCore v2.2.7

Timbn.GraveyardKeeperTwo.Core/Timbn.GraveyardKeeperTwo.Core.dll

Decompiled 5 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using Cysharp.Threading.Tasks;
using Expressive;
using Expressive.Expressions;
using FlowCanvas;
using FlowCanvas.Nodes;
using GK2.FlowCanvasNodes;
using HarmonyLib;
using LazyBearTechnology;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using NodeCanvas.Framework;
using Pathfinding;
using Pathfinding.Graphs.Grid.Rules;
using Pathfinding.Graphs.Navmesh;
using Pathfinding.Util;
using Sirenix.Serialization;
using Steamworks;
using TMPro;
using Timbn.GraveyardKeeperTwo.Core.Framework;
using Unity.Collections;
using Unity.Jobs;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.ResourceManagement.AsyncOperations;
using UnityEngine.SceneManagement;
using UnityEngine.TextCore;
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("Timbn")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Shared framework for Graveyard Keeper 2 (BepInEx 5) mods. A plugin base class with auto patching and config, plus the Core mod that hosts it.")]
[assembly: AssemblyFileVersion("2.2.7.0")]
[assembly: AssemblyInformationalVersion("2.2.7+779e224e9f8695c607b082ba08dcc45ab57305dd")]
[assembly: AssemblyProduct("Timbn Core")]
[assembly: AssemblyTitle("Timbn.GraveyardKeeperTwo.Core")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/TimbnMods/Timbn.GraveyardKeeperTwo")]
[assembly: InternalsVisibleTo("Timbn.GraveyardKeeperTwo.Core.Tests")]
[assembly: InternalsVisibleTo("Timbn.GraveyardKeeperTwo.InfoDump")]
[assembly: InternalsVisibleTo("Timbn.GraveyardKeeperTwo.QuestPacks")]
[assembly: AssemblyVersion("2.2.7.0")]
[module: RefSafetyRules(11)]
[DebuggerDisplay("Count = {System.Collections.ICollection.Count}")]
[CompilerGenerated]
internal sealed class <>z__ReadOnlyArray<T> : IEnumerable, ICollection, IList, IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T>, IList<T>
{
	int ICollection.Count => _items.Length;

	bool ICollection.IsSynchronized => false;

	object ICollection.SyncRoot => this;

	object IList.this[int index]
	{
		get
		{
			return _items[index];
		}
		set
		{
			throw new NotSupportedException();
		}
	}

	bool IList.IsFixedSize => true;

	bool IList.IsReadOnly => true;

	int IReadOnlyCollection<T>.Count => _items.Length;

	T IReadOnlyList<T>.this[int index] => _items[index];

	int ICollection<T>.Count => _items.Length;

	bool ICollection<T>.IsReadOnly => true;

	T IList<T>.this[int index]
	{
		get
		{
			return _items[index];
		}
		set
		{
			throw new NotSupportedException();
		}
	}

	public <>z__ReadOnlyArray(T[] items)
	{
		_items = items;
	}

	IEnumerator IEnumerable.GetEnumerator()
	{
		return ((IEnumerable)_items).GetEnumerator();
	}

	void ICollection.CopyTo(Array array, int index)
	{
		((ICollection)_items).CopyTo(array, index);
	}

	int IList.Add(object value)
	{
		throw new NotSupportedException();
	}

	void IList.Clear()
	{
		throw new NotSupportedException();
	}

	bool IList.Contains(object value)
	{
		return ((IList)_items).Contains(value);
	}

	int IList.IndexOf(object value)
	{
		return ((IList)_items).IndexOf(value);
	}

	void IList.Insert(int index, object value)
	{
		throw new NotSupportedException();
	}

	void IList.Remove(object value)
	{
		throw new NotSupportedException();
	}

	void IList.RemoveAt(int index)
	{
		throw new NotSupportedException();
	}

	IEnumerator<T> IEnumerable<T>.GetEnumerator()
	{
		return ((IEnumerable<T>)_items).GetEnumerator();
	}

	void ICollection<T>.Add(T item)
	{
		throw new NotSupportedException();
	}

	void ICollection<T>.Clear()
	{
		throw new NotSupportedException();
	}

	bool ICollection<T>.Contains(T item)
	{
		return ((ICollection<T>)_items).Contains(item);
	}

	void ICollection<T>.CopyTo(T[] array, int arrayIndex)
	{
		((ICollection<T>)_items).CopyTo(array, arrayIndex);
	}

	bool ICollection<T>.Remove(T item)
	{
		throw new NotSupportedException();
	}

	int IList<T>.IndexOf(T item)
	{
		return ((IList<T>)_items).IndexOf(item);
	}

	void IList<T>.Insert(int index, T item)
	{
		throw new NotSupportedException();
	}

	void IList<T>.RemoveAt(int index)
	{
		throw new NotSupportedException();
	}
}
[DebuggerDisplay("Count = {System.Collections.ICollection.Count}")]
[CompilerGenerated]
internal sealed class <>z__ReadOnlyList<T> : IEnumerable, ICollection, IList, IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T>, IList<T>
{
	int ICollection.Count => _items.Count;

	bool ICollection.IsSynchronized => false;

	object ICollection.SyncRoot => this;

	object IList.this[int index]
	{
		get
		{
			return _items[index];
		}
		set
		{
			throw new NotSupportedException();
		}
	}

	bool IList.IsFixedSize => true;

	bool IList.IsReadOnly => true;

	int IReadOnlyCollection<T>.Count => _items.Count;

	T IReadOnlyList<T>.this[int index] => _items[index];

	int ICollection<T>.Count => _items.Count;

	bool ICollection<T>.IsReadOnly => true;

	T IList<T>.this[int index]
	{
		get
		{
			return _items[index];
		}
		set
		{
			throw new NotSupportedException();
		}
	}

	public <>z__ReadOnlyList(List<T> items)
	{
		_items = items;
	}

	IEnumerator IEnumerable.GetEnumerator()
	{
		return ((IEnumerable)_items).GetEnumerator();
	}

	void ICollection.CopyTo(Array array, int index)
	{
		((ICollection)_items).CopyTo(array, index);
	}

	int IList.Add(object value)
	{
		throw new NotSupportedException();
	}

	void IList.Clear()
	{
		throw new NotSupportedException();
	}

	bool IList.Contains(object value)
	{
		return ((IList)_items).Contains(value);
	}

	int IList.IndexOf(object value)
	{
		return ((IList)_items).IndexOf(value);
	}

	void IList.Insert(int index, object value)
	{
		throw new NotSupportedException();
	}

	void IList.Remove(object value)
	{
		throw new NotSupportedException();
	}

	void IList.RemoveAt(int index)
	{
		throw new NotSupportedException();
	}

	IEnumerator<T> IEnumerable<T>.GetEnumerator()
	{
		return ((IEnumerable<T>)_items).GetEnumerator();
	}

	void ICollection<T>.Add(T item)
	{
		throw new NotSupportedException();
	}

	void ICollection<T>.Clear()
	{
		throw new NotSupportedException();
	}

	bool ICollection<T>.Contains(T item)
	{
		return _items.Contains(item);
	}

	void ICollection<T>.CopyTo(T[] array, int arrayIndex)
	{
		_items.CopyTo(array, arrayIndex);
	}

	bool ICollection<T>.Remove(T item)
	{
		throw new NotSupportedException();
	}

	int IList<T>.IndexOf(T item)
	{
		return _items.IndexOf(item);
	}

	void IList<T>.Insert(int index, T item)
	{
		throw new NotSupportedException();
	}

	void IList<T>.RemoveAt(int index)
	{
		throw new NotSupportedException();
	}
}
[DebuggerDisplay("Count = {System.Collections.ICollection.Count}")]
[CompilerGenerated]
internal sealed class <>z__ReadOnlySingleElementList<T> : IEnumerable, ICollection, IList, IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T>, IList<T>
{
	private sealed class Enumerator : IDisposable, IEnumerator, IEnumerator<T>
	{
		object IEnumerator.Current => _item;

		T IEnumerator<T>.Current => _item;

		public Enumerator(T item)
		{
			_item = item;
		}

		bool IEnumerator.MoveNext()
		{
			if (!_moveNextCalled)
			{
				return _moveNextCalled = true;
			}
			return false;
		}

		void IEnumerator.Reset()
		{
			_moveNextCalled = false;
		}

		void IDisposable.Dispose()
		{
		}
	}

	int ICollection.Count => 1;

	bool ICollection.IsSynchronized => false;

	object ICollection.SyncRoot => this;

	object IList.this[int index]
	{
		get
		{
			if (index != 0)
			{
				throw new IndexOutOfRangeException();
			}
			return _item;
		}
		set
		{
			throw new NotSupportedException();
		}
	}

	bool IList.IsFixedSize => true;

	bool IList.IsReadOnly => true;

	int IReadOnlyCollection<T>.Count => 1;

	T IReadOnlyList<T>.this[int index]
	{
		get
		{
			if (index != 0)
			{
				throw new IndexOutOfRangeException();
			}
			return _item;
		}
	}

	int ICollection<T>.Count => 1;

	bool ICollection<T>.IsReadOnly => true;

	T IList<T>.this[int index]
	{
		get
		{
			if (index != 0)
			{
				throw new IndexOutOfRangeException();
			}
			return _item;
		}
		set
		{
			throw new NotSupportedException();
		}
	}

	public <>z__ReadOnlySingleElementList(T item)
	{
		_item = item;
	}

	IEnumerator IEnumerable.GetEnumerator()
	{
		return new Enumerator(_item);
	}

	void ICollection.CopyTo(Array array, int index)
	{
		array.SetValue(_item, index);
	}

	int IList.Add(object value)
	{
		throw new NotSupportedException();
	}

	void IList.Clear()
	{
		throw new NotSupportedException();
	}

	bool IList.Contains(object value)
	{
		return EqualityComparer<T>.Default.Equals(_item, (T)value);
	}

	int IList.IndexOf(object value)
	{
		if (!EqualityComparer<T>.Default.Equals(_item, (T)value))
		{
			return -1;
		}
		return 0;
	}

	void IList.Insert(int index, object value)
	{
		throw new NotSupportedException();
	}

	void IList.Remove(object value)
	{
		throw new NotSupportedException();
	}

	void IList.RemoveAt(int index)
	{
		throw new NotSupportedException();
	}

	IEnumerator<T> IEnumerable<T>.GetEnumerator()
	{
		return new Enumerator(_item);
	}

	void ICollection<T>.Add(T item)
	{
		throw new NotSupportedException();
	}

	void ICollection<T>.Clear()
	{
		throw new NotSupportedException();
	}

	bool ICollection<T>.Contains(T item)
	{
		return EqualityComparer<T>.Default.Equals(_item, item);
	}

	void ICollection<T>.CopyTo(T[] array, int arrayIndex)
	{
		array[arrayIndex] = _item;
	}

	bool ICollection<T>.Remove(T item)
	{
		throw new NotSupportedException();
	}

	int IList<T>.IndexOf(T item)
	{
		if (!EqualityComparer<T>.Default.Equals(_item, item))
		{
			return -1;
		}
		return 0;
	}

	void IList<T>.Insert(int index, T item)
	{
		throw new NotSupportedException();
	}

	void IList<T>.RemoveAt(int index)
	{
		throw new NotSupportedException();
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[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 Timbn.GraveyardKeeperTwo.Core
{
	internal sealed class TimbnCoreData
	{
		public string WarnedGameVersion { get; set; } = "";
	}
	[BepInPlugin("Timbn.GraveyardKeeperTwo.Core", "Timbn Core", "2.2.7")]
	public sealed class TimbnCorePlugin : TimbnFrameworkPlugin<TimbnCorePlugin>
	{
		public const string Guid = "Timbn.GraveyardKeeperTwo.Core";

		public const string Version = "2.2.7";

		public const string TestedGameVersion = "1.013.4";

		public const string TestedGameBuild = "ddc880f62af3";

		private bool _loadErrorsChecked;

		public static string GameBuild { get; } = typeof(MainGame).Assembly.ManifestModule.ModuleVersionId.ToString("N").Substring(0, 12);

		protected override TimbnModInfo ModInfo => new TimbnModInfo
		{
			Description = "The shared framework the Timbn mods are built on. It adds nothing to the game by itself.",
			Author = "Timbn",
			NexusLink = "https://www.nexusmods.com/graveyardkeeper2/mods/84",
			SteamWorkshopLink = "https://steamcommunity.com/sharedfiles/filedetails/?id=3810064587",
			ThunderstoreLink = "https://thunderstore.io/c/graveyard-keeper-2/p/Timbn/TimbnCore/",
			WebsiteLink = "https://timbnmods.github.io/"
		};

		protected override void BindConfig(ConfigFile config)
		{
			TimbnModsWindowHost.Bind(config);
		}

		protected override void OnAwake()
		{
			TimbnExpression.CompileNow = true;
			TimbnExpressionFunctions.Register();
			base.Subscriptions.Add(TimbnGameEvents.GameStarted(delegate
			{
				TimbnSession.Open(base.SessionSubscriptions);
			}));
			base.Subscriptions.Add(TimbnGameEvents.GoToMainMenu(TimbnSession.Close));
			base.Subscriptions.Add(TimbnGameEvents.SaveWriteEnded(TimbnGlobalSaves.Flush));
			base.Subscriptions.Add(TimbnGameEvents.On(TimbnSaves.OnLoadingExistingSave, delegate(Action h)
			{
				SaveSystem.OnSaveLoadingStarted += h;
			}, delegate(Action h)
			{
				SaveSystem.OnSaveLoadingStarted -= h;
			}));
			base.Subscriptions.Add(TimbnGameEvents.On(TimbnGlobalSaves.Flush, delegate(Action h)
			{
				Application.quitting += h;
			}, delegate(Action h)
			{
				Application.quitting -= h;
			}));
			base.Subscriptions.Add(TimbnGameEvents.On(TimbnPageWindow.CloseAll, delegate(Action h)
			{
				Application.quitting += h;
			}, delegate(Action h)
			{
				Application.quitting -= h;
			}));
			base.Subscriptions.Add(TimbnGameEvents.On(delegate
			{
				TimbnModels.OnBalanceLoaded();
			}, delegate(Action<GameBalance> h)
			{
				TimbnPatchedEvents.BalanceLoaded += h;
			}, delegate(Action<GameBalance> h)
			{
				TimbnPatchedEvents.BalanceLoaded -= h;
			}));
			base.Events.WindowOpened(TimbnMainMenu.OnWindowOpened);
			TimbnModsWindowHost.Start(this);
			base.Subscriptions.Add(TimbnMainMenu.AddLine(base.Metadata.Name + ": ", base.Metadata.Version.ToString()));
			base.Events.EveryRealSeconds(1f, TimbnDialog.Refresh);
			base.Events.EveryRealSeconds(0.25f, TimbnModsCatalog.Warm);
			base.Events.EveryRealSeconds(1f, TimbnQuests.StartContinuedQuests);
			base.Events.EveryRealSeconds(1f, TimbnQuests.CheckReadyWhen);
			base.Events.EveryRealSeconds(0.5f, TimbnQuestMarker.Tick);
			base.Events.Update(TimbnPotions.Tick);
			base.Events.Update(TimbnNpcs.Tick);
			base.Events.Update(TimbnPlayerGrid.Tick);
			base.Events.Update(TimbnInteractionSpots.Tick);
			base.Events.Update(TimbnKeyHints.Tick);
			base.Events.Update(TimbnPlayerAnimation.Tick);
			base.Events.FixedUpdate(TimbnPlayerWalk.FixedTick);
			TimbnSaveData<TimbnCoreSaveData> saved = base.Saves.Register<TimbnCoreSaveData>();
			TimbnDialog.UseSeenTalks(() => saved.Current.SeenTalks);
			TimbnQuests.UseReadyMarks(() => saved.Current.QuestsReady);
			TimbnQuests.UseRuns(() => saved.Current.QuestRuns);
			base.Events.NewDayStarted(delegate
			{
				TimbnQuests.OnNewDay();
			});
			base.Subscriptions.Add(TimbnGameEvents.On(TimbnQuests.OnGameEvent, delegate(Action<Type, string> h)
			{
				TimbnPatchedEvents.Triggered += h;
			}, delegate(Action<Type, string> h)
			{
				TimbnPatchedEvents.Triggered -= h;
			}));
			TimbnGlobalData<TimbnCoreData> timbnCoreGlobalData = base.Saves.RegisterGlobal<TimbnCoreData>();
			string game = Application.version + " " + GameBuild;
			string text = "Core 2.2.7 started on Graveyard Keeper 2 " + Application.version + " (build " + GameBuild + ")";
			if (Application.version != "1.013.4")
			{
				TimbnFrameworkPlugin<TimbnCorePlugin>.Logger.LogWarning((object)(text + ", but these mods were tested on 1.013.4. Include this line when reporting a problem."));
				WarnOnce(timbnCoreGlobalData, game, "Untested game version", "Timbn mods were tested on version 1.013.4 and this is " + Application.version + ". Some mods may misbehave until they are updated.");
			}
			else if (GameBuild != "ddc880f62af3")
			{
				TimbnFrameworkPlugin<TimbnCorePlugin>.Logger.LogWarning((object)(text + ", but these mods were tested on build ddc880f62af3 of that version, so this is likely a hotfix. Include this line when reporting a problem."));
				WarnOnce(timbnCoreGlobalData, game, "Untested game build", "Timbn mods were tested on an earlier build of " + Application.version + ", so this is likely a hotfix. Some mods may misbehave until they are updated.");
			}
			else
			{
				TimbnFrameworkPlugin<TimbnCorePlugin>.Logger.LogInfo((object)(text + "."));
			}
		}

		private void WarnOnce(TimbnGlobalData<TimbnCoreData> timbnCoreGlobalData, string game, string title, string message)
		{
			if (!(timbnCoreGlobalData.Current.WarnedGameVersion == game))
			{
				base.MainMenu.AddPopup(title, message);
				timbnCoreGlobalData.Current.WarnedGameVersion = game;
				timbnCoreGlobalData.Save();
			}
		}

		protected override void OnUpdate()
		{
			if (!_loadErrorsChecked)
			{
				_loadErrorsChecked = true;
				TimbnSafe.Run(delegate
				{
					base.Subscriptions.Add(TimbnScriptReloads.Install(TimbnFrameworkPlugin<TimbnCorePlugin>.Logger));
				}, TimbnFrameworkPlugin<TimbnCorePlugin>.Logger, "TimbnScriptReloads|Guarding the F6 reload");
				string text = TimbnLoadErrors.Describe();
				if (text != null)
				{
					base.MainMenu.AddPopup("Some mods did not load", text);
				}
			}
			TimbnControlWarmUp.Tick();
			TimbnMainMenu.OnUpdate();
		}

		private void OnGUI()
		{
			TimbnGui.Draw();
		}

		protected override void OnUnload()
		{
			TimbnSession.ReleaseHolds();
			TimbnSettingsPages.Clear();
			TimbnModInfos.Clear();
			TimbnGroupPages.Clear();
			TimbnPageWindow.DestroyInstance();
		}
	}
	internal sealed class TimbnCoreSaveData
	{
		public HashSet<string> SeenTalks { get; set; } = new HashSet<string>();

		public HashSet<string> QuestsReady { get; set; } = new HashSet<string>();

		public Dictionary<string, TimbnQuestRunData> QuestRuns { get; set; } = new Dictionary<string, TimbnQuestRunData>();
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "Timbn.GraveyardKeeperTwo.Core";

		public const string PLUGIN_NAME = "Timbn Core";

		public const string PLUGIN_VERSION = "2.2.7";
	}
}
namespace Timbn.GraveyardKeeperTwo.Core.Patches
{
	[HarmonyPatch(typeof(BigDropInteractionHandler))]
	internal static class BigDropInteractionHandlerPatch
	{
		[HarmonyPatch("HasInteraction")]
		[HarmonyPostfix]
		private static void HasInteractionPostFix(ref bool __result)
		{
			if (__result && TimbnOverhead.HandsLocked)
			{
				__result = false;
			}
		}
	}
	[HarmonyPatch(typeof(Bubble))]
	internal static class BubblePatch
	{
		[HarmonyPatch("ShowMultiAnswer")]
		[HarmonyPrefix]
		private static void ShowMultiAnswerPreFix(List<AnswerVisualData> answers, Transform targetTransform, WgoData dialogParticipant, ref Action<string> onChosen, Action onDisappeared, bool isOverBlackout)
		{
			TimbnDialog.AddToMenu(answers, targetTransform, dialogParticipant, ref onChosen, onDisappeared, isOverBlackout);
		}
	}
	[HarmonyPatch(typeof(CraftComponent))]
	internal static class CraftComponentPatch
	{
		[HarmonyPatch("GetStartCraftStatus")]
		[HarmonyPostfix]
		private static void GetStartCraftStatusPostFix(CraftElementBase craftElement, ICraftable ___craftableObject, ref CraftStatus __result)
		{
			if ((int)__result == 0 && craftElement != null && !craftElement.IsStarted)
			{
				WgoData val = (WgoData)(object)((___craftableObject is WgoData) ? ___craftableObject : null);
				if (val != null && !TimbnCraftRequirements.Allows(craftElement.CraftId, val))
				{
					__result = (CraftStatus)999;
				}
			}
		}
	}
	[HarmonyPatch(typeof(EasySpritesCollection))]
	internal static class EasySpritesCollectionPatch
	{
		[HarmonyPatch("GetSprite")]
		[HarmonyPrefix]
		private static bool GetSpritePreFix(string spriteName, ref Sprite __result)
		{
			if (!TimbnSprites.TryGet(spriteName, out Sprite sprite))
			{
				return true;
			}
			__result = sprite;
			return false;
		}

		[HarmonyPatch("HasSprite")]
		[HarmonyPrefix]
		private static bool HasSpritePreFix(string spriteName, ref bool __result)
		{
			if (!TimbnSprites.TryGet(spriteName, out Sprite _))
			{
				return true;
			}
			__result = true;
			return false;
		}
	}
	[HarmonyPatch(typeof(EnergySystem))]
	internal static class EnergySystemPatch
	{
		[HarmonyPatch("StartSleeping")]
		[HarmonyPrefix]
		private static void StartSleepingPreFix(ref Action? onSleepDidNotStartedCallback, bool sleepWithoutSavingGame, out StrongBox<bool> __state)
		{
			__state = new StrongBox<bool>();
			StrongBox<bool> box = __state;
			Action original = onSleepDidNotStartedCallback;
			onSleepDidNotStartedCallback = delegate
			{
				box.Value = true;
				TimbnPatchedEvents.RaiseSleepRefused(!sleepWithoutSavingGame);
				original?.Invoke();
			};
		}

		[HarmonyPatch("StartSleeping")]
		[HarmonyPostfix]
		private static void StartSleepingPostFix(StrongBox<bool> __state)
		{
			if (!__state.Value)
			{
				TimbnPatchedEvents.RaiseSleepStarted();
			}
		}

		[HarmonyPatch("StopSleeping")]
		[HarmonyPrefix]
		private static void StopSleepingPreFix()
		{
			TimbnQuests.OnWakingUp();
		}

		[HarmonyPatch("StopSleeping")]
		[HarmonyPostfix]
		private static void StopSleepingPostFix()
		{
			TimbnPatchedEvents.RaiseSleepEnded();
		}
	}
	[HarmonyPatch(typeof(EnvironmentEngine))]
	internal static class EnvironmentEnginePatch
	{
		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		[HarmonyPostfix]
		private static void IsPausedSetterPostFix(bool value)
		{
			TimbnClockPause.OnGameSet(value);
		}
	}
	[HarmonyPatch(typeof(Flow_SetWGOPosition))]
	internal static class Flow_SetWGOPositionPatch
	{
		private static Func<GKCustomFlowNodeWithWgoData, WgoData?>? _wgoData;

		private static bool Prepare()
		{
			if (_wgoData == null)
			{
				_wgoData = TimbnReflection.TryDelegate<Func<GKCustomFlowNodeWithWgoData, WgoData>>(() => AccessTools.Method(typeof(GKCustomFlowNodeWithWgoData), "GetWgoData", (Type[])null, (Type[])null), "GKCustomFlowNodeWithWgoData.GetWgoData");
			}
			if (_wgoData != null)
			{
				return true;
			}
			TimbnFrameworkPlugin<TimbnCorePlugin>.Logger.LogWarning((object)"Flow_SetWGOPositionPatch|The game's story teleport changed, so schedules do not notice a story graph teleporting someone.");
			return false;
		}

		[HarmonyPatch("Teleport")]
		[HarmonyPrefix]
		private static void TeleportPreFix(Flow_SetWGOPosition __instance)
		{
			TimbnGameMoves.OnTeleport(_wgoData((GKCustomFlowNodeWithWgoData)(object)__instance));
		}
	}
	[HarmonyPatch(typeof(GameBalance))]
	internal static class GameBalancePatch
	{
		[HarmonyPatch("LoadGameBalance")]
		[HarmonyPostfix]
		private static void LoadGameBalancePostFix()
		{
			GameBalance loaded = TimbnBalance.Loaded;
			if (loaded != null)
			{
				TimbnBalance.OnBalanceLoaded(loaded);
				TimbnPatchedEvents.RaiseBalanceLoaded(loaded);
			}
		}
	}
	[HarmonyPatch(typeof(GameSave))]
	internal static class GameSavePatch
	{
		[HarmonyPatch("PrepareForGame")]
		[HarmonyPrefix]
		private static void PrepareForGamePreFix(GameSave __instance)
		{
			TimbnSafe.Run(delegate
			{
				TimbnModContent.OnPrepareForGame(__instance);
			}, "GameSavePatch|Putting mod items, buffs, crafts and stations back into the save");
		}
	}
	[HarmonyPatch(typeof(GlobalEventsSystem))]
	internal static class GlobalEventsSystemPatch
	{
		[HarmonyPatch("FireTrigger")]
		[HarmonyPostfix]
		private static void FireTriggerPostFix(Type type, string id)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			TimbnPatchedEvents.RaiseTriggered(type, id);
		}
	}
	[HarmonyPatch(typeof(HUD))]
	internal static class HUDPatch
	{
		[HarmonyPatch("HasWorkInteractionEvent")]
		[HarmonyPostfix]
		private static void HasWorkInteractionEventPostFix(WgoData wgoData, ref bool __result)
		{
			__result = __result || TimbnQuestMarker.IsMarked(wgoData);
		}
	}
	[HarmonyPatch(typeof(InteractionEvent))]
	internal static class InteractionEventPatch
	{
		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		[HarmonyPostfix]
		private static void CustomIconPostFix(InteractionEvent __instance, ref string __result)
		{
			__result = TimbnDialog.IconFor(__instance.str, __result);
		}
	}
	[HarmonyPatch(typeof(LLBase))]
	internal static class LLBasePatch
	{
		[HarmonyPatch("InitHashDictionary")]
		[HarmonyPostfix]
		private static void InitHashDictionaryPostFix(LLBase __instance)
		{
			TimbnLocale.ApplyTo(__instance);
		}
	}
	[HarmonyPatch(typeof(MainGame))]
	internal static class MainGamePatch
	{
		[HarmonyPatch("CreateGameSaveAndStart")]
		[HarmonyPrefix]
		private static void CreateGameSaveAndStartPreFix()
		{
			TimbnSafe.Run(TimbnSaves.OnNewGameStarting, "MainGamePatch|Starting the Timbn save file for a new game");
		}

		[HarmonyPatch("ContinueGame")]
		[HarmonyPrefix]
		private static void ContinueGamePreFix(SaveSlotData saveSlotData, GameSave gameSave)
		{
			TimbnSafe.Run(delegate
			{
				TimbnSaves.OnContinueGame(saveSlotData, gameSave);
			}, "MainGamePatch|Reading the Timbn save file for slot " + saveSlotData?.slotName);
		}
	}
	[HarmonyPatch(typeof(MainGame))]
	internal static class MainGameStartPatch
	{
		[HarmonyPatch("Start")]
		[HarmonyPostfix]
		private static void StartPostFix()
		{
			TimbnSafe.Run(TimbnGameEvents.OnMainGameStarted, "MainGameStartPatch|Moving the game start handlers behind the game's own");
		}
	}
	[HarmonyPatch(typeof(MovementComponent))]
	internal static class MovementComponentPatch
	{
		[HarmonyPatch("StartPath", new Type[]
		{
			typeof(Vector3),
			typeof(string),
			typeof(string),
			typeof(MovementType),
			typeof(float),
			typeof(string),
			typeof(Action),
			typeof(Seeker),
			typeof(DestinationType),
			typeof(bool)
		})]
		[HarmonyPrefix]
		private static void StartPathPreFix(MovementComponent __instance)
		{
			TimbnGameMoves.OnWalk(__instance);
		}

		[HarmonyPatch("StartPath", new Type[]
		{
			typeof(Vector3),
			typeof(GraphMask),
			typeof(string),
			typeof(float),
			typeof(string),
			typeof(Action),
			typeof(DestinationType),
			typeof(bool)
		})]
		[HarmonyPrefix]
		private static void StartZonePathPreFix(MovementComponent __instance)
		{
			TimbnGameMoves.OnWalk(__instance);
		}
	}
	[HarmonyPatch(typeof(MovementComponent))]
	internal static class MovementComponentRoutePatch
	{
		private static bool Prepare()
		{
			if (TimbnPlannedRoute.IsAvailable)
			{
				return true;
			}
			TimbnFrameworkPlugin<TimbnCorePlugin>.Logger.LogWarning((object)"MovementComponentRoutePatch|The game's walker changed, so people walking the paths keep to the one way links.");
			return false;
		}

		[HarmonyPatch("FindPathGDGraph")]
		[HarmonyPrefix]
		private static bool FindPathGDGraphPreFix(MovementComponent __instance)
		{
			return !TimbnPlannedRoute.TryUse(__instance);
		}

		[HarmonyPatch("FindPathRecastGraph")]
		[HarmonyPrefix]
		private static bool FindPathRecastGraphPreFix(MovementComponent __instance, ref bool __result)
		{
			if (!TimbnPlannedRoute.TryUseCorners(__instance))
			{
				return true;
			}
			__result = true;
			return false;
		}
	}
	[HarmonyPatch(typeof(PlayerData))]
	internal static class PlayerDataDropPatch
	{
		[HarmonyPatch("DropOverheadItem", new Type[] { typeof(Item) })]
		[HarmonyPrefix]
		private static bool DropOverheadItemPreFix(Item item)
		{
			return !TimbnOverhead.BlocksDrop(item);
		}

		[HarmonyPatch("AddOverheadItem")]
		[HarmonyPrefix]
		private static bool AddOverheadItemPreFix(Item item, out bool __state)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			__state = TimbnOverhead.IsReadingInput;
			TimbnOverhead.IsReadingInput = false;
			if (!TimbnOverhead.HandsLocked || item == null || item.IsEmpty)
			{
				return true;
			}
			TimbnItems.DropAt(item, MainGame.PlayerData.currentGameSceneId, TimbnPlayer.Position);
			return false;
		}

		[HarmonyPatch("AddOverheadItem")]
		[HarmonyFinalizer]
		private static void AddOverheadItemFinalizer(bool __state)
		{
			TimbnOverhead.IsReadingInput = __state;
		}
	}
	[HarmonyPatch(typeof(PlayerData))]
	internal static class PlayerDataInteractingItemPatch
	{
		[HarmonyPatch("SetInteractingItem")]
		[HarmonyPrefix]
		private static bool SetInteractingItemPreFix()
		{
			return !TimbnOverhead.HandsLocked;
		}
	}
	[HarmonyPatch(typeof(PlayerInputHandler))]
	internal static class PlayerInputHandlerPatch
	{
		[HarmonyPatch("UpdateInput")]
		[HarmonyPrefix]
		private static bool UpdateInputPreFix()
		{
			TimbnOverhead.IsReadingInput = true;
			return !TimbnInteractionHint.IsKeyClaimed();
		}

		[HarmonyPatch("UpdateInput")]
		[HarmonyFinalizer]
		private static void UpdateInputFinalizer()
		{
			TimbnOverhead.IsReadingInput = false;
		}

		[HarmonyPatch("UpdateInputInteractionOnly")]
		[HarmonyPrefix]
		private static bool UpdateInputInteractionOnlyPreFix()
		{
			TimbnOverhead.IsReadingInput = true;
			return !TimbnInteractionHint.IsKeyClaimed();
		}

		[HarmonyPatch("UpdateInputInteractionOnly")]
		[HarmonyFinalizer]
		private static void UpdateInputInteractionOnlyFinalizer()
		{
			TimbnOverhead.IsReadingInput = false;
		}
	}
	[HarmonyPatch(typeof(PlayerPhysicalBody))]
	internal static class PlayerPhysicalBodyPatch
	{
		[HarmonyPatch("MoveByDirection")]
		[HarmonyPrefix]
		private static void MoveByDirectionPreFix(PlayerPhysicalBody __instance, ref Vector2 direction, out float? __state)
		{
			TimbnPlayerWalk.Steer(__instance, ref direction);
			__state = TimbnMovement.SpeedUp(__instance);
		}

		[HarmonyPatch("MoveByDirection")]
		[HarmonyFinalizer]
		private static void MoveByDirectionFinalizer(PlayerPhysicalBody __instance, float? __state)
		{
			if (__state.HasValue)
			{
				float valueOrDefault = __state.GetValueOrDefault();
				__instance.SpeedMultiplier = valueOrDefault;
			}
		}
	}
	[HarmonyPatch(typeof(QuestSystemData))]
	internal static class QuestSystemDataPatch
	{
		[HarmonyPatch("PrepareForGame")]
		[HarmonyPrefix]
		private static void PrepareForGamePreFix(QuestSystemData __instance)
		{
			TimbnSafe.Run(delegate
			{
				TimbnQuests.StubOrphans(__instance);
			}, "QuestSystemDataPatch|Standing in for saved quests whose mod is gone");
		}

		[HarmonyPatch("PrepareForGame")]
		[HarmonyPostfix]
		private static void PrepareForGamePostFix(QuestSystemData __instance)
		{
			TimbnSafe.Run(delegate
			{
				TimbnQuests.OnQuestsPrepared(__instance);
			}, "QuestSystemDataPatch|Preparing mod quests for the save");
		}
	}
	[HarmonyPatch(typeof(QuestTreeConnector))]
	internal static class QuestTreeConnectorPatch
	{
		[HarmonyPatch("Draw")]
		[HarmonyPostfix]
		private static void DrawPostFix(QuestTreeConnector __instance, LazyScrollableElement child, bool isBackground)
		{
			TimbnQuestTree.TintLine(__instance, child, isBackground);
		}
	}
	[HarmonyPatch(typeof(SaveSystem))]
	internal static class SaveSystemPatch
	{
		[HarmonyPatch("Save")]
		[HarmonyPrefix]
		private static void SavePreFix(SaveSlotData slotData, GameSave gameSave, ref Action? callbackSuccessful, out List<IDisposable> __state)
		{
			try
			{
				callbackSuccessful = TimbnSaves.WrapSaveCallback(slotData, gameSave, callbackSuccessful);
			}
			catch (Exception arg)
			{
				TimbnFrameworkPlugin<TimbnCorePlugin>.Logger.LogError((object)string.Format("{0}|Could not add mod save data to the save: {1}", "SaveSystemPatch", arg));
			}
			__state = new List<IDisposable>();
			int num;
			if ((Object)(object)MainGame.Instance != (Object)null)
			{
				num = ((gameSave == MainGame.Instance.GameSave) ? 1 : 0);
				if (num != 0)
				{
					TimbnSafe.Run(TimbnSaveEvents.RaiseBefore, TimbnFrameworkPlugin<TimbnCorePlugin>.Logger, "Before");
				}
			}
			else
			{
				num = 0;
			}
			Strip(__state, () => TimbnQuests.HideForSave(gameSave));
			Strip(__state, TimbnDialog.RemoveForSave);
			Strip(__state, TimbnNpcs.RemoveSpawnedForSave);
			Strip(__state, TimbnNpcs.ReleaseClaimsForSave);
			Strip(__state, TimbnNpc.ClearAnimationsForSave);
			Strip(__state, TimbnOverhead.RemoveForSave);
			Strip(__state, TimbnBaseGamePlaces.PlaceAllForSave);
			Strip(__state, TimbnPotions.RevertForSave);
			if (num != 0)
			{
				Strip(__state, () => TimbnModContent.StripForSave(gameSave));
				__state.Insert(0, new TimbnUndo(delegate
				{
					TimbnSafe.Run(TimbnSaveEvents.RaiseAfter, TimbnFrameworkPlugin<TimbnCorePlugin>.Logger, "After");
				}));
			}
		}

		[HarmonyPatch("Save")]
		[HarmonyFinalizer]
		private static void SaveFinalizer(List<IDisposable>? __state)
		{
			if (__state == null)
			{
				return;
			}
			for (int num = __state.Count - 1; num >= 0; num--)
			{
				try
				{
					__state[num].Dispose();
				}
				catch (Exception arg)
				{
					TimbnFrameworkPlugin<TimbnCorePlugin>.Logger.LogError((object)string.Format("{0}|Could not restore mod state after the save: {1}", "SaveSystemPatch", arg));
				}
			}
		}

		[HarmonyPatch("Remove")]
		[HarmonyPostfix]
		private static void RemovePostFix(SaveSlotData slotData, bool __result)
		{
			if (!__result || slotData.isDemoSave)
			{
				return;
			}
			try
			{
				TimbnSaves.DeleteSlot(slotData.slotName);
			}
			catch (Exception arg)
			{
				TimbnFrameworkPlugin<TimbnCorePlugin>.Logger.LogError((object)string.Format("{0}|Could not delete mod save data for slot {1}: {2}", "SaveSystemPatch", slotData.slotName, arg));
			}
		}

		private static void Strip(List<IDisposable> undos, Func<IDisposable> strip)
		{
			try
			{
				undos.Add(strip());
			}
			catch (Exception arg)
			{
				TimbnFrameworkPlugin<TimbnCorePlugin>.Logger.LogError((object)string.Format("{0}|Could not strip mod state from the save: {1}", "SaveSystemPatch", arg));
			}
		}
	}
	[HarmonyPatch(typeof(TechDef))]
	internal static class TechDefPatch
	{
		[HarmonyPatch("InitTechs")]
		[HarmonyPostfix]
		private static void InitTechsPostFix()
		{
			TimbnSafe.Run(TimbnTechRows.RefreshAll, "TechDefPatch|The rewards a mod's tech lists");
		}
	}
	[HarmonyPatch(typeof(UIGamePauseWindow))]
	internal static class UIGamePauseWindowPatch
	{
		[HarmonyPatch("Init")]
		[HarmonyPostfix]
		private static void InitPostFix(UIGamePauseWindow __instance)
		{
			TimbnSafe.Run(delegate
			{
				if (TimbnModsWindowHost.ShowModSettings.Value)
				{
					TimbnModSettingsButton.CreateInPause(__instance);
				}
			}, TimbnModsWindowHost.Log, "UIGamePauseWindowPatch|Adding the Mods button");
		}

		[HarmonyPatch("Open")]
		[HarmonyPostfix]
		[HarmonyPriority(0)]
		private static void OpenPostFix(UIGamePauseWindow __instance)
		{
			TimbnSafe.Run(delegate
			{
				TimbnModSettingsButton.MoveUnderSettings(__instance);
			}, TimbnModsWindowHost.Log, "UIGamePauseWindowPatch|Ordering the Mod Settings button");
		}
	}
	[HarmonyPatch(typeof(UIMagnifyingGlassWidget))]
	internal static class UIMagnifyingGlassWidgetPatch
	{
		[HarmonyPatch("Draw")]
		[HarmonyPostfix]
		private static void DrawPostFix(UIMagnifyingGlassWidget __instance, UIMagnifyingGlassWidgetData data)
		{
			TimbnQuestMarker.Recolor(__instance, data);
		}
	}
	[HarmonyPatch(typeof(UIMainMenuInfoPanel))]
	internal static class UIMainMenuInfoPanelPatch
	{
		[HarmonyPatch("SetMenuOnlyLabelsVisible")]
		[HarmonyPostfix]
		private static void SetMenuOnlyLabelsVisiblePostFix()
		{
			TimbnMainMenu.DrawLines();
		}
	}
	[HarmonyPatch(typeof(UIMainMenuWindow))]
	internal static class UIMainMenuWindowPatch
	{
		[HarmonyPatch("Init")]
		[HarmonyPostfix]
		private static void InitPostFix(UIMainMenuWindow __instance)
		{
			TimbnSafe.Run(delegate
			{
				if (TimbnModsWindowHost.ShowModSettings.Value)
				{
					TimbnModSettingsButton.Create(__instance);
				}
			}, TimbnModsWindowHost.Log, "UIMainMenuWindowPatch|Adding the Mod Settings button");
		}

		[HarmonyPatch("Open")]
		[HarmonyPostfix]
		[HarmonyPriority(0)]
		private static void OpenPostFix(UIMainMenuWindow __instance)
		{
			TimbnSafe.Run(delegate
			{
				TimbnModSettingsButton.MoveUnderSettings(__instance);
				TimbnModSettingsButton.Relayout(__instance);
			}, TimbnModsWindowHost.Log, "UIMainMenuWindowPatch|Laying out the main menu buttons");
		}
	}
	[HarmonyPatch(typeof(UIMultiAnswerOption))]
	internal static class UIMultiAnswerOptionPatch
	{
		[HarmonyPatch("Show")]
		[HarmonyPostfix]
		private static void ShowPostFix(UIMultiAnswerOption __instance)
		{
			TimbnSafe.Run(delegate
			{
				TimbnAnswerColors.Paint(__instance);
			}, "UIMultiAnswerOptionPatch|Painting an answer");
		}

		[HarmonyPatch("ChangeColor")]
		[HarmonyPrefix]
		private static void ChangeColorPreFix(UIMultiAnswerOption __instance, ref Color color)
		{
			//IL_000f: 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)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			Color shown = color;
			TimbnSafe.Run(delegate
			{
				//IL_0008: 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)
				shown = TimbnAnswerColors.Recolor(__instance, shown);
			}, "UIMultiAnswerOptionPatch|Recoloring an answer");
			color = shown;
		}
	}
	[HarmonyPatch(typeof(UIVendorWindow))]
	internal static class UIVendorWindowPatch
	{
		[HarmonyPatch("Open", new Type[] { typeof(UIVendorWindowData) })]
		[HarmonyPrefix]
		private static bool OpenPreFix(UIVendorWindowData data)
		{
			return TimbnVendorGates.LetOpen(data);
		}
	}
	[HarmonyPatch(typeof(UIWorkbenchAdditionWorldIconWidget))]
	internal static class UIWorkbenchAdditionWorldIconWidgetPatch
	{
		[HarmonyPatch("Redraw")]
		[HarmonyPostfix]
		private static void RedrawPostFix(UIWorkbenchAdditionWorldIconWidget __instance)
		{
			TimbnSafe.Run(delegate
			{
				TimbnBubble.Style(__instance);
			}, "UIWorkbenchAdditionWorldIconWidgetPatch|The look of a bubble");
		}
	}
	[HarmonyPatch(typeof(WgoData))]
	internal static class WgoDataPatch
	{
		[HarmonyPatch("FireInteractionEvent")]
		[HarmonyPrefix]
		private static bool FireInteractionEventPreFix(WgoData __instance, ref bool __result, out bool __state)
		{
			TimbnGameMoves.InteractionStarted();
			__state = true;
			if (TimbnDialog.TryHandleInteraction(__instance))
			{
				__result = true;
				return false;
			}
			InteractionEvent val = __instance.PeekFirstAddedEvent();
			if (val != null && !val.isFake)
			{
				TimbnNpcTalk.GameTalkStarted(__instance);
			}
			return true;
		}

		[HarmonyPatch("FireInteractionEvent")]
		[HarmonyFinalizer]
		private static void FireInteractionEventFinalizer(bool __state)
		{
			if (__state)
			{
				TimbnGameMoves.InteractionEnded();
			}
		}

		[HarmonyPatch("FireEvent")]
		[HarmonyPrefix]
		private static void FireEventPreFix(WgoData __instance, string eventName)
		{
			if (eventName == "interaction")
			{
				TimbnNpcTalk.GameTalkStarted(__instance);
			}
			TimbnGameMoves.OnEvent(__instance, eventName);
		}

		[HarmonyPatch("OnCraftStart")]
		[HarmonyPostfix]
		private static void OnCraftStartPostFix(WgoData __instance, CraftElementBase ce)
		{
			TimbnCraftEvents.Started(__instance, ce);
		}

		[HarmonyPatch("OnCraftEnd")]
		[HarmonyPostfix]
		private static void OnCraftEndPostFix(WgoData __instance, CraftElementBase ce)
		{
			TimbnCraftEvents.Finished(__instance, ce);
		}

		[HarmonyPatch("AddInteractionEvent")]
		[HarmonyPostfix]
		private static void AddInteractionEventPostFix(WgoData __instance, string id)
		{
			TimbnDialog.OnEventAdded(__instance, id);
		}
	}
	[HarmonyPatch(typeof(WGOInteractionHandlerBase))]
	internal static class WGOInteractionHandlerBasePatch
	{
		[HarmonyPatch("GetInteractionInfos")]
		[HarmonyPostfix]
		private static void GetInteractionInfosPostFix(Wgo ___assignedWgo, InteractionInfos __result)
		{
			TimbnInteractions.AddHints(___assignedWgo, __result);
		}

		[HarmonyPatch("HasInteraction")]
		[HarmonyPostfix]
		private static void HasInteractionPostFix(Wgo ___assignedWgo, ref bool __result)
		{
			if (!__result && TimbnInteractions.Has(___assignedWgo, primary: true))
			{
				__result = true;
			}
		}

		[HarmonyPatch("Interact")]
		[HarmonyPrefix]
		private static bool InteractPreFix(Wgo ___assignedWgo, ref bool __result)
		{
			if (!TimbnInteractions.Interact(___assignedWgo, primary: true))
			{
				return true;
			}
			__result = true;
			return false;
		}

		[HarmonyPatch("HasInteraction2")]
		[HarmonyPostfix]
		private static void HasInteraction2PostFix(Wgo ___assignedWgo, ref bool __result)
		{
			if (!__result && TimbnInteractions.Has(___assignedWgo, primary: false))
			{
				__result = true;
			}
		}

		[HarmonyPatch("Interact2")]
		[HarmonyPrefix]
		private static bool Interact2PreFix(Wgo ___assignedWgo, ref bool __result)
		{
			if (!TimbnInteractions.Interact(___assignedWgo, primary: false))
			{
				return true;
			}
			__result = true;
			return false;
		}
	}
	[HarmonyPatch(typeof(WgoPart))]
	internal static class WgoPartPatch
	{
		[HarmonyPatch("SetupZombieSkin")]
		[HarmonyPostfix]
		private static void SetupZombieSkinPostFix(WgoPart __instance, ZombieWgoData zombieWgoData)
		{
			TimbnPatchedEvents.RaiseZombieViewReady(__instance, zombieWgoData);
		}

		[HarmonyPatch("ApplyWgoPartState", new Type[] { typeof(WgoPartState) })]
		[HarmonyPostfix]
		private static void ApplyWgoPartStatePostFix(WgoPart __instance)
		{
			TimbnPartPrefab.PlaceDock(__instance);
		}
	}
	[HarmonyPatch(typeof(WgoPartPool))]
	internal static class WgoPartPoolPatch
	{
		[HarmonyPatch("LoadPrefabAsync")]
		[HarmonyPrefix]
		private static bool LoadPrefabAsyncPreFix(string addressableKey, ref AsyncOperationHandle<GameObject> __result)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			if (!TimbnModels.TryGetPart(addressableKey, out TimbnPartPrefab part))
			{
				return true;
			}
			__result = part.CreateHandle();
			return false;
		}
	}
	[HarmonyPatch(typeof(Wgo))]
	internal static class WgoPatch
	{
		[HarmonyPatch("SetSelectionTint")]
		[HarmonyPostfix]
		private static void SetSelectionTintPostFix(Wgo __instance, Color color, float amount)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			TimbnModels.TintParts(__instance, color, amount);
		}
	}
	[HarmonyPatch(typeof(WorldData))]
	internal static class WorldDataPatch
	{
		private static int _putBack;

		[HarmonyPatch("MoveWgoDataToAnotherGameScene")]
		[HarmonyPrefix]
		private static void MoveWgoDataToAnotherGameScenePreFix()
		{
			_putBack++;
		}

		[HarmonyPatch("MoveWgoDataToAnotherGameScene")]
		[HarmonyFinalizer]
		private static void MoveWgoDataToAnotherGameSceneFinalizer()
		{
			_putBack--;
		}

		[HarmonyPatch("RemoveWgoDataFromGameScene", new Type[]
		{
			typeof(WgoData),
			typeof(bool)
		})]
		[HarmonyPrefix]
		private static void RemoveWgoDataFromGameScenePreFix(WorldData __instance, WgoData wgoData, out WgoData? __state)
		{
			__state = __instance.GetWgoData(wgoData.UniqueId);
		}

		[HarmonyPatch("RemoveWgoDataFromGameScene", new Type[]
		{
			typeof(WgoData),
			typeof(bool)
		})]
		[HarmonyPostfix]
		private static void RemoveWgoDataFromGameScenePostFix(WgoData? __state, bool clearCraftComponent)
		{
			if (clearCraftComponent)
			{
				Removed(__state);
			}
		}

		[HarmonyPatch("RemoveWgoDataFromGameScene", new Type[] { typeof(SGuid) })]
		[HarmonyPrefix]
		private static void RemoveWgoDataFromGameSceneByIdPreFix(WorldData __instance, SGuid sGuid, out WgoData? __state)
		{
			__state = __instance.GetWgoData(sGuid);
		}

		[HarmonyPatch("RemoveWgoDataFromGameScene", new Type[] { typeof(SGuid) })]
		[HarmonyPostfix]
		private static void RemoveWgoDataFromGameSceneByIdPostFix(WgoData? __state)
		{
			Removed(__state);
		}

		private static void Removed(WgoData? data)
		{
			if (data != null && _putBack == 0)
			{
				TimbnPatchedEvents.RaiseWorldObjectRemoved(data);
			}
		}
	}
	[HarmonyPatch(typeof(ZombieDropInteractionHandler))]
	internal static class ZombieDropInteractionHandlerPatch
	{
		[HarmonyPatch("HasInteraction")]
		[HarmonyPostfix]
		private static void HasInteractionPostFix(ref bool __result)
		{
			if (__result && TimbnOverhead.HandsLocked)
			{
				__result = false;
			}
		}
	}
	[HarmonyPatch(typeof(ZombieWgoData))]
	internal static class ZombieWgoDataSeatPatch
	{
		[HarmonyPatch("CaretakerUpdateBehaviour")]
		[HarmonyPrefix]
		private static bool CaretakerUpdateBehaviourPreFix(ZombieWgoData __instance)
		{
			return !TimbnZombieSpots.KeepsSeated(__instance);
		}
	}
}
namespace Timbn.GraveyardKeeperTwo.Core.Framework
{
	internal static class TimbnMusic
	{
		private sealed class Playing
		{
			internal PlaylistController Music { get; }

			internal PlaylistController? Paused { get; }

			internal Playing(PlaylistController music, PlaylistController? paused)
			{
				Music = music;
				Paused = paused;
			}

			internal void Stop(bool restore)
			{
				if (_current != this)
				{
					return;
				}
				_current = null;
				if ((Object)(object)Music != (Object)null)
				{
					Music.Stop(2f);
				}
				if (restore)
				{
					if ((Object)(object)Paused != (Object)null && Paused.IsActive && Paused.IsPaused)
					{
						Paused.UnPause(2f);
					}
					else if (!LazyAudio.GetPlaylistControllers().Exists((PlaylistController each) => (Object)(object)each != (Object)(object)Music && each.IsActive && !each.IsPaused))
					{
						LazyAudio.PlayPlaylist("gameplay");
					}
				}
			}
		}

		private const string _prefix = "timbn_music_";

		private const string _gameplay = "gameplay";

		private const float _fade = 2f;

		private static readonly FieldInfo? _instance = AccessTools.Field(typeof(LazyAudio), "instance");

		private static readonly FieldRef<LazyAudio, List<PlaylistController>>? _controllers = TimbnReflection.TryField<LazyAudio, List<PlaylistController>>("playlistControllers");

		private static Playing? _current;

		internal static IDisposable Play(string trackId, ManualLogSource logger)
		{
			if (TimbnGame.IsInGame)
			{
				PlaylistController music = Controller(trackId, logger);
				if (music != null)
				{
					PlaylistController val = _current?.Paused;
					_current?.Stop(restore: false);
					if (val == null)
					{
						val = LazyAudio.GetPlaylistControllers().Find((PlaylistController each) => (Object)(object)each != (Object)(object)music && each.IsActive && !each.IsPaused);
					}
					if (val != null)
					{
						val.Pause(2f);
					}
					music.Play(2f);
					logger.LogDebug((object)("TimbnPluginAudio.PlayMusic|Playing " + trackId + (((Object)(object)val != (Object)null) ? (" over " + val.Id) : "") + "."));
					Playing playing = new Playing(music, val);
					_current = playing;
					return new TimbnUndo(delegate
					{
						playing.Stop(restore: true);
					});
				}
			}
			return TimbnUndo.None;
		}

		private static PlaylistController? Controller(string trackId, ManualLogSource logger)
		{
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0108: Unknown result type (might be due to invalid IL or missing references)
			//IL_0114: Unknown result type (might be due to invalid IL or missing references)
			//IL_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_012d: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Expected O, but got Unknown
			//IL_015a: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0196: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b8: Expected O, but got Unknown
			//IL_01b8: Unknown result type (might be due to invalid IL or missing references)
			if ((object)_instance != null && _controllers != null)
			{
				object? value = _instance.GetValue(null);
				LazyAudio val = (LazyAudio)((value is LazyAudio) ? value : null);
				if (val != null)
				{
					List<PlaylistController> list = _controllers.Invoke(val);
					if (list != null)
					{
						string id = "timbn_music_" + trackId;
						PlaylistController val2 = list.Find((PlaylistController each) => (Object)(object)each != (Object)null && each.Id == id);
						if (val2 != null)
						{
							return val2;
						}
						(Playlist, Track) tuple = list.Where((PlaylistController each) => ((each != null) ? each.Playlist : null) != null).SelectMany((PlaylistController each) => each.Playlist.tracks.Select((Track track) => (Playlist: each.Playlist, Track: track))).FirstOrDefault(((Playlist Playlist, Track Track) pair) => pair.Track.id == trackId);
						if ((Object)(object)tuple.Item2?.clip == (Object)null)
						{
							logger.LogWarning((object)("TimbnPluginAudio.PlayMusic|The game has no music track " + trackId + "."));
							return null;
						}
						Playlist val3 = new Playlist
						{
							id = id,
							loop = true,
							volume = tuple.Item1.volume,
							fadeDuration = tuple.Item1.fadeDuration,
							group = tuple.Item1.group
						};
						val3.tracks.Add(new Track
						{
							id = trackId,
							clip = tuple.Item2.clip,
							volume = tuple.Item2.volume,
							loop = true,
							pitch = tuple.Item2.pitch,
							weight = 1f
						});
						PlaylistController val4 = new GameObject().AddComponent<PlaylistController>();
						((Component)val4).transform.SetParent(((Component)val).transform);
						val4.Initialize(val3);
						list.Add(val4);
						return val4;
					}
				}
			}
			return null;
		}
	}
	public sealed class TimbnPluginAudio
	{
		private readonly TimbnFrameworkPlugin _owner;

		internal TimbnPluginAudio(TimbnFrameworkPlugin owner)
		{
			_owner = owner;
		}

		public IDisposable PlayMusic(string trackId)
		{
			return _owner.SessionSubscriptions.Add(TimbnMusic.Play(trackId, _owner.PluginLogger));
		}

		public void PlaySound(string soundId)
		{
			if (TimbnGame.IsInGame && !string.IsNullOrEmpty(soundId))
			{
				LazyAudio.PlayAndForget(soundId);
			}
		}
	}
	public static class TimbnBalance
	{
		private interface IEdit
		{
			Type DefinitionType { get; }

			bool CanApply(GameBalance balance);

			bool Apply(GameBalance balance);

			bool Revert();
		}

		private sealed class DefinitionEdit<T>(string id, Action<T> apply, Action<T> revert, ManualLogSource logger) : IEdit where T : BalanceBaseObject
		{
			private T? _applied;

			public Type DefinitionType => typeof(T);

			public bool CanApply(GameBalance balance)
			{
				return ((GameBalanceBase)balance).GetDataOrNull<T>(<id>P) != null;
			}

			public bool Apply(GameBalance balance)
			{
				T dataOrNull = ((GameBalanceBase)balance).GetDataOrNull<T>(<id>P);
				if (dataOrNull == null)
				{
					<logger>P.LogWarning((object)("TimbnBalance|The balance has no " + typeof(T).Name + " '" + <id>P + "' to change."));
					return false;
				}
				if ((object)dataOrNull == (object)_applied)
				{
					return false;
				}
				_applied = dataOrNull;
				Run(<apply>P, dataOrNull, "changing");
				return true;
			}

			public bool Revert()
			{
				T applied = _applied;
				_applied = default(T);
				if (applied != null)
				{
					GameBalance? loaded = Loaded;
					if ((object)((loaded != null) ? ((GameBalanceBase)loaded).GetDataOrNull<T>(<id>P) : default(T)) == (object)applied)
					{
						Run(<revert>P, applied, "restoring");
						return true;
					}
				}
				return false;
			}

			private void Run(Action<T> action, T definition, string doing)
			{
				TimbnSafe.Run(delegate
				{
					action(definition);
				}, <logger>P, "TimbnBalance|" + doing + " " + typeof(T).Name + " '" + <id>P + "'");
				object obj = definition;
				ItemDef val = (ItemDef)((obj is ItemDef) ? obj : null);
				if (val != null)
				{
					RefreshUseEffects(val);
				}
			}
		}

		private sealed class Entry
		{
			public BalanceBaseObject Definition { get; }

			public Func<GameBalance, bool>? Prepare { get; }

			public Action<GameBalance>? Removed { get; }

			public Entry(BalanceBaseObject definition, Func<GameBalance, bool>? prepare, Action<GameBalance>? removed)
			{
				Definition = definition;
				Prepare = prepare;
				Removed = removed;
			}
		}

		private static readonly FieldRef<GameBalance?> _instance = AccessTools.StaticFieldRefAccess<GameBalance>(AccessTools.Field(typeof(GameBalance), "instance"));

		private static readonly FieldRef<GameBalanceBase, List<Type>> _types = AccessTools.FieldRefAccess<GameBalanceBase, List<Type>>("types");

		private static readonly FieldRef<GameBalanceBase, List<Dictionary<string, int>>> _cache = AccessTools.FieldRefAccess<GameBalanceBase, List<Dictionary<string, int>>>("cache");

		private static readonly Action<GameBalance> _createQuestsCache = CacheBuilder("CreateQuestsCache");

		private static readonly Action<GameBalance> _createCraftCache = CacheBuilder("CreateCraftCache");

		private static readonly Action<GameBalance> _createAutopsyCraftsCache = CacheBuilder("CreateAutopsyCraftsCache");

		private static readonly Action<GameBalance> _createCraftGroupsCache = CacheBuilder("CreateCraftGroupsCache");

		private static readonly Action<GameBalance> _createCraftInItemsCache = CacheBuilder("CreateCraftInItemsCache");

		private static readonly Action<GameBalance> _createWorkbenchExtensionsCache = CacheBuilder("CreateWorkbenchExtensionsCache");

		private static readonly Action<GameBalance> _createBuildCache = CacheBuilder("CreateBuildCache");

		private static readonly Action<GameBalance> _createCustomBuildAreaCache = CacheBuilder("CreateCustomBuildAreaIdToWgoIdsCache");

		private static readonly FieldRef<ObjectLinkedToDefinition<WGODef>, string> _worldObjectCachedId = AccessTools.FieldRefAccess<ObjectLinkedToDefinition<WGODef>, string>("cachedId");

		private static readonly FieldRef<ItemDef, string> _itemCustomIcon = AccessTools.FieldRefAccess<ItemDef, string>("customIcon");

		private static readonly FieldRef<ItemDef, bool> _itemPerksCached = AccessTools.FieldRefAccess<ItemDef, bool>("perksCached");

		private static readonly List<Entry> _entries = new List<Entry>();

		private static readonly List<Entry> _held = new List<Entry>();

		private static bool _holding;

		private static readonly List<IEdit> _edits = new List<IEdit>();

		private static readonly HashSet<BalanceBaseObject> _deferred = new HashSet<BalanceBaseObject>();

		private static bool _resolving;

		public static GameBalance? Loaded => _instance.Invoke();

		internal static IDisposable Add(BalanceBaseObject definition)
		{
			return Add(definition, null, null);
		}

		internal static IDisposable Add(BalanceBaseObject definition, Action<GameBalance>? prepare)
		{
			Func<GameBalance, bool> prepare2 = ((prepare == null) ? null : ((Func<GameBalance, bool>)delegate(GameBalance balance)
			{
				prepare(balance);
				return true;
			}));
			return Add(definition, prepare2, null);
		}

		internal static IDisposable Add(BalanceBaseObject definition, Func<GameBalance, bool>? prepare, Action<GameBalance>? removed)
		{
			return Add(definition, prepare, removed, refresh: true);
		}

		internal static IDisposable AddWithoutRefresh(BalanceBaseObject definition)
		{
			return Add(definition, null, null, refresh: false);
		}

		private static IDisposable Add(BalanceBaseObject definition, Func<GameBalance, bool>? prepare, Action<GameBalance>? removed, bool refresh)
		{
			Entry entry = new Entry(definition, prepare, removed);
			_entries.Add(entry);
			GameBalance loaded = Loaded;
			if (loaded != null && Insert(loaded, entry))
			{
				if (refresh)
				{
					RefreshDerivedCaches(loaded, ((object)definition).GetType());
				}
				RefreshLoadedObjects(definition);
			}
			return new TimbnUndo(delegate
			{
				Remove(entry);
			});
		}

		internal static IDisposable AddCopy<T>(string templateId, string id, Action<T>? edit) where T : BalanceBaseObject, new()
		{
			return AddCopy((GameBalance _) => templateId, id, (edit == null) ? null : ((Action<GameBalance, T>)delegate(GameBalance _, T definition)
			{
				edit(definition);
			}));
		}

		internal static IDisposable AddCopy<T>(Func<GameBalance, string> templateIdOf, string id, Action<GameBalance, T>? edit, Func<GameBalance, bool>? accept = null) where T : BalanceBaseObject, new()
		{
			T val = new T();
			((BalanceBaseObject)val).id = id;
			T definition = val;
			return Add((BalanceBaseObject)(object)definition, delegate(GameBalance balance)
			{
				if (accept != null && !accept(balance))
				{
					return false;
				}
				string text = templateIdOf(balance);
				T dataOrNull = ((GameBalanceBase)balance).GetDataOrNull<T>(text);
				if (dataOrNull == null && _resolving && IsPending<T>(balance, text))
				{
					_deferred.Add((BalanceBaseObject)(object)definition);
					return false;
				}
				if (dataOrNull == null)
				{
					TimbnFrameworkPlugin<TimbnCorePlugin>.Logger.LogError((object)("TimbnBalance|There is no " + typeof(T).Name + " '" + text + "' to copy for '" + id + "'."));
					return false;
				}
				JsonUtility.FromJsonOverwrite(JsonUtility.ToJson((object)dataOrNull), (object)definition);
				((BalanceBaseObject)definition).id = id;
				edit?.Invoke(balance, definition);
				object obj = definition;
				ItemDef val2 = (ItemDef)((obj is ItemDef) ? obj : null);
				if (val2 != null)
				{
					RefreshUseEffects(val2);
				}
				return true;
			}, null);
		}

		internal static IDisposable AddItem(string templateItemId, string id, string name, string description, string iconId, Action<ItemDef>? edit)
		{
			List<IDisposable> list = new List<IDisposable>();
			Dictionary<string, string> dictionary = TimbnStationRules.Texts((id, name), (TimbnStationRules.DescriptionKey(id), description));
			if (dictionary.Count > 0)
			{
				list.Add(TimbnLocale.Add(dictionary));
			}
			list.Add(TimbnBalance.AddCopy<ItemDef>(templateItemId, id, (Action<ItemDef>?)delegate(ItemDef item)
			{
				if (iconId.Length > 0)
				{
					SetIcon(item, iconId);
				}
				edit?.Invoke(item);
			}));
			return TimbnUndo.All(list);
		}

		public static LazyExpression TextExpression(string value)
		{
			return TimbnExpression.PureText(value);
		}

		public static LazyExpression Expression(string formula)
		{
			return TimbnExpression.Formula(formula);
		}

		internal static IDisposable Edit<T>(string id, Action<T> apply, Action<T> revert, ManualLogSource logger) where T : BalanceBaseObject
		{
			DefinitionEdit<T> edit = new DefinitionEdit<T>(id, apply, revert, logger);
			_edits.Add(edit);
			GameBalance loaded = Loaded;
			if (loaded != null && edit.Apply(loaded))
			{
				RefreshDerivedCaches(loaded, typeof(T));
			}
			return new TimbnUndo(delegate
			{
				_edits.Remove(edit);
				if (edit.Revert())
				{
					GameBalance loaded2 = Loaded;
					if (loaded2 != null)
					{
						RefreshDerivedCaches(loaded2, typeof(T));
					}
				}
			});
		}

		private static bool IsPending<T>(GameBalance balance, string id) where T : BalanceBaseObject
		{
			return _entries.Any((Entry entry) => entry.Definition is T && entry.Definition.id == id && !((GameBalanceBase)balance).GetDataCollection(typeof(T)).Contains(entry.Definition));
		}

		internal static void OnBalanceLoaded(GameBalance balance)
		{
			HashSet<Type> hashSet = new HashSet<Type>();
			ApplyReadyEdits(balance, hashSet);
			List<Entry> list = _entries.ToList();
			_resolving = true;
			try
			{
				while (list.Count > 0)
				{
					bool flag = false;
					List<Entry> list2 = new List<Entry>();
					foreach (Entry item in list)
					{
						if (Insert(balance, item))
						{
							hashSet.Add(((object)item.Definition).GetType());
							flag = true;
							ApplyReadyEdits(balance, hashSet);
						}
						else if (_deferred.Remove(item.Definition))
						{
							list2.Add(item);
						}
					}
					if (list2.Count == 0)
					{
						break;
					}
					if (!flag)
					{
						_resolving = false;
						foreach (Entry item2 in list2)
						{
							Insert(balance, item2);
						}
						break;
					}
					list = list2;
				}
			}
			finally
			{
				_resolving = false;
				_deferred.Clear();
			}
			foreach (IEdit item3 in _edits.ToList())
			{
				if (item3.Apply(balance))
				{
					hashSet.Add(item3.DefinitionType);
				}
			}
			if (hashSet.Remove(typeof(ItemDef)))
			{
				hashSet.Add(typeof(CraftDef));
			}
			foreach (Type item4 in hashSet)
			{
				RefreshDerivedCaches(balance, item4);
			}
		}

		private static void ApplyReadyEdits(GameBalance balance, HashSet<Type> touched)
		{
			foreach (IEdit item in from edit in _edits.ToList()
				where edit.CanApply(balance)
				select edit)
			{
				if (item.Apply(balance))
				{
					touched.Add(item.DefinitionType);
				}
			}
		}

		internal static void RefreshQuestCaches(GameBalance balance)
		{
			_createQuestsCache(balance);
		}

		internal static HashSet<string> AddedIds<T>() where T : BalanceBaseObject
		{
			HashSet<string> hashSet = new HashSet<string>();
			foreach (string item in from entry in _entries
				where entry.Definition is T
				select entry.Definition.id)
			{
				hashSet.Add(item);
			}
			return hashSet;
		}

		internal static HashSet<string> AllAddedIds()
		{
			HashSet<string> hashSet = new HashSet<string>();
			foreach (string item in _entries.Select((Entry entry) => entry.Definition.id))
			{
				hashSet.Add(item);
			}
			return hashSet;
		}

		internal static bool IsAdded(BalanceBaseObject definition)
		{
			if (!_entries.Any((Entry entry) => entry.Definition == definition))
			{
				return _held.Any((Entry entry) => entry.Definition == definition);
			}
			return true;
		}

		internal static void RefreshCraftCaches()
		{
			GameBalance loaded = Loaded;
			if (loaded == null)
			{
				return;
			}
			_createCraftGroupsCache(loaded);
			_createCraftCache(loaded);
			_createAutopsyCraftsCache(loaded);
			loaded.craftInItemsCache.Clear();
			loaded.craftInItemsCacheShownInTooltips.Clear();
			_createCraftInItemsCache(loaded);
			foreach (WgoData item in TimbnWorld.Objects())
			{
				CraftComponent craftComponent = item.CraftComponent;
				if (craftComponent != null)
				{
					craftComponent.ResetCraftsFromBalanceCache();
				}
			}
		}

		public static void SetIcon(ItemDef item, string iconId)
		{
			item.iconId = iconId;
			_itemCustomIcon.Invoke(item) = iconId;
		}

		public static string GetIcon(ItemDef item)
		{
			string text = _itemCustomIcon.Invoke(item);
			if (text == null || text.Length <= 0)
			{
				return item.iconId;
			}
			return text;
		}

		internal static void RefreshUseEffects(ItemDef item)
		{
			_itemPerksCached.Invoke(item) = false;
		}

		private static Action<GameBalance> CacheBuilder(string name)
		{
			return AccessTools.MethodDelegate<Action<GameBalance>>(AccessTools.Method(typeof(GameBalance), name, (Type[])null, (Type[])null), (object)null, true);
		}

		private static bool Insert(GameBalance balance, Entry entry)
		{
			BalanceBaseObject definition = entry.Definition;
			int num = _types.Invoke((GameBalanceBase)(object)balance).IndexOf(((object)definition).GetType());
			if (num == -1)
			{
				TimbnFrameworkPlugin<TimbnCorePlugin>.Logger.LogError((object)("TimbnBalance|The balance has no table for " + ((object)definition).GetType().Name + "."));
				return false;
			}
			IList list = ((GameBalanceBase)balance).GetDataCollection(((object)definition).GetType());
			if (list.Contains(definition))
			{
				return false;
			}
			int existing = FindById(list, definition.id);
			if (existing != -1 && !_entries.Any((Entry e) => e != entry && e.Definition == list[existing]) && !_held.Any((Entry e) => e.Definition == list[existing]))
			{
				_entries.Remove(entry);
				TimbnFrameworkPlugin<TimbnCorePlugin>.Logger.LogError((object)("TimbnBalance|The game already has a " + ((object)definition).GetType().Name + " with id '" + definition.id + "', so it is not added."));
				return false;
			}
			Func<GameBalance, bool> prepare = entry.Prepare;
			if (prepare != null && !prepare(balance))
			{
				return false;
			}
			if (existing == -1)
			{
				list.Add(definition);
				_cache.Invoke((GameBalanceBase)(object)balance)[num][definition.id] = list.Count - 1;
				return true;
			}
			object replaced = list[existing];
			_held.RemoveAll((Entry held) => held.Definition == replaced);
			list[existing] = definition;
			return true;
		}

		internal static void HoldRemovals()
		{
			_holding = true;
		}

		internal static void ReleaseHeldRemovals()
		{
			_holding = false;
			List<Entry> list = _held.ToList();
			_held.Clear();
			foreach (Entry item in list)
			{
				Drop(item);
			}
		}

		private static void Remove(Entry entry)
		{
			_entries.Remove(entry);
			if (_holding)
			{
				_held.Add(entry);
			}
			else
			{
				Drop(entry);
			}
		}

		private static void Drop(Entry entry)
		{
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			GameBalance balance = Loaded;
			if (balance == null)
			{
				return;
			}
			BalanceBaseObject definition = entry.Definition;
			int num = _types.Invoke((GameBalanceBase)(object)balance).IndexOf(((object)definition).GetType());
			if (num == -1)
			{
				return;
			}
			IList dataCollection = ((GameBalanceBase)balance).GetDataCollection(((object)definition).GetType());
			int num2 = dataCollection.IndexOf(definition);
			if (num2 != -1)
			{
				dataCollection.RemoveAt(num2);
				Dictionary<string, int> dictionary = _cache.Invoke((GameBalanceBase)(object)balance)[num];
				dictionary.Clear();
				for (int i = 0; i < dataCollection.Count; i++)
				{
					dictionary[((BalanceBaseObject)dataCollection[i]).id] = i;
				}
				RefreshDerivedCaches(balance, ((object)definition).GetType());
				TimbnSafe.Run(delegate
				{
					entry.Removed?.Invoke(balance);
				}, "TimbnBalance|Cleaning up after " + ((object)definition).GetType().Name + " '" + definition.id + "'");
			}
		}

		private static int FindById(IList list, string id)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			for (int i = 0; i < list.Count; i++)
			{
				if (((BalanceBaseObject)list[i]).id == id)
				{
					return i;
				}
			}
			return -1;
		}

		private static void RefreshDerivedCaches(GameBalance balance, Type type)
		{
			if (type == typeof(QuestDef))
			{
				TimbnQuestRuntime.RefreshCaches(balance);
			}
			else if (type == typeof(CraftDef) || type == typeof(ItemDef))
			{
				RefreshCraftCaches();
				if (type == typeof(CraftDef))
				{
					_createWorkbenchExtensionsCache(balance);
				}
			}
			else if (type == typeof(WGODef))
			{
				_createWorkbenchExtensionsCache(balance);
			}
			else if (type == typeof(BuildingDef))
			{
				_createBuildCache(balance);
				_createCustomBuildAreaCache(balance);
			}
		}

		private static void RefreshLoadedObjects(BalanceBaseObject definition)
		{
			if (!(definition is WGODef) || !TimbnGame.IsInGame)
			{
				return;
			}
			foreach (WgoData item in TimbnWorld.Objects((WgoData wgo) => ((ObjectLinkedToDefinition<WGODef>)(object)wgo).id == definition.id).ToList())
			{
				_worldObjectCachedId.Invoke((ObjectLinkedToDefinition<WGODef>)(object)item) = "";
				CraftComponent craftComponent = item.CraftComponent;
				if (craftComponent != null)
				{
					craftComponent.Init((ICraftable)(object)item);
				}
			}
		}
	}
	public sealed class TimbnPluginBalance
	{
		private readonly TimbnFrameworkPlugin _owner;

		internal TimbnPluginBalance(TimbnFrameworkPlugin owner)
		{
			_owner = owner;
		}

		public IDisposable Add(BalanceBaseObject definition)
		{
			return _owner.Subscriptions.Add(TimbnBalance.Add(definition));
		}

		public IDisposable Add(BalanceBaseObject definition, Action<GameBalance>? prepare)
		{
			return _owner.Subscriptions.Add(TimbnBalance.Add(definition, prepare));
		}

		public IDisposable AddCopy<T>(string templateId, string id, Action<T>? edit = null) where T : BalanceBaseObject, new()
		{
			return _owner.Subscriptions.Add(TimbnBalance.AddCopy(templateId, id, edit));
		}

		public IDisposable AddItem(string templateItemId, string id, string name, string description, string iconId = "", Action<ItemDef>? edit = null)
		{
			return _owner.Subscriptions.Add(TimbnBalance.AddItem(templateItemId, id, name, description, iconId, edit));
		}

		public IDisposable Edit<T>(string id, Action<T> apply, Action<T> revert) where T : BalanceBaseObject
		{
			return _owner.Subscriptions.Add(TimbnBalance.Edit(id, apply, revert, _owner.PluginLogger));
		}
	}
	public static class TimbnClock
	{
		private static readonly (TimbnWeekday Day, string Id)[] _weekdayIds = new(TimbnWeekday, string)[6]
		{
			(TimbnWeekday.Gluttony, "day_gluttony"),
			(TimbnWeekday.Sloth, "day_sloth"),
			(TimbnWeekday.Lust, "day_lust"),
			(TimbnWeekday.Envy, "day_envy"),
			(TimbnWeekday.Pride, "day_pride"),
			(TimbnWeekday.Wrath, "day_wrath")
		};

		private static EnvironmentData? Data
		{
			get
			{
				if (!TimbnGame.IsInGame)
				{
					return null;
				}
				return MainGame.Instance.GameSave?.environmentData;
			}
		}

		public static int Day
		{
			get
			{
				EnvironmentData? data = Data;
				if (data == null)
				{
					return 0;
				}
				return data.Day;
			}
		}

		public static int WeekdayNumber
		{
			get
			{
				EnvironmentData? data = Data;
				if (data == null)
				{
					return 0;
				}
				return data.CurrentDayNumber;
			}
		}

		public static TimbnWeekday? Weekday
		{
			get
			{
				EnvironmentData data = Data;
				if (data == null)
				{
					return null;
				}
				(TimbnWeekday, string)[] weekdayIds = _weekdayIds;
				for (int i = 0; i < weekdayIds.Length; i++)
				{
					(TimbnWeekday, string) tuple = weekdayIds[i];
					TimbnWeekday item = tuple.Item1;
					ConstDef obj = ConstDef.Get(tuple.Item2);
					if (((obj != null) ? new int?(obj.IntValue) : ((int?)null)) == data.CurrentDayNumber)
					{
						return item;
					}
				}
				return null;
			}
		}

		public static float TimeOfDay
		{
			get
			{
				EnvironmentData? data = Data;
				if (data == null)
				{
					return 0f;
				}
				return data.TimeOfDay;
			}
		}

		public static double Minutes => TimbnDayPlan.Minutes(Day, TimeOfDay);

		public static string TimeText
		{
			get
			{
				int num = Mathf.RoundToInt(TimeOfDay * 24f * 60f) % 1440;
				return string.Format(CultureInfo.InvariantCulture, "{0:00}:{1:00}", num / 60, num % 60);
			}
		}

		public static bool IsPaused
		{
			get
			{
				if (TimbnGame.IsInGame && (Object)(object)EnvironmentEngine.Instance != (Object)null)
				{
					return EnvironmentEngine.Instance.IsPaused;
				}
				return false;
			}
		}

		public static float DayFractionBetween(float from, float to)
		{
			return Mathf.Repeat(to - from, 1f);
		}

		public static bool SetTime(float timeOfDay)
		{
			if (!TimbnGame.IsInGame || (Object)(object)EnvironmentEngine.Instance == (Object)null)
			{
				return false;
			}
			EnvironmentEngine.Instance.SetTimeOfDay(Mathf.Repeat(timeOfDay, 1f));
			return true;
		}

		internal static string WeekdayId(TimbnWeekday day)
		{
			return _weekdayIds.First(((TimbnWeekday Day, string Id) pair) => pair.Day == day).Id;
		}
	}
	internal static class TimbnClockPause
	{
		private static readonly TimbnHolds<bool> _holds = new TimbnHolds<bool>(delegate
		{
			Apply();
		}, Restore);

		private static EnvironmentEngine? _engine;

		private static bool _wasPaused;

		private static bool _applying;

		private static bool _gamePausedMeanwhile;

		internal static IDisposable Take()
		{
			EnvironmentEngine val = (TimbnGame.IsInGame ? EnvironmentEngine.Instance : null);
			if ((Object)(object)val == (Object)null)
			{
				return TimbnUndo.None;
			}
			if ((Object)(object)_engine != (Object)(object)val)
			{
				_holds.ReleaseAll();
				_wasPaused = val.IsPaused;
				_gamePausedMeanwhile = false;
			}
			_engine = val;
			return _holds.Take(value: true);
		}

		internal static void ReleaseAll()
		{
			_holds.ReleaseAll();
		}

		internal static void OnGameSet(bool paused)
		{
			if ((Object)(object)_engine != (Object)null && !_applying)
			{
				_gamePausedMeanwhile = paused;
			}
		}

		private static void Apply()
		{
			if (!((Object)(object)_engine == (Object)null))
			{
				_applying = true;
				_engine.IsPaused = true;
				_applying = false;
			}
		}

		private static void Restore()
		{
			EnvironmentEngine engine = _engine;
			bool gamePausedMeanwhile = _gamePausedMeanwhile;
			_engine = null;
			_gamePausedMeanwhile = false;
			if ((Object)(object)engine != (Object)null && engine.IsPaused && !gamePausedMeanwhile)
			{
				engine.IsPaused = _wasPaused;
			}
		}
	}
	internal static class TimbnGameSpeed
	{
		private static readonly TimbnHolds<float> _holds = new TimbnHolds<float>(Apply, Restore);

		private static UpdateManager? _manager;

		private static float _gameSpeed = 1f;

		private static float _appliedSpeed = 1f;

		internal static IDisposable Set(float multiplier)
		{
			UpdateManager val = (((Object)(object)MainGame.Instance != (Object)null) ? MainGame.UpdateManager : null);
			if ((Object)(object)val == (Object)null)
			{
				return TimbnUndo.None;
			}
			if ((Object)(object)_manager != (Object)(object)val)
			{
				_holds.ReleaseAll();
				_gameSpeed = val.TimeMultiplier;
			}
			_manager = val;
			return _holds.Take(multiplier);
		}

		internal static void ReleaseAll()
		{
			_holds.ReleaseAll();
		}

		private static void Apply(float multiplier)
		{
			if (!((Object)(object)_manager == (Object)null))
			{
				_manager.SetTimeSpeedMultiplier(multiplier);
				_appliedSpeed = multiplier;
			}
		}

		private static void Restore()
		{
			UpdateManager manager = _manager;
			_manager = null;
			if ((Object)(object)manager != (Object)null && Mathf.Approximately(manager.TimeMultiplier, _appliedSpeed))
			{
				manager.SetTimeSpeedMultiplier(_gameSpeed);
			}
		}
	}
	public sealed class TimbnPluginClock
	{
		private readonly TimbnFrameworkPlugin _owner;

		internal TimbnPluginClock(TimbnFrameworkPlugin owner)
		{
			_owner = owner;
		}

		public IDisposable MultiplyGameSpeed(float multiplier)
		{
			return _owner.SessionSubscriptions.Add(TimbnGameSpeed.Set(multiplier));
		}

		public IDisposable Freeze()
		{
			return _owner.SessionSubscriptions.Add(TimbnClockPause.Take());
		}
	}
	internal sealed class TimbnCraftChecks<TStation>
	{
		private readonly Dictionary<string, List<Func<TStation, bool>>> _checks = new Dictionary<string, List<Func<TStation, bool>>>();

		private readonly HashSet<Func<TStation, bool>> _reported = new HashSet<Func<TStation, bool>>();

		internal bool IsEmpty => _checks.Count == 0;

		internal IDisposable Add(string craftId, Func<TStation, bool> check)
		{
			if (!_checks.TryGetValue(craftId, out List<Func<TStation, bool>> list))
			{
				list = new List<Func<TStation, bool>>();
				_checks[craftId] = list;
			}
			list.Add(check);
			return new TimbnUndo(delegate
			{
				list.Remove(check);
				_reported.Remove(check);
				if (list.Count == 0)
				{
					_checks.Remove(craftId);
				}
			});
		}

		internal bool Allows(string craftId, TStation station, Action<Func<TStation, bool>, Exception> report)
		{
			if (!_checks.TryGetValue(craftId, out List<Func<TStation, bool>> value))
			{
				return true;
			}
			foreach (Func<TStation, bool> item in value.ToList())
			{
				try
				{
					if (!item(station))
					{
						return false;
					}
				}
				catch (Exception arg)
				{
					if (_reported.Add(item))
					{
						report(item, arg);
					}
				}
			}
			return true;
		}
	}
	internal static class TimbnCraftRequirements
	{
		private static readonly TimbnCraftChecks<WgoData> _checks = new TimbnCraftChecks<WgoData>();

		internal static IDisposable Add(string craftId, Func<WgoData, bool> check)
		{
			return _checks.Add(craftId, check);
		}

		internal static bool Allows(string craftId, WgoData station)
		{
			if (!_checks.IsEmpty)
			{
				return _checks.Allows(craftId, station, delegate(Func<WgoData, bool> check, Exception exception)
				{
					TimbnFrameworkPlugin<TimbnCorePlugin>.Logger.LogError((object)string.Format("{0}|The check {1} for craft {2} threw, so the craft is allowed. It is only reported once. {3}", "TimbnCraftRequirements", TimbnSafe.Describe(check), craftId, exception));
				});
			}
			return true;
		}
	}
	internal sealed class TimbnCraftEventRouter<TEvent>
	{
		private readonly Dictionary<string, List<Action<TEvent>>> _handlers = new Dictionary<string, List<Action<TEvent>>>();

		internal bool IsEmpty => _handlers.Count == 0;

		internal IDisposable Add(string craftId, Action<TEvent> handler)
		{
			if (!_handlers.TryGetValue(craftId, out List<Action<TEvent>> list))
			{
				list = new List<Action<TEvent>>();
				_handlers[craftId] = list;
			}
			list.Add(handler);
			return new TimbnUndo(delegate
			{
				list.Remove(handler);
				if (list.Count == 0)
				{
					_handlers.Remove(craftId);
				}
			});
		}

		internal IReadOnlyList<Action<TEvent>> HandlersFor(string craftId)
		{
			if (!_handlers.TryGetValue(craftId, out List<Action<TEvent>> value))
			{
				return Array.Empty<Action<TEvent>>();
			}
			return new <>z__ReadOnlyArray<Action<TEvent>>(value.ToArray());
		}
	}
	internal static class TimbnCraftEvents
	{
		private static readonly TimbnCraftEventRouter<TimbnCraftEvent> _started = new TimbnCraftEventRouter<TimbnCraftEvent>();

		private static readonly TimbnCraftEventRouter<TimbnCraftEvent> _finished = new TimbnCraftEventRouter<TimbnCraftEvent>();

		internal static IDisposable OnStarted(string craftId, Action<TimbnCraftEvent> handler)
		{
			return _started.Add(craftId, handler);
		}

		internal static IDisposable OnFinished(string craftId, Action<TimbnCraftEvent> handler)
		{
			return _finished.Add(craftId, handler);
		}

		internal static void Started(WgoData station, CraftElementBase craft)
		{
			Raise(_started, station, craft, "started");
		}

		internal static void Finished(WgoData station, CraftElementBase craft)
		{
			Raise(_finished, station, craft, "finished");
		}

		private static void Raise(TimbnCraftEventRouter<TimbnCraftEvent> router, WgoData station, CraftElementBase craft, string what)
		{
			if (router.IsEmpty)
			{
				return;
			}
			IReadOnlyList<Action<TimbnCraftEvent>> readOnlyList = router.HandlersFor(craft.CraftId);
			if (readOnlyList.Count == 0)
			{
				return;
			}
			TimbnCraftEvent craftEvent = new TimbnCraftEvent(station, craft.CraftId);
			foreach (Action<TimbnCraftEvent> handler in readOnlyList)
			{
				TimbnSafe.Run(delegate
				{
					handler(craftEvent);
				}, TimbnFrameworkPlugin<TimbnCorePlugin>.Logger, "TimbnCraftEvents|A handler for craft " + craft.CraftId + " " + what);
			}
		}
	}
	internal static class TimbnCraftRules
	{
		internal const string DefaultTemplate = "wooden_plank";

		internal static bool IsAuto(bool? stationRunsItself, bool templateIsAuto)
		{
			return stationRunsItself ?? templateIsAuto;
		}

		internal static Dictionary<string, string> Texts(string id, string name, string description)
		{
			return TimbnStationRules.Texts((id, name), (TimbnStationRules.DescriptionKey(id), description));
		}
	}
	internal static class TimbnCrafts
	{
		private static readonly FieldRef<CraftDef, string> _description = AccessTools.FieldRefAccess<CraftDef, string>("description");

		internal static IDisposable Add(TimbnCraftBuilder craft)
		{
			List<IDisposable> list = new List<IDisposable>();
			Dictionary<string, string> dictionary = TimbnCraftRules.Texts(craft.Id, craft.Name, craft.Description);
			if (dictionary.Count > 0)
			{
				list.Add(TimbnLocale.Add(dictionary));
			}
			foreach (Action<TimbnCraftEvent> startedHandler in craft.StartedHandlers)
			{
				list.Add(TimbnCraftEvents.OnStarted(craft.Id, startedHandler));
			}
			foreach (Action<TimbnCraftEvent> finishedHandler in craft.FinishedHandlers)
			{
				list.Add(TimbnCraftEvents.OnFinished(craft.Id, finishedHandler));
			}
			foreach (Func<WgoData, bool> check in craft.Checks)
			{
				list.Add(TimbnCraftRequirements.Add(craft.Id, check));
			}
			list.Add(TimbnBalance.AddCopy<CraftDef>((Func<GameBalance, string>)((GameBalance _) => craft.TemplateId), craft.Id, (Action<GameBalance, CraftDef>?)delegate(GameBalance balance, CraftDef def)
			{
				Fill(balance, craft, def);
			}, (Func<GameBalance, bool>?)null));
			string techId = craft.TechId;
			if (techId != null)
			{
				list.Add(TimbnTechGrants.Craft(techId, craft.Id));
			}
			return TimbnUndo.All(list);
		}

		private static void Fill(GameBalance balance, TimbnCraftBuilder craft, CraftDef def)
		{
			_description.Invoke(def) = TimbnStationRules.DescriptionKey(craft.Id);
			List<string> stationIds = craft.StationIds;
			if (stationIds != null)
			{
				((CraftDefBase)def).craftsIn = stationIds.ToList();
			}
			List<(string, string)> needItems = craft.NeedItems;
			if (needItems != null)
			{
				((CraftDefBase)def).needItems = needItems.Select<(string, string), NeedItemData>(((string Item, string Count) need) => new NeedItemData(need.Item, TimbnExpression.Formula(need.Count))).ToList();
			}
			List<(string, string)> outputs = craft.Outputs;
			if (outputs != null)
			{
				((CraftDefBase)def).outputItems.chanceOutputItems = outputs.Select<(string, string), ChanceOutputItem>(((string Item, string Count) output) => new ChanceOutputItem
				{
					id = output.Item,
					count = TimbnExpression.Formula(output.Count)
				}).ToList();
				((CraftDefBase)def).outputItems.groupChanceOutputItems.Clear();
			}
			def.isNeedsUnlock = craft.MustBeUnlocked;
			int? masteryLevel = craft.MasteryLevel;
			if (masteryLevel.HasValue)
			{
				int valueOrDefault = masteryLevel.GetValueOrDefault();
				((CraftDefBase)def).talentLock = valueOrDefault;
			}
			string extensionId = craft.ExtensionId;
			if (extensionId != null)
			{
				((CraftDefBase)def).extensionNeedId = extensionId;
			}
			string iconId = craft.IconId;
			if (iconId != null)
			{
				def.iconId = iconId;
				def.customCraftResultIcon = TimbnExpression.PureText(iconId);
			}
			masteryLevel = craft.WorkTicks;
			if (masteryLevel.HasValue)
			{
				int valueOrDefault2 = masteryLevel.GetValueOrDefault();
				((CraftDefBase)def).duration = TimbnExpression.Number(valueOrDefault2);
			}
			masteryLevel = craft.EnergyEachTick;
			if (masteryLevel.HasValue)
			{
				int valueOrDefault3 = masteryLevel.GetValueOrDefault();
				((CraftDefBase)def).energyPerTick = TimbnExpression.Number(valueOrDefault3);
			}
			if (craft.FinishesItself)
			{
				((CraftDefBase)def).autoFinishAutoCraft = true;
			}
			if (craft.IsHidden)
			{
				((CraftDefBase)def).isHidden = true;
			}
			(int Red, int Green, int Blue) obj = craft.Points ?? (0, 0, 0);
			int item = obj.Red;
			int item2 = obj.Green;
			int item3 = obj.Blue;
			def.techRed = TimbnExpression.Number(item);
			def.techGreen = TimbnExpression.Number(item2);
			def.techBlue = TimbnExpression.Number(item3);
			((CraftDefBase)def).linkedPerks = new List<string>();
			def.onCraftEndExpressions = new List<LazyExpression>();
			((CraftDefBase)def).isAuto = TimbnCraftRules.IsAuto(StationRunsItself(balance, ((CraftDefBase)def).craftsIn), ((CraftDefBase)def).isAuto);
			craft.EditCraft?.Invoke(def);
		}

		private static bool? StationRunsItself(GameBalance balance, List<string> stationIds)
		{
			foreach (string stationId in stationIds)
			{
				WGODef dataOrNull = ((GameBalanceBase)balance).GetDataOrNull<WGODef>(stationId);
				if (dataOrNull != null)
				{
					return dataOrNull.isAutoCrafter;
				}
			}
			return null;
		}
	}
	public sealed class TimbnCraftBuilder
	{
		internal string Id { get; }

		internal string Name { get; }

		internal string Description { get; }

		internal string TemplateId { get; private set; } = "wooden_plank";

		internal List<string>? StationIds { get; private set; }

		internal List<(string Item, string Count)>? NeedItems { get; private set; }

		internal List<(string Item, string Count)>? Outputs { get; private set; }

		internal bool MustBeUnlocked { get; private set; }

		internal string? TechId { get; private set; }

		internal int? MasteryLevel { get; private set; }

		internal string? ExtensionId { get; private set; }

		internal string? IconId { get; private set; }

		internal int? WorkTicks { get; private set; }

		internal int? EnergyEachTick { get; private set; }

		internal bool FinishesItself { get; private set; }

		internal bool IsHidden { get; private set; }

		internal (int Red, int Green, int Blue)? Points { get; private set; }

		internal Action<CraftDef>? EditCraft { get; private set; }

		internal List<Action<TimbnCraftEvent>> StartedHandlers { get; } = new List<Action<TimbnCraftEvent>>();

		internal List<Action<TimbnCraftEvent>> FinishedHandlers { get; } = new List<Action<TimbnCraftEvent>>();

		internal List<Func<WgoData, bool>> Checks { get; } = new List<Func<WgoData, bool>>();

		internal TimbnCraftBuilder(string id, string name, string description)
		{
			Id = id;
			Name = name;
			Description = description;
		}

		public TimbnCraftBuilder In(string stationId)
		{
			if (StationIds == null)
			{
				List<string> list = (StationIds = new List<string>());
			}
			StationIds.Add(stationId);
			return this;
		}

		public TimbnCraftBuilder In(TimbnStation station)
		{
			return In(station.Id);
		}

		public TimbnCraftBuilder BasedOn(string craftId)
		{
			TemplateId = craftId;
			return this;
		}

		public TimbnCraftBuilder Needs(string itemId, int count = 1)
		{
			return Needs(itemId, count.ToString());
		}

		public TimbnCraftBuilder Needs(string itemId, string count)
		{
			if (NeedItems == null)
			{
				List<(string, string)> list = (NeedItems = new List<(string, string)>());
			}
			NeedItems.Add((itemId, Checked(count)));
			return this;
		}

		public TimbnCraftBuilder Needs(params (string Item, int Count)[] items)
		{
			for (int i = 0; i < items.Length; i++)
			{
				var (itemId, count) = items[i];
				Needs(itemId, count);
			}
			return this;
		}

		public TimbnCraftBuilder Makes(string itemId, int count = 1)
		{
			return Makes(itemId, count.ToString());
		}

		public TimbnCraftBuilder Makes(string itemId, string count)
		{
			if (Outputs == null)
			{
				List<(string, string)> list = (Outputs = new List<(string, string)>());
			}
			Outputs.Add((itemId, Checked(count)));
			return this;
		}

		public TimbnCraftBuilder NeedsUnlock()
		{
			MustBeUnlocked = true;
			return this;
		}

		public TimbnCraftBuilder UnlockedBy(string techId)
		{
			TechId = techId;
			MustBeUnlocked = true;
			return this;
		}

		public TimbnCraftBuilder Mastery(int level)
		{
			MasteryLevel = level;
			return this;
		}

		public TimbnCraftBuilder NeedsExtension(string extensionId)
		{
			ExtensionId = extensionId;
			return this;
		}

		public TimbnCraftBuilder Icon(string spriteId)
		{
			IconId = spriteId;
			return this;
		}

		public TimbnCraftBuilder DurationTicks(int ticks)
		{
			WorkTicks = ticks;
			return this;
		}

		public TimbnCraftBuilder EnergyPerTick(int energy)
		{
			EnergyEachTick = energy;
			return this;
		}

		public TimbnCraftBuilder AutoFinish()
		{
			FinishesItself = true;
			return this;
		}

		public TimbnCraftBuilder Hidden()
		{
			IsHidden = true;
			return this;
		}

		public TimbnCraftBuilder TechPoints(int red, int green, int blue)
		{
			Points = (red, green, blue);
			return this;
		}

		public TimbnCraftBuilder OnStarted(Action<TimbnCraftEvent> handler)
		{
			StartedHandlers.Add(handler);
			return this;
		}

		public TimbnCraftBuilder OnFinished(Action<TimbnCraftEvent> handler)
		{
			FinishedHandlers.Add(handler);
			return this;
		}

		public TimbnCraftBuilder Requires(Func<WgoData, bool> check)
		{
			Checks.Add(check ?? throw new ArgumentNullException("check"));
			return this;
		}

		public TimbnCraftBuilder Edit(Action<CraftDef> edit)
		{
			EditCraft = edit;
			return this;
		}

		private static string Checked(string count)
		{
			new TimbnExpression(count);
			return count;
		}
	}
	public sealed class TimbnCraftEvent
	{
		public WgoData Station { get; }

		public string CraftId { get; }

		internal TimbnCraftEvent(WgoData station, string craftId)
		{
			Station = station;
			CraftId = craftId;
		}
	}
	public sealed class TimbnPluginCrafts
	{
		private readonly TimbnFrameworkPlugin _owner;

		internal TimbnPluginCrafts(TimbnFrameworkPlugin owner)
		{
			_owner = owner;
		}

		public IDisposable Add(string id, string name, string description, Action<TimbnCraftBuilder> craft)
		{
			if (string.IsNullOrEmpty(id))
			{
				throw new ArgumentException("A craft needs an id.", "id");
			}
			TimbnCraftBuilder timbnCraftBuilder = new TimbnCraftBuilder(id, name, description);
			craft(timbnCraftBuilder);
			return _owner.Subscriptions.Add(TimbnCrafts.Add(timbnCraftBuilder));
		}

		public IDisposable Add(string id, Action<TimbnCraftBuilder> craft)
		{
			return Add(id, "", "", craft);
		}

		public bool Start(WgoData station, string craftId)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Expected O, but got Unknown
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			if (GameBalance.GetCraftDef(craftId) == null)
			{
				return false;
			}
			station.CraftComponent.AddToQueue((CraftElementBase)new CraftElement(craftId, 1, new CraftParamsData(craftId, station, (CraftParamsType)0, -1)), false, -1);
			return true;
		}

		public void Finish(WgoData station)
		{
			station.CraftComponent.TryFinishCurCraft();
		}
	}
	internal sealed class TimbnAnswer
	{
		private readonly AnswerData _data = new AnswerData();

		private bool _hasExtras;

		internal string Key { get; }

		internal string Id { get; }

		internal TimbnAnswer(string key, string? id = null)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000b: Expected O, but got Unknown
			Key = key;
			Id = id ?? key;
		}

		internal TimbnAnswer Costs(string itemId, int count = 1)
		{
			return Extra(delegate
			{
				_data.AddCostRes(Items(itemId, count));
			});
		}

		internal TimbnAnswer CostsResource(string resourceId, float amount)
		{
			return Extra(delegate
			{
				_data.AddCostRes(Resource(resourceId, amount));
			});
		}

		internal TimbnAnswer Requires(string itemId, int count = 1)
		{
			return Extra(delegate
			{
				_data.AddLockRes(Items(itemId, count));
			});
		}

		internal TimbnAnswer RequiresResource(string resourceId, float amount)
		{
			return Extra(delegate
			{
				_data.AddLockRes(Resource(resourceId, amount));
			});
		}

		internal TimbnAnswer RequiresDay(TimbnWeekday day)
		{
			return Extra(delegate
			{
				_data.AddDay(TimbnClock.WeekdayId(day));
			});
		}

		internal TimbnAnswer RequiresOrder(string orderId)
		{
			return Extra(delegate
			{
				_data.AddOrder(orderId);
			});
		}

		internal TimbnAnswer Rewards(string itemId, int count = 1)
		{
			return Extra(delegate
			{
				_data.AddRewardRes(Items(itemId, count));
			});
		}

		internal TimbnAnswer RewardsResource(string resourceId, float amount)
		{
			return Extra(delegate
			{
				_data.AddRewardRes(Resource(resourceId, amount));
			});
		}

		internal TimbnAnswer ShowsReward(string itemId, int count = 1)
		{
			return Extra(delegate
			{
				AddShown(Items(itemId, count));
			});
		}

		internal TimbnAnswer ShowsRewardResource(string resourceId, float amount)
		{
			return Extra(delegate
			{
				AddShown(Resource(resourceId, amount));
			});
		}

		internal AnswerData? ToData()
		{
			if (!_hasExtras)
			{
				return null;
			}
			return _data;
		}

		private TimbnAnswer Extra(Action add)
		{
			add();
			_hasExtras = true;
			return this;
		}

		private void AddShown(SmartRes reward)
		{
			if (_data.fakeRewardRes == null)
			{
				_data.fakeRewardRes = reward;
				return;
			}
			_data.fakeRewardRes.items.AddRange(reward.items);
			_data.fakeRewardRes.gameRes.Add(reward.gameRes);
		}

		private static SmartRes Items(string itemId, int count)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0025: Expected O, but got Unknown
			//IL_002b: Expected O, but got Unknown
			return new SmartRes
			{
				items = new List<ItemCount>(1)
				{
					new ItemCount
					{
						itemId = itemId,
						count = count
					}
				}
			};
		}

		private static SmartRes Resource(string resourceId, float amount)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			//IL_0013: Expected O, but got Unknown
			return new SmartRes
			{
				gameRes = new GameRes(resourceId, amount)
			};
		}
	}
	internal static class TimbnAnswerColors
	{
		private static readonly Dictionary<string, Color> _colors = new Dictionary<string, Color>();

		private static readonly FieldRef<UIMultiAnswerOption, AnswerVisualData> _visualData = AccessTools.FieldRefAccess<UIMultiAnswerOption, AnswerVisualData>("visualData");

		private static readonly FieldRef<UIMultiAnswerOption, Image> _button = AccessTools.FieldRefAccess<UIMultiAnswerOption, Image>("optionButtonImage");

		private static readonly FieldRef<UIMultiAnswerOption, Color> _original = AccessTools.FieldRefAccess<UIMultiAnswerOption, Color>("originalColor");

		private static readonly FieldRef<UIMultiAnswerOption, Color> _highlighted = AccessTools.FieldRefAccess<UIMultiAnswerOption, Color>("highlightedColor");

		private static readonly FieldRef<UIMultiAnswerOption, RectTransform> _leftArrow = AccessTools.FieldRefAccess<UIMultiAnswerOption, RectTransform>("leftArrow");

		private static readonly FieldRef<UIMultiAnswerOption, RectTransform> _rightArrow = AccessTools.FieldRefAccess<UIMultiAnswerOption, RectTransform>("rightArrow");

		private static readonly FieldRef<UIMultiAnswerOption, List<UIBubbleCorner>> _corners = AccessTools.FieldRefAccess<UIMultiAnswerOption, List<UIBubbleCorner>>("corners");

		internal static IDisposable Add(string answerId, Color color)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			_colors[answerId] = color;
			return new TimbnUndo(delegate
			{
				_colors.Remove(answerId);
			});
		}

		internal static void Paint(UIMultiAnswerOption option)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			if (!TryGet(option, out var color))
			{
				return;
			}
			((Graphic)_button.Invoke(option)).color = color;
			RectTransform[] array = (RectTransform[])(object)new RectTransform[2]
			{
				_leftArrow.Invoke(option),
				_rightArrow.Invoke(option)
			};
			Image val2 = default(Image);
			foreach (RectTransform val in array)
			{
				if ((Object)(object)val != (Object)null && ((Component)val).TryGetComponent<Image>(ref val2))
				{
					((Graphic)val2).color = color;
				}
			}
			foreach (UIBubbleCorner item in _corners.Invoke(option))
			{
				if ((Object)(object)item != (Object)null && (Object)(object)item.customImage != (Object)null)
				{
					((Graphic)item.customImage).color = color;
				}
			}
		}

		internal static Color Recolor(UIMultiAnswerOption option, Color color)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			if (!TryGet(option, out var color2))
			{
				return color;
			}
			if (!(color == _highlighted.Invoke(option)))
			{
				return color2;
			}
			return Hover(color2, _original.Invoke(option), _highlighted.Invoke(option));
		}

		private static bool TryGet(UIMultiAnswerOption option, out Color color)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			color = default(Color);
			string text = _visualData.Invoke(option)?.id;
			if (text != null)
			{
				return _colors.TryGetValue(text, out color);
			}
			return false;
		}

		private static Color Hover(Color own, Color original, Color highlighted)
		{
			//IL_0000: 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_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: 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_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: 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_004b: Unknown result type (might be due to invalid IL or missing references)
			return new Color(Scale(own.r, original.r, highlighted.r), Scale(own.g, original.g, highlighted.g), Scale(own.b, original.b, highlighted.b), own.a);
		}

		private static float Scale(float own, float original, float highlighted)
		{
			if (!(original > 0f))
			{
				return Mathf.Clamp01(own + highlighted);
			}
			return Mathf.Clamp01(own * highlighted / original);
		}
	}
	internal sealed class TimbnConversation
	{
		private readonly List<Action<Action, Action>> _steps = new List<Action<Action, Action>>();

		private readonly string _talkId;

		private readonly TimbnConversation _root;

		private Dictionary<string, TimbnConversation>? _branches;

		private List<Action>? _ended;

		internal WgoData Npc { get; }

		internal bool TurnedOnBars { get; private set; }

		internal bool OpensMenu { get; private set; }

		internal TimbnConversation(WgoData npc, string talkId)
		{
			Npc = npc;
			_talkId = talkId;
			_root = this;
		}

		private TimbnConversation(TimbnConversation parent)
		{
			Npc = parent.Npc;
			_talkId = parent._talkId;
			_root = parent._root;
		}

		internal void ThenOpenMenu()
		{
			_root.OpensMenu = true;
		}

		internal void OnEnded(Action action)
		{
			TimbnConversation root = _root;
			(root._ended ?? (root._ended = new List<Action>())).Add(action);
		}

		internal void RunEnded()
		{
			if (_ended == null)
			{
				return;
			}
			foreach (Action item in _ended)
			{
				TimbnSafe.Run(item, "TimbnConversation|The end of talk '" + _talkId + "'");
			}
		}

		internal TimbnConversation Say(string key, object[] values)
		{
			return Add(delegate(Action next, Action end)
			{
				if (!TimbnDialog.Say(Npc, key, values, next))
				{
					end();
				}
			});
		}

		internal TimbnConversation SayAs(string npcId, string key)
		{
			return Add(delegate(Action next, Action end)
			{
				WgoData val = TimbnNpcs.FindData(npcId);
				if (val == null)
				{
					TimbnFrameworkPlugin<TimbnCorePlugin>.Logger.LogWarning((object)("TimbnConversation|Talk '" + _talkId + "' skipped the line '" + key + "', since " + npcId + " is not in the world."));
					next();
				}
				else if (!TimbnDialog.Say(val, key, Array.Empty<object>(), next))
				{
					end();
				}
			});
		}

		internal TimbnConversation PlayerSay(string key, object[] values)
		{
			return Add(delegate(Action next, Action end)
			{
				if (!TimbnDialog.PlayerSay(key, values, next))
				{
					end();
				}
			});
		}

		internal TimbnConversation Wait(float seconds)
		{
			return Add(delegate(Action next, Action end)
			{
				if (!TimbnDialog.Wait(seconds, next))
				{
					end();
				}
			});
		}

		internal TimbnConversation Cinematic()
		{
			return Add(delegate(Action next, Action end)
			{
				if (_root.TurnedOnBars || !TimbnStoryScene.TryShowBars(next))
				{
					next();
				}
				else
				{
					_root.TurnedOnBars = true;
				}
			});
		}

		internal TimbnConversation Do(Action action)
		{
			return Add(delegate(Action next, Action end)
			{
				if (TimbnSafe.Run(action, "TimbnConversation|A step in talk '" + _talkId + "'"))
				{
					next();
				}
				else
				{
					end();
				}
			});
		}

		internal TimbnConversation Give(string itemId, int count)
		{
			return Do(delegate
			{
				//IL_000c: Unknown result type (might be due