Decompiled source of CUCoreLib v1.1.0

CUCoreLib.dll

Decompiled 7 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Linq.Expressions;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using System.Security.Cryptography;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using CUCoreLib.Bootstrap;
using CUCoreLib.BugReporting;
using CUCoreLib.ContentReload;
using CUCoreLib.Data;
using CUCoreLib.Helpers;
using CUCoreLib.Networking;
using CUCoreLib.Patches;
using CUCoreLib.Registries;
using CUCoreLib.Registries.Infrastructure;
using CUCoreLib.Saving;
using Costura;
using HarmonyLib;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Collections.Generic;
using NAudio.Vorbis;
using NAudio.Wave;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using TMPro;
using UnityEngine;
using UnityEngine.Animations;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.Networking;
using UnityEngine.Playables;
using UnityEngine.Rendering.Universal;
using UnityEngine.SceneManagement;
using UnityEngine.Tilemaps;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("CUCoreLib")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("HP")]
[assembly: AssemblyProduct("CUCoreLib")]
[assembly: AssemblyCopyright("Copyright © HP 2025")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("dc5a5587-6134-4087-babe-7ad67496e316")]
[assembly: AssemblyFileVersion("1.1")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyVersion("1.1.0.0")]
internal class <Module>
{
	static <Module>()
	{
		AssemblyLoader.Attach(subscribe: true);
	}
}
public class SettingString : Setting
{
	public string value;

	public override object GetValue()
	{
		return value;
	}

	public override void SetValue(object val)
	{
		value = val?.ToString() ?? string.Empty;
	}
}
namespace CUCoreLib
{
	[BepInPlugin("net.cucorelib", "CUCoreLib", "1.1")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class CUCoreLibPlugin : BaseUnityPlugin
	{
		public const string GUID = "net.cucorelib";

		public const string MODNAME = "CUCoreLib";

		public const string VERSION = "1.1";

		private const string BepInExCoreConfigFileName = "BepInEx.cfg";

		private const string ConfigFileMutexName = "Local\\CUCoreLib.ConfigFile";

		private static readonly Mutex ConfigFileMutex = new Mutex(initiallyOwned: false, "Local\\CUCoreLib.ConfigFile");

		internal static ManualLogSource Log;

		public static CUCoreLibPlugin Instance { get; private set; }

		internal static ConfigFile SharedConfig { get; private set; }

		internal static ConfigFile GetOrCreateSharedConfig()
		{
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Expected O, but got Unknown
			if (SharedConfig != null)
			{
				return SharedConfig;
			}
			if (!EnterSharedConfigMutex())
			{
				throw new IOException("CUCoreLib config is busy.");
			}
			try
			{
				if (SharedConfig != null)
				{
					return SharedConfig;
				}
				SharedConfig = new ConfigFile(Path.Combine(Paths.ConfigPath, "CUCoreLib.cfg"), false)
				{
					SaveOnConfigSet = false
				};
				return SharedConfig;
			}
			finally
			{
				ConfigFileMutex.ReleaseMutex();
			}
		}

		internal static ConfigEntry<T> BindSharedConfig<T>(string section, string key, T defaultValue, string description)
		{
			ConfigFile orCreateSharedConfig = GetOrCreateSharedConfig();
			if (!EnterSharedConfigMutex())
			{
				ManualLogSource log = Log;
				if (log != null)
				{
					log.LogWarning((object)("CUCoreLib config is busy; '" + section + "." + key + "' was not saved."));
				}
				return orCreateSharedConfig.Bind<T>(section, key, defaultValue, description);
			}
			try
			{
				if (File.Exists(orCreateSharedConfig.ConfigFilePath))
				{
					orCreateSharedConfig.Reload();
				}
				ConfigEntry<T> result = orCreateSharedConfig.Bind<T>(section, key, defaultValue, description);
				orCreateSharedConfig.Save();
				return result;
			}
			catch (IOException ex)
			{
				ManualLogSource log2 = Log;
				if (log2 != null)
				{
					log2.LogWarning((object)("CUCoreLib could not save '" + section + "." + key + "': " + ex.Message));
				}
				return orCreateSharedConfig.Bind<T>(section, key, defaultValue, description);
			}
			finally
			{
				ConfigFileMutex.ReleaseMutex();
			}
		}

		internal static void SetSharedConfigValue<T>(ConfigEntry<T> entry, T value)
		{
			if (entry == null)
			{
				return;
			}
			if (!EnterSharedConfigMutex())
			{
				ManualLogSource log = Log;
				if (log != null)
				{
					log.LogWarning((object)"CUCoreLib config is busy; its latest changes were not saved.");
				}
				return;
			}
			try
			{
				ConfigFile orCreateSharedConfig = GetOrCreateSharedConfig();
				if (File.Exists(orCreateSharedConfig.ConfigFilePath))
				{
					orCreateSharedConfig.Reload();
				}
				entry.Value = value;
				orCreateSharedConfig.Save();
			}
			catch (IOException ex)
			{
				ManualLogSource log2 = Log;
				if (log2 != null)
				{
					log2.LogWarning((object)("CUCoreLib could not save its config: " + ex.Message));
				}
			}
			finally
			{
				ConfigFileMutex.ReleaseMutex();
			}
		}

		private static bool EnterSharedConfigMutex()
		{
			try
			{
				return ConfigFileMutex.WaitOne(TimeSpan.FromSeconds(5.0));
			}
			catch (AbandonedMutexException)
			{
				return true;
			}
		}

		internal static void RunWithConfigFileLock(Action action)
		{
			if (!EnterSharedConfigMutex())
			{
				throw new IOException("CUCoreLib config is busy.");
			}
			try
			{
				action();
			}
			finally
			{
				ConfigFileMutex.ReleaseMutex();
			}
		}

		private void Awake()
		{
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Expected O, but got Unknown
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			SharedConfig = GetOrCreateSharedConfig();
			BepInExConfigurationGuard.EnsureManagerIsHidden(Path.Combine(Paths.ConfigPath, "BepInEx.cfg"), ((BaseUnityPlugin)this).Logger);
			AssetLoader.Initialize(((BaseUnityPlugin)this).Logger);
			FileLoader.Initialize(((BaseUnityPlugin)this).Logger);
			LocaleLoader.Initialize(((BaseUnityPlugin)this).Logger);
			LaunchOverrideManager.Initialize();
			DebugWatchService.Initialize();
			ContentReloadManager.Initialize();
			SaveRegistry.RegisterBuiltIns();
			LiquidTileRegistry.RegisterBuiltIns();
			MultiplayerApi.RegisterBuiltIns();
			BuiltInCommandRegistrar.Register();
			UpdateChecker.Initialize(((BaseUnityPlugin)this).Logger);
			Harmony harmony = new Harmony("net.cucorelib");
			PatchApplier.ApplyAll(harmony);
			KrokMpCompatibilityPatches.Install(harmony);
			QoLUnknownCompatibilityPatches.Install(harmony);
			MultiplayerBridge.Initialize(harmony);
			MultiplayerSyncRegistry.ScheduleInitialSnapshot();
			((BaseUnityPlugin)this).Logger.LogInfo((object)"CUCoreLib is ready to sit in the background.");
		}
	}
	public class UpdateChecker : MonoBehaviour
	{
		private const string ApiUrl = "https://api.github.com/repos/jimmyking9999999/CUCoreLib/releases/latest";

		private const string UserAgent = "CUCoreLib";

		private static ManualLogSource _logger;

		private static UpdateChecker _instance;

		private static bool _initialized;

		private static bool _hasChecked;

		private static string _currentVersion;

		public static void Initialize(ManualLogSource logger)
		{
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Expected O, but got Unknown
			if (_initialized)
			{
				return;
			}
			_initialized = true;
			_logger = logger;
			if (Chainloader.PluginInfos.TryGetValue("net.cucorelib", out var value))
			{
				object obj;
				if (value == null)
				{
					obj = null;
				}
				else
				{
					BepInPlugin metadata = value.Metadata;
					obj = ((metadata != null) ? metadata.Version : null);
				}
				if ((Version?)obj != null)
				{
					_currentVersion = "v" + value.Metadata.Version;
					goto IL_0085;
				}
			}
			_currentVersion = "v1.1";
			goto IL_0085;
			IL_0085:
			GameObject val = new GameObject("CUCoreLib_UpdateChecker");
			Object.DontDestroyOnLoad((Object)(object)val);
			((Object)val).hideFlags = (HideFlags)61;
			_instance = val.AddComponent<UpdateChecker>();
			((MonoBehaviour)_instance).StartCoroutine(_instance.CheckForUpdates());
		}

		private IEnumerator CheckForUpdates()
		{
			if (_hasChecked)
			{
				yield break;
			}
			_hasChecked = true;
			UnityWebRequest request = UnityWebRequest.Get("https://api.github.com/repos/jimmyking9999999/CUCoreLib/releases/latest");
			try
			{
				request.SetRequestHeader("User-Agent", "CUCoreLib");
				yield return request.SendWebRequest();
				if ((int)request.result != 1)
				{
					yield return Notify("CUCoreLib could not check for updates.");
					yield break;
				}
				string latestTag = TryExtractTagName(request.downloadHandler.text);
				if (string.IsNullOrWhiteSpace(latestTag))
				{
					yield return Notify("CUCoreLib could not read the latest release version.");
					yield break;
				}
				if (IsNewer(_currentVersion, latestTag))
				{
					yield return Notify("CUCoreLib update available! " + _currentVersion + " -> " + latestTag, warning: true);
					yield break;
				}
				yield return Notify("CUCoreLib is up to date! Current: " + _currentVersion + ", Latest: " + latestTag);
			}
			finally
			{
				((IDisposable)request)?.Dispose();
			}
		}

		private static string TryExtractTagName(string json)
		{
			if (string.IsNullOrEmpty(json))
			{
				return null;
			}
			int num = json.IndexOf("\"tag_name\":\"", StringComparison.Ordinal);
			if (num < 0)
			{
				return null;
			}
			num += "\"tag_name\":\"".Length;
			int num2 = json.IndexOf('"', num);
			if (num2 < 0 || num2 <= num)
			{
				return null;
			}
			return json.Substring(num, num2 - num);
		}

		private static bool IsNewer(string current, string latest)
		{
			string input = NormalizeVersion(current);
			string input2 = NormalizeVersion(latest);
			if (Version.TryParse(input, out Version result) && Version.TryParse(input2, out Version result2))
			{
				return result2 > result;
			}
			return false;
		}

		private static string NormalizeVersion(string version)
		{
			return (version ?? string.Empty).Trim().TrimStart('v', 'V');
		}

		private IEnumerator Notify(string message, bool warning = false)
		{
			if (warning)
			{
				ManualLogSource logger = _logger;
				if (logger != null)
				{
					logger.LogWarning((object)message);
				}
			}
			else
			{
				ManualLogSource logger2 = _logger;
				if (logger2 != null)
				{
					logger2.LogInfo((object)message);
				}
			}
			ConsoleScript console = null;
			int attempts = 0;
			while ((Object)(object)console == (Object)null && attempts < 50)
			{
				console = (((Object)(object)ConsoleScript.instance != (Object)null) ? ConsoleScript.instance : Object.FindObjectOfType<ConsoleScript>());
				if ((Object)(object)console == (Object)null)
				{
					attempts++;
					yield return (object)new WaitForSecondsRealtime(0.2f);
				}
			}
			if ((Object)(object)console != (Object)null)
			{
				string consoleMessage = (warning ? ("<color=#FFA500>" + message + "</color>") : message);
				CUCoreUtils.ConsoleLog(console, consoleMessage);
			}
		}
	}
}
namespace CUCoreLib.Saving
{
	internal sealed class BuiltInBuildingEntitySaveProvider : IWorldSaveProvider
	{
		public int GetVersion()
		{
			return 2;
		}

