Decompiled source of TruckDecorator v0.3.8

plugins/TruckDecorator.dll

Decompiled a week ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

[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("TruckDecorator")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("TruckDecorator")]
[assembly: AssemblyTitle("TruckDecorator")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace TruckDecoratorMod
{
	[BepInPlugin("norbert.truckdecorator", "TruckDecorator", "0.3.8")]
	public sealed class TruckDecoratorPlugin : BaseUnityPlugin
	{
		private sealed class RestorableCandidate
		{
			public GameObject Object;

			public string AssetName;

			public string InstanceName;

			public Vector3 LocalPosition;
		}

		public const string PluginGuid = "norbert.truckdecorator";

		public const string PluginName = "TruckDecorator";

		public const string PluginVersion = "0.3.8";

		internal static TruckDecoratorPlugin Instance;

		private string _savePath;

		private string _lastJson;

		private float _nextCapture;

		private string _uiStatus = "Arrange purchased items, then save your layout.";

		private float _truckReadySince = -1f;

		private bool _restoreQueued;

		private bool _restoreAttemptedThisSession;

		private bool _restoreSucceededThisSession;

		private bool _savedLayoutExistedAtStartup;

		private bool _truckWasPresent;

		private int _lastTruckRoomInstanceId;

		private RoomVolume _cachedTruckRoom;

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

		private float _nextRestoreRetryTime;

		private Harmony _harmony;

		private ManualLogSource _log;

		private void Awake()
		{
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Expected O, but got Unknown
			Instance = this;
			_log = ((BaseUnityPlugin)this).Logger;
			_savePath = Path.Combine(Paths.ConfigPath, "TruckDecorator", "purchased-items.json");
			Directory.CreateDirectory(Path.GetDirectoryName(_savePath));
			_savedLayoutExistedAtStartup = File.Exists(_savePath);
			_harmony = new Harmony("norbert.truckdecorator");
			_harmony.PatchAll();
			_log.LogInfo((object)"TruckDecorator 0.3.8 loaded (cached GUI truck lookup + reduced-frequency scanning + manual save + partial per-item restore retry).");
			_log.LogInfo((object)("Purchased equipment snapshots: " + _savePath));
			LogGameApiDiagnostics();
		}

		private void OnDestroy()
		{
			if (_harmony != null)
			{
				_harmony.UnpatchSelf();
			}
			if ((Object)(object)Instance == (Object)(object)this)
			{
				Instance = null;
			}
		}

		private void LogGameApiDiagnostics()
		{
			LogTypeMembers(typeof(ItemManager), "ItemManager", "GetPurchasedItems", "Spawn");
			LogTypeMembers(typeof(StatsManager), "StatsManager", "Purchase", "Purchased", "Item");
			LogTypeMembers(typeof(ItemAttributes), "ItemAttributes", "itemAssetName", "instanceName", "item", "purchase", "shop", "spawn", "asset", "valuable", "value");
			LogAllItemAttributeMembers();
			LogTypeMembers(typeof(RoomVolumeCheck), "RoomVolumeCheck", "CurrentRooms", "Room");
			LogTypeMembers(typeof(RoomVolume), "RoomVolume", "Truck");
			LogTypeMembers(typeof(PunManager), "PunManager", "SpawnItem");
		}

		private void LogAllItemAttributeMembers()
		{
			Type typeFromHandle = typeof(ItemAttributes);
			FieldInfo[] fields = typeFromHandle.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (FieldInfo fieldInfo in fields)
			{
				_log.LogInfo((object)("[ItemAttributes detail] FIELD " + fieldInfo.FieldType.FullName + " " + fieldInfo.Name));
			}
			PropertyInfo[] properties = typeFromHandle.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (PropertyInfo propertyInfo in properties)
			{
				_log.LogInfo((object)("[ItemAttributes detail] PROPERTY " + propertyInfo.PropertyType.FullName + " " + propertyInfo.Name));
			}
			MethodInfo[] methods = typeFromHandle.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MethodInfo methodInfo in methods)
			{
				if (!methodInfo.IsSpecialName)
				{
					string text = string.Join(", ", from parameter in methodInfo.GetParameters()
						select parameter.ParameterType.FullName + " " + parameter.Name);
					_log.LogInfo((object)("[ItemAttributes detail] METHOD " + methodInfo.ReturnType.FullName + " " + methodInfo.Name + "(" + text + ")"));
				}
			}
		}

		private void LogTypeMembers(Type type, string label, params string[] filters)
		{
			_log.LogInfo((object)("[API probe] " + label + " => " + type.FullName));
			FieldInfo[] fields = type.GetFields(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (FieldInfo field in fields)
			{
				if (filters.Any((string filter) => field.Name.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0))
				{
					_log.LogInfo((object)("[API probe] FIELD " + label + "." + field.FieldType.FullName + " " + field.Name));
				}
			}
			PropertyInfo[] properties = type.GetProperties(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (PropertyInfo property in properties)
			{
				if (filters.Any((string filter) => property.Name.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0))
				{
					_log.LogInfo((object)("[API probe] PROPERTY " + label + "." + property.PropertyType.FullName + " " + property.Name));
				}
			}
			MethodInfo[] methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			foreach (MethodInfo method in methods)
			{
				if (filters.Any((string filter) => method.Name.IndexOf(filter, StringComparison.OrdinalIgnoreCase) >= 0))
				{
					string text = string.Join(", ", from parameter in method.GetParameters()
						select parameter.ParameterType.FullName + " " + parameter.Name);
					_log.LogInfo((object)("[API probe] METHOD " + label + "." + method.ReturnType.FullName + " " + method.Name + "(" + text + ")"));
				}
			}
		}

		private void Update()
		{
			if (Time.unscaledTime < _nextCapture)
			{
				return;
			}
			_nextCapture = Time.unscaledTime + 2.5f;
			RoomVolume val = (_cachedTruckRoom = FindTruckRoom());
			if ((Object)(object)val == (Object)null)
			{
				_truckWasPresent = false;
				return;
			}
			int instanceID = ((Object)val).GetInstanceID();
			if (!_truckWasPresent || instanceID != _lastTruckRoomInstanceId)
			{
				_truckWasPresent = true;
				_lastTruckRoomInstanceId = instanceID;
				_restoreAttemptedThisSession = false;
				_restoreSucceededThisSession = false;
				_restoredSnapshotToCandidate.Clear();
				_nextRestoreRetryTime = Time.unscaledTime + 2f;
				_log.LogInfo((object)("Truck room detected (instance " + instanceID + "); restore is armed for this truck."));
			}
			if (_savedLayoutExistedAtStartup && !_restoreAttemptedThisSession && !_restoreSucceededThisSession && !_restoreQueued && Time.unscaledTime >= _nextRestoreRetryTime && (Object)(object)StatsManager.instance != (Object)null)
			{
				QueueRestore();
			}
		}

		internal void QueueRestore()
		{
			if (!_restoreQueued && !_restoreAttemptedThisSession && File.Exists(_savePath) && IsAuthority() && !((Object)(object)StatsManager.instance == (Object)null) && !((Object)(object)FindTruckRoom() == (Object)null))
			{
				_restoreQueued = true;
				((MonoBehaviour)this).StartCoroutine(RestoreSavedLayout());
			}
		}

		private IEnumerator RestoreSavedLayout()
		{
			int restoredTotal = 0;
			try
			{
				string json = File.ReadAllText(_savePath);
				PurchasedItemsDocument document = DeserializeDocument(json);
				if (document == null || document.items == null)
				{
					_log.LogWarning((object)"Restore skipped: saved truck layout could not be read. Original save has been preserved.");
					yield break;
				}
				if (document.items.Count == 0)
				{
					string text = _savePath + ".bak";
					if (File.Exists(text))
					{
						PurchasedItemsDocument purchasedItemsDocument = DeserializeDocument(File.ReadAllText(text));
						if (purchasedItemsDocument != null && purchasedItemsDocument.items != null && purchasedItemsDocument.items.Count > 0)
						{
							document = purchasedItemsDocument;
							string text2 = _savePath + ".recovered";
							if (!File.Exists(text2))
							{
								File.Copy(text, text2, overwrite: false);
							}
							_log.LogWarning((object)("Main layout was empty; recovered " + document.items.Count + " purchased item(s) from the previous backup. A protected .recovered copy was kept."));
						}
					}
				}
				if (document.items.Count == 0)
				{
					_log.LogWarning((object)"Restore skipped: current and backup layouts are empty. No empty layout will be treated as a successful restore.");
					yield break;
				}
				for (int attempt = 0; attempt < 15; attempt++)
				{
					yield return (object)new WaitForSecondsRealtime(2f);
					RoomVolume val = FindTruckRoom();
					if ((Object)(object)val == (Object)null)
					{
						continue;
					}
					List<RestorableCandidate> source = FindPurchasedTruckItems(val);
					HashSet<int> hashSet = new HashSet<int>(from candidate in source
						where candidate != null && (Object)(object)candidate.Object != (Object)null
						select ((Object)candidate.Object).GetInstanceID());
					foreach (int item in _restoredSnapshotToCandidate.Keys.ToList())
					{
						if (!hashSet.Contains(_restoredSnapshotToCandidate[item]))
						{
							_restoredSnapshotToCandidate.Remove(item);
						}
					}
					HashSet<int> claimedCandidateIds = new HashSet<int>(_restoredSnapshotToCandidate.Values);
					List<KeyValuePair<int, RestorableCandidate>> list = new List<KeyValuePair<int, RestorableCandidate>>();
					foreach (IGrouping<string, int> savedGroup in (from index in Enumerable.Range(0, document.items.Count)
						where !_restoredSnapshotToCandidate.ContainsKey(index)
						select index).GroupBy<int, string>((int index) => document.items[index].itemAsset, StringComparer.Ordinal))
					{
						List<int> list2 = (from index in savedGroup
							orderby document.items[index].localPosition.x, document.items[index].localPosition.y, document.items[index].localPosition.z
							select index).ToList();
						List<RestorableCandidate> source2 = (from candidate in source
							where candidate != null && (Object)(object)candidate.Object != (Object)null && string.Equals(candidate.AssetName, savedGroup.Key, StringComparison.Ordinal)
							orderby candidate.LocalPosition.x, candidate.LocalPosition.y, candidate.LocalPosition.z
							select candidate).ToList();
						foreach (int item2 in list2)
						{
							PurchasedItemSnapshot savedItem = document.items[item2];
							RestorableCandidate restorableCandidate = null;
							if (!string.IsNullOrEmpty(savedItem.instanceName))
							{
								restorableCandidate = source2.FirstOrDefault((RestorableCandidate candidate) => !claimedCandidateIds.Contains(((Object)candidate.Object).GetInstanceID()) && string.Equals(candidate.InstanceName, savedItem.instanceName, StringComparison.Ordinal));
							}
							if (restorableCandidate == null)
							{
								restorableCandidate = source2.FirstOrDefault((RestorableCandidate candidate) => !claimedCandidateIds.Contains(((Object)candidate.Object).GetInstanceID()));
							}
							if (restorableCandidate != null)
							{
								int instanceID = ((Object)restorableCandidate.Object).GetInstanceID();
								claimedCandidateIds.Add(instanceID);
								list.Add(new KeyValuePair<int, RestorableCandidate>(item2, restorableCandidate));
							}
						}
					}
					foreach (KeyValuePair<int, RestorableCandidate> item3 in list)
					{
						PurchasedItemSnapshot purchasedItemSnapshot = document.items[item3.Key];
						Transform transform = item3.Value.Object.transform;
						transform.position = ((Component)val).transform.TransformPoint(purchasedItemSnapshot.localPosition);
						transform.rotation = ((Component)val).transform.rotation * purchasedItemSnapshot.localRotation;
						Rigidbody component = item3.Value.Object.GetComponent<Rigidbody>();
						if ((Object)(object)component != (Object)null && !component.isKinematic)
						{
							component.velocity = Vector3.zero;
							component.angularVelocity = Vector3.zero;
						}
						_restoredSnapshotToCandidate[item3.Key] = ((Object)item3.Value.Object).GetInstanceID();
					}
					if (_restoredSnapshotToCandidate.Count >= document.items.Count)
					{
						restoredTotal = document.items.Count;
						_restoreSucceededThisSession = true;
						break;
					}
				}
				if (_restoreSucceededThisSession)
				{
					_log.LogInfo((object)("Restored saved positions/rotations for all " + restoredTotal + " purchased truck item(s)."));
					yield break;
				}
				RoomVolume val2 = FindTruckRoom();
				List<RestorableCandidate> source3 = (((Object)(object)val2 != (Object)null) ? FindPurchasedTruckItems(val2) : new List<RestorableCandidate>());
				var orderedEnumerable = (from entry in document.items.Select((PurchasedItemSnapshot item, int index) => new { item, index })
					where entry.item != null && !string.IsNullOrEmpty(entry.item.itemAsset) && !_restoredSnapshotToCandidate.ContainsKey(entry.index)
					select entry).GroupBy(entry => entry.item.itemAsset, StringComparer.Ordinal).OrderBy(grouping => grouping.Key, StringComparer.Ordinal);
				List<string> list3 = new List<string>();
				foreach (var group in orderedEnumerable)
				{
					int num = group.Count();
					int num2 = source3.Count((RestorableCandidate candidate) => string.Equals(candidate.AssetName, group.Key, StringComparison.Ordinal) && !_restoredSnapshotToCandidate.Values.Contains(((Object)candidate.Object).GetInstanceID()));
					list3.Add(group.Key + "=" + num2 + "/" + num);
				}
				_log.LogWarning((object)("Partial restore: restored " + _restoredSnapshotToCandidate.Count + "/" + document.items.Count + " purchased item(s). Still waiting for: " + ((list3.Count == 0) ? "items to spawn" : string.Join(", ", list3.ToArray())) + ". Already-restored items will not be moved again; saved layout preserved. Will retry in 15 seconds."));
			}
			finally
			{
				TruckDecoratorPlugin truckDecoratorPlugin = this;
				truckDecoratorPlugin._restoreQueued = false;
				if (truckDecoratorPlugin._restoreSucceededThisSession)
				{
					truckDecoratorPlugin._restoreAttemptedThisSession = true;
				}
				else
				{
					truckDecoratorPlugin._restoreAttemptedThisSession = false;
					truckDecoratorPlugin._nextRestoreRetryTime = Time.unscaledTime + 15f;
				}
			}
		}

		private static string ReadStringMember(object target, params string[] names)
		{
			if (target == null)
			{
				return string.Empty;
			}
			Type type = target.GetType();
			foreach (string name in names)
			{
				try
				{
					PropertyInfo property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					if (property != null && property.PropertyType == typeof(string))
					{
						return (property.GetValue(target, null) as string) ?? string.Empty;
					}
					FieldInfo field = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					if (field != null && field.FieldType == typeof(string))
					{
						return (field.GetValue(target) as string) ?? string.Empty;
					}
				}
				catch
				{
				}
			}
			return string.Empty;
		}

		private static bool ReadBoolMember(object target, params string[] names)
		{
			if (target == null)
			{
				return false;
			}
			Type type = target.GetType();
			foreach (string name in names)
			{
				try
				{
					PropertyInfo property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					if (property != null && property.PropertyType == typeof(bool))
					{
						return (bool)property.GetValue(target, null);
					}
					FieldInfo field = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					if (field != null && field.FieldType == typeof(bool))
					{
						return (bool)field.GetValue(target);
					}
				}
				catch
				{
				}
			}
			return false;
		}

		private static object ReadObjectMember(object target, params string[] names)
		{
			if (target == null)
			{
				return null;
			}
			Type type = target.GetType();
			foreach (string name in names)
			{
				try
				{
					PropertyInfo property = type.GetProperty(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					if (property != null && property.GetIndexParameters().Length == 0)
					{
						return property.GetValue(target, null);
					}
					FieldInfo field = type.GetField(name, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					if (field != null)
					{
						return field.GetValue(target);
					}
				}
				catch
				{
				}
			}
			return null;
		}

		private List<ItemAttributes> GetPurchasedItemAttributes()
		{
			List<ItemAttributes> list = new List<ItemAttributes>();
			HashSet<ItemAttributes> hashSet = new HashSet<ItemAttributes>();
			try
			{
				FieldInfo field = typeof(ItemManager).GetField("spawnedItems", BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
				if (field == null)
				{
					_log.LogWarning((object)"Purchase registry unavailable: ItemManager.spawnedItems field was not found.");
					return list;
				}
				List<object> list2 = new List<object>();
				if (field.IsStatic)
				{
					list2.Add(null);
				}
				else
				{
					FieldInfo field2 = typeof(ItemManager).GetField("instance", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
					if (field2 != null)
					{
						object value = field2.GetValue(null);
						if (value != null)
						{
							list2.Add(value);
						}
					}
					if (list2.Count == 0)
					{
						Object[] array = Resources.FindObjectsOfTypeAll(typeof(ItemManager));
						foreach (Object val in array)
						{
							if (val != (Object)null)
							{
								list2.Add(val);
							}
						}
					}
				}
				foreach (object item in list2)
				{
					if (!(field.GetValue(item) is IEnumerable enumerable))
					{
						continue;
					}
					foreach (object item2 in enumerable)
					{
						ItemAttributes val2 = (ItemAttributes)((item2 is ItemAttributes) ? item2 : null);
						if ((Object)(object)val2 != (Object)null && hashSet.Add(val2))
						{
							list.Add(val2);
						}
					}
				}
				_log.LogInfo((object)("Purchase registry scan: managers=" + list2.Count + ", spawnedItems=" + list.Count + "."));
			}
			catch (Exception ex)
			{
				_log.LogWarning((object)("Could not read ItemManager.spawnedItems purchase registry: " + ex.GetType().Name + ": " + ex.Message));
			}
			return list;
		}

		private static GameObject GetPhysicalGameObject(ItemAttributes attributes)
		{
			if ((Object)(object)attributes == (Object)null)
			{
				return null;
			}
			object obj = ReadObjectMember(attributes, "physGrabObject");
			PhysGrabObject val = (PhysGrabObject)((obj is PhysGrabObject) ? obj : null);
			if ((Object)(object)val != (Object)null)
			{
				return ((Component)val).gameObject;
			}
			return ((Component)attributes).gameObject;
		}

		private static string GetItemAssetName(ItemAttributes attributes)
		{
			if ((Object)(object)attributes == (Object)null)
			{
				return string.Empty;
			}
			string text = ReadStringMember(attributes, "itemAssetName", "assetName", "itemName");
			if (!string.IsNullOrEmpty(text))
			{
				return text;
			}
			object item = attributes.item;
			text = ReadStringMember(item, "itemAssetName", "assetName", "itemName", "name");
			if (!string.IsNullOrEmpty(text))
			{
				return text;
			}
			Object val = (Object)((item is Object) ? item : null);
			if (!(val != (Object)null))
			{
				return string.Empty;
			}
			return val.name;
		}

		private static string GetInstanceName(ItemAttributes attributes)
		{
			if ((Object)(object)attributes == (Object)null)
			{
				return string.Empty;
			}
			string text = ReadStringMember(attributes, "instanceName", "uniqueName", "objectName");
			if (!string.IsNullOrEmpty(text))
			{
				return text;
			}
			return ReadStringMember(((Component)attributes).gameObject, "instanceName", "uniqueName");
		}

		private static string EscapeJson(string value)
		{
			if (value == null)
			{
				return string.Empty;
			}
			return value.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\r", "\\r")
				.Replace("\n", "\\n")
				.Replace("\t", "\\t");
		}

		private static string Number(float value)
		{
			return value.ToString("R", CultureInfo.InvariantCulture);
		}

		private static string SerializeDocument(PurchasedItemsDocument document, bool pretty)
		{
			string text = (pretty ? "\n" : string.Empty);
			string text2 = (pretty ? "  " : string.Empty);
			List<string> list = new List<string>();
			foreach (PurchasedItemSnapshot item in document.items ?? new List<PurchasedItemSnapshot>())
			{
				string text3 = "{\"itemAsset\":\"" + EscapeJson(item.itemAsset) + "\",\"instanceName\":\"" + EscapeJson(item.instanceName) + "\",\"localPosition\":{\"x\":" + Number(item.localPosition.x) + ",\"y\":" + Number(item.localPosition.y) + ",\"z\":" + Number(item.localPosition.z) + "},\"localRotation\":{\"x\":" + Number(item.localRotation.x) + ",\"y\":" + Number(item.localRotation.y) + ",\"z\":" + Number(item.localRotation.z) + ",\"w\":" + Number(item.localRotation.w) + "},\"batteryPercent\":" + item.batteryPercent + "}";
				list.Add(pretty ? (text2 + text3) : text3);
			}
			return "{\"formatVersion\":" + document.formatVersion + ",\"capturedUtc\":\"" + EscapeJson(document.capturedUtc) + "\",\"items\":[" + (pretty ? text : string.Empty) + string.Join(pretty ? ",\n" : ",", list) + (pretty ? text : string.Empty) + "]}";
		}

		private static string JsonString(Match match)
		{
			if (!match.Success)
			{
				return string.Empty;
			}
			return match.Groups[1].Value.Replace("\\\"", "\"").Replace("\\\\", "\\").Replace("\\n", "\n")
				.Replace("\\r", "\r")
				.Replace("\\t", "\t");
		}

		private static float JsonFloat(string block, string key, float fallback)
		{
			Match match = Regex.Match(block, "\\\"" + key + "\\\"\\s*:\\s*(-?(?:[0-9]+(?:\\.[0-9]*)?|\\.[0-9]+)(?:[eE][+-]?[0-9]+)?)");
			if (!match.Success || !float.TryParse(match.Groups[1].Value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result))
			{
				return fallback;
			}
			return result;
		}

		private static PurchasedItemsDocument DeserializeDocument(string json)
		{
			//IL_020e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0213: Unknown result type (might be due to invalid IL or missing references)
			//IL_025d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0262: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrEmpty(json))
			{
				return null;
			}
			PurchasedItemsDocument purchasedItemsDocument = new PurchasedItemsDocument();
			Match match = Regex.Match(json, "\\\"formatVersion\\\"\\s*:\\s*(\\d+)");
			if (match.Success)
			{
				int.TryParse(match.Groups[1].Value, out purchasedItemsDocument.formatVersion);
			}
			Match match2 = Regex.Match(json, "\\\"capturedUtc\\\"\\s*:\\s*\\\"((?:\\\\.|[^\\\"])*)\\\"");
			purchasedItemsDocument.capturedUtc = JsonString(match2);
			Match match3 = Regex.Match(json, "\\\"items\\\"\\s*:\\s*\\[(.*)\\]", RegexOptions.Singleline);
			if (!match3.Success)
			{
				return null;
			}
			string value = match3.Groups[1].Value;
			int num = 0;
			int num2 = -1;
			bool flag = false;
			bool flag2 = false;
			for (int i = 0; i < value.Length; i++)
			{
				char c = value[i];
				if (flag)
				{
					if (flag2)
					{
						flag2 = false;
						continue;
					}
					switch (c)
					{
					case '\\':
						flag2 = true;
						break;
					case '"':
						flag = false;
						break;
					}
					continue;
				}
				switch (c)
				{
				case '"':
					flag = true;
					break;
				case '{':
					if (num == 0)
					{
						num2 = i;
					}
					num++;
					break;
				case '}':
					if (num <= 0)
					{
						break;
					}
					num--;
					if (num == 0 && num2 >= 0)
					{
						string input = value.Substring(num2, i - num2 + 1);
						Match match4 = Regex.Match(input, "\\\"itemAsset\\\"\\s*:\\s*\\\"((?:\\\\.|[^\\\"])*)\\\"");
						Match match5 = Regex.Match(input, "\\\"instanceName\\\"\\s*:\\s*\\\"((?:\\\\.|[^\\\"])*)\\\"");
						string value2 = Regex.Match(input, "\\\"localPosition\\\"\\s*:\\s*\\{([^}]*)\\}").Groups[1].Value;
						string value3 = Regex.Match(input, "\\\"localRotation\\\"\\s*:\\s*\\{([^}]*)\\}").Groups[1].Value;
						Match match6 = Regex.Match(input, "\\\"batteryPercent\\\"\\s*:\\s*(-?\\d+)");
						int result = -1;
						if (match6.Success)
						{
							int.TryParse(match6.Groups[1].Value, out result);
						}
						purchasedItemsDocument.items.Add(new PurchasedItemSnapshot
						{
							itemAsset = JsonString(match4),
							instanceName = JsonString(match5),
							localPosition = new Vector3(JsonFloat(value2, "x", 0f), JsonFloat(value2, "y", 0f), JsonFloat(value2, "z", 0f)),
							localRotation = new Quaternion(JsonFloat(value3, "x", 0f), JsonFloat(value3, "y", 0f), JsonFloat(value3, "z", 0f), JsonFloat(value3, "w", 1f)),
							batteryPercent = result
						});
						num2 = -1;
					}
					break;
				}
			}
			return purchasedItemsDocument;
		}

		private RoomVolume FindTruckRoom()
		{
			return ((IEnumerable<RoomVolume>)Object.FindObjectsOfType<RoomVolume>()).FirstOrDefault((Func<RoomVolume, bool>)((RoomVolume room) => (Object)(object)room != (Object)null && room.Truck));
		}

		private static bool IsInsideTruckRoom(GameObject go, RoomVolume truckRoom)
		{
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)go == (Object)null || (Object)(object)truckRoom == (Object)null)
			{
				return false;
			}
			RoomVolumeCheck component = go.GetComponent<RoomVolumeCheck>();
			if ((Object)(object)component != (Object)null && component.CurrentRooms != null && component.CurrentRooms.Any((RoomVolume room) => (Object)(object)room != (Object)null && (Object)(object)room == (Object)(object)truckRoom))
			{
				return true;
			}
			Collider[] componentsInChildren = ((Component)truckRoom).GetComponentsInChildren<Collider>();
			Vector3 position = go.transform.position;
			Collider[] array = componentsInChildren;
			Bounds bounds;
			foreach (Collider val in array)
			{
				if (!((Object)(object)val == (Object)null) && val.enabled && val.isTrigger)
				{
					bounds = val.bounds;
					if (((Bounds)(ref bounds)).Contains(position))
					{
						return true;
					}
				}
			}
			array = componentsInChildren;
			foreach (Collider val2 in array)
			{
				if (!((Object)(object)val2 == (Object)null) && val2.enabled)
				{
					bounds = val2.bounds;
					if (((Bounds)(ref bounds)).Contains(position))
					{
						return true;
					}
				}
			}
			return false;
		}

		private List<RestorableCandidate> FindPurchasedTruckItems(RoomVolume truckRoom)
		{
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			List<RestorableCandidate> list = new List<RestorableCandidate>();
			foreach (ItemAttributes purchasedItemAttribute in GetPurchasedItemAttributes())
			{
				if ((Object)(object)purchasedItemAttribute == (Object)null || (Object)(object)purchasedItemAttribute.item == (Object)null)
				{
					continue;
				}
				GameObject physicalGameObject = GetPhysicalGameObject(purchasedItemAttribute);
				if (!((Object)(object)physicalGameObject == (Object)null) && !((Object)(object)physicalGameObject.GetComponent<ValuableObject>() != (Object)null))
				{
					string itemAssetName = GetItemAssetName(purchasedItemAttribute);
					if (!string.IsNullOrEmpty(itemAssetName) && IsInsideTruckRoom(physicalGameObject, truckRoom))
					{
						list.Add(new RestorableCandidate
						{
							Object = physicalGameObject,
							AssetName = itemAssetName,
							InstanceName = GetInstanceName(purchasedItemAttribute),
							LocalPosition = ((Component)truckRoom).transform.InverseTransformPoint(physicalGameObject.transform.position)
						});
					}
				}
			}
			return list;
		}

		private bool IsAuthority()
		{
			try
			{
				Type type = typeof(ItemManager).Assembly.GetType("SemiFunc");
				MethodInfo methodInfo = ((type != null) ? type.GetMethod("IsMasterClientOrSingleplayer", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) : null);
				if (methodInfo != null && methodInfo.ReturnType == typeof(bool) && methodInfo.GetParameters().Length == 0)
				{
					return (bool)methodInfo.Invoke(null, null);
				}
			}
			catch (Exception ex)
			{
				_log.LogWarning((object)("Could not check host authority: " + ex));
			}
			return true;
		}

		private bool CapturePurchasedTruckItems(bool manual)
		{
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Unknown result type (might be due to invalid IL or missing references)
			//IL_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!manual || !IsAuthority() || _restoreQueued)
				{
					return false;
				}
				RoomVolume val = FindTruckRoom();
				if ((Object)(object)val == (Object)null)
				{
					_uiStatus = "Save failed: truck not found. Try again inside the truck.";
					return false;
				}
				List<PurchasedItemSnapshot> list = new List<PurchasedItemSnapshot>();
				List<ItemAttributes> purchasedItemAttributes = GetPurchasedItemAttributes();
				int num = 0;
				int num2 = 0;
				int num3 = 0;
				foreach (ItemAttributes item in purchasedItemAttributes)
				{
					if ((Object)(object)item == (Object)null || (Object)(object)item.item == (Object)null)
					{
						continue;
					}
					GameObject physicalGameObject = GetPhysicalGameObject(item);
					if ((Object)(object)physicalGameObject == (Object)null)
					{
						continue;
					}
					if ((Object)(object)physicalGameObject.GetComponent<ValuableObject>() != (Object)null)
					{
						num3++;
					}
					else if (IsInsideTruckRoom(physicalGameObject, val))
					{
						num++;
						string itemAssetName = GetItemAssetName(item);
						if (string.IsNullOrEmpty(itemAssetName))
						{
							num2++;
							continue;
						}
						Quaternion localRotation = Quaternion.Inverse(((Component)val).transform.rotation) * physicalGameObject.transform.rotation;
						ItemBattery component = physicalGameObject.GetComponent<ItemBattery>();
						list.Add(new PurchasedItemSnapshot
						{
							itemAsset = itemAssetName,
							instanceName = GetInstanceName(item),
							localPosition = ((Component)val).transform.InverseTransformPoint(physicalGameObject.transform.position),
							localRotation = localRotation,
							batteryPercent = (((Object)(object)component != (Object)null) ? Mathf.RoundToInt(Mathf.Clamp(component.batteryLife, 0f, 100f)) : (-1))
						});
					}
				}
				_log.LogInfo((object)("Manual save scan: registeredPurchased=" + purchasedItemAttributes.Count + ", insideTruck=" + num + ", valuablesExcluded=" + num3 + ", missingAsset=" + num2 + ", savedCandidates=" + list.Count + "."));
				if (list.Count == 0)
				{
					_uiStatus = "Nothing to save. No registered purchased items were found inside the truck.";
					_log.LogWarning((object)"Manual save skipped: ItemManager purchase registry contained no eligible items inside the truck. Existing layout preserved.");
					return false;
				}
				list = list.OrderBy<PurchasedItemSnapshot, string>((PurchasedItemSnapshot entry) => entry.itemAsset, StringComparer.Ordinal).ThenBy<PurchasedItemSnapshot, string>((PurchasedItemSnapshot entry) => entry.instanceName, StringComparer.Ordinal).ThenBy((PurchasedItemSnapshot entry) => entry.localPosition.x)
					.ThenBy((PurchasedItemSnapshot entry) => entry.localPosition.y)
					.ThenBy((PurchasedItemSnapshot entry) => entry.localPosition.z)
					.ToList();
				string text = SerializeDocument(new PurchasedItemsDocument
				{
					formatVersion = 1,
					capturedUtc = DateTime.UtcNow.ToString("o"),
					items = list
				}, pretty: true);
				string text2 = _savePath + ".tmp";
				string text3 = _savePath + ".bak";
				byte[] bytes = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(text);
				using (FileStream fileStream = new FileStream(text2, FileMode.Create, FileAccess.Write, FileShare.None))
				{
					fileStream.Write(bytes, 0, bytes.Length);
					fileStream.Flush(flushToDisk: true);
				}
				if (File.Exists(_savePath))
				{
					try
					{
						if (File.Exists(text3))
						{
							File.Delete(text3);
						}
						File.Replace(text2, _savePath, text3, ignoreMetadataErrors: true);
					}
					catch (PlatformNotSupportedException)
					{
						File.Copy(_savePath, text3, overwrite: true);
						File.Delete(_savePath);
						File.Move(text2, _savePath);
					}
					catch (IOException)
					{
						File.Copy(_savePath, text3, overwrite: true);
						File.Delete(_savePath);
						File.Move(text2, _savePath);
					}
				}
				else
				{
					File.Move(text2, _savePath);
				}
				_savedLayoutExistedAtStartup = true;
				_restoreAttemptedThisSession = true;
				_lastJson = text;
				_uiStatus = "Saved " + list.Count + " purchased item(s)!";
				_log.LogInfo((object)("MANUAL SAVE: stored " + list.Count + " registry-confirmed purchased item(s); valuables excluded. Path: " + _savePath));
				return true;
			}
			catch (Exception ex3)
			{
				_uiStatus = "Save failed. Check LogOutput.log.";
				if (_log != null)
				{
					_log.LogError((object)("TruckDecorator manual save failed: " + ex3));
				}
				return false;
			}
		}

		private void OnGUI()
		{
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)_cachedTruckRoom == (Object)null))
			{
				if (Input.GetKeyDown((KeyCode)287))
				{
					CapturePurchasedTruckItems(manual: true);
				}
				float num = Mathf.Max(10f, (float)Screen.width - 250f - 20f);
				GUI.Box(new Rect(num - 8f, 12f, 266f, 88f), "TruckDecorator");
				if (GUI.Button(new Rect(num, 36f, 250f, 42f), "SAVE TRUCK LAYOUT"))
				{
					CapturePurchasedTruckItems(manual: true);
				}
				GUI.Label(new Rect(num, 80f, 250f, 20f), _uiStatus);
				GUI.Label(new Rect(num, 98f, 250f, 18f), "Keyboard shortcut: F6");
			}
		}
	}
	[Serializable]
	public sealed class PurchasedItemsDocument
	{
		public int formatVersion;

		public string capturedUtc;

		public List<PurchasedItemSnapshot> items = new List<PurchasedItemSnapshot>();
	}
	[Serializable]
	public sealed class PurchasedItemSnapshot
	{
		public string itemAsset;

		public string instanceName;

		public Vector3 localPosition;

		public Quaternion localRotation;

		public int batteryPercent;
	}
}