Decompiled source of Pocket Vehicles v0.3.0

plugins/PocketVehicles.dll

Decompiled a week ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using AzNean.SotfCommon;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Core.Logging.Interpolation;
using BepInEx.Logging;
using BepInEx.Unity.IL2CPP;
using Endnight.Rendering;
using HarmonyLib;
using Il2CppInterop.Runtime.InteropTypes;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Microsoft.CodeAnalysis;
using PocketVehicles.Logic;
using Sons.Cutscenes;
using Sons.Gameplay;
using Sons.Inventory;
using Sons.Items.Core;
using TheForest.Items.Inventory;
using TheForest.Utils;
using UnityEngine;
using UnityEngine.AddressableAssets;
using UnityEngine.Localization;
using UnityEngine.Localization.Settings;
using UnityEngine.Localization.Tables;
using UnityEngine.SceneManagement;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("PocketVehicles")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.3.0.0")]
[assembly: AssemblyInformationalVersion("0.3.0+f0d300f64abb79f2a892f14426e3479b5b5147d2")]
[assembly: AssemblyProduct("PocketVehicles")]
[assembly: AssemblyTitle("PocketVehicles")]
[assembly: AssemblyVersion("0.3.0.0")]
[module: RefSafetyRules(11)]
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 AzNean.SotfCommon
{
	internal static class ModLog
	{
		private static ManualLogSource _log;

		private static ConfigEntry<bool> _full;

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

		private static readonly Dictionary<(int, string), int> _state = new Dictionary<(int, string), int>();

		internal static bool Full => _full.Value;

		internal static void Init(ManualLogSource log, ConfigEntry<bool> full)
		{
			_log = log;
			_full = full;
		}

		internal static void Trace(string message)
		{
			if (_full.Value)
			{
				_log.LogInfo((object)message);
			}
		}

		internal static bool Changed(int id, string what, int state)
		{
			if (!_full.Value || (_state.TryGetValue((id, what), out var value) && value == state))
			{
				return false;
			}
			_state[(id, what)] = state;
			return true;
		}

		internal static void Once(string key, string message, LogLevel level = (LogLevel)16)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if (_once.Add(key))
			{
				_log.Log(level, (object)message);
			}
		}
	}
}
namespace PocketVehicles
{
	internal static class Patches
	{
		[HarmonyPatch(typeof(PickUp), "MainEffect")]
		private static class Pickup
		{
			private static void Prefix(PickUp __instance)
			{
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				//IL_001e: Expected O, but got Unknown
				try
				{
					Vehicles.PickingUp(__instance._itemId);
				}
				catch (Exception ex)
				{
					ManualLogSource logger = Plugin.Logger;
					bool flag = default(bool);
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(49, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Pickup check failed (the game's pickup goes on): ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
					}
					logger.LogError(val);
				}
			}
		}

		[HarmonyPatch(typeof(PlayerInventory), "TryEquip", new Type[]
		{
			typeof(int),
			typeof(bool),
			typeof(bool),
			typeof(bool)
		})]
		private static class SkipEquip
		{
			private static bool Prefix(int __0, ref bool __result)
			{
				if (!Vehicles.IntoBackpack(__0))
				{
					return true;
				}
				ModLog.Trace($"Item {__0} stays in the backpack: taking it in hand skipped (PickUpInto = Backpack).");
				__result = false;
				return false;
			}
		}

		[HarmonyPatch(typeof(PlayerInventory), "AddItem")]
		private static class Add
		{
			private static void Postfix(PlayerInventory __instance, int __0, bool __result)
			{
				//IL_0025: Unknown result type (might be due to invalid IL or missing references)
				//IL_002b: Expected O, but got Unknown
				if (!__result)
				{
					return;
				}
				try
				{
					Vehicles.Added(__instance, __0, Time.frameCount == _loadingFrame);
				}
				catch (Exception ex)
				{
					ManualLogSource logger = Plugin.Logger;
					bool flag = default(bool);
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(31, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Stored-vehicle message failed: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
					}
					logger.LogError(val);
				}
			}
		}

		[HarmonyPatch(typeof(PlayerInventory), "Sons_Save_ISaveGameSerializer_TheForest_Items_Inventory_PlayerInventory_PlayerInventorySaveData__OnDeserialize")]
		private static class Load
		{
			private static void Prefix()
			{
				//IL_001d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0023: Expected O, but got Unknown
				_loadingFrame = Time.frameCount;
				try
				{
					Vehicles.Apply(keepStored: true);
				}
				catch (Exception ex)
				{
					ManualLogSource logger = Plugin.Logger;
					bool flag = default(bool);
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(39, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Vehicle cards not set before the load: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
					}
					logger.LogError(val);
				}
			}