		public JToken Capture(WorldSaveContext context)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_0139: Unknown result type (might be due to invalid IL or missing references)
			//IL_0148: Expected O, but got Unknown
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
			//IL_0102: Expected O, but got Unknown
			JArray val = new JArray();
			CustomBuildingRuntime[] activeRuntimes = BuildingEntityRegistry.GetActiveRuntimes();
			BuildingEntity val2 = default(BuildingEntity);
			foreach (CustomBuildingRuntime customBuildingRuntime in activeRuntimes)
			{
				if (!((Object)(object)customBuildingRuntime == (Object)null) && !string.IsNullOrWhiteSpace(customBuildingRuntime.DefinitionId) && ((Component)customBuildingRuntime).TryGetComponent<BuildingEntity>(ref val2))
				{
					val.Add((JToken)new JObject
					{
						["id"] = JToken.op_Implicit(customBuildingRuntime.DefinitionId),
						["position"] = (JToken)(object)Vector2Token(Vector2.op_Implicit(((Component)customBuildingRuntime).transform.position)),
						["rotation"] = JToken.op_Implicit(((Component)customBuildingRuntime).transform.eulerAngles.z),
						["scale"] = (JToken)(object)Vector3Token(((Component)customBuildingRuntime).transform.localScale),
						["health"] = JToken.op_Implicit(val2.GetHealth()),
						["blockPlacedOn"] = (JToken)(object)Vector2IntToken(val2.blockPlacedOn)
					});
				}
			}
			return (JToken)new JObject
			{
				["layer"] = JToken.op_Implicit(context.World?.biomeDepth ?? (-1)),
				["buildings"] = (JToken)(object)val
			};
		}

		public void Restore(WorldSaveContext context, JToken payload, int version, SaveRestoreContext contextForRestore)
		{
			JObject val = (JObject)(object)((payload is JObject) ? payload : null);
			JArray buildings = (JArray)((val != null) ? ((object)/*isinst with value type is only supported in some contexts*/) : ((object)((payload is JArray) ? payload : null)));
			JToken obj = ((payload is JObject) ? payload : null);
			int? layer = ((obj != null) ? obj.Value<int?>((object)"layer") : ((int?)null));
			if (buildings == null)
			{
				return;
			}
			contextForRestore.Defer(delegate
			{
				//IL_0117: Unknown result type (might be due to invalid IL or missing references)
				//IL_011c: Unknown result type (might be due to invalid IL or missing references)
				//IL_013c: Unknown result type (might be due to invalid IL or missing references)
				//IL_013e: Unknown result type (might be due to invalid IL or missing references)
				//IL_014f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0188: Unknown result type (might be due to invalid IL or missing references)
				//IL_018d: Unknown result type (might be due to invalid IL or missing references)
				//IL_01f9: Unknown result type (might be due to invalid IL or missing references)
				if (layer.HasValue && layer != WorldGeneration.world?.biomeDepth)
				{
					return;
				}
				CustomBuildingRuntime[] activeRuntimes = BuildingEntityRegistry.GetActiveRuntimes();
				foreach (CustomBuildingRuntime customBuildingRuntime in activeRuntimes)
				{
					if ((Object)(object)customBuildingRuntime != (Object)null)
					{
						Object.Destroy((Object)(object)((Component)customBuildingRuntime).gameObject);
					}
				}
				BuildingEntity building = default(BuildingEntity);
				foreach (JToken item in buildings)
				{
					string text = (string)item[(object)"id"];
					if (!BuildingEntityRegistry.TryGetDefinition(text, out var _))
					{
						ManualLogSource log = CUCoreLibPlugin.Log;
						if (log != null)
						{
							log.LogWarning((object)("CUCoreLib Save: Skipped unknown custom building '" + text + "'."));
						}
					}
					else
					{
						Vector2 val2 = ReadVector2(item[(object)"position"]);
						float valueOrDefault = ((float?)item[(object)"rotation"]).GetValueOrDefault();
						GameObject val3 = BuildingEntityRegistry.Spawn(text, Vector2.op_Implicit(val2), Quaternion.Euler(0f, 0f, valueOrDefault));
						if (!((Object)(object)val3 == (Object)null))
						{
							val3.transform.localScale = ReadVector3(item[(object)"scale"], val3.transform.localScale);
							if (val3.TryGetComponent<BuildingEntity>(ref building))
							{
								building.SetHealth(((float?)item[(object)"health"]) ?? building.GetHealth());
								BuildingEntityRegistry.RestoreSeating(val3, context.World, ReadVector2Int(item[(object)"blockPlacedOn"]));
							}
						}
					}
				}
			});
		}

		private static JObject Vector2Token(Vector2 value)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: 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_0035: Expected O, but got Unknown
			return new JObject
			{
				["x"] = JToken.op_Implicit(value.x),
				["y"] = JToken.op_Implicit(value.y)
			};
		}

