Decompiled source of PlantEverything1point0fork v1.21.1

plugins/Advize_PlantEverything.dll

Decompiled 3 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using ServerSync;
using SoftReferenceableAssets;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyTitle("Advize_PlantEverything")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Valheim Game Modification")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("85f3bb36-d51d-4e6c-a523-feb593b3156f")]
[assembly: AssemblyFileVersion("1.21.1.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.21.1.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
internal class ConfigurationManagerAttributes
{
	public bool? Browsable;

	public string? Category;

	public int? Order;

	public bool? ReadOnly;
}
namespace Advize_PlantEverything
{
	public static class SeasonsCompatibility
	{
		private static bool _isInitialized;

		private static bool _isReady;

		private const string GUID = "shudnal.Seasons";

		private static Assembly _assembly;

		private static FieldInfo _seasonState;

		private static MethodInfo _getSecondsToRespawnPickable;

		private static MethodInfo _getSecondsToGrowPlant;

		public static bool IsReady
		{
			get
			{
				if (!_isInitialized)
				{
					Initialize();
				}
				return _isReady;
			}
		}

		public static double GetSecondsToRespawnPickable(Pickable pickable)
		{
			return (double)_getSecondsToRespawnPickable.Invoke(_seasonState.GetValue(_seasonState), new object[1] { pickable });
		}

		public static double GetSecondsToGrowPlant(Plant plant)
		{
			return (double)_getSecondsToGrowPlant.Invoke(_seasonState.GetValue(_seasonState), new object[1] { plant });
		}

		private static void Initialize()
		{
			_isInitialized = true;
			if (Chainloader.PluginInfos.TryGetValue("shudnal.Seasons", out var value))
			{
				_assembly = Assembly.GetAssembly(((object)value.Instance).GetType());
				if (_assembly != null)
				{
					_seasonState = AccessTools.Field(_assembly.GetType("Seasons.Seasons"), "seasonState");
					_getSecondsToRespawnPickable = AccessTools.Method(_seasonState.FieldType, "GetSecondsToRespawnPickable", (Type[])null, (Type[])null);
					_getSecondsToGrowPlant = AccessTools.Method(_seasonState.FieldType, "GetSecondsToGrowPlant", (Type[])null, (Type[])null);
				}
			}
			_isReady = _seasonState != null && _getSecondsToRespawnPickable != null && _getSecondsToGrowPlant != null;
		}
	}
	internal static class ConfigEventHandlers
	{
		private static bool s_reInitQueueInProcess = false;

		private static bool s_isLocalConfigChange = false;

		private static bool s_configSettingChangedFirst = false;

		private static bool s_configFileChangedFirst = false;

		private static readonly HashSet<Action> s_reInitMethodSet = new HashSet<Action>();

		private static readonly Queue<Action> s_reInitMethodQueue = new Queue<Action>();

		private static readonly Dictionary<string, Action[]> s_initMethods = new Dictionary<string, Action[]>
		{
			{
				"Core",
				new Action[7]
				{
					PluginInitUtils.InitPieceRefs,
					PluginInitUtils.InitPieces,
					PluginInitUtils.InitSaplingRefs,
					PluginInitUtils.InitSaplings,
					PluginInitUtils.InitCrops,
					PluginInitUtils.InitVines,
					PluginInitUtils.InitCultivator
				}
			},
			{
				"Piece",
				new Action[3]
				{
					PluginInitUtils.InitPieceRefs,
					PluginInitUtils.InitPieces,
					PluginInitUtils.InitCultivator
				}
			},
			{
				"Sapling",
				new Action[3]
				{
					PluginInitUtils.InitSaplingRefs,
					PluginInitUtils.InitSaplings,
					PluginInitUtils.InitCultivator
				}
			},
			{
				"Seed",
				new Action[1] { PluginInitUtils.ModifyTreeDrops }
			},
			{
				"Crop",
				new Action[1] { PluginInitUtils.InitCrops }
			},
			{
				"Vine",
				new Action[1] { PluginInitUtils.InitVines }
			}
		};

		private static bool PerformingLocalConfigChange
		{
			get
			{
				return s_isLocalConfigChange;
			}
			set
			{
				StaticMembers.Dbgl("Config change " + (value ? "is" : "was") + " local.", forceLog: false, (LogLevel)16);
				s_isLocalConfigChange = value;
			}
		}

		private static bool ShouldQueueMethod
		{
			get
			{
				if (!StaticMembers.isDedicatedServer && !StaticMembers.config.IsSourceOfTruth)
				{
					return !PerformingLocalConfigChange;
				}
				return false;
			}
		}

		private static void QueueReInitMethod(Action method)
		{
			if (!s_reInitQueueInProcess)
			{
				StaticMembers.Dbgl("Beginning method queue.", forceLog: false, (LogLevel)16);
				s_reInitQueueInProcess = true;
			}
			if (s_reInitMethodSet.Add(method))
			{
				StaticMembers.Dbgl("Adding method to queue.", forceLog: false, (LogLevel)16);
				s_reInitMethodQueue.Enqueue(method);
			}
		}

		internal static void ProcessReInitQueue()
		{
			StaticMembers.Dbgl("Processing ReInit queue.", forceLog: false, (LogLevel)16);
			if (s_reInitMethodQueue.Count == 0 && !StaticMembers.isDedicatedServer && !StaticMembers.config.IsSourceOfTruth && StaticMembers.config.InitialSyncDone)
			{
				PerformingLocalConfigChange = true;
				return;
			}
			while (s_reInitMethodQueue.Count > 0)
			{
				s_reInitMethodQueue.Dequeue()();
			}
			s_reInitMethodSet.Clear();
			s_reInitQueueInProcess = false;
		}

		private static void HandleSettingChange(string category)
		{
			if (ShouldQueueMethod)
			{
				Array.ForEach(s_initMethods[category], QueueReInitMethod);
				return;
			}
			Array.ForEach(s_initMethods[category], delegate(Action initMethod)
			{
				initMethod();
			});
			PerformingLocalConfigChange = false;
		}

		internal static void CoreSettingChanged(object o, EventArgs e)
		{
			StaticMembers.Dbgl("Config setting changed, scheduling re-initialization of mod", forceLog: false, (LogLevel)16);
			HandleSettingChange("Core");
		}

		internal static void PieceSettingChanged(object o, EventArgs e)
		{
			StaticMembers.Dbgl("Config setting changed, scheduling re-initialization of pieces", forceLog: false, (LogLevel)16);
			HandleSettingChange("Piece");
		}

		internal static void SaplingSettingChanged(object o, EventArgs e)
		{
			StaticMembers.Dbgl("Config setting changed, scheduling re-initialization of saplings", forceLog: false, (LogLevel)16);
			HandleSettingChange("Sapling");
		}

		internal static void SeedSettingChanged(object o, EventArgs e)
		{
			StaticMembers.Dbgl("Config setting changed, scheduling modification of TreeBase drop tables", forceLog: false, (LogLevel)16);
			HandleSettingChange("Seed");
		}

		internal static void CropSettingChanged(object o, EventArgs e)
		{
			StaticMembers.Dbgl("Config setting changed, scheduling re-initialization of crops", forceLog: false, (LogLevel)16);
			HandleSettingChange("Crop");
		}

		internal static void VineSettingChanged(object o, EventArgs e)
		{
			StaticMembers.Dbgl("Config setting changed, scheduling re-initialization of vines", forceLog: false, (LogLevel)16);
			HandleSettingChange("Vine");
		}

		internal static void ExtraResourcesChanged()
		{
			StaticMembers.Dbgl("ExtraResourcesChanged", forceLog: false, (LogLevel)16);
			StaticMembers.deserializedExtraResources.Clear();
			foreach (string item2 in StaticMembers.config.SyncedExtraResources.Value)
			{
				ExtraResource item = PluginUtils.DeserializeExtraResource(item2);
				StaticMembers.deserializedExtraResources.Add(item);
			}
			if (Object.op_Implicit((Object)(object)ZNetScene.s_instance))
			{
				PluginInitUtils.InitExtraResourceRefs(ZNetScene.s_instance);
				PieceSettingChanged(null, null);
			}
		}

		internal static void ExtraResourcesFileOrSettingChanged(object sender, EventArgs e)
		{
			StaticMembers.Dbgl("ExtraResources file or setting has changed", forceLog: false, (LogLevel)16);
			if (ConfigWatcher.ExtraResourcesWatcher == null)
			{
				ConfigWatcher.InitExtraResourcesWatcher();
			}
			if (StaticMembers.config.IsSourceOfTruth)
			{
				if (StaticMembers.config.EnableExtraResources)
				{
					StaticMembers.Dbgl("IsSourceOfTruth: true, loading extra resources from disk", forceLog: false, (LogLevel)16);
					PluginUtils.LoadExtraResources();
				}
				else
				{
					StaticMembers.config.SyncedExtraResources.AssignLocalValue(new List<string>());
				}
			}
			else
			{
				StaticMembers.Dbgl("IsSourceOfTruth: false, extra resources will not be loaded from disk", forceLog: false, (LogLevel)16);
			}
		}

		internal static void ConfigSettingChanged(object sender, EventArgs e)
		{
			if (!s_configFileChangedFirst && !ShouldQueueMethod)
			{
				s_configSettingChangedFirst = true;
				StaticMembers.Dbgl("SAVING", forceLog: false, (LogLevel)16);
				StaticMembers.config.Save();
			}
			else
			{
				s_configFileChangedFirst = false;
			}
		}

		internal static void ConfigFileChanged(object sender, EventArgs e)
		{
			s_configFileChangedFirst = !s_configSettingChangedFirst;
			if (StaticMembers.isDedicatedServer || s_configFileChangedFirst)
			{
				StaticMembers.Dbgl("RELOADING", forceLog: false, (LogLevel)16);
				StaticMembers.config.Reload();
			}
			s_configSettingChangedFirst = false;
		}

		internal static void ConfigManagerDisplayingWindowChanged(object sender, EventArgs e)
		{
			if (!ConfigManagerHelper.IsConfigManagerWindowActive)
			{
				StaticMembers.Dbgl("Configuration Manager Window Closed", forceLog: false, (LogLevel)16);
			}
		}
	}
	internal class ConfigManagerHelper
	{
		private static object? _configManagerInstance;

		private static Type? _configManagerType;

		private static MethodInfo? _buildSettingList;

		private static PropertyInfo? _displayingWindowProperty;

		internal static bool IsConfigManagerWindowActive
		{
			get
			{
				object obj = _displayingWindowProperty?.GetValue(_configManagerInstance);
				bool flag = default(bool);
				int num;
				if (obj is bool)
				{
					flag = (bool)obj;
					num = 1;
				}
				else
				{
					num = 0;
				}
				return (byte)((uint)num & (flag ? 1u : 0u)) != 0;
			}
		}

		internal static void Initialize()
		{
			_configManagerType = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly a) => a.GetName().Name == "ConfigurationManager")?.GetType("ConfigurationManager.ConfigurationManager");
			_configManagerInstance = ((_configManagerType == null) ? null : Chainloader.ManagerObject.GetComponent(_configManagerType));
			_buildSettingList = _configManagerType?.GetMethod("BuildSettingList");
			_displayingWindowProperty = _configManagerType?.GetProperty("DisplayingWindow");
			EventInfo eventInfo = _configManagerInstance?.GetType().GetEvent("DisplayingWindowChanged");
			if ((object)eventInfo != null)
			{
				EventHandler eventHandler = ConfigEventHandlers.ConfigManagerDisplayingWindowChanged;
				Delegate handler = Delegate.CreateDelegate(eventInfo.EventHandlerType, eventHandler.Target, eventHandler.Method);
				eventInfo.AddEventHandler(_configManagerInstance, handler);
			}
		}

		internal static void ReloadConfigDisplay()
		{
			_buildSettingList?.Invoke(_configManagerInstance, Array.Empty<object>());
		}
	}
	internal sealed class ConfigWatcher
	{
		internal static FileSystemWatcher ExtraResourcesWatcher;

		internal static void InitConfigWatcher()
		{
			FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Paths.ConfigPath, "advize.PlantEverything.cfg");
			fileSystemWatcher.Changed += ConfigEventHandlers.ConfigFileChanged;
			fileSystemWatcher.Created += ConfigEventHandlers.ConfigFileChanged;
			fileSystemWatcher.Renamed += ConfigEventHandlers.ConfigFileChanged;
			fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject;
			fileSystemWatcher.IncludeSubdirectories = true;
			fileSystemWatcher.EnableRaisingEvents = true;
		}

		internal static void InitExtraResourcesWatcher()
		{
			ExtraResourcesWatcher = new FileSystemWatcher(StaticMembers.CustomConfigPath, "ExtraResources.json");
			ExtraResourcesWatcher.Changed += ConfigEventHandlers.ExtraResourcesFileOrSettingChanged;
			ExtraResourcesWatcher.Created += ConfigEventHandlers.ExtraResourcesFileOrSettingChanged;
			ExtraResourcesWatcher.Renamed += ConfigEventHandlers.ExtraResourcesFileOrSettingChanged;
			ExtraResourcesWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject;
			ExtraResourcesWatcher.IncludeSubdirectories = true;
			ExtraResourcesWatcher.EnableRaisingEvents = true;
		}
	}
	internal sealed class ModConfig
	{
		private readonly ConfigFile ConfigFile;

		private readonly ConfigSync ConfigSync;

		private ConfigEntry<bool> serverConfigLocked;

		internal ConfigEntry<int> nexusID;

		private ConfigEntry<bool> enableDebugMessages;

		private ConfigEntry<bool> showPickableSpawners;

		private ConfigEntry<bool> enableMiscFlora;

		private ConfigEntry<bool> enableDebris;

		private ConfigEntry<bool> enableExtraResources;

		private ConfigEntry<bool> snappableVines;

		private ConfigEntry<bool> enableLocalization;

		private ConfigEntry<string> language;

		private ConfigEntry<string> disabledResourceNames;

		private ConfigEntry<bool> requireCultivation;

		private ConfigEntry<bool> placeAnywhere;

		private ConfigEntry<bool> enforceBiomes;

		private ConfigEntry<bool> enforceBiomesVanilla;

		private ConfigEntry<bool> plantsRequireShielding;

		private ConfigEntry<bool> canRemoveFlora;

		private ConfigEntry<bool> recoverResources;

		private ConfigEntry<bool> resourcesSpawnEmpty;

		private ConfigEntry<bool> enemiesTargetPieces;

		private ConfigEntry<int> raspberryCost;

		private ConfigEntry<int> blueberryCost;

		private ConfigEntry<int> cloudberryCost;

		private ConfigEntry<int> raspberryRespawnTime;

		private ConfigEntry<int> blueberryRespawnTime;

		private ConfigEntry<int> cloudberryRespawnTime;

		private ConfigEntry<int> raspberryReturn;

		private ConfigEntry<int> blueberryReturn;

		private ConfigEntry<int> cloudberryReturn;

		private ConfigEntry<bool> enableCropOverrides;

		private ConfigEntry<bool> overrideModdedCrops;

		private ConfigEntry<bool> cropRequireCultivation;

		private ConfigEntry<bool> cropRequireSunlight;

		private ConfigEntry<bool> cropRequireGrowthSpace;

		private ConfigEntry<bool> enemiesTargetCrops;

		private ConfigEntry<float> cropMinScale;

		private ConfigEntry<float> cropMaxScale;

		private ConfigEntry<float> cropGrowTimeMin;

		private ConfigEntry<float> cropGrowTimeMax;

		private ConfigEntry<float> cropGrowRadius;

		private ConfigEntry<int> barleyCost;

		private ConfigEntry<int> barleyReturn;

		private ConfigEntry<int> carrotCost;

		private ConfigEntry<int> carrotReturn;

		private ConfigEntry<int> flaxCost;

		private ConfigEntry<int> flaxReturn;

		private ConfigEntry<int> onionCost;

		private ConfigEntry<int> onionReturn;

		private ConfigEntry<int> seedCarrotCost;

		private ConfigEntry<int> seedCarrotReturn;

		private ConfigEntry<int> seedOnionCost;

		private ConfigEntry<int> seedOnionReturn;

		private ConfigEntry<int> seedTurnipCost;

		private ConfigEntry<int> seedTurnipReturn;

		private ConfigEntry<int> turnipCost;

		private ConfigEntry<int> turnipReturn;

		private ConfigEntry<int> magecapCost;

		private ConfigEntry<int> magecapReturn;

		private ConfigEntry<int> jotunPuffsCost;

		private ConfigEntry<int> jotunPuffsReturn;

		private ConfigEntry<int> pickableBranchCost;

		private ConfigEntry<int> pickableBranchReturn;

		private ConfigEntry<int> pickableBranchRespawnTime;

		private ConfigEntry<int> pickableStoneCost;

		private ConfigEntry<int> pickableStoneReturn;

		private ConfigEntry<int> pickableStoneRespawnTime;

		private ConfigEntry<int> pickableFlintCost;

		private ConfigEntry<int> pickableFlintReturn;

		private ConfigEntry<int> pickableFlintRespawnTime;

		private ConfigEntry<int> mushroomCost;

		private ConfigEntry<int> yellowMushroomCost;

		private ConfigEntry<int> blueMushroomCost;

		private ConfigEntry<int> smokePuffCost;

		private ConfigEntry<int> mushroomRespawnTime;

		private ConfigEntry<int> yellowMushroomRespawnTime;

		private ConfigEntry<int> blueMushroomRespawnTime;

		private ConfigEntry<int> smokePuffRespawnTime;

		private ConfigEntry<int> mushroomReturn;

		private ConfigEntry<int> yellowMushroomReturn;

		private ConfigEntry<int> blueMushroomReturn;

		private ConfigEntry<int> smokePuffReturn;

		private ConfigEntry<int> thistleCost;

		private ConfigEntry<int> dandelionCost;

		private ConfigEntry<int> fiddleheadCost;

		private ConfigEntry<int> thistleRespawnTime;

		private ConfigEntry<int> dandelionRespawnTime;

		private ConfigEntry<int> fiddleheadRespawnTime;

		private ConfigEntry<int> thistleReturn;

		private ConfigEntry<int> dandelionReturn;

		private ConfigEntry<int> fiddleheadReturn;

		private ConfigEntry<bool> overrideModdedSaplings;

		private ConfigEntry<float> moddedSaplingMinScale;

		private ConfigEntry<float> moddedSaplingMaxScale;

		private ConfigEntry<float> moddedSaplingGrowthTime;

		private ConfigEntry<float> moddedSaplingGrowRadius;

		private ConfigEntry<float> birchMinScale;

		private ConfigEntry<float> birchMaxScale;

		private ConfigEntry<float> oakMinScale;

		private ConfigEntry<float> oakMaxScale;

		private ConfigEntry<float> ancientMinScale;

		private ConfigEntry<float> ancientMaxScale;

		private ConfigEntry<float> birchGrowthTime;

		private ConfigEntry<float> oakGrowthTime;

		private ConfigEntry<float> ancientGrowthTime;

		private ConfigEntry<float> birchGrowRadius;

		private ConfigEntry<float> oakGrowRadius;

		private ConfigEntry<float> ancientGrowRadius;

		private ConfigEntry<float> beechGrowthTime;

		private ConfigEntry<float> pineGrowthTime;

		private ConfigEntry<float> firGrowthTime;

		private ConfigEntry<float> beechMinScale;

		private ConfigEntry<float> beechMaxScale;

		private ConfigEntry<float> pineMinScale;

		private ConfigEntry<float> pineMaxScale;

		private ConfigEntry<float> firMinScale;

		private ConfigEntry<float> firMaxScale;

		private ConfigEntry<float> beechGrowRadius;

		private ConfigEntry<float> pineGrowRadius;

		private ConfigEntry<float> firGrowRadius;

		private ConfigEntry<float> yggaMinScale;

		private ConfigEntry<float> yggaMaxScale;

		private ConfigEntry<float> yggaGrowthTime;

		private ConfigEntry<float> yggaGrowRadius;

		private ConfigEntry<float> autumnBirchMinScale;

		private ConfigEntry<float> autumnBirchMaxScale;

		private ConfigEntry<float> autumnBirchGrowthTime;

		private ConfigEntry<float> autumnBirchGrowRadius;

		private ConfigEntry<float> ashwoodMinScale;

		private ConfigEntry<float> ashwoodMaxScale;

		private ConfigEntry<float> ashwoodGrowthTime;

		private ConfigEntry<float> ashwoodGrowRadius;

		private ConfigEntry<bool> enableSeedOverrides;

		private ConfigEntry<int> seedDropMin;

		private ConfigEntry<int> seedDropMax;

		private ConfigEntry<int> treeDropMin;

		private ConfigEntry<int> treeDropMax;

		private ConfigEntry<float> dropChance;

		private ConfigEntry<bool> oneOfEach;

		private ConfigEntry<bool> enablePickableTimers;

		private ConfigEntry<bool> enablePlantTimers;

		private ConfigEntry<bool> growthAsPercentage;

		private ConfigEntry<bool> enableVineOverrides;

		private ConfigEntry<float> vineAttachDistance;

		private ConfigEntry<float> vineGrowRadius;

		private ConfigEntry<float> vineGrowthTime;

		private ConfigEntry<int> vineBerryRespawnTime;

		private ConfigEntry<int> vineBerryReturn;

		private CustomSyncedValue<List<string>> extraResources;

		private readonly ConfigurationManagerAttributes seedSettingAtrributes = new ConfigurationManagerAttributes();

		private readonly List<ConfigurationManagerAttributes> cropSettingAttributes = new List<ConfigurationManagerAttributes>(2)
		{
			new ConfigurationManagerAttributes(),
			new ConfigurationManagerAttributes
			{
				Order = 27
			}
		};

		internal bool EnableDebugMessages => enableDebugMessages.Value;

		internal bool ShowPickableSpawners => showPickableSpawners.Value;

		internal bool EnableMiscFlora => enableMiscFlora.Value;

		internal bool EnableDebris => enableDebris.Value;

		internal bool EnableExtraResources => enableExtraResources.Value;

		internal bool SnappableVines => snappableVines.Value;

		internal bool EnableLocalization => enableLocalization.Value;

		internal string Language => language.Value;

		internal string[] DisabledResourceNames => disabledResourceNames.Value.Split(new char[1] { ',' });

		internal bool RequireCultivation => requireCultivation.Value;

		internal bool PlaceAnywhere => placeAnywhere.Value;

		internal bool EnforceBiomes => enforceBiomes.Value;

		internal bool EnforceBiomesVanilla => enforceBiomesVanilla.Value;

		internal bool PlantsRequireShielding => plantsRequireShielding.Value;

		internal bool CanRemoveFlora => canRemoveFlora.Value;

		internal bool RecoverResources => recoverResources.Value;

		internal bool ResourcesSpawnEmpty => resourcesSpawnEmpty.Value;

		internal bool EnemiesTargetPieces => enemiesTargetPieces.Value;

		internal int RaspberryCost => raspberryCost.Value;

		internal int BlueberryCost => blueberryCost.Value;

		internal int CloudberryCost => cloudberryCost.Value;

		internal int RaspberryRespawnTime => raspberryRespawnTime.Value;

		internal int BlueberryRespawnTime => blueberryRespawnTime.Value;

		internal int CloudberryRespawnTime => cloudberryRespawnTime.Value;

		internal int RaspberryReturn => raspberryReturn.Value;

		internal int BlueberryReturn => blueberryReturn.Value;

		internal int CloudberryReturn => cloudberryReturn.Value;

		internal bool EnableCropOverrides => enableCropOverrides.Value;

		internal bool OverrideModdedCrops => overrideModdedCrops.Value;

		internal float CropMinScale => cropMinScale.Value;

		internal float CropMaxScale => cropMaxScale.Value;

		internal float CropGrowTimeMin => Mathf.Max(cropGrowTimeMin.Value, 10f);

		internal float CropGrowTimeMax => Mathf.Max(cropGrowTimeMax.Value, 10f);

		internal float CropGrowRadius => cropGrowRadius.Value;

		internal bool CropRequireCultivation => cropRequireCultivation.Value;

		internal bool CropRequireSunlight => cropRequireSunlight.Value;

		internal bool CropRequireGrowthSpace => cropRequireGrowthSpace.Value;

		internal bool EnemiesTargetCrops => enemiesTargetCrops.Value;

		internal int BarleyCost => barleyCost.Value;

		internal int BarleyReturn => barleyReturn.Value;

		internal int CarrotCost => carrotCost.Value;

		internal int CarrotReturn => carrotReturn.Value;

		internal int FlaxCost => flaxCost.Value;

		internal int FlaxReturn => flaxReturn.Value;

		internal int OnionCost => onionCost.Value;

		internal int OnionReturn => onionReturn.Value;

		internal int SeedCarrotCost => seedCarrotCost.Value;

		internal int SeedCarrotReturn => seedCarrotReturn.Value;

		internal int SeedOnionCost => seedOnionCost.Value;

		internal int SeedOnionReturn => seedOnionReturn.Value;

		internal int SeedTurnipCost => seedTurnipCost.Value;

		internal int SeedTurnipReturn => seedTurnipReturn.Value;

		internal int TurnipCost => turnipCost.Value;

		internal int TurnipReturn => turnipReturn.Value;

		internal int MagecapCost => magecapCost.Value;

		internal int MagecapReturn => magecapReturn.Value;

		internal int JotunPuffsCost => jotunPuffsCost.Value;

		internal int JotunPuffsReturn => jotunPuffsReturn.Value;

		internal int PickableBranchCost => pickableBranchCost.Value;

		internal int PickableBranchReturn => pickableBranchReturn.Value;

		internal int PickableBranchRespawnTime => pickableBranchRespawnTime.Value;

		internal int PickableStoneCost => pickableStoneCost.Value;

		internal int PickableStoneReturn => pickableStoneReturn.Value;

		internal int PickableStoneRespawnTime => pickableStoneRespawnTime.Value;

		internal int PickableFlintCost => pickableFlintCost.Value;

		internal int PickableFlintReturn => pickableFlintReturn.Value;

		internal int PickableFlintRespawnTime => pickableFlintRespawnTime.Value;

		internal int MushroomCost => mushroomCost.Value;

		internal int YellowMushroomCost => yellowMushroomCost.Value;

		internal int BlueMushroomCost => blueMushroomCost.Value;

		internal int SmokePuffCost => smokePuffCost.Value;

		internal int MushroomRespawnTime => mushroomRespawnTime.Value;

		internal int YellowMushroomRespawnTime => yellowMushroomRespawnTime.Value;

		internal int BlueMushroomRespawnTime => blueMushroomRespawnTime.Value;

		internal int SmokePuffRespawnTime => smokePuffRespawnTime.Value;

		internal int MushroomReturn => mushroomReturn.Value;

		internal int YellowMushroomReturn => yellowMushroomReturn.Value;

		internal int BlueMushroomReturn => blueMushroomReturn.Value;

		internal int SmokePuffReturn => smokePuffReturn.Value;

		internal int ThistleCost => thistleCost.Value;

		internal int DandelionCost => dandelionCost.Value;

		internal int FiddleheadCost => fiddleheadCost.Value;

		internal int ThistleRespawnTime => thistleRespawnTime.Value;

		internal int DandelionRespawnTime => dandelionRespawnTime.Value;

		internal int FiddleheadRespawnTime => fiddleheadRespawnTime.Value;

		internal int ThistleReturn => thistleReturn.Value;

		internal int DandelionReturn => dandelionReturn.Value;

		internal int FiddleheadReturn => fiddleheadReturn.Value;

		internal bool OverrideModdedSaplings => overrideModdedSaplings.Value;

		internal float ModdedSaplingMinScale => moddedSaplingMinScale.Value;

		internal float ModdedSaplingMaxScale => moddedSaplingMaxScale.Value;

		internal float ModdedSaplingGrowthTime => moddedSaplingGrowthTime.Value;

		internal float ModdedSaplingGrowRadius => moddedSaplingGrowRadius.Value;

		internal float BirchMinScale => birchMinScale.Value;

		internal float BirchMaxScale => birchMaxScale.Value;

		internal float OakMinScale => oakMinScale.Value;

		internal float OakMaxScale => oakMaxScale.Value;

		internal float AncientMinScale => ancientMinScale.Value;

		internal float AncientMaxScale => ancientMaxScale.Value;

		internal float BirchGrowthTime => Mathf.Max(birchGrowthTime.Value, 10f);

		internal float OakGrowthTime => Mathf.Max(oakGrowthTime.Value, 10f);

		internal float AncientGrowthTime => Mathf.Max(ancientGrowthTime.Value, 10f);

		internal float BirchGrowRadius => birchGrowRadius.Value;

		internal float OakGrowRadius => oakGrowRadius.Value;

		internal float AncientGrowRadius => ancientGrowRadius.Value;

		internal float BeechGrowthTime => Mathf.Max(beechGrowthTime.Value, 10f);

		internal float PineGrowthTime => Mathf.Max(pineGrowthTime.Value, 10f);

		internal float FirGrowthTime => Mathf.Max(firGrowthTime.Value, 10f);

		internal float BeechMinScale => beechMinScale.Value;

		internal float BeechMaxScale => beechMaxScale.Value;

		internal float PineMinScale => pineMinScale.Value;

		internal float PineMaxScale => pineMaxScale.Value;

		internal float FirMinScale => firMinScale.Value;

		internal float FirMaxScale => firMaxScale.Value;

		internal float BeechGrowRadius => beechGrowRadius.Value;

		internal float PineGrowRadius => pineGrowRadius.Value;

		internal float FirGrowRadius => firGrowRadius.Value;

		internal float YggaMinScale => yggaMinScale.Value;

		internal float YggaMaxScale => yggaMaxScale.Value;

		internal float YggaGrowthTime => yggaGrowthTime.Value;

		internal float YggaGrowRadius => yggaGrowRadius.Value;

		internal float AutumnBirchMinScale => autumnBirchMinScale.Value;

		internal float AutumnBirchMaxScale => autumnBirchMaxScale.Value;

		internal float AutumnBirchGrowthTime => autumnBirchGrowthTime.Value;

		internal float AutumnBirchGrowRadius => autumnBirchGrowRadius.Value;

		internal float AshwoodMinScale => ashwoodMinScale.Value;

		internal float AshwoodMaxScale => ashwoodMaxScale.Value;

		internal float AshwoodGrowthTime => ashwoodGrowthTime.Value;

		internal float AshwoodGrowRadius => ashwoodGrowRadius.Value;

		internal bool EnableSeedOverrides => enableSeedOverrides.Value;

		internal int SeedDropMin => seedDropMin.Value;

		internal int SeedDropMax => seedDropMax.Value;

		internal int TreeDropMin => treeDropMin.Value;

		internal int TreeDropMax => treeDropMax.Value;

		internal float DropChance => dropChance.Value;

		internal bool OneOfEach => oneOfEach.Value;

		internal bool EnablePickableTimers => enablePickableTimers.Value;

		internal bool EnablePlantTimers => enablePlantTimers.Value;

		internal bool GrowthAsPercentage => growthAsPercentage.Value;

		internal bool EnableVineOverrides => enableVineOverrides.Value;

		internal float VinesAttachDistance => vineAttachDistance.Value;

		internal float VineGrowRadius => vineGrowRadius.Value;

		internal float VinesGrowthTime => vineGrowthTime.Value;

		internal int VineBerryRespawnTime => vineBerryRespawnTime.Value;

		internal int VineBerryReturn => vineBerryReturn.Value;

		internal CustomSyncedValue<List<string>> SyncedExtraResources => extraResources;

		internal bool IsSourceOfTruth => ConfigSync.IsSourceOfTruth;

		internal bool InitialSyncDone => ConfigSync.InitialSyncDone;

		private ConfigEntry<T> Config<T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true)
		{
			ConfigEntry<T> val = ConfigFile.Bind<T>(group, name, value, description);
			((OwnConfigEntryBase)ConfigSync.AddConfigEntry<T>(val)).SynchronizedConfig = synchronizedSetting;
			return val;
		}

		private ConfigEntry<T> Config<T>(string group, string name, T value, string description, bool synchronizedSetting = true)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			return Config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting);
		}

		internal ModConfig(ConfigFile configFile, ConfigSync configSync)
		{
			ConfigFile = configFile;
			ConfigSync = configSync;
			configFile.SaveOnConfigSet = false;
			BindConfigEntries();
			configFile.Save();
			SetupSettingChangedSubscriptions();
			configSync.AddLockingConfigEntry<bool>(serverConfigLocked);
			ConfigWatcher.InitConfigWatcher();
			ConfigManagerHelper.Initialize();
		}

		private void BindConfigEntries()
		{
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_0191: Expected O, but got Unknown
			//IL_03da: Unknown result type (might be due to invalid IL or missing references)
			//IL_03e5: Expected O, but got Unknown
			//IL_0412: Unknown result type (might be due to invalid IL or missing references)
			//IL_041d: Expected O, but got Unknown
			//IL_044e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0459: Expected O, but got Unknown
			//IL_048a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0495: Expected O, but got Unknown
			//IL_04c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_04d1: Expected O, but got Unknown
			//IL_0502: Unknown result type (might be due to invalid IL or missing references)
			//IL_050d: Expected O, but got Unknown
			//IL_053e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0549: Expected O, but got Unknown
			//IL_0576: Unknown result type (might be due to invalid IL or missing references)
			//IL_0581: Expected O, but got Unknown
			//IL_05ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_05b9: Expected O, but got Unknown
			//IL_05e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_05f1: Expected O, but got Unknown
			//IL_061e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0629: Expected O, but got Unknown
			//IL_0656: Unknown result type (might be due to invalid IL or missing references)
			//IL_0661: Expected O, but got Unknown
			//IL_068e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0699: Expected O, but got Unknown
			//IL_06c6: Unknown result type (might be due to invalid IL or missing references)
			//IL_06d1: Expected O, but got Unknown
			//IL_06fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_0709: Expected O, but got Unknown
			//IL_0736: Unknown result type (might be due to invalid IL or missing references)
			//IL_0741: Expected O, but got Unknown
			//IL_076e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0779: Expected O, but got Unknown
			//IL_07a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_07b1: Expected O, but got Unknown
			//IL_07de: Unknown result type (might be due to invalid IL or missing references)
			//IL_07e9: Expected O, but got Unknown
			//IL_0816: Unknown result type (might be due to invalid IL or missing references)
			//IL_0821: Expected O, but got Unknown
			//IL_084e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0859: Expected O, but got Unknown
			//IL_0886: Unknown result type (might be due to invalid IL or missing references)
			//IL_0891: Expected O, but got Unknown
			//IL_08be: Unknown result type (might be due to invalid IL or missing references)
			//IL_08c9: Expected O, but got Unknown
			//IL_08f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0901: Expected O, but got Unknown
			//IL_092e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0939: Expected O, but got Unknown
			//IL_0966: Unknown result type (might be due to invalid IL or missing references)
			//IL_0971: Expected O, but got Unknown
			//IL_099e: Unknown result type (might be due to invalid IL or missing references)
			//IL_09a9: Expected O, but got Unknown
			//IL_09d6: Unknown result type (might be due to invalid IL or missing references)
			//IL_09e1: Expected O, but got Unknown
			//IL_0a0e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a19: Expected O, but got Unknown
			//IL_0a46: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a51: Expected O, but got Unknown
			//IL_0a7e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0a89: Expected O, but got Unknown
			//IL_0e47: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e52: Expected O, but got Unknown
			//IL_0e89: Unknown result type (might be due to invalid IL or missing references)
			//IL_0e94: Expected O, but got Unknown
			//IL_0ecb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0ed6: Expected O, but got Unknown
			//IL_0f0d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0f18: Expected O, but got Unknown
			//IL_0f4f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0f5a: Expected O, but got Unknown
			//IL_1431: Unknown result type (might be due to invalid IL or missing references)
			//IL_143c: Expected O, but got Unknown
			//IL_1463: Unknown result type (might be due to invalid IL or missing references)
			//IL_146e: Expected O, but got Unknown
			//IL_1495: Unknown result type (might be due to invalid IL or missing references)
			//IL_14a0: Expected O, but got Unknown
			//IL_14c7: Unknown result type (might be due to invalid IL or missing references)
			//IL_14d2: Expected O, but got Unknown
			//IL_14f9: Unknown result type (might be due to invalid IL or missing references)
			//IL_1504: Expected O, but got Unknown
			//IL_152f: Unknown result type (might be due to invalid IL or missing references)
			//IL_153a: Expected O, but got Unknown
			//IL_1561: Unknown result type (might be due to invalid IL or missing references)
			//IL_156c: Expected O, but got Unknown
			//IL_15f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_1601: Expected O, but got Unknown
			serverConfigLocked = Config("General", "LockConfiguration", value: true, "If on, the configuration is locked and can be changed by server admins only.");
			nexusID = Config("General", "NexusID", 1042, new ConfigDescription("Nexus mod ID for updates.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Category = "Internal",
					ReadOnly = true
				}
			}), synchronizedSetting: false);
			enableDebugMessages = Config("General", "EnableDebugMessages", value: false, "Enable mod debug messages in console.", synchronizedSetting: false);
			showPickableSpawners = Config("General", "ShowPickableSpawners", value: true, "Continue to show mushroom, thistle, and dandelion spawners after being picked. (Requires world reload on client to take effect.)", synchronizedSetting: false);
			enableMiscFlora = Config("General", "EnableMiscFlora", value: true, "Enables small trees, bushes, shrubs, vines, and large mushrooms.");
			enableDebris = Config("General", "EnableDebris", value: true, "Allows for the placement of debris such as branches, flint, and stone.");
			enableExtraResources = Config("General", "EnableExtraResources", value: false, "When set to true, the mod will attempt to make user-defined prefabs buildable with the cultivator. Prefabs are defined in PlantEverything_ExtraResources.cfg. If file is not present, an example one will be generated for you.");
			snappableVines = Config("General", "SnappableVines", value: true, "Enables snap points when placing vines adjacently.", synchronizedSetting: false);
			enableLocalization = Config("General", "EnableLocalization", value: false, "Enable this to attempt to load localized text data for the language set in the following setting.", synchronizedSetting: false);
			language = Config("General", "Language", "english", "Language to be used. If EnableLocalization is enabled, game will attempt to load localized text from a file named {language}_PlantEverything.json.", synchronizedSetting: false);
			disabledResourceNames = Config("General", "DisabledResourceNames", "", new ConfigDescription("To disable specific resources added by this mod (and not add them to the cultivator), list their prefab names here separated by a comma. Names are case-sensitive.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = -1
				}
			}));
			requireCultivation = Config("Difficulty", "RequireCultivation", value: false, "Pickable resources can only be planted on cultivated ground.");
			placeAnywhere = Config("Difficulty", "PlaceAnywhere", value: false, "Allow resources to be placed anywhere (not just on the ground). Does not apply to mushrooms or flowers.");
			enforceBiomes = Config("Difficulty", "EnforceBiomes", value: false, "Restrict modded plantables (pickables and saplings) to being placed in their respective biome.");
			enforceBiomesVanilla = Config("Difficulty", "EnforceBiomesVanilla", value: true, "Restrict vanilla plantables (crops and saplings) to being placed in their respective biome.");
			plantsRequireShielding = Config("Difficulty", "PlantsRequireShielding", value: true, "Controls whether plants need shielding to survive in hostile environments.");
			canRemoveFlora = Config("Difficulty", "CanRemoveFlora", value: false, "Allows the cultivator to deconstruct decorative flora placed by a player. Useful for creative game types.");
			recoverResources = Config("Difficulty", "RecoverResources", value: false, "Recover resources when pickables are removed with the cultivator. Applies to berries, mushrooms, and flowers.");
			resourcesSpawnEmpty = Config("Difficulty", "ResourcesSpawnEmpty", value: false, "Specifies whether resources should spawn empty or full. Applies to berry bushes, mushrooms, flowers, and debris.");
			enemiesTargetPieces = Config("Difficulty", "EnemiesTargetPieces", value: true, "When enabled, enemies may target and attack player placed resources added by the mod. If this setting is changed, pre-existing placed pieces will not be affected until the world/server is reloaded.");
			raspberryCost = Config("Berries", "RaspberryCost", 5, "Number of raspberries required to place a raspberry bush. Set to 0 to disable the ability to plant this resource.");
			blueberryCost = Config("Berries", "BlueberryCost", 5, "Number of blueberries required to place a blueberry bush. Set to 0 to disable the ability to plant this resource.");
			cloudberryCost = Config("Berries", "CloudberryCost", 5, "Number of cloudberries required to place a cloudberry bush. Set to 0 to disable the ability to plant this resource.");
			raspberryRespawnTime = Config("Berries", "RaspberryRespawnTime", 300, "Number of minutes it takes for a raspberry bush to respawn berries.");
			blueberryRespawnTime = Config("Berries", "BlueberryRespawnTime", 300, "Number of minutes it takes for a blueberry bush to respawn berries.");
			cloudberryRespawnTime = Config("Berries", "CloudberryRespawnTime", 300, "Number of minutes it takes for a cloudberry bush to respawn berries.");
			raspberryReturn = Config("Berries", "RaspberryReturn", 1, "Number of berries a raspberry bush will spawn.");
			blueberryReturn = Config("Berries", "BlueberryReturn", 1, "Number of berries a blueberry bush will spawn.");
			cloudberryReturn = Config("Berries", "CloudberryReturn", 1, "Number of berries a cloudberry bush will spawn.");
			enableCropOverrides = Config("Crops", "EnableCropOverrides", value: false, new ConfigDescription("Enables the [Crops] section of this config.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = 28
				}
			}));
			overrideModdedCrops = Config("Crops", "OverrideModdedCrops", value: true, new ConfigDescription("Applies all [Crops] settings to 3rd party modded crops.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[1] }));
			cropMinScale = Config("Crops", "CropMinScale", 0.9f, new ConfigDescription("The minimum scaling factor used to scale crops upon growth.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			cropMaxScale = Config("Crops", "CropMaxScale", 1.1f, new ConfigDescription("The maximum scaling factor used to scale crops upon growth.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			cropGrowTimeMin = Config("Crops", "CropGrowTimeMin", 4000f, new ConfigDescription("Minimum number of seconds it takes for crops to grow (will take at least 10 seconds after planting to grow).", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			cropGrowTimeMax = Config("Crops", "CropGrowTimeMax", 5000f, new ConfigDescription("Maximum number of seconds it takes for crops to grow (will take at least 10 seconds after planting to grow).", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			cropGrowRadius = Config("Crops", "CropGrowRadius", 0.5f, new ConfigDescription("Radius of free space required for crops to grow.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			cropRequireCultivation = Config("Crops", "CropsRequireCultivation", value: true, new ConfigDescription("Crops can only be planted on cultivated ground.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[1] }));
			cropRequireSunlight = Config("Crops", "CropsRequireSunlight", value: true, new ConfigDescription("Crops can only grow under an open sky.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[1] }));
			cropRequireGrowthSpace = Config("Crops", "CropsRequireGrowthSpace", value: true, new ConfigDescription("Crops require space to grow. This setting overrides the CropGrowRadius setting but without altering it, allowing grid spacing mods to continue functioning.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[1] }));
			enemiesTargetCrops = Config("Crops", "EnemiesTargetCrops", value: true, new ConfigDescription("Determines whether enemies will target and attack crops. If this setting is changed, pre-existing placed crops will not be affected until the world/server is reloaded.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[1] }));
			barleyCost = Config("Crops", "BarleyCost", 1, new ConfigDescription("Resource cost of planting barley.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			barleyReturn = Config("Crops", "BarleyReturn", 2, new ConfigDescription("Resources gained upon harvesting barley (does not apply to wild barley).", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			carrotCost = Config("Crops", "CarrotCost", 1, new ConfigDescription("Resource cost of planting carrots.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			carrotReturn = Config("Crops", "CarrotReturn", 1, new ConfigDescription("Resources gained upon harvesting carrots.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			flaxCost = Config("Crops", "FlaxCost", 1, new ConfigDescription("Resource cost of planting flax.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			flaxReturn = Config("Crops", "FlaxReturn", 2, new ConfigDescription("Resources gained upon harvesting flax (does not apply to wild flax).", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			onionCost = Config("Crops", "OnionCost", 1, new ConfigDescription("Resource cost of planting onions.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			onionReturn = Config("Crops", "OnionReturn", 1, new ConfigDescription("Resources gained upon harvesting onions.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			seedCarrotCost = Config("Crops", "SeedCarrotCost", 1, new ConfigDescription("Resource cost of planting seed carrots.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			seedCarrotReturn = Config("Crops", "SeedCarrotReturn", 3, new ConfigDescription("Resources gained upon harvesting seed carrots.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			seedOnionCost = Config("Crops", "SeedOnionCost", 1, new ConfigDescription("Resource cost of planting seed onions.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			seedOnionReturn = Config("Crops", "SeedOnionReturn", 3, new ConfigDescription("Resources gained upon harvesting seed onions.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			seedTurnipCost = Config("Crops", "SeedTurnipCost", 1, new ConfigDescription("Resource cost of planting seed turnips.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			seedTurnipReturn = Config("Crops", "SeedTurnipReturn", 3, new ConfigDescription("Resources gained upon harvesting seed turnips.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			turnipCost = Config("Crops", "TurnipCost", 1, new ConfigDescription("Resource cost of planting turnips.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			turnipReturn = Config("Crops", "TurnipReturn", 1, new ConfigDescription("Resources gained upon harvesting turnips.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			magecapCost = Config("Crops", "MagecapCost", 1, new ConfigDescription("Resource cost of planting magecap.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			magecapReturn = Config("Crops", "MagecapReturn", 3, new ConfigDescription("Resources gained upon harvesting magecap.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			jotunPuffsCost = Config("Crops", "JotunPuffsCost", 1, new ConfigDescription("Resource cost of planting Jotun puffs.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			jotunPuffsReturn = Config("Crops", "JotunPuffsReturn", 3, new ConfigDescription("Resources gained upon harvesting Jotun puffs.", (AcceptableValueBase)null, new object[1] { cropSettingAttributes[0] }));
			pickableBranchCost = Config("Debris", "PickableBranchCost", 5, "Amount of wood required to place branch debris. Set to 0 to disable the ability to plant this resource.");
			pickableBranchReturn = Config("Debris", "PickableBranchReturn", 1, "Amount of wood that branch debris drops when picked.");
			pickableBranchRespawnTime = Config("Debris", "PickableBranchRespawnTime", 240, "Number of minutes it takes for a pickable branch to respawn.");
			pickableStoneCost = Config("Debris", "PickableStoneCost", 1, "Amount of stone required to place stone debris. Set to 0 to disable the ability to plant this resource.");
			pickableStoneReturn = Config("Debris", "PickableStoneReturn", 1, "Amount of stones that stone debris drops when picked.");
			pickableStoneRespawnTime = Config("Debris", "PickableStoneRespawnTime", 0, "Number of minutes it takes for a pickable Stone to respawn.");
			pickableFlintCost = Config("Debris", "PickableFlintCost", 5, "Amount of flint required to place flint debris. Set to 0 to disable the ability to plant this resource.");
			pickableFlintReturn = Config("Debris", "PickableFlintReturn", 1, "Amount of flint that flint debris drops when picked.");
			pickableFlintRespawnTime = Config("Debris", "PickableFlintRespawnTime", 240, "Number of minutes it takes for pickable flint to respawn.");
			mushroomCost = Config("Mushrooms", "MushroomCost", 5, "Number of mushrooms required to place a pickable mushroom spawner. Set to 0 to disable the ability to plant this resource.");
			yellowMushroomCost = Config("Mushrooms", "YellowMushroomCost", 5, "Number of yellow mushrooms required to place a pickable yellow mushroom spawner. Set to 0 to disable the ability to plant this resource.");
			blueMushroomCost = Config("Mushrooms", "BlueMushroomCost", 5, "Number of blue mushrooms required to place a pickable blue mushroom spawner. Set to 0 to disable the ability to plant this resource.");
			smokePuffCost = Config("Mushrooms", "SmokepuffCost", 5, "Number of smoke puffs required to place a pickable smoke puff spawner. Set to 0 to disable the ability to plant this resource.");
			mushroomRespawnTime = Config("Mushrooms", "MushroomRespawnTime", 240, "Number of minutes it takes for mushrooms to respawn.");
			yellowMushroomRespawnTime = Config("Mushrooms", "YellowMushroomRespawnTime", 240, "Number of minutes it takes for yellow mushrooms to respawn.");
			blueMushroomRespawnTime = Config("Mushrooms", "BlueMushroomRespawnTime", 240, "Number of minutes it takes for blue mushrooms to respawn.");
			smokePuffRespawnTime = Config("Mushrooms", "SmokepuffRespawnTime", 240, "Number of minutes it takes for smoke puffs to respawn.");
			mushroomReturn = Config("Mushrooms", "MushroomReturn", 1, "Number of mushrooms a pickable mushroom spawner will spawn.");
			yellowMushroomReturn = Config("Mushrooms", "YellowMushroomReturn", 1, "Number of yellow mushrooms a pickable yellow mushroom spawner will spawn.");
			blueMushroomReturn = Config("Mushrooms", "BlueMushroomReturn", 1, "Number of blue mushrooms a pickable blue mushroom spawner will spawn.");
			smokePuffReturn = Config("Mushrooms", "SmokepuffReturn", 1, "Number of smoke puffs a pickable smoke puff spawner will spawn.");
			thistleCost = Config("Flowers", "ThistleCost", 5, "Number of thistle required to place a pickable thistle spawner. Set to 0 to disable the ability to plant this resource.");
			dandelionCost = Config("Flowers", "DandelionCost", 5, "Number of dandelion required to place a pickable dandelion spawner. Set to 0 to disable the ability to plant this resource.");
			fiddleheadCost = Config("Flowers", "FiddleheadCost", 15, "Number of fiddlehead required to place a pickable fiddlehead spawner. Set to 0 to disable the ability to plant this resource.");
			thistleRespawnTime = Config("Flowers", "ThistleRespawnTime", 240, "Number of minutes it takes for thistle to respawn.");
			dandelionRespawnTime = Config("Flowers", "DandelionRespawnTime", 240, "Number of minutes it takes for dandelion to respawn.");
			fiddleheadRespawnTime = Config("Flowers", "FiddleheadRespawnTime", 300, "Number of minutes it takes for fiddlehead to respawn.");
			thistleReturn = Config("Flowers", "ThistleReturn", 1, "Number of thistle a pickable thistle spawner will spawn.");
			dandelionReturn = Config("Flowers", "DandelionReturn", 1, "Number of dandelion a pickable dandelion spawner will spawn.");
			fiddleheadReturn = Config("Flowers", "FiddleheadReturn", 3, "Number of fiddlehead a pickable fiddlehead spawner will spawn.");
			overrideModdedSaplings = Config("Saplings", "OverrideModdedSaplings", value: false, new ConfigDescription("Applies all [Saplings]Modded* settings to 3rd party modded saplings.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = 41
				}
			}));
			moddedSaplingMinScale = Config("Saplings", "ModdedSaplingMinScale", 0.5f, new ConfigDescription("The minimum scaling factor used to scale a 3rd party modded tree upon growth.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = 37
				}
			}));
			moddedSaplingMaxScale = Config("Saplings", "ModdedSaplingMaxScale", 2f, new ConfigDescription("The maximum scaling factor used to scale a 3rd party modded tree upon growth.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = 38
				}
			}));
			moddedSaplingGrowthTime = Config("Saplings", "ModdedSaplingGrowthTime", 3000f, new ConfigDescription("Number of seconds it takes for a 3rd party modded tree to grow from its modded sapling (will take at least 10 seconds after planting to grow).", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = 39
				}
			}));
			moddedSaplingGrowRadius = Config("Saplings", "ModdedSaplingGrowRadius", 2f, new ConfigDescription("Radius of free space required for a 3rd party modded sapling to grow.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = 40
				}
			}));
			birchMinScale = Config("Saplings", "BirchMinScale", 0.5f, "The minimum scaling factor used to scale a birch tree upon growth.");
			birchMaxScale = Config("Saplings", "BirchMaxScale", 1f, "The maximum scaling factor used to scale a birch tree upon growth.");
			oakMinScale = Config("Saplings", "OakMinScale", 0.7f, "The minimum scaling factor used to scale an oak tree upon growth.");
			oakMaxScale = Config("Saplings", "OakMaxScale", 0.9f, "The maximum scaling factor used to scale an oak tree upon growth.");
			ancientMinScale = Config("Saplings", "AncientMinScale", 0.5f, "The minimum scaling factor used to scale an ancient tree upon growth.");
			ancientMaxScale = Config("Saplings", "AncientMaxScale", 2f, "The maximum scaling factor used to scale an ancient tree upon growth.");
			birchGrowthTime = Config("Saplings", "BirchGrowthTime", 3000f, "Number of seconds it takes for a birch tree to grow from a birch sapling (will take at least 10 seconds after planting to grow).");
			oakGrowthTime = Config("Saplings", "OakGrowthTime", 3000f, "Number of seconds it takes for an oak tree to grow from an oak sapling (will take at least 10 seconds after planting to grow).");
			ancientGrowthTime = Config("Saplings", "AncientGrowthTime", 3000f, "Number of seconds it takes for an ancient tree to grow from an ancient sapling (will take at least 10 seconds after planting to grow).");
			birchGrowRadius = Config("Saplings", "BirchGrowRadius", 2f, "Radius of free space required for a birch sapling to grow.");
			oakGrowRadius = Config("Saplings", "OakGrowRadius", 3f, "Radius of free space required for an oak sapling to grow.");
			ancientGrowRadius = Config("Saplings", "AncientGrowRadius", 2f, "Radius of free space required for an ancient sapling to grow.");
			beechGrowthTime = Config("Saplings", "BeechGrowthTime", 3000f, "Number of seconds it takes for a beech tree to grow from a beech sapling (will take at least 10 seconds after planting to grow).");
			pineGrowthTime = Config("Saplings", "PineGrowthTime", 3000f, "Number of seconds it takes for a pine tree to grow from a pine sapling (will take at least 10 seconds after planting to grow).");
			firGrowthTime = Config("Saplings", "FirGrowthTime", 3000f, "Number of seconds it takes for a fir tree to grow from a fir sapling (will take at least 10 seconds after planting to grow).");
			beechMinScale = Config("Saplings", "BeechMinScale", 0.8f, "The minimum scaling factor used to scale a beech tree upon growth.");
			beechMaxScale = Config("Saplings", "BeechMaxScale", 1.5f, "The maximum scaling factor used to scale a beech tree upon growth.");
			pineMinScale = Config("Saplings", "PineMinScale", 1.5f, "The minimum scaling factor used to scale a pine tree upon growth.");
			pineMaxScale = Config("Saplings", "PineMaxScale", 2.5f, "The maximum scaling factor used to scale a pine tree upon growth.");
			firMinScale = Config("Saplings", "FirMinScale", 1f, "The minimum scaling factor used to scale a fir tree upon growth.");
			firMaxScale = Config("Saplings", "FirMaxScale", 2.5f, "The maximum scaling factor used to scale a fir tree upon growth.");
			beechGrowRadius = Config("Saplings", "BeechGrowRadius", 2f, "Radius of free space required for a beech sapling to grow.");
			pineGrowRadius = Config("Saplings", "PineGrowRadius", 2f, "Radius of free space required for a pine sapling to grow.");
			firGrowRadius = Config("Saplings", "FirGrowRadius", 2f, "Radius of free space required for a fir sapling to grow.");
			yggaMinScale = Config("Saplings", "YggaMinScale", 0.5f, "The minimum scaling factor used to scale a ygga tree upon growth.");
			yggaMaxScale = Config("Saplings", "YggaMaxScale", 2f, "The minimum scaling factor used to scale a ygga tree upon growth.");
			yggaGrowthTime = Config("Saplings", "YggaGrowthTime", 3000f, "Number of seconds it takes for a ygga tree to grow from a ygga sapling (will take at least 10 seconds after planting to grow).");
			yggaGrowRadius = Config("Saplings", "YggaGrowRadius", 2f, "Radius of free space required for a ygga sapling to grow.");
			autumnBirchMinScale = Config("Saplings", "AutumnBirchMinScale", 0.5f, "The minimum scaling factor used to scale an autumn birch tree upon growth.");
			autumnBirchMaxScale = Config("Saplings", "AutumnBirchMaxScale", 1f, "The minimum scaling factor used to scale an autumn birch tree upon growth.");
			autumnBirchGrowthTime = Config("Saplings", "AutumnBirchGrowthTime", 3000f, "Number of seconds it takes for an autumn birch tree to grow from an autumn birch sapling (will take at least 10 seconds after planting to grow).");
			autumnBirchGrowRadius = Config("Saplings", "AutumnBirchGrowRadius", 2f, "Radius of free space required for an autumn birch sapling to grow.");
			ashwoodMinScale = Config("Saplings", "AshwoodMinScale", 0.5f, "The minimum scaling factor used to scale an ashwood tree upon growth.");
			ashwoodMaxScale = Config("Saplings", "AshwoodMaxScale", 2f, "The minimum scaling factor used to scale an ashwood tree upon growth.");
			ashwoodGrowthTime = Config("Saplings", "AshwoodGrowthTime", 3000f, "Number of seconds it takes for an ashwood tree to grow from an ashwood sapling (will take at least 10 seconds after planting to grow).");
			ashwoodGrowRadius = Config("Saplings", "AshwoodGrowRadius", 2f, "Radius of free space required for an ashwood sapling to grow.");
			enableSeedOverrides = Config("Seeds", "EnableSeedOverrides", value: false, new ConfigDescription("Enables the [Seeds] section of this config.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = 10
				}
			}));
			seedDropMin = Config("Seeds", "seedDropMin", 1, new ConfigDescription("Determines minimum amount of seeds that can drop when trees drop seeds.", (AcceptableValueBase)null, new object[1] { seedSettingAtrributes }));
			seedDropMax = Config("Seeds", "seedDropMax", 2, new ConfigDescription("Determines maximum amount of seeds that can drop when trees drop seeds.", (AcceptableValueBase)null, new object[1] { seedSettingAtrributes }));
			treeDropMin = Config("Seeds", "treeDropMin", 1, new ConfigDescription("Determines minimum amount of times a destroyed tree will attempt to select a drop from its drop table.", (AcceptableValueBase)null, new object[1] { seedSettingAtrributes }));
			treeDropMax = Config("Seeds", "treeDropMax", 3, new ConfigDescription("Determines (maximum amount of times - 1) a destroyed tree will attempt to select a drop from its drop table.", (AcceptableValueBase)null, new object[1] { seedSettingAtrributes }));
			dropChance = Config("Seeds", "dropChance", 0.5f, new ConfigDescription("Chance that items will drop from trees when destroyed. Default value 0.5f (50%). Set between 0 and 1f.", (AcceptableValueBase)null, new object[1] { seedSettingAtrributes }));
			oneOfEach = Config("Seeds", "oneOfEach", value: false, new ConfigDescription("When enabled, destroyed trees will not drop the same item from its drop table more than once.", (AcceptableValueBase)null, new object[1] { seedSettingAtrributes }));
			enablePickableTimers = Config("UI", "EnablePickableTimers", value: true, "Enables display of growth time remaining on pickable resources.", synchronizedSetting: false);
			enablePlantTimers = Config("UI", "EnablePlantTimers", value: true, "Enables display of growth time remaining on planted resources, such as crops and saplings.", synchronizedSetting: false);
			growthAsPercentage = Config("UI", "GrowthAsPercentage", value: false, "Enables display of growth time as a percentage instead of time remaining.", synchronizedSetting: false);
			enableVineOverrides = Config("Vines", "EnableVineOverrides", value: false, new ConfigDescription("Enables/Disables the [Vines] section of this config with the exception of color related settings.", (AcceptableValueBase)null, new object[1]
			{
				new ConfigurationManagerAttributes
				{
					Order = 12
				}
			}));
			vineAttachDistance = Config("Vines", "VineAttachDistance", 1.8f, "Distance at which vine saplings can attach to walls.");
			vineGrowRadius = Config("Vines", "VineGrowRadius", 1.8f, "Distance from existing wall-attached vines required for an ashvine sapling to mature and attach to a wall.");
			vineGrowthTime = Config("Vines", "VineGrowthTime", 200f, "Length of time (in seconds) that it takes for a vine ash sapling to mature.");
			vineBerryRespawnTime = Config("Vines", "VineBerryRespawnTime", 200, "Length of time (in minutes) that it takes for vine berries to regrow");
			vineBerryReturn = Config("Vines", "VineBerryReturn", 3, "Resources gained upon harvesting vine berries.");
		}

		private void SetupSettingChangedSubscriptions()
		{
			ConfigFile.SettingChanged += ConfigEventHandlers.ConfigSettingChanged;
			showPickableSpawners.SettingChanged += ConfigEventHandlers.CoreSettingChanged;
			enableMiscFlora.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			enableDebris.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			snappableVines.SettingChanged += ConfigEventHandlers.CoreSettingChanged;
			enableExtraResources.SettingChanged += ConfigEventHandlers.ExtraResourcesFileOrSettingChanged;
			disabledResourceNames.SettingChanged += ConfigEventHandlers.CoreSettingChanged;
			requireCultivation.SettingChanged += ConfigEventHandlers.CoreSettingChanged;
			placeAnywhere.SettingChanged += ConfigEventHandlers.CoreSettingChanged;
			enforceBiomes.SettingChanged += ConfigEventHandlers.CoreSettingChanged;
			enforceBiomesVanilla.SettingChanged += ConfigEventHandlers.CoreSettingChanged;
			plantsRequireShielding.SettingChanged += ConfigEventHandlers.CoreSettingChanged;
			recoverResources.SettingChanged += ConfigEventHandlers.CoreSettingChanged;
			enemiesTargetPieces.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			raspberryCost.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			blueberryCost.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			cloudberryCost.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			raspberryRespawnTime.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			blueberryRespawnTime.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			cloudberryRespawnTime.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			raspberryReturn.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			blueberryReturn.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			cloudberryReturn.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			enableCropOverrides.SettingChanged += ConfigEventHandlers.CropSettingChanged;
			overrideModdedCrops.SettingChanged += ConfigEventHandlers.CropSettingChanged;
			cropMinScale.SettingChanged += ConfigEventHandlers.CropSettingChanged;
			cropMaxScale.SettingChanged += ConfigEventHandlers.CropSettingChanged;
			cropGrowTimeMin.SettingChanged += ConfigEventHandlers.CropSettingChanged;
			cropGrowTimeMax.SettingChanged += ConfigEventHandlers.CropSettingChanged;
			cropGrowRadius.SettingChanged += ConfigEventHandlers.CropSettingChanged;
			cropRequireCultivation.SettingChanged += ConfigEventHandlers.CropSettingChanged;
			enemiesTargetCrops.SettingChanged += ConfigEventHandlers.CropSettingChanged;
			barleyCost.SettingChanged += ConfigEventHandlers.CropSettingChanged;
			barleyReturn.SettingChanged += ConfigEventHandlers.CropSettingChanged;
			carrotCost.SettingChanged += ConfigEventHandlers.CropSettingChanged;
			carrotReturn.SettingChanged += ConfigEventHandlers.CropSettingChanged;
			flaxCost.SettingChanged += ConfigEventHandlers.CropSettingChanged;
			flaxReturn.SettingChanged += ConfigEventHandlers.CropSettingChanged;
			onionCost.SettingChanged += ConfigEventHandlers.CropSettingChanged;
			onionReturn.SettingChanged += ConfigEventHandlers.CropSettingChanged;
			seedCarrotCost.SettingChanged += ConfigEventHandlers.CropSettingChanged;
			seedCarrotReturn.SettingChanged += ConfigEventHandlers.CropSettingChanged;
			seedOnionCost.SettingChanged += ConfigEventHandlers.CropSettingChanged;
			seedOnionReturn.SettingChanged += ConfigEventHandlers.CropSettingChanged;
			seedTurnipCost.SettingChanged += ConfigEventHandlers.CropSettingChanged;
			seedTurnipReturn.SettingChanged += ConfigEventHandlers.CropSettingChanged;
			turnipCost.SettingChanged += ConfigEventHandlers.CropSettingChanged;
			turnipReturn.SettingChanged += ConfigEventHandlers.CropSettingChanged;
			pickableBranchCost.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			pickableBranchReturn.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			pickableBranchRespawnTime.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			pickableStoneCost.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			pickableStoneReturn.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			pickableStoneRespawnTime.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			pickableFlintCost.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			pickableFlintReturn.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			pickableFlintRespawnTime.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			mushroomCost.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			yellowMushroomCost.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			blueMushroomCost.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			smokePuffCost.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			mushroomRespawnTime.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			yellowMushroomRespawnTime.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			blueMushroomRespawnTime.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			smokePuffRespawnTime.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			mushroomReturn.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			yellowMushroomReturn.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			blueMushroomReturn.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			smokePuffReturn.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			thistleCost.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			dandelionCost.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			fiddleheadCost.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			thistleRespawnTime.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			dandelionRespawnTime.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			fiddleheadRespawnTime.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			thistleReturn.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			dandelionReturn.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			fiddleheadReturn.SettingChanged += ConfigEventHandlers.PieceSettingChanged;
			overrideModdedSaplings.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			moddedSaplingMinScale.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			moddedSaplingMaxScale.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			moddedSaplingGrowthTime.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			moddedSaplingGrowRadius.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			ancientGrowRadius.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			ancientGrowthTime.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			ancientMinScale.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			ancientMaxScale.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			beechGrowRadius.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			beechGrowthTime.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			beechMinScale.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			beechMaxScale.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			pineGrowRadius.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			pineGrowthTime.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			pineMinScale.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			pineMaxScale.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			firGrowRadius.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			firGrowthTime.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			firMinScale.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			firMaxScale.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			birchGrowRadius.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			birchGrowthTime.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			birchMinScale.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			birchMaxScale.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			oakGrowRadius.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			oakGrowthTime.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			oakMinScale.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			oakMaxScale.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			yggaGrowRadius.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			yggaGrowthTime.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			yggaMinScale.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			yggaMaxScale.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			autumnBirchGrowRadius.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			autumnBirchGrowthTime.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			autumnBirchMinScale.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			autumnBirchMaxScale.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			ashwoodGrowRadius.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			ashwoodGrowthTime.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			ashwoodMinScale.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			ashwoodMaxScale.SettingChanged += ConfigEventHandlers.SaplingSettingChanged;
			enableSeedOverrides.SettingChanged += ConfigEventHandlers.SeedSettingChanged;
			seedDropMin.SettingChanged += ConfigEventHandlers.SeedSettingChanged;
			seedDropMax.SettingChanged += ConfigEventHandlers.SeedSettingChanged;
			treeDropMin.SettingChanged += ConfigEventHandlers.SeedSettingChanged;
			treeDropMax.SettingChanged += ConfigEventHandlers.SeedSettingChanged;
			dropChance.SettingChanged += ConfigEventHandlers.SeedSettingChanged;
			oneOfEach.SettingChanged += ConfigEventHandlers.SeedSettingChanged;
			enableVineOverrides.SettingChanged += ConfigEventHandlers.VineSettingChanged;
			vineAttachDistance.SettingChanged += ConfigEventHandlers.VineSettingChanged;
			vineGrowRadius.SettingChanged += ConfigEventHandlers.VineSettingChanged;
			vineGrowthTime.SettingChanged += ConfigEventHandlers.VineSettingChanged;
			vineBerryRespawnTime.SettingChanged += ConfigEventHandlers.VineSettingChanged;
			vineBerryReturn.SettingChanged += ConfigEventHandlers.VineSettingChanged;
			extraResources = new CustomSyncedValue<List<string>>(ConfigSync, "PE_ExtraResources", new List<string>(), 0);
			((CustomSyncedValueBase)extraResources).ValueChanged += ConfigEventHandlers.ExtraResourcesChanged;
			cropSettingAttributes.ForEach(delegate(ConfigurationManagerAttributes attributes)
			{
				attributes.Browsable = enableCropOverrides.Value;
			});
			seedSettingAtrributes.Browsable = enableSeedOverrides.Value;
			enableCropOverrides.SettingChanged += delegate
			{
				cropSettingAttributes.ForEach(delegate(ConfigurationManagerAttributes attributes)
				{
					attributes.Browsable = enableCropOverrides.Value;
				});
				ConfigManagerHelper.ReloadConfigDisplay();
			};
			enableSeedOverrides.SettingChanged += delegate
			{
				seedSettingAtrributes.Browsable = enableSeedOverrides.Value;
				ConfigManagerHelper.ReloadConfigDisplay();
			};
		}

		internal void Save()
		{
			ConfigFile.Save();
		}

		internal void Reload()
		{
			ConfigFile.Reload();
		}
	}
	internal struct ExtraResource
	{
		public string prefabName;

		public string resourceName;

		public int resourceCost;

		public bool groundOnly;

		public string pieceName;

		public string pieceDescription;

		internal readonly bool IsValid()
		{
			if (prefabName != null && !prefabName.StartsWith("PE_Fake") && resourceName != null)
			{
				return resourceCost != 0;
			}
			return false;
		}
	}
	internal static class PluginInitUtils
	{
		internal static void InitPrefabRefs()
		{
			//IL_00e2: 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_01e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e8: Expected O, but got Unknown
			StaticMembers.Dbgl("InitPrefabRefs", forceLog: false, (LogLevel)16);
			if (StaticMembers.prefabRefs.Count > 0)
			{
				return;
			}
			Dictionary<string, AssetID> allAssetPathsInBundleMappedToAssetID = Runtime.GetAllAssetPathsInBundleMappedToAssetID();
			bool flag = false;
			StaticContent.VanillaPrefabRefs.ForEach(delegate(string s)
			{
				StaticMembers.prefabRefs.Add(s, null);
			});
			StaticContent.VanillaPrefabRefs.Clear();
			StaticMembers.deserializedExtraResources.ForEach(delegate(ExtraResource er)
			{
				StaticMembers.prefabRefs[er.prefabName] = null;
			});
			SoftReference<GameObject> val = default(SoftReference<GameObject>);
			foreach (string key2 in allAssetPathsInBundleMappedToAssetID.Keys)
			{
				if (!key2.EndsWith(".prefab", StringComparison.Ordinal))
				{
					continue;
				}
				string key = key2.Split(new char[1] { '/' }).Last().Replace(".prefab", "");
				if (StaticMembers.prefabRefs.ContainsKey(key))
				{
					val..ctor(allAssetPathsInBundleMappedToAssetID[key2]);
					val.Load();
					StaticMembers.prefabRefs[key] = val.Asset;
					if (!StaticMembers.prefabRefs.Any((KeyValuePair<string, GameObject> keyValuePair) => !Object.op_Implicit((Object)(object)keyValuePair.Value)))
					{
						StaticMembers.Dbgl("Found all prefab references.", forceLog: false, (LogLevel)16);
						flag = true;
						break;
					}
				}
			}
			if (!flag)
			{
				StaticMembers.Dbgl("Could not find all prefab references, attempting alternate prefab detection method.", forceLog: false, (LogLevel)16);
				List<string> list = (from kvp in StaticMembers.prefabRefs
					where !Object.op_Implicit((Object)(object)kvp.Value)
					select kvp.Key).ToList();
				Object[] array = Resources.FindObjectsOfTypeAll(typeof(GameObject));
				for (int num = 0; num < array.Length; num++)
				{
					GameObject val2 = (GameObject)array[num];
					if (list.Contains(((Object)val2).name))
					{
						StaticMembers.prefabRefs[((Object)val2).name] = val2;
						list.Remove(((Object)val2).name);
						if (!list.Any())
						{
							StaticMembers.Dbgl("Found all prefab references on second attempt.", forceLog: false, (LogLevel)16);
							break;
						}
					}
				}
				foreach (string item in list)
				{
					StaticMembers.Dbgl("prefabRefs[" + item + "] value is null, removing key and value pair.", forceLog: false, (LogLevel)16);
					StaticMembers.prefabRefs.Remove(item);
				}
			}
			StaticContent.CustomPrefabRefs.ForEach(delegate(string s)
			{
				StaticMembers.prefabRefs.Add(s, PluginUtils.CreatePrefab(s));
			});
			StaticContent.CustomPrefabRefs.Clear();
		}

		internal static bool InitExtraResourceRefs(ZNetScene instance, bool logErrors = false)
		{
			StaticMembers.Dbgl("InitExtraResourceRefs", forceLog: false, (LogLevel)16);
			bool result = false;
			foreach (ExtraResource deserializedExtraResource in StaticMembers.deserializedExtraResources)
			{
				if (!StaticMembers.prefabRefs.TryGetValue(deserializedExtraResource.prefabName, out var value))
				{
					value = instance.GetPrefab(deserializedExtraResource.prefabName);
					if (Object.op_Implicit((Object)(object)value))
					{
						StaticMembers.prefabRefs[deserializedExtraResource.prefabName] = value;
						StaticMembers.Dbgl("Added " + deserializedExtraResource.prefabName + " to prefabRefs", forceLog: false, (LogLevel)16);
						result = true;
					}
					else
					{
						StaticMembers.Dbgl("Could not find prefab reference for " + deserializedExtraResource.prefabName + ", skipping entry.", logErrors || StaticMembers.config.EnableDebugMessages, (LogLevel)4);
					}
				}
			}
			return result;
		}

		internal static void InitPieceRefs()
		{
			StaticMembers.Dbgl("InitPieceRefs", forceLog: false, (LogLevel)16);
			if (StaticMembers.pieceRefs.Count > 0)
			{
				PluginUtils.RemoveFromCultivator(StaticMembers.pieceRefs.ConvertAll((Converter<PieceDB, PrefabDB>)((PieceDB x) => x)));
				StaticMembers.pieceRefs.Clear();
			}
			StaticMembers.pieceRefs = StaticContent.GeneratePieceRefs();
		}

		internal static void InitPieces()
		{
			//IL_016e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0173: Unknown result type (might be due to invalid IL or missing references)
			//IL_017a: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_019d: Expected O, but got Unknown
			//IL_01f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_0217: Unknown result type (might be due to invalid IL or missing references)
			//IL_021c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0231: Unknown result type (might be due to invalid IL or missing references)
			//IL_0239: Expected O, but got Unknown
			//IL_023b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0240: Unknown result type (might be due to invalid IL or missing references)
			//IL_0255: Unknown result type (might be due to invalid IL or missing references)
			//IL_025d: Expected O, but got Unknown
			//IL_00df: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fb: Unknown result type (might be due to invalid IL or missing references)
			//IL_0113: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Expected O, but got Unknown
			//IL_03be: Unknown result type (might be due to invalid IL or missing references)
			//IL_03c3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02bf: Unknown result type (might be due to invalid IL or missing references)
			//IL_02c4: Unknown result type (might be due to invalid IL or missing references)
			//IL_02cb: Unknown result type (might be due to invalid IL or missing references)
			//IL_02d0: Unknown result type (might be due to invalid IL or missing references)
			//IL_02db: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e8: Unknown result type (might be due to invalid IL or missing references)
			StaticMembers.Dbgl("InitPieces", forceLog: false, (LogLevel)16);
			foreach (PieceDB pdb in StaticMembers.pieceRefs)
			{
				if (StaticMembers.config.DisabledResourceNames.Contains(pdb.key))
				{
					StaticMembers.Dbgl("Resource disabled: " + pdb.key + ", skipping.", forceLog: false, (LogLevel)16);
					pdb.enabled = false;
				}
				ItemDrop component = ObjectDB.instance.GetItemPrefab(pdb.Resource.Key).GetComponent<ItemDrop>();
				if (pdb.Resources.Count > 0)
				{
					List<Requirement> list = new List<Requirement>();
					foreach (string key in pdb.Resources.Keys)
					{
						list.Add(new Requirement
						{
							m_resItem = ObjectDB.instance.GetItemPrefab(key).GetComponent<ItemDrop>(),
							m_amount = pdb.Resources[key],
							m_recover = pdb.recover
						});
					}
					pdb.Piece.m_resources = list.ToArray();
				}
				else
				{
					pdb.Piece.m_resources = (Requirement[])(object)new Requirement[1]
					{
						new Requirement
						{
							m_resItem = component,
							m_amount = pdb.ResourceCost,
							m_recover = pdb.recover
						}
					};
				}
				pdb.Piece.m_icon = (pdb.icon ? PluginUtils.CreateSprite(pdb.key + "PieceIcon.png", new Rect(0f, 0f, 64f, 64f)) : component.m_itemData.GetIcon());
				pdb.Piece.m_placeEffect.m_effectPrefabs = (EffectData[])(object)new EffectData[2]
				{
					new EffectData
					{
						m_prefab = StaticMembers.prefabRefs["vfx_Place_wood_pole"],
						m_enabled = true
					},
					new EffectData
					{
						m_prefab = StaticMembers.prefabRefs["sfx_build_cultivator"],
						m_enabled = true
					}
				};
				if (pdb.snapPoints != null)
				{
					Transform val = pdb.Prefab.transform.Find("_snappoint");
					if (StaticMembers.config.SnappableVines)
					{
						if (!Object.op_Implicit((Object)(object)val))
						{
							foreach (Vector3 snapPoint in pdb.snapPoints)
							{
								GameObject val2 = new GameObject("_snappoint")
								{
									tag = "snappoint"
								};
								val2.transform.position = snapPoint;
								val2.transform.SetParent(pdb.Prefab.transform);
								val2.SetActive(false);
							}
						}
					}
					else
					{
						while (Object.op_Implicit((Object)(object)val))
						{
							Object.DestroyImmediate((Object)(object)((Component)val).gameObject);
							val = pdb.Prefab.transform.Find("_snappoint");
						}
					}
				}
				Pickable component2 = pdb.Prefab.GetComponent<Pickable>();
				if (!Object.op_Implicit((Object)(object)component2) || StaticMembers.deserializedExtraResources.Any((ExtraResource x) => x.prefabName == pdb.key))
				{
					continue;
				}
				component2.m_respawnTimeMinutes = pdb.respawnTime;
				component2.m_amount = pdb.resourceReturn;
				pdb.Piece.m_onlyInBiome = pdb.biome;
				if (pdb.hideWhenPicked)
				{
					component2.m_hideWhenPicked = ((pdb.respawnTime > 0) ? ((Component)component2).gameObject : null);
				}
				Transform val3 = pdb.Prefab.transform.Find("visual");
				if (!Object.op_Implicit((Object)(object)val3))
				{
					continue;
				}
				Transform val4 = StaticMembers.prefabRefs[pdb.key + "_Picked"].transform.Find("PE_Picked");
				if (Object.op_Implicit((Object)(object)val4))
				{
					if (StaticMembers.config.ShowPickableSpawners)
					{
						val4.SetParent(pdb.Prefab.transform);
					}
					if (!StaticMembers.piecesInitialized)
					{
						MeshRenderer component3 = ((Component)val4).GetComponent<MeshRenderer>();
						MeshRenderer component4 = ((Component)val3).GetComponent<MeshRenderer>();
						((Renderer)component3).sharedMaterials = ((pdb.key == "Pickable_Thistle") ? ((Renderer)((Component)val3.Find("default")).GetComponent<MeshRenderer>()).sharedMaterials : ((Renderer)component4).sharedMaterials);
						if (pdb.key.Contains("Dandelion"))
						{
							Material val5 = ((Renderer)component4).sharedMaterials[0];
							((Renderer)component3).sharedMaterials = (Material[])(object)new Material[2] { val5, val5 };
						}
					}
				}
				else
				{
					Transform val6 = StaticMembers.prefabRefs[pdb.key].transform.Find("PE_Picked");
					if (!StaticMembers.config.ShowPickableSpawners && Object.op_Implicit((Object)(object)val6))
					{
						val6.SetParent(StaticMembers.prefabRefs[pdb.key + "_Picked"].transform);
					}
				}
				if (pdb.extraDrops)
				{
					component2.m_extraDrops.m_drops.Clear();
				}
			}
			StaticMembers.piecesInitialized = true;
		}

		internal static void InitSaplingRefs()
		{
			StaticMembers.Dbgl("InitSaplingRefs", forceLog: false, (LogLevel)16);
			if (StaticMembers.saplingRefs.Count > 0)
			{
				PluginUtils.RemoveFromCultivator(StaticMembers.saplingRefs.ConvertAll((Converter<SaplingDB, PrefabDB>)((SaplingDB x) => x)));
				StaticMembers.saplingRefs.Clear();
			}
			StaticMembers.saplingRefs = StaticContent.GenerateCustomSaplingRefs();
		}

		internal static void InitSaplings()
		{
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_0093: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_0158: Unknown result type (might be due to invalid IL or missing references)
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0177: Expected O, but got Unknown
			//IL_022b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0234: Unknown result type (might be due to invalid IL or missing references)
			//IL_094c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0958: Unknown result type (might be due to invalid IL or missing references)
			//IL_0959: Unknown result type (might be due to invalid IL or missing references)
			//IL_095b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0960: Unknown result type (might be due to invalid IL or missing references)
			//IL_0962: Unknown result type (might be due to invalid IL or missing references)
			//IL_0953: Unknown result type (might be due to invalid IL or missing references)
			//IL_078a: Unknown result type (might be due to invalid IL or missing references)
			StaticMembers.Dbgl("InitSaplings", forceLog: false, (LogLevel)16);
			ModifyTreeDrops();
			AssetID val2 = default(AssetID);
			SoftReference<Shader> val3 = default(SoftReference<Shader>);
			foreach (SaplingDB item in StaticContent.GenerateVanillaSaplingRefs().Concat(StaticMembers.saplingRefs))
			{
				Plant component = item.Prefab.GetComponent<Plant>();
				Piece component2 = item.Prefab.GetComponent<Piece>();
				component.m_growTime = (component.m_growTimeMax = item.growTime);
				component.m_growRadius = item.growRadius;
				component.m_minScale = item.minScale;
				component.m_maxScale = item.maxScale;
				component2.m_onlyInBiome = (component.m_biome = item.biome);
				component.m_tolerateCold = item.tolerateCold || !StaticMembers.config.PlantsRequireShielding;
				component.m_tolerateHeat = item.tolerateHeat || !StaticMembers.config.PlantsRequireShielding;
				component.m_destroyIfCantGrow = (component2.m_groundOnly = !StaticMembers.config.PlaceAnywhere);
				if (!StaticMembers.saplingRefs.Contains(item))
				{
					continue;
				}
				component.m_grownPrefabs = item.grownPrefabs;
				List<Requirement> list = new List<Requirement>();
				foreach (string key in item.Resources.Keys)
				{
					list.Add(new Requirement
					{
						m_resItem = ObjectDB.instance.GetItemPrefab(key).GetComponent<ItemDrop>(),
						m_amount = item.Resources[key],
						m_recover = false
					});
				}
				component2.m_resources = list.ToArray();
				if (StaticMembers.config.DisabledResourceNames.Contains(item.key))
				{
					StaticMembers.Dbgl("Resource disabled: " + item.key, forceLog: false, (LogLevel)16);
					item.enabled = false;
				}
				if (StaticMembers.saplingsInitialized)
				{
					continue;
				}
				string[] array = new string[2] { "healthy", "unhealthy" };
				Transform val = StaticMembers.prefabRefs["Birch_Sapling"].transform.Find(array[0]);
				Shader shader;
				if (!StaticMembers.isDedicatedServer)
				{
					AssetID.TryParse("f6de4704e075b4095ae641aed283b641", ref val2);
					val3..ctor(val2);
					val3.Load();
					shader = val3.Asset;
				}
				else
				{
					shader = Shader.Find("Custom/Piece");
				}
				if (item.source != "AshlandsTree3")
				{
					string[] array2 = array;
					foreach (string text in array2)
					{
						((Component)item.Prefab.transform.Find(text)).GetComponent<MeshFilter>().mesh = ((Component)val.Find("Birch_Sapling")).GetComponent<MeshFilter>().mesh;
					}
				}
				switch (item.source)
				{
				case "YggaShoot_small1":
				{
					string[] array7 = new string[6] { "birchleafs002", "birchleafs003", "birchleafs008", "birchleafs009", "birchleafs010", "birchleafs011" };
					Material[] sharedMaterials3 = (Material[])(object)new Material[1] { ((Renderer)((Component)StaticMembers.prefabRefs[item.source].transform.Find("beech")).GetComponent<MeshRenderer>()).sharedMaterials[0] };
					Material[] sharedMaterials4 = (Material[])(object)new Material[1] { ((Renderer)((Component)StaticMembers.prefabRefs[item.source].transform.Find("beech")).GetComponent<MeshRenderer>()).sharedMaterials[1] };
					string[] array2 = array;
					foreach (string text7 in array2)
					{
						((Renderer)((Component)item.Prefab.transform.Find(text7)).GetComponent<MeshRenderer>()).sharedMaterials = sharedMaterials4;
					}
					array2 = array7;
					foreach (string text8 in array2)
					{
						string[] array6 = array;
						foreach (string text9 in array6)
						{
							((Component)item.Prefab.transform.Find(text9).Find(text8)).GetComponent<MeshFilter>().mesh = ((Component)val.Find(text8)).GetComponent<MeshFilter>().mesh;
							((Renderer)((Component)item.Prefab.transform.Find(text9).Find(text8)).GetComponent<MeshRenderer>()).sharedMaterials = sharedMaterials3;
						}
					}
					break;
				}
				case "SwampTree1":
				{
					Material[] array4 = (Material[])(object)new Material[1] { ((Renderer)((Component)StaticMembers.prefabRefs[item.source].transform.Find("swamptree1")).GetComponent<MeshRenderer>()).sharedMaterials[0] };
					array4[0].shader = shader;
					string[] array2 = array;
					foreach (string text3 in array2)
					{
						((Renderer)((Component)item.Prefab.transform.Find(text3)).GetComponent<MeshRenderer>()).sharedMaterials = array4;
					}
					break;
				}
				case "Birch1_aut":
				{
					string[] array5 = new string[6] { "birchleafs002", "birchleafs003", "birchleafs008", "birchleafs009", "birchleafs010", "birchleafs011" };
					Material[] sharedMaterials = (Material[])(object)new Material[1] { ((Renderer)((Component)StaticMembers.prefabRefs[item.source].transform.Find("Lod0")).GetComponent<MeshRenderer>()).sharedMaterials[0] };
					Material[] sharedMaterials2 = (Material[])(object)new Material[1] { ((Renderer)((Component)val.Find("Birch_Sapling")).GetComponent<MeshRenderer>()).sharedMaterials[0] };
					string[] array2 = array;
					foreach (string text4 in array2)
					{
						((Renderer)((Component)item.Prefab.transform.Find(text4)).GetComponent<MeshRenderer>()).sharedMaterials = sharedMaterials2;
					}
					array2 = array5;
					foreach (string text5 in array2)
					{
						string[] array6 = array;
						foreach (string text6 in array6)
						{
							((Component)item.Prefab.transform.Find(text6).Find(text5)).GetComponent<MeshFilter>().mesh = ((Component)val.Find(text5)).GetComponent<MeshFilter>().mesh;
							((Renderer)((Component)item.Prefab.transform.Find(text6).Find(text5)).GetComponent<MeshRenderer>()).sharedMaterials = sharedMaterials;
						}
					}
					break;
				}
				case "AshlandsTree3":
				{
					Transform val4 = StaticMembers.prefabRefs[item.source].transform.Find("default");
					MeshRenderer component3 = ((Component)val4).GetComponent<MeshRenderer>();
					Material[] array3 = (Material[])(object)new Material[1] { ((Renderer)component3).sharedMaterials[0] };
					array3[0].shader = shader;
					array3[0].SetTexture("_EmissionMap", ((Renderer)component3).sharedMaterials[0].GetTexture("_EmissiveTex"));
					string[] array2 = array;
					foreach (string text2 in array2)
					{
						((Component)item.Prefab.transform.Find(text2)).GetComponent<MeshFilter>().mesh = ((Component)val4).GetComponent<MeshFilter>().mesh;
						((Renderer)((Component)item.Prefab.transform.Find(text2)).GetComponent<MeshRenderer>()).sharedMaterials = array3;
					}
					break;
				}
				}
				component2.m_icon = (item.icon ? PluginUtils.CreateSprite(item.key + "PieceIcon.png", new Rect(0f, 0f, 64f, 64f)) : component2.m_resources[0].m_resItem.m_itemData.GetIcon());
				component2.m_placeEffect.m_effectPrefabs[0].m_prefab = StaticMembers.prefabRefs["vfx_Place_wood_pole"];
				component2.m_placeEffect.m_effectPrefabs[1].m_prefab = StaticMembers.prefabRefs["sfx_build_cultivator"];
				item.Prefab.GetComponent<Destructible>().m_hitEffect.m_effectPrefabs = StaticMembers.prefabRefs["Birch_Sapling"].GetComponent<Destructible>().m_hitEffect.m_effectPrefabs;
			}
			StaticMembers.saplingsInitialized = true;
			if (StaticMembers.moddedSaplingRefs.Count == 0)
			{
				return;
			}
			bool overrideModdedSaplings = StaticMembers.config.OverrideModdedSaplings;
			foreach (ModdedPlantDB moddedSaplingRef in StaticMembers.moddedSaplingRefs)
			{
				if (!Object.op_Implicit((Object)(object)moddedSaplingRef.Prefab))
				{
					StaticMembers.Dbgl(moddedSaplingRef.key + " reference is null, skipping application of modded sapling override settings", forceLog: true, (LogLevel)4);
					continue;
				}
				Piece component4 = moddedSaplingRef.Prefab.GetComponent<Piece>();
				Plant component5 = moddedSaplingRef.Prefab.GetComponent<Plant>();
				component5.m_growTime = (overrideModdedSaplings ? StaticMembers.config.ModdedSaplingGrowthTime : moddedSaplingRef.growTime);
				component5.m_growTimeMax = (overrideModdedSaplings ? StaticMembers.config.ModdedSaplingGrowthTime : moddedSaplingRef.growTimeMax);
				component5.m_growRadius = (overrideModdedSaplings ? StaticMembers.config.ModdedSaplingGrowRadius : moddedSaplingRef.growRadius);
				component5.m_minScale = (overrideModdedSaplings ? StaticMembers.config.ModdedSaplingMinScale : moddedSaplingRef.minScale);
				component5.m_maxScale = (overrideModdedSaplings ? StaticMembers.config.ModdedSaplingMaxScale : moddedSaplingRef.maxScale);
				component4.m_onlyInBiome = (component5.m_biome = ((overrideModdedSaplings && !StaticMembers.config.EnforceBiomes) ? StaticMembers.AllBiomes : moddedSaplingRef.biome));
				component5.m_tolerateCold = moddedSaplingRef.tolerateCold || !StaticMembers.config.PlantsRequireShielding;
				component5.m_tolerateHeat = moddedSaplingRef.tolerateHeat || !StaticMembers.config.PlantsRequireShielding;
				component5.m_destroyIfCantGrow = (component4.m_groundOnly = !StaticMembers.config.PlaceAnywhere);
			}
		}

		internal static void ModifyTreeDrops()
		{
			//IL_0034: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0058: 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_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_009f: Unknown result type (might be due to invalid IL or missing references)
			if (!StaticMembers.config.EnableSeedOverrides)
			{
				return;
			}
			foreach (KeyValuePair<GameObject, GameObject> treesToSeed in StaticContent.TreesToSeeds)
			{
				TreeBase component = treesToSeed.Key.GetComponent<TreeBase>();
				DropData item = default(DropData);
				bool flag = false;
				foreach (DropData drop in component.m_dropWhenDestroyed.m_drops)
				{
					if (((object)drop.m_item).Equals((object?)treesToSeed.Value))
					{
						flag = true;
						item = drop;
						break;
					}
				}
				if (flag)
				{
					component.m_dropWhenDestroyed.m_drops.Remove(item);
				}
				item.m_item = treesToSeed.Value;
				item.m_stackMin = StaticMembers.config.SeedDropMin;
				item.m_stackMax = StaticMembers.config.SeedDropMax;
				item.m_weight = 1f;
				component.m_dropWhenDestroyed.m_dropMin = StaticMembers.config.TreeDropMin;
				component.m_dropWhenDestroyed.m_dropMax = StaticMembers.config.TreeDropMax;
				component.m_dropWhenDestroyed.m_drops.Add(item);
				component.m_dropWhenDestroyed.m_dropChance = Mathf.Clamp(StaticMembers.config.DropChance, 0f, 1f);
				component.m_dropWhenDestroyed.m_oneOfEach = StaticMembers.config.OneOfEach;
			}
		}

		internal static void InitCrops()
		{
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_008b: Unknown result type (might be due to invalid IL or missing references)
			//IL_02a6: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ad: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a7: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d7: Unknown result type (might be due to invalid IL or missing references)
			StaticMembers.Dbgl("InitCrops", forceLog: false, (LogLevel)16);
			bool enableCropOverrides = StaticMembers.config.EnableCropOverrides;
			foreach (PrefabDB item in StaticContent.GenerateCropRefs())
			{
				Piece component = item.Prefab.GetComponent<Piece>();
				Plant component2 = item.Prefab.GetComponent<Plant>();
				Pickable component3 = component2.m_grownPrefabs[0].GetComponent<Pickable>();
				component.m_resources[0].m_amount = item.resourceCost;
				((StaticTarget)component).m_primaryTarget = (((StaticTarget)component).m_randomTarget = StaticMembers.config.EnemiesTargetCrops);
				component2.m_biome = item.biome;
				component2.m_tolerateCold = item.tolerateCold || !StaticMembers.config.PlantsRequireShielding;
				component2.m_tolerateHeat = item.tolerateHeat || !StaticMembers.config.PlantsRequireShielding;
				component2.m_minScale = (enableCropOverrides ? StaticMembers.config.CropMinScale : 0.9f);
				component2.m_maxScale = (enableCropOverrides ? StaticMembers.config.CropMaxScale : 1.1f);
				component2.m_growTime = (enableCropOverrides ? StaticMembers.config.CropGrowTimeMin : 4000f);
				component2.m_growTimeMax = (enableCropOverrides ? StaticMembers.config.CropGrowTimeMax : 5000f);
				

plugins/ServerSync.dll

Decompiled 3 hours ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Globalization;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Serialization;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using JetBrains.Annotations;
using Microsoft.CodeAnalysis;
using TMPro;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("ServerSync")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ServerSync")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("E16C3332-50B4-4DA6-9E8A-A590C4E5CD49")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace ServerSync
{
	[PublicAPI]
	public abstract class OwnConfigEntryBase
	{
		public object? LocalBaseValue;

		public bool SynchronizedConfig = true;

		public abstract ConfigEntryBase BaseConfig { get; }
	}
	[PublicAPI]
	public class SyncedConfigEntry<T>(ConfigEntry<T> sourceConfig) : OwnConfigEntryBase()
	{
		public readonly ConfigEntry<T> SourceConfig = sourceConfig;

		public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig;

		public T Value
		{
			get
			{
				return SourceConfig.Value;
			}
			set
			{
				SourceConfig.Value = value;
			}
		}

		public void AssignLocalValue(T value)
		{
			if (LocalBaseValue == null)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	public abstract class CustomSyncedValueBase
	{
		public object? LocalBaseValue;

		public readonly string Identifier;

		public readonly Type Type;

		private object? boxedValue;

		protected bool localIsOwner;

		public readonly int Priority;

		public object? BoxedValue
		{
			get
			{
				return boxedValue;
			}
			set
			{
				boxedValue = value;
				this.ValueChanged?.Invoke();
			}
		}

		public event Action? ValueChanged;

		protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority)
		{
			Priority = priority;
			Identifier = identifier;
			Type = type;
			configSync.AddCustomValue(this);
			localIsOwner = configSync.IsSourceOfTruth;
			configSync.SourceOfTruthChanged += delegate(bool truth)
			{
				localIsOwner = truth;
			};
		}
	}
	[PublicAPI]
	public sealed class CustomSyncedValue<T> : CustomSyncedValueBase
	{
		public T Value
		{
			get
			{
				return (T)base.BoxedValue;
			}
			set
			{
				base.BoxedValue = value;
			}
		}

		public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0)
			: base(configSync, identifier, typeof(T), priority)
		{
			Value = value;
		}

		public void AssignLocalValue(T value)
		{
			if (localIsOwner)
			{
				Value = value;
			}
			else
			{
				LocalBaseValue = value;
			}
		}
	}
	internal class ConfigurationManagerAttributes
	{
		[UsedImplicitly]
		public bool? ReadOnly = false;
	}
	[PublicAPI]
	public class ConfigSync
	{
		[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
		private static class SnatchCurrentlyHandlingRPC
		{
			public static ZRpc? currentRpc;

			[HarmonyPrefix]
			private static void Prefix(ZRpc __instance)
			{
				currentRpc = __instance;
			}
		}

		[HarmonyPatch(typeof(ZNet), "Awake")]
		internal static class RegisterRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance)
			{
				isServer = __instance.IsServer();
				foreach (ConfigSync configSync2 in configSyncs)
				{
					ZRoutedRpc.instance.Register<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync);
					if (isServer)
					{
						configSync2.InitialSyncDone = true;
						Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"));
					}
				}
				if (isServer)
				{
					((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges());
				}
				static void SendAdmin(List<ZNetPeer> peers, bool isAdmin)
				{
					ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1]
					{
						new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = isAdmin
						}
					});
					ConfigSync configSync = configSyncs.First();
					if (configSync != null)
					{
						((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package));
					}
				}
				static IEnumerator WatchAdminListChanges()
				{
					MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
					SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
					List<string> CurrentList = new List<string>(adminList.GetList());
					while (true)
					{
						yield return (object)new WaitForSeconds(30f);
						if (!adminList.GetList().SequenceEqual(CurrentList))
						{
							CurrentList = new List<string>(adminList.GetList());
							List<ZNetPeer> adminPeer = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p)
							{
								string hostName = p.m_rpc.GetSocket().GetHostName();
								return ((object)listContainsId == null) ? adminList.Contains(hostName) : ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName }));
							}).ToList();
							List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList();
							SendAdmin(nonAdminPeer, isAdmin: false);
							SendAdmin(adminPeer, isAdmin: true);
						}
					}
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		private static class RegisterClientRPCPatch
		{
			[HarmonyPostfix]
			private static void Postfix(ZNet __instance, ZNetPeer peer)
			{
				if (__instance.IsServer())
				{
					return;
				}
				foreach (ConfigSync configSync in configSyncs)
				{
					peer.m_rpc.Register<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync);
				}
			}
		}

		private class ParsedConfigs
		{
			public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>();

			public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>();
		}

		[HarmonyPatch(typeof(ZNet), "Shutdown")]
		private class ResetConfigsOnShutdown
		{
			[HarmonyPostfix]
			private static void Postfix()
			{
				ProcessingServerUpdate = true;
				foreach (ConfigSync configSync in configSyncs)
				{
					configSync.resetConfigsFromServer();
					configSync.IsSourceOfTruth = true;
					configSync.InitialSyncDone = false;
				}
				ProcessingServerUpdate = false;
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		private class SendConfigsAfterLogin
		{
			private class BufferingSocket : ZPlayFabSocket, ISocket
			{
				public volatile bool finished = false;

				public volatile int versionMatchQueued = -1;

				public readonly List<ZPackage> Package = new List<ZPackage>();

				public readonly ISocket Original;

				public BufferingSocket(ISocket original)
				{
					Original = original;
					((ZPlayFabSocket)this)..ctor();
				}

				public bool IsConnected()
				{
					return Original.IsConnected();
				}

				public ZPackage Recv()
				{
					return Original.Recv();
				}

				public int GetSendQueueSize()
				{
					return Original.GetSendQueueSize();
				}

				public int GetCurrentSendRate()
				{
					return Original.GetCurrentSendRate();
				}

				public bool IsHost()
				{
					return Original.IsHost();
				}

				public void Dispose()
				{
					Original.Dispose();
				}

				public bool GotNewData()
				{
					return Original.GotNewData();
				}

				public void Close()
				{
					Original.Close();
				}

				public string GetEndPointString()
				{
					return Original.GetEndPointString();
				}

				public void GetAndResetStats(out int totalSent, out int totalRecv)
				{
					Original.GetAndResetStats(ref totalSent, ref totalRecv);
				}

				public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec)
				{
					Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec);
				}

				public ISocket Accept()
				{
					return Original.Accept();
				}

				public int GetHostPort()
				{
					return Original.GetHostPort();
				}

				public bool Flush()
				{
					return Original.Flush();
				}

				public string GetHostName()
				{
					return Original.GetHostName();
				}

				public void VersionMatch()
				{
					if (finished)
					{
						Original.VersionMatch();
					}
					else
					{
						versionMatchQueued = Package.Count;
					}
				}

				public void Send(ZPackage pkg)
				{
					//IL_0057: Unknown result type (might be due to invalid IL or missing references)
					//IL_005d: Expected O, but got Unknown
					int pos = pkg.GetPos();
					pkg.SetPos(0);
					int num = pkg.ReadInt();
					if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished)
					{
						ZPackage val = new ZPackage(pkg.GetArray());
						val.SetPos(pos);
						Package.Add(val);
					}
					else
					{
						pkg.SetPos(pos);
						Original.Send(pkg);
					}
				}
			}

			[HarmonyPriority(800)]
			[HarmonyPrefix]
			private static void Prefix(ref Dictionary<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc)
			{
				//IL_0078: Unknown result type (might be due to invalid IL or missing references)
				//IL_007e: Invalid comparison between Unknown and I4
				if (!__instance.IsServer())
				{
					return;
				}
				BufferingSocket bufferingSocket = new BufferingSocket(rpc.GetSocket());
				AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket);
				object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
				ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
				if (val != null && (int)ZNet.m_onlineBackend > 0)
				{
					FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket");
					object? value = fieldInfo.GetValue(val);
					ZPlayFabSocket val2 = (ZPlayFabSocket)((value is ZPlayFabSocket) ? value : null);
					if (val2 != null)
					{
						typeof(ZPlayFabSocket).GetField("m_remotePlayerId").SetValue(bufferingSocket, val2.m_remotePlayerId);
					}
					fieldInfo.SetValue(val, bufferingSocket);
				}
				if (__state == null)
				{
					__state = new Dictionary<Assembly, BufferingSocket>();
				}
				__state[Assembly.GetExecutingAssembly()] = bufferingSocket;
			}

			[HarmonyPostfix]
			private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc)
			{
				ZNetPeer peer;
				if (__instance.IsServer())
				{
					object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
					peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null);
					if (peer == null)
					{
						SendBufferedData();
					}
					else
					{
						((MonoBehaviour)__instance).StartCoroutine(sendAsync());
					}
				}
				void SendBufferedData()
				{
					if (rpc.GetSocket() is BufferingSocket bufferingSocket)
					{
						AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original);
						object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc });
						ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null);
						if (val != null)
						{
							AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original);
						}
					}
					BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()];
					bufferingSocket2.finished = true;
					for (int i = 0; i < bufferingSocket2.Package.Count; i++)
					{
						if (i == bufferingSocket2.versionMatchQueued)
						{
							bufferingSocket2.Original.VersionMatch();
						}
						bufferingSocket2.Original.Send(bufferingSocket2.Package[i]);
					}
					if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued)
					{
						bufferingSocket2.Original.VersionMatch();
					}
				}
				IEnumerator sendAsync()
				{
					foreach (ConfigSync configSync in configSyncs)
					{
						List<PackageEntry> entries = new List<PackageEntry>();
						if (configSync.CurrentVersion != null)
						{
							entries.Add(new PackageEntry
							{
								section = "Internal",
								key = "serverversion",
								type = typeof(string),
								value = configSync.CurrentVersion
							});
						}
						MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						entries.Add(new PackageEntry
						{
							section = "Internal",
							key = "lockexempt",
							type = typeof(bool),
							value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2]
							{
								adminList,
								rpc.GetSocket().GetHostName()
							}))
						});
						ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false);
						yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package));
					}
					SendBufferedData();
				}
			}
		}

		private class PackageEntry
		{
			public string section = null;

			public string key = null;

			public Type type = null;

			public object? value;
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")]
		private static class PreventSavingServerInfo
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, ref string __result)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase))
				{
					return true;
				}
				__result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType);
				return false;
			}
		}

		[HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")]
		private static class PreventConfigRereadChangingValues
		{
			[HarmonyPrefix]
			private static bool Prefix(ConfigEntryBase __instance, string value)
			{
				OwnConfigEntryBase ownConfigEntryBase = configData(__instance);
				if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null)
				{
					return true;
				}
				try
				{
					ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType);
				}
				catch (Exception ex)
				{
					Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}");
				}
				return false;
			}
		}

		private class InvalidDeserializationTypeException : Exception
		{
			public string expected = null;

			public string received = null;

			public string field = "";
		}

		public static bool ProcessingServerUpdate;

		public readonly string Name;

		public string? DisplayName;

		public string? CurrentVersion;

		public string? MinimumRequiredVersion;

		public bool ModRequired = false;

		private bool? forceConfigLocking;

		private bool isSourceOfTruth = true;

		private static readonly HashSet<ConfigSync> configSyncs;

		private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>();

		private HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>();

		private static bool isServer;

		private static bool lockExempt;

		private OwnConfigEntryBase? lockedConfig = null;

		private const byte PARTIAL_CONFIGS = 1;

		private const byte FRAGMENTED_CONFIG = 2;

		private const byte COMPRESSED_CONFIG = 4;

		private readonly Dictionary<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>();

		private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>();

		private static long packageCounter;

		public bool IsLocked
		{
			get
			{
				bool? flag = forceConfigLocking;
				bool num;
				if (!flag.HasValue)
				{
					if (lockedConfig == null)
					{
						goto IL_0052;
					}
					num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0;
				}
				else
				{
					num = flag == true;
				}
				if (!num)
				{
					goto IL_0052;
				}
				int result = ((!lockExempt) ? 1 : 0);
				goto IL_0053;
				IL_0052:
				result = 0;
				goto IL_0053;
				IL_0053:
				return (byte)result != 0;
			}
			set
			{
				forceConfigLocking = value;
			}
		}

		public bool IsAdmin => lockExempt || isSourceOfTruth;

		public bool IsSourceOfTruth
		{
			get
			{
				return isSourceOfTruth;
			}
			private set
			{
				if (value != isSourceOfTruth)
				{
					isSourceOfTruth = value;
					this.SourceOfTruthChanged?.Invoke(value);
				}
			}
		}

		public bool InitialSyncDone { get; private set; } = false;

		public event Action<bool>? SourceOfTruthChanged;

		private event Action? lockedConfigChanged;

		static ConfigSync()
		{
			ProcessingServerUpdate = false;
			configSyncs = new HashSet<ConfigSync>();
			lockExempt = false;
			packageCounter = 0L;
			RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle);
		}

		public ConfigSync(string name)
		{
			Name = name;
			configSyncs.Add(this);
			new VersionCheck(this);
		}

		public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry)
		{
			OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry);
			SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>;
			if (syncedEntry == null)
			{
				syncedEntry = new SyncedConfigEntry<T>(configEntry);
				AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1]
				{
					new ConfigurationManagerAttributes()
				}.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray());
				configEntry.SettingChanged += delegate
				{
					if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig)
					{
						Broadcast(0L, (ConfigEntryBase)configEntry);
					}
				};
				allConfigs.Add(syncedEntry);
			}
			return syncedEntry;
		}

		public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible
		{
			if (lockedConfig != null)
			{
				throw new Exception("Cannot initialize locking ConfigEntry twice");
			}
			lockedConfig = AddConfigEntry<T>(lockingConfig);
			lockingConfig.SettingChanged += delegate
			{
				this.lockedConfigChanged?.Invoke();
			};
			return (SyncedConfigEntry<T>)lockedConfig;
		}

		internal void AddCustomValue(CustomSyncedValueBase customValue)
		{
			if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier))
			{
				throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)");
			}
			allCustomValues.Add(customValue);
			allCustomValues = new HashSet<CustomSyncedValueBase>(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority));
			customValue.ValueChanged += delegate
			{
				if (!ProcessingServerUpdate)
				{
					Broadcast(0L, customValue);
				}
			};
		}

		private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package)
		{
			lockedConfigChanged += serverLockedSettingChanged;
			IsSourceOfTruth = false;
			if (HandleConfigSyncRPC(0L, package, clientUpdate: false))
			{
				InitialSyncDone = true;
			}
		}

		private void RPC_FromOtherClientConfigSync(long sender, ZPackage package)
		{
			HandleConfigSyncRPC(sender, package, clientUpdate: true);
		}

		private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate)
		{
			//IL_0076: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Expected O, but got Unknown
			//IL_0250: Unknown result type (might be due to invalid IL or missing references)
			//IL_0257: Expected O, but got Unknown
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f1: Expected O, but got Unknown
			try
			{
				if (isServer && IsLocked)
				{
					ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc;
					object obj;
					if (currentRpc == null)
					{
						obj = null;
					}
					else
					{
						ISocket socket = currentRpc.GetSocket();
						obj = ((socket != null) ? socket.GetHostName() : null);
					}
					string text = (string)obj;
					if (text != null)
					{
						MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null);
						SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance);
						if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text }))))
						{
							return false;
						}
					}
				}
				cacheExpirations.RemoveAll(delegate(KeyValuePair<long, string> kv)
				{
					if (kv.Key < DateTimeOffset.Now.Ticks)
					{
						configValueCache.Remove(kv.Value);
						return true;
					}
					return false;
				});
				byte b = package.ReadByte();
				if ((b & 2) != 0)
				{
					long num = package.ReadLong();
					string text2 = sender.ToString() + num;
					if (!configValueCache.TryGetValue(text2, out SortedDictionary<int, byte[]> value))
					{
						value = new SortedDictionary<int, byte[]>();
						configValueCache[text2] = value;
						cacheExpirations.Add(new KeyValuePair<long, string>(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2));
					}
					int key = package.ReadInt();
					int num2 = package.ReadInt();
					value.Add(key, package.ReadByteArray());
					if (value.Count < num2)
					{
						return false;
					}
					configValueCache.Remove(text2);
					package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray());
					b = package.ReadByte();
				}
				ProcessingServerUpdate = true;
				if ((b & 4) != 0)
				{
					byte[] buffer = package.ReadByteArray();
					MemoryStream stream = new MemoryStream(buffer);
					MemoryStream memoryStream = new MemoryStream();
					using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress))
					{
						deflateStream.CopyTo(memoryStream);
					}
					package = new ZPackage(memoryStream.ToArray());
					b = package.ReadByte();
				}
				if ((b & 1) == 0)
				{
					resetConfigsFromServer();
				}
				ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package);
				ConfigFile val2 = null;
				bool saveOnConfigSet = false;
				foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues)
				{
					if (!isServer && configValue.Key.LocalBaseValue == null)
					{
						configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue;
					}
					if (val2 == null)
					{
						val2 = configValue.Key.BaseConfig.ConfigFile;
						saveOnConfigSet = val2.SaveOnConfigSet;
						val2.SaveOnConfigSet = false;
					}
					configValue.Key.BaseConfig.BoxedValue = configValue.Value;
				}
				if (val2 != null)
				{
					val2.SaveOnConfigSet = saveOnConfigSet;
				}
				foreach (KeyValuePair<CustomSyncedValueBase, object> customValue in parsedConfigs.customValues)
				{
					if (!isServer)
					{
						CustomSyncedValueBase key2 = customValue.Key;
						if (key2.LocalBaseValue == null)
						{
							key2.LocalBaseValue = customValue.Key.BoxedValue;
						}
					}
					customValue.Key.BoxedValue = customValue.Value;
				}
				Debug.Log((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name));
				if (!isServer)
				{
					serverLockedSettingChanged();
				}
				return true;
			}
			finally
			{
				ProcessingServerUpdate = false;
			}
		}

		private ParsedConfigs ReadConfigsFromPackage(ZPackage package)
		{
			ParsedConfigs parsedConfigs = new ParsedConfigs();
			Dictionary<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c);
			Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c);
			int num = package.ReadInt();
			for (int num2 = 0; num2 < num; num2++)
			{
				string text = package.ReadString();
				string text2 = package.ReadString();
				string text3 = package.ReadString();
				Type type = Type.GetType(text3);
				if (text3 == "" || type != null)
				{
					object obj;
					try
					{
						obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type));
					}
					catch (InvalidDeserializationTypeException ex)
					{
						Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected));
						continue;
					}
					OwnConfigEntryBase value2;
					if (text == "Internal")
					{
						CustomSyncedValueBase value;
						if (text2 == "serverversion")
						{
							if (obj?.ToString() != CurrentVersion)
							{
								Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")));
							}
						}
						else if (text2 == "lockexempt")
						{
							if (obj is bool flag)
							{
								lockExempt = flag;
							}
						}
						else if (dictionary2.TryGetValue(text2, out value))
						{
							if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3)
							{
								parsedConfigs.customValues[value] = obj;
								continue;
							}
							Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName));
						}
					}
					else if (dictionary.TryGetValue(text + "_" + text2, out value2))
					{
						Type type2 = configType(value2.BaseConfig);
						if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3)
						{
							parsedConfigs.configValues[value2] = obj;
							continue;
						}
						Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName));
					}
					else
					{
						Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."));
					}
					continue;
				}
				Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs"));
				return new ParsedConfigs();
			}
			return parsedConfigs;
		}

		private static bool isWritableConfig(OwnConfigEntryBase config)
		{
			ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config));
			if (configSync == null)
			{
				return true;
			}
			return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt));
		}

		private void serverLockedSettingChanged()
		{
			foreach (OwnConfigEntryBase allConfig in allConfigs)
			{
				configAttribute<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig);
			}
		}

		private void resetConfigsFromServer()
		{
			ConfigFile val = null;
			bool saveOnConfigSet = false;
			foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null))
			{
				if (val == null)
				{
					val = item.BaseConfig.ConfigFile;
					saveOnConfigSet = val.SaveOnConfigSet;
					val.SaveOnConfigSet = false;
				}
				item.BaseConfig.BoxedValue = item.LocalBaseValue;
				item.LocalBaseValue = null;
			}
			if (val != null)
			{
				val.SaveOnConfigSet = saveOnConfigSet;
			}
			foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null))
			{
				item2.BoxedValue = item2.LocalBaseValue;
				item2.LocalBaseValue = null;
			}
			lockedConfigChanged -= serverLockedSettingChanged;
			serverLockedSettingChanged();
		}

		private IEnumerator<bool> distributeConfigToPeers(ZNetPeer peer, ZPackage package)
		{
			ZRoutedRpc rpc = ZRoutedRpc.instance;
			if (rpc == null)
			{
				yield break;
			}
			byte[] data = package.GetArray();
			if (data != null && data.LongLength > 250000)
			{
				int fragments = (int)(1 + (data.LongLength - 1) / 250000);
				long packageIdentifier = ++packageCounter;
				int fragment = 0;
				while (fragment < fragments)
				{
					foreach (bool item in waitForQueue())
					{
						yield return item;
					}
					if (peer.m_socket.IsConnected())
					{
						ZPackage fragmentedPackage = new ZPackage();
						fragmentedPackage.Write((byte)2);
						fragmentedPackage.Write(packageIdentifier);
						fragmentedPackage.Write(fragment);
						fragmentedPackage.Write(fragments);
						fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray());
						SendPackage(fragmentedPackage);
						if (fragment != fragments - 1)
						{
							yield return true;
						}
						int num = fragment + 1;
						fragment = num;
						continue;
					}
					break;
				}
				yield break;
			}
			foreach (bool item2 in waitForQueue())
			{
				yield return item2;
			}
			SendPackage(package);
			void SendPackage(ZPackage pkg)
			{
				string text = Name + " ConfigSync";
				if (isServer)
				{
					peer.m_rpc.Invoke(text, new object[1] { pkg });
				}
				else
				{
					rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg });
				}
			}
			IEnumerable<bool> waitForQueue()
			{
				float timeout = Time.time + 30f;
				while (peer.m_socket.GetSendQueueSize() > 20000)
				{
					if (Time.time > timeout)
					{
						Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout");
						peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 });
						ZNet.instance.Disconnect(peer);
						break;
					}
					yield return false;
				}
			}
		}

		private IEnumerator sendZPackage(long target, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				return Enumerable.Empty<object>().GetEnumerator();
			}
			List<ZNetPeer> list = (List<ZNetPeer>)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance);
			if (target != 0)
			{
				list = list.Where((ZNetPeer p) => p.m_uid == target).ToList();
			}
			return sendZPackage(list, package);
		}

		private IEnumerator sendZPackage(List<ZNetPeer> peers, ZPackage package)
		{
			if (!Object.op_Implicit((Object)(object)ZNet.instance))
			{
				yield break;
			}
			byte[] rawData = package.GetArray();
			if (rawData != null && rawData.LongLength > 10000)
			{
				ZPackage compressedPackage = new ZPackage();
				compressedPackage.Write((byte)4);
				MemoryStream output = new MemoryStream();
				using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal))
				{
					deflateStream.Write(rawData, 0, rawData.Length);
				}
				compressedPackage.Write(output.ToArray());
				package = compressedPackage;
			}
			List<IEnumerator<bool>> writers = (from p in peers
				where p.IsReady()
				select distributeConfigToPeers(p, package)).ToList();
			writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			while (writers.Count > 0)
			{
				yield return null;
				writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext());
			}
		}

		private void Broadcast(long target, params ConfigEntryBase[] configs)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(configs);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private void Broadcast(long target, params CustomSyncedValueBase[] customValues)
		{
			if (!IsLocked || isServer)
			{
				ZPackage package = ConfigsToPackage(null, customValues);
				ZNet instance = ZNet.instance;
				if (instance != null)
				{
					((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package));
				}
			}
		}

		private static OwnConfigEntryBase? configData(ConfigEntryBase config)
		{
			return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault();
		}

		public static SyncedConfigEntry<T>? ConfigData<T>(ConfigEntry<T> config)
		{
			return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault();
		}

		private static T configAttribute<T>(ConfigEntryBase config)
		{
			return config.Description.Tags.OfType<T>().First();
		}

		private static Type configType(ConfigEntryBase config)
		{
			return configType(config.SettingType);
		}

		private static Type configType(Type type)
		{
			return type.IsEnum ? Enum.GetUnderlyingType(type) : type;
		}

		private static ZPackage ConfigsToPackage(IEnumerable<ConfigEntryBase>? configs = null, IEnumerable<CustomSyncedValueBase>? customValues = null, IEnumerable<PackageEntry>? packageEntries = null, bool partial = true)
		{
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Expected O, but got Unknown
			List<ConfigEntryBase> list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>();
			List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>();
			ZPackage val = new ZPackage();
			val.Write((byte)(partial ? 1 : 0));
			val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0));
			foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>())
			{
				AddEntryToPackage(val, item);
			}
			foreach (CustomSyncedValueBase item2 in list2)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = "Internal",
					key = item2.Identifier,
					type = item2.Type,
					value = item2.BoxedValue
				});
			}
			foreach (ConfigEntryBase item3 in list)
			{
				AddEntryToPackage(val, new PackageEntry
				{
					section = item3.Definition.Section,
					key = item3.Definition.Key,
					type = configType(item3),
					value = item3.BoxedValue
				});
			}
			return val;
		}

		private static void AddEntryToPackage(ZPackage package, PackageEntry entry)
		{
			package.Write(entry.section);
			package.Write(entry.key);
			package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type));
			AddValueToZPackage(package, entry.value);
		}

		private static string GetZPackageTypeString(Type type)
		{
			return type.AssemblyQualifiedName;
		}

		private static void AddValueToZPackage(ZPackage package, object? value)
		{
			Type type = value?.GetType();
			if (value is Enum)
			{
				value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture);
			}
			else
			{
				if (value is ICollection collection)
				{
					package.Write(collection.Count);
					{
						foreach (object item in collection)
						{
							AddValueToZPackage(package, item);
						}
						return;
					}
				}
				if ((object)type != null && type.IsValueType && !type.IsPrimitive)
				{
					FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
					package.Write(fields.Length);
					FieldInfo[] array = fields;
					foreach (FieldInfo fieldInfo in array)
					{
						package.Write(GetZPackageTypeString(fieldInfo.FieldType));
						AddValueToZPackage(package, fieldInfo.GetValue(value));
					}
					return;
				}
			}
			ZRpc.Serialize(new object[1] { value }, ref package);
		}

		private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type)
		{
			if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum)
			{
				FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
				int num = package.ReadInt();
				if (num != fields.Length)
				{
					throw new InvalidDeserializationTypeException
					{
						received = $"(field count: {num})",
						expected = $"(field count: {fields.Length})"
					};
				}
				object uninitializedObject = FormatterServices.GetUninitializedObject(type);
				FieldInfo[] array = fields;
				foreach (FieldInfo fieldInfo in array)
				{
					string text = package.ReadString();
					if (text != GetZPackageTypeString(fieldInfo.FieldType))
					{
						throw new InvalidDeserializationTypeException
						{
							received = text,
							expected = GetZPackageTypeString(fieldInfo.FieldType),
							field = fieldInfo.Name
						};
					}
					fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType));
				}
				return uninitializedObject;
			}
			if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >))
			{
				int num2 = package.ReadInt();
				IDictionary dictionary = (IDictionary)Activator.CreateInstance(type);
				Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments);
				FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic);
				FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic);
				for (int j = 0; j < num2; j++)
				{
					object obj = ReadValueWithTypeFromZPackage(package, type2);
					dictionary.Add(field.GetValue(obj), field2.GetValue(obj));
				}
				return dictionary;
			}
			if (type != typeof(List<string>) && type.IsGenericType)
			{
				Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]);
				if ((object)type3 != null && type3.IsAssignableFrom(type))
				{
					int num3 = package.ReadInt();
					object obj2 = Activator.CreateInstance(type);
					MethodInfo method = type3.GetMethod("Add");
					for (int k = 0; k < num3; k++)
					{
						method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) });
					}
					return obj2;
				}
			}
			ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo));
			AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type);
			List<object> source = new List<object>();
			ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source);
			return source.First();
		}
	}
	[PublicAPI]
	[HarmonyPatch]
	public class VersionCheck
	{
		private static readonly HashSet<VersionCheck> versionChecks;

		private static readonly Dictionary<string, string> notProcessedNames;

		public string Name;

		private string? displayName;

		private string? currentVersion;

		private string? minimumRequiredVersion;

		public bool ModRequired = true;

		private string? ReceivedCurrentVersion;

		private string? ReceivedMinimumRequiredVersion;

		private readonly List<ZRpc> ValidatedClients = new List<ZRpc>();

		private ConfigSync? ConfigSync;

		public string DisplayName
		{
			get
			{
				return displayName ?? Name;
			}
			set
			{
				displayName = value;
			}
		}

		public string CurrentVersion
		{
			get
			{
				return currentVersion ?? "0.0.0";
			}
			set
			{
				currentVersion = value;
			}
		}

		public string MinimumRequiredVersion
		{
			get
			{
				return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0");
			}
			set
			{
				minimumRequiredVersion = value;
			}
		}

		private static void PatchServerSync()
		{
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null));
			if (patchInfo != null && patchInfo.Postfixes.Count((Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0)
			{
				return;
			}
			Harmony val = new Harmony("org.bepinex.helpers.ServerSync");
			foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) })
				where t.IsClass
				select t)
			{
				val.PatchAll(item);
			}
		}

		static VersionCheck()
		{
			versionChecks = new HashSet<VersionCheck>();
			notProcessedNames = new Dictionary<string, string>();
			typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1]
			{
				new Action(PatchServerSync)
			});
		}

		public VersionCheck(string name)
		{
			Name = name;
			ModRequired = true;
			versionChecks.Add(this);
		}

		public VersionCheck(ConfigSync configSync)
		{
			ConfigSync = configSync;
			Name = ConfigSync.Name;
			versionChecks.Add(this);
		}

		public void Initialize()
		{
			ReceivedCurrentVersion = null;
			ReceivedMinimumRequiredVersion = null;
			if (ConfigSync != null)
			{
				Name = ConfigSync.Name;
				DisplayName = ConfigSync.DisplayName;
				CurrentVersion = ConfigSync.CurrentVersion;
				MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion;
				ModRequired = ConfigSync.ModRequired;
			}
		}

		private bool IsVersionOk()
		{
			if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null)
			{
				return !ModRequired;
			}
			bool flag = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion);
			bool flag2 = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion);
			return flag && flag2;
		}

		private string ErrorClient()
		{
			if (ReceivedMinimumRequiredVersion == null)
			{
				return DisplayName + " is not installed on the server.";
			}
			return (new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)) ? (DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + ".") : (DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". You have version " + CurrentVersion + ".");
		}

		private string ErrorServer(ZRpc rpc)
		{
			return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion;
		}

		private string Error(ZRpc? rpc = null)
		{
			return (rpc == null) ? ErrorClient() : ErrorServer(rpc);
		}

		private static VersionCheck[] GetFailedClient()
		{
			return versionChecks.Where((VersionCheck check) => !check.IsVersionOk()).ToArray();
		}

		private static VersionCheck[] GetFailedServer(ZRpc rpc)
		{
			return versionChecks.Where((VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc)).ToArray();
		}

		private static void Logout()
		{
			Game.instance.Logout(true, true);
			AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3);
		}

		private static void DisconnectClient(ZRpc rpc)
		{
			rpc.Invoke("Error", new object[1] { 3 });
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg)
		{
			CheckVersion(rpc, pkg, null);
		}

		private static void CheckVersion(ZRpc rpc, ZPackage pkg, Action<ZRpc, ZPackage>? original)
		{
			string text = pkg.ReadString();
			string text2 = pkg.ReadString();
			string text3 = pkg.ReadString();
			bool flag = false;
			foreach (VersionCheck versionCheck in versionChecks)
			{
				if (!(text != versionCheck.Name))
				{
					Debug.Log((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + "."));
					versionCheck.ReceivedMinimumRequiredVersion = text2;
					versionCheck.ReceivedCurrentVersion = text3;
					if (ZNet.instance.IsServer() && versionCheck.IsVersionOk())
					{
						versionCheck.ValidatedClients.Add(rpc);
					}
					flag = true;
				}
			}
			if (flag)
			{
				return;
			}
			pkg.SetPos(0);
			if (original != null)
			{
				original(rpc, pkg);
				if (pkg.GetPos() == 0)
				{
					notProcessedNames.Add(text, text3);
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
		[HarmonyPrefix]
		private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance)
		{
			VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient());
			if (array.Length == 0)
			{
				return true;
			}
			VersionCheck[] array2 = array;
			foreach (VersionCheck versionCheck in array2)
			{
				Debug.LogWarning((object)versionCheck.Error(rpc));
			}
			if (__instance.IsServer())
			{
				DisconnectClient(rpc);
			}
			else
			{
				Logout();
			}
			return false;
		}

		[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
		[HarmonyPrefix]
		private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance)
		{
			//IL_018e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0195: Expected O, but got Unknown
			notProcessedNames.Clear();
			IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc);
			if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")))
			{
				object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")];
				Action<ZRpc, ZPackage> action = (Action<ZRpc, ZPackage>)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj);
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)delegate(ZRpc rpc, ZPackage pkg)
				{
					CheckVersion(rpc, pkg, action);
				});
			}
			else
			{
				peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)CheckVersion);
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.Initialize();
				if (versionCheck.ModRequired || __instance.IsServer())
				{
					Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + "."));
					ZPackage val = new ZPackage();
					val.Write(versionCheck.Name);
					val.Write(versionCheck.MinimumRequiredVersion);
					val.Write(versionCheck.CurrentVersion);
					peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val });
				}
			}
		}

		[HarmonyPatch(typeof(ZNet), "Disconnect")]
		[HarmonyPrefix]
		private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance)
		{
			if (!__instance.IsServer())
			{
				return;
			}
			foreach (VersionCheck versionCheck in versionChecks)
			{
				versionCheck.ValidatedClients.Remove(peer.m_rpc);
			}
		}

		[HarmonyPatch(typeof(FejdStartup), "ShowConnectError")]
		[HarmonyPostfix]
		private static void ShowConnectionError(FejdStartup __instance)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0014: Invalid comparison between Unknown and I4
			//IL_0186: Unknown result type (might be due to invalid IL or missing references)
			//IL_018b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0199: Unknown result type (might be due to invalid IL or missing references)
			//IL_01de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_020a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0219: Unknown result type (might be due to invalid IL or missing references)
			//IL_021e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0229: Unknown result type (might be due to invalid IL or missing references)
			if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3)
			{
				return;
			}
			bool flag = false;
			VersionCheck[] failedClient = GetFailedClient();
			if (failedClient.Length != 0)
			{
				string text = string.Join("\n", failedClient.Select((VersionCheck check) => check.Error()));
				TMP_Text connectionFailedError = __instance.m_connectionFailedError;
				connectionFailedError.text = connectionFailedError.text + "\n" + text;
				flag = true;
			}
			foreach (KeyValuePair<string, string> item in notProcessedNames.OrderBy<KeyValuePair<string, string>, string>((KeyValuePair<string, string> kv) => kv.Key))
			{
				if (!__instance.m_connectionFailedError.text.Contains(item.Key))
				{
					TMP_Text connectionFailedError2 = __instance.m_connectionFailedError;
					connectionFailedError2.text = connectionFailedError2.text + "\nServer expects you to have " + item.Key + " (Version: " + item.Value + ") installed.";
					flag = true;
				}
			}
			if (flag)
			{
				RectTransform component = ((Component)__instance.m_connectionFailedPanel.transform.Find("Image")).GetComponent<RectTransform>();
				Vector2 sizeDelta = component.sizeDelta;
				sizeDelta.x = 675f;
				component.sizeDelta = sizeDelta;
				__instance.m_connectionFailedError.ForceMeshUpdate(false, false);
				float num = __instance.m_connectionFailedError.renderedHeight + 105f;
				RectTransform component2 = ((Component)((Component)component).transform.Find("ButtonOk")).GetComponent<RectTransform>();
				component2.anchoredPosition = new Vector2(component2.anchoredPosition.x, component2.anchoredPosition.y - (num - component.sizeDelta.y) / 2f);
				sizeDelta = component.sizeDelta;
				sizeDelta.y = num;
				component.sizeDelta = sizeDelta;
			}
		}
	}
}