			private static void Postfix(PlayerInventory __instance)
			{
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				//IL_001c: Expected O, but got Unknown
				//IL_0073: Unknown result type (might be due to invalid IL or missing references)
				//IL_007a: Expected O, but got Unknown
				bool flag = default(bool);
				try
				{
					Vehicles.Apply();
					Vehicles.Vehicle knightV = Vehicles.KnightV;
					ManualLogSource logger = Plugin.Logger;
					BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(36, 2, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Inventory loaded: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(__instance.AmountOf(knightV.Id, false, false));
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(knightV.Name);
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" in the backpack.");
					}
					logger.LogInfo(val);
				}
				catch (Exception ex)
				{
					ManualLogSource logger2 = Plugin.Logger;
					BepInExErrorLogInterpolatedStringHandler val2 = new BepInExErrorLogInterpolatedStringHandler(38, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val2).AppendLiteral("Vehicle cards not set after the load: ");
						((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<Exception>(ex);
					}
					logger2.LogError(val2);
				}
			}
		}

		[HarmonyPatch(typeof(InventoryCutscene), "Play")]
		private static class OpenBackpack
		{
			private static void Prefix()
			{
				//IL_001d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0023: Expected O, but got Unknown
				try
				{
					Vehicles.Apply();
					Vehicles.EnsureKnightVPlace(LocalPlayer.Inventory);
				}
				catch (Exception ex)
				{
					ManualLogSource logger = Plugin.Logger;
					bool flag = default(bool);
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(31, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Backpack opening check failed: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
					}
					logger.LogError(val);
				}
			}

			private static void Postfix()
			{
				//IL_0017: Unknown result type (might be due to invalid IL or missing references)
				//IL_001d: Expected O, but got Unknown
				try
				{
					Vehicles.Sync(LocalPlayer.Inventory);
				}
				catch (Exception ex)
				{
					ManualLogSource logger = Plugin.Logger;
					bool flag = default(bool);
					BepInExErrorLogInterpolatedStringHandler val = new BepInExErrorLogInterpolatedStringHandler(40, 1, ref flag);
					if (flag)
					{
						((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Knight V backpack place refresh failed: ");
						((BepInExLogInterpolatedStringHandler)val).AppendFormatted<Exception>(ex);
					}
					logger.LogError(val);
				}
			}
		}

		private static int _loadingFrame = -1;
	}
	public enum PickUpTarget
	{
		Backpack,
		Hands
	}
	[BepInPlugin("aznan.sotf.pocketvehicles", "PocketVehicles", "0.3.0")]
	public class Plugin : BasePlugin
	{
		internal const string Version = "0.3.0";

		internal static ManualLogSource Logger;

		internal static ConfigEntry<bool> Enabled;

		internal static ConfigEntry<float> KnightVX;

		internal static ConfigEntry<float> KnightVY;

		internal static ConfigEntry<float> KnightVZ;

		internal static ConfigEntry<float> KnightVTilt;

		internal static ConfigEntry<float> KnightVScale;

		internal static ConfigEntry<string> StoredMessage;

		internal static ConfigEntry<float> MessageSeconds;

		internal static ConfigEntry<bool> FullLogging;

