Decompiled source of WoodFrame v1.0.1

Mods/WoodFrame.dll

Decompiled 26 minutes ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text;
using System.Text.Json;
using System.Text.Json.Nodes;
using HarmonyLib;
using Il2CppFishNet;
using Il2CppInterop.Runtime;
using Il2CppInterop.Runtime.InteropTypes.Arrays;
using Il2CppScheduleOne;
using Il2CppScheduleOne.Core.Items.Framework;
using Il2CppScheduleOne.DevUtilities;
using Il2CppScheduleOne.Economy;
using Il2CppScheduleOne.Effects;
using Il2CppScheduleOne.Equipping;
using Il2CppScheduleOne.GameTime;
using Il2CppScheduleOne.ItemFramework;
using Il2CppScheduleOne.Messaging;
using Il2CppScheduleOne.NPCs;
using Il2CppScheduleOne.NPCs.Relation;
using Il2CppScheduleOne.Persistence;
using Il2CppScheduleOne.PlayerScripts;
using Il2CppScheduleOne.Product;
using Il2CppScheduleOne.Quests;
using Il2CppScheduleOne.Storage;
using Il2CppScheduleOne.UI;
using Il2CppScheduleOne.UI.Phone;
using Il2CppScheduleOne.UI.Relations;
using Il2CppScheduleOne.UI.Shop;
using Il2CppSystem;
using Il2CppSystem.Collections.Generic;
using Il2CppTMPro;
using MelonLoader;
using MelonLoader.Preferences;
using MelonLoader.Utils;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.Events;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;
using UnityEngine.Rendering;
using UnityEngine.UI;
using WoodFrame.Internal;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: MelonInfo(typeof(Core), "WoodFrame", "1.0.0", "Wood Studios", null)]
[assembly: MelonGame("TVGS", "Schedule I")]
[assembly: MelonPriority(-1000)]
[assembly: MelonColor(255, 196, 140, 80)]
[assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")]
[assembly: AssemblyCompany("WoodFrame")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("WoodFrame")]
[assembly: AssemblyTitle("WoodFrame")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace WoodFrame
{
	public sealed class Claim
	{
		public string Mod { get; internal set; }

		public string Kind { get; internal set; }

		public string What { get; internal set; }

		public Vector3 Centre { get; internal set; }

		public float Radius { get; internal set; }

		public string Value { get; internal set; }

		public bool BuiltIn { get; internal set; }

		public override string ToString()
		{
			//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			if (Kind == "place")
			{
				return $"{Mod}: {What} ({Centre.x:0}, {Centre.y:0}, {Centre.z:0}, {Radius:0} m)";
			}
			return $"{Mod}: {What} [{Value}]";
		}
	}
	public sealed class ClaimResult
	{
		public bool Ok => Clashes.Count == 0;

		public Claim Claim { get; internal set; }

		public IReadOnlyList<Claim> Clashes { get; internal set; } = Array.Empty<Claim>();
	}
	public static class Claims
	{
		internal sealed class KeyClaim
		{
			public string Mod;

			public string What;

			public string OnlyWhenInstalled;

			public KeyCode Key;

			public KeyMods Mods;
		}

		public const float Margin = 5f;

		internal static readonly List<KeyClaim> KeyClaims = new List<KeyClaim>();

		public static IReadOnlyList<Claim> All
		{
			get
			{
				//IL_0066: Unknown result type (might be due to invalid IL or missing references)
				ClaimsData.RefreshLive();
				List<Claim> list = new List<Claim>(ClaimsData.Places);
				list.AddRange(ClaimsData.Live);
				list.AddRange(DeadDrops.AllClaims());
				foreach (KeyClaim keyClaim in KeyClaims)
				{
					list.Add(new Claim
					{
						Mod = keyClaim.Mod,
						Kind = "key",
						What = keyClaim.What,
						Value = Keys.Describe(keyClaim.Key, keyClaim.Mods),
						BuiltIn = true
					});
				}
				foreach (Keybind item in Keys.All)
				{
					list.Add(new Claim
					{
						Mod = item.Owner.Name,
						Kind = "key",
						What = item.Label,
						Value = item.Text
					});
				}
				return list;
			}
		}

		public static ClaimResult Place(Mod mod, string what, Vector3 centre, float radius)
		{
			//IL_0043: 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)
			Claim c = new Claim
			{
				Mod = (mod?.Name ?? "?"),
				Kind = "place",
				What = (what ?? "a place"),
				Centre = centre,
				Radius = Mathf.Max(0f, radius)
			};
			List<Claim> list = Clashing(centre, radius, mod?.Name);
			ClaimsData.Places.RemoveAll((Claim p) => p.Mod == c.Mod && p.What == c.What);
			ClaimsData.Places.Add(c);
			if (list.Count > 0)
			{
				Instance log = Core.Log;
				if (log != null)
				{
					log.Warning($"{c.Mod}'s {c.What} is close to: {string.Join("; ", list)}.");
				}
				Report.Problem($"Place clash: {c.Mod}'s {c.What} vs {string.Join("; ", list.Select((Claim x) => x.Mod + " " + x.What))}");
			}
			return new ClaimResult
			{
				Claim = c,
				Clashes = list
			};
		}

		public static void Release(Mod mod, string what)
		{
			ClaimsData.Places.RemoveAll((Claim p) => p.Mod == mod?.Name && p.What == what);
		}

		public static bool IsFree(Vector3 centre, float radius, Mod mod = null)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return Clashing(centre, radius, mod?.Name).Count == 0;
		}

		public static List<Claim> Clashing(Vector3 centre, float radius, string exceptMod = null)
		{
			//IL_003c: 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_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			ClaimsData.RefreshLive();
			List<Claim> list = new List<Claim>();
			foreach (Claim item in ClaimsData.Places.Concat(ClaimsData.Live))
			{
				if (exceptMod == null || !string.Equals(item.Mod, exceptMod, StringComparison.OrdinalIgnoreCase))
				{
					Vector3 val = item.Centre - centre;
					if (!(item.Centre.y > 100f) && !(centre.y > 100f))
					{
						val.y = 0f;
					}
					if (((Vector3)(ref val)).magnitude < item.Radius + radius + 5f)
					{
						list.Add(item);
					}
				}
			}
			return list;
		}

		internal static void SeedWoodStudios()
		{
			//IL_0140: Unknown result type (might be due to invalid IL or missing references)
			//IL_014b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0198: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a4: Unknown result type (might be due to invalid IL or missing references)
			//IL_01eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b9: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c5: Unknown result type (might be due to invalid IL or missing references)
			//IL_050e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0513: Unknown result type (might be due to invalid IL or missing references)
			//IL_051c: Unknown result type (might be due to invalid IL or missing references)
			if (!ClaimsData.Seeded)
			{
				ClaimsData.Seeded = true;
				P("Bayside", "Bayside island town", -112f, 0f, -150f, 65f);
				P("Bayside", "Bayside Drive turn-off from the coast road", -11.5f, 0f, -92.3f, 8f);
				P("Bayside", "BAYSIDE arch and walkway join", -19f, 0f, -97f, 15f);
				P("Bayside", "Bayside Drive and bridge (about the middle)", -37f, 0f, -121f, 15f);
				P("Copper Mesa", "bus stop to Copper Mesa", 156f, 4f, -104.5f, 15f);
				P("Copper Mesa", "Copper Mesa town (far outside the map)", 4000f, 0f, -500f, 1300f);
				P("Prize Fighter", "Iron Bell Boxing Club door (Westville community center)", -146.7f, -3.9f, 80.9f, 6f);
				P("Prize Fighter", "Iron Bell arena (in the sky above the community center)", -146f, 520f, 74f, 25f);
				KeyCode[] array = new KeyCode[11];
				RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
				KeyCode[] array2 = (KeyCode[])(object)array;
				foreach (KeyCode k in array2)
				{
					K("the game", "default controls", k);
				}
				for (int j = 0; j <= 9; j++)
				{
					K("the game", "hotbar", (KeyCode)(48 + j));
				}
				KeyCode[] array3 = new KeyCode[5];
				RuntimeHelpers.InitializeArray(array3, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
				array2 = (KeyCode[])(object)array3;
				foreach (KeyCode k2 in array2)
				{
					K("Fortify Your Base", "developer key", k2, KeyMods.None, "Fortify Your Base");
				}
				K("Fortify Your Base", "developer: police raid", (KeyCode)93, KeyMods.None, "Fortify Your Base");
				KeyCode[] array4 = new KeyCode[4];
				RuntimeHelpers.InitializeArray(array4, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
				array2 = (KeyCode[])(object)array4;
				foreach (KeyCode k3 in array2)
				{
					K("Fortify Your Base", "Left Alt combo", k3, KeyMods.Alt, "Fortify Your Base");
				}
				K("Wood Studios labs", "developer: give everything", (KeyCode)108, KeyMods.Ctrl);
				K("Arsenal", "developer: aim test", (KeyCode)107, KeyMods.None, "Arsenal");
				K("Bayside", "developer: send into/out of Bayside", (KeyCode)49, KeyMods.Ctrl, "Bayside");
				K("Bayside", "developer: resident to the Docks", (KeyCode)49, KeyMods.Ctrl | KeyMods.Shift, "Bayside");
				for (int l = 2; l <= 6; l++)
				{
					K("Bayside", "developer key", (KeyCode)(48 + l), KeyMods.Ctrl, "Bayside");
				}
				K("Prize Fighter", "developer: boxing", (KeyCode)47, KeyMods.Alt);
				K("Prize Fighter", "developer: boxing", (KeyCode)47, KeyMods.Shift | KeyMods.Alt);
				K("Street Talk", "hold to talk", (KeyCode)116);
				K("Street Talk", "type to someone", (KeyCode)121);
				K("Supernova", "developer: put the stations down", (KeyCode)283, KeyMods.Ctrl);
				K("Copper Mesa", "developer: bus", (KeyCode)96, KeyMods.Ctrl);
				K("Copper Mesa", "developer key", (KeyCode)96, KeyMods.Ctrl | KeyMods.Shift);
				K("Copper Mesa", "developer key", (KeyCode)96, KeyMods.Alt);
				K("Copper Mesa", "developer key", (KeyCode)96, KeyMods.Ctrl | KeyMods.Alt);
				K("Copper Mesa", "developer key", (KeyCode)96, KeyMods.Shift);
				K("Street Map", "show or hide the minimap", (KeyCode)290, KeyMods.None, "Street Map");
				K("Performance Boost", "cycle presets", (KeyCode)290, KeyMods.None, "Performance Boost");
				K("Performance Boost", "FPS counter", (KeyCode)291, KeyMods.None, "Performance Boost");
				KeyCode[] array5 = new KeyCode[10];
				RuntimeHelpers.InitializeArray(array5, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/);
				array2 = (KeyCode[])(object)array5;
				foreach (KeyCode k4 in array2)
				{
					K("Fortify Your Base", "developer key", k4, KeyMods.None, "Fortify Your Base");
				}
				K("Open For Business", "developer key", (KeyCode)292, KeyMods.Ctrl);
				K("Arsenal", "developer: give items", (KeyCode)293, KeyMods.Alt);
				K("Cozy Furniture", "developer key", (KeyCode)278, KeyMods.Alt);
				(string, KeyCode)[] array6 = new(string, KeyCode)[11]
				{
					("Backpacks", (KeyCode)98),
					("Zipline", (KeyCode)122),
					("Security Cameras", (KeyCode)99),
					("Snitch", (KeyCode)99),
					("Greenhouse", (KeyCode)111),
					("Lumberjack", (KeyCode)104),
					("Counterfeit Press", (KeyCode)117),
					("House Builder", (KeyCode)112),
					("Weekend Market", (KeyCode)109),
					("Prison Time", (KeyCode)118),
					("Pre-Roll Shop", (KeyCode)118)
				};
				for (int i = 0; i < array6.Length; i++)
				{
					var (text, k5) = array6[i];
					K(text, "may use this key", k5, KeyMods.None, text);
				}
			}
			static void K(string mod, string what, KeyCode key, KeyMods m = KeyMods.None, string onlyWhen = null)
			{
				//IL_0019: Unknown result type (might be due to invalid IL or missing references)
				//IL_001a: Unknown result type (might be due to invalid IL or missing references)
				KeyClaims.Add(new KeyClaim
				{
					Mod = mod,
					What = what,
					Key = key,
					Mods = m,
					OnlyWhenInstalled = onlyWhen
				});
			}
			static void P(string mod, string what, float x, float y, float z, float r)
			{
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				ClaimsData.Places.Add(new Claim
				{
					Mod = mod,
					Kind = "place",
					What = what,
					Centre = new Vector3(x, y, z),
					Radius = r,
					BuiltIn = true
				});
			}
		}
	}
	public static class Installed
	{
		public static bool S1API => Compat.S1Api;

		public static bool FortifyYourBase => Compat.Fyb != null;

		public static bool ModSettings => Compat.ModSettings;

		public static bool AnyListedOrders => Compat.AnyListed;

		public static IReadOnlyList<string> WoodStudiosMods => Compat.WoodMods;

		public static bool Mod(string name)
		{
			return MelonBase.RegisteredMelons.Any((MelonBase m) => ((m != null) ? m.Info : null) != null && string.Equals(m.Info.Name, name, StringComparison.OrdinalIgnoreCase));
		}
	}
	public sealed class SaveData<T> : IDataSlot where T : class, new()
	{
		private readonly SortedDictionary<int, Action<JsonNode>> _steps = new SortedDictionary<int, Action<JsonNode>>();

		private JsonNode _keptNewer;

		public Mod Mod { get; }

		public string Key { get; }

		public int Version { get; }

		public T Value { get; set; } = new T();

		public bool Ready { get; private set; }

		string IDataSlot.Key => Key;

		Mod IDataSlot.Owner => Mod;

		public event Action<T> Loaded;

		internal SaveData(Mod mod, string key, int version)
		{
			Mod = mod;
			Key = key;
			Version = Math.Max(1, version);
		}

		public SaveData<T> Migration(int fromVersion, Action<JsonNode> upgrade)
		{
			if (upgrade != null)
			{
				_steps[fromVersion] = upgrade;
			}
			return this;
		}

		public void Reset()
		{
			Value = new T();
			_keptNewer = null;
		}

		void IDataSlot.Load(JsonObject entry)
		{
			_keptNewer = null;
			Value = new T();
			if (entry != null)
			{
				int num = entry["version"]?.GetValue<int>() ?? 1;
				JsonNode jsonNode = entry["data"];
				if (num > Version)
				{
					_keptNewer = Store.Clone(entry);
					Mod.Warn($"Saved data '{Key}' was written by a newer version of {Mod.Name} (data v{num}, this version reads v{Version}). It is kept unchanged; update {Mod.Name} to use it.");
				}
				else if (jsonNode != null)
				{
					JsonNode node = Store.Clone(jsonNode);
					for (int i = num; i < Version; i++)
					{
						if (_steps.TryGetValue(i, out var step))
						{
							int value = i;
							if (!Guard.Run(Mod, $"upgrading saved data '{Key}' from v{value}", delegate
							{
								step(node);
							}))
							{
								break;
							}
						}
					}
					T val = Guard.Get(Mod, "reading saved data '" + Key + "'", () => node.Deserialize<T>(Store.Json));
					if (val != null)
					{
						Value = val;
					}
				}
			}
			Ready = true;
			Action<T> action = this.Loaded;
			if (action == null)
			{
				return;
			}
			Delegate[] invocationList = action.GetInvocationList();
			for (int num2 = 0; num2 < invocationList.Length; num2++)
			{
				Action<T> d = (Action<T>)invocationList[num2];
				Guard.Run(Guard.OwnerOf(d) ?? Mod, "'" + Key + "' loaded", delegate
				{
					d(Value);
				});
			}
		}

		JsonObject IDataSlot.Save()
		{
			if (_keptNewer != null)
			{
				return (JsonObject)Store.Clone(_keptNewer);
			}
			JsonNode jsonNode = Guard.Get(Mod, "writing saved data '" + Key + "'", () => JsonSerializer.SerializeToNode(Value ?? new T(), Store.Json));
			if (jsonNode == null)
			{
				return null;
			}
			return new JsonObject
			{
				["version"] = Version,
				["data"] = jsonNode
			};
		}

		void IDataSlot.Unload()
		{
			Ready = false;
			Value = new T();
			_keptNewer = null;
		}
	}
	public sealed class PlayerData<T> : IDataSlot where T : class, new()
	{
		private Dictionary<string, T> _byPlayer = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase);

		private readonly SortedDictionary<int, Action<JsonNode>> _steps = new SortedDictionary<int, Action<JsonNode>>();

		private JsonObject _keptNewer;

		public Mod Mod { get; }

		public string Key { get; }

		public int Version { get; }

		public bool Ready { get; private set; }

		public T Local => For(Session.LocalPlayerId);

		public IEnumerable<string> Players => _byPlayer.Keys;

		string IDataSlot.Key => "players/" + Key;

		Mod IDataSlot.Owner => Mod;

		internal PlayerData(Mod mod, string key, int version)
		{
			Mod = mod;
			Key = key;
			Version = Math.Max(1, version);
		}

		public T For(string playerId)
		{
			playerId = (string.IsNullOrEmpty(playerId) ? "local" : playerId);
			if (!_byPlayer.TryGetValue(playerId, out var value) || value == null)
			{
				value = (_byPlayer[playerId] = new T());
			}
			return value;
		}

		public PlayerData<T> Migration(int fromVersion, Action<JsonNode> upgrade)
		{
			if (upgrade != null)
			{
				_steps[fromVersion] = upgrade;
			}
			return this;
		}

		void IDataSlot.Load(JsonObject entry)
		{
			_byPlayer = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase);
			_keptNewer = null;
			if (entry != null)
			{
				int num = entry["version"]?.GetValue<int>() ?? 1;
				if (num > Version)
				{
					_keptNewer = (JsonObject)Store.Clone(entry);
					Mod.Warn($"Player data '{Key}' was written by a newer version of {Mod.Name}; it is kept unchanged.");
				}
				else if (entry["data"] is JsonObject jsonObject)
				{
					foreach (KeyValuePair<string, JsonNode> item in jsonObject)
					{
						if (item.Value == null)
						{
							continue;
						}
						JsonNode node = Store.Clone(item.Value);
						for (int i = num; i < Version; i++)
						{
							if (_steps.TryGetValue(i, out var step))
							{
								int value = i;
								if (!Guard.Run(Mod, $"upgrading player data '{Key}' from v{value}", delegate
								{
									step(node);
								}))
								{
									break;
								}
							}
						}
						T val = Guard.Get(Mod, "reading player data '" + Key + "'", () => node.Deserialize<T>(Store.Json));
						if (val != null)
						{
							_byPlayer[item.Key] = val;
						}
					}
				}
			}
			Ready = true;
		}

		JsonObject IDataSlot.Save()
		{
			if (_keptNewer != null)
			{
				return (JsonObject)Store.Clone(_keptNewer);
			}
			JsonObject jsonObject = new JsonObject();
			foreach (KeyValuePair<string, T> kv in _byPlayer)
			{
				JsonNode jsonNode = Guard.Get(Mod, "writing player data '" + Key + "'", () => JsonSerializer.SerializeToNode(kv.Value ?? new T(), Store.Json));
				if (jsonNode != null)
				{
					jsonObject[kv.Key] = jsonNode;
				}
			}
			return new JsonObject
			{
				["version"] = Version,
				["data"] = jsonObject
			};
		}

		void IDataSlot.Unload()
		{
			Ready = false;
			_byPlayer = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase);
			_keptNewer = null;
		}
	}
	public sealed class DeadDropClaim
	{
		public Mod Mod { get; internal set; }

		public string Purpose { get; internal set; }

		public string Preferred { get; internal set; }

		public string Guid { get; internal set; }

		public string Name => DeadDrops.NameOf(Guid);

		public bool Moved => !string.Equals(Guid, Preferred, StringComparison.OrdinalIgnoreCase);

		public bool Deliver(string itemId, int quantity)
		{
			return DeadDrops.Deliver(Guid, itemId, quantity);
		}

		public override string ToString()
		{
			return $"{Mod?.Name}: {Purpose} at {Name}";
		}
	}
	public static class DeadDrops
	{
		private static readonly List<DeadDropClaim> Claims_ = new List<DeadDropClaim>();

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

		private static readonly (string mod, string what, string drop)[] WoodStudios = new(string, string, string)[9]
		{
			("Angel Dust Lab", "supplier's stash", "BehindMedicalPractice"),
			("DMT Lab", "supplier's stash", "Gazebo"),
			("Edibles Kitchen", "supplier's stash", "BehindSupermarket"),
			("LSD Lab", "supplier's stash", "BrownApartmentBlock"),
			("Pill Press", "supplier's stash", "BehindCrimsonCanary"),
			("Poppy Lab", "supplier's stash", "GreyDocksBuilding"),
			("Pre-Roll Shop", "supplier's stash", "BehindLaundromat"),
			("Vape Lab", "supplier's stash", "BehindTopTattoo"),
			("Supernova", "Dr. Vesper Lane's stash", "BehindCasino")
		};

		private static readonly (string Name, string Guid)[] Table = new(string, string)[25]
		{
			("BehindSupermarket", "fe1782b0-64e5-4ae6-a3f9-56af509af104"),
			("BehindMotelOffice", "d66b3fd6-7b7f-4e98-b000-6d5a197f7437"),
			("SkatePark", "eda8c6a4-07be-4d8f-97f4-ddd6dfca19df"),
			("BehindGasMart", "64d10032-64a9-4cd9-8750-8048d71c5029"),
			("UnderWestBridge", "0fd91cf3-ac6a-41ce-968f-1f356f996a83"),
			("BehindCasino", "f5614c42-2c74-42d5-bee2-025e84718792"),
			("TacoTicklersExteriorWall", "79200bb6-7d39-44d9-ab22-c63f136d8cdf"),
			("TownHallFountain", "d28c727e-5175-4989-8c33-2a36c159c817"),
			("PawnShopWestWall", "fde97bca-d21a-476c-bf03-b00768a45030"),
			("BehindSlopShop", "58ec86b5-647e-456d-9266-4cd77413e9c3"),
			("Gazebo", "94eef741-d688-4380-ac64-cf190e812b10"),
			("BehindRandysBaitAndTackle", "baf08ceb-a0e7-4e4a-baa8-6b4cc992cb15"),
			("BehindBank", "e5399b56-22a5-4a2c-a254-cc81e3ab2f75"),
			("BehindCrimsonCanary", "51e8f8ec-adcb-4800-8020-55cc24f9ba40"),
			("BehindThompsonConstruction", "766389cd-b2e3-44ec-84fe-9c59eccfcdd7"),
			("CentralCanal", "4ac50ff1-ad3c-415b-aa77-c80249dfa473"),
			("NorthArcadeWall", "dd3d22f1-da56-4673-9203-640eeaf915fc"),
			("BrownApartmentBlock", "b77ed1a0-c729-41d5-b8a2-81b480ca971f"),
			("BehindMedicalPractice", "683fa5b9-c55d-4b3f-8026-6f29857d09d1"),
			("BehindLaundromat", "555e565d-2f65-4882-9edb-7167168b2e00"),
			("BehindAutoShop", "aaea12a7-ee38-47ba-aeb8-fb0d45a03957"),
			("GreyDocksBuilding", "eff8fff2-0f89-4936-aef5-c4d383ea4f50"),
			("BehindGroceryStore", "5aeef10c-955d-4fdb-9061-38f4ad7a6289"),
			("BehindFireStation", "86835825-f5f8-454d-9c74-c31e257f9cc2"),
			("BehindTopTattoo", "3ed706ba-458d-44b5-95cd-d65e4a699043")
		};

		public static IReadOnlyList<(string Name, string Guid)> All => Table;

		public static IReadOnlyDictionary<string, string> InUse
		{
			get
			{
				Resolve();
				return Users(null);
			}
		}

		public static DeadDropClaim Claim(Mod mod, string purpose, string preferred = null)
		{
			string preferred2 = GuidOf(preferred) ?? Table[0].Guid;
			DeadDropClaim deadDropClaim = Claims_.FirstOrDefault((DeadDropClaim x) => x.Mod == mod && x.Purpose == purpose);
			if (deadDropClaim == null)
			{
				deadDropClaim = new DeadDropClaim
				{
					Mod = mod,
					Purpose = (purpose ?? "stash")
				};
				Claims_.Add(deadDropClaim);
			}
			deadDropClaim.Preferred = preferred2;
			Resolve();
			return deadDropClaim;
		}

		public static string NameOf(string guid)
		{
			(string, string)[] table = Table;
			for (int i = 0; i < table.Length; i++)
			{
				(string, string) tuple = table[i];
				if (string.Equals(tuple.Item2, guid, StringComparison.OrdinalIgnoreCase))
				{
					return tuple.Item1;
				}
			}
			return guid ?? "";
		}

		public static string GuidOf(string nameOrGuid)
		{
			if (string.IsNullOrWhiteSpace(nameOrGuid))
			{
				return null;
			}
			string text = Key(nameOrGuid);
			(string, string)[] table = Table;
			for (int i = 0; i < table.Length; i++)
			{
				(string, string) tuple = table[i];
				if (Key(tuple.Item1) == text || string.Equals(tuple.Item2, nameOrGuid.Trim(), StringComparison.OrdinalIgnoreCase))
				{
					return tuple.Item2;
				}
			}
			return null;
		}

		public static bool Deliver(string guid, string itemId, int quantity)
		{
			//IL_0034: 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)
			if (!Session.InSave || !Session.IsHost || quantity <= 0)
			{
				return false;
			}
			try
			{
				List<DeadDrop> deadDrops = DeadDrop.DeadDrops;
				int num = 0;
				while (deadDrops != null && num < deadDrops.Count)
				{
					DeadDrop val = deadDrops[num];
					if (!((Object)(object)val == (Object)null) && string.Equals(((object)val.GUID/*cast due to .constrained prefix*/).ToString(), guid, StringComparison.OrdinalIgnoreCase))
					{
						ItemDefinition item = Registry.GetItem(itemId);
						if ((Object)(object)item == (Object)null || (Object)(object)val.Storage == (Object)null)
						{
							return false;
						}
						ItemInstance defaultInstance = item.GetDefaultInstance(quantity);
						if (!((StorageEntity)val.Storage).CanItemFit(defaultInstance, quantity))
						{
							return false;
						}
						((StorageEntity)val.Storage).InsertItem(defaultInstance, true);
						return true;
					}
					num++;
				}
			}
			catch (Exception ex)
			{
				Instance log = Core.Log;
				if (log != null)
				{
					log.Warning($"Delivering {itemId} to {NameOf(guid)}: {ex.Message}");
				}
			}
			return false;
		}

		private static Dictionary<string, string> Users(DeadDropClaim except)
		{
			Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
			(string, string, string)[] woodStudios = WoodStudios;
			for (int i = 0; i < woodStudios.Length; i++)
			{
				(string, string, string) tuple = woodStudios[i];
				string text = GuidOf(tuple.Item3);
				if (text != null && !dictionary.ContainsKey(text))
				{
					dictionary[text] = tuple.Item1 + " (" + tuple.Item2 + ")";
				}
			}
			foreach (KeyValuePair<string, string> item in S1ApiSuppliers())
			{
				if (!dictionary.ContainsKey(item.Key))
				{
					dictionary[item.Key] = item.Value;
				}
			}
			foreach (DeadDropClaim item2 in Claims_)
			{
				if (item2 != except && item2.Guid != null && !dictionary.ContainsKey(item2.Guid))
				{
					dictionary[item2.Guid] = item2.Mod?.Name + " (" + item2.Purpose + ")";
				}
			}
			return dictionary;
		}

		private static Dictionary<string, string> S1ApiSuppliers()
		{
			Dictionary<string, string> dictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
			if (!Installed.S1API)
			{
				return dictionary;
			}
			try
			{
				if ((AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly a) => (a.GetName().Name ?? "").StartsWith("S1API", StringComparison.OrdinalIgnoreCase) && a.GetType("S1API.Entities.NPC") != null)?.GetType("S1API.Entities.NPC")?.GetField("TypeToBuiltSupplierDefaults", BindingFlags.Static | BindingFlags.NonPublic))?.GetValue(null) is IDictionary dictionary2)
				{
					foreach (DictionaryEntry item in dictionary2)
					{
						if ((item.Value?.GetType().GetProperty("StashDeadDropGuid", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))?.GetValue(item.Value) is string text && !string.IsNullOrEmpty(text) && !dictionary.ContainsKey(text))
						{
							dictionary[text] = ((item.Key as Type)?.Name ?? "an S1API supplier") + " (S1API supplier)";
						}
					}
				}
			}
			catch
			{
			}
			return dictionary;
		}

		internal static void Resolve()
		{
			foreach (DeadDropClaim item2 in Claims_)
			{
				item2.Guid = null;
			}
			foreach (DeadDropClaim c in Claims_.OrderBy<DeadDropClaim, string>((DeadDropClaim x) => x.Mod?.Id, StringComparer.Ordinal).ThenBy<DeadDropClaim, string>((DeadDropClaim x) => x.Purpose, StringComparer.Ordinal))
			{
				Dictionary<string, string> dictionary = Users(c);
				if (!dictionary.TryGetValue(c.Preferred, out var value))
				{
					c.Guid = c.Preferred;
					continue;
				}
				int val = Array.FindIndex(Table, ((string Name, string Guid) d) => string.Equals(d.Guid, c.Preferred, StringComparison.OrdinalIgnoreCase));
				for (int num = 1; num <= Table.Length; num++)
				{
					if (c.Guid != null)
					{
						break;
					}
					(string, string) tuple = Table[(Math.Max(val, 0) + num) % Table.Length];
					if (!dictionary.ContainsKey(tuple.Item2))
					{
						c.Guid = tuple.Item2;
					}
				}
				string item = c.Mod?.Id + "|" + c.Purpose + "|" + c.Guid;
				if (c.Guid == null)
				{
					c.Guid = c.Preferred;
					if (Told.Add(item))
					{
						Instance log = Core.Log;
						if (log != null)
						{
							log.Warning($"{c.Mod?.Name}: every dead drop is taken; {c.Purpose} shares {NameOf(c.Preferred)} with {value}.");
						}
						Report.Problem($"No free dead drop for {c.Mod?.Name} ({c.Purpose})");
					}
				}
				else if (Told.Add(item))
				{
					Instance log2 = Core.Log;
					if (log2 != null)
					{
						log2.Msg($"{c.Mod?.Name}: {NameOf(c.Preferred)} is used by {value}, so {c.Purpose} is at {NameOf(c.Guid)} instead.");
					}
				}
			}
		}

		internal static IEnumerable<Claim> AllClaims()
		{
			Resolve();
			foreach (KeyValuePair<string, string> item in Users(null))
			{
				yield return new Claim
				{
					Mod = item.Value,
					Kind = "deaddrop",
					What = "stash",
					Value = item.Key
				};
			}
		}

		private static string Key(string s)
		{
			return new string((s ?? "").Where(char.IsLetterOrDigit).ToArray()).ToLowerInvariant();
		}
	}
	public static class Frame
	{
		public const string Version = "1.0.0";

		public const int ApiLevel = 1;

		public static int InstalledApiLevel => 1;

		public static IReadOnlyList<Mod> Mods => Registry.All;

		public static bool DevKeys => Compat.DevKeys;

		public static KeyCode UseKey => Compat.UseKey;

		public static Mod Register(MelonBase melon, string id = null)
		{
			if (melon == null)
			{
				throw new ArgumentNullException("melon");
			}
			Core.EnsureStarted();
			return Registry.Add(melon, id);
		}

		public static Mod Find(string id)
		{
			return Registry.ById(id);
		}
	}
	public sealed class Mod
	{
		private MelonPreferences_Category _settings;

		public string Id { get; }

		public string Name { get; }

		public string Version { get; }

		public string Author { get; }

		public MelonBase Melon { get; }

		public Assembly Assembly { get; }

		public int Faults { get; internal set; }

		public MelonPreferences_Category Settings
		{
			get
			{
				if (_settings != null)
				{
					return _settings;
				}
				string text = new string(Name.Where(char.IsLetterOrDigit).ToArray());
				if (text.Length < 3)
				{
					text = new string(Id.Where(char.IsLetterOrDigit).ToArray());
				}
				_settings = MelonPreferences.GetCategory(text) ?? MelonPreferences.CreateCategory(text, Name);
				return _settings;
			}
		}

		internal Mod(MelonBase melon, string id)
		{
			Melon = melon;
			Id = id;
			MelonInfoAttribute info = melon.Info;
			Name = ((info != null) ? info.Name : null) ?? id;
			MelonInfoAttribute info2 = melon.Info;
			Version = ((info2 != null) ? info2.Version : null) ?? "0";
			MelonInfoAttribute info3 = melon.Info;
			Author = ((info3 != null) ? info3.Author : null) ?? "";
			try
			{
				MelonAssembly melonAssembly = melon.MelonAssembly;
				Assembly = ((melonAssembly != null) ? melonAssembly.Assembly : null);
			}
			catch
			{
			}
			if ((object)Assembly == null)
			{
				Assembly = ((object)melon).GetType().Assembly;
			}
		}

		public void Log(string message)
		{
			try
			{
				Melon.LoggerInstance.Msg(message);
			}
			catch
			{
			}
		}

		public void Warn(string message)
		{
			try
			{
				Melon.LoggerInstance.Warning(message);
			}
			catch
			{
			}
		}

		public void Error(string message)
		{
			try
			{
				Melon.LoggerInstance.Error(message);
			}
			catch
			{
			}
		}

		public bool Safely(string what, Action action)
		{
			return Guard.Run(this, what, action);
		}

		public MelonPreferences_Entry<T> Setting<T>(string key, T defaultValue, string label = null, string description = null, bool hidden = false)
		{
			MelonPreferences_Category settings = Settings;
			return settings.GetEntry<T>(key) ?? settings.CreateEntry<T>(key, defaultValue, label ?? key, description, hidden, false, (ValueValidator)null, (string)null);
		}

		public SaveData<T> SaveData<T>(string key, int version = 1) where T : class, new()
		{
			return Store.Open<T>(this, key, version);
		}

		public PlayerData<T> PlayerData<T>(string key, int version = 1) where T : class, new()
		{
			return Store.OpenPlayers<T>(this, key, version);
		}

		public Keybind Key(string id, string label, KeyCode key, KeyMods mods = KeyMods.None, bool devOnly = false)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return Keys.Register(this, id, label, key, mods, devOnly);
		}

		public ItemBuilder Item(string id)
		{
			return new ItemBuilder(this, id);
		}

		public ProductBuilder Product(string id)
		{
			return new ProductBuilder(this, id);
		}

		public PhoneApp PhoneApp(string title, Color color, Action<AppPage> build)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return Phone.AddApp(this, title, color, build);
		}

		public ClaimResult ClaimPlace(string what, Vector3 centre, float radius)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			return Claims.Place(this, what, centre, radius);
		}

		public DeadDropClaim ClaimDeadDrop(string purpose, string preferred = null)
		{
			return DeadDrops.Claim(this, purpose, preferred);
		}

		public override string ToString()
		{
			return Name + " (" + Id + ")";
		}
	}
	public enum ItemCategory
	{
		Tools,
		Furniture,
		Decoration,
		Equipment,
		Consumable,
		Ingredient,
		Packaging,
		Growing,
		Lighting,
		Other
	}
	public sealed class ItemBuilder
	{
		internal readonly Item I;

		internal ItemBuilder(Mod mod, string id)
		{
			I = new Item(mod, id);
		}

		public ItemBuilder Name(string name)
		{
			I.Name = name;
			return this;
		}

		public ItemBuilder Description(string text)
		{
			I.Description = text;
			return this;
		}

		public ItemBuilder Category(ItemCategory c)
		{
			I.Category = c;
			return this;
		}

		public ItemBuilder Price(float price, float resellShare = 0.5f)
		{
			I.Price = Mathf.Max(0f, price);
			I.Resell = Mathf.Clamp01(resellShare);
			return this;
		}

		public ItemBuilder StackLimit(int n)
		{
			I.Stack = Mathf.Clamp(n, 1, 999);
			return this;
		}

		public ItemBuilder Illegal(bool illegal = true)
		{
			I.Illegal = illegal;
			return this;
		}

		public ItemBuilder ShopTab(string tab)
		{
			I.ShopTab = tab;
			return this;
		}

		public ItemBuilder Model(string glbResource)
		{
			I.GlbResource = glbResource;
			return this;
		}

		public ItemBuilder Model(Func<GameObject> build)
		{
			I.ModelFactory = build;
			return this;
		}

		public ItemBuilder ModelSize(float metres)
		{
			I.Size = Mathf.Max(0f, metres);
			return this;
		}

		public ItemBuilder Held(Vector3 offset, Vector3 euler, float size = 0.25f)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: 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_0013: Unknown result type (might be due to invalid IL or missing references)
			I.HeldOffset = offset;
			I.HeldEuler = euler;
			I.HeldSize = size;
			return this;
		}

		public ItemBuilder Icon(string pngResource)
		{
			I.IconResource = pngResource;
			return this;
		}

		public ItemBuilder Icon(Sprite sprite)
		{
			I.IconSprite = sprite;
			return this;
		}

		public ItemBuilder IconColor(Color c)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			I.TileColor = c;
			return this;
		}

		public ItemBuilder Placeable(bool onWalls = false)
		{
			I.Placeable = true;
			I.OnWalls = onWalls;
			return this;
		}

		public Item Register()
		{
			Items.Add(I);
			return I;
		}
	}
	public sealed class Item
	{
		internal float Resell = 0.5f;

		internal float Size;

		internal float HeldSize = 0.25f;

		internal int Stack = 10;

		internal bool Illegal;

		internal bool OnWalls;

		internal string ShopTab;

		internal string GlbResource;

		internal string IconResource;

		internal Func<GameObject> ModelFactory;

		internal Sprite IconSprite;

		internal Color TileColor = new Color(0.55f, 0.4f, 0.25f);

		internal Vector3 HeldOffset = Vector3.zero;

		internal Vector3 HeldEuler = Vector3.zero;

		internal StorableItemDefinition Def;

		internal GameObject Template;

		internal readonly Hook PlacedHook = new Hook("item placed");

		internal readonly Hook PickedHook = new Hook("item picked up");

		internal readonly Hook UsedHook = new Hook("item used");

		public Mod Mod { get; }

		public string Id { get; }

		public string Name { get; internal set; }

		public string Description { get; internal set; } = "";

		public ItemCategory Category { get; internal set; }

		public float Price { get; internal set; } = 10f;

		public bool Placeable { get; internal set; }

		public bool Registered { get; internal set; }

		public string Problem { get; internal set; }

		public int Carried => Items.Carried(Id);

		public bool InHand => Items.HeldId() == Id;

		public IReadOnlyList<PlacedItem> PlacedCopies => Placement.Of(this);

		public event Action<PlacedItem> Placed
		{
			add
			{
				PlacedHook.Add(value);
			}
			remove
			{
				PlacedHook.Remove(value);
			}
		}

		public event Action<PlacedItem> PickedUp
		{
			add
			{
				PickedHook.Add(value);
			}
			remove
			{
				PickedHook.Remove(value);
			}
		}

		public event Action Used
		{
			add
			{
				UsedHook.Add(value);
			}
			remove
			{
				UsedHook.Remove(value);
			}
		}

		internal Item(Mod mod, string id)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: 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_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: 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)
			Mod = mod;
			Id = (id ?? "").Trim();
			Name = Id;
		}

		public bool Give(int quantity = 1)
		{
			return Items.Give(Id, quantity);
		}

		public bool Take(int quantity = 1)
		{
			return Items.Take(Id, quantity);
		}

		public GameObject NewModel()
		{
			return Models.Make(this, null);
		}

		public override string ToString()
		{
			return Name + " (" + Id + ")";
		}
	}
	[Flags]
	public enum KeyMods
	{
		None = 0,
		Ctrl = 1,
		Shift = 2,
		Alt = 4
	}
	public sealed class Keybind
	{
		internal readonly Hook _pressed = new Hook("key press");

		public Mod Owner { get; }

		public string Id { get; }

		public string Label { get; }

		public KeyCode Default { get; }

		public KeyMods DefaultMods { get; }

		public KeyCode Key { get; private set; }

		public KeyMods Mods { get; private set; }

		public bool DevOnly { get; }

		public bool Down
		{
			get
			{
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				if (Active && KeyInput.Down(Key))
				{
					return KeyInput.ModsHeld() == Mods;
				}
				return false;
			}
		}

		public bool Held
		{
			get
			{
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				if (Active && KeyInput.Held(Key))
				{
					return (KeyInput.ModsHeld() & Mods) == Mods;
				}
				return false;
			}
		}

		public bool Up
		{
			get
			{
				//IL_0009: Unknown result type (might be due to invalid IL or missing references)
				if (Active)
				{
					return KeyInput.Up(Key);
				}
				return false;
			}
		}

		private bool Active
		{
			get
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				if ((int)Key != 0 && !KeyInput.Quiet)
				{
					if (DevOnly)
					{
						return Frame.DevKeys;
					}
					return true;
				}
				return false;
			}
		}

		public string Text => Keys.Describe(Key, Mods);

		public IReadOnlyList<string> Conflicts => Keys.ConflictsOf(this);

		public event Action Pressed
		{
			add
			{
				_pressed.Add(value);
			}
			remove
			{
				_pressed.Remove(value);
			}
		}

		internal Keybind(Mod owner, string id, string label, KeyCode key, KeyMods mods, bool devOnly)
		{
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: 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)
			Owner = owner;
			Id = id;
			Label = label ?? id;
			Default = key;
			DefaultMods = mods;
			Key = key;
			Mods = mods;
			DevOnly = devOnly;
		}

		public void Rebind(KeyCode key, KeyMods mods)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			Key = key;
			Mods = mods;
			Keys.Saved(this);
		}

		public void ResetToDefault()
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			Rebind(Default, DefaultMods);
		}

		internal void SetQuiet(KeyCode key, KeyMods mods)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			Key = key;
			Mods = mods;
		}

		public override string ToString()
		{
			return $"{Owner?.Name}: {Label} [{Text}]";
		}
	}
	public enum NetRole
	{
		None,
		SinglePlayer,
		Host,
		Guest
	}
	public static class Events
	{
		internal static readonly Hook MainMenuHook = new Hook("main menu");

		internal static readonly Hook SaveLoadingHook = new Hook("save loading");

		internal static readonly Hook SaveLoadedHook = new Hook("save loaded");

		internal static readonly Hook SavingHook = new Hook("saving");

		internal static readonly Hook SavedHook = new Hook("saved");

		internal static readonly Hook SaveExitedHook = new Hook("leaving the save");

		internal static readonly Hook QuittingHook = new Hook("quitting");

		internal static readonly Hook MinuteHook = new Hook("minute passed");

		internal static readonly Hook HourHook = new Hook("hour passed");

		internal static readonly Hook DayHook = new Hook("new day");

		internal static readonly Hook NightHook = new Hook("night fell");

		internal static readonly Hook MorningHook = new Hook("morning came");

		public static event Action MainMenu
		{
			add
			{
				MainMenuHook.Add(value);
			}
			remove
			{
				MainMenuHook.Remove(value);
			}
		}

		public static event Action SaveLoading
		{
			add
			{
				SaveLoadingHook.Add(value);
			}
			remove
			{
				SaveLoadingHook.Remove(value);
			}
		}

		public static event Action SaveLoaded
		{
			add
			{
				SaveLoadedHook.Add(value);
			}
			remove
			{
				SaveLoadedHook.Remove(value);
			}
		}

		public static event Action Saving
		{
			add
			{
				SavingHook.Add(value);
			}
			remove
			{
				SavingHook.Remove(value);
			}
		}

		public static event Action Saved
		{
			add
			{
				SavedHook.Add(value);
			}
			remove
			{
				SavedHook.Remove(value);
			}
		}

		public static event Action SaveExited
		{
			add
			{
				SaveExitedHook.Add(value);
			}
			remove
			{
				SaveExitedHook.Remove(value);
			}
		}

		public static event Action Quitting
		{
			add
			{
				QuittingHook.Add(value);
			}
			remove
			{
				QuittingHook.Remove(value);
			}
		}

		public static event Action<int> MinutePassed
		{
			add
			{
				MinuteHook.Add(value);
			}
			remove
			{
				MinuteHook.Remove(value);
			}
		}

		public static event Action<int> HourPassed
		{
			add
			{
				HourHook.Add(value);
			}
			remove
			{
				HourHook.Remove(value);
			}
		}

		public static event Action<int> NewDay
		{
			add
			{
				DayHook.Add(value);
			}
			remove
			{
				DayHook.Remove(value);
			}
		}

		public static event Action NightFell
		{
			add
			{
				NightHook.Add(value);
			}
			remove
			{
				NightHook.Remove(value);
			}
		}

		public static event Action MorningCame
		{
			add
			{
				MorningHook.Add(value);
			}
			remove
			{
				MorningHook.Remove(value);
			}
		}
	}
	public static class Session
	{
		public static bool InSave => Lifecycle.InSave;

		public static bool InMenu => Lifecycle.Scene_ == "Menu";

		public static NetRole Role => Lifecycle.Role();

		public static bool IsHost
		{
			get
			{
				if (Role != NetRole.Host)
				{
					return Role == NetRole.SinglePlayer;
				}
				return true;
			}
		}

		public static bool IsGuest => Role == NetRole.Guest;

		public static bool IsCoop
		{
			get
			{
				if (Role != NetRole.Host)
				{
					return Role == NetRole.Guest;
				}
				return true;
			}
		}

		public static string SaveFolder => Lifecycle.Folder;

		public static int SaveSlot => Lifecycle.Slot;

		public static string SaveName => Lifecycle.OrgName;

		public static string LocalPlayerId => Players.Id(Player.Local);

		public static string LocalPlayerName
		{
			get
			{
				try
				{
					Player local = Player.Local;
					return (local != null) ? local.PlayerName : null;
				}
				catch
				{
					return null;
				}
			}
		}

		public static IReadOnlyList<string> PlayerIds => Players.AllIds();
	}
	public static class Clock
	{
		public static int Time => Lifecycle.LastTime;

		public static int Hour
		{
			get
			{
				if (Time >= 0)
				{
					return Time / 100;
				}
				return -1;
			}
		}

		public static int Minute
		{
			get
			{
				if (Time >= 0)
				{
					return Time % 100;
				}
				return -1;
			}
		}

		public static int MinuteOfDay
		{
			get
			{
				if (Time >= 0)
				{
					return Hour * 60 + Minute;
				}
				return -1;
			}
		}

		public static int Day => Lifecycle.LastDay;

		public static string Weekday
		{
			get
			{
				//IL_0005: 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)
				try
				{
					return ((object)NetworkSingleton<TimeManager>.Instance.CurrentDay/*cast due to .constrained prefix*/).ToString();
				}
				catch
				{
					return "";
				}
			}
		}

		public static bool IsNight => Lifecycle.LastNight;

		public static string Text
		{
			get
			{
				try
				{
					return TimeManager.Get12HourTime((float)Time, true);
				}
				catch
				{
					return Time.ToString("0000");
				}
			}
		}

		public static bool Between(int from, int to)
		{
			int time = Time;
			if (time < 0)
			{
				return false;
			}
			if (from > to)
			{
				if (time < from)
				{
					return time < to;
				}
				return true;
			}
			if (time >= from)
			{
				return time < to;
			}
			return false;
		}
	}
	public sealed class NpcRef
	{
		public string Id { get; }

		internal NPC Native => WoodFrame.Internal.Npcs.Find_(Id);

		public bool Exists => (Object)(object)Native != (Object)null;

		public string Name
		{
			get
			{
				NPC native = Native;
				if ((Object)(object)native == (Object)null)
				{
					return Id;
				}
				try
				{
					return (native.FirstName + " " + native.LastName).Trim();
				}
				catch
				{
					return Id;
				}
			}
		}

		public string FirstName
		{
			get
			{
				try
				{
					NPC native = Native;
					return ((native != null) ? native.FirstName : null) ?? "";
				}
				catch
				{
					return "";
				}
			}
		}

		public Vector3 Position
		{
			get
			{
				//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_001d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0010: Unknown result type (might be due to invalid IL or missing references)
				//IL_002e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0022: Unknown result type (might be due to invalid IL or missing references)
				try
				{
					NPC native = Native;
					return ((Object)(object)native != (Object)null) ? ((Component)native).transform.position : Vector3.zero;
				}
				catch
				{
					return Vector3.zero;
				}
			}
		}

		public string Region
		{
			get
			{
				//IL_000d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0012: Unknown result type (might be due to invalid IL or missing references)
				try
				{
					NPC native = Native;
					return ((native != null) ? ((object)native.Region/*cast due to .constrained prefix*/).ToString() : null) ?? "";
				}
				catch
				{
					return "";
				}
			}
		}

		public bool IsCustomer
		{
			get
			{
				try
				{
					NPC native = Native;
					return (Object)(object)((native != null) ? ((Component)native).GetComponent<Customer>() : null) != (Object)null;
				}
				catch
				{
					return false;
				}
			}
		}

		public bool IsUnlocked
		{
			get
			{
				try
				{
					NPC native = Native;
					bool? obj;
					if (native == null)
					{
						obj = null;
					}
					else
					{
						NPCRelationData relationData = native.RelationData;
						obj = ((relationData != null) ? new bool?(relationData.Unlocked) : ((bool?)null));
					}
					bool? flag = obj;
					return flag == true;
				}
				catch
				{
					return false;
				}
			}
		}

		public float Relationship
		{
			get
			{
				try
				{
					NPC native = Native;
					float? obj;
					if (native == null)
					{
						obj = null;
					}
					else
					{
						NPCRelationData relationData = native.RelationData;
						obj = ((relationData != null) ? new float?(relationData.RelationDelta) : ((float?)null));
					}
					float? num = obj;
					return num.GetValueOrDefault();
				}
				catch
				{
					return 0f;
				}
			}
		}

		internal NpcRef(string id)
		{
			Id = id;
		}

		public bool Text(string message)
		{
			return Phone.Text(this, message);
		}

		public override string ToString()
		{
			return Name + " (" + Id + ")";
		}
	}
	public sealed class DealInfo
	{
		public NpcRef Customer { get; internal set; }

		public IReadOnlyList<(string productId, int quantity)> Products { get; internal set; } = Array.Empty<(string, int)>();

		public float Payment { get; internal set; }

		public override string ToString()
		{
			return $"{Customer?.Name}: {string.Join(", ", Products.Select(((string productId, int quantity) p) => p.quantity + "x " + p.productId))} for ${Payment:0}";
		}
	}
	public static class Npcs
	{
		public static IReadOnlyList<NpcRef> All => (from n in WoodFrame.Internal.Npcs.AllNative()
			select new NpcRef(n.ID)).ToList();

		public static NpcRef Get(string id)
		{
			return new NpcRef(id);
		}

		public static IReadOnlyList<NpcRef> Near(Vector3 point, float radius)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			return (from x in WoodFrame.Internal.Npcs.AllNative().Select(delegate(NPC n)
				{
					//IL_0007: Unknown result type (might be due to invalid IL or missing references)
					//IL_000d: Unknown result type (might be due to invalid IL or missing references)
					//IL_0012: Unknown result type (might be due to invalid IL or missing references)
					//IL_0017: Unknown result type (might be due to invalid IL or missing references)
					Vector3 val = ((Component)n).transform.position - point;
					return (n: n, d: ((Vector3)(ref val)).sqrMagnitude);
				})
				where x.d <= radius * radius
				orderby x.d
				select new NpcRef(x.n.ID)).ToList();
		}

		public static void KeepCustomersVisible(Mod mod, params string[] ids)
		{
			string[] array = ids ?? Array.Empty<string>();
			foreach (string text in array)
			{
				if (!string.IsNullOrEmpty(text))
				{
					WoodFrame.Internal.Npcs.Visible.Add(text);
				}
			}
		}
	}
	public static class Customers
	{
		internal static readonly Hook OfferHook = new Hook("customer offer");

		internal static readonly Hook AcceptHook = new Hook("deal accepted");

		internal static readonly Hook DoneHook = new Hook("deal completed");

		public static IReadOnlyList<NpcRef> Unlocked
		{
			get
			{
				List<NpcRef> list = new List<NpcRef>();
				try
				{
					List<Customer> unlockedCustomers = Customer.UnlockedCustomers;
					int num = 0;
					while (unlockedCustomers != null && num < unlockedCustomers.Count)
					{
						Customer obj = unlockedCustomers[num];
						NPC val = ((obj != null) ? obj.NPC : null);
						if ((Object)(object)val != (Object)null)
						{
							list.Add(new NpcRef(val.ID));
						}
						num++;
					}
				}
				catch
				{
				}
				return list;
			}
		}

		public static event Action<DealInfo> OfferMade
		{
			add
			{
				OfferHook.Add(value);
			}
			remove
			{
				OfferHook.Remove(value);
			}
		}

		public static event Action<DealInfo> DealAccepted
		{
			add
			{
				AcceptHook.Add(value);
			}
			remove
			{
				AcceptHook.Remove(value);
			}
		}

		public static event Action<DealInfo> DealCompleted
		{
			add
			{
				DoneHook.Add(value);
			}
			remove
			{
				DoneHook.Remove(value);
			}
		}
	}
	public static class Phone
	{
		public static IReadOnlyList<PhoneApp> Apps => PhoneApps.Apps;

		public static bool IsOpen
		{
			get
			{
				try
				{
					return PlayerSingleton<Phone>.InstanceExists && PlayerSingleton<Phone>.Instance.IsOpen;
				}
				catch
				{
					return false;
				}
			}
		}

		public static void Notify(Mod mod, string title, string text, Sprite icon = null)
		{
			Guard.Run(mod, "phone notification", delegate
			{
				if (!Singleton<NotificationsManager>.InstanceExists)
				{
					mod?.Log(title + ": " + text);
				}
				else
				{
					Singleton<NotificationsManager>.Instance.SendNotification(title ?? "", text ?? "", icon ?? PhoneApps.DefaultIcon(mod), 5f, true);
				}
			});
		}

		public static bool Text(NpcRef from, string message)
		{
			//IL_002d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			if (from == null || string.IsNullOrEmpty(message))
			{
				return false;
			}
			try
			{
				NPC native = from.Native;
				MSGConversation val = ((native != null) ? native.MSGConversation : null);
				if (val == null)
				{
					return false;
				}
				val.SendMessage(new Message(message, (ESenderType)1, true, -1), true, true);
				return true;
			}
			catch (Exception ex)
			{
				Instance log = Core.Log;
				if (log != null)
				{
					log.Warning("Text from " + from.Id + ": " + ex.Message);
				}
				return false;
			}
		}

		public static PhoneApp AddApp(Mod mod, string title, Color color, Action<AppPage> build)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			PhoneApp phoneApp = new PhoneApp(mod, title, color, build);
			PhoneApps.Apps.Add(phoneApp);
			return phoneApp;
		}
	}
	public sealed class PhoneApp
	{
		internal Action<AppPage> Build;

		internal GameObject Icon;

		internal GameObject Panel;

		internal RectTransform Content;

		internal Action CloseAction;

		internal ExitDelegate ExitDelegate;

		public Mod Owner { get; }

		public string Title { get; }

		public Color Color { get; }

		public bool Built
		{
			get
			{
				if ((Object)(object)Icon != (Object)null)
				{
					return (Object)(object)Panel != (Object)null;
				}
				return false;
			}
		}

		public bool IsOpen
		{
			get
			{
				if ((Object)(object)Panel != (Object)null && Panel.activeSelf)
				{
					return (Object)(object)Phone.ActiveApp == (Object)(object)Panel;
				}
				return false;
			}
		}

		internal PhoneApp(Mod owner, string title, Color color, Action<AppPage> build)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			Owner = owner;
			Title = title ?? owner?.Name ?? "App";
			Color = color;
			Build = build;
		}

		public void Refresh()
		{
			PhoneApps.Fill(this);
		}

		public void Open()
		{
			PhoneApps.Open(this);
		}

		public void Close()
		{
			PhoneApps.Close(this);
		}
	}
	public sealed class AppPage
	{
		internal PhoneApp App;

		internal float Y;

		internal AppPage(PhoneApp app)
		{
			App = app;
		}

		public void Title(string text)
		{
			//IL_0004: Unknown result type (might be due to invalid IL or missing references)
			PhoneApps.Label(this, text, 30, Color.white, (FontStyle)1);
		}

		public void Text(string text, Color? color = null, int size = 20)
		{
			//IL_0026: 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)
			PhoneApps.Label(this, text, size, (Color)(((??)color) ?? new Color(0.88f, 0.88f, 0.88f)), (FontStyle)0);
		}

		public void Button(string label, Action onClick, Color? color = null)
		{
			PhoneApps.Button(this, null, label, onClick, color);
		}

		public void Row(string text, string buttonLabel, Action onClick, Color? textColor = null)
		{
			PhoneApps.Button(this, text, buttonLabel, onClick, null, textColor);
		}

		public void Space(float height = 12f)
		{
			Y += height;
		}
	}
	public sealed class PlacedItem
	{
		internal PlacedRecord Rec;

		public Item Item { get; }

		public string Uid => Rec.Uid;

		public GameObject GameObject { get; internal set; }

		public Vector3 Position => new Vector3(Rec.X, Rec.Y, Rec.Z);

		public float Yaw => Rec.Yaw;

		public Dictionary<string, string> Data
		{
			get
			{
				PlacedRecord rec = Rec;
				return rec.Data ?? (rec.Data = new Dictionary<string, string>());
			}
		}

		internal PlacedItem(Item item, PlacedRecord rec, GameObject go)
		{
			Item = item;
			Rec = rec;
			GameObject = go;
		}

		public void Remove()
		{
			Placement.Remove(this, give: false);
		}

		public bool ReturnToPlayer()
		{
			return Placement.Remove(this, give: true);
		}
	}
	public enum ProductKind
	{
		Weed,
		Meth,
		Cocaine,
		Shrooms
	}
	public sealed class ProductBuilder
	{
		internal readonly Product P;

		internal ProductBuilder(Mod mod, string id)
		{
			P = new Product(mod, id);
		}

		public ProductBuilder Name(string name)
		{
			P.Name = name;
			return this;
		}

		public ProductBuilder Kind(ProductKind kind)
		{
			P.Kind = kind;
			return this;
		}

		public ProductBuilder Effects(params string[] effectIds)
		{
			P.EffectIds = (from e in effectIds ?? Array.Empty<string>()
				where !string.IsNullOrWhiteSpace(e)
				select e.Trim()).Distinct().Take(8).ToList();
			return this;
		}

		public ProductBuilder Colors(Color main, Color second, Color? third = null)
		{
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: 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_0013: Unknown result type (might be due to invalid IL or missing references)
			P.Main = main;
			P.Second = second;
			P.Third = third;
			return this;
		}

		public ProductBuilder Price(float price)
		{
			P.WantPrice = Mathf.Max(1f, price);
			return this;
		}

		public ProductBuilder Listed(bool listed = true)
		{
			P.WantListed = listed;
			return this;
		}

		public Product Register()
		{
			Products.Add(P);
			return P;
		}
	}
	public sealed class Product
	{
		internal List<string> EffectIds = new List<string>();

		internal Color Main = new Color(0.4f, 0.7f, 0.3f);

		internal Color Second = new Color(0.3f, 0.5f, 0.2f);

		internal Color? Third;

		internal float? WantPrice;

		internal bool WantListed = true;

		internal bool Requested;

		internal bool Settled;

		internal float RequestedAt;

		public Mod Mod { get; }

		public string Id { get; }

		public string Name { get; internal set; }

		public ProductKind Kind { get; internal set; }

		public IReadOnlyList<string> Effects => EffectIds;

		public bool Exists
		{
			get
			{
				try
				{
					return Registry.ItemExists(Id);
				}
				catch
				{
					return false;
				}
			}
		}

		public bool Listed
		{
			get
			{
				try
				{
					List<ProductDefinition> listedProducts = ProductManager.ListedProducts;
					int num = 0;
					while (listedProducts != null && num < listedProducts.Count)
					{
						ProductDefinition obj = listedProducts[num];
						if (((obj != null) ? ((BaseItemDefinition)obj).ID : null) == Id)
						{
							return true;
						}
						num++;
					}
				}
				catch
				{
				}
				return false;
			}
		}

		public string State { get; internal set; } = "waiting for a save";

		internal Product(Mod mod, string id)
		{
			//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_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			Mod = mod;
			Id = (id ?? "").Trim();
			Name = Id;
		}

		public bool Give(int quantity = 1)
		{
			return Items.Give(Id, quantity);
		}

		public override string ToString()
		{
			return Name + " (" + Id + ")";
		}
	}
	public static class SelfCheck
	{
		public static string Text => Report.Last ?? "";

		public static IReadOnlyList<string> Problems => Report.Problems;

		public static string Run()
		{
			return Report.Build();
		}
	}
	public enum Restock
	{
		Daily,
		Weekly,
		Never
	}
	public sealed class ShopOffer
	{
		internal readonly List<string> _in = new List<string>();

		internal bool Withdrawn;

		public Mod Mod { get; internal set; }

		public string ItemId { get; internal set; }

		public string Shop { get; internal set; }

		public float? Price { get; internal set; }

		public int Stock { get; internal set; } = -1;

		public Restock Restock { get; internal set; }

		public bool Deliverable { get; internal set; } = true;

		public IReadOnlyList<string> InShops => _in;

		public void Withdraw()
		{
			Withdrawn = true;
			WoodFrame.Internal.Shops.Pull(this);
		}
	}
	public static class Shops
	{
		public const string GasMarts = "gas-mart";

		public const string Hardware = "hardware";

		public const string Oscar = "oscar";

		public const string Suppliers = "suppliers";

		public const string Everywhere = "all";

		public static IReadOnlyList<string> Names => (from s in WoodFrame.Internal.Shops.AllShops()
			select s.ShopName into n
			where !string.IsNullOrEmpty(n)
			select n).Distinct().ToList();

		public static ShopOffer Sell(Mod mod, string itemId, string shop, float? price = null, int stock = -1, Restock restock = Restock.Daily, bool deliverable = true)
		{
			ShopOffer shopOffer = new ShopOffer
			{
				Mod = mod,
				ItemId = itemId,
				Shop = (shop ?? "hardware"),
				Price = price,
				Stock = stock,
				Restock = restock,
				Deliverable = deliverable
			};
			WoodFrame.Internal.Shops.Offers.Add(shopOffer);
			WoodFrame.Internal.Shops.Dirty = true;
			return shopOffer;
		}
	}
	public static class Visuals
	{
		public static Material Material(Color color, float metallic = 0f, float smoothness = 0.3f, Color? emission = null)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			return Mats.Lit($"{ColorUtility.ToHtmlStringRGBA(color)}_{metallic:0.00}_{smoothness:0.00}_{(emission.HasValue ? ColorUtility.ToHtmlStringRGBA(emission.Value) : "-")}", color, metallic, smoothness, emission);
		}

		public static GameObject Part(Transform parent, PrimitiveType type, Vector3 position, Vector3 scale, Material material, Vector3? euler = null, bool collider = false, string name = null)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = GameObject.CreatePrimitive(type);
			if (!string.IsNullOrEmpty(name))
			{
				((Object)val).name = name;
			}
			if (!collider)
			{
				Collider component = val.GetComponent<Collider>();
				if ((Object)(object)component != (Object)null)
				{
					Object.Destroy((Object)(object)component);
				}
			}
			val.transform.SetParent(parent, false);
			val.transform.localPosition = position;
			val.transform.localScale = scale;
			if (euler.HasValue)
			{
				val.transform.localEulerAngles = euler.Value;
			}
			Renderer component2 = val.GetComponent<Renderer>();
			if ((Object)(object)component2 != (Object)null && (Object)(object)material != (Object)null)
			{
				component2.sharedMaterial = material;
			}
			return val;
		}

		public static GameObject Root(string name)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Expected O, but got Unknown
			return new GameObject(name ?? "Model");
		}

		public static GameObject LoadGlb(Mod mod, string resource)
		{
			return Guard.Get(mod, "loading " + resource, () => Glb.LoadEmbedded(mod.Assembly, resource, null));
		}
	}
}
namespace WoodFrame.Internal
{
	internal static class ClaimsData
	{
		internal static bool Seeded;

