Decompiled source of World v1.0.1

meadworks.world.dll

Decompiled 28 minutes 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.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using BepInEx;
using BepInEx.Configuration;
using HarmonyLib;
using MagicaCloth2;
using MeadWorks.Core;
using MeadWorks.UI;
using Microsoft.CodeAnalysis;
using Newtonsoft.Json;
using Steamworks;
using TMPro;
using UnityEngine;
using UnityEngine.Audio;
using UnityEngine.Experimental.Rendering;
using UnityEngine.Rendering;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("assembly_guiutils")]
[assembly: IgnoresAccessChecksTo("assembly_utils")]
[assembly: IgnoresAccessChecksTo("assembly_valheim")]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("expDARE")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyCopyright("Copyright (c) 2026 expDARE")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1")]
[assembly: AssemblyProduct("meadworks.world")]
[assembly: AssemblyTitle("meadworks.world")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.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.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace MeadWorks.World
{
	public static class AltarInventoryRules
	{
		public static bool FindOffering(bool enabled, bool hold, bool stands, bool hasOffering)
		{
			return enabled && !hold && !stands && hasOffering;
		}
	}
	internal static class AltarInventory
	{
		[HarmonyPatch(typeof(OfferingBowl), "Interact")]
		private static class Patches
		{
			[HarmonyPrefix]
			private static bool Interact(OfferingBowl __instance, Humanoid user, bool hold, ref bool __result, bool __runOriginal = true)
			{
				if (!__runOriginal)
				{
					return false;
				}
				if ((Object)(object)__instance == (Object)null || (Object)(object)user == (Object)null || user.GetInventory() == null || (Object)(object)__instance.m_bossItem == (Object)null || __instance.m_bossItem.m_itemData?.m_shared == null)
				{
					return true;
				}
				if (!AltarInventoryRules.FindOffering(_live, hold, __instance.m_useItemStands, (Object)(object)__instance.m_bossItem != (Object)null) || (Object)(object)user == (Object)null)
				{
					return true;
				}
				ItemData item = user.GetInventory().GetItem(__instance.m_bossItem.m_itemData.m_shared.m_name, -1, false);
				if (item == null)
				{
					return true;
				}
				__result = __instance.UseItem(user, item);
				return false;
			}
		}

		[HarmonyPatch(typeof(OfferingBowl), "GetHoverText")]
		private static class HoverPatch
		{
			[HarmonyPostfix]
			private static void GetHoverText(OfferingBowl __instance, ref string __result)
			{
				if (_live && !((Object)(object)__instance == (Object)null) && !__instance.m_useItemStands && !((Object)(object)__instance.m_bossItem == (Object)null) && Localization.instance != null)
				{
					__result = Localization.instance.Localize(__instance.m_name + "\n[<color=yellow><b>$KEY_Use</b></color>] " + __instance.m_useItemText);
				}
			}
		}

		private static bool _live;

		public static void Init()
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Expected O, but got Unknown
			_live = true;
			Harmony val = new Harmony("expdare.meadworks.world.altarinventory");
			val.PatchAll(typeof(Patches));
			val.PatchAll(typeof(HoverPatch));
			LedgerTrack.Patch(val, "world altar inventory");
			Ledger.Add("world altar inventory state", (Action)delegate
			{
				_live = false;
			});
		}
	}
	internal static class ArrivalScene
	{
		private static class Patches
		{
			[HarmonyPatch(typeof(ZNetScene), "CreateObjects")]
			[HarmonyPrefix]
			private static void Begin(ZNetScene __instance)
			{
				_started = (_budget = 0L);
				_attempted = false;
				float num = _milliseconds?.Value ?? 0f;
				if (num > 0f && !((Object)(object)ZNet.instance == (Object)null) && !ZNet.instance.IsDedicated() && __instance.InLoadingScreen())
				{
					_budget = ArrivalSceneRules.BudgetTicks(num, Stopwatch.Frequency);
				}
			}

			[HarmonyPatch(typeof(ZNetScene), "CreateObjects")]
			[HarmonyFinalizer]
			private static void End()
			{
				_budget = 0L;
			}

			[HarmonyPatch(typeof(ZNetScene), "CreateObjectsSorted")]
			[HarmonyTranspiler]
			private static IEnumerable<CodeInstruction> BudgetNear(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
			{
				return BudgetCreation(instructions, generator);
			}

			[HarmonyPatch(typeof(ZNetScene), "CreateDistantObjects")]
			[HarmonyTranspiler]
			private static IEnumerable<CodeInstruction> BudgetDistant(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
			{
				return BudgetCreation(instructions, generator);
			}

			private static IEnumerable<CodeInstruction> BudgetCreation(IEnumerable<CodeInstruction> instructions, ILGenerator generator)
			{
				//IL_012b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0132: Expected O, but got Unknown
				//IL_017c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0182: Expected O, but got Unknown
				//IL_0190: Unknown result type (might be due to invalid IL or missing references)
				//IL_0196: Expected O, but got Unknown
				List<CodeInstruction> list = instructions.ToList();
				MethodInfo create = AccessTools.Method(typeof(ZNetScene), "CreateObject", (Type[])null, (Type[])null);
				MethodInfo methodInfo = AccessTools.Method(typeof(ArrivalScene), "AllowNext", (Type[])null, (Type[])null);
				int num = list.FindIndex((CodeInstruction i) => CodeInstructionExtensions.Calls(i, create));
				if (num < 2 || list.Count((CodeInstruction i) => CodeInstructionExtensions.Calls(i, create)) != 1 || list[num - 2].opcode != OpCodes.Ldarg_0 || list[num - 2].blocks.Count != 0 || list[num - 1].labels.Count != 0 || list[num].labels.Count != 0 || list[list.Count - 1].opcode != OpCodes.Ret)
				{
					throw new InvalidOperationException("Scene object creation loop changed");
				}
				Label label = generator.DefineLabel();
				list[list.Count - 1].labels.Add(label);
				CodeInstruction val = list[num - 2];
				Label label2 = generator.DefineLabel();
				CodeInstruction val2 = new CodeInstruction(OpCodes.Call, (object)methodInfo);
				val2.labels.AddRange(val.labels);
				val.labels.Clear();
				val.labels.Add(label2);
				list.InsertRange(num - 2, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[3]
				{
					val2,
					new CodeInstruction(OpCodes.Brtrue, (object)label2),
					new CodeInstruction(OpCodes.Leave, (object)label)
				});
				return list;
			}
		}

		private static Setting<float> _milliseconds;

		private static long _started;

		private static long _budget;

		private static bool _attempted;

		internal static void Init(SettingsPage page)
		{
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Expected O, but got Unknown
			_milliseconds = page.Slider("arrival_scene_budget", "Arrival object budget (ms)", 0f, 0f, 8f, 0.5f, (SettingPolicy)0, true);
			page.LabelZero(_milliseconds, "Native");
			Ledger.Add("world arrival scene state", (Action)delegate
			{
				_milliseconds = null;
				_budget = 0L;
			});
			Harmony val = new Harmony("expdare.meadworks.world.arrivalscene");
			LedgerTrack.Patch(val, "world arrival scene");
			try
			{
				val.PatchAll(typeof(Patches));
			}
			catch (Exception ex)
			{
				val.UnpatchSelf();
				MwLog.Warn((object)("Arrival object budget unavailable: " + ex.GetBaseException().Message));
			}
		}

		private static bool AllowNext()
		{
			if (_budget == 0L)
			{
				return true;
			}
			if (!_attempted)
			{
				_started = Stopwatch.GetTimestamp();
			}
			if (!ArrivalSceneRules.MayCreate(_budget, Stopwatch.GetTimestamp() - _started, _attempted))
			{
				return false;
			}
			_attempted = true;
			return true;
		}
	}
	public static class ArrivalSceneRules
	{
		public static long BudgetTicks(float milliseconds, long frequency)
		{
			if (!(milliseconds > 0f))
			{
				return 0L;
			}
			return Math.Max(1L, (long)((double)Math.Min(milliseconds, 8f) * ((double)frequency / 1000.0)));
		}

		public static bool MayCreate(long budget, long elapsed, bool attempted)
		{
			if (budget > 0 && attempted)
			{
				return elapsed < budget;
			}
			return true;
		}
	}
	public enum AuraKind
	{
		Move,
		Run,
		Poison,
		Frost,
		FireDamage,
		Stamina,
		Fire,
		Carry,
		Health
	}
	public sealed class AuraDef
	{
		public readonly string Trophy;

		public readonly string Name;

		public readonly AuraKind Kind;

		public readonly float Strength;

		public AuraDef(string trophy, string name, AuraKind kind, float strength)
		{
			Trophy = trophy;
			Name = name;
			Kind = kind;
			Strength = strength;
		}
	}
	public static class AuraRules
	{
		public static readonly IReadOnlyList<AuraDef> Table = Array.AsReadOnly(new AuraDef[15]
		{
			new AuraDef("TrophyEikthyr", "Eikthyr's stride", AuraKind.Run, 0.05f),
			new AuraDef("TrophyBonemass", "Bonemass's ward", AuraKind.Poison, 1f),
			new AuraDef("TrophyDragonQueen", "Moder's shelter", AuraKind.Frost, 1f),
			new AuraDef("TrophyGoblinKing", "Yagluth's embers", AuraKind.FireDamage, 0.05f),
			new AuraDef("TrophySeekerQueen", "Queen's resolve", AuraKind.Stamina, 0.1f),
			new AuraDef("TrophyFader", "Fader's ward", AuraKind.Fire, 1f),
			new AuraDef("TrophyDeer", "Deer's grace", AuraKind.Move, 0.05f),
			new AuraDef("TrophyBoar", "Boar's vigor", AuraKind.Health, 0.05f),
			new AuraDef("TrophyNeck", "Neck's vigor", AuraKind.Stamina, 0.03f),
			new AuraDef("TrophyGreydwarf", "Forest vigor", AuraKind.Stamina, 0.05f),
			new AuraDef("TrophyForestTroll", "Troll's burden", AuraKind.Carry, 0.05f),
			new AuraDef("TrophyDraugr", "Swamp vigor", AuraKind.Health, 0.07f),
			new AuraDef("TrophyWolf", "Wolf's stride", AuraKind.Run, 0.03f),
			new AuraDef("TrophyLox", "Lox's burden", AuraKind.Carry, 0.07f),
			new AuraDef("TrophySeeker", "Seeker's resolve", AuraKind.Stamina, 0.07f)
		});

		public static AuraDef[] Select(IEnumerable<string> trophies)
		{
			return (from t in trophies ?? Array.Empty<string>()
				select Table.FirstOrDefault((AuraDef d) => d.Trophy == t) into d
				where d != null
				group d by d.Kind into g
				select g.OrderByDescending((AuraDef d) => d.Strength).ThenBy<AuraDef, string>((AuraDef d) => d.Trophy, StringComparer.Ordinal).First() into d
				orderby d.Strength descending
				select d).ThenBy<AuraDef, string>((AuraDef d) => d.Trophy, StringComparer.Ordinal).Take(3).ToArray();
		}

		public static bool InRange(float squaredDistance, float radius)
		{
			if (radius > 0f && squaredDistance >= 0f)
			{
				return squaredDistance <= radius * radius;
			}
			return false;
		}

		public static string Shown(AuraDef def)
		{
			return Lang.Derived("world.aura." + def.Trophy.ToLowerInvariant(), def.Name);
		}

		public static string Tooltip(AuraDef def)
		{
			string text = (def.Strength * 100f).ToString("0", CultureInfo.InvariantCulture) + "%";
			return def.Kind switch
			{
				AuraKind.Move => Lang.T("world.aura_move_speed", "Move speed +{0}", new object[1] { text }), 
				AuraKind.Run => Lang.T("world.aura_run_speed", "Run speed +{0}", new object[1] { text }), 
				AuraKind.Stamina => Lang.T("world.aura_stamina_regeneration", "Stamina regeneration +{0}", new object[1] { text }), 
				AuraKind.Health => Lang.T("world.aura_health_regeneration", "Health regeneration +{0}", new object[1] { text }), 
				AuraKind.FireDamage => Lang.T("world.aura_fire_damage", "Fire damage +{0}", new object[1] { text }), 
				AuraKind.Carry => Lang.T("world.aura_carry_weight", "Carry weight +{0}", new object[1] { (300f * def.Strength).ToString("0", CultureInfo.InvariantCulture) }), 
				AuraKind.Poison => Lang.T("world.poison_resistance", "Poison resistance"), 
				AuraKind.Frost => Lang.T("world.frost_resistance", "Frost resistance"), 
				AuraKind.Fire => Lang.T("world.fire_resistance", "Fire resistance"), 
				_ => "", 
			};
		}
	}
	public static class BedClaimRules
	{
		public static bool NeedsExposure(bool enabled, bool serverSupports, bool claiming)
		{
			if (enabled && serverSupports)
			{
				return !claiming;
			}
			return true;
		}

		public static int[] ClaimExposureIndexes(int count)
		{
			if (count != 3)
			{
				return null;
			}
			return new int[2] { 0, 2 };
		}
	}
	internal static class BedRespawn
	{
		private static class Patches
		{
			[HarmonyPatch(typeof(Game), "FindSpawnPoint")]
			[HarmonyPrefix]
			private static void Begin(Game __instance, out float __state)
			{
				//IL_0029: Unknown result type (might be due to invalid IL or missing references)
				//IL_002f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0034: Unknown result type (might be due to invalid IL or missing references)
				//IL_0039: Unknown result type (might be due to invalid IL or missing references)
				__state = __instance.m_respawnLoadDuration;
				PlayerProfile playerProfile = __instance.m_playerProfile;
				if (playerProfile != null && playerProfile.HaveDeathPoint())
				{
					bool respawnAfterDeath = __instance.m_respawnAfterDeath;
					bool hasBed = playerProfile.HaveCustomSpawnPoint();
					Vector3 val = playerProfile.GetCustomSpawnPoint() - playerProfile.GetDeathPoint();
					__instance.m_respawnLoadDuration = BedRespawnRules.Delay(respawnAfterDeath, hasBed, ((Vector3)(ref val)).sqrMagnitude, __state);
				}
			}

			[HarmonyPatch(typeof(Game), "FindSpawnPoint")]
			[HarmonyFinalizer]
			private static void End(Game __instance, float __state)
			{
				__instance.m_respawnLoadDuration = __state;
			}
		}

		public static void Init()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			Harmony val = new Harmony("expdare.meadworks.world.bedrespawn");
			LedgerTrack.Patch(val, "world nearby bed respawn");
			val.PatchAll(typeof(Patches));
		}
	}
	public static class BedRespawnRules
	{
		public static float Delay(bool afterDeath, bool hasBed, float distanceSquared, float native)
		{
			if (!(afterDeath && hasBed) || !(distanceSquared >= 0f) || !(distanceSquared <= 16384f))
			{
				return native;
			}
			return Math.Min(native, 2f);
		}
	}
	public static class BiomeWeatherRules
	{
		public static readonly int[] Biomes = new int[9] { 1, 2, 4, 8, 16, 32, 64, 256, 512 };

		public const int MaxPackedLength = 2048;

		public static bool KnownBiome(int biome)
		{
			return Array.IndexOf(Biomes, biome) >= 0;
		}

		public static void Collect(HashSet<int> biomes, int biome)
		{
			if (biomes != null && KnownBiome(biome))
			{
				biomes.Add(biome);
			}
		}

		public static bool IsWeatherKey(string name)
		{
			if (name != null)
			{
				if (!string.Equals(name, "MWWeather", StringComparison.OrdinalIgnoreCase))
				{
					return name.StartsWith("MWWeather ", StringComparison.OrdinalIgnoreCase);
				}
				return true;
			}
			return false;
		}

		public static WeatherRules.State At(IDictionary<int, WeatherRules.State> states, int biome)
		{
			if (states == null || !states.TryGetValue(biome, out var value))
			{
				return default(WeatherRules.State);
			}
			return value;
		}

		public static string Pack(IDictionary<int, WeatherRules.State> states)
		{
			return "v2;" + string.Join(";", from p in states
				orderby p.Key
				select p.Key.ToString(CultureInfo.InvariantCulture) + "=" + WeatherRules.Pack(p.Value));
		}

		public static bool TryUnpack(string raw, out Dictionary<int, WeatherRules.State> states)
		{
			states = new Dictionary<int, WeatherRules.State>();
			if (string.IsNullOrEmpty(raw))
			{
				return true;
			}
			if (raw.Length > 2048 || !raw.StartsWith("v2;", StringComparison.OrdinalIgnoreCase))
			{
				return false;
			}
			if (raw.Length == 3)
			{
				return true;
			}
			string[] array = raw.Substring(3).Split(new char[1] { ';' });
			if (array.Length > Biomes.Length)
			{
				return false;
			}
			string[] array2 = array;
			foreach (string text in array2)
			{
				int num = text.IndexOf('=');
				if (num <= 0 || !int.TryParse(text.Substring(0, num), NumberStyles.None, CultureInfo.InvariantCulture, out var result) || !KnownBiome(result) || states.ContainsKey(result))
				{
					return false;
				}
				string text2 = text.Substring(num + 1);
				WeatherRules.State state = WeatherRules.Unpack(text2, WeatherRules.KnownId);
				if (!string.Equals(WeatherRules.Pack(state), text2, StringComparison.OrdinalIgnoreCase))
				{
					return false;
				}
				if (!Allows(state.Id, result) || !Allows(state.WarnId, result) || !Allows(state.NextId, result))
				{
					return false;
				}
				states.Add(result, state);
			}
			return true;
		}

		private static bool Allows(string id, int biome)
		{
			if (!string.IsNullOrEmpty(id))
			{
				return WeatherCatalog.Find(id)?.AllowsBiome(biome) ?? false;
			}
			return true;
		}
	}
	public static class CleanupStutterRules
	{
		public const int DefaultBudget = 25;

		public static bool ShouldGuard(bool enabled, bool isServer)
		{
			if (enabled)
			{
				return !isServer;
			}
			return false;
		}

		public static bool ShouldDestroyZDO(bool persistent, bool isOwner)
		{
			return !persistent && isOwner;
		}

		public static int Batch(int queued, int budget, bool loadingScreen)
		{
			if (queued <= 0)
			{
				return 0;
			}
			if (loadingScreen || budget <= 0)
			{
				return queued;
			}
			if (queued >= budget)
			{
				return budget;
			}
			return queued;
		}
	}
	internal static class CleanupStutterGuard
	{
		private sealed class Worker : MonoBehaviour
		{
			private void Update()
			{
				if (Queue.Count != 0)
				{
					if ((Object)(object)ZNet.instance == (Object)null || (Object)(object)ZNetScene.instance == (Object)null)
					{
						Queue.Clear();
					}
					else
					{
						Drain();
					}
				}
			}
		}

		private static class Patches
		{
			[HarmonyPatch(typeof(ZNetScene), "RemoveObjects")]
			[HarmonyPrefix]
			private static bool RemoveObjects(ZNetScene __instance, List<ZDO> currentNearObjects, List<ZDO> currentDistantObjects, bool __runOriginal = true)
			{
				if (!__runOriginal)
				{
					return false;
				}
				if ((Object)(object)ZNet.instance == (Object)null || !CleanupStutterRules.ShouldGuard(Enabled, ZNet.instance.IsServer()))
				{
					return true;
				}
				Dictionary<ZDO, ZNetView> instances = __instance.m_instances;
				if (instances == null)
				{
					return true;
				}
				byte b = (byte)(Time.frameCount & 0xFF);
				for (int i = 0; i < currentNearObjects.Count; i++)
				{
					currentNearObjects[i].TempRemoveEarmark = b;
				}
				for (int j = 0; j < currentDistantObjects.Count; j++)
				{
					currentDistantObjects[j].TempRemoveEarmark = b;
				}
				Removed.Clear();
				foreach (ZNetView value in instances.Values)
				{
					ZDO val = (((Object)(object)value != (Object)null) ? value.GetZDO() : null);
					if (val != null && val.TempRemoveEarmark != b)
					{
						Removed.Add(value);
					}
				}
				for (int k = 0; k < Removed.Count; k++)
				{
					ZNetView obj = Removed[k];
					ZDO zDO = obj.GetZDO();
					obj.ResetZDO();
					if (CleanupStutterRules.ShouldDestroyZDO(zDO.Persistent, zDO.IsOwner()) && ZDOMan.instance != null)
					{
						ZDOMan.instance.DestroyZDO(zDO);
					}
					instances.Remove(zDO);
					Enqueue(((Component)obj).gameObject);
				}
				Removed.Clear();
				return false;
			}

			[HarmonyPatch(typeof(ZNetScene), "Shutdown")]
			[HarmonyPostfix]
			private static void Shutdown()
			{
				Flush();
			}
		}

		private static bool _on;

		private static Harmony _harmony;

		private static readonly List<GameObject> Queue = new List<GameObject>();

		private static readonly List<ZNetView> Removed = new List<ZNetView>();

		private static int _deferred;

		private static int _destroyed;

		public static bool Enabled => _on;

		public static int Budget => 25;

		public static bool Active
		{
			get
			{
				if ((Object)(object)ZNet.instance != (Object)null)
				{
					return CleanupStutterRules.ShouldGuard(Enabled, ZNet.instance.IsServer());
				}
				return false;
			}
		}

		public static void Init()
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Expected O, but got Unknown
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0048: Expected O, but got Unknown
			//IL_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Expected O, but got Unknown
			_on = true;
			_harmony = new Harmony("expdare.meadworks.world.cleanupstutterguard");
			_harmony.PatchAll(typeof(Patches));
			LedgerTrack.Patch(_harmony, "world cleanup stutter guard");
			GameObject val = new GameObject("MeadWorks.CleanupStutterGuard");
			Object.DontDestroyOnLoad((Object)val);
			val.AddComponent<Worker>();
			LedgerTrack.Object<GameObject>(val, "world cleanup stutter guard worker");
			Ledger.Add("world cleanup stutter guard state", (Action)delegate
			{
				_on = false;
				Flush();
				Queue.Clear();
				Removed.Clear();
				_deferred = 0;
				_destroyed = 0;
			});
		}

		public static string Status()
		{
			return "cleanup active=" + Active + " on=" + Enabled + " budget=" + Budget + " queued=" + Queue.Count + " deferred=" + _deferred + " destroyed=" + _destroyed;
		}

		private static void Enqueue(GameObject go)
		{
			if (!((Object)(object)go == (Object)null))
			{
				go.SetActive(false);
				Queue.Add(go);
				_deferred++;
			}
		}

		public static void Flush()
		{
			for (int i = 0; i < Queue.Count; i++)
			{
				GameObject val = Queue[i];
				if ((Object)(object)val != (Object)null)
				{
					Object.Destroy((Object)(object)val);
					_destroyed++;
				}
			}
			Queue.Clear();
		}

		private static bool LoadingScreen()
		{
			Player localPlayer = Player.m_localPlayer;
			if (!((Object)(object)localPlayer == (Object)null))
			{
				return ((Character)localPlayer).IsTeleporting();
			}
			return true;
		}

		private static void Drain()
		{
			int num = CleanupStutterRules.Batch(Queue.Count, Budget, LoadingScreen());
			for (int i = 0; i < num; i++)
			{
				GameObject val = Queue[i];
				if ((Object)(object)val != (Object)null)
				{
					Object.Destroy((Object)(object)val);
					_destroyed++;
				}
			}
			if (num > 0)
			{
				Queue.RemoveRange(0, num);
			}
		}
	}
	public static class ColdRules
	{
		public enum Kind
		{
			None,
			Soften,
			ForceCold,
			FreezeAtNight,
			Freeze
		}

		public static Kind FromMult(float coldMult)
		{
			if (coldMult < 0.99f)
			{
				return Kind.Soften;
			}
			if (coldMult >= 2.5f)
			{
				return Kind.Freeze;
			}
			if (coldMult >= 1.5f)
			{
				return Kind.FreezeAtNight;
			}
			if (coldMult > 1.01f)
			{
				return Kind.ForceCold;
			}
			return Kind.None;
		}

		public static int ShiftAfter(WeatherRules.State state, double now, int biome)
		{
			return (int)ForDisplayed(WeatherRules.Active(state, now) ? state.Id : "", biome, effectsOn: true);
		}

		public static Kind ForDisplayed(string activeId, int biome, bool effectsOn)
		{
			if (!effectsOn)
			{
				return Kind.None;
			}
			if (!WeatherCatalog.TryGet(WeatherRules.Displayed(effectsOn: true, activeId, biome), out var def))
			{
				return Kind.None;
			}
			return FromMult(def.ColdMult);
		}

		public static void ApplyHost(int hostKind, bool nativeCold, bool nativeFreezing, bool seasonCold, bool seasonFreezing, bool night, bool outdoors, bool plainServer, out bool cold, out bool freezing)
		{
			if (plainServer)
			{
				cold = nativeCold;
				freezing = nativeFreezing;
			}
			else
			{
				Kind hostKind2 = ((hostKind == 1 || hostKind == 2 || hostKind == 3 || hostKind == 4) ? ((Kind)hostKind) : Kind.None);
				Apply(nativeCold, nativeFreezing, seasonCold, seasonFreezing, night, hostKind2, outdoors, out cold, out freezing);
			}
		}

		public static void Apply(bool nativeCold, bool nativeFreezing, bool seasonCold, bool seasonFreezing, bool night, Kind hostKind, bool outdoors, out bool cold, out bool freezing)
		{
			if (!outdoors)
			{
				cold = nativeCold;
				freezing = nativeFreezing;
				return;
			}
			cold = nativeCold || seasonCold;
			freezing = nativeFreezing || seasonFreezing;
			switch (hostKind)
			{
			case Kind.Soften:
				if (freezing)
				{
					freezing = false;
					cold = true;
				}
				else
				{
					cold = false;
				}
				break;
			case Kind.ForceCold:
				cold = true;
				break;
			case Kind.FreezeAtNight:
				cold = true;
				if (night)
				{
					freezing = true;
				}
				break;
			case Kind.Freeze:
				cold = true;
				freezing = true;
				break;
			}
		}
	}
	public static class CompressionPacketRules
	{
		public static int Method(byte[] bytes)
		{
			if (bytes == null || bytes.Length < 4)
			{
				return 0;
			}
			return bytes[0] | (bytes[1] << 8) | (bytes[2] << 16) | (bytes[3] << 24);
		}

		public static bool Reserved(byte[] bytes, int envelope, int offer, int ready)
		{
			int num = Method(bytes);
			if (num != envelope && num != offer)
			{
				return num == ready;
			}
			return true;
		}

		public static bool TryWrap(NegotiatedCompressionRules.Peer peer, byte[] bytes, int threshold, int envelope, int offer, int ready, out byte[] wire)
		{
			wire = null;
			if (bytes == null || bytes.Length < 4 || Reserved(bytes, envelope, offer, ready))
			{
				return false;
			}
			if (!NegotiatedCompressionRules.TryEncode(peer, bytes, threshold, out var frame, 4))
			{
				return false;
			}
			wire = new byte[frame.Length + 4];
			wire[0] = (byte)envelope;
			wire[1] = (byte)(envelope >> 8);
			wire[2] = (byte)(envelope >> 16);
			wire[3] = (byte)(envelope >> 24);
			Buffer.BlockCopy(frame, 0, wire, 4, frame.Length);
			return true;
		}

		public static bool TryUnwrap(NegotiatedCompressionRules.Peer peer, byte[] wire, int envelope, int offer, int ready, out byte[] bytes, double nowSeconds = 0.0)
		{
			string reason;
			return TryUnwrap(peer, wire, envelope, offer, ready, out bytes, out reason, nowSeconds);
		}

		public static bool TryUnwrap(NegotiatedCompressionRules.Peer peer, byte[] wire, int envelope, int offer, int ready, out byte[] bytes, out string reason, double nowSeconds = 0.0)
		{
			bytes = null;
			reason = "invalid envelope size or method";
			if (wire == null || wire.Length < 4 || wire.Length > 1048580 || Method(wire) != envelope)
			{
				return false;
			}
			byte[] array = new byte[wire.Length - 4];
			Buffer.BlockCopy(wire, 4, array, 0, array.Length);
			if (!NegotiatedCompressionRules.TryDecode(peer, array, out var package, out reason, nowSeconds))
			{
				return false;
			}
			reason = "invalid inner RPC length or reserved method";
			if (package.Length < 4 || Reserved(package, envelope, offer, ready))
			{
				return false;
			}
			bytes = package;
			reason = null;
			return true;
		}
	}
	public sealed class CompressionSession
	{
		public enum Inbound
		{
			Pass,
			Decoded,
			Consumed,
			Dropped,
			Closed
		}

		private readonly NegotiatedCompressionRules.Peer _peer;

		private readonly int _envelope;

		private readonly int _offer;

		private readonly int _ready;

		private readonly Action<byte[]> _control;

		private readonly Action<string> _close;

		public bool Accepted { get; private set; }

		public bool Failed { get; private set; }

		public bool Closed { get; private set; }

		public bool CanSend
		{
			get
			{
				if (Accepted)
				{
					return _peer.CanSend;
				}
				return false;
			}
		}

		public bool CanReceive
		{
			get
			{
				if (Accepted)
				{
					return _peer.CanReceive;
				}
				return false;
			}
		}

		public CompressionSession(bool enabled, bool steamSocket, int envelope, int offer, int ready, Action<byte[]> control, Action<string> close = null)
		{
			_peer = new NegotiatedCompressionRules.Peer(enabled, steamSocket);
			_envelope = envelope;
			_offer = offer;
			_ready = ready;
			_control = control;
			_close = close;
		}

		public bool CanRead(double nowSeconds)
		{
			if (!Closed)
			{
				if (CanReceive)
				{
					return _peer.HasDecodedBytes(1048576, nowSeconds);
				}
				return true;
			}
			return false;
		}

		public bool Reserved(int method)
		{
			if (method != _envelope && method != _offer)
			{
				return method == _ready;
			}
			return true;
		}

		public void Accept()
		{
			if (!Accepted)
			{
				Accepted = true;
				if (_peer.TryOffer())
				{
					Control(_offer, 1);
				}
				if (_peer.TryReady())
				{
					Control(_ready, 1);
				}
			}
		}

		public Inbound Receive(byte[] wire, double nowSeconds, out byte[] package)
		{
			package = null;
			if (Closed)
			{
				return Inbound.Closed;
			}
			if (wire == null || wire.Length < 4)
			{
				return Inbound.Pass;
			}
			int num = CompressionPacketRules.Method(wire);
			if (num == _envelope)
			{
				string reason = "data frame before login acceptance";
				if (Accepted && CompressionPacketRules.TryUnwrap(_peer, wire, _envelope, _offer, _ready, out var bytes, out reason, nowSeconds))
				{
					package = bytes;
					return Inbound.Decoded;
				}
				Close(reason);
				return Inbound.Closed;
			}
			if (num != _offer && num != _ready)
			{
				return Inbound.Pass;
			}
			if (wire.Length != 8)
			{
				Fail();
				return Inbound.Dropped;
			}
			int version = wire[4] | (wire[5] << 8) | (wire[6] << 16) | (wire[7] << 24);
			if (num == _offer)
			{
				_peer.ReceiveOffer(version, enabled: true);
				if (Accepted && _peer.TryReady())
				{
					Control(_ready, 1);
				}
			}
			else
			{
				_peer.ReceiveReady(version);
			}
			return Inbound.Consumed;
		}

		public bool Send(byte[] package, int threshold, out byte[] wire)
		{
			wire = null;
			if (CanSend)
			{
				return CompressionPacketRules.TryWrap(_peer, package, threshold, _envelope, _offer, _ready, out wire);
			}
			return false;
		}

		public void Withdraw()
		{
			_peer.StopSending();
			if (Accepted && !Closed)
			{
				Control(_offer, 0);
			}
		}

		public void Fail()
		{
			if (!Failed)
			{
				Failed = true;
				Withdraw();
			}
		}

		public void Close(string reason)
		{
			if (!Closed)
			{
				Closed = true;
				Failed = true;
				_peer.StopSending();
				if (_close != null)
				{
					_close(reason);
				}
			}
		}

		private void Control(int method, int version)
		{
			if (_control != null)
			{
				_control(new byte[8]
				{
					(byte)method,
					(byte)(method >> 8),
					(byte)(method >> 16),
					(byte)(method >> 24),
					(byte)version,
					(byte)(version >> 8),
					(byte)(version >> 16),
					(byte)(version >> 24)
				});
			}
		}
	}
	public sealed class CompressionTable<TSocket, TRpc> where TSocket : class where TRpc : class
	{
		private readonly Dictionary<TSocket, CompressionSession> _bySocket = new Dictionary<TSocket, CompressionSession>();

		private readonly Dictionary<TRpc, KeyValuePair<TSocket, CompressionSession>> _byRpc = new Dictionary<TRpc, KeyValuePair<TSocket, CompressionSession>>();

		public int Count => _byRpc.Count;

		public IEnumerable<KeyValuePair<TSocket, CompressionSession>> Entries => _byRpc.Values;

		public void Add(TSocket socket, TRpc rpc, CompressionSession session)
		{
			if (socket != null && rpc != null && session != null)
			{
				Remove(rpc);
				_bySocket[socket] = session;
				_byRpc[rpc] = new KeyValuePair<TSocket, CompressionSession>(socket, session);
			}
		}

		public CompressionSession BySocket(TSocket socket)
		{
			if (socket == null || !_bySocket.TryGetValue(socket, out var value))
			{
				return null;
			}
			return value;
		}

		public CompressionSession ByRpc(TRpc rpc)
		{
			if (rpc == null || !_byRpc.TryGetValue(rpc, out var value))
			{
				return null;
			}
			return value.Value;
		}

		public void Remove(TRpc rpc)
		{
			if (rpc != null && _byRpc.TryGetValue(rpc, out var value))
			{
				_byRpc.Remove(rpc);
				if (_bySocket.TryGetValue(value.Key, out var value2) && value2 == value.Value)
				{
					_bySocket.Remove(value.Key);
				}
			}
		}

		public void WithdrawAll()
		{
			foreach (KeyValuePair<TSocket, CompressionSession> entry in Entries)
			{
				if (!entry.Value.Failed)
				{
					entry.Value.Withdraw();
				}
			}
		}

		public void Clear()
		{
			_bySocket.Clear();
			_byRpc.Clear();
		}
	}
	public static class DisconnectedOwnershipRules
	{
		public enum Plan
		{
			None,
			Free,
			ClearUse
		}

		public const int BatchPerFrame = 250;

		public static bool ShouldHandle(bool enabled, bool isServer, long sessionId, long goneUid)
		{
			if (enabled && isServer && goneUid != 0L)
			{
				return goneUid != sessionId;
			}
			return false;
		}

		public static bool IsGoneOwned(long goneUid, long owner)
		{
			if (goneUid != 0L)
			{
				return owner == goneUid;
			}
			return false;
		}

		public static bool InUseLeft(int inUse)
		{
			return inUse == 1;
		}

		public static Plan PlanFor(long goneUid, long owner, int inUse)
		{
			if (!IsGoneOwned(goneUid, owner))
			{
				return Plan.None;
			}
			if (!InUseLeft(inUse))
			{
				return Plan.Free;
			}
			return Plan.ClearUse;
		}

		public static int Batch(int queued)
		{
			if (queued <= 0)
			{
				return 0;
			}
			if (queued >= 250)
			{
				return 250;
			}
			return queued;
		}
	}
	internal static class DisconnectedOwnership
	{
		private struct Entry
		{
			public long Uid;

			public ZDO Zdo;
		}

		private sealed class Worker : MonoBehaviour
		{
			private void Update()
			{
				if (Queue.Count != 0)
				{
					if ((Object)(object)ZNet.instance == (Object)null || ZDOMan.instance == null || !Enabled)
					{
						Queue.Clear();
					}
					else
					{
						Drain();
					}
				}
			}
		}

		private static class Patches
		{
			[HarmonyPatch(typeof(ZNet), "Disconnect")]
			[HarmonyPostfix]
			private static void PeerGone(ZNetPeer peer)
			{
				if (peer != null)
				{
					Enqueue(peer.m_uid);
				}
			}
		}

		private static Setting<bool> _on;

		private static Harmony _harmony;

		private static readonly List<Entry> Queue = new List<Entry>();

		private static long _lastGone;

		private static int _released;

		public static bool Enabled
		{
			get
			{
				if (_on != null)
				{
					return _on.Value;
				}
				return false;
			}
		}

		public static void Init(SettingsPage page)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected O, but got Unknown
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Expected O, but got Unknown
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Expected O, but got Unknown
			_on = page.Toggle("disconnected_ownership", "Release objects of disconnected players", true, (SettingPolicy)1, true);
			_harmony = new Harmony("expdare.meadworks.world.disconnectedownership");
			_harmony.PatchAll(typeof(Patches));
			LedgerTrack.Patch(_harmony, "world disconnected ownership");
			GameObject val = new GameObject("MeadWorks.DisconnectedOwnership");
			Object.DontDestroyOnLoad((Object)val);
			val.AddComponent<Worker>();
			LedgerTrack.Object<GameObject>(val, "world disconnected ownership worker");
			Ledger.Add("world disconnected ownership state", (Action)delegate
			{
				_on = null;
				Queue.Clear();
				_lastGone = 0L;
				_released = 0;
			});
		}

		public static string Status()
		{
			return "release on=" + Enabled + " queued=" + Queue.Count + " lastGone=" + _lastGone + " released=" + _released;
		}

		private static void Enqueue(long goneUid)
		{
			if ((Object)(object)ZNet.instance == (Object)null || ZDOMan.instance == null || !DisconnectedOwnershipRules.ShouldHandle(Enabled, ZNet.instance.IsServer(), ZDOMan.GetSessionID(), goneUid))
			{
				return;
			}
			_lastGone = goneUid;
			foreach (ZDO value in ZDOMan.instance.m_objectsByID.Values)
			{
				if (DisconnectedOwnershipRules.IsGoneOwned(goneUid, value.GetOwner()))
				{
					Queue.Add(new Entry
					{
						Uid = goneUid,
						Zdo = value
					});
				}
			}
		}

		private static void Drain()
		{
			int num = DisconnectedOwnershipRules.Batch(Queue.Count);
			for (int i = 0; i < num; i++)
			{
				Entry entry = Queue[i];
				ZDO zdo = entry.Zdo;
				if (zdo == null || !zdo.IsValid())
				{
					continue;
				}
				DisconnectedOwnershipRules.Plan plan = DisconnectedOwnershipRules.PlanFor(entry.Uid, zdo.GetOwner(), zdo.GetInt(ZDOVars.s_inUse, 0));
				if (plan != DisconnectedOwnershipRules.Plan.None)
				{
					if (plan == DisconnectedOwnershipRules.Plan.ClearUse)
					{
						zdo.Set(ZDOVars.s_inUse, 0, false);
					}
					zdo.SetOwner(0L);
					_released++;
				}
			}
			if (num > 0)
			{
				Queue.RemoveRange(0, num);
			}
		}
	}
	internal static class DistantCloth
	{
		private sealed class State
		{
			public readonly Dictionary<Behaviour, bool> Cloth = new Dictionary<Behaviour, bool>();

			public readonly Dictionary<Cloth, bool> Legacy = new Dictionary<Cloth, bool>();

			public Animator Animator;

			public AnimatorCullingMode Culling;

			public bool Reduced;
		}

		private static class Patches
		{
			[HarmonyPatch(typeof(Player), "Update")]
			[HarmonyPostfix]
			private static void Tick(Player __instance)
			{
				//IL_00b3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00be: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c3: Unknown result type (might be due to invalid IL or missing references)
				//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
				if ((Object)(object)__instance != (Object)(object)Player.m_localPlayer || Time.unscaledTime < _due)
				{
					return;
				}
				_due = Time.unscaledTime + 0.5f;
				foreach (Player allPlayer in Player.GetAllPlayers())
				{
					if ((Object)(object)allPlayer == (Object)null)
					{
						continue;
					}
					if (!States.TryGetValue(allPlayer, out var value))
					{
						value = (States[allPlayer] = Capture(allPlayer));
					}
					bool fighting = ((Character)allPlayer).InAttack() || ((Character)allPlayer).IsBlocking() || ((Character)__instance).InAttack() || ((Character)__instance).IsBlocking();
					bool enabled = _on != null && _on.Value;
					bool local = (Object)(object)allPlayer == (Object)(object)__instance;
					Vector3 val = ((Component)allPlayer).transform.position - ((Component)__instance).transform.position;
					if (!DistantClothRules.Reduce(enabled, local, ((Vector3)(ref val)).sqrMagnitude, fighting))
					{
						Restore(value);
					}
					else
					{
						if (value.Reduced)
						{
							continue;
						}
						foreach (Behaviour key in value.Cloth.Keys)
						{
							if ((Object)(object)key != (Object)null)
							{
								key.enabled = false;
							}
						}
						foreach (Cloth key2 in value.Legacy.Keys)
						{
							if ((Object)(object)key2 != (Object)null)
							{
								key2.enabled = false;
							}
						}
						if ((Object)(object)value.Animator != (Object)null)
						{
							value.Animator.cullingMode = (AnimatorCullingMode)1;
						}
						value.Reduced = true;
					}
				}
			}

			[HarmonyPatch(typeof(VisEquipment), "UpdateLodgroup")]
			[HarmonyPrefix]
			private static void Equipment(VisEquipment __instance)
			{
				Player componentInParent = ((Component)__instance).GetComponentInParent<Player>();
				if ((Object)(object)componentInParent != (Object)null && States.TryGetValue(componentInParent, out var value))
				{
					Restore(value);
					States.Remove(componentInParent);
				}
			}

			[HarmonyPatch(typeof(Player), "OnDestroy")]
			[HarmonyPrefix]
			private static void Leaving(Player __instance)
			{
				State value;
				if ((Object)(object)__instance == (Object)(object)Player.m_localPlayer)
				{
					RestoreAll();
				}
				else if (States.TryGetValue(__instance, out value))
				{
					Restore(value);
					States.Remove(__instance);
				}
			}
		}

		private static readonly Dictionary<Player, State> States = new Dictionary<Player, State>();

		private static Setting<bool> _on;

		private static float _due;

		public static void Init(SettingsPage page)
		{
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			//IL_0052: Expected O, but got Unknown
			_on = page.Toggle("distant_cloth", "Reduce distant player cloth", true, (SettingPolicy)0, false);
			((Setting)_on).Changed += RestoreAll;
			Harmony val = new Harmony("expdare.meadworks.world.distantcloth");
			LedgerTrack.Patch(val, "world distant cloth");
			val.PatchAll(typeof(Patches));
			Ledger.Add("world distant cloth state", (Action)delegate
			{
				RestoreAll();
				((Setting)_on).Changed -= RestoreAll;
				_on = null;
			});
		}

		private static void Restore(State state)
		{
			//IL_00c0: Unknown result type (might be due to invalid IL or missing references)
			if (!state.Reduced)
			{
				return;
			}
			foreach (KeyValuePair<Behaviour, bool> item in state.Cloth)
			{
				if ((Object)(object)item.Key != (Object)null)
				{
					item.Key.enabled = item.Value;
				}
			}
			foreach (KeyValuePair<Cloth, bool> item2 in state.Legacy)
			{
				if ((Object)(object)item2.Key != (Object)null)
				{
					item2.Key.enabled = item2.Value;
				}
			}
			if ((Object)(object)state.Animator != (Object)null)
			{
				state.Animator.cullingMode = state.Culling;
			}
			state.Reduced = false;
		}

		private static void RestoreAll()
		{
			foreach (State value in States.Values)
			{
				Restore(value);
			}
			States.Clear();
			_due = 0f;
		}

		private static State Capture(Player player)
		{
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			State state = new State
			{
				Animator = ((Character)player).m_animator
			};
			MagicaCloth[] componentsInChildren = ((Component)player).GetComponentsInChildren<MagicaCloth>(true);
			foreach (MagicaCloth val in componentsInChildren)
			{
				state.Cloth[(Behaviour)(object)val] = ((Behaviour)val).enabled;
			}
			Cloth[] componentsInChildren2 = ((Component)player).GetComponentsInChildren<Cloth>(true);
			foreach (Cloth val2 in componentsInChildren2)
			{
				state.Legacy[val2] = val2.enabled;
			}
			if ((Object)(object)state.Animator != (Object)null)
			{
				state.Culling = state.Animator.cullingMode;
			}
			return state;
		}
	}
	public static class DistantClothRules
	{
		public static bool Reduce(bool enabled, bool local, float distanceSquared, bool fighting)
		{
			if (enabled && !local && !fighting)
			{
				return distanceSquared > 3600f;
			}
			return false;
		}
	}
	public static class DungeonLayerRules
	{
		public enum Layer
		{
			Unknown,
			Surface,
			Interior
		}

		public sealed class Peer<T>
		{
			private struct Wait
			{
				public double Since;

				public ulong Receipt;
			}

			private readonly Dictionary<T, Wait> _waiting = new Dictionary<T, Wait>();

			private readonly HashSet<T> _seen = new HashSet<T>();

			private readonly List<T> _remove = new List<T>();

			private Layer _layer;

			private double _lastTime = double.NaN;

			private double _graceUntil;

			private bool _filter;

			private float _hysteresis;

			public int Pending => _waiting.Count;

			public void BeginRound(float height, double now, float hysteresis, double grace)
			{
				_seen.Clear();
				_hysteresis = hysteresis;
				Layer layer = Classify(height, _layer, hysteresis);
				if (double.IsNaN(_lastTime) || now < _lastTime || layer != _layer)
				{
					_graceUntil = now + grace;
				}
				_layer = layer;
				_lastTime = now;
				_filter = layer != Layer.Unknown && now >= _graceUntil && Math.Abs(height - 3000f) > hysteresis && !double.IsNaN(now) && !double.IsInfinity(now);
				if (!_filter)
				{
					_waiting.Clear();
				}
			}

			public bool ShouldDefer(T id, float height, bool known, bool protectedObject, double now, double maxWait, ulong receipt = 0uL)
			{
				Layer layer = Classify(height, Layer.Unknown, _hysteresis);
				if (!_filter || !known || protectedObject || layer == Layer.Unknown || layer == _layer)
				{
					_waiting.Remove(id);
					return false;
				}
				_seen.Add(id);
				if (!_waiting.TryGetValue(id, out var value) || value.Receipt != receipt)
				{
					value = (_waiting[id] = new Wait
					{
						Since = now,
						Receipt = receipt
					});
				}
				return now - value.Since < maxWait;
			}

			public void EndRound()
			{
				_remove.Clear();
				foreach (KeyValuePair<T, Wait> item in _waiting)
				{
					if (!_seen.Contains(item.Key))
					{
						_remove.Add(item.Key);
					}
				}
				foreach (T item2 in _remove)
				{
					_waiting.Remove(item2);
				}
			}
		}

		public const float InteriorHeight = 3000f;

		public const float DefaultHysteresis = 100f;

		public const float DefaultGrace = 10f;

		public const float DefaultMaxWait = 5f;

		public const string DefaultPrefabs = "Player,Player_tombstone,Raft,Karve,VikingShip,VikingShip_Ashlands,Cart,portal,portal_wood,portal_stone,LocationProxy,dungeon_forestcrypt_door,dungeon_sunkencrypt_irongate,dungeon_queen_door,sunken_crypt_gate";

		public static bool Active(bool enabled, bool server)
		{
			return enabled && server;
		}

		public static Layer Classify(float height, Layer previous, float hysteresis)
		{
			if (float.IsNaN(height) || float.IsInfinity(height))
			{
				return Layer.Unknown;
			}
			if (height > 3000f + hysteresis)
			{
				return Layer.Interior;
			}
			if (height < 3000f - hysteresis)
			{
				return Layer.Surface;
			}
			return previous;
		}

		public static HashSet<string> ParsePrefabs(string text)
		{
			HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal);
			string[] array = (text ?? "").Split(new char[4] { ',', ';', '\n', '\r' }, StringSplitOptions.RemoveEmptyEntries);
			for (int i = 0; i < array.Length; i++)
			{
				string text2 = array[i].Trim();
				if (text2.Length > 0)
				{
					hashSet.Add(text2);
				}
			}
			return hashSet;
		}

		public static bool AlwaysSend(ISet<string> names, string prefab)
		{
			if (prefab != null)
			{
				return names.Contains(prefab);
			}
			return false;
		}
	}
	internal static class DungeonLayers
	{
		private static class Patches
		{
			[HarmonyPatch(typeof(ZDOMan), "CreateSyncList")]
			[HarmonyPostfix]
			[HarmonyBefore(new string[] { "expdare.meadworks.world.peerscheduler" })]
			private static void SyncList(ZDOPeer peer, List<ZDO> toSync)
			{
				Filter(peer, toSync);
			}

			[HarmonyPatch(typeof(ZDOMan), "ShutDown")]
			[HarmonyPostfix]
			private static void Shutdown()
			{
				Reset();
			}
		}

		private static Setting<bool> _on;

		private static Setting<float> _hysteresis;

		private static Setting<float> _grace;

		private static Setting<float> _wait;

		private static Setting<string> _prefabs;

		private static HashSet<string> _always = new HashSet<string>();

		private static readonly Dictionary<int, bool> Critical = new Dictionary<int, bool>();

		private static ConditionalWeakTable<ZDOPeer, DungeonLayerRules.Peer<ZDOID>> _peers = new ConditionalWeakTable<ZDOPeer, DungeonLayerRules.Peer<ZDOID>>();

		public static void Init(SettingsPage page)
		{
			//IL_0178: Unknown result type (might be due to invalid IL or missing references)
			//IL_017d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0197: Expected O, but got Unknown
			_on = page.Toggle("dungeon_layers", "Filter dungeon layer updates", false, (SettingPolicy)1, true);
			_prefabs = page.Text("dungeon_layer_prefabs", "Always sync prefabs", "Player,Player_tombstone,Raft,Karve,VikingShip,VikingShip_Ashlands,Cart,portal,portal_wood,portal_stone,LocationProxy,dungeon_forestcrypt_door,dungeon_sunkencrypt_irongate,dungeon_queen_door,sunken_crypt_gate", (SettingPolicy)1, true);
			_hysteresis = page.Slider("dungeon_layer_hysteresis", "Layer height margin (meters)", 100f, 0f, 500f, 10f, (SettingPolicy)1, true);
			_grace = page.Slider("dungeon_layer_grace", "Layer transition grace (seconds)", 10f, 2f, 30f, 1f, (SettingPolicy)1, true);
			_wait = page.Slider("dungeon_layer_wait", "Other layer maximum deferral (seconds)", 5f, 1f, 30f, 1f, (SettingPolicy)1, true);
			((Setting)_on).Changed += Reset;
			((Setting)_prefabs).Changed += Reset;
			((Setting)_hysteresis).Changed += Reset;
			((Setting)_grace).Changed += Reset;
			((Setting)_wait).Changed += Reset;
			Reset();
			Harmony val = new Harmony("expdare.meadworks.world.dungeonlayers");
			val.PatchAll(typeof(Patches));
			LedgerTrack.Patch(val, "world dungeon layers");
			Ledger.Add("world dungeon layer state", (Action)delegate
			{
				((Setting)_on).Changed -= Reset;
				((Setting)_prefabs).Changed -= Reset;
				((Setting)_hysteresis).Changed -= Reset;
				((Setting)_grace).Changed -= Reset;
				((Setting)_wait).Changed -= Reset;
				_on = null;
				_prefabs = null;
				_hysteresis = (_grace = (_wait = null));
				Reset();
			});
		}

		private static void Reset()
		{
			_peers = new ConditionalWeakTable<ZDOPeer, DungeonLayerRules.Peer<ZDOID>>();
			Critical.Clear();
			_always = DungeonLayerRules.ParsePrefabs((_prefabs != null) ? _prefabs.Value : null);
		}

		private static bool AlwaysSend(ZDO zdo)
		{
			int prefab = zdo.GetPrefab();
			if (Critical.TryGetValue(prefab, out var value))
			{
				return value;
			}
			GameObject val = (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.GetPrefab(prefab) : null);
			if ((Object)(object)val == (Object)null)
			{
				return true;
			}
			value = DungeonLayerRules.AlwaysSend(_always, ((Object)val).name) || (Object)(object)val.GetComponent<Player>() != (Object)null || (Object)(object)val.GetComponent<TombStone>() != (Object)null || (Object)(object)val.GetComponent<Ship>() != (Object)null || (Object)(object)val.GetComponent<Vagon>() != (Object)null || (Object)(object)val.GetComponentInChildren<Teleport>(true) != (Object)null || (Object)(object)val.GetComponentInChildren<TeleportWorld>(true) != (Object)null || (Object)(object)val.GetComponentInChildren<DungeonGenerator>(true) != (Object)null || (Object)(object)val.GetComponent<LocationProxy>() != (Object)null;
			Critical.Add(prefab, value);
			return value;
		}

		private static void Filter(ZDOPeer peer, List<ZDO> toSync)
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ae: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f6: Unknown result type (might be due to invalid IL or missing references)
			//IL_0104: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)ZNet.instance == (Object)null || !DungeonLayerRules.Active(_on != null && _on.Value, ZNet.instance.IsServer()))
			{
				return;
			}
			DungeonLayerRules.Peer<ZDOID> value = _peers.GetValue(peer, (ZDOPeer _) => new DungeonLayerRules.Peer<ZDOID>());
			ZNetPeer peer2 = peer.m_peer;
			double timeAsDouble = Time.timeAsDouble;
			value.BeginRound(peer2.GetRefPos().y, timeAsDouble, _hysteresis.Value, _grace.Value);
			int num = 0;
			for (int num2 = 0; num2 < toSync.Count; num2++)
			{
				ZDO val = toSync[num2];
				bool protectedObject = peer.m_forceSend.Contains(val.m_uid) || val.GetOwner() == peer2.m_uid || AlwaysSend(val);
				PeerZDOInfo value2;
				bool known = peer.m_zdos.TryGetValue(val.m_uid, out value2);
				ulong receipt = ((ulong)value2.m_ownerRevision << 32) | value2.m_dataRevision;
				if (!value.ShouldDefer(val.m_uid, val.GetPosition().y, known, protectedObject, timeAsDouble, _wait.Value, receipt))
				{
					toSync[num++] = val;
				}
			}
			if (num < toSync.Count)
			{
				toSync.RemoveRange(num, toSync.Count - num);
			}
			value.EndRound();
		}
	}
	public static class FermenterBatchRules
	{
		public struct Batch
		{
			public long Start;

			public long Observed;

			public long Owner;

			public float Duration;
		}

		public struct Decision
		{
			public float Duration;

			public string Write;
		}

		private sealed class Parsed
		{
			public bool Ok;

			public Batch Batch;
		}

		public const string Key = "MW_FermenterBatch_v1";

		private static readonly ConditionalWeakTable<string, Parsed> Cache = new ConditionalWeakTable<string, Parsed>();

		private static readonly ConditionalWeakTable<string, Parsed>.CreateValueCallback Parse = delegate(string text)
		{
			Parsed parsed = new Parsed();
			parsed.Ok = ParseText(text, out parsed.Batch);
			return parsed;
		};

		public static bool TryRead(string text, out Batch batch)
		{
			if (string.IsNullOrEmpty(text))
			{
				batch = default(Batch);
				return false;
			}
			Parsed value = Cache.GetValue(text, Parse);
			batch = value.Batch;
			return value.Ok;
		}

		private static bool ParseText(string text, out Batch batch)
		{
			batch = default(Batch);
			if (text.Length > 160)
			{
				return false;
			}
			string[] array = text.Split(new char[1] { '|' });
			if (array.Length != 5 || array[0] != "1" || !long.TryParse(array[1], NumberStyles.Integer, CultureInfo.InvariantCulture, out batch.Start) || !float.TryParse(array[2], NumberStyles.Float, CultureInfo.InvariantCulture, out batch.Duration) || !long.TryParse(array[3], NumberStyles.Integer, CultureInfo.InvariantCulture, out batch.Observed) || !long.TryParse(array[4], NumberStyles.Integer, CultureInfo.InvariantCulture, out batch.Owner))
			{
				return false;
			}
			if (batch.Start > 0 && batch.Observed >= batch.Start)
			{
				long observed = batch.Observed;
				DateTime maxValue = DateTime.MaxValue;
				if (observed <= maxValue.Ticks && batch.Duration > 0f && !float.IsNaN(batch.Duration))
				{
					return !float.IsInfinity(batch.Duration);
				}
			}
			return false;
		}

		public static string Pack(Batch batch)
		{
			return "1|" + batch.Start.ToString(CultureInfo.InvariantCulture) + "|" + batch.Duration.ToString("R", CultureInfo.InvariantCulture) + "|" + batch.Observed.ToString(CultureInfo.InvariantCulture) + "|" + batch.Owner.ToString(CultureInfo.InvariantCulture);
		}

		public static Decision Resolve(string saved, long start, long now, long owner, bool isOwner, bool plainServer, float baseDuration, float speed, SeasonModifierRules.FermenterHistory history, bool newBatch = false)
		{
			Decision result = new Decision
			{
				Duration = baseDuration
			};
			if (plainServer || start <= 0)
			{
				return result;
			}
			Batch batch;
			bool flag = TryRead(saved, out batch) && batch.Start == start;
			float duration = batch.Duration;
			float num = Elapsed(start, now);
			if (!isOwner)
			{
				result.Duration = (flag ? batch.Duration : ((num >= baseDuration) ? baseDuration : float.MaxValue));
				return result;
			}
			float num2 = SeasonModifierRules.SpeedDuration(baseDuration, SeasonModifierRules.Clamp(speed));
			if (newBatch)
			{
				batch = new Batch
				{
					Start = start,
					Duration = num2
				};
			}
			else if (!flag)
			{
				batch = new Batch
				{
					Start = start,
					Duration = Math.Max(baseDuration, Math.Max(num2, history.Duration(baseDuration, start)))
				};
			}
			result.Duration = batch.Duration;
			if (newBatch || !flag || batch.Owner != owner || history.LatestTicks > batch.Observed || batch.Duration != duration)
			{
				batch.Owner = owner;
				batch.Observed = Math.Max(start, now);
				result.Write = Pack(batch);
			}
			return result;
		}

		private static float Elapsed(long start, long now)
		{
			return (float)((double)(now - start) / 10000000.0);
		}

		public static string ResetTimer(string saved, long start, long now, long owner)
		{
			if (start <= 0 || !TryRead(saved, out var batch) || batch.Start == start)
			{
				return null;
			}
			batch.Start = start;
			batch.Observed = Math.Max(start, now);
			batch.Owner = owner;
			return Pack(batch);
		}
	}
	public static class HeatwaveRules
	{
		public readonly struct State
		{
			public readonly bool Hot;

			public readonly float WetTimeMultiplier;

			public float StaminaMultiplier
			{
				get
				{
					if (!Hot)
					{
						return 1f;
					}
					return 0.8f;
				}
			}

			public State(bool hot, float wetTimeMultiplier)
			{
				Hot = hot;
				WetTimeMultiplier = wetTimeMultiplier;
			}

			public bool Cold(bool raw)
			{
				if (raw)
				{
					return !Hot;
				}
				return false;
			}

			public float ExtraWetTime(float dt)
			{
				return Math.Max(0f, dt) * (WetTimeMultiplier - 1f);
			}
		}

		public const float StaminaRegenCut = 0.2f;

		public const float ShimmerStrengthMultiplier = 10f;

		public static State Evaluate(string weatherId, bool localPlayer, bool outdoors, bool shaded, bool wet)
		{
			bool flag = weatherId == "W1" && localPlayer && outdoors;
			return new State(flag && !shaded && !wet, flag ? 2f : 1f);
		}
	}
	internal static class MovementPayload
	{
		private struct Sample
		{
			public Vector3 Position;

			public Vector3 Velocity;

			public Vector3 AngularVelocity;

			public Quaternion Rotation;
		}

		private sealed class State
		{
			public Sample Published;

			public Sample Observed;

			public double PublishedAt;

			public ushort OwnerRevision;

			public bool HasPublished;

			public bool WasMoving;

			public int Force;
		}

		private sealed class Owner
		{
			public WeakReference<ZSyncTransform> Sync;
		}

		private struct Frame
		{
			public State State;

			public Sample Sample;

			public bool Position;

			public bool Rotation;

			public bool Velocity;

			public bool Masked;

			public double Now;

			public ushort OwnerRevision;
		}

		private static class Patches
		{
			[HarmonyPatch(typeof(ZSyncTransform), "OwnerSync")]
			[HarmonyPrefix]
			private static void BeforeSync(ZSyncTransform __instance, out Frame __state)
			{
				Prepare(__instance, out __state);
			}

			[HarmonyPatch(typeof(ZSyncTransform), "OwnerSync")]
			[HarmonyFinalizer]
			private static void AfterSync(ZSyncTransform __instance, Frame __state, Exception __exception)
			{
				if (__state.State == null)
				{
					return;
				}
				if (__state.Masked)
				{
					__instance.m_syncPosition = __state.Position;
					__instance.m_syncRotation = __state.Rotation;
					__instance.m_syncBodyVelocity = __state.Velocity;
				}
				else if (__exception == null)
				{
					__state.State.Published = __state.Sample;
					__state.State.PublishedAt = __state.Now;
					__state.State.OwnerRevision = __state.OwnerRevision;
					__state.State.HasPublished = true;
					_allowed++;
					if (_on == null || !_on.Value)
					{
						_states.Remove(__instance);
					}
				}
				else
				{
					_states.Remove(__instance);
				}
			}

			[HarmonyPatch(typeof(ZSyncTransform), "SyncNow")]
			[HarmonyPrefix]
			private static void ForceSync(ZSyncTransform __instance, out State __state)
			{
				__state = null;
				if (_states.TryGetValue(__instance, out var value))
				{
					__state = value;
					value.Force++;
				}
			}

			[HarmonyPatch(typeof(ZSyncTransform), "SyncNow")]
			[HarmonyFinalizer]
			private static void EndForce(State __state)
			{
				if (__state != null)
				{
					__state.Force--;
				}
			}

			[HarmonyPatch(typeof(ZDO), "SetOwner")]
			[HarmonyPrefix]
			private static void ChangingOwner(ZDO __instance, long uid)
			{
				if (__instance.IsOwner() && __instance.GetOwner() != uid && _owners.TryGetValue(__instance, out var value) && value.Sync.TryGetTarget(out var target) && (Object)(object)target != (Object)null && (Object)(object)target.m_nview != (Object)null && target.m_nview.GetZDO() == __instance)
				{
					Flush(target);
				}
			}

			[HarmonyPatch(typeof(ZSyncTransform), "OnDisable")]
			[HarmonyPrefix]
			private static void Disabling(ZSyncTransform __instance)
			{
				Flush(__instance);
				_states.Remove(__instance);
			}

			[HarmonyPatch(typeof(ZDOMan), "ShutDown")]
			[HarmonyPostfix]
			private static void Shutdown()
			{
				Reset();
			}
		}

		private static Setting<bool> _on;

		private static ConditionalWeakTable<ZSyncTransform, State> _states = new ConditionalWeakTable<ZSyncTransform, State>();

		private static ConditionalWeakTable<ZDO, Owner> _owners = new ConditionalWeakTable<ZDO, Owner>();

		private static int _allowed;

		private static int _suppressed;

		public static void Init(Setting<bool> enabled)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Expected O, but got Unknown
			_on = enabled;
			Harmony val = new Harmony("expdare.meadworks.world.movementpayload");
			val.PatchAll(typeof(Patches));
			LedgerTrack.Patch(val, "world movement payload");
			Ledger.Add("world movement payload state", (Action)delegate
			{
				FlushAll();
				_on = null;
				Reset();
			});
		}

		private static void Reset()
		{
			_states = new ConditionalWeakTable<ZSyncTransform, State>();
			_owners = new ConditionalWeakTable<ZDO, Owner>();
			_allowed = (_suppressed = 0);
		}

		public static string Status()
		{
			return "movement on=" + (_on != null && _on.Value) + " allowed=" + _allowed + " suppressed=" + _suppressed;
		}

		private static void FlushAll()
		{
			IMonoUpdater[] array = ZSyncTransform.Instances.ToArray();
			foreach (IMonoUpdater obj in array)
			{
				ZSyncTransform val = (ZSyncTransform)(object)((obj is ZSyncTransform) ? obj : null);
				if (val != null)
				{
					Flush(val);
				}
			}
		}

		private static void Flush(ZSyncTransform sync)
		{
			if ((Object)(object)sync != (Object)null && _states.TryGetValue(sync, out var value) && value.HasPublished && (Object)(object)sync.m_nview != (Object)null && sync.m_nview.IsValid() && sync.m_nview.IsOwner())
			{
				sync.SyncNow();
			}
		}

		private static Sample Read(ZSyncTransform sync)
		{
			//IL_000b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0038: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0045: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006c: Unknown result type (might be due to invalid IL or missing references)
			//IL_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0071: Unknown result type (might be due to invalid IL or missing references)
			return new Sample
			{
				Position = sync.GetPosition(),
				Rotation = (((Object)(object)sync.m_body != (Object)null) ? sync.m_body.rotation : ((Component)sync).transform.rotation),
				Velocity = sync.GetVelocity(),
				AngularVelocity = (((Object)(object)sync.m_body != (Object)null) ? sync.m_body.angularVelocity : Vector3.zero)
			};
		}

		private static void Prepare(ZSyncTransform sync, out Frame frame)
		{
			//IL_0090: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d2: Unknown result type (might be due to invalid IL or missing references)
			//IL_01dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0187: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ff: 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_0234: Unknown result type (might be due to invalid IL or missing references)
			//IL_023f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0261: Unknown result type (might be due to invalid IL or missing references)
			//IL_026c: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_02f8: Unknown result type (might be due to invalid IL or missing references)
			//IL_02fd: Unknown result type (might be due to invalid IL or missing references)
			//IL_0302: Unknown result type (might be due to invalid IL or missing references)
			frame = default(Frame);
			if (((_on == null || !_on.Value) && !_states.TryGetValue(sync, out var value)) || (Object)(object)sync.m_nview == (Object)null || !sync.m_nview.IsValid())
			{
				return;
			}
			ZDO zDO = sync.m_nview.GetZDO();
			if (!zDO.IsOwner())
			{
				_states.Remove(sync);
				return;
			}
			ZDOID val = default(ZDOID);
			string text = default(string);
			Vector3 val2 = default(Vector3);
			Quaternion val3 = default(Quaternion);
			Vector3 val4 = default(Vector3);
			if (!sync.m_wasOwner || sync.m_syncScale || (Object)(object)((Component)sync).transform.parent != (Object)null || ((Component)sync).transform.position.y < -5000f || (sync.m_characterParentSync && (sync.GetRelativePosition(zDO, ref val, ref text, ref val2, ref val3, ref val4) || !((ZDOID)(ref sync.m_tempParentCached)).IsNone())))
			{
				if (_states.Remove(sync) && sync.m_syncRotation)
				{
					((Component)sync).transform.hasChanged = true;
				}
				return;
			}
			bool flag = _on != null && _on.Value;
			if (!flag && !_states.TryGetValue(sync, out value))
			{
				return;
			}
			State value2 = _states.GetValue(sync, (ZSyncTransform _) => new State());
			Sample sample = Read(sync);
			double realtimeSinceStartupAsDouble = Time.realtimeSinceStartupAsDouble;
			bool flag2 = ((Vector3)(ref sample.Velocity)).sqrMagnitude > 1E-06f || ((Vector3)(ref sample.AngularVelocity)).sqrMagnitude > 1E-06f || (value2.HasPublished && (!((Vector3)(ref sample.Position)).Equals(value2.Observed.Position) || !((Quaternion)(ref sample.Rotation)).Equals(value2.Observed.Rotation)));
			MovementPayloadRules.Change change = new MovementPayloadRules.Change
			{
				Position = (sync.m_syncPosition ? Vector3.Distance(sample.Position, value2.Published.Position) : 0f),
				Rotation = (sync.m_syncRotation ? Quaternion.Angle(sample.Rotation, value2.Published.Rotation) : 0f),
				Velocity = ((sync.m_syncPosition || sync.m_syncBodyVelocity) ? Vector3.Distance(sample.Velocity, value2.Published.Velocity) : 0f),
				AngularVelocity = (sync.m_syncBodyVelocity ? Vector3.Distance(sample.AngularVelocity, value2.Published.AngularVelocity) : 0f),
				Stopped = ((value2.WasMoving && !flag2) || MovementPayloadRules.Stopped(((Vector3)(ref value2.Observed.Velocity)).sqrMagnitude, ((Vector3)(ref sample.Velocity)).sqrMagnitude) || MovementPayloadRules.Stopped(((Vector3)(ref value2.Observed.AngularVelocity)).sqrMagnitude, ((Vector3)(ref sample.AngularVelocity)).sqrMagnitude)),
				ContextChanged = (value2.OwnerRevision != zDO.OwnerRevision || (sync.m_syncPosition && !((object)ZoneSystem.GetSectorIndex(sample.Position)/*cast due to .constrained prefix*/).Equals((object?)zDO.GetSectorIndex())))
			};
			value2.Observed = sample;
			value2.WasMoving = flag2;
			bool flag3 = MovementPayloadRules.ShouldPublish(change, realtimeSinceStartupAsDouble - value2.PublishedAt, !flag || !value2.HasPublished || value2.Force > 0);
			frame = new Frame
			{
				State = value2,
				Sample = sample,
				Now = realtimeSinceStartupAsDouble,
				OwnerRevision = zDO.OwnerRevision,
				Position = sync.m_syncPosition,
				Rotation = sync.m_syncRotation,
				Velocity = sync.m_syncBodyVelocity,
				Masked = !flag3
			};
			Owner value3 = _owners.GetValue(zDO, (ZDO _) => new Owner());
			if (value3.Sync == null || !value3.Sync.TryGetTarget(out var target) || (Object)(object)target != (Object)(object)sync)
			{
				value3.Sync = new WeakReference<ZSyncTransform>(sync);
			}
			if (flag3)
			{
				if (sync.m_syncRotation)
				{
					((Component)sync).transform.hasChanged = true;
				}
			}
			else
			{
				sync.m_syncPosition = (sync.m_syncRotation = (sync.m_syncBodyVelocity = false));
				_suppressed++;
			}
		}
	}
	public static class MovementPayloadRules
	{
		public struct Change
		{
			public double Position;

			public double Rotation;

			public double Velocity;

			public double AngularVelocity;

			public bool Stopped;

			public bool ContextChanged;
		}

		public const double PositionThreshold = 0.02;

		public const double RotationThreshold = 0.5;

		public const double VelocityThreshold = 0.02;

		public const double AngularVelocityThreshold = 0.02;

		public const double MaximumStaleness = 0.1;

		public static bool ShouldPublish(Change change, double elapsed, bool forced)
		{
			if (forced || change.Stopped || change.ContextChanged)
			{
				return true;
			}
			if (!Finite(elapsed) || elapsed < 0.0 || elapsed >= 0.1)
			{
				return true;
			}
			if (!Reached(change.Position, 0.02) && !Reached(change.Rotation, 0.5) && !Reached(change.Velocity, 0.02))
			{
				return Reached(change.AngularVelocity, 0.02);
			}
			return true;
		}

		private static bool Reached(double value, double threshold)
		{
			if (Finite(value) && !(value < 0.0))
			{
				return value >= threshold;
			}
			return true;
		}

		public static bool Stopped(double previousSpeedSquared, double speedSquared)
		{
			if (previousSpeedSquared > 1E-06)
			{
				return speedSquared <= 1E-06;
			}
			return false;
		}

		private static bool Finite(double value)
		{
			if (!double.IsNaN(value))
			{
				return !double.IsInfinity(value);
			}
			return false;
		}
	}
	public static class NativeWeatherRules
	{
		public readonly struct Flags
		{
			public readonly bool Wet;

			public readonly bool Cold;

			public readonly bool ColdAtNight;

			public readonly bool Freezing;

			public readonly bool FreezingAtNight;

			public readonly bool Dark;

			public readonly bool Lightning;

			public Flags(bool wet, bool cold, bool coldAtNight, bool freezing, bool freezingAtNight, bool dark, bool lightning)
			{
				Wet = wet;
				Cold = cold;
				ColdAtNight = coldAtNight;
				Freezing = freezing;
				FreezingAtNight = freezingAtNight;
				Dark = dark;
				Lightning = lightning;
			}
		}

		public const int MaxChangeSteps = 4;

		public static List<HudSideLine> Lines(Flags f)
		{
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0092: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_0115: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			List<HudSideLine> list = new List<HudSideLine>();
			if (f.Wet)
			{
				list.Add(Row(Lang.T("world.native_wet", "Wet"), (HudEffectTone)0));
			}
			if (f.Freezing)
			{
				list.Add(Row(Lang.T("world.native_freezing", "Freezing"), (HudEffectTone)3));
			}
			else if (f.Cold)
			{
				list.Add(Row(Lang.T("world.native_cold", "Cold"), (HudEffectTone)0));
			}
			if (f.FreezingAtNight && !f.Freezing)
			{
				list.Add(Row(Lang.T("world.native_freezing_night", "Freezing at night"), (HudEffectTone)3));
			}
			else if (f.ColdAtNight && !f.Cold && !f.Freezing && !f.FreezingAtNight)
			{
				list.Add(Row(Lang.T("world.native_cold_night", "Cold at night"), (HudEffectTone)0));
			}
			if (f.Dark)
			{
				list.Add(Row(Lang.T("world.native_dark", "Dark"), (HudEffectTone)0));
			}
			if (f.Lightning)
			{
				list.Add(Row(Lang.T("world.native_lightning", "Lightning"), (HudEffectTone)0));
			}
			return list;
		}

		private static HudSideLine Row(string text, HudEffectTone tone)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return new HudSideLine(text, tone, false);
		}

		public static bool Shows(bool hasTime, int effectLines, bool hasForecast)
		{
			return hasTime || effectLines > 0 || hasForecast;
		}

		public static HudSideLine Title(string name, bool hasTime, double secondsLeft, Flags f)
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			return new HudSideLine(hasTime ? WeatherHudRules.Title(name, secondsLeft) : (name ?? ""), (HudEffectTone)((f.Freezing || f.FreezingAtNight) ? 3 : 0), true);
		}

		public static List<HudSideLine> Card(string name, bool hasTime, double secondsLeft, Flags f, IList<HudSideLine> tail)
		{
			//IL_000a: 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)
			List<HudSideLine> list = new List<HudSideLine> { Title(name, hasTime, secondsLeft, f) };
			list.AddRange(Lines(f));
			int num = Math.Min(tail?.Count ?? 0, 7);
			int num2 = 8 - num;
			if (list.Count > num2)
			{
				list.RemoveRange(num2, list.Count - num2);
			}
			for (int i = 0; i < num; i++)
			{
				list.Add(tail[i]);
			}
			return list;
		}

		public static HudSideLine Next(string forecast)
		{
			//IL_0003: Unknown result type (might be due to invalid IL or missing references)
			return new HudSideLine(forecast, (HudEffectTone)1, false);
		}

		public static int ChangeStep(string current, Func<int, string> nameAt, int maxSteps)
		{
			if (nameAt == null || string.IsNullOrEmpty(current))
			{
				return 0;
			}
			for (int i = 1; i <= maxSteps; i++)
			{
				string text = nameAt(i);
				if (string.IsNullOrEmpty(text))
				{
					return 0;
				}
				if (WeatherHudRules.ForecastShown(current, text, null))
				{
					return i;
				}
			}
			return 0;
		}

		public static double SecondsToStep(double now, double duration, int step)
		{
			if (duration <= 0.0 || step < 1)
			{
				return 0.0;
			}
			return Math.Max(0.0, (Math.Floor(now / duration) + (double)step) * duration - now);
		}
	}
	internal static class NegotiatedCompression
	{
		private static class Patches
		{
			[HarmonyPatch(typeof(ZNet), "OnNewConnection")]
			[HarmonyPostfix]
			private static void Connected(ZNetPeer peer)
			{
				try
				{
					if (peer?.m_socket != null && peer.m_rpc != null && !(((object)peer.m_socket).GetType() != typeof(ZSteamSocket)))
					{
						Connections.Add(peer.m_socket, peer.m_rpc, Session(peer.m_socket));
					}
				}
				catch (Exception)
				{
				}
			}

			[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
			[HarmonyPostfix]
			private static void Accepted(ZNet __instance, ZRpc rpc)
			{
				try
				{
					CompressionSession compressionSession = Connections.ByRpc(rpc);
					if (compressionSession != null)
					{
						ZNetPeer peer = __instance.GetPeer(rpc);
						if (peer != null && peer.IsReady())
						{
							compressionSession.Accept();
						}
					}
				}
				catch (Exception)
				{
				}
			}

			[HarmonyPatch(typeof(ZSteamSocket), "Send")]
			[HarmonyPrefix]
			private static void Send(ZSteamSocket __instance, ref ZPackage pkg)
			{
				//IL_006b: Unknown result type (might be due to invalid IL or missing references)
				//IL_0071: Expected O, but got Unknown
				try
				{
					if (_on != null && _on.Value && pkg != null)
					{
						CompressionSession compressionSession = Connections.BySocket((ISocket)(object)__instance);
						if (compressionSession != null && compressionSession.CanSend && pkg.Size() >= NegotiatedCompressionRules.Threshold((int)_threshold.Value) && compressionSession.Send(pkg.GetArray(), (int)_threshold.Value, out var wire))
						{
							pkg = new ZPackage(wire);
						}
					}
				}
				catch (Exception)
				{
				}
			}

			[HarmonyPatch(typeof(ZRpc), "HandlePackage")]
			[HarmonyPrefix]
			private static bool Receive(ZRpc __instance, ref ZPackage package, bool __runOriginal = true)
			{
				//IL_008a: Unknown result type (might be due to invalid IL or missing references)
				//IL_0090: Expected O, but got Unknown
				if (!__runOriginal)
				{
					return false;
				}
				bool flag = false;
				bool flag2 = false;
				CompressionSession compressionSession = null;
				try
				{
					compressionSession = Connections.ByRpc(__instance);
					if (compressionSession == null || package == null || package.Size() < 4)
					{
						return true;
					}
					int pos = package.GetPos();
					package.SetPos(0);
					int num = package.ReadInt();
					package.SetPos(pos);
					if (!compressionSession.Reserved(num))
					{
						return true;
					}
					flag = true;
					flag2 = num == EnvelopeHash;
					byte[] package2;
					CompressionSession.Inbound inbound = compressionSession.Receive(package.GetArray(), Now(), out package2);
					if (inbound == CompressionSession.Inbound.Decoded)
					{
						package = new ZPackage(package2);
					}
					return inbound == CompressionSession.Inbound.Decoded || inbound == CompressionSession.Inbound.Pass;
				}
				catch (Exception ex)
				{
					if (flag2)
					{
						compressionSession?.Close("receive exception: " + ex.GetType().Name);
					}
					return !flag;
				}
			}

			[HarmonyPatch(typeof(ZSteamSocket), "Recv")]
			[HarmonyPrefix]
			private static bool ReceiveNext(ZSteamSocket __instance, ref ZPackage __result, bool __runOriginal = true)
			{
				if (!__runOriginal)
				{
					return false;
				}
				CompressionSession compressionSession = Connections.BySocket((ISocket)(object)__instance);
				if (compressionSession == null || compressionSession.CanRead(Now()))
				{
					return true;
				}
				__result = null;
				return false;
			}

			[HarmonyPatch(typeof(ZRpc), "Dispose")]
			[HarmonyPrefix]
			private static void Disposed(ZRpc __instance)
			{
				try
				{
					Connections.Remove(__instance);
				}
				catch (Exception)
				{
				}
			}
		}

		private const string Offer = "MW_World_Compression.Offer.v1";

		private const string Ready = "MW_World_Compression.Ready.v1";

		private const string Envelope = "MW_World_Compression.Frame.v1";

		private static readonly int OfferHash = StringExtensionMethods.GetStableHashCode("MW_World_Compression.Offer.v1");

		private static readonly int ReadyHash = StringExtensionMethods.GetStableHashCode("MW_World_Compression.Ready.v1");

		private static readonly int EnvelopeHash = StringExtensionMethods.GetStableHashCode("MW_World_Compression.Frame.v1");

		private static readonly CompressionTable<ISocket, ZRpc> Connections = new CompressionTable<ISocket, ZRpc>();

		private static Setting<bool> _on;

		private static Setting<float> _threshold;

		public static void Init(Setting<bool> enabled, Setting<float> threshold)
		{
			//IL_0036: Unknown result type (might be due to invalid IL or missing references)
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0055: Expected O, but got Unknown
			_on = enabled;
			_threshold = threshold;
			((Setting)_on).Changed += Changed;
			Harmony val = new Harmony("expdare.meadworks.world.compression");
			val.PatchAll(typeof(Patches));
			LedgerTrack.Patch(val, "world negotiated compression");
			Ledger.Add("world compression connections", (Action)delegate
			{
				((Setting)_on).Changed -= Changed;
				foreach (KeyValuePair<ISocket, CompressionSession> entry in Connections.Entries)
				{
					if (entry.Value.CanReceive)
					{
						try
						{
							entry.Key.Close();
						}
						catch (Exception)
						{
						}
					}
				}
				Connections.Clear();
				_on = null;
				_threshold = null;
			});
		}

		private static void Changed()
		{
			if (_on == null || !_on.Value)
			{
				Connections.WithdrawAll();
			}
		}

		private static double Now()
		{
			return (double)Stopwatch.GetTimestamp() / (double)Stopwatch.Frequency;
		}

		private static CompressionSession Session(ISocket socket)
		{
			return new CompressionSession(_on != null && _on.Value, steamSocket: true, EnvelopeHash, OfferHash, ReadyHash, delegate(byte[] bytes)
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				//IL_0011: Expected O, but got Unknown
				try
				{
					socket.Send(new ZPackage(bytes));
				}
				catch (Exception)
				{
				}
			}, delegate(string reason)
			{
				try
				{
					MwLog.Warn((object)("world compression: closing connection after unreadable data frame: " + reason));
				}
				catch (Exception)
				{
				}
				socket.Close();
			});
		}
	}
	public static class NegotiatedCompressionRules
	{
		public sealed class Peer
		{
			private readonly bool _eligible;

			private bool _offerSent;

			private bool _offerReceived;

			private bool _readySent;

			private bool _readyReceived;

			private bool _stopped;

			private double _decodedAllowance = 8388608.0;

			private double _decodedAt = double.NaN;

			public bool CanSend
			{
				get
				{
					if (!_stopped && _readySent)
					{
						return _readyReceived;
					}
					return false;
				}
			}

			public bool CanReceive => _readySent;

			public bool HasDecodedBytes(int bytes, double nowSeconds)
			{
				if (bytes <= 0 || bytes > 1048576 || double.IsNaN(nowSeconds) || double.IsInfinity(nowSeconds) || nowSeconds < 0.0 || (!double.IsNaN(_decodedAt) && nowSeconds < _decodedAt))
				{
					return false;
				}
				if (!double.IsNaN(_decodedAt))
				{
					_decodedAllowance = Math.Min(8388608.0, _decodedAllowance + (nowSeconds - _decodedAt) * 4194304.0);
				}
				_decodedAt = nowSeconds;
				return (double)bytes <= _decodedAllowance;
			}

			public bool SpendDecodedBytes(int bytes, double nowSeconds)
			{
				if (!HasDecodedBytes(bytes, nowSeconds))
				{
					return false;
				}
				_decodedAllowance -= bytes;
				return true;
			}

			public Peer(bool enabled, bool steamSocket)
			{
				_eligible = enabled && steamSocket;
			}

			public bool TryOffer()
			{
				if (!_eligible || _stopped || _offerSent)
				{
					return false;
				}
				_offerSent = true;
				return true;
			}

			public void ReceiveOffer(int version, bool enabled)
			{
				if (_eligible && !_stopped)
				{
					if (version != 1 || !enabled)
					{
						StopSending();
					}
					else
					{
						_offerReceived = true;
					}
				}
			}

			public bool TryReady()
			{
				if (_stopped || !_offerSent || !_offerReceived || _readySent)
				{
					return false;
				}
				_readySent = true;
				return true;
			}

			public void ReceiveReady(int version)
			{
				if (!_stopped && _offerSent && _offerReceived)
				{
					if (version != 1)
					{
						StopSending();
					}
					else
					{
						_readyReceived = true;
					}
				}
			}

			public void StopSending()
			{
				_stopped = true;
			}
		}

		public const int Version = 1;

		public const int DefaultThreshold = 256;

		public const int MinimumThreshold = 64;

		public const int MaximumThreshold = 65536;

		public const int MaximumPackageBytes = 1048576;

		public const int HeaderBytes = 45;

		public const int DecodedBytesPerSecond = 4194304;

		public const int DecodedBurstBytes = 8388608;

		private const byte DeflateFlag = 1;

		public static int Threshold(int value)
		{
			return Math.Max(64, Math.Min(65536, value));
		}

		public static bool TryEncode(Peer peer, byte[] package, int threshold, out byte[] frame, int envelopeBytes = 0)
		{
			frame = null;
			if (peer == null || !peer.CanSend || package == null || package.Length < Threshold(threshold) || package.Length > 1048576)
			{
				return false;
			}
			try
			{
				byte[] array;
				using (MemoryStream memoryStream = new MemoryStream())
				{
					using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionLevel.Fastest, leaveOpen: true))
					{
						deflateStream.Write(package, 0, package.Length);
					}
					if (memoryStream.Length + 45 + Math.Max(0, envelopeBytes) >= package.Length)
					{
						return false;
					}
					array = memoryStream.ToArray();
				}
				using (MemoryStream memoryStream2 = new MemoryStream(45 + array.Length))
				{
					using BinaryWriter binaryWriter = new BinaryWriter(memoryStream2);
					using SHA256 sHA = SHA256.Create();
					binaryWriter.Write((byte)77);
					binaryWriter.Write((byte)87);
					binaryWriter.Write((byte)67);
					binaryWriter.Write((byte)1);
					binaryWriter.Write((byte)1);
					binaryWriter.Write(package.Length);
					binaryWriter.Write(array.Length);
					binaryWriter.Write(sHA.ComputeHash(package));
					binaryWriter.Write(array);
					frame = memoryStream2.ToArray();
				}
				return true;
			}
			catch (IOException)
			{
				return false;
			}
			catch (CryptographicException)
			{
				return false;
			}
		}

		public static bool TryDecode(Peer peer, byte[] frame, out byte[] package, double nowSeconds = 0.0)
		{
			string reason;
			return TryDecode(peer, frame, out package, out reason, nowSeconds);
		}

		public static bool TryDecode(Peer peer, byte[] frame, out byte[] package, out string reason, double nowSeconds = 0.0)
		{
			package = null;
			reason = "decoder not armed or invalid frame size";
			if (peer == null || !peer.CanReceive || frame == null || frame.Length <= 45 || frame.Length > 1048576)
			{
				return false;
			}
			reason = "invalid frame header, version or flags";
			if (frame[0] != 77 || frame[1] != 87 || frame[2] != 67 || frame[3] != 1 || frame[4] != 1)
			{
				return false;
			}
			try
			{
				using MemoryStream memoryStream = new MemoryStream(frame, writable: false);
				using BinaryReader binaryReader = new BinaryReader(memoryStream);
				memoryStream.Position = 5L;
				int num = binaryReader.ReadInt32();
				int num2 = binaryReader.ReadInt32();
				reason = "invalid declared frame lengths";
				if (num <= 0 || num > 1048576 || num2 != frame.Length - 45)
				{
					return false;
				}
				reason = "decoded-byte allowance exceeded";
				if (!peer.SpendDecodedBytes(num, nowSeconds))
				{
					return false;
				}
				reason = "invalid Deflate data or decoded length";
				byte[] array = binaryReader.ReadBytes(32);
				byte[] array2 = new byte[num];
				using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionMode.Decompress, leaveOpen: true))
				{
					int num3;
					for (int i = 0; i < num; i += num3)
					{
						num3 = deflateStream.Read(array2, i, num - i);
						if (num3 == 0)
						{
							return false;
						}
					}
					if (deflateStream.ReadByte() != -1)
					{
						return false;
					}
				}
				using (SHA256 sHA = SHA256.Create())
				{
					reason = "checksum mismatch";
					byte[] array3 = sHA.ComputeHash(array2);
					for (int j = 0; j < array3.Length; j++)
					{
						if (array3[j] != array[j])
						{
							return false;
						}
					}
				}
				package = array2;
				reason = null;
				return true;
			}
			catch (InvalidDataException)
			{
				return false;
			}
			catch (IOException)
			{
				return false;
			}
			catch (CryptographicException)
			{
				return false;
			}
		}
	}
	internal static class PeerScheduler
	{
		private sealed class PeerState
		{
			public readonly PeerSchedulerRules.Queue<ZDOID> Queue = new PeerSchedulerRules.Queue<ZDOID>();

			public readonly List<ZDO> Candidates = new List<ZDO>();

			public readonly List<PeerSchedulerRules.Candidate<ZDOID>> Ranked = new List<PeerSchedulerRules.Candidate<ZDOID>>();
		}

		private static class Patches
		{
			[HarmonyPatch(typeof(ZDOMan), "CreateSyncList")]
			[HarmonyPostfix]
			private static void SyncList(ZDOPeer peer, List<ZDO> toSync)
			{
				Order(peer, toSync);
			}

			[HarmonyPatch(typeof(ZDOMan), "SendZDOs")]
			[HarmonyPostfix]
			private static void Sent(ZDOPeer peer)
			{
				//IL_003d: Unknown result type (might be due to invalid IL or missing references)
				if (!Active || !_peers.TryGetValue(peer, out var value))
				{
					return;
				}
				foreach (ZDO candidate in value.Candidates)
				{
					if (!peer.ShouldSend(candidate))
					{
						value.Queue.Sent(candidate.m_uid);
					}
				}
				_lastPending = value.Queue.Count;
			}

			[HarmonyPatch(typeof(ZDOMan), "ShutDown")]
			[HarmonyPostfix]
			private static void Shutdown()
			{
				Reset();
			}
		}

		private static Setting<bool> _on;

		private static Setting<float> _wait;

		private static Setting<float> _boost;

		private static ConditionalWeakTable<ZDOPeer, PeerState> _peers = new ConditionalWeakTable<ZDOPeer, PeerState>();

		private static readonly Dictionary<int, bool> Vehicles = new Dictionary<int, bool>();

		private static int _rounds;

		private static int _lastPending;

		public static bool Active
		{
			get
			{
				if ((Object)(object)ZNet.instance != (Object)null)
				{
					return PeerSchedulerRules.ShouldSchedule(_on != null && _on.Value, ZNet.instance.IsServer());
				}
				return false;
			}
		}

		public static void Init(SettingsPage page)
		{
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Expected O, but got Unknown
			_on = page.Toggle("peer_scheduler", "Prioritize ZDO updates per player", false, (SettingPolicy)1, true);
			_wait = page.Slider("peer_scheduler_wait", "ZDO maximum priority wait (seconds)", 5f, 1f, 30f, 1f, (SettingPolicy)1, true);
			_boost = page.Slider("peer_scheduler_boost", "ZDO priority distance boost (meters)", 100f, 0f, 500f, 10f, (SettingPolicy)1, true);
			((Setting)_on).Changed += Reset;
			Harmony val = new Harmony("expdare.meadworks.world.peerscheduler");
			val.PatchAll(typeof(Patches));
			LedgerTrack.Patch(val, "world peer scheduler");
			Ledger.Add("world peer scheduler state", (Action)delegate
			{
				((Setting)_on).Changed -= Reset;
				_on = null;
				_wait = (_boost = null);
				Reset();
			});
		}

		private static void Reset()
		{
			_peers = new ConditionalWeakTable<ZDOPeer, PeerState>();
			Vehicles.Clear();
			_rounds = (_lastPending = 0);
		}

		public static string Status()
		{
			return "scheduler active=" + Active + " on=" + (_on != null && _on.Value) + " rounds=" + _rounds + " lastPending=" + _lastPending;
		}

		private static bool IsVehicle(ZDO zdo)
		{
			int prefab = zdo.GetPrefab();
			if (Vehicles.TryGetValue(prefab, out var value))
			{
				return value;
			}
			GameObject val = (((Object)(object)ZNetScene.instance != (Object)null) ? ZNetScene.instance.GetPrefab(prefab) : null);
			if ((Object)(object)val == (Object)null)
			{
				return false;
			}
			value = (Object)(object)val.GetComponent<Ship>() != (Object)null || (Object)(object)val.GetComponent<Vagon>() != (Object)null;
			Vehicles.Add(prefab, value);
			return value;
		}

		private static void Order(ZDOPeer peer, List<ZDO> toSync)
		{
			//IL_004e: 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_0078: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0131: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Invalid comparison between Unknown and I4
			//IL_01da: Unknown result type (might be due to invalid IL or missing references)
			//IL_01df: Unknown result type (might be due to invalid IL or missing references)
			if (Active)
			{
				PeerState value = _peers.GetValue(peer, (ZDOPeer _) => new PeerState());
				List<PeerSchedulerRules.Candidate<ZDOID>> ranked = value.Ranked;
				ranked.Clear();
				float time = Time.time;
				ZNetPeer peer2 = peer.m_peer;
				Vector3 refPos = peer2.GetRefPos();
				int num;
				for (num = 0; num < toSync.Count && peer.m_forceSend.Contains(toSync[num].m_uid); num++)
				{
				}
				for (int num2 = 0; num2 < toSync.Count; num2++)
				{
					ZDO val = toSync[num2];
					PeerZDOInfo value2;
					bool flag = peer.m_zdos.TryGetValue(val.m_uid, out value2);
					float num3 = (flag ? Math.Max(0f, Math.Min(100f, time - value2.m_syncTime)) : 100f);
					bool flag2 = val.GetBool(ZDOVars.s_tamed, false);
					ranked.Add(new PeerSchedulerRules.Candidate<ZDOID>
					{
						Id = val.m_uid,
						Revision = (((ulong)val.OwnerRevision << 32) | val.DataRevision),
						Known = flag,
						Forced = (num2 < num),
						VanillaPriority = ((int)val.Type == 1 && val.HasOwner() && val.GetOwner() != peer2.m_uid),
						Relevant = PeerSchedulerRules.Relevant(peer2.m_uid, val.GetOwner(), peer2.m_playerID, val.GetLong(ZDOVars.s_user, 0L), peer2.m_playerName, flag2 ? val.GetString(ZDOVars.s_follow, "") : null, IsVehicle(val), flag2),
						Combat = (val.GetBool(ZDOVars.s_alert, false) || val.GetBool(ZDOVars.s_haveTargetHash, false)),
						DistanceScore = (double)Vector3.Distance(val.GetPosition(), refPos) - (double)num3 * 1.5
					});
				}
				int[] array = value.Queue.Order(ranked, time, _wait.Value, _boost.Value);
				value.Candidates.Clear();
				value.Candidates.AddRange(toSync);
				for (int num4 = 0; num4 < array.Length; num4++)
				{
					toSync[num4] = value.Candidates[array[num4]];
				}
				_lastPending = value.Queue.Count;
				_rounds++;
			}
		}
	}
	public static class PeerSchedulerRules
	{
		public struct Candidate<TKey>
		{
			public TKey Id;

			public ulong Revision;

			public bool Known;

			public bool Forced;

			public bool VanillaPriority;

			public bool Relevant;

			public bool Combat;

			public double DistanceScore;
		}

		public sealed class Queue<TKey>
		{
			private sealed class Pending
			{
				public double Since;

				public double Changed;

				public long Ticket;

				public ulong Revision;
			}

			private struct Key
			{
				public bool Forced;

				public bool Old;

				public long Ticket;

				public int Priority;

				public double Score;
			}

			private sealed class ByKey : IComparer<int>
			{
				public Key[] Keys;

				public int Compare(int a, int b)
				{
					Key key = Keys[a];
					Key key2 = Keys[b];
					if (key.Forced != key2.Forced)
					{
						if (!key.Forced)
						{
							return 1;
						}
						return -1;
					}
					if (key.Forced)
					{
						return a.CompareTo(b);
					}
					if (key.Old != key2.Old)
					{
						if (!key.Old)
						{
							return 1;
						}
						return -1;
					}
					if (key.Old)
					{
						int num = key.Ticket.CompareTo(key2.Ticket);
						if (num == 0)
						{
							return a.CompareTo(b);
						}
						return num;
					}
					int num2 = key2.Priority.CompareTo(key.Priority);
					if (num2 != 0)
					{
						return num2;
					}
					if (key.Priority == 0)
					{
						return a.CompareTo(b);
					}
					int num3 = key.Score.CompareTo(key2.Score);
					if (num3 == 0)
					{
						return a.CompareTo(b);
					}
					return num3;
				}
			}

			private readonly Dictionary<TKey, Pending> _pending = new Dictionary<TKey, Pending>();

			private readonly HashSet<TKey> _present = new HashSet<TKey>();

			private readonly List<TKey> _gone = new List<TKey>();

			private readonly ByKey _byKey = new ByKey();

			private Key[] _keys = Array.Empty<Key>();

			private int[] _order = Array.Empty<int>();

			private long _ticket;

			public int Count => _pending.Count;

			public void Sent(TKey id)
			{
				_pending.Remove(id);
			}

			public int[] Order(IReadOnlyList<Candidate<TKey>> candidates, double now, double maxWait, double boost)
			{
				maxWait = Math.Max(1.0, Math.Min(30.0, maxWait));
				boost = Math.Max(0.0, Math.Min(500.0, boost));
				int count = candidates.Count;
				if (_order.Length != count)
				{
					_order = new int[count];
					_keys = new Key[count];
				}
				_present.Clear();
				for (int i = 0; i < count; i++)
				{
					Candidate<TKey> candidate = candidates[i];
					_present.Add(candidate.Id);
					if (!_pending.TryGetValue(candidate.Id, out var value))
					{
						value = new Pending
						{
							Since = now,
							Ticket = _ticket++,
							Revision = candidate.Revision,
							Changed = (candidate.Known ? now : double.NegativeInfinity)
						};
						_pending.Add(candidate.Id, value);
					}
					else if (value.Revision != candidate.Revision)
					{
						value.Revision = candidate.Revision;
						value.Changed = now;
					}
					bool flag = now - value.Changed < 2.0;
					_keys[i].Forced = candidate.Forced;
					_keys[i].Old = now - value.Since >= maxWait;
					_keys[i].Ticket = value.Ticket;
					_keys[i].Priority = (candidate.VanillaPriority ? 2 : ((candidate.Relevant || candidate.Combat || flag) ? 1 : 0));
					_keys[i].Score = candidate.DistanceScore - boost * ((double)((candidate.Relevant ? 1 : 0) + (candidate.Combat ? 1 : 0)) + (flag ? 0.5 : 0.0));
					_order[i] = i;
				}
				_gone.Clear();
				foreach (TKey key in _pending.Keys)
				{
					if (!_present.Contains(key))
					{
						_gone.Add(key);
					}
				}
				for (int j = 0; j < _gone.Count; j++)
				{
					_pending.Remove(_gone[j]);
				}
				_byKey.Keys = _keys;
				if (count > 1)
				{
					Array.Sort(_order, 0, count, _byKey);
				}
				return _order;
			}
		}

		public const float DefaultMaxWait = 5f;

		public const float DefaultBoost = 100f;

		public const float RecentSeconds = 2f;

		public static bool ShouldSchedule(bool enabled, bool server)
		{
			return enabled && server;
		}

		public static bool Relevant(long peer, long owner, long player, long user, string name, string follow, bool vehicle, bool tamed)
		{
			if ((peer == 0L || peer != owner || !(vehicle || tamed)) && (!vehicle || player == 0L || player != user))
			{
				if (tamed && !string.IsNullOrEmpty(name))
				{
					return name == follow;
				}
				return false;
			}
			return true;
		}
	}
	internal static class PlayerCap
	{
		private static class Patches
		{
			[HarmonyPatch(typeof(ZNet), "Awake")]
			[HarmonyPrefix]
			private static void Begin()
			{
				//IL_0018: Unknown result type (might be due to invalid IL or missing references)
				//IL_001e: Invalid comparison between Unknown and I4
				_sessionCap = PlayerCapRules.Limit((_cap == null) ? 10f : _cap.Value, (int)ZNet.m_onlineBackend == 1);
			}

			[HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")]
			[HarmonyTranspiler]
			private static IEnumerable<CodeInstruction> Admission(IEnumerable<CodeInstruction> instructions)
			{
				List<CodeInstruction> code = instructions.ToList();
				MethodInfo count = AccessTools.Method(typeof(ZNet), "GetNrOfPlayers", (Type[])null, (Type[])null);
				int[] array = (from i in Enumerable.Range(1, code.Count - 1)
					where CodeInstructionExtensions.Calls(code[i - 1], count) && CodeInstructionExtensions.LoadsConstant(code[i], 10L)
					select i).ToArray();
				if (array.Length != 1)
				{
					MwLog.Warn((object)"world: player cap admission shape changed; keeping native limit");
					return code;
				}
				CodeInstruction obj = code[array[0]];
				obj.opcode = OpCodes.Call;
				obj.operand = AccessTools.Method(typeof(PlayerCap), "Limit", (Type[])null, (Type[])null);
				return code;
			}

			[HarmonyPatch(typeof(ZSteamMatchmaking), "RegisterServer")]
			[HarmonyTranspiler]
			private static IEnumerable<CodeInstruction> Lobby(IEnumerable<CodeInstruction> instructions)
			{
				List<CodeInstruction> code = instructions.ToList();
				MethodInfo create = AccessTools.Method(typeof(SteamMatchmaking), "CreateLobby", (Type[])null, (Type[])null);
				int[] array = (from i in Enumerable.Range(0, code.Count - 1)
					where CodeInstructionExtensions.LoadsConstant(code[i], 10L) && CodeInstructionExtensions.Calls(code[i + 1], create)
					select i).ToArray();
				if (array.Length != 1)
				{
					MwLog.Warn((object)"world: player cap lobby shape changed; keeping native lobby");
					return code;
				}
				CodeInstruction obj = code[array[0]];
				obj.opcode = OpCodes.Call;
				obj.operand = AccessTools.Method(typeof(PlayerCap), "Limit", (Type[])null, (Type[])null);
				return code;
			}
		}

		private static Setting<float> _cap;

		private static int _sessionCap = 10;

		public static void Init(SettingsPage page)
		{
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			_cap = page.Slider("player_cap", "Player limit", 10f, 1f, 64f, 1f, (SettingPolicy)1, false);
			Harmony val = new Harmony("expdare.meadworks.world.playercap");
			LedgerTrack.Patch(val, "world player cap");
			val.PatchAll(typeof(Patches));
			Ledger.Add("world player cap state", (Action)delegate
			{
				_cap = null;
				_sessionCap = 10;
			});
		}

		private static int Limit()
		{
			return _sessionCap;
		}
	}
	public static class PlayerCapRules
	{
		public static int Limit(float configured, bool crossplay)
		{
			if (!crossplay && !float.IsNaN(configured) && !float.IsInfinity(configured))
			{
				return Math.Max(1, Math.Min(64