		public override void Load()
		{
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Expected O, but got Unknown
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Expected O, but got Unknown
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_012a: Expected O, but got Unknown
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_0162: Expected O, but got Unknown
			//IL_0190: Unknown result type (might be due to invalid IL or missing references)
			//IL_019a: Expected O, but got Unknown
			//IL_0272: Unknown result type (might be due to invalid IL or missing references)
			//IL_0286: Unknown result type (might be due to invalid IL or missing references)
			//IL_028c: Expected O, but got Unknown
			Logger = ((BasePlugin)this).Log;
			Texts.SelfCheck();
			Enabled = ((BasePlugin)this).Config.Bind<bool>("General", "Enabled", true, "True = the Knight V can be kept in your backpack like any item (settings below). False = the game's behaviour: carried in hand only, put down on the ground when put away. A Knight V already in your backpack is never thrown away when a save loads; take it out to use it. The hang glider needs no mod: the game already keeps it in the backpack.");
			Vehicles.KnightV = new Vehicles.Vehicle
			{
				Name = "Knight V",
				Storable = ((BasePlugin)this).Config.Bind<bool>("KnightV", "KeepInBackpack", true, "True = the Knight V goes into your backpack instead of falling to the ground whenever the game puts it away (put-away key, opening the backpack, swimming, ziplines...), and comes back out from the backpack like any item; it can be put on one of the game's quick slots like a tool (its key takes it out and puts it back). It keeps its battery charge. It drops on the ground when your backpack has no room, as any item does. False = the game's behaviour for the Knight V. Default true."),
				PickUpTo = ((BasePlugin)this).Config.Bind<PickUpTarget>("KnightV", "PickUpInto", PickUpTarget.Backpack, "Where the Knight V goes when you pick it up with the game's prompt. Backpack = straight into your backpack (take it out from there). Hands = in your hands, as in the game; putting it away then stores it. Default Backpack. Only when KeepInBackpack is true.")
			};
			KnightVX = ((BasePlugin)this).Config.Bind<float>("KnightV", "BackpackSpotX", -1.19f, new ConfigDescription("Where the Knight V lies in the open backpack, left (-) to right (+), in metres of the backpack (items there are life-size: a rifle is 1 m). Default -1.19 (a free spot measured in the game's files, among the books and the money). Takes effect after loading a game.", (AcceptableValueBase)null, new object[1] { "ReloadSave" }));
			KnightVY = ((BasePlugin)this).Config.Bind<float>("KnightV", "BackpackSpotHeight", 0.275f, new ConfigDescription("Height of the Knight V above the backpack, in metres. Default 0.275 (half its width, so it lies on the backpack when on its side). Raise it if it sinks in, lower it if it floats. Takes effect after loading a game.", (AcceptableValueBase)null, new object[1] { "ReloadSave" }));
			KnightVZ = ((BasePlugin)this).Config.Bind<float>("KnightV", "BackpackSpotZ", 0.105f, new ConfigDescription("Where the Knight V lies in the open backpack, near (-) to far (+), in metres of the backpack. Default 0.105. Takes effect after loading a game.", (AcceptableValueBase)null, new object[1] { "ReloadSave" }));
			KnightVTilt = ((BasePlugin)this).Config.Bind<float>("KnightV", "BackpackTiltDegrees", 90f, new ConfigDescription("How far the Knight V is turned onto its side in the backpack, in degrees. Default 90 (lying on its side). 0 = standing on its wheel (then set BackpackSpotHeight to about 0.28). Takes effect after loading a game.", (AcceptableValueBase)null, new object[1] { "ReloadSave" }));
			KnightVScale = ((BasePlugin)this).Config.Bind<float>("KnightV", "BackpackModelScale", 1f, new ConfigDescription("Size of the Knight V shown in the backpack, times its real size. Default 1 (life-size, like the other items there). Advised: 0.5 to 1.2. 0 or less = 1. Takes effect after loading a game.", (AcceptableValueBase)null, new object[1] { "ReloadSave" }));
			StoredMessage = ((BasePlugin)this).Config.Bind<string>("Texts", "StoredMessage", "", "On-screen message when the Knight V goes into your backpack; {0} = its name in the game's language. Empty = automatic, in the game's language.");
			MessageSeconds = ((BasePlugin)this).Config.Bind<float>("Texts", "MessageSeconds", 3f, "Seconds the on-screen message stays. Default 3 (the game's own message length). Advised: 2 to 6. 0 or less = no message.");
			FullLogging = ((BasePlugin)this).Config.Bind<bool>("Debug", "FullLogging", false, "True = the BepInEx log gets every step useful to diagnose a problem (the Knight V's item settings applied, each put-away, its backpack spot and what it shows). False = only loading, version, errors, the Knight V's game settings once, and one line per pickup or Knight V put in the backpack.");
			ModLog.Init(Logger, FullLogging);
			Enabled.SettingChanged += delegate
			{
				Vehicles.Apply();
			};
			Vehicles.KnightV.Storable.SettingChanged += delegate
			{
				Vehicles.Apply();
			};
			new Harmony("aznan.sotf.pocketvehicles").PatchAll();
			ManualLogSource logger = Logger;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(23, 1, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral("PocketVehicles ");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>("0.3.0");
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" loaded.");
			}
			logger.LogInfo(val);
		}
	}
	internal static class Vehicles
	{
		internal sealed class Vehicle
		{
			public int Id;

			public string Name;

			public ConfigEntry<bool> Storable;

			public ConfigEntry<PickUpTarget> PickUpTo;

			public IntPtr Card;

			public bool GameCanNotBeStored;

			public bool GameAlwaysDrop;

			public bool GamePreventEquip;

			public bool GameHotkey;