		internal static readonly List<Claim> Places = new List<Claim>();

		internal static readonly List<Claim> Live = new List<Claim>();

		private static float _liveAt = -100f;

		public static void RefreshLive()
		{
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f5: Unknown result type (might be due to invalid IL or missing references)
			if (Time.unscaledTime - _liveAt < 5f)
			{
				return;
			}
			_liveAt = Time.unscaledTime;
			Live.Clear();
			try
			{
				if (!((Compat.Fyb?.GetField("Reserved", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic))?.GetValue(null) is IDictionary dictionary))
				{
					return;
				}
				foreach (DictionaryEntry item in dictionary)
				{
					object value = item.Value;
					Type type = value?.GetType();
					if (!(type == null))
					{
						Vector3 centre = (Vector3)type.GetField("Item1").GetValue(value);
						float radius = (float)type.GetField("Item2").GetValue(value);
						Live.Add(new Claim
						{
							Mod = "Fortify Your Base (reserved ground)",
							Kind = "place",
							What = (item.Key as string),
							Centre = centre,
							Radius = radius
						});
					}
				}
			}
			catch
			{
			}
		}
	}
	internal static class Compat
	{
		internal static bool S1Api;

		internal static bool ModSettings;

		internal static bool Scanned;

		internal static Type Fyb;