		private static JObject Vector2IntToken(Vector2Int value)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Expected O, but got Unknown
			return new JObject
			{
				["x"] = JToken.op_Implicit(((Vector2Int)(ref value)).x),
				["y"] = JToken.op_Implicit(((Vector2Int)(ref value)).y)
			};
		}

		private static JObject Vector3Token(Vector3 value)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: 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_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_004c: Expected O, but got Unknown
			return new JObject
			{
				["x"] = JToken.op_Implicit(value.x),
				["y"] = JToken.op_Implicit(value.y),
				["z"] = JToken.op_Implicit(value.z)
			};
		}

		private static Vector2 ReadVector2(JToken token)
		{
			//IL_003d: 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_0045: Unknown result type (might be due to invalid IL or missing references)
			return new Vector2(((float?)((token != null) ? token[(object)"x"] : null)).GetValueOrDefault(), ((float?)((token != null) ? token[(object)"y"] : null)).GetValueOrDefault());
		}

		private static Vector2Int ReadVector2Int(JToken token)
		{
			//IL_003d: 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_0045: Unknown result type (might be due to invalid IL or missing references)
			return new Vector2Int(((int?)((token != null) ? token[(object)"x"] : null)).GetValueOrDefault(), ((int?)((token != null) ? token[(object)"y"] : null)).GetValueOrDefault());
		}

		private static Vector3 ReadVector3(JToken token, Vector3 fallback)
		{
			//IL_0009: 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_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_007c: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			if (token == null)
			{
				return fallback;
			}
			return new Vector3(((float?)token[(object)"x"]) ?? fallback.x, ((float?)token[(object)"y"]) ?? fallback.y, ((float?)token[(object)"z"]) ?? fallback.z);
		}
	}
	internal sealed class BuiltInBodyStatusSaveProvider : IBodySaveProvider
	{
		public int GetVersion()
		{
			return 1;
		}

		public JToken Capture(Body body)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			if ((Object)(object)body == (Object)null)
			{
				return null;
			}
			JArray val = new JArray();
			foreach (KeyValuePair<Type, BodyStatus> item in StatusRegistry.EnumerateBodyStatuses(body))
			{
				if (StatusRegistry.TryCapture(item.Value, out var payload))
				{
					val.Add((JToken)(object)payload);
				}
			}
			return (JToken)(object)((((JContainer)val).Count == 0) ? null : val);
		}

		public void Restore(Body body, JToken payload, int version, SaveRestoreContext context)
		{
			StatusRegistry.RestoreBodyStatuses(body, (JArray)(object)((payload is JArray) ? payload : null));
		}
	}
	internal sealed class BuiltInItemRuntimeSaveProvider : IItemSaveProvider
	{
		public int GetVersion()
		{
			return 2;
		}

		public JToken Capture(Item item, string itemKey)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			if ((Object)(object)item == (Object)null || !ItemRegistry.TryGetCustomInfo(item, out var _))
			{
				return null;
			}
			JObject val = new JObject();
			JObject val2 = ItemRegistry.CaptureRuntimeCustomData(item);
			if (val2 != null)
			{
				val["customData"] = (JToken)(object)val2;
			}
			if (ItemRegistryPatches.TryGetRuntimeIconOverride(item, out var sprite) && (Object)(object)sprite != (Object)null)
			{
				val["iconOverride"] = (JToken)(object)NetworkSnapshotSerialization.WriteSprite(sprite);
			}
			LightItem component = ((Component)item).GetComponent<LightItem>();
			if ((Object)(object)component != (Object)null)
			{
				val["lightEnabled"] = JToken.op_Implicit(component.shouldEnable);
			}
			return (JToken)(object)(((JToken)val).HasValues ? val : null);
		}

		public void Restore(Item item, string itemKey, JToken payload, int version, SaveRestoreContext context)
		{
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Invalid comparison between Unknown and I4
			if ((Object)(object)item == (Object)null)
			{
				return;
			}
			JObject val = (JObject)(object)((payload is JObject) ? payload : null);
			if (val == null || !ItemRegistry.TryGetCustomInfo(item, out var _))
			{
				return;
			}
			JToken obj = val["customData"];
			JObject val2 = (JObject)(object)((obj is JObject) ? obj : null);
			if (val2 != null)
			{
				ItemRegistry.RestoreRuntimeCustomData(item, val2);
			}
			JToken obj2 = val["iconOverride"];
			JObject val3 = (JObject)(object)((obj2 is JObject) ? obj2 : null);
			if (val3 != null)
			{
				ItemRegistryPatches.SetRuntimeIconOverride(item, NetworkSnapshotSerialization.ReadSprite((JToken)(object)val3));
			}
			else
			{
				ItemRegistryPatches.SetRuntimeIconOverride(item, null);
			}
			JToken val4 = val["lightEnabled"];
			if (val4 == null || (int)val4.Type == 10)
			{
				return;
			}
			bool enabled = Extensions.Value<bool>((IEnumerable<JToken>)val4);
			LightItem component = ((Component)item).GetComponent<LightItem>();
			if ((Object)(object)component == (Object)null)
			{
				context.Defer(delegate
				{
					ItemRegistryPatches.ApplyCustomItemRuntime(item);
					ApplyLightState(item, enabled);
				});
			}
			else
			{
				ApplyLightState(item, enabled);
			}
		}

		private static void ApplyLightState(Item item, bool enabled)
		{
			if ((Object)(object)item == (Object)null)
			{
				return;
			}
			LightItem component = ((Component)item).GetComponent<LightItem>();
			if (!((Object)(object)component == (Object)null))
			{
				component.shouldEnable = enabled;
				if ((Object)(object)component.light == (Object)null)
				{
					component.light = ((Component)item).GetComponentInChildren<Light2D>();
				}
				if ((Object)(object)component.light != (Object)null)
				{
					((Behaviour)component.light).enabled = enabled && !component.inContainer;
				}
			}
		}
	}
	internal sealed class BuiltInLimbStatusSaveProvider : ILimbSaveProvider
	{
		public int GetVersion()
		{
			return 1;
		}

		public JToken Capture(Limb limb, int limbIndex)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0016: Expected O, but got Unknown
			if ((Object)(object)limb == (Object)null)
			{
				return null;
			}
			JArray val = new JArray();
			foreach (KeyValuePair<Type, LimbStatus> item in StatusRegistry.EnumerateLimbStatuses(limb))
			{
				if (StatusRegistry.TryCapture(item.Value, out var payload))
				{
					val.Add((JToken)(object)payload);
				}
			}
			return (JToken)(object)((((JContainer)val).Count == 0) ? null : val);
		}

		public void Restore(Limb limb, int limbIndex, JToken payload, int version, SaveRestoreContext context)
		{
			StatusRegistry.RestoreLimbStatuses(limb, (JArray)(object)((payload is JArray) ? payload : null));
		}
	}
	internal sealed class BuiltInLiquidTileSaveProvider : IWorldSaveProvider
	{
		public int GetVersion()
		{
			return 2;
		}

		public JToken Capture(WorldSaveContext context)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: 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_004c: Expected O, but got Unknown
			return (JToken)new JObject
			{
				["layer"] = JToken.op_Implicit(context.World?.biomeDepth ?? (-1)),
				["mapping"] = (JToken)(object)LiquidTileRegistry.CaptureMappingSnapshot(),
				["world"] = (JToken)(object)LiquidTileRegistry.CaptureWorldStateSnapshot()
			};
		}

		public void Restore(WorldSaveContext context, JToken payload, int version, SaveRestoreContext contextForRestore)
		{
			JObject obj = (JObject)(object)((payload is JObject) ? payload : null);
			if (obj == null)
			{
				return;
			}
			int? layer = ((JToken)obj).Value<int?>((object)"layer");
			contextForRestore.Defer(delegate
			{
				if (layer.HasValue && layer != WorldGeneration.world?.biomeDepth)
				{
					obj["world"] = null;
				}
				LiquidTileRegistry.ApplyNetworkSnapshot(obj);
			});
		}
	}
	internal sealed class SaveItemEntry
	{
		public Item Item;

		public string Key;
	}
	internal static class SaveCoordinator
	{
		internal sealed class LoadState
		{
			internal readonly KrokMpSaveScope Scope;

			internal readonly JObject Payload;

			internal readonly Body Body;

			internal readonly PlayerCamera PlayerCamera;

			internal readonly WorldGeneration World;

			internal LoadState(KrokMpSaveScope scope, JObject payload, Body body, PlayerCamera playerCamera, WorldGeneration world)
			{
				Scope = scope;
				Payload = payload;
				Body = body;
				PlayerCamera = playerCamera;
				World = world;
			}
		}

		private const string RootKey = "CUCoreLib";

		private const string VersionKey = "version";

		private const string PayloadKey = "payload";

		private const int SchemaVersion = 1;

		private static bool _warnedUnsupportedKrokMpScope;

		internal static void EmbedIntoSaveFile()
		{
			try
			{
				if (TryGetSavePath(out var scope, out var path) && File.Exists(path))
				{
					string text = SaveSystem.Unzip(File.ReadAllBytes(path));
					JObject val = JObject.Parse(text);
					PlayerCamera main = PlayerCamera.main;
					Body body = (((Object)(object)main != (Object)null) ? main.body : null);
					JObject val2 = CapturePayload(scope, body, main, WorldGeneration.world);
					if (val2 != null)
					{
						val["CUCoreLib"] = (JToken)(object)val2;
						string text2 = JsonConvert.SerializeObject((object)val, (Formatting)0);
						File.WriteAllBytes(path, SaveSystem.Zip(text2));
					}
				}
			}
			catch (Exception ex)
			{
				SaveLogger.Warn("Failed to append CUCoreLib payload to save file.", ex);
			}
		}

		internal static LoadState PrepareRestoreFromSaveFile()
		{
			try
			{
				if (!TryGetSavePath(out var scope, out var path))
				{
					return null;
				}
				if (scope == KrokMpSaveScope.NotActive && (!SaveSystem.loadedRun || !SaveSystem.HasSave()))
				{
					return null;
				}
				if (!File.Exists(path))
				{
					return null;
				}
				string text = SaveSystem.Unzip(File.ReadAllBytes(path));
				JObject val = JObject.Parse(text);
				JToken obj = val["CUCoreLib"];
				JObject val2 = (JObject)(object)((obj is JObject) ? obj : null);
				if (val2 == null)
				{
					return null;
				}
				PlayerCamera main = PlayerCamera.main;
				return new LoadState(scope, val2, ((Object)(object)main != (Object)null) ? main.body : null, main, WorldGeneration.world);
			}
			catch (Exception ex)
			{
				SaveLogger.Warn("Failed to read CUCoreLib payload from save file.", ex);
				return null;
			}
		}

		internal static void ApplyRestore(LoadState state)
		{
			if (state == null || state.Payload == null || !SaveSystem.loadedRun)
			{
				return;
			}
			try
			{
				SaveRestoreContext saveRestoreContext = new SaveRestoreContext(state.Body, state.PlayerCamera, state.World);
				if (state.Scope != KrokMpSaveScope.Player)
				{
					JToken obj = state.Payload["global"];
					WarnUnknownProviders((JObject)(object)((obj is JObject) ? obj : null), SaveRegistry.GlobalProviderKeys, "global");
					JToken obj2 = state.Payload["world"];
					WarnUnknownProviders((JObject)(object)((obj2 is JObject) ? obj2 : null), SaveRegistry.WorldProviderKeys, "world");
					JToken obj3 = state.Payload["global"];
					ApplyGlobalProviders((JObject)(object)((obj3 is JObject) ? obj3 : null), saveRestoreContext);
					JToken obj4 = state.Payload["world"];
					ApplyWorldProviders((JObject)(object)((obj4 is JObject) ? obj4 : null), saveRestoreContext, state.Body, state.PlayerCamera, state.World);
				}
				if (state.Scope != KrokMpSaveScope.Shared && (Object)(object)state.Body != (Object)null)
				{
					ApplyBodyState(state.Body, state.Payload, saveRestoreContext);
					Body body = state.Body;
					JToken obj5 = state.Payload["items"];
					ApplyItemProviders(body, (JObject)(object)((obj5 is JObject) ? obj5 : null), saveRestoreContext);
				}
				saveRestoreContext.ExecuteDeferred();
			}
			catch (Exception ex)
			{
				SaveLogger.Warn("Unexpected failure while restoring CUCoreLib save payload D:", ex);
			}
		}

		internal static JObject CaptureBodyState(Body body)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			if ((Object)(object)body == (Object)null)
			{
				return null;
			}
			return new JObject
			{
				["version"] = JToken.op_Implicit(1),
				["body"] = (JToken)(object)CaptureBodyProviders(body),
				["limbs"] = (JToken)(object)CaptureLimbProviders(body)
			};
		}

		internal static void RestoreBodyState(Body body, JObject payload)
		{
			if (!((Object)(object)body == (Object)null) && payload != null)
			{
				SaveRestoreContext saveRestoreContext = new SaveRestoreContext(body, PlayerCamera.main, WorldGeneration.world);
				ApplyBodyState(body, payload, saveRestoreContext);
				saveRestoreContext.ExecuteDeferred();
			}
		}

		private static void ApplyBodyState(Body body, JObject payload, SaveRestoreContext context)
		{
			JToken obj = payload["body"];
			WarnUnknownProviders((JObject)(object)((obj is JObject) ? obj : null), SaveRegistry.BodyProviderKeys, "body");
			JToken obj2 = payload["body"];
			ApplyBodyProviders(body, (JObject)(object)((obj2 is JObject) ? obj2 : null), context);
			JToken obj3 = payload["limbs"];
			ApplyLimbProviders(body, (JArray)(object)((obj3 is JArray) ? obj3 : null), context);
		}

		private static JObject CapturePayload(KrokMpSaveScope scope, Body body, PlayerCamera playerCamera, WorldGeneration world)
		{
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Expected O, but got Unknown
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d6: Unknown result type (might be due to invalid IL or missing references)
			if (scope != KrokMpSaveScope.Shared && (Object)(object)body == (Object)null)
			{
				SaveLogger.Warn("Skipping custom save capture because the player body is not ready.");
				return null;
			}
			JObject val = new JObject { ["version"] = JToken.op_Implicit(1) };
			if (scope != KrokMpSaveScope.Player)
			{
				val["global"] = (JToken)(((object)CaptureGlobalProviders()) ?? ((object)new JObject()));
				val["world"] = (JToken)(((object)CaptureWorldProviders(body, playerCamera, world)) ?? ((object)new JObject()));
			}
			if (scope != KrokMpSaveScope.Shared)
			{
				val["body"] = (JToken)(((object)CaptureBodyProviders(body)) ?? ((object)new JObject()));
				val["limbs"] = (JToken)(((object)CaptureLimbProviders(body)) ?? ((object)new JArray()));
				val["items"] = (JToken)(((object)CaptureItemProviders(body)) ?? ((object)new JObject()));
			}
			return val;
		}

		private static JObject CaptureGlobalProviders()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			JObject val = new JObject();
			foreach (KeyValuePair<string, ICustomSaveProvider> entry in SaveRegistry.GlobalProviders)
			{
				CaptureProvider(entry.Key, entry.Value, val, () => entry.Value.Capture());
			}
			return val;
		}

		private static JObject CaptureBodyProviders(Body body)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Expected O, but got Unknown
			JObject val = new JObject();
			foreach (KeyValuePair<string, IBodySaveProvider> entry in SaveRegistry.BodyProviders)
			{
				CaptureProvider(entry.Key, entry.Value, val, () => entry.Value.Capture(body));
			}
			return val;
		}

		private static JArray CaptureLimbProviders(Body body)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Expected O, but got Unknown
			JArray val = new JArray();
			Limb[] array = body.limbs ?? Array.Empty<Limb>();
			for (int i = 0; i < array.Length; i++)
			{
				JObject val2 = new JObject();
				Limb limb = array[i];
				foreach (KeyValuePair<string, ILimbSaveProvider> entry in SaveRegistry.LimbProviders)
				{
					int limbIndex = i;
					CaptureProvider(entry.Key, entry.Value, val2, () => entry.Value.Capture(limb, limbIndex));
				}
				val.Add((JToken)(object)val2);
			}
			return val;
		}

		private static JObject CaptureItemProviders(Body body)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0028: Expected O, but got Unknown
			JObject val = new JObject();
			foreach (SaveItemEntry item2 in BuildItemEntries(body))
			{
				JObject val2 = new JObject();
				foreach (KeyValuePair<string, IItemSaveProvider> providerEntry in SaveRegistry.ItemProviders)
				{
					string itemKey = item2.Key;
					Item item = item2.Item;
					CaptureProvider(providerEntry.Key, providerEntry.Value, val2, () => providerEntry.Value.Capture(item, itemKey));
				}
				if (((JToken)val2).HasValues)
				{
					val[item2.Key] = (JToken)(object)val2;
				}
			}
			return val;
		}

		private static JObject CaptureWorldProviders(Body body, PlayerCamera playerCamera, WorldGeneration world)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Expected O, but got Unknown
			JObject val = new JObject();
			WorldSaveContext context = new WorldSaveContext(body, playerCamera, world);
			foreach (KeyValuePair<string, IWorldSaveProvider> entry in SaveRegistry.WorldProviders)
			{
				CaptureProvider(entry.Key, entry.Value, val, () => entry.Value.Capture(context));
			}
			return val;
		}

		private static void CaptureProvider(string key, object provider, JObject destination, Func<JToken> capture)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Invalid comparison between Unknown and I4
			try
			{
				JToken val = capture();
				if (val != null && (int)val.Type != 10)
				{
					int providerVersion = GetProviderVersion(provider);
					destination[key] = (JToken)(object)WrapPayload(val, providerVersion);
				}
			}
			catch (Exception ex)
			{
				SaveLogger.Warn("Provider '" + key + "' failed during save capture.", ex);
			}
		}

		private static void ApplyGlobalProviders(JObject payloadRoot, SaveRestoreContext context)
		{
			if (payloadRoot == null)
			{
				return;
			}
			foreach (JProperty item in payloadRoot.Properties())
			{
				if (!SaveRegistry.GlobalProviders.TryGetValue(item.Name, out var provider))
				{
					SaveLogger.Warn("Skipping missing global save provider '" + item.Name + "'.");
					continue;
				}
				string name = item.Name;
				JToken value = item.Value;
				RestoreProvider(name, (JObject)(object)((value is JObject) ? value : null), delegate(JToken payload, int version)
				{
					provider.Restore(payload, version, context);
				});
			}
		}

		private static void ApplyBodyProviders(Body body, JObject payloadRoot, SaveRestoreContext context)
		{
			if (payloadRoot == null)
			{
				return;
			}
			foreach (JProperty item in payloadRoot.Properties())
			{
				if (!SaveRegistry.BodyProviders.TryGetValue(item.Name, out var provider))
				{
					SaveLogger.Warn("Skipping missing body save provider '" + item.Name + "'.");
					continue;
				}
				string name = item.Name;
				JToken value = item.Value;
				RestoreProvider(name, (JObject)(object)((value is JObject) ? value : null), delegate(JToken payload, int version)
				{
					provider.Restore(body, payload, version, context);
				});
			}
		}

		private static void ApplyLimbProviders(Body body, JArray payloadRoot, SaveRestoreContext context)
		{
			if (payloadRoot == null || body.limbs == null)
			{
				return;
			}
			for (int i = 0; i < ((JContainer)payloadRoot).Count; i++)
			{
				if (i >= body.limbs.Length)
				{
					SaveLogger.Warn("Skipping saved limb payload at index " + i + " because that limb no longer exists.");
					continue;
				}
				JToken obj = payloadRoot[i];
				JObject val = (JObject)(object)((obj is JObject) ? obj : null);
				if (val == null)
				{
					continue;
				}
				WarnUnknownProviders(val, SaveRegistry.LimbProviderKeys, "limb[" + i + "]");
				foreach (JProperty item in val.Properties())
				{
					if (!SaveRegistry.LimbProviders.TryGetValue(item.Name, out var provider))
					{
						SaveLogger.Warn("Skipping missing limb save provider '" + item.Name + "' for limb index " + i + ".");
					}
					else
					{
						int limbIndex = i;
						Limb limb = body.limbs[i];
						string name = item.Name;
						JToken value = item.Value;
						RestoreProvider(name, (JObject)(object)((value is JObject) ? value : null), delegate(JToken payload, int version)
						{
							provider.Restore(limb, limbIndex, payload, version, context);
						});
					}
				}
			}
		}

		private static void ApplyItemProviders(Body body, JObject payloadRoot, SaveRestoreContext context)
		{
			if (payloadRoot == null)
			{
				return;
			}
			Dictionary<string, Item> dictionary = new Dictionary<string, Item>(StringComparer.Ordinal);
			foreach (SaveItemEntry item2 in BuildItemEntries(body))
			{
				dictionary[item2.Key] = item2.Item;
			}
			foreach (JProperty item3 in payloadRoot.Properties())
			{
				if (!dictionary.TryGetValue(item3.Name, out var item) || (Object)(object)item == (Object)null)
				{
					SaveLogger.Warn("Skipping saved item payload for missing item key '" + item3.Name + "'.");
					continue;
				}
				JToken value = item3.Value;
				JObject val = (JObject)(object)((value is JObject) ? value : null);
				if (val == null)
				{
					continue;
				}
				WarnUnknownProviders(val, SaveRegistry.ItemProviderKeys, "item[" + item3.Name + "]");
				foreach (JProperty item4 in val.Properties())
				{
					if (!SaveRegistry.ItemProviders.TryGetValue(item4.Name, out var provider))
					{
						SaveLogger.Warn("Skipping missing item save provider '" + item4.Name + "' for item key '" + item3.Name + "'.");
					}
					else
					{
						string itemKey = item3.Name;
						string name = item4.Name;
						JToken value2 = item4.Value;
						RestoreProvider(name, (JObject)(object)((value2 is JObject) ? value2 : null), delegate(JToken payload, int version)
						{
							provider.Restore(item, itemKey, payload, version, context);
						});
					}
				}
			}
		}

		private static void ApplyWorldProviders(JObject payloadRoot, SaveRestoreContext context, Body body, PlayerCamera playerCamera, WorldGeneration world)
		{
			if (payloadRoot == null)
			{
				return;
			}
			WorldSaveContext worldContext = new WorldSaveContext(body, playerCamera, world);
			foreach (JProperty item in payloadRoot.Properties())
			{
				if (!SaveRegistry.WorldProviders.TryGetValue(item.Name, out var provider))
				{
					SaveLogger.Warn("Skipping missing world save provider '" + item.Name + "'.");
					continue;
				}
				string name = item.Name;
				JToken value = item.Value;
				RestoreProvider(name, (JObject)(object)((value is JObject) ? value : null), delegate(JToken payload, int version)
				{
					provider.Restore(worldContext, payload, version, context);
				});
			}
		}

		private static void RestoreProvider(string key, JObject wrappedPayload, Action<JToken, int> restore)
		{
			if (wrappedPayload == null)
			{
				SaveLogger.Warn("Skipping malformed save payload for provider '" + key + "'.");
				return;
			}
			try
			{
				int valueOrDefault = ((JToken)wrappedPayload).Value<int?>((object)"version").GetValueOrDefault();
				JToken arg = wrappedPayload["payload"];
				restore(arg, valueOrDefault);
			}
			catch (Exception ex)
			{
				SaveLogger.Warn("Provider '" + key + "' failed during restore.", ex);
			}
		}

		private static JObject WrapPayload(JToken payload, int version)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Expected O, but got Unknown
			return new JObject
			{
				["version"] = JToken.op_Implicit(version),
				["payload"] = payload.DeepClone()
			};
		}

		private static int GetProviderVersion(object provider)
		{
			if (!(provider is ICustomSaveProvider customSaveProvider))
			{
				if (!(provider is IItemSaveProvider itemSaveProvider))
				{
					if (!(provider is IBodySaveProvider bodySaveProvider))
					{
						if (!(provider is ILimbSaveProvider limbSaveProvider))
						{
							if (provider is IWorldSaveProvider worldSaveProvider)
							{
								return Math.Max(0, worldSaveProvider.GetVersion());
							}
							return 0;
						}
						return Math.Max(0, limbSaveProvider.GetVersion());
					}
					return Math.Max(0, bodySaveProvider.GetVersion());
				}
				return Math.Max(0, itemSaveProvider.GetVersion());
			}
			return Math.Max(0, customSaveProvider.GetVersion());
		}

		private static List<SaveItemEntry> BuildItemEntries(Body body)
		{
			List<SaveItemEntry> list = new List<SaveItemEntry>();
			if ((Object)(object)body == (Object)null)
			{
				return list;
			}
			if (body.slots != null)
			{
				for (int i = 0; i < body.slots.Length; i++)
				{
					if (body.HoldingItem(i))
					{
						Item item = body.GetItem(i);
						if (!((Object)(object)item == (Object)null))
						{
							string text = "slot:" + i;
							list.Add(new SaveItemEntry
							{
								Key = text,
								Item = item
							});
							AppendContainerEntries(list, item, text);
						}
					}
				}
			}
			foreach (Item allWearable in body.GetAllWearables())
			{
				if (!((Object)(object)allWearable == (Object)null) && allWearable.Stats != null)
				{
					string text2 = (string.IsNullOrWhiteSpace(allWearable.Stats.wearSlotId) ? "unknown" : allWearable.Stats.wearSlotId);
					string text3 = "wear:" + text2;
					list.Add(new SaveItemEntry
					{
						Key = text3,
						Item = allWearable
					});
					AppendContainerEntries(list, allWearable, text3);
				}
			}
			return list;
		}

		private static void AppendContainerEntries(List<SaveItemEntry> entries, Item parentItem, string parentKey)
		{
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Expected O, but got Unknown
			if (entries == null || (Object)(object)parentItem == (Object)null || !Object.op_Implicit((Object)(object)((Component)parentItem).GetComponent<Container>()))
			{
				return;
			}
			int num = 0;
			Item item = default(Item);
			foreach (Transform item2 in ((Component)parentItem).transform)
			{
				Transform val = item2;
				if (!((Object)(object)val == (Object)null) && ((Component)val).TryGetComponent<Item>(ref item))
				{
					string key = parentKey + "/container:" + num;
					entries.Add(new SaveItemEntry
					{
						Key = key,
						Item = item
					});
					num++;
				}
			}
		}

		private static void WarnUnknownProviders(JObject payloadRoot, IEnumerable<string> knownKeys, string scope)
		{
			if (payloadRoot == null)
			{
				return;
			}
			HashSet<string> hashSet = new HashSet<string>(knownKeys, StringComparer.Ordinal);
			foreach (JProperty item in payloadRoot.Properties())
			{
				if (!hashSet.Contains(item.Name))
				{
					SaveLogger.Warn("Skipping unknown " + scope + " save provider '" + item.Name + "'.");
				}
			}
		}

		private static bool TryGetSavePath(out KrokMpSaveScope scope, out string path)
		{
			scope = MultiplayerBridge.GetKrokMpSaveScope(out var directory);
			switch (scope)
			{
			case KrokMpSaveScope.NotActive:
				path = Path.Combine(Application.persistentDataPath, "save.sv");
				return true;
			case KrokMpSaveScope.Shared:
			case KrokMpSaveScope.Player:
				path = Path.Combine(directory, "save.sv");
				return true;
			case KrokMpSaveScope.Client:
				path = null;
				return false;
			default:
				if (!_warnedUnsupportedKrokMpScope)
				{
					_warnedUnsupportedKrokMpScope = true;
					SaveLogger.Warn("Skipping CUCoreLib save-provider persistence because KrokMP's active save directory could not be resolved safely.");
				}
				path = null;
				return false;
			}
		}
	}
	internal static class SaveLogger
	{
		internal static void Warn(string message)
		{
			ManualLogSource log = CUCoreLibPlugin.Log;
			if (log != null)
			{
				log.LogWarning((object)(message ?? ""));
			}
		}

		internal static void Warn(string message, Exception ex)
		{
			ManualLogSource log = CUCoreLibPlugin.Log;
			if (log != null)
			{
				log.LogWarning((object)(message + "\n" + ex));
			}
		}
	}
	public interface ICustomSaveProvider
	{
		int GetVersion();

		JToken Capture();

		void Restore(JToken payload, int version, SaveRestoreContext context);
	}
	public interface IItemSaveProvider
	{
		int GetVersion();

		JToken Capture(Item item, string itemKey);

		void Restore(Item item, string itemKey, JToken payload, int version, SaveRestoreContext context);
	}
	public interface IBodySaveProvider
	{
		int GetVersion();

		JToken Capture(Body body);

		void Restore(Body body, JToken payload, int version, SaveRestoreContext context);
	}
	public interface ILimbSaveProvider
	{
		int GetVersion();

		JToken Capture(Limb limb, int limbIndex);

		void Restore(Limb limb, int limbIndex, JToken payload, int version, SaveRestoreContext context);
	}
	public interface IWorldSaveProvider
	{
		int GetVersion();

		JToken Capture(WorldSaveContext context);

		void Restore(WorldSaveContext context, JToken payload, int version, SaveRestoreContext contextForRestore);
	}
	public sealed class WorldSaveContext
	{
		private readonly Body _body;

		private readonly PlayerCamera _playerCamera;

		private readonly WorldGeneration _world;

		public Body Body => _body;

		public PlayerCamera PlayerCamera => _playerCamera;

		public WorldGeneration World => _world;

		public WorldSaveContext()
			: this(((Object)(object)PlayerCamera.main != (Object)null) ? PlayerCamera.main.body : null, PlayerCamera.main, WorldGeneration.world)
		{
		}

		internal WorldSaveContext(Body body, PlayerCamera playerCamera, WorldGeneration world)
		{
			_body = body;
			_playerCamera = playerCamera;
			_world = world;
		}
	}
	public sealed class SaveRestoreContext
	{
		private readonly List<Action> _deferredActions = new List<Action>();

		public Body Body { get; }

		public PlayerCamera PlayerCamera { get; }

		public WorldGeneration World { get; }

		internal SaveRestoreContext(Body body, PlayerCamera playerCamera, WorldGeneration world)
		{
			Body = body;
			PlayerCamera = playerCamera;
			World = world;
		}

		public void Defer(Action action)
		{
			if (action != null)
			{
				_deferredActions.Add(action);
			}
		}

		internal void ExecuteDeferred()
		{
			if (_deferredActions.Count != 0)
			{
				List<Action> actions = new List<Action>(_deferredActions);
				_deferredActions.Clear();
				CUCoreUtils.StartCoroutine(RunDeferred(actions));
			}
		}

		private static IEnumerator RunDeferred(List<Action> actions)
		{
			yield return null;
			foreach (Action action in actions)
			{
				try
				{
					action();
				}
				catch (Exception ex)
				{
					ManualLogSource log = CUCoreLibPlugin.Log;
					if (log != null)
					{
						log.LogWarning((object)("CUCoreLib Save: Deferred restore action failed.\n" + ex));
					}
				}
			}
		}
	}
}
namespace CUCoreLib.Registries
{
	internal static class DropPoolRegistry
	{
		private readonly struct WorldSpawnConfig
		{
			internal readonly float PerChunk;

			internal WorldSpawnConfig(float perChunk)
			{
				PerChunk = perChunk;
			}
		}