			public bool GameHotkeyToggle;

			public int GameMax;

			public bool Stores
			{
				get
				{
					if (Plugin.Enabled.Value)
					{
						return Storable.Value;
					}
					return false;
				}
			}
		}

		internal static Vehicle KnightV;

		private static int _gliderId;

		private static bool _idsRead;

		private static int _pickedId;

		private static int _pickedFrame = -1;

		private const string SpotName = "PocketVehicles_KnightVSpot";

		private const string PlaceName = "PocketVehicles_KnightVLayoutGroup";

		private const string HolderName = "PocketVehicles_Holder";

		private const string KnightVModelGuid = "cc781d82705c15641903ffc190d191e4";

		private static InventoryLayoutItemGroup _place;

		private static IntPtr _warnedWorld;

		internal static Vehicle Of(int id)
		{
			ReadIds();
			if (id == 0 || id != KnightV.Id)
			{
				return null;
			}
			return KnightV;
		}

		private static void ReadIds()
		{
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004b: Expected O, but got Unknown
			if (_idsRead)
			{
				return;
			}
			_gliderId = ItemDatabase.HangGliderId;
			KnightV.Id = ItemDatabase.KnightVId;
			if (_gliderId != 0 && KnightV.Id != 0)
			{
				_idsRead = true;
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(82, 2, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral("Item ids: Knight V ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(KnightV.Id);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(", hang glider ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(_gliderId);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" (its backpack place is copied for the Knight V).");
				}
				logger.LogInfo(val);
				if (((BaseChainloader<BasePlugin>)(object)IL2CPPChainloader.Instance).Plugins.ContainsKey("SmokyAce.StoreKnightV"))
				{
					Plugin.Logger.LogWarning((object)"StoreKnightV is installed: it also puts the Knight V in the backpack, with its own spot, so the backpack can show two Knight Vs. Remove one of the two mods.");
				}
			}
		}