		internal static List<string> WoodMods = new List<string>();

		private static PropertyInfo _fybDev;

		private static PropertyInfo _fybUse;

		private static float _anyListedCheckedAt = -100f;

		private static bool _anyListed;

		public static bool DevKeys
		{
			get
			{
				if (_fybDev != null)
				{
					try
					{
						return (bool)_fybDev.GetValue(null);
					}
					catch
					{
					}
				}
				try
				{
					return Core.OwnDevKeys?.Value ?? false;
				}
				catch
				{
					return false;
				}
			}
		}

		public static KeyCode UseKey
		{
			get
			{
				//IL_0018: 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_0026: Unknown result type (might be due to invalid IL or missing references)
				if (_fybUse != null)
				{
					try
					{
						return (KeyCode)_fybUse.GetValue(null);
					}
					catch
					{
					}
				}
				return (KeyCode)101;
			}
		}

		public static bool AnyListed
		{
			get
			{
				if (Time.unscaledTime - _anyListedCheckedAt < 10f)
				{
					return _anyListed;
				}
				_anyListedCheckedAt = Time.unscaledTime;
				try
				{
					_anyListed = Harmony.GetAllPatchedMethods().Any(delegate(MethodBase m)
					{
						Patches patchInfo = Harmony.GetPatchInfo(m);
						return patchInfo != null && patchInfo.Owners.Contains("WoodStudios.AnyListed");
					});
				}
				catch
				{
					_anyListed = false;
				}
				return _anyListed;
			}
		}