		private static readonly Dictionary<DropPool, List<string>> ExplicitPools = new Dictionary<DropPool, List<string>>();

		private static readonly Random PoolRandom = new Random();

		private static readonly Dictionary<string, Dictionary<string, double>> GenerationRolls = new Dictionary<string, Dictionary<string, double>>(StringComparer.OrdinalIgnoreCase);

		private static readonly Dictionary<string, Dictionary<string, int>> ResolvedCounts = new Dictionary<string, Dictionary<string, int>>(StringComparer.OrdinalIgnoreCase);

		private static readonly Dictionary<string, Dictionary<string, int>> HostCounts = new Dictionary<string, Dictionary<string, int>>(StringComparer.OrdinalIgnoreCase);

		private static string generationId;

		private static bool generationActive;

		private static readonly Dictionary<string, WorldSpawnConfig> WorldSpawnConfigs = new Dictionary<string, WorldSpawnConfig>(StringComparer.OrdinalIgnoreCase);

		private static readonly HashSet<string> WarnedInvalidWorldSpawn = new HashSet<string>(StringComparer.OrdinalIgnoreCase);

		private static readonly DropPool[] SingleSourceFlags = new DropPool[9]
		{
			DropPool.Corpse,
			DropPool.MedicalCrate,
			DropPool.FoodCrate,
			DropPool.ContainerCrate,
			DropPool.Trader1,
			DropPool.Trader2,
			DropPool.Trader3,
			DropPool.DropCapsule,
			DropPool.CapsuleContainer
		};