		internal static void Apply(bool keepStored = false)
		{
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0101: Expected O, but got Unknown
			ReadIds();
			if (!_idsRead)
			{
				return;
			}
			Vehicle knightV = KnightV;
			ItemData val = ItemDatabaseManager.ItemById(knightV.Id);
			if ((Object)(object)val == (Object)null)
			{
				ModLog.Once("no card", $"No item card for the {knightV.Name} (id {knightV.Id}): it keeps the game's behaviour.", (LogLevel)4);
				return;
			}
			if (((Il2CppObjectBase)val).Pointer != knightV.Card)
			{
				knightV.Card = ((Il2CppObjectBase)val).Pointer;
				knightV.GameCanNotBeStored = val._canNotBeStored;
				knightV.GameAlwaysDrop = val._alwaysDropOnUnequip;
				knightV.GamePreventEquip = val._preventEquipFromInventoryView;
				knightV.GameMax = val._maxAmount;
				knightV.GameHotkey = val._canBeHotKeyed;
				knightV.GameHotkeyToggle = val._hotkeyCanToggleItem;
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExInfoLogInterpolatedStringHandler val2 = new BepInExInfoLogInterpolatedStringHandler(196, 8, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<string>(knightV.Name);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" game item card: can not be stored ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<bool>(knightV.GameCanNotBeStored);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(", always drop when put away ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<bool>(knightV.GameAlwaysDrop);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(", no taking out from the backpack ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<bool>(knightV.GamePreventEquip);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(", at most ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<int>(knightV.GameMax);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(" in the backpack, drops on death ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<bool>(val._dropsOnDeath);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(", can be put on a quick slot ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<bool>(knightV.GameHotkey);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(", quick slot puts it away ");
					((BepInExLogInterpolatedStringHandler)val2).AppendFormatted<bool>(knightV.GameHotkeyToggle);
					((BepInExLogInterpolatedStringHandler)val2).AppendLiteral(".");
				}
				logger.LogInfo(val2);
			}
			bool flag2 = keepStored || knightV.Stores;
			val._canNotBeStored = !flag2 && knightV.GameCanNotBeStored;
			val._alwaysDropOnUnequip = !flag2 && knightV.GameAlwaysDrop;
			val._preventEquipFromInventoryView = false;
			val._maxAmount = (flag2 ? Math.Max(knightV.GameMax, 1) : knightV.GameMax);
			val._canBeHotKeyed = flag2 || knightV.GameHotkey;
			val._hotkeyCanToggleItem = flag2 || knightV.GameHotkeyToggle;
			if (ModLog.Changed(knightV.Id, "card", flag2 ? 1 : 0))
			{
				ModLog.Trace($"{knightV.Name} item card set {(flag2 ? "storable" : "as in the game")}{(keepStored ? " (save loading)" : "")}.");
			}
		}

		internal static bool IntoBackpack(int id)
		{
			if (id != 0 && id == _pickedId)
			{
				return Time.frameCount == _pickedFrame;
			}
			return false;
		}

		internal static void PickingUp(int itemId)
		{
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Expected O, but got Unknown
			Vehicle vehicle = Of(itemId);
			if (vehicle != null)
			{
				Apply();
				bool flag = vehicle.Stores && vehicle.PickUpTo.Value == PickUpTarget.Backpack;
				_pickedId = (flag ? vehicle.Id : 0);
				_pickedFrame = Time.frameCount;
				ManualLogSource logger = Plugin.Logger;
				bool flag2 = default(bool);
				BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(13, 2, ref flag2);
				if (flag2)
				{
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(vehicle.Name);
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" picked up: ");
					((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(flag ? "into the backpack" : (vehicle.Stores ? "in hand (put it away to store it)" : "in hand, as in the game"));
					((BepInExLogInterpolatedStringHandler)val).AppendLiteral(".");
				}
				logger.LogInfo(val);
			}
		}

		internal static void Added(PlayerInventory inv, int itemId, bool loading)
		{
			//IL_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Expected O, but got Unknown
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Expected O, but got Unknown
			Vehicle vehicle = Of(itemId);
			if (vehicle == null || loading || !vehicle.Stores || (Time.frameCount == _pickedFrame && !IntoBackpack(itemId)))
			{
				return;
			}
			if (inv.AmountOf(itemId, false, false) <= 0)
			{
				ModLog.Trace(vehicle.Name + " added but not in the backpack itself (in hand, or refused by the game): no message.");
				return;
			}
			ManualLogSource logger = Plugin.Logger;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val = new BepInExInfoLogInterpolatedStringHandler(30, 2, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<string>(vehicle.Name);
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" put in the backpack (");
				((BepInExLogInterpolatedStringHandler)val).AppendFormatted<int>(inv.AmountOf(itemId, false, false));
				((BepInExLogInterpolatedStringHandler)val).AppendLiteral(" there).");
			}
			logger.LogInfo(val);
			if (Plugin.MessageSeconds.Value <= 0f)
			{
				ModLog.Trace("No on-screen message: MessageSeconds is 0 or less.");
				return;
			}
			ItemData val2 = ItemDatabaseManager.ItemById(itemId);
			string text = GameName(val2);
			if (text == null)
			{
				text = vehicle.Name;
				ModLog.Once("no game name", "The " + vehicle.Name + "'s name in the game's language was not found: the message uses its English name.", (LogLevel)4);
			}
			string text2 = Plugin.StoredMessage.Value;
			if (string.IsNullOrEmpty(text2))
			{
				Locale selectedLocale = LocalizationSettings.SelectedLocale;
				text2 = Texts.Get((selectedLocale != null) ? selectedLocale.Identifier.Code : null, "Stored");
			}
			HudGui instance = HudGui._instance;
			if ((Object)(object)instance == (Object)null)
			{
				ModLog.Once("no hud", "The game's message line (HudGui) was not found: no on-screen message.", (LogLevel)4);
				return;
			}
			try
			{
				instance.DisplayGeneralMessage(text2.Replace("{0}", text), Plugin.MessageSeconds.Value, ((Object)(object)val2 != (Object)null) ? val2._uiData : null);
			}
			catch (Exception ex)
			{
				ManualLogSource logger2 = Plugin.Logger;
				BepInExWarningLogInterpolatedStringHandler val3 = new BepInExWarningLogInterpolatedStringHandler(26, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Game message line failed: ");
					((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<string>(ex.Message);
				}
				logger2.LogWarning(val3);
			}
		}

		private static string GameName(ItemData card)
		{
			if ((Object)(object)card == (Object)null || card._uiData == null)
			{
				return null;
			}
			try
			{
				string localizedString = LocalizationSettings.StringDatabase.GetLocalizedString(TableReference.op_Implicit(ItemUiData.ItemsTableReference), TableEntryReference.op_Implicit(card._uiData._translationKey), (Locale)null, (FallbackBehavior)0, (Il2CppReferenceArray<Object>)null);
				return string.IsNullOrEmpty(localizedString) ? null : localizedString;
			}
			catch (Exception ex)
			{
				ModLog.Trace($"Game name of item {card._id} not read: {ex.Message}");
				return null;
			}
		}

		internal static void EnsureKnightVPlace(PlayerInventory inv)
		{
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_010c: Expected O, but got Unknown
			if ((Object)(object)inv == (Object)null || !_idsRead)
			{
				return;
			}
			if ((Object)(object)_place != (Object)null)
			{
				Sync(inv);
				return;
			}
			if (!KnightV.Stores && inv.AmountOf(KnightV.Id, false, false) <= 0)
			{
				if (ModLog.Changed(((Object)inv).GetInstanceID(), "place skipped", 1))
				{
					ModLog.Trace("Knight V backpack place not built: KeepInBackpack (or the mod) is off and none is in the backpack.");
				}
				return;
			}
			List<InventoryLayoutItemGroup> val = (((Object)(object)inv._inventoryCutscene != (Object)null) ? inv._inventoryCutscene._inventoryLayoutItemGroups : null);
			InventoryLayoutItemGroup val2 = null;
			if (val != null)
			{
				Enumerator<InventoryLayoutItemGroup> enumerator = val.GetEnumerator();
				while (enumerator.MoveNext())
				{
					InventoryLayoutItemGroup current = enumerator.Current;
					if ((Object)(object)current != (Object)null && ((LayoutItemGroup<InventoryLayoutItem>)(object)current)._itemId == _gliderId)
					{
						val2 = current;
						break;
					}
				}
			}
			if ((Object)(object)val2 == (Object)null)
			{
				if (_warnedWorld != ((Il2CppObjectBase)inv).Pointer)
				{
					Plugin.Logger.LogWarning((object)"The backpack's hang glider place was not found: the Knight V has no place in the backpack (it is still kept and saved).");
				}
				_warnedWorld = ((Il2CppObjectBase)inv).Pointer;
				return;
			}
			try
			{
				Build(inv, val2, val);
			}
			catch (Exception ex)
			{
				ManualLogSource logger = Plugin.Logger;
				bool flag = default(bool);
				BepInExErrorLogInterpolatedStringHandler val3 = new BepInExErrorLogInterpolatedStringHandler(74, 1, ref flag);
				if (flag)
				{
					((BepInExLogInterpolatedStringHandler)val3).AppendLiteral("Knight V backpack place not built (the Knight V is still kept and saved): ");
					((BepInExLogInterpolatedStringHandler)val3).AppendFormatted<Exception>(ex);
				}
				logger.LogError(val3);
			}
		}

		private static void Build(PlayerInventory inv, InventoryLayoutItemGroup glider, List<InventoryLayoutItemGroup> groups)
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_020c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0211: Unknown result type (might be due to invalid IL or missing references)
			//IL_0224: Expected O, but got Unknown
			//IL_0257: Unknown result type (might be due to invalid IL or missing references)
			//IL_027c: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_032f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0336: Expected O, but got Unknown
			//IL_0391: Unknown result type (might be due to invalid IL or missing references)
			Transform parent = ((Component)glider).transform.parent;
			if ((Object)(object)parent == (Object)null)
			{
				throw new InvalidOperationException("the hang glider place has no parent");
			}
			Transform val = parent.Find("PocketVehicles_KnightVSpot");
			if ((Object)(object)val != (Object)null)
			{
				Object.Destroy((Object)(object)((Component)val).gameObject);
				Plugin.Logger.LogWarning((object)"A Knight V backpack spot from an earlier build was still there: replaced.");
			}
			GameObject val2 = new GameObject("PocketVehicles_Holder");
			val2.SetActive(false);
			val2.transform.SetParent(parent, false);
			GameObject val3 = Object.Instantiate<GameObject>(((Component)glider).gameObject, val2.transform);
			((Object)val3).name = "PocketVehicles_KnightVLayoutGroup";
			val3.transform.localPosition = Vector3.zero;
			val3.transform.localRotation = Quaternion.identity;
			InventoryLayoutItemGroup component = val3.GetComponent<InventoryLayoutItemGroup>();
			((LayoutItemGroup<InventoryLayoutItem>)(object)component)._itemId = KnightV.Id;
			((LayoutItemGroup<InventoryLayoutItem>)(object)component)._itemData = ItemDatabaseManager.ItemById(KnightV.Id);
			float num = ((Plugin.KnightVScale.Value > 0f) ? Plugin.KnightVScale.Value : 1f);
			string from;
			AssetReference baseRenderable = KnightVModel(out from);
			int num2 = 0;
			foreach (ItemRenderable componentsInChild in val3.GetComponentsInChildren<ItemRenderable>(true))
			{
				for (int num3 = ((Component)componentsInChild).transform.childCount - 1; num3 >= 0; num3--)
				{
					Object.DestroyImmediate((Object)(object)((Component)((Component)componentsInChild).transform.GetChild(num3)).gameObject);
				}
				((AssetReferenceRenderable)componentsInChild)._cachedLoadedObject = null;
				componentsInChild._itemId = KnightV.Id;
				((AssetReferenceRenderable)componentsInChild)._baseRenderable = baseRenderable;
				((AssetReferenceRenderable)componentsInChild)._applyScale = true;
				((AssetReferenceRenderable)componentsInChild)._scale = Vector3.one * num;
				num2++;
			}
			foreach (InventoryLayoutItem componentsInChild2 in val3.GetComponentsInChildren<InventoryLayoutItem>(true))
			{
				((LayoutItem)componentsInChild2)._renderers?.Clear();
				((LayoutItem)componentsInChild2)._meshOutliners?.Clear();
			}
			GameObject val4 = new GameObject("PocketVehicles_KnightVSpot")
			{
				layer = ((Component)glider).gameObject.layer
			};
			val4.transform.SetParent(parent, false);
			val4.transform.localPosition = new Vector3(Plugin.KnightVX.Value, Plugin.KnightVY.Value, Plugin.KnightVZ.Value);
			val4.transform.localRotation = Quaternion.Euler(0f, 0f, Plugin.KnightVTilt.Value);
			val3.transform.SetParent(val4.transform, false);
			Object.Destroy((Object)(object)val2);
			_place = component;
			groups.Add(component);
			int num4 = 0;
			foreach (InventoryEnableLayoutGroups item in Resources.FindObjectsOfTypeAll<InventoryEnableLayoutGroups>())
			{
				Scene scene = ((Component)item).gameObject.scene;
				if (((Scene)(ref scene)).IsValid() && item._layoutGroups != null && item._layoutGroups.Contains(glider))
				{
					item._layoutGroups.Add(component);
					num4++;
				}
			}
			ManualLogSource logger = Plugin.Logger;
			bool flag = default(bool);
			BepInExInfoLogInterpolatedStringHandler val5 = new BepInExInfoLogInterpolatedStringHandler(194, 7, ref flag);
			if (flag)
			{
				((BepInExLogInterpolatedStringHandler)val5).AppendLiteral("Knight V backpack place built next to the game's hang glider place: model from ");
				((BepInExLogInterpolatedStringHandler)val5).AppendFormatted<string>(from);
				((BepInExLogInterpolatedStringHandler)val5).AppendLiteral(", ");
				((BepInExLogInterpolatedStringHandler)val5).AppendFormatted<int>(num2);
				((BepInExLogInterpolatedStringHandler)val5).AppendLiteral(" model holder(s), scale ");
				((BepInExLogInterpolatedStringHandler)val5).AppendFormatted<float>(num);
				((BepInExLogInterpolatedStringHandler)val5).AppendLiteral(", spot ");
				((BepInExLogInterpolatedStringHandler)val5).AppendFormatted<Vector3>(val4.transform.localPosition);
				((BepInExLogInterpolatedStringHandler)val5).AppendLiteral(" tilted ");
				((BepInExLogInterpolatedStringHandler)val5).AppendFormatted<float>(Plugin.KnightVTilt.Value);
				((BepInExLogInterpolatedStringHandler)val5).AppendLiteral(" deg; in the backpack list and ");
				((BepInExLogInterpolatedStringHandler)val5).AppendFormatted<int>(num4);
				((BepInExLogInterpolatedStringHandler)val5).AppendLiteral(" on/off list(s); linked to your inventory ");
				((BepInExLogInterpolatedStringHandler)val5).AppendFormatted<bool>((Object)(object)component._inventory != (Object)null && ((Il2CppObjectBase)component._inventory).Pointer == ((Il2CppObjectBase)inv).Pointer);
				((BepInExLogInterpolatedStringHandler)val5).AppendLiteral(".");
			}
			logger.LogInfo(val5);
			Sync(inv);
		}

		private static AssetReference KnightVModel(out string from)
		{
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Expected O, but got Unknown
			ItemData val = ItemDatabaseManager.ItemById(KnightV.Id);
			Transform val2 = (((Object)(object)val != (Object)null) ? val._pickupPrefab : null);
			ItemRenderable val3 = (((Object)(object)val2 != (Object)null) ? ((Component)val2).GetComponentInChildren<ItemRenderable>(true) : null);
			if ((Object)(object)val3 != (Object)null && ((AssetReferenceRenderable)val3)._baseRenderable != null && !string.IsNullOrEmpty(((AssetReferenceRenderable)val3)._baseRenderable.AssetGUID))
			{
				from = "the game's Knight V pickup (" + ((AssetReferenceRenderable)val3)._baseRenderable.AssetGUID + ")";
				return ((AssetReferenceRenderable)val3)._baseRenderable;
			}
			Plugin.Logger.LogWarning((object)"The Knight V pickup's model was not readable: using the model key read in the game files.");
			from = "the catalog key cc781d82705c15641903ffc190d191e4";
			return new AssetReference("cc781d82705c15641903ffc190d191e4");
		}

		internal static void Sync(PlayerInventory inv)
		{
			if (!((Object)(object)_place == (Object)null) && !((Object)(object)inv == (Object)null))
			{
				int num = inv.AmountOf(KnightV.Id, false, false);
				int activeVisualCount = ((LayoutItemGroup<InventoryLayoutItem>)(object)_place).GetActiveVisualCount();
				bool flag = activeVisualCount != Math.Min(num, ((LayoutItemGroup<InventoryLayoutItem>)(object)_place)._layoutItems?.Count ?? 0);
				if (flag)
				{
					((LayoutItemGroup<InventoryLayoutItem>)(object)_place).RefreshItems();
				}
				if (ModLog.Changed(((Object)_place).GetInstanceID(), "shown", HashCode.Combine(num, activeVisualCount, flag)))
				{
					ModLog.Trace($"Knight V backpack place: {num} in the backpack, shown {activeVisualCount}{(flag ? $" -> {((LayoutItemGroup<InventoryLayoutItem>)(object)_place).GetActiveVisualCount()} (refreshed)" : " (already right)")}.");
				}
			}
		}
	}
}
namespace PocketVehicles.Logic
{
	public static class Texts
	{
		public const string Stored = "Stored";

		private static readonly Dictionary<string, Dictionary<string, string>> ByLanguage = new Dictionary<string, Dictionary<string, string>>
		{
			["en"] = new Dictionary<string, string> { ["Stored"] = "{0} put in your backpack" },
			["fr"] = new Dictionary<string, string> { ["Stored"] = "{0} rangé dans le sac à dos" },
			["zh"] = new Dictionary<string, string> { ["Stored"] = "{0}已放入背包" },
			["zh-hant"] = new Dictionary<string, string> { ["Stored"] = "{0}已放入背包" },
			["cs"] = new Dictionary<string, string> { ["Stored"] = "{0} uloženo do batohu" },
			["fi"] = new Dictionary<string, string> { ["Stored"] = "{0} laitettu reppuusi" },
			["de"] = new Dictionary<string, string> { ["Stored"] = "{0} in deinen Rucksack gelegt" },
			["it"] = new Dictionary<string, string> { ["Stored"] = "{0} messo nello zaino" },
			["ja"] = new Dictionary<string, string> { ["Stored"] = "{0}をバックパックに入れた" },
			["ko"] = new Dictionary<string, string> { ["Stored"] = "{0} 배낭에 넣음" },
			["pl"] = new Dictionary<string, string> { ["Stored"] = "{0} schowano do plecaka" },
			["pt"] = new Dictionary<string, string> { ["Stored"] = "{0} guardado na mochila" },
			["ru"] = new Dictionary<string, string> { ["Stored"] = "{0} убрано в рюкзак" },
			["es"] = new Dictionary<string, string> { ["Stored"] = "{0} guardado en la mochila" },
			["sv"] = new Dictionary<string, string> { ["Stored"] = "{0} lades i ryggsäcken" },
			["tr"] = new Dictionary<string, string> { ["Stored"] = "{0} sırt çantana konuldu" }
		};

		public static string Get(string localeCode, string key)
		{
			string text = (localeCode ?? "en").ToLowerInvariant();
			string key2 = (ByLanguage.ContainsKey(text) ? text : text.Split('-')[0]);
			if (!ByLanguage.TryGetValue(key2, out var value) || !value.TryGetValue(key, out var value2))
			{
				return ByLanguage["en"][key];
			}
			return value2;
		}

		public static void SelfCheck()
		{
			if (Get("fr-FR", "Stored") != ByLanguage["fr"]["Stored"] || Get("xx", "Stored") != ByLanguage["en"]["Stored"] || Get(null, "Stored") != ByLanguage["en"]["Stored"])
			{
				throw new InvalidOperationException("Texts lookup is wrong.");
			}
		}
	}
}