		public static void Scan()
		{
			Scanned = true;
			WoodMods = new List<string>();
			foreach (MelonBase registeredMelon in MelonBase.RegisteredMelons)
			{
				if (((registeredMelon != null) ? registeredMelon.Info : null) != null)
				{
					string text = registeredMelon.Info.Name ?? "";
					string text2 = "";
					try
					{
						text2 = registeredMelon.MelonAssembly.Assembly.GetName().Name ?? "";
					}
					catch
					{
					}
					if (text.IndexOf("S1API", StringComparison.OrdinalIgnoreCase) >= 0 || text2.StartsWith("S1API", StringComparison.OrdinalIgnoreCase))
					{
						S1Api = true;
					}
					if (text == "Mod Settings")
					{
						ModSettings = true;
					}
					if ((registeredMelon.Info.Author ?? "").IndexOf("Wood Studios", StringComparison.OrdinalIgnoreCase) >= 0 && text != "WoodFrame")
					{
						WoodMods.Add(text);
					}
				}
			}
			if (!S1Api)
			{
				S1Api = AppDomain.CurrentDomain.GetAssemblies().Any((Assembly a) => (a.GetName().Name ?? "").StartsWith("S1API", StringComparison.OrdinalIgnoreCase));
			}
			try
			{
				Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies();
				foreach (Assembly assembly in assemblies)
				{
					if (!(assembly.GetName().Name != "HoldTheFort"))
					{
						Fyb = assembly.GetType("HoldTheFort.FortifyApi");
						_fybDev = Fyb?.GetProperty("DevKeys", BindingFlags.Static | BindingFlags.Public);
						_fybUse = Fyb?.GetProperty("UseKey", BindingFlags.Static | BindingFlags.Public);
					}
				}
			}
			catch
			{
			}
			Instance log = Core.Log;
			if (log != null)
			{
				log.Msg($"Found {WoodMods.Count} Wood Studios mod(s){(S1Api ? ", S1API" : "")}{((Fyb != null) ? ", Fortify Your Base" : "")}{(ModSettings ? ", Mod Settings" : "")}. WoodFrame works alongside all of them.");
			}
		}
	}
	public sealed class Core : MelonMod
	{
		internal static Instance Log;