		private static readonly int GroundMask = LayerMask.GetMask(new string[1] { "Ground" });

		private static bool IsRemoteClient => MultiplayerBridge.IsRunning && !MultiplayerBridge.IsServer;

		internal static float ValidateSpawnFrequency(string id, float frequency)
		{
			if (float.IsNaN(frequency) || float.IsInfinity(frequency) || Math.Ceiling(frequency) > 2147483647.0)
			{
				ManualLogSource log = CUCoreLibPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("Custom item '" + id + "' disabled pooled spawning: spawnFrequency must be finite and fit an integer entry count."));
				}
				return 0f;
			}
			return Math.Max(0f, frequency);
		}

		internal static int GetEntryCount(string id, CustomItemInfo info, string poolKey)
		{
			id = SpawnIdHelpers.NormalizeSpawnId(id);
			double num = (info.FractionalSpawnFrequency.HasValue ? ((double)info.FractionalSpawnFrequency.Value) : ((double)Math.Max(0, info.SpawnFrequency)));
			int num2 = (int)Math.Floor(num);
			double num3 = num - (double)num2;
			if (IsRemoteClient)
			{
				if (HostCounts.TryGetValue(id, out var value) && value.TryGetValue(poolKey, out var value2) && value2 >= num2 && (double)value2 <= Math.Ceiling(num))
				{
					num2 = value2;
				}
			}
			else if (generationActive && num3 > 0.0)
			{
				if (!GenerationRolls.TryGetValue(id, out var value3))
				{
					value3 = (GenerationRolls[id] = new Dictionary<string, double>(StringComparer.Ordinal));
				}
				if (!value3.TryGetValue(poolKey, out var value4))
				{
					value4 = (value3[poolKey] = PoolRandom.NextDouble());
				}
				if (value4 < num3)
				{
					num2++;
				}
			}
			if (!ResolvedCounts.TryGetValue(id, out var value5))
			{
				value5 = (ResolvedCounts[id] = new Dictionary<string, int>(StringComparer.Ordinal));
			}
			value5[poolKey] = num2;
			return num2;
		}

		internal static void BeginGeneration()
		{
			if (IsRemoteClient)
			{
				RefreshPools();
				MultiplayerSyncRegistry.RequestInitialSnapshotForNewSession();
				return;
			}
			generationId = Guid.NewGuid().ToString("N");
			generationActive = true;
			GenerationRolls.Clear();
			HostCounts.Clear();
			RefreshPools();
			if (MultiplayerBridge.IsServer)
			{
				MultiplayerSyncRegistry.BroadcastSnapshot();
			}
		}

		internal static void ResetGeneration()
		{
			generationId = null;
			generationActive = false;
			GenerationRolls.Clear();
			HostCounts.Clear();
			RefreshPools();
		}

		private static void RefreshPools()
		{
			Rebuild();
			foreach (KeyValuePair<string, CustomItemInfo> item in ItemRegistry.RegisteredItems.OrderBy<KeyValuePair<string, CustomItemInfo>, string>((KeyValuePair<string, CustomItemInfo> entry) => entry.Key, StringComparer.Ordinal))
			{
				ItemLootPoolPatch.EnsureItemInLootPool(item.Key, (ItemInfo)(object)item.Value);
			}
		}

		internal static JObject CaptureNetworkSnapshot()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Expected O, but got Unknown
			//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_0107: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Expected O, but got Unknown
			JObject val = new JObject();
			foreach (KeyValuePair<string, Dictionary<string, int>> item in ResolvedCounts.OrderBy<KeyValuePair<string, Dictionary<string, int>>, string>((KeyValuePair<string, Dictionary<string, int>> entry) => entry.Key, StringComparer.Ordinal))
			{
				JObject val2 = new JObject();
				foreach (KeyValuePair<string, int> item2 in item.Value.OrderBy<KeyValuePair<string, int>, string>((KeyValuePair<string, int> entry) => entry.Key, StringComparer.Ordinal))
				{
					val2[item2.Key] = JToken.op_Implicit(item2.Value);
				}
				val[item.Key] = (JToken)(object)val2;
			}
			return new JObject
			{
				["generation"] = JToken.op_Implicit(generationId),
				["items"] = (JToken)(object)val
			};
		}

		internal static void ApplyNetworkSnapshot(JObject snapshot)
		{
			//IL_00c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Invalid comparison between Unknown and I4
			if (!IsRemoteClient)
			{
				return;
			}
			JToken obj = ((snapshot != null) ? snapshot["items"] : null);
			JObject val = (JObject)(object)((obj is JObject) ? obj : null);
			if (val == null)
			{
				return;
			}
			HostCounts.Clear();
			generationId = ((JToken)snapshot).Value<string>((object)"generation");
			foreach (JProperty item in val.Properties())
			{
				if (string.IsNullOrWhiteSpace(item.Name))
				{
					continue;
				}
				JToken value = item.Value;
				JObject val2 = (JObject)(object)((value is JObject) ? value : null);
				if (val2 == null)
				{
					continue;
				}
				Dictionary<string, int> dictionary = new Dictionary<string, int>(StringComparer.Ordinal);
				foreach (JProperty item2 in val2.Properties())
				{
					if ((int)item2.Value.Type == 6 && int.TryParse(((object)item2.Value).ToString(), out var result) && result >= 0)
					{
						dictionary[item2.Name] = result;
					}
				}
				HostCounts[SpawnIdHelpers.NormalizeSpawnId(item.Name)] = dictionary;
			}
			RefreshPools();
		}

		internal static void Rebuild()
		{
			ExplicitPools.Clear();
			WorldSpawnConfigs.Clear();
			ResolvedCounts.Clear();
			if (ItemRegistry.RegisteredItems == null)
			{
				return;
			}
			foreach (KeyValuePair<string, CustomItemInfo> item in ItemRegistry.RegisteredItems.OrderBy<KeyValuePair<string, CustomItemInfo>, string>((KeyValuePair<string, CustomItemInfo> entry) => entry.Key, StringComparer.Ordinal))
			{
				RegisterItem(item.Key, item.Value);
			}
		}

		internal static void RegisterItem(string id, CustomItemInfo info)
		{
			RemoveItem(id);
			if (!string.IsNullOrWhiteSpace(id) && info != null)
			{
				string id2 = SpawnIdHelpers.NormalizeSpawnId(id);
				RegisterFixedSources(id2, info);
				RegisterWorldSpawn(id2, info);
			}
		}

		internal static void RemoveItem(string id)
		{
			if (string.IsNullOrWhiteSpace(id))
			{
				return;
			}
			string normalizedId = SpawnIdHelpers.NormalizeSpawnId(id);
			foreach (List<string> value in ExplicitPools.Values)
			{
				value.RemoveAll((string itemId) => string.Equals(itemId, normalizedId, StringComparison.OrdinalIgnoreCase));
			}
			WorldSpawnConfigs.Remove(normalizedId);
			ResolvedCounts.Remove(normalizedId);
		}

		internal static bool UsesVanillaCategoryFallback(ItemInfo info)
		{
			if (!(info is CustomItemInfo customItemInfo))
			{
				return true;
			}
			return !customItemInfo.DropPool.HasValue && !customItemInfo.WorldSpawnPerChunk.HasValue;
		}

		internal static bool TryGetRandomItemId(DropPool source, string fallbackCategory, out string itemId)
		{
			itemId = null;
			List<string> value = null;
			if (!string.IsNullOrWhiteSpace(fallbackCategory) && ItemLootPool.pool != null)
			{
				ItemLootPool.pool.TryGetValue(fallbackCategory, out value);
			}
			if (value != null && value.Count == 0)
			{
				value = null;
			}
			ExplicitPools.TryGetValue(source, out var value2);
			if (value2 != null && value2.Count == 0)
			{
				value2 = null;
			}
			int num = value?.Count ?? 0;
			int num2 = value2?.Count ?? 0;
			int num3 = num + num2;
			if (num3 == 0)
			{
				return false;
			}
			int num4 = Random.Range(0, num3);
			itemId = ((num4 < num) ? value[num4] : value2[num4 - num]);
			return !string.IsNullOrWhiteSpace(itemId);
		}

		internal static void ScatterWorldSpawns(WorldGeneration world)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Invalid comparison between Unknown and I4
			if ((Object)(object)world == (Object)null || (int)world.biomeOverride > 0 || WorldSpawnConfigs.Count == 0)
			{
				return;
			}
			foreach (KeyValuePair<string, WorldSpawnConfig> worldSpawnConfig in WorldSpawnConfigs)
			{
				int num = Mathf.RoundToInt((float)(world.chunkWidth * world.chunkHeight) * worldSpawnConfig.Value.PerChunk);
				for (int i = 0; i < num; i++)
				{
					TrySpawnLooseWorldItem(world, worldSpawnConfig.Key);
				}
			}
		}

		private static void RegisterFixedSources(string id, CustomItemInfo info)
		{
			if (info == null || !info.DropPool.HasValue || info.DropPool.Value == DropPool.None)
			{
				return;
			}
			DropPool[] singleSourceFlags = SingleSourceFlags;
			for (int i = 0; i < singleSourceFlags.Length; i++)
			{
				DropPool dropPool = singleSourceFlags[i];
				if (info.DropPool.Value.HasFlag(dropPool))
				{
					int entryCount = GetEntryCount(id, info, "source:" + dropPool);
					if (!ExplicitPools.TryGetValue(dropPool, out var value))
					{
						value = new List<string>();
						ExplicitPools[dropPool] = value;
					}
					for (int j = 0; j < entryCount; j++)
					{
						value.Add(id);
					}
				}
			}
		}

		private static void RegisterWorldSpawn(string id, CustomItemInfo info)
		{
			if (info != null && info.WorldSpawnPerChunk.HasValue)
			{
				float value = info.WorldSpawnPerChunk.Value;
				if (value < 0f)
				{
					WarnInvalidWorldSpawnConfig(id, "DropPool world spawn requires WorldSpawnPerChunk >= 0.");
				}
				else
				{
					WorldSpawnConfigs[id] = new WorldSpawnConfig(value);
				}
			}
		}

		private static void WarnInvalidWorldSpawnConfig(string id, string message)
		{
			if (WarnedInvalidWorldSpawn.Add(id))
			{
				ManualLogSource log = CUCoreLibPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("Custom item '" + id + "' skipped world-spawn registration. " + message));
				}
			}
		}

		private static void TrySpawnLooseWorldItem(WorldGeneration world, string itemId)
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_007a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: 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)
			Vector2 val = default(Vector2);
			((Vector2)(ref val))..ctor(Random.Range(0f - (float)world.halfWidth, (float)world.halfWidth), Random.Range(0f - (float)world.halfHeight, (float)world.halfHeight));
			if (Object.op_Implicit((Object)(object)Physics2D.OverlapPoint(val, GroundMask)))
			{
				return;
			}
			RaycastHit2D val2 = Physics2D.Raycast(val, Vector2.down, (float)WorldGeneration.CHUNKSIZE, GroundMask);
			if (RaycastHit2D.op_Implicit(val2))
			{
				GameObject val3 = CustomInstantiate.InstantiateReturn(itemId, Vector2.op_Implicit(((RaycastHit2D)(ref val2)).point + Vector2.up), Quaternion.Euler(0f, 0f, Random.Range(0f, 360f)), 1f);
				Item val4 = default(Item);
				if (!((Object)(object)val3 == (Object)null) && val3.TryGetComponent<Item>(ref val4))
				{
					val4.SetCondition(1f);
				}
			}
		}
	}
	public static class BuildingEntityRegistry
	{
		private const string DefaultHitSoundReferenceId = "glowplant";

		public const int AllSpawnLayersMask = -1;

		private static readonly Dictionary<string, CustomBuildingEntityDefinition> RegisteredDefinitions = new Dictionary<string, CustomBuildingEntityDefinition>(StringComparer.OrdinalIgnoreCase);

		private static readonly Dictionary<string, GameObject> PrefabCache = new Dictionary<string, GameObject>(StringComparer.OrdinalIgnoreCase);

		private static readonly RegistrationOwnershipIndex<string> DefinitionOwners = new RegistrationOwnershipIndex<string>(StringComparer.OrdinalIgnoreCase);

		private static readonly HashSet<CustomBuildingRuntime> ActiveRuntimes = new HashSet<CustomBuildingRuntime>();

		private static readonly ItemDrop[] EmptyDrops = Array.Empty<ItemDrop>();

		private static readonly string[] EmptyCategories = Array.Empty<string>();

		private static readonly int GroundMask = LayerMask.GetMask(new string[1] { "Ground" });

		private static readonly int GroundLayer = LayerMask.NameToLayer("Ground");

		private static bool NetworkSpawnComponentsWarningLogged;

		private static readonly IReadOnlyDictionary<string, CustomBuildingEntityDefinition> ReadOnlyDefinitions = new ReadOnlyDictionary<string, CustomBuildingEntityDefinition>(RegisteredDefinitions);

		public static IReadOnlyDictionary<string, CustomBuildingEntityDefinition> RegisteredDefinitionsView => ReadOnlyDefinitions;

		public static event Action<string, CustomBuildingEntityDefinition, bool> Registered;

		public static void Register(string id, CustomBuildingEntityDefinition definition, Sprite icon = null)
		{
			if (definition != null && (Object)(object)icon != (Object)null)
			{
				definition.Sprite = icon;
			}
			Register(id, definition);
		}

		public static void Register(string id, CustomBuildingEntityDefinition definition)
		{
			ContentReloadSession.AssertAllowed(ContentReloadSurface.Buildings, "BuildingEntityRegistry.Register()", "Only basic/scriptless building definitions are supported during strict content reload.");
			if (string.IsNullOrWhiteSpace(id))
			{
				ManualLogSource log = CUCoreLibPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)"Ignored custom building registration with no ID.");
				}
				return;
			}
			id = id.Trim();
			if (definition == null)
			{
				definition = new CustomBuildingEntityDefinition();
			}
			definition.ID = id;
			bool arg = RegisteredDefinitions.ContainsKey(id);
			RegisteredDefinitions[id] = definition;
			DefinitionOwners.Assign(id, ContentReloadSession.ResolveAmbientOwnerId());
			PrefabCache.Remove(id);
			BuildingEntityRegistry.Registered?.Invoke(id, definition, arg);
			if (!string.IsNullOrEmpty(definition.Name))
			{
				LocaleRegistry.Register("building", id, definition.Name);
			}
			if (!string.IsNullOrEmpty(definition.Description))
			{
				LocaleRegistry.Register("building", id + "dsc", definition.Description);
			}
			MultiplayerSyncRegistry.QueueHostSnapshotBroadcast();
		}

		public static IDisposable BeginOwnerRegistration(string ownerId)
		{
			return DefinitionOwners.BeginScope(ownerId);
		}

		public static bool TryGetDefinition(string id, out CustomBuildingEntityDefinition definition)
		{
			definition = null;
			if (string.IsNullOrWhiteSpace(id))
			{
				return false;
			}
			return RegisteredDefinitions.TryGetValue(SpawnIdHelpers.NormalizeSpawnId(id), out definition);
		}

		public static bool TryGetRegisteredDefinition(string id, out CustomBuildingEntityDefinition definition)
		{
			return TryGetDefinition(id, out definition);
		}

		public static bool TryGetOwnerModGuid(string id, out string modGuid)
		{
			modGuid = null;
			if (string.IsNullOrWhiteSpace(id))
			{
				return false;
			}
			return DefinitionOwners.TryGetOwner(SpawnIdHelpers.NormalizeSpawnId(id), out modGuid) && !string.IsNullOrWhiteSpace(modGuid);
		}

		public static bool TryGetPrefab(string id, out GameObject prefab)
		{
			prefab = GetOrCreatePrefab(id);
			return (Object)(object)prefab != (Object)null;
		}

		public static IEnumerable<string> GetRegisteredIds()
		{
			return RegisteredDefinitions.Keys.ToArray();
		}

		public static IEnumerable<KeyValuePair<string, CustomBuildingEntityDefinition>> GetRegisteredDefinitions()
		{
			return RegisteredDefinitions.ToArray();
		}

		public static int LayerToMask(int layerNumber)
		{
			return SpawnLayerMask.FromLayerNumber(layerNumber);
		}

		public static int LayersToMask(int layerNumber)
		{
			return SpawnLayerMask.FromLayerNumber(layerNumber);
		}

		public static int LayersToMask(params int[] layerNumbers)
		{
			return SpawnLayerMask.Combine(layerNumbers);
		}

		public static int AllLayersExcept(int excludedLayerNumber)
		{
			return SpawnLayerMask.Excluding(new int[1] { excludedLayerNumber });
		}

		public static int AllLayersExcept(params int[] excludedLayerNumbers)
		{
			return SpawnLayerMask.Excluding(excludedLayerNumbers);
		}

		internal static void RegisterRuntime(CustomBuildingRuntime runtime)
		{
			if ((Object)(object)runtime != (Object)null)
			{
				ActiveRuntimes.Add(runtime);
			}
		}

		internal static void UnregisterRuntime(CustomBuildingRuntime runtime)
		{
			if ((Object)(object)runtime != (Object)null)
			{
				ActiveRuntimes.Remove(runtime);
			}
		}

		internal static CustomBuildingRuntime[] GetActiveRuntimes()
		{
			return ActiveRuntimes.Where((CustomBuildingRuntime runtime) => (Object)(object)runtime != (Object)null && ((Behaviour)runtime).isActiveAndEnabled).ToArray();
		}

		internal static void ClearWorldInstances()
		{
			CustomBuildingRuntime[] array = ActiveRuntimes.Where((CustomBuildingRuntime runtime) => (Object)(object)runtime != (Object)null).ToArray();
			foreach (CustomBuildingRuntime customBuildingRuntime in array)
			{
				customBuildingRuntime.DestroyForWorldClear();
			}
		}

		internal static Dictionary<string, CustomBuildingEntityDefinition> CaptureOwnerEntries(string ownerId)
		{
			if (string.IsNullOrWhiteSpace(ownerId))
			{
				return new Dictionary<string, CustomBuildingEntityDefinition>(StringComparer.OrdinalIgnoreCase);
			}
			CustomBuildingEntityDefinition value;
			return (from id in DefinitionOwners.GetKeys(ownerId)
				where RegisteredDefinitions.TryGetValue(id, out value)
				select id).ToDictionary<string, string, CustomBuildingEntityDefinition>((string id) => id, (string id) => RegisteredDefinitions[id], StringComparer.OrdinalIgnoreCase);
		}

		internal static void RestoreOwnerEntries(string ownerId, IDictionary<string, CustomBuildingEntityDefinition> entries)
		{
			if (entries == null || entries.Count == 0)
			{
				return;
			}
			foreach (KeyValuePair<string, CustomBuildingEntityDefinition> entry in entries)
			{
				Register(entry.Key, entry.Value);
			}
		}

		internal static void ClearOwnerEntries(string ownerId, ContentReloadResult result)
		{
			if (!string.IsNullOrWhiteSpace(ownerId))
			{
				string text = ownerId.Trim();
				string[] keys = DefinitionOwners.GetKeys(text);
				foreach (string key in keys)
				{
					RegisteredDefinitions.Remove(key);
					DefinitionOwners.Remove(key);
					PrefabCache.Remove(key);
				}
				if (keys.Length != 0)
				{
					result?.AddInfo("Cleared " + keys.Length + " building registrations owned by '" + text + "'.");
				}
			}
		}

		internal static void RefreshLiveInstances(IEnumerable<string> definitionIds = null)
		{
			HashSet<string> hashSet = ((definitionIds != null) ? new HashSet<string>(from id in definitionIds
				where !string.IsNullOrWhiteSpace(id)
				select id.Trim(), StringComparer.OrdinalIgnoreCase) : null);
			CustomBuildingRuntime[] activeRuntimes = GetActiveRuntimes();
			foreach (CustomBuildingRuntime customBuildingRuntime in activeRuntimes)
			{
				if (!((Object)(object)customBuildingRuntime == (Object)null) && !string.IsNullOrWhiteSpace(customBuildingRuntime.DefinitionId) && (hashSet == null || hashSet.Contains(customBuildingRuntime.DefinitionId)))
				{
					RefreshLiveInstance(((Component)customBuildingRuntime).gameObject, customBuildingRuntime.DefinitionId);
				}
			}
		}

		internal static JObject CaptureNetworkSnapshot()
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Unknown result type (might be due to invalid IL or missing references)
			//IL_018c: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0202: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_0230: Unknown result type (might be due to invalid IL or missing references)
			//IL_0247: Unknown result type (might be due to invalid IL or missing references)
			//IL_025e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0265: Unknown result type (might be due to invalid IL or missing references)
			//IL_026f: Expected I4, but got Unknown
			//IL_0275: Unknown result type (might be due to invalid IL or missing references)
			//IL_028c: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0316: Unknown result type (might be due to invalid IL or missing references)
			//IL_032d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0344: Unknown result type (might be due to invalid IL or missing references)
			//IL_035b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0372: Unknown result type (might be due to invalid IL or missing references)
			//IL_0389: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e5: Unknown result type (might be due to invalid IL or missing references)
			//IL_0405: Unknown result type (might be due to invalid IL or missing references)
			//IL_0425: Unknown result type (might be due to invalid IL or missing references)
			//IL_0457: Unknown result type (might be due to invalid IL or missing references)
			//IL_046e: Unknown result type (might be due to invalid IL or missing references)
			//IL_048e: Unknown result type (might be due to invalid IL or missing references)
			//IL_04a5: Unknown result type (might be due to invalid IL or missing references)
			//IL_04bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_04ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_04f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0510: Unknown result type (might be due to invalid IL or missing references)
			//IL_0529: Expected O, but got Unknown
			JObject val = new JObject();
			foreach (KeyValuePair<string, CustomBuildingEntityDefinition> registeredDefinition in RegisteredDefinitions)
			{
				CustomBuildingEntityDefinition value = registeredDefinition.Value;
				if (value != null)
				{
					JObject val2 = new JObject
					{
						["name"] = JToken.op_Implicit(value.Name ?? string.Empty),
						["description"] = JToken.op_Implicit(value.Description ?? string.Empty),
						["sprite"] = (JToken)(object)NetworkSnapshotSerialization.WriteSprite(value.Sprite),
						["sortingOrder"] = JToken.op_Implicit(value.SortingOrder),
						["useGlowPlantMaterial"] = JToken.op_Implicit(value.UseGlowPlantMaterial),
						["scaleX"] = JToken.op_Implicit(value.Scale.x),
						["scaleY"] = JToken.op_Implicit(value.Scale.y),
						["scaleZ"] = JToken.op_Implicit(value.Scale.z),
						["colliderSizeX"] = JToken.op_Implicit(value.ColliderSize?.x),
						["colliderSizeY"] = JToken.op_Implicit(value.ColliderSize?.y),
						["colliderOffsetX"] = JToken.op_Implicit(value.ColliderOffset?.x),
						["colliderOffsetY"] = JToken.op_Implicit(value.ColliderOffset?.y),
						["colliderIsTrigger"] = JToken.op_Implicit(value.ColliderIsTrigger),
						["layer"] = JToken.op_Implicit(ResolveAssignedLayer(value)),
						["addRigidbody2D"] = JToken.op_Implicit(value.AddRigidbody2D),
						["damagePlayerOnImpact"] = JToken.op_Implicit(value.DamagePlayerOnImpact),
						["rigidbodyBodyType"] = JToken.op_Implicit((int)value.RigidbodyBodyType),
						["rigidbodyGravityScale"] = JToken.op_Implicit(value.RigidbodyGravityScale),
						["health"] = JToken.op_Implicit(value.Health),
						["requireGround"] = JToken.op_Implicit(value.RequireGround),
						["metallic"] = JToken.op_Implicit(value.Metallic),
						["cantHit"] = JToken.op_Implicit(value.CantHit),
						["animal"] = JToken.op_Implicit(value.Animal),
						["ignoreBodyOptimize"] = JToken.op_Implicit(value.IgnoreBodyOptimize),
						["dropChanceMultiplier"] = JToken.op_Implicit(value.DropChanceMultiplier),
						["placement"] = JToken.op_Implicit((int)value.Placement),
						["generationStyle"] = JToken.op_Implicit((int)value.GenerationStyle),
						["spawnMinPerChunk"] = JToken.op_Implicit(value.SpawnMinPerChunk),
						["spawnMaxPerChunk"] = JToken.op_Implicit(value.SpawnMaxPerChunk),
						["spawnLayers"] = JToken.op_Implicit(value.SpawnLayers),
						["surfaceOffset"] = JToken.op_Implicit(value.SurfaceOffset),
						["randomFlip"] = JToken.op_Implicit(value.RandomFlip),
						["spawnInGround"] = JToken.op_Implicit(value.SpawnInGround),
						["hitSoundReferenceId"] = JToken.op_Implicit(value.HitSoundReferenceId ?? string.Empty),
						["spriteAnimationId"] = JToken.op_Implicit(value.SpriteAnimationId ?? string.Empty),
						["hitSound"] = JToken.op_Implicit(NetworkSnapshotSerialization.WriteStringOrEmpty(((Object)(object)value.HitSound != (Object)null) ? ((Object)value.HitSound).name : null)),
						["blockFootstepSoundId"] = JToken.op_Implicit(value.BlockFootstepSoundId),
						["renderReferenceId"] = JToken.op_Implicit(value.RenderReferenceId ?? string.Empty),
						["copyGlowPlantLayer"] = JToken.op_Implicit(value.CopyGlowPlantLayer),
						["heatRadius"] = JToken.op_Implicit(value.HeatRadius),
						["heatPerSecond"] = JToken.op_Implicit(value.HeatPerSecond),
						["maxHeatBodyTemperature"] = JToken.op_Implicit(value.MaxHeatBodyTemperature),
						["spawnComponents"] = (JToken)((value.SpawnComponents != null) ? ((object)JArray.FromObject((object)value.SpawnComponents)) : ((object)new JArray())),
						["components"] = (JToken)(object)NetworkSnapshotSerialization.WriteTypeNames(value.Components)
					};
					if (value.ItemsDropOnDestroy != null)
					{
						val2["itemsDropOnDestroy"] = (JToken)(object)JArray.FromObject((object)value.ItemsDropOnDestroy);
					}
					if (value.AlwaysDrop != null)
					{
						val2["alwaysDrop"] = (JToken)(object)JArray.FromObject((object)value.AlwaysDrop);
					}
					if (value.ItemCategoriesToAdd != null)
					{
						val2["itemCategoriesToAdd"] = (JToken)(object)JArray.FromObject((object)value.ItemCategoriesToAdd);
					}
					val[registeredDefinition.Key] = (JToken)(object)val2;
				}
			}
			return val;
		}

		internal static void ApplyNetworkSnapshot(JObject snapshot)
		{
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Unknown result type (might be due to invalid IL or missing references)
			//IL_0192: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fe: 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)
			if (snapshot == null)
			{
				return;
			}
			foreach (JProperty item in snapshot.Properties())
			{
				string name = item.Name;
				JToken value = item.Value;
				JObject val = (JObject)(object)((value is JObject) ? value : null);
				if (!string.IsNullOrWhiteSpace(name) && val != null)
				{
					RegisteredDefinitions.TryGetValue(name, out var value2);
					CustomBuildingEntityDefinition customBuildingEntityDefinition = new CustomBuildingEntityDefinition
					{
						Name = ((JToken)val).Value<string>((object)"name"),
						Description = ((JToken)val).Value<string>((object)"description"),
						Sprite = NetworkSnapshotSerialization.ReadSprite(val["sprite"]),
						SortingOrder = (((JToken)val).Value<int?>((object)"sortingOrder") ?? 5),
						UseGlowPlantMaterial = (((JToken)val).Value<bool?>((object)"useGlowPlantMaterial") == true),
						Scale = new Vector3(((JToken)val).Value<float?>((object)"scaleX") ?? 1f, ((JToken)val).Value<float?>((object)"scaleY") ?? 1f, ((JToken)val).Value<float?>((object)"scaleZ") ?? 1f),
						ColliderSize = ((HasValue(val["colliderSizeX"]) || HasValue(val["colliderSizeY"])) ? new Vector2?(new Vector2(((JToken)val).Value<float?>((object)"colliderSizeX").GetValueOrDefault(), ((JToken)val).Value<float?>((object)"colliderSizeY").GetValueOrDefault())) : ((Vector2?)null)),
						ColliderOffset = ((HasValue(val["colliderOffsetX"]) || HasValue(val["colliderOffsetY"])) ? new Vector2?(new Vector2(((JToken)val).Value<float?>((object)"colliderOffsetX").GetValueOrDefault(), ((JToken)val).Value<float?>((object)"colliderOffsetY").GetValueOrDefault())) : ((Vector2?)null)),
						ColliderIsTrigger = (((JToken)val).Value<bool?>((object)"colliderIsTrigger") == true),
						Layer = ((JToken)val).Value<int?>((object)"layer"),
						AddRigidbody2D = (((JToken)val).Value<bool?>((object)"addRigidbody2D") == true),
						DamagePlayerOnImpact = (((JToken)val).Value<bool?>((object)"damagePlayerOnImpact") == true),
						RigidbodyBodyType = (RigidbodyType2D)((JToken)val).Value<int?>((object)"rigidbodyBodyType").GetValueOrDefault(),
						RigidbodyGravityScale = (((JToken)val).Value<float?>((object)"rigidbodyGravityScale") ?? 1f),
						Health = (((JToken)val).Value<float?>((object)"health") ?? 250f),
						RequireGround = (((JToken)val).Value<bool?>((object)"requireGround") ?? true),
						Metallic = (((JToken)val).Value<bool?>((object)"metallic") == true),
						CantHit = (((JToken)val).Value<bool?>((object)"cantHit") == true),
						Animal = (((JToken)val).Value<bool?>((object)"animal") == true),
						IgnoreBodyOptimize = (((JToken)val).Value<bool?>((object)"ignoreBodyOptimize") == true),
						DropChanceMultiplier = (((JToken)val).Value<float?>((object)"dropChanceMultiplier") ?? 1f),
						Placement = ReadEnum(val["placement"], BuildingPlacementType.Floor),
						GenerationStyle = ReadEnum(val["generationStyle"], BuildingGenerationStyle.None),
						SpawnMinPerChunk = ((JToken)val).Value<float?>((object)"spawnMinPerChunk").GetValueOrDefault(),
						SpawnMaxPerChunk = ((JToken)val).Value<float?>((object)"spawnMaxPerChunk").GetValueOrDefault(),
						SpawnLayers = (((JToken)val).Value<int?>((object)"spawnLayers") ?? (-1)),
						SurfaceOffset = (((JToken)val).Value<float?>((object)"surfaceOffset") ?? 0.5f),
						RandomFlip = (((JToken)val).Value<bool?>((object)"randomFlip") ?? true),
						SpawnInGround = (((JToken)val).Value<bool?>((object)"spawnInGround") == true),
						HitSoundReferenceId = ((JToken)val).Value<string>((object)"hitSoundReferenceId"),
						SpriteAnimationId = (((JToken)val).Value<string>((object)"spriteAnimationId") ?? value2?.SpriteAnimationId),
						HitSound = value2?.HitSound,
						PlaceCheck = value2?.PlaceCheck,
						BlockFootstepSoundId = ((JToken)val).Value<ushort?>((object)"blockFootstepSoundId").GetValueOrDefault(),
						RenderReferenceId = ((JToken)val).Value<string>((object)"renderReferenceId"),
						CopyGlowPlantLayer = (((JToken)val).Value<bool?>((object)"copyGlowPlantLayer") == true),
						HeatRadius = ((JToken)val).Value<float?>((object)"heatRadius").GetValueOrDefault(),
						HeatPerSecond = ((JToken)val).Value<float?>((object)"heatPerSecond").GetValueOrDefault(),
						MaxHeatBodyTemperature = ((JToken)val).Value<float?>((object)"maxHeatBodyTemperature").GetValueOrDefault(),
						SpawnComponents = (value2?.SpawnComponents ?? new List<string>()),
						Components = (value2?.Components ?? NetworkSnapshotSerialization.ReadTypeNames(val["components"])),
						ConfigurePrefab = value2?.ConfigurePrefab,
						ConfigureInstance = value2?.ConfigureInstance
					};
					if (val["spawnComponents"] is JArray)
					{
						WarnIgnoredNetworkSpawnComponents();
					}
					JToken obj = val["itemsDropOnDestroy"];
					JArray val2 = (JArray)(object)((obj is JArray) ? obj : null);
					if (val2 != null)
					{
						customBuildingEntityDefinition.ItemsDropOnDestroy = ((JToken)val2).ToObject<ItemDrop[]>();
					}
					JToken obj2 = val["alwaysDrop"];
					JArray val3 = (JArray)(object)((obj2 is JArray) ? obj2 : null);
					if (val3 != null)
					{
						customBuildingEntityDefinition.AlwaysDrop = ((JToken)val3).ToObject<ItemDrop[]>();
					}
					JToken obj3 = val["itemCategoriesToAdd"];
					JArray val4 = (JArray)(object)((obj3 is JArray) ? obj3 : null);
					if (val4 != null)
					{
						customBuildingEntityDefinition.ItemCategoriesToAdd = ((JToken)val4).ToObject<string[]>();
					}
					Register(name, customBuildingEntityDefinition);
				}
			}
		}

		private static void WarnIgnoredNetworkSpawnComponents()
		{
			if (!NetworkSpawnComponentsWarningLogged)
			{
				NetworkSpawnComponentsWarningLogged = true;
			}
		}

		public static bool Contains(string id)
		{
			return IsRegistered(id);
		}

		public static GameObject Spawn(string id, Vector3 position)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return Spawn(id, position, Quaternion.identity);
		}

		public static GameObject Spawn(string id, Vector3 position, Quaternion rotation)
		{
			//IL_006e: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			if (string.IsNullOrWhiteSpace(id))
			{
				ManualLogSource log = CUCoreLibPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)"No custom building ID provided.");
				}
				return null;
			}
			id = SpawnIdHelpers.NormalizeSpawnId(id);
			GameObject orCreatePrefab = GetOrCreatePrefab(id);
			if ((Object)(object)orCreatePrefab == (Object)null)
			{
				ManualLogSource log2 = CUCoreLibPlugin.Log;
				if (log2 != null)
				{
					log2.LogWarning((object)("Could not spawn custom building '" + id.Trim() + "' because it is not registered."));
				}
				return null;
			}
			GameObject val = CustomInstantiate.InstantiateInActiveScene(orCreatePrefab, position, rotation);
			val.SetActive(true);
			return val;
		}

		public static GameObject PlaceOnSurface(string id, Vector2 origin, Vector2 direction, WorldGeneration world = null)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0002: 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_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_006d: 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_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			if (direction == Vector2.zero)
			{
				direction = Vector2.down;
			}
			if (!TryGetDefinition(id, out var definition))
			{
				return null;
			}
			world = world ?? WorldGeneration.world;
			RaycastHit2D val = Physics2D.Raycast(origin, ((Vector2)(ref direction)).normalized, (float)WorldGeneration.CHUNKSIZE, GroundMask);
			if (!RaycastHit2D.op_Implicit(val))
			{
				return null;
			}
			Vector2 val2 = ((RaycastHit2D)(ref val)).point - ((Vector2)(ref direction)).normalized * definition.SurfaceOffset;
			GameObject val3 = Spawn(id, Vector2.op_Implicit(val2), Quaternion.identity);
			if ((Object)(object)val3 == (Object)null)
			{
				return null;
			}
			ApplyPlacement(val3, definition, direction);
			SetBlockSeating(val3, world, ((RaycastHit2D)(ref val)).point + ((Vector2)(ref direction)).normalized * 0.5f);
			return val3;
		}

		public static void DistributeInWorld(string id, WorldGeneration world)
		{
			if ((Object)(object)world == (Object)null || !TryGetDefinition(id, out var definition) || definition.GenerationStyle == BuildingGenerationStyle.None || !CanSpawnInLayer(definition, world.biomeDepth))
			{
				return;
			}
			GameObject orCreatePrefab = GetOrCreatePrefab(id);
			if ((Object)(object)orCreatePrefab == (Object)null)
			{
				return;
			}
			int num = Mathf.RoundToInt((float)(world.chunkWidth * world.chunkHeight) * Random.Range(definition.SpawnMinPerChunk, definition.SpawnMaxPerChunk));
			for (int i = 0; i < num; i++)
			{
				if (definition.GenerationStyle == BuildingGenerationStyle.DropPod)
				{
					DistributeDropPod(world, id, definition);
				}
				else
				{
					DistributeStandard(world, id, definition);
				}
			}
		}

		public static ItemDrop AddDrop(string id, float chance = 1f, float conditionMin = 1f, float conditionMax = 1f)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Unknown result type (might be due to invalid IL or missing references)
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Expected O, but got Unknown
			return new ItemDrop
			{
				id = id,
				chance = chance,
				conditionMin = conditionMin,
				conditionMax = conditionMax
			};
		}

		public static ItemDrop AddDrop(ICollection<ItemDrop> drops, string id, float chance = 1f, float conditionMin = 1f, float conditionMax = 1f)
		{
			ItemDrop val = AddDrop(id, chance, conditionMin, conditionMax);
			drops?.Add(val);
			return val;
		}

		internal static GameObject GetOrCreatePrefab(string id)
		{
			if (string.IsNullOrWhiteSpace(id))
			{
				return null;
			}
			id = id.Trim();
			if (PrefabCache.TryGetValue(id, out var value) && (Object)(object)value != (Object)null)
			{
				return value;
			}
			if (!RegisteredDefinitions.TryGetValue(id, out var value2))
			{
				ManualLogSource log = CUCoreLibPlugin.Log;
				if (log != null)
				{
					log.LogWarning((object)("No custom building definition was registered for '" + id + "'."));
				}
				return null;
			}
			GameObject val = CreatePrefab(id, value2);
			if ((Object)(object)val == (Object)null)
			{
				return null;
			}
			PrefabCache[id] = val;
			return val;
		}

		public static bool IsRegistered(string id)
		{
			return !string.IsNullOrWhiteSpace(id) && RegisteredDefinitions.ContainsKey(id.Trim());
		}

		internal static void ApplyInstanceConfiguration(GameObject instance, string id)
		{
			if (!((Object)(object)instance == (Object)null) && !string.IsNullOrWhiteSpace(id) && RegisteredDefinitions.TryGetValue(id.Trim(), out var value))
			{
				value.ConfigureInstance?.Invoke(instance);
			}
		}

		internal static void SpawnDrops(BuildingEntity source, string id)
		{
			//IL_0046: 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)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			if (!((Object)(object)source == (Object)null) && TryGetDefinition(id, out var definition))
			{
				bool isNearPlayer = (Object)(object)PlayerCamera.main != (Object)null && (Object)(object)PlayerCamera.main.body != (Object)null && Vector2.Distance(Vector2.op_Implicit(((Component)source).transform.position), Vector2.op_Implicit(((Component)PlayerCamera.main.body).transform.position)) < 8f;
				SpawnDropArray(source, definition.ItemsDropOnDestroy, definition.DropChanceMultiplier, isNearPlayer, rollChance: true);
				SpawnCategoryDrops(source, definition, isNearPlayer);
				SpawnDropArray(source, definition.AlwaysDrop, definition.DropChanceMultiplier, isNearPlayer, rollChance: false);
			}
		}

		internal static void RestoreSeating(GameObject instance, WorldGeneration world, Vector2Int blockPlacedOn)
		{
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			BuildingEntity val = default(BuildingEntity);
			if (!((Object)(object)instance == (Object)null) && !((Object)(object)world == (Object)null) && instance.TryGetComponent<BuildingEntity>(ref val))
			{
				val.blockPlacedOn = blockPlacedOn;
				AttachSeatingListener(val, world);
			}
		}

		internal static void RefreshLiveInstance(GameObject instance, string id)
		{
			//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_00b8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0124: Unknown result type (might be due to invalid IL or missing references)
			//IL_014a: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0153: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_017b: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01af: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)instance == (Object)null || string.IsNullOrWhiteSpace(id) || !TryGetDefinition(id, out var definition) || definition == null)
			{
				return;
			}
			((Object)instance).name = id.Trim();
			SpriteRenderer component = instance.GetComponent<SpriteRenderer>();
			if ((Object)(object)component != (Object)null)
			{
				component.sprite = definition.Sprite;
				((Renderer)component).sortingOrder = definition.SortingOrder;
				if (!string.IsNullOrWhiteSpace(definition.SpriteAnimationId))
				{
					AssetLoader.TryApplyAnimation(component, definition.SpriteAnimationId);
				}
			}
			instance.transform.localScale = ((definition.Scale == Vector3.zero) ? Vector3.one : definition.Scale);
			instance.layer = ResolveAssignedLayer(definition) ?? GetReferenceLayer(GetRenderReference(definition), GroundLayer);
			BoxCollider2D component2 = instance.GetComponent<BoxCollider2D>();
			if ((Object)(object)component2 != (Object)null)
			{
				Bounds bounds;
				if (definition.ColliderSize.HasValue)
				{
					component2.size = definition.ColliderSize.Value;
				}
				else if ((Object)(object)definition.Sprite != (Object)null)
				{
					bounds = definition.Sprite.bounds;
					component2.size = Vector2.op_Implicit(((Bounds)(ref bounds)).size);
				}
				if (definition.ColliderOffset.HasValue)
				{
					((Collider2D)component2).offset = definition.ColliderOffset.Value;
				}
				else if ((Object)(object)definition.Sprite != (Object)null)
				{
					bounds = definition.Sprite.bounds;
					((Collider2D)component2).offset = Vector2.op_Implicit(((Bounds)(ref bounds)).center);
				}
				((Collider2D)component2).isTrigger = definition.ColliderIsTrigger;
			}
			BuildingEntity component3 = instance.GetComponent<BuildingEntity>();
			if ((Object)(object)component3 != (Object)null)
			{
				ApplyRigidbody2D(instance, definition);
				ApplyBuildingFields(component3, definition);
				if (!string.IsNullOrEmpty(definition.Name))
				{
					component3.fullName = LocaleRegistry.Get("building", id, definition.Name);
				}
				if (!string.IsNullOrEmpty(definition.Description))
				{
					component3.description = LocaleRegistry.Get("building", id + "dsc", definition.Description);
				}
			}
		}

		private static GameObject CreatePrefab(string id, CustomBuildingEntityDefinition definition)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Expected O, but got Unknown
			//IL_001e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0178: 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_0181: Unknown result type (might be due to invalid IL or missing references)
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject(id);
			val.SetActive(false);
			Object.DontDestroyOnLoad((Object)(object)val);
			val.transform.localScale = ((definition.Scale == Vector3.zero) ? Vector3.one