		internal static Core Instance;

		internal static int SelfFaults;

		internal static Harmony Patches;

		internal static Mod SelfMod;

		private static bool _started;

		internal static MelonPreferences_Category Prefs;

		internal static MelonPreferences_Entry<bool> OwnDevKeys;

		internal static MelonPreferences_Entry<bool> LogSelfCheck;

		internal static MelonPreferences_Entry<bool> WriteSelfCheckFile;

		internal static void EnsureStarted()
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0024: Expected O, but got Unknown
			if (!_started)
			{
				_started = true;
				if (Log == null)
				{
					Log = new Instance("WoodFrame");
				}
				try
				{
					Prefs = MelonPreferences.GetCategory("WoodFrame") ?? MelonPreferences.CreateCategory("WoodFrame", "WoodFrame");
					OwnDevKeys = Prefs.GetEntry<bool>("DevKeys") ?? Prefs.CreateEntry<bool>("DevKeys", false, "Developer keys", "Turns on developer keys for mods built on WoodFrame (only used when Fortify Your Base is not installed; it has its own).", false, false, (ValueValidator)null, (string)null);
					LogSelfCheck = Prefs.GetEntry<bool>("LogSelfCheck") ?? Prefs.CreateEntry<bool>("LogSelfCheck", true, "Self-check in the log", "After a save loads, write a short health report of every mod on WoodFrame to the log.", false, false, (ValueValidator)null, (string)null);
					WriteSelfCheckFile = Prefs.GetEntry<bool>("WriteSelfCheckFile") ?? Prefs.CreateEntry<bool>("WriteSelfCheckFile", true, "Self-check file", "Also write the full report to UserData/WoodFrame/SelfCheck.txt.", false, false, (ValueValidator)null, (string)null);
				}
				catch (Exception ex)
				{
					Log.Warning("Settings: " + ex.Message);
				}
				Guard.Self("claims", Claims.SeedWoodStudios);
				Guard.Self("keys", Keys.Load);
			}
		}

		public override void OnInitializeMelon()
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Expected O, but got Unknown
			Instance = this;
			Log = ((MelonBase)this).LoggerInstance;
			EnsureStarted();
			Patches = new Harmony("WoodStudios.WoodFrame");
			SelfMod = new Mod((MelonBase)(object)this, "woodframe");
			Log.Msg($"WoodFrame {"1.0.0"} (API level {1}) ready for mods to build on.");
		}

		public override void OnLateInitializeMelon()
		{
			Guard.Self("compat", Compat.Scan);
			Guard.Self("own app", FrameApp.Register);
		}

		public override void OnSceneWasLoaded(int buildIndex, string sceneName)
		{
			Guard.Self("scene", delegate
			{
				Lifecycle.Scene(sceneName);
			});
		}

		public override void OnUpdate()
		{
			Guard.Self("lifecycle", Lifecycle.Tick);
			Guard.Self("items", Items.Tick);
			Guard.Self("shops", Shops.Tick);
			Guard.Self("products", Products.Tick);
			Guard.Self("npcs", Npcs.Tick);
			Guard.Self("phone", PhoneApps.Tick);
			Guard.Self("keys", Keys.Tick);
			Guard.Self("placement", Placement.Tick);
			Guard.Self("report", Report.Tick);
		}

		public override void OnGUI()
		{
			Guard.Self("placement hint", Placement.DrawHint);
			Guard.Self("rebind", Keys.DrawCapture);
		}

		public override void OnApplicationQuit()
		{
			Guard.Self("quit", Lifecycle.Quit);
		}
	}
	internal interface IDataSlot
	{
		string Key { get; }

		Mod Owner { get; }

		void Load(JsonObject entry);

		JsonObject Save();

		void Unload();
	}
	internal static class Store
	{
		internal const string FolderName = "WoodFrame";

		internal const int Format = 1;

		internal static readonly JsonSerializerOptions Json = new JsonSerializerOptions
		{
			IncludeFields = true,
			WriteIndented = true,
			AllowTrailingCommas = true,
			ReadCommentHandling = JsonCommentHandling.Skip
		};

		private static readonly Dictionary<Mod, List<IDataSlot>> Slots = new Dictionary<Mod, List<IDataSlot>>();

		private static readonly Dictionary<Mod, JsonObject> Files = new Dictionary<Mod, JsonObject>();

		private static readonly HashSet<Mod> Broken = new HashSet<Mod>();

		private static string _folder;

		private static bool _loaded;

		public static int Writes;

		public static int WriteFailures;

		public static string LastWriteError;

		public static int SlotCount
		{
			get
			{
				int num = 0;
				foreach (List<IDataSlot> value in Slots.Values)
				{
					num += value.Count;
				}
				return num;
			}
		}

		public static SaveData<T> Open<T>(Mod mod, string key, int version) where T : class, new()
		{
			key = Clean(key);
			foreach (IDataSlot item in List(mod))
			{
				if (item.Key == key)
				{
					return (item as SaveData<T>) ?? throw new InvalidOperationException("Saved data '" + key + "' was opened before with a different type.");
				}
			}
			SaveData<T> saveData = new SaveData<T>(mod, key, version);
			List(mod).Add(saveData);
			if (_loaded)
			{
				LoadSlot(mod, saveData);
			}
			return saveData;
		}

		public static PlayerData<T> OpenPlayers<T>(Mod mod, string key, int version) where T : class, new()
		{
			key = Clean(key);
			foreach (IDataSlot item in List(mod))
			{
				if (item.Key == "players/" + key)
				{
					return (item as PlayerData<T>) ?? throw new InvalidOperationException("Player data '" + key + "' was opened before with a different type.");
				}
			}
			PlayerData<T> playerData = new PlayerData<T>(mod, key, version);
			List(mod).Add(playerData);
			if (_loaded)
			{
				LoadSlot(mod, playerData);
			}
			return playerData;
		}

		internal static JsonNode Clone(JsonNode n)
		{
			if (n != null)
			{
				return JsonNode.Parse(n.ToJsonString());
			}
			return null;
		}

		private static string Clean(string key)
		{
			if (!string.IsNullOrWhiteSpace(key))
			{
				return key.Trim();
			}
			return "data";
		}

		private static List<IDataSlot> List(Mod mod)
		{
			if (!Slots.TryGetValue(mod, out var value))
			{
				value = (Slots[mod] = new List<IDataSlot>());
			}
			return value;
		}

		private static string FileOf(string folder, Mod mod)
		{
			return Path.Combine(folder, "WoodFrame", Registry.CleanId(mod.Id) + ".json");
		}

		public static void LoadAll(string folder)
		{
			_folder = folder;
			Files.Clear();
			Broken.Clear();
			_loaded = true;
			foreach (KeyValuePair<Mod, List<IDataSlot>> slot in Slots)
			{
				foreach (IDataSlot item in slot.Value)
				{
					LoadSlot(slot.Key, item);
				}
			}
		}

		private static JsonObject FileFor(Mod mod)
		{
			if (Files.TryGetValue(mod, out var value))
			{
				return value;
			}
			value = null;
			if (_folder != null)
			{
				string text = FileOf(_folder, mod);
				value = Read(text, out var error);
				if (value == null && error != null)
				{
					string error2;
					JsonObject jsonObject = Read(text + ".bak", out error2);
					if (jsonObject != null)
					{
						value = jsonObject;
						Instance log = Core.Log;
						if (log != null)
						{
							log.Warning(mod.Name + ": its saved data file couldn't be read (" + error + "); using the backup from the save before.");
						}
					}
					else
					{
						Broken.Add(mod);
						Instance log2 = Core.Log;
						if (log2 != null)
						{
							log2.Error($"{mod.Name}: its saved data file couldn't be read ({error}). It is kept as it is and set aside at the next save; {mod.Name} starts fresh for this save.");
						}
						Report.Problem(mod.Name + ": saved data unreadable (" + error + ")");
					}
				}
			}
			Files[mod] = value ?? (value = new JsonObject());
			return value;
		}

		private static JsonObject Read(string file, out string error)
		{
			error = null;
			try
			{
				if (!File.Exists(file))
				{
					return null;
				}
				string json = File.ReadAllText(file, Encoding.UTF8);
				JsonDocumentOptions documentOptions = new JsonDocumentOptions
				{
					AllowTrailingCommas = true,
					CommentHandling = JsonCommentHandling.Skip
				};
				if (JsonNode.Parse(json, null, documentOptions) is JsonObject result)
				{
					return result;
				}
				error = "not a WoodFrame data file";
			}
			catch (Exception ex)
			{
				error = ex.Message;
			}
			return null;
		}

		private static void LoadSlot(Mod mod, IDataSlot slot)
		{
			JsonObject jsonObject = FileFor(mod);
			JsonObject entry = null;
			try
			{
				entry = jsonObject["entries"]?[slot.Key] as JsonObject;
			}
			catch
			{
			}
			Guard.Run(mod, "loading '" + slot.Key + "'", delegate
			{
				slot.Load(entry);
			});
		}

		public static void Unload()
		{
			_loaded = false;
			_folder = null;
			Files.Clear();
			Broken.Clear();
			foreach (List<IDataSlot> value in Slots.Values)
			{
				foreach (IDataSlot item in value)
				{
					Guard.Self("unload", item.Unload);
				}
			}
		}

		public static void Approve(SaveManager sm)
		{
			try
			{
				List<string> val = ((sm != null) ? sm.ApprovedBaseLevelPaths : null);
				if (val != null && !val.Contains("WoodFrame"))
				{
					val.Add("WoodFrame");
				}
			}
			catch
			{
			}
		}

		public static void WriteAll(string folder)
		{
			if (string.IsNullOrEmpty(folder) || Slots.Count == 0)
			{
				return;
			}
			string path = Path.Combine(folder, "WoodFrame");
			foreach (KeyValuePair<Mod, List<IDataSlot>> slot in Slots)
			{
				Mod key = slot.Key;
				try
				{
					JsonObject jsonObject = (FileFor(key)["entries"] as JsonObject) ?? new JsonObject();
					foreach (IDataSlot item in slot.Value)
					{
						JsonObject jsonObject2 = item.Save();
						if (jsonObject2 != null)
						{
							jsonObject[item.Key] = jsonObject2;
						}
					}
					JsonObject jsonObject3 = new JsonObject
					{
						["format"] = 1,
						["woodframe"] = "1.0.0",
						["mod"] = key.Id,
						["modName"] = key.Name,
						["modVersion"] = key.Version,
						["savedUtc"] = DateTime.UtcNow.ToString("o"),
						["entries"] = Clone(jsonObject)
					};
					Directory.CreateDirectory(path);
					string text = FileOf(folder, key);
					if (Broken.Remove(key) && File.Exists(text))
					{
						try
						{
							File.Move(text, text + ".unreadable-" + DateTime.Now.ToString("yyyyMMdd-HHmmss"));
						}
						catch
						{
						}
					}
					WriteAtomic(text, jsonObject3.ToJsonString(Json));
					Files[key] = jsonObject3;
					Writes++;
				}
				catch (Exception ex)
				{
					WriteFailures++;
					LastWriteError = key.Name + ": " + ex.Message;
					Instance log = Core.Log;
					if (log != null)
					{
						log.Error($"Couldn't write {key.Name}'s saved data: {ex.Message}. The game's own save is not affected.");
					}
				}
			}
		}

		internal static void WriteAtomic(string file, string text)
		{
			string text2 = file + ".tmp";
			byte[] bytes = new UTF8Encoding(encoderShouldEmitUTF8Identifier: false).GetBytes(text);
			using (FileStream fileStream = new FileStream(text2, FileMode.Create, FileAccess.Write, FileShare.None))
			{
				fileStream.Write(bytes, 0, bytes.Length);
				fileStream.Flush(flushToDisk: true);
			}
			if (File.Exists(file))
			{
				try
				{
					File.Replace(text2, file, file + ".bak", ignoreMetadataErrors: true);
					return;
				}
				catch
				{
					try
					{
						File.Copy(file, file + ".bak", overwrite: true);
					}
					catch
					{
					}
				}
			}
			File.Move(text2, file, overwrite: true);
		}
	}
	internal static class Registry
	{
		private static readonly List<Mod> List = new List<Mod>();

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

		private static readonly Dictionary<Assembly, Mod> Asms = new Dictionary<Assembly, Mod>();

		public static IReadOnlyList<Mod> All => List;

		public static Mod ById(string id)
		{
			if (id == null || !Ids.TryGetValue(id, out var value))
			{
				return null;
			}
			return value;
		}

		public static Mod ByAssembly(Assembly a)
		{
			if (!(a != null) || !Asms.TryGetValue(a, out var value))
			{
				return null;
			}
			return value;
		}

		public static string CleanId(string id)
		{
			return new string((from c in (id ?? "").Trim().ToLowerInvariant()
				select (!char.IsLetterOrDigit(c) && c != '.' && c != '-' && c != '_') ? '.' : c).ToArray()).Trim('.');
		}

		public static Mod Add(MelonBase melon, string id)
		{
			foreach (Mod item in List)
			{
				if (item.Melon == melon)
				{
					return item;
				}
			}
			if (string.IsNullOrWhiteSpace(id))
			{
				try
				{
					MelonAssembly melonAssembly = melon.MelonAssembly;
					id = ((melonAssembly == null) ? null : melonAssembly.Assembly?.GetName().Name);
				}
				catch
				{
				}
				if (id == null)
				{
					MelonInfoAttribute info = melon.Info;
					id = ((info != null) ? info.Name : null) ?? "mod";
				}
			}
			id = CleanId(id);
			if (id.Length == 0)
			{
				id = "mod";
			}
			if (Ids.ContainsKey(id))
			{
				string text = id;
				int num = 2;
				while (Ids.ContainsKey(id))
				{
					id = text + "-" + num++;
				}
				Instance log = Core.Log;
				DefaultInterpolatedStringHandler defaultInterpolatedStringHandler;
				if (log != null)
				{
					defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(79, 4);
					defaultInterpolatedStringHandler.AppendLiteral("Two mods want the id '");
					defaultInterpolatedStringHandler.AppendFormatted(text);
					defaultInterpolatedStringHandler.AppendLiteral("': ");
					defaultInterpolatedStringHandler.AppendFormatted(Ids[text].Name);
					defaultInterpolatedStringHandler.AppendLiteral(" has it, so ");
					MelonInfoAttribute info2 = melon.Info;
					defaultInterpolatedStringHandler.AppendFormatted((info2 != null) ? info2.Name : null);
					defaultInterpolatedStringHandler.AppendLiteral(" gets '");
					defaultInterpolatedStringHandler.AppendFormatted(id);
					defaultInterpolatedStringHandler.AppendLiteral("'. Please give your mod its own id.");
					log.Warning(defaultInterpolatedStringHandler.ToStringAndClear());
				}
				defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(27, 3);
				defaultInterpolatedStringHandler.AppendLiteral("Duplicate mod id '");
				defaultInterpolatedStringHandler.AppendFormatted(text);
				defaultInterpolatedStringHandler.AppendLiteral("' (");
				defaultInterpolatedStringHandler.AppendFormatted(Ids[text].Name);
				defaultInterpolatedStringHandler.AppendLiteral(" and ");
				MelonInfoAttribute info3 = melon.Info;
				defaultInterpolatedStringHandler.AppendFormatted((info3 != null) ? info3.Name : null);
				defaultInterpolatedStringHandler.AppendLiteral(")");
				Report.Problem(defaultInterpolatedStringHandler.ToStringAndClear());
			}
			Mod mod = new Mod(melon, id);
			List.Add(mod);
			Ids[id] = mod;
			if (mod.Assembly != null && !Asms.ContainsKey(mod.Assembly))
			{
				Asms[mod.Assembly] = mod;
			}
			Instance log2 = Core.Log;
			if (log2 != null)
			{
				log2.Msg($"{mod.Name} {mod.Version} registered as '{id}'.");
			}
			return mod;
		}
	}
	internal static class FrameApp
	{
		private static PhoneApp _app;

		private static bool _showAllClaims;

		public static void Register()
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			if (_app != null)
			{
				return;
			}
			if (Frame.Mods.Count == 0)
			{
				Instance log = Core.Log;
				if (log != null)
				{
					log.Msg("No mods use WoodFrame yet, so it adds nothing to the phone.");
				}
			}
			else
			{
				_app = Phone.AddApp(Core.SelfMod, "WoodFrame", new Color(0.55f, 0.36f, 0.2f), Build);
			}
		}

		public static void Refresh()
		{
			try
			{
				if (_app != null && _app.IsOpen)
				{
					_app.Refresh();
				}
			}
			catch
			{
			}
		}

		private static void Build(AppPage p)
		{
			//IL_0228: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_045e: Unknown result type (might be due to invalid IL or missing references)
			//IL_05a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_0592: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_0661: Unknown result type (might be due to invalid IL or missing references)
			p.Title("WoodFrame 1.0.0");
			p.Text($"{Frame.Mods.Count} mod(s) built on WoodFrame: {string.Join(", ", Frame.Mods.Select((Mod m) => m.Name + " " + m.Version))}");
			p.Space();
			p.Title("Keys");
			if (Keys.All.Count == 0)
			{
				p.Text("No mod has a key here yet.");
			}
			foreach (Keybind item in Keys.All.Where((Keybind k) => !k.DevOnly || Frame.DevKeys))
			{
				Keybind bind = item;
				IReadOnlyList<string> conflicts = bind.Conflicts;
				string text = $"{bind.Owner.Name}: {bind.Label}   [{bind.Text}]{(bind.DevOnly ? " (developer)" : "")}{((conflicts.Count > 0) ? ("\nAlso used by " + string.Join("; ", conflicts)) : "")}";
				p.Row(text, (Keys.Capturing == bind) ? "Press a key..." : "Change", delegate
				{
					Keys.StartCapture(bind);
					_app?.Refresh();
				}, (conflicts.Count > 0) ? new Color?(new Color(1f, 0.72f, 0.45f)) : ((Color?)null));
			}
			if (Keys.All.Count > 0)
			{
				p.Button("Put every key back to its default", delegate
				{
					foreach (Keybind item2 in Keys.All)
					{
						item2.ResetToDefault();
					}
					_app?.Refresh();
				});
			}
			p.Space();
			p.Title("World claims");
			IReadOnlyList<Claim> all = Claims.All;
			p.Text($"{all.Count((Claim x) => x.Kind == "place")} places, {all.Count((Claim x) => x.Kind == "deaddrop")} dead drops and {all.Count((Claim x) => x.Kind == "key")} keys are taken by mods (Wood Studios mods included), so mods on WoodFrame keep clear of them.");
			foreach (Claim item3 in DeadDrops.AllClaims().Take(_showAllClaims ? 999 : 0))
			{
				p.Text("Dead drop " + DeadDrops.NameOf(item3.Value) + ": " + item3.Mod, (Color?)new Color(0.75f, 0.75f, 0.75f), 18);
			}
			foreach (Claim item4 in all.Where((Claim x) => x.Kind == "place").Take(_showAllClaims ? 999 : 0))
			{
				p.Text(item4.ToString(), (Color?)new Color(0.75f, 0.75f, 0.75f), 18);
			}
			p.Button(_showAllClaims ? "Hide the list" : "Show the list", delegate
			{
				_showAllClaims = !_showAllClaims;
				_app?.Refresh();
			});
			p.Space();
			p.Title("Self-check");
			p.Text(string.IsNullOrEmpty(SelfCheck.Text) ? "Runs about half a minute after a save loads." : (SelfCheck.Text.Split('\n').FirstOrDefault((string l) => l.StartsWith("Items")) ?? ""));
			List<string> problems = Report.Problems;
			p.Text((problems.Count == 0) ? "No problems found." : $"{problems.Count} problem(s):", (Color?)((problems.Count == 0) ? new Color(0.6f, 0.9f, 0.6f) : new Color(1f, 0.72f, 0.45f)), 20);
			foreach (string item5 in problems.Skip(Math.Max(0, problems.Count - 8)))
			{
				p.Text(item5, (Color?)new Color(0.85f, 0.85f, 0.85f), 18);
			}
			p.Button("Run the self-check now", delegate
			{
				Report.Build();
				Report.WriteFile();
				_app?.Refresh();
			});
			p.Text("The full report is in UserData/WoodFrame/SelfCheck.txt.", (Color?)new Color(0.7f, 0.7f, 0.7f), 17);
		}
	}
	internal static class Glb
	{
		public static GameObject LoadEmbedded(Assembly asm, string resource, Transform parent)
		{
			string text = resource;
			string[] manifestResourceNames = asm.GetManifestResourceNames();
			if (Array.IndexOf(manifestResourceNames, text) < 0)
			{
				string[] array = manifestResourceNames;
				foreach (string text2 in array)
				{
					if (text2.EndsWith(resource, StringComparison.OrdinalIgnoreCase))
					{
						text = text2;
						break;
					}
				}
			}
			using Stream stream = asm.GetManifestResourceStream(text);
			if (stream == null)
			{
				throw new FileNotFoundException("Embedded model missing: " + resource);
			}
			using MemoryStream memoryStream = new MemoryStream();
			stream.CopyTo(memoryStream);
			return Load(memoryStream.ToArray(), Path.GetFileNameWithoutExtension(resource), parent);
		}

		public static GameObject Load(byte[] glb, string name, Transform parent)
		{
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Expected O, but got Unknown
			if (glb.Length < 20 || BitConverter.ToUInt32(glb, 0) != 1179937895)
			{
				throw new InvalidDataException("Not a GLB file");
			}
			int num = (int)BitConverter.ToUInt32(glb, 12);
			string json = Encoding.UTF8.GetString(glb, 20, num);
			int bin = 20 + num + 8;
			using JsonDocument jsonDocument = JsonDocument.Parse(json);
			JsonElement rootElement = jsonDocument.RootElement;
			Material[] materials = BuildMaterials(rootElement);
			Dictionary<int, (Mesh, Material[])> meshCache = new Dictionary<int, (Mesh, Material[])>();
			GameObject val = new GameObject(name);
			val.transform.SetParent(parent, false);
			JsonElement property = rootElement.GetProperty("nodes");
			HashSet<int> hashSet = new HashSet<int>();
			for (int i = 0; i < property.GetArrayLength(); i++)
			{
				if (!property[i].TryGetProperty("children", out var value))
				{
					continue;
				}
				foreach (JsonElement item in value.EnumerateArray())
				{
					hashSet.Add(item.GetInt32());
				}
			}
			for (int j = 0; j < property.GetArrayLength(); j++)
			{
				if (!hashSet.Contains(j))
				{
					BuildNode(rootElement, property, j, val.transform, glb, bin, materials, meshCache);
				}
			}
			return val;
		}

		private static void BuildNode(JsonElement root, JsonElement nodes, int index, Transform parent, byte[] glb, int bin, Material[] materials, Dictionary<int, (Mesh, Material[])> meshCache)
		{
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_008d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ee: 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)
			JsonElement jsonElement = nodes[index];
			JsonElement value;
			GameObject val = new GameObject(jsonElement.TryGetProperty("name", out value) ? value.GetString() : ("node" + index));
			Transform transform = val.transform;
			transform.SetParent(parent, false);
			if (jsonElement.TryGetProperty("translation", out var value2))
			{
				transform.localPosition = new Vector3(value2[0].GetSingle(), value2[1].GetSingle(), 0f - value2[2].GetSingle());
			}
			if (jsonElement.TryGetProperty("rotation", out var value3))
			{
				transform.localRotation = new Quaternion(0f - value3[0].GetSingle(), 0f - value3[1].GetSingle(), value3[2].GetSingle(), value3[3].GetSingle());
			}
			if (jsonElement.TryGetProperty("scale", out var value4))
			{
				transform.localScale = new Vector3(value4[0].GetSingle(), value4[1].GetSingle(), value4[2].GetSingle());
			}
			if (jsonElement.TryGetProperty("mesh", out var value5))
			{
				int @int = value5.GetInt32();
				if (!meshCache.TryGetValue(@int, out var value6))
				{
					value6 = (meshCache[@int] = BuildMesh(root, @int, glb, bin, materials));
				}
				val.AddComponent<MeshFilter>().sharedMesh = value6.Item1;
				MeshRenderer val2 = val.AddComponent<MeshRenderer>();
				Il2CppReferenceArray<Material> val3 = new Il2CppReferenceArray<Material>((long)value6.Item2.Length);
				for (int i = 0; i < value6.Item2.Length; i++)
				{
					((Il2CppArrayBase<Material>)(object)val3)[i] = value6.Item2[i];
				}
				((Renderer)val2).sharedMaterials = val3;
			}
			if (!jsonElement.TryGetProperty("children", out var value7))
			{
				return;
			}
			foreach (JsonElement item in value7.EnumerateArray())
			{
				BuildNode(root, nodes, item.GetInt32(), transform, glb, bin, materials, meshCache);
			}
		}

		private static (Mesh, Material[]) BuildMesh(JsonElement root, int meshIndex, byte[] glb, int bin, Material[] materials)
		{
			//IL_02cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ed: Expected O, but got Unknown
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: 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_0188: Unknown result type (might be due to invalid IL or missing references)
			//IL_0289: Unknown result type (might be due to invalid IL or missing references)
			JsonElement property = root.GetProperty("meshes")[meshIndex].GetProperty("primitives");
			List<Vector3> list = new List<Vector3>();
			List<Vector3> list2 = new List<Vector3>();
			List<Vector2> list3 = new List<Vector2>();
			List<int[]> list4 = new List<int[]>();
			List<Material> list5 = new List<Material>();
			foreach (JsonElement item in property.EnumerateArray())
			{
				JsonElement property2 = item.GetProperty("attributes");
				int count = list.Count;
				int count2;
				float[] array = ReadFloats(root, property2.GetProperty("POSITION").GetInt32(), glb, bin, out count2);
				for (int i = 0; i < count2; i++)
				{
					list.Add(new Vector3(array[i * 3], array[i * 3 + 1], 0f - array[i * 3 + 2]));
				}
				int count3;
				if (property2.TryGetProperty("NORMAL", out var value))
				{
					float[] array2 = ReadFloats(root, value.GetInt32(), glb, bin, out count3);
					for (int j = 0; j < count2; j++)
					{
						list2.Add(new Vector3(array2[j * 3], array2[j * 3 + 1], 0f - array2[j * 3 + 2]));
					}
				}
				else
				{
					for (int k = 0; k < count2; k++)
					{
						list2.Add(Vector3.up);
					}
				}
				if (property2.TryGetProperty("TEXCOORD_0", out var value2))
				{
					float[] array3 = ReadFloats(root, value2.GetInt32(), glb, bin, out count3);
					for (int l = 0; l < count2; l++)
					{
						list3.Add(new Vector2(array3[l * 2], 1f - array3[l * 2 + 1]));
					}
				}
				else
				{
					for (int m = 0; m < count2; m++)
					{
						list3.Add(Vector2.zero);
					}
				}
				int[] array4;
				if (item.TryGetProperty("indices", out var value3))
				{
					array4 = ReadIndices(root, value3.GetInt32(), glb, bin);
				}
				else
				{
					array4 = new int[count2];
					for (int n = 0; n < count2; n++)
					{
						array4[n] = n;
					}
				}
				for (int num = 0; num + 2 < array4.Length; num += 3)
				{
					int num2 = array4[num] + count;
					int num3 = array4[num + 1] + count;
					int num4 = array4[num + 2] + count;
					array4[num] = num2;
					array4[num + 1] = num4;
					array4[num + 2] = num3;
				}
				list4.Add(array4);
				JsonElement value4;
				int num5 = (item.TryGetProperty("material", out value4) ? value4.GetInt32() : (-1));
				list5.Add((num5 >= 0 && num5 < materials.Length) ? materials[num5] : Mats.Lit("gltf_default", Color.gray));
			}
			Mesh val = new Mesh
			{
				name = "HTF_" + meshIndex
			};
			if (list.Count > 65000)
			{
				val.indexFormat = (IndexFormat)1;
			}
			val.vertices = new Il2CppStructArray<Vector3>(list.ToArray());
			val.normals = new Il2CppStructArray<Vector3>(list2.ToArray());
			val.uv = new Il2CppStructArray<Vector2>(list3.ToArray());
			val.subMeshCount = list4.Count;
			for (int num6 = 0; num6 < list4.Count; num6++)
			{
				val.SetTriangles(new Il2CppStructArray<int>(list4[num6]), num6);
			}
			val.RecalculateBounds();
			((Object)val).hideFlags = (HideFlags)32;
			return (val, list5.ToArray());
		}

		private static Material[] BuildMaterials(JsonElement root)
		{
			//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)
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01b3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d4: Unknown result type (might be due to invalid IL or missing references)
			if (!root.TryGetProperty("materials", out var value))
			{
				return Array.Empty<Material>();
			}
			Material[] array = (Material[])(object)new Material[value.GetArrayLength()];
			for (int i = 0; i < array.Length; i++)
			{
				JsonElement jsonElement = value[i];
				JsonElement value2;
				string text = (jsonElement.TryGetProperty("name", out value2) ? value2.GetString() : ("mat" + i));
				Color white = Color.white;
				float metallic = 1f;
				float num = 1f;
				if (jsonElement.TryGetProperty("pbrMetallicRoughness", out var value3))
				{
					if (value3.TryGetProperty("baseColorFactor", out var value4))
					{
						((Color)(ref white))..ctor(value4[0].GetSingle(), value4[1].GetSingle(), value4[2].GetSingle(), value4[3].GetSingle());
					}
					if (value3.TryGetProperty("metallicFactor", out var value5))
					{
						metallic = value5.GetSingle();
					}
					if (value3.TryGetProperty("roughnessFactor", out var value6))
					{
						num = value6.GetSingle();
					}
				}
				Color? emission = null;
				if (jsonElement.TryGetProperty("emissiveFactor", out var value7))
				{
					float num2 = 1f;
					if (jsonElement.TryGetProperty("extensions", out var value8) && value8.TryGetProperty("KHR_materials_emissive_strength", out var value9) && value9.TryGetProperty("emissiveStrength", out var value10))
					{
						num2 = value10.GetSingle();
					}
					Color value11 = new Color(value7[0].GetSingle(), value7[1].GetSingle(), value7[2].GetSingle()) * Mathf.Min(num2, 8f) * 0.5f;
					if (((Color)(ref value11)).maxColorComponent > 0.001f)
					{
						emission = value11;
					}
				}
				array[i] = Mats.Lit("glb_" + text, white, metallic, 1f - num, emission);
			}
			return array;
		}

		private static float[] ReadFloats(JsonElement root, int accessor, byte[] glb, int bin, out int count)
		{
			JsonElement jsonElement = root.GetProperty("accessors")[accessor];
			count = jsonElement.GetProperty("count").GetInt32();
			int num = Components(jsonElement.GetProperty("type").GetString());
			JsonElement jsonElement2 = root.GetProperty("bufferViews")[jsonElement.GetProperty("bufferView").GetInt32()];
			JsonElement value;
			JsonElement value2;
			int num2 = bin + (jsonElement2.TryGetProperty("byteOffset", out value) ? value.GetInt32() : 0) + (jsonElement.TryGetProperty("byteOffset", out value2) ? value2.GetInt32() : 0);
			JsonElement value3;
			int num3 = (jsonElement2.TryGetProperty("byteStride", out value3) ? value3.GetInt32() : (num * 4));
			float[] array = new float[count * num];
			for (int i = 0; i < count; i++)
			{
				for (int j = 0; j < num; j++)
				{
					array[i * num + j] = BitConverter.ToSingle(glb, num2 + i * num3 + j * 4);
				}
			}
			return array;
		}

		private static int[] ReadIndices(JsonElement root, int accessor, byte[] glb, int bin)
		{
			JsonElement jsonElement = root.GetProperty("accessors")[accessor];
			int @int = jsonElement.GetProperty("count").GetInt32();
			int int2 = jsonElement.GetProperty("componentType").GetInt32();
			JsonElement value;
			JsonElement value2;
			int num = bin + (root.GetProperty("bufferViews")[jsonElement.GetProperty("bufferView").GetInt32()].TryGetProperty("byteOffset", out value) ? value.GetInt32() : 0) + (jsonElement.TryGetProperty("byteOffset", out value