Decompiled source of WeatherRegistry v0.1.10

WeatherRegistry.dll

Decompiled 5 hours ago
using System;
using System.Collections.Generic;
using System.Data;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Cryptography;
using System.Security.Permissions;
using System.Text;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using ConsoleTables;
using HarmonyLib;
using LethalLib.Modules;
using LobbyCompatibility.Enums;
using LobbyCompatibility.Features;
using Microsoft.CodeAnalysis;
using Mono.Cecil.Cil;
using MonoMod.Cil;
using MonoMod.RuntimeDetour;
using Newtonsoft.Json;
using On;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.ProBuilder;
using WeatherRegistry.Events;
using WeatherRegistry.NetcodePatcher;
using WeatherRegistry.Patches;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: IgnoresAccessChecksTo("AmazingAssets.TerrainToMesh")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp-firstpass")]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: IgnoresAccessChecksTo("ClientNetworkTransform")]
[assembly: IgnoresAccessChecksTo("DissonanceVoip")]
[assembly: IgnoresAccessChecksTo("Facepunch Transport for Netcode for GameObjects")]
[assembly: IgnoresAccessChecksTo("Facepunch.Steamworks.Win64")]
[assembly: IgnoresAccessChecksTo("Unity.AI.Navigation")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging")]
[assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging.DocCodeExamples")]
[assembly: IgnoresAccessChecksTo("Unity.Burst")]
[assembly: IgnoresAccessChecksTo("Unity.Burst.Unsafe")]
[assembly: IgnoresAccessChecksTo("Unity.Collections")]
[assembly: IgnoresAccessChecksTo("Unity.Collections.LowLevel.ILSupport")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem")]
[assembly: IgnoresAccessChecksTo("Unity.InputSystem.ForUI")]
[assembly: IgnoresAccessChecksTo("Unity.Jobs")]
[assembly: IgnoresAccessChecksTo("Unity.Mathematics")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.Common")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.MetricTypes")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStats")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Component")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Implementation")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsReporting")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkProfiler.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkSolutionInterface")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Components")]
[assembly: IgnoresAccessChecksTo("Unity.Netcode.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.Networking.Transport")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Csg")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.KdTree")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Poly2Tri")]
[assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Stl")]
[assembly: IgnoresAccessChecksTo("Unity.Profiling.Core")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.ShaderLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Config.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Runtime")]
[assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.ShaderGraph.ShaderGraphLibrary")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Authentication")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Analytics")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Configuration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Device")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Internal")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Networking")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Registration")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Scheduler")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Telemetry")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Core.Threading")]
[assembly: IgnoresAccessChecksTo("Unity.Services.QoS")]
[assembly: IgnoresAccessChecksTo("Unity.Services.Relay")]
[assembly: IgnoresAccessChecksTo("Unity.TextMeshPro")]
[assembly: IgnoresAccessChecksTo("Unity.Timeline")]
[assembly: IgnoresAccessChecksTo("Unity.VisualEffectGraph.Runtime")]
[assembly: IgnoresAccessChecksTo("UnityEngine.ARModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.NVIDIAModule")]
[assembly: IgnoresAccessChecksTo("UnityEngine.UI")]
[assembly: AssemblyCompany("WeatherRegistry")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("A Weather API for Lethal Company.")]
[assembly: AssemblyFileVersion("0.1.10.0")]
[assembly: AssemblyInformationalVersion("0.1.10+a8361cac1049379eaadf120fa4a5645b1ec7ae28")]
[assembly: AssemblyProduct("WeatherRegistry")]
[assembly: AssemblyTitle("WeatherRegistry")]
[assembly: AssemblyMetadata("RepositoryUrl", "https://github.com/AndreyMrovol/LethalWeatherRegistry/")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
[module: NetcodePatchedAssembly]
internal class <Module>
{
	static <Module>()
	{
		NetworkVariableSerializationTypes.InitializeSerializer_FixedString<FixedString4096Bytes>();
		NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedIEquatable<FixedString4096Bytes>();
	}
}
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.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 ConsoleTables
{
	public class ConsoleTable
	{
		public static readonly HashSet<Type> NumericTypes = new HashSet<Type>
		{
			typeof(int),
			typeof(double),
			typeof(decimal),
			typeof(long),
			typeof(short),
			typeof(sbyte),
			typeof(byte),
			typeof(ulong),
			typeof(ushort),
			typeof(uint),
			typeof(float)
		};

		public IList<object> Columns { get; }

		public IList<object[]> Rows { get; }

		public ConsoleTableOptions Options { get; }

		public Type[] ColumnTypes { get; private set; }

		public IList<string> Formats { get; private set; }

		public ConsoleTable(params string[] columns)
			: this(new ConsoleTableOptions
			{
				Columns = new List<string>(columns)
			})
		{
		}

		public ConsoleTable(ConsoleTableOptions options)
		{
			Options = options ?? throw new ArgumentNullException("options");
			Rows = new List<object[]>();
			Columns = new List<object>(options.Columns);
		}

		public ConsoleTable AddColumn(IEnumerable<string> names)
		{
			foreach (string name in names)
			{
				Columns.Add(name);
			}
			return this;
		}

		public ConsoleTable AddRow(params object[] values)
		{
			if (values == null)
			{
				throw new ArgumentNullException("values");
			}
			if (!Columns.Any())
			{
				throw new Exception("Please set the columns first");
			}
			if (Columns.Count != values.Length)
			{
				throw new Exception($"The number columns in the row ({Columns.Count}) does not match the values ({values.Length})");
			}
			Rows.Add(values);
			return this;
		}

		public ConsoleTable Configure(Action<ConsoleTableOptions> action)
		{
			action(Options);
			return this;
		}

		public static ConsoleTable FromDictionary(Dictionary<string, Dictionary<string, object>> values)
		{
			ConsoleTable consoleTable = new ConsoleTable();
			List<string> list = values.SelectMany((KeyValuePair<string, Dictionary<string, object>> x) => x.Value.Keys).Distinct().ToList();
			list.Insert(0, "");
			consoleTable.AddColumn(list);
			foreach (KeyValuePair<string, Dictionary<string, object>> value2 in values)
			{
				List<object> list2 = new List<object> { value2.Key };
				foreach (string item in list.Skip(1))
				{
					list2.Add(value2.Value.TryGetValue(item, out var value) ? value : "");
				}
				consoleTable.AddRow(list2.Cast<object>().ToArray());
			}
			return consoleTable;
		}

		public static ConsoleTable From<T>(IEnumerable<T> values)
		{
			ConsoleTable consoleTable = new ConsoleTable
			{
				ColumnTypes = GetColumnsType<T>().ToArray()
			};
			List<string> columns = GetColumns<T>().ToList();
			consoleTable.AddColumn(columns);
			foreach (IEnumerable<object> item in values.Select((T value) => columns.Select((string column) => GetColumnValue<T>(value, column))))
			{
				consoleTable.AddRow(item.ToArray());
			}
			return consoleTable;
		}

		public static ConsoleTable From(DataTable dataTable)
		{
			ConsoleTable consoleTable = new ConsoleTable();
			List<string> names = (from DataColumn x in dataTable.Columns
				select x.ColumnName).ToList();
			consoleTable.AddColumn(names);
			foreach (DataRow row in dataTable.Rows)
			{
				string[] array = row.ItemArray.Select((object x) => (!(x is byte[] inArray)) ? x.ToString() : Convert.ToBase64String(inArray)).ToArray();
				object[] values = array;
				consoleTable.AddRow(values);
			}
			return consoleTable;
		}

		public override string ToString()
		{
			StringBuilder stringBuilder = new StringBuilder();
			List<int> columnLengths = ColumnLengths();
			List<string> columnAlignment = Enumerable.Range(0, Columns.Count).Select(GetNumberAlignment).ToList();
			string format = (from i in Enumerable.Range(0, Columns.Count)
				select " | {" + i + "," + columnAlignment[i] + columnLengths[i] + "}").Aggregate((string s, string a) => s + a) + " |";
			SetFormats(ColumnLengths(), columnAlignment);
			int val = Math.Max(0, Rows.Any() ? Rows.Max((object[] row) => string.Format(format, row).Length) : 0);
			string text = string.Format(Formats[0], Columns.ToArray());
			int num = Math.Max(val, text.Length);
			List<string> list = Rows.Select((object[] row, int i) => string.Format(Formats[i + 1], row)).ToList();
			string value = " " + string.Join("", Enumerable.Repeat("-", num - 1)) + " ";
			stringBuilder.AppendLine(value);
			stringBuilder.AppendLine(text);
			foreach (string item in list)
			{
				stringBuilder.AppendLine(value);
				stringBuilder.AppendLine(item);
			}
			stringBuilder.AppendLine(value);
			if (Options.EnableCount)
			{
				stringBuilder.AppendLine("");
				stringBuilder.AppendFormat(" Count: {0}", Rows.Count);
			}
			return stringBuilder.ToString();
		}

		private void SetFormats(List<int> columnLengths, List<string> columnAlignment)
		{
			List<object[]> list = new List<object[]>();
			list.Add(Columns.ToArray());
			list.AddRange(Rows);
			Formats = list.Select((object[] d) => Enumerable.Range(0, Columns.Count).Select(delegate(int i)
			{
				string text = d[i]?.ToString() ?? "";
				int num = columnLengths[i] - (GetTextWidth(text) - text.Length);
				return " | {" + i + "," + columnAlignment[i] + num + "}";
			}).Aggregate((string s, string a) => s + a) + " |").ToList();
		}

		public static int GetTextWidth(string value)
		{
			return value?.ToCharArray().Sum((char c) => (c <= '\u007f') ? 1 : 2) ?? 0;
		}

		public string ToMarkDownString()
		{
			return ToMarkDownString('|');
		}

		private string ToMarkDownString(char delimiter)
		{
			StringBuilder builder = new StringBuilder();
			List<int> columnLengths = ColumnLengths();
			Format(columnLengths, delimiter);
			string text = string.Format(Formats[0].TrimStart(), Columns.ToArray());
			List<string> list = Rows.Select((object[] row, int i) => string.Format(Formats[i + 1].TrimStart(), row)).ToList();
			string value = Regex.Replace(text, "[^|]", "-");
			builder.AppendLine(text);
			builder.AppendLine(value);
			list.ForEach(delegate(string row)
			{
				builder.AppendLine(row);
			});
			return builder.ToString();
		}

		public string ToMinimalString()
		{
			return ToMarkDownString('\0');
		}

		public string ToStringAlternative()
		{
			StringBuilder stringBuilder = new StringBuilder();
			string text = string.Format(Formats[0].TrimStart(), Columns.ToArray());
			List<string> list = Rows.Select((object[] row, int i) => string.Format(Formats[i + 1].TrimStart(), row)).ToList();
			string value = Regex.Replace(text, "[^| ]", "-").Replace("|", "+");
			stringBuilder.AppendLine(value);
			stringBuilder.AppendLine(text);
			foreach (string item in list)
			{
				stringBuilder.AppendLine(value);
				stringBuilder.AppendLine(item);
			}
			stringBuilder.AppendLine(value);
			return stringBuilder.ToString();
		}

		private string Format(List<int> columnLengths, char delimiter = '|')
		{
			List<string> columnAlignment = Enumerable.Range(0, Columns.Count).Select(GetNumberAlignment).ToList();
			SetFormats(columnLengths, columnAlignment);
			string delimiterStr = ((delimiter == '\0') ? string.Empty : delimiter.ToString());
			return ((from i in Enumerable.Range(0, Columns.Count)
				select " " + delimiterStr + " {" + i + "," + columnAlignment[i] + columnLengths[i] + "}").Aggregate((string s, string a) => s + a) + " " + delimiterStr).Trim();
		}

		private string GetNumberAlignment(int i)
		{
			if (Options.NumberAlignment != Alignment.Right || ColumnTypes == null || !NumericTypes.Contains(ColumnTypes[i]))
			{
				return "-";
			}
			return "";
		}

		private List<int> ColumnLengths()
		{
			return Columns.Select((object t, int i) => (from x in Rows.Select((object[] x) => x[i]).Union(new object[1] { Columns[i] })
				where x != null
				select x.ToString().ToCharArray().Sum((char c) => (c <= '\u007f') ? 1 : 2)).Max()).ToList();
		}

		public void Write(Format format = ConsoleTables.Format.Default)
		{
			SetFormats(ColumnLengths(), Enumerable.Range(0, Columns.Count).Select(GetNumberAlignment).ToList());
			switch (format)
			{
			case ConsoleTables.Format.Default:
				Options.OutputTo.WriteLine(ToString());
				break;
			case ConsoleTables.Format.MarkDown:
				Options.OutputTo.WriteLine(ToMarkDownString());
				break;
			case ConsoleTables.Format.Alternative:
				Options.OutputTo.WriteLine(ToStringAlternative());
				break;
			case ConsoleTables.Format.Minimal:
				Options.OutputTo.WriteLine(ToMinimalString());
				break;
			default:
				throw new ArgumentOutOfRangeException("format", format, null);
			}
		}

		private static IEnumerable<string> GetColumns<T>()
		{
			return (from x in typeof(T).GetProperties()
				select x.Name).ToArray();
		}

		private static object GetColumnValue<T>(object target, string column)
		{
			return typeof(T).GetProperty(column)?.GetValue(target, null);
		}

		private static IEnumerable<Type> GetColumnsType<T>()
		{
			return (from x in typeof(T).GetProperties()
				select x.PropertyType).ToArray();
		}
	}
	public class ConsoleTableOptions
	{
		public IEnumerable<string> Columns { get; set; } = new List<string>();


		public bool EnableCount { get; set; } = true;


		public Alignment NumberAlignment { get; set; }

		public TextWriter OutputTo { get; set; } = Console.Out;

	}
	public enum Format
	{
		Default,
		MarkDown,
		Alternative,
		Minimal
	}
	public enum Alignment
	{
		Left,
		Right
	}
}
namespace WeatherRegistry
{
	public class Rarity
	{
		private int _weight;

		public int Weight
		{
			get
			{
				return _weight;
			}
			set
			{
				_weight = Math.Clamp(value, 0, 10000);
			}
		}
	}
	public class NameRarity : Rarity
	{
		public string Name { get; set; }
	}
	public class LevelRarity : Rarity
	{
		public SelectableLevel Level { get; set; }
	}
	public class WeatherRarity : Rarity
	{
		public Weather Weather { get; set; }
	}
	public abstract class ConfigHandler<T, CT>
	{
		internal ConfigEntry<CT> ConfigEntry { get; }

		internal CT DefaultValue { get; }

		public abstract T Value { get; }

		public ConfigHandler(CT defaultValue, Weather weather, string configTitle, ConfigDescription configDescription = null)
		{
			DefaultValue = defaultValue;
			string text = "Weather: " + ((Object)weather).name + ((weather.Origin != 0) ? $" ({weather.Origin})" : "");
			ConfigEntry = ConfigManager.configFile.Bind<CT>(text, configTitle, DefaultValue, configDescription);
		}
	}
	public class LevelListConfigHandler : ConfigHandler<SelectableLevel[], string>
	{
		public override SelectableLevel[] Value => ConfigHelper.ConvertStringToLevels(base.ConfigEntry.Value);

		public LevelListConfigHandler(string defaultValue, Weather weather, string configTitle, ConfigDescription configDescription)
			: base(defaultValue, weather, configTitle, configDescription)
		{
		}
	}
	public class LevelWeightsConfigHandler : ConfigHandler<LevelRarity[], string>
	{
		public override LevelRarity[] Value => ConfigHelper.ConvertStringToLevelRarities(base.ConfigEntry.Value);

		public LevelWeightsConfigHandler(string defaultValue, Weather weather, string configTitle, ConfigDescription configDescription)
			: base(defaultValue, weather, configTitle, configDescription)
		{
		}
	}
	public class WeatherWeightsConfigHandler : ConfigHandler<WeatherRarity[], string>
	{
		public override WeatherRarity[] Value => ConfigHelper.ConvertStringToWeatherWeights(base.ConfigEntry.Value);

		public WeatherWeightsConfigHandler(string defaultValue, Weather weather, string configTitle, ConfigDescription configDescription)
			: base(defaultValue, weather, configTitle, configDescription)
		{
		}
	}
	public class IntegerConfigHandler : ConfigHandler<int, int>
	{
		public override int Value => base.ConfigEntry.Value;

		public IntegerConfigHandler(int defaultValue, Weather weather, string configTitle, ConfigDescription configDescription)
			: base(defaultValue, weather, configTitle, configDescription)
		{
		}
	}
	public class FloatConfigHandler : ConfigHandler<float, float>
	{
		public override float Value => base.ConfigEntry.Value;

		public FloatConfigHandler(float defaultValue, Weather weather, string configTitle, ConfigDescription configDescription)
			: base(defaultValue, weather, configTitle, configDescription)
		{
		}
	}
	internal class ConfigHelper
	{
		private static Dictionary<string, SelectableLevel> _levelsDictionary;

		private static Dictionary<string, Weather> _weathersDictionary;

		public static Dictionary<string, SelectableLevel> StringToLevel
		{
			get
			{
				if (_levelsDictionary != null)
				{
					return _levelsDictionary;
				}
				Dictionary<string, SelectableLevel> Levels = new Dictionary<string, SelectableLevel>();
				StartOfRound.Instance.levels.ToList().ForEach(delegate(SelectableLevel level)
				{
					Levels.TryAdd(GetNumberlessName(level).ToLower(), level);
					Levels.TryAdd(level.PlanetName.ToLower(), level);
					Levels.TryAdd(((Object)level).name.ToLower(), level);
				});
				_levelsDictionary = Levels;
				return Levels;
			}
			set
			{
				_levelsDictionary = value;
			}
		}

		public static Dictionary<string, Weather> StringToWeather
		{
			get
			{
				if (_weathersDictionary != null)
				{
					return _weathersDictionary;
				}
				Dictionary<string, Weather> Weathers = new Dictionary<string, Weather>();
				WeatherManager.Weathers.ToList().ForEach(delegate(Weather weather)
				{
					//IL_0037: Unknown result type (might be due to invalid IL or missing references)
					//IL_003d: Expected I4, but got Unknown
					Weathers.TryAdd(((Object)weather).name.ToLower(), weather);
					Weathers.TryAdd(weather.Name.ToLower(), weather);
					Weathers.TryAdd(((int)weather.VanillaWeatherType).ToString(), weather);
				});
				_weathersDictionary = Weathers;
				return Weathers;
			}
			set
			{
				_weathersDictionary = value;
			}
		}

		public static SelectableLevel ResolveStringToLevel(string str)
		{
			return StringToLevel.GetValueOrDefault(str.ToLower());
		}

		public static Weather ResolveStringToWeather(string str)
		{
			return StringToWeather.GetValueOrDefault(str.ToLower());
		}

		public static string GetNumberlessName(SelectableLevel level)
		{
			return new string(level.PlanetName.SkipWhile((char c) => !char.IsLetter(c)).ToArray());
		}

		public static string[] ConvertStringToArray(string str)
		{
			return (from s in str.Split(';')
				where !string.IsNullOrWhiteSpace(s)
				select s.Trim()).ToArray();
		}

		public static SelectableLevel[] ConvertStringToLevels(string str)
		{
			string[] array = ConvertStringToArray(str);
			List<SelectableLevel> list = new List<SelectableLevel>();
			if (array.Count() == 0)
			{
				return Array.Empty<SelectableLevel>();
			}
			string[] array2 = array;
			foreach (string text in array2)
			{
				SelectableLevel val = ResolveStringToLevel(text);
				Plugin.logger.LogDebug((object)$"String {text} resolved to selectable level: {val} (is null: {(Object)(object)val == (Object)null})");
				if (!list.Contains(val))
				{
					list.Add(val);
				}
			}
			return list.ToArray();
		}

		public static NameRarity[] ConvertStringToRarities(string str)
		{
			string[] array = ConvertStringToArray(str);
			List<NameRarity> list = new List<NameRarity>();
			string[] array2 = array;
			for (int i = 0; i < array2.Length; i++)
			{
				string[] array3 = array2[i].Split(':');
				if (array3.Length == 2 && int.TryParse(array3[1], out var result))
				{
					list.Add(new NameRarity
					{
						Name = array3[0],
						Weight = result
					});
				}
			}
			return list.ToArray();
		}

		public static LevelRarity[] ConvertStringToLevelRarities(string str)
		{
			string[] array = ConvertStringToArray(str);
			List<LevelRarity> list = new List<LevelRarity>();
			string[] array2 = array;
			for (int i = 0; i < array2.Length; i++)
			{
				string[] array3 = array2[i].Split('@');
				if (array3.Length == 2 && int.TryParse(array3[1], out var result))
				{
					SelectableLevel val = ResolveStringToLevel(array3[0]);
					if (!((Object)(object)val == (Object)null))
					{
						list.Add(new LevelRarity
						{
							Level = val,
							Weight = result
						});
					}
				}
			}
			return list.ToArray();
		}

		public static WeatherRarity[] ConvertStringToWeatherWeights(string str)
		{
			string[] array = ConvertStringToArray(str);
			List<WeatherRarity> list = new List<WeatherRarity>();
			string[] array2 = array;
			for (int i = 0; i < array2.Length; i++)
			{
				string[] array3 = array2[i].Split('@');
				if (array3.Length == 2 && int.TryParse(array3[1], out var result))
				{
					Weather weather = ResolveStringToWeather(array3[0]);
					if (!((Object)(object)weather == (Object)null))
					{
						list.Add(new WeatherRarity
						{
							Weather = weather,
							Weight = result
						});
					}
				}
			}
			return list.ToArray();
		}
	}
	public class ConfigManager
	{
		internal static ConfigFile configFile;

		public static ConfigManager Instance { get; private set; }

		public static ConfigEntry<bool> LogWeatherChanges { get; private set; }

		public static ConfigEntry<bool> LogStartup { get; private set; }

		public static ConfigEntry<bool> ColoredWeathers { get; private set; }

		private static ConfigEntry<string> SunAnimatorBlacklist { get; set; }

		public static SelectableLevel[] SunAnimatorBlacklistLevels { get; internal set; }

		public static void Init(ConfigFile config)
		{
			Instance = new ConfigManager(config);
		}

		private ConfigManager(ConfigFile config)
		{
			configFile = config;
			EventManager.SetupFinished.AddListener(StartupActions);
			LogWeatherChanges = configFile.Bind<bool>("|Debugging", "Log Weather Changes", true, "Log weather changes to console");
			LogStartup = configFile.Bind<bool>("|Debugging", "Log Startup", true, "Log startup information to console");
			ColoredWeathers = configFile.Bind<bool>("|General", "Colored Weathers", true, "Enable colored weathers in map screen");
			SunAnimatorBlacklist = configFile.Bind<string>("|SunAnimator", "Blacklist", "Asteroid-13;", "Semicolon-separated list of level names to blacklist from being patched by sun animator");
		}

		private static void OnConfigChange(object sender, EventArgs eventArgs)
		{
			SunAnimatorBlacklistLevels = ConfigHelper.ConvertStringToLevels(SunAnimatorBlacklist.Value);
		}

		internal static void StartupActions()
		{
			SunAnimatorBlacklistLevels = ConfigHelper.ConvertStringToLevels(SunAnimatorBlacklist.Value);
			SunAnimatorBlacklist.SettingChanged += OnConfigChange;
		}
	}
	internal class Defaults
	{
		internal static List<LevelWeatherType> VanillaWeathers = new List<LevelWeatherType>(7)
		{
			(LevelWeatherType)(-1),
			(LevelWeatherType)0,
			(LevelWeatherType)3,
			(LevelWeatherType)1,
			(LevelWeatherType)2,
			(LevelWeatherType)4,
			(LevelWeatherType)5
		};

		internal static Dictionary<LevelWeatherType, Color> VanillaWeatherColors = new Dictionary<LevelWeatherType, Color>
		{
			{
				(LevelWeatherType)(-1),
				new Color(0.41f, 1f, 0.42f, 1f)
			},
			{
				(LevelWeatherType)0,
				new Color(0.41f, 1f, 0.42f, 1f)
			},
			{
				(LevelWeatherType)3,
				new Color(1f, 0.86f, 0f, 1f)
			},
			{
				(LevelWeatherType)1,
				new Color(1f, 0.86f, 0f, 1f)
			},
			{
				(LevelWeatherType)2,
				new Color(1f, 0.57f, 0f, 1f)
			},
			{
				(LevelWeatherType)4,
				new Color(1f, 0.57f, 0f, 1f)
			},
			{
				(LevelWeatherType)5,
				new Color(1f, 0f, 0f, 1f)
			}
		};

		internal static Dictionary<LevelWeatherType, string> VanillaWeatherToWeatherWeights = new Dictionary<LevelWeatherType, string>
		{
			{
				(LevelWeatherType)(-1),
				"None@160; Rainy@100; Stormy@70; Flooded@20; Foggy@40; Eclipsed@10"
			},
			{
				(LevelWeatherType)1,
				"None@100; Rainy@60; Stormy@40; Flooded@30; Foggy@50; Eclipsed@20"
			},
			{
				(LevelWeatherType)2,
				"None@160; Rainy@110; Stormy@10; Flooded@120; Foggy@20; Eclipsed@80"
			},
			{
				(LevelWeatherType)4,
				"None@160; Rainy@60; Stormy@50; Flooded@10; Foggy@60; Eclipsed@40"
			},
			{
				(LevelWeatherType)3,
				"None@200; Rainy@60; Stormy@50; Flooded@10; Foggy@30; Eclipsed@20"
			},
			{
				(LevelWeatherType)5,
				"None@300; Rainy@40; Stormy@16; Flooded@20; Foggy@60; Eclipsed@10"
			}
		};

		internal static Color LethalLibColor = new Color(0f, 0.44f, 0.76f, 1f);
	}
	public class WeatherConfig
	{
		[JsonIgnore]
		internal IntegerConfigHandler DefaultWeight;

		[JsonIgnore]
		internal FloatConfigHandler ScrapAmountMultiplier;

		[JsonIgnore]
		internal FloatConfigHandler ScrapValueMultiplier;

		[JsonIgnore]
		internal LevelListConfigHandler LevelFilters;

		[JsonIgnore]
		internal LevelWeightsConfigHandler LevelWeights;

		[JsonIgnore]
		internal WeatherWeightsConfigHandler WeatherToWeatherWeights;

		[JsonIgnore]
		internal ConfigEntry<bool> _filteringOptionConfig { get; private set; }

		internal void Init(Weather weather)
		{
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected O, but got Unknown
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0096: Expected O, but got Unknown
			//IL_00c1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cb: Expected O, but got Unknown
			//IL_00f0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fa: Expected O, but got Unknown
			//IL_012b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Expected O, but got Unknown
			//IL_0163: Unknown result type (might be due to invalid IL or missing references)
			//IL_016d: Expected O, but got Unknown
			//IL_0179: Unknown result type (might be due to invalid IL or missing references)
			//IL_01bb: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c5: Expected O, but got Unknown
			string text = "Weather: " + ((Object)weather).name + ((weather.Origin != 0) ? $" ({weather.Origin})" : "");
			DefaultWeight = new IntegerConfigHandler(weather._defaultWeight, weather, "Default weight", new ConfigDescription("The default weight of this weather", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 10000), Array.Empty<object>()));
			ScrapAmountMultiplier = new FloatConfigHandler(weather._scrapAmountMultiplier, weather, "Scrap amount multiplier", new ConfigDescription("Multiplier for the amount of scrap spawned", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			ScrapValueMultiplier = new FloatConfigHandler(weather._scrapValueMultiplier, weather, "Scrap value multiplier", new ConfigDescription("Multiplier for the value of scrap spawned", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 100f), Array.Empty<object>()));
			_filteringOptionConfig = ConfigManager.configFile.Bind<bool>(text, "Filtering option", weather.LevelFilteringOption == FilteringOption.Include, new ConfigDescription("Whether to make the filter a whitelist (false is blacklist, true is whitelist)", (AcceptableValueBase)null, Array.Empty<object>()));
			LevelFilters = new LevelListConfigHandler(string.Join(";", weather.DefaultLevelFilters) + ";", weather, "Level filter", new ConfigDescription("Semicolon-separated list of level names to filter", (AcceptableValueBase)null, Array.Empty<object>()));
			LevelWeights = new LevelWeightsConfigHandler(string.Join(';', weather.DefaultLevelWeights) + ";", weather, "Level weights", new ConfigDescription("Semicolon-separated list of level weights", (AcceptableValueBase)null, Array.Empty<object>()));
			WeatherToWeatherWeights = new WeatherWeightsConfigHandler((Defaults.VanillaWeatherToWeatherWeights.TryGetValue(weather.VanillaWeatherType, out var value) ? value : (string.Join(';', weather.DefaultWeatherToWeatherWeights) + ";")) ?? "", weather, "Weather weights", new ConfigDescription("Semicolon-separated list of weather weights", (AcceptableValueBase)null, Array.Empty<object>()));
		}
	}
	[CreateAssetMenu(fileName = "WeatherEffect", menuName = "WeatherRegistry/WeatherEffect", order = 10)]
	public class ImprovedWeatherEffect : ScriptableObject
	{
		[JsonIgnore]
		public GameObject EffectObject;

		[JsonIgnore]
		public GameObject WorldObject;

		private bool _effectEnabled;

		[field: SerializeField]
		public string SunAnimatorBool { get; set; }

		[field: SerializeField]
		public int DefaultVariable1 { get; set; }

		[field: SerializeField]
		public int DefaultVariable2 { get; set; }

		public bool EffectEnabled
		{
			get
			{
				return _effectEnabled;
			}
			set
			{
				Plugin.logger.LogWarning((object)$"Setting effect {((Object)this).name} to {value}");
				GameObject effectObject = EffectObject;
				if (effectObject != null)
				{
					effectObject.SetActive(value);
				}
				GameObject worldObject = WorldObject;
				if (worldObject != null)
				{
					worldObject.SetActive(value);
				}
				_effectEnabled = value;
			}
		}

		public void DisableEffect(bool permament = false)
		{
			if (permament)
			{
				EffectEnabled = false;
				return;
			}
			GameObject effectObject = EffectObject;
			if (effectObject != null)
			{
				effectObject.SetActive(false);
			}
		}

		public ImprovedWeatherEffect(GameObject effectObject, GameObject worldObject)
		{
			EffectObject = effectObject;
			WorldObject = worldObject;
		}
	}
	public enum WeatherType
	{
		Clear,
		Vanilla,
		Modded
	}
	public enum WeatherOrigin
	{
		Vanilla,
		WeatherRegistry,
		LethalLib,
		LethalLevelLoader
	}
	public enum FilteringOption
	{
		Include,
		Exclude
	}
	[JsonObject(/*Could not decode attribute arguments.*/)]
	[CreateAssetMenu(fileName = "Weather", menuName = "WeatherRegistry/WeatherDefinition", order = 5)]
	public class Weather : ScriptableObject
	{
		[JsonProperty]
		public string Name;

		[JsonIgnore]
		public ImprovedWeatherEffect Effect;

		[JsonIgnore]
		public Dictionary<SelectableLevel, LevelWeatherVariables> WeatherVariables = new Dictionary<SelectableLevel, LevelWeatherVariables>();

		[JsonIgnore]
		public AnimationClip AnimationClip;

		[JsonIgnore]
		internal WeatherConfig Config = new WeatherConfig();

		internal int _defaultWeight = 100;

		internal float _scrapAmountMultiplier = 1f;

		internal float _scrapValueMultiplier = 1f;

		[JsonProperty]
		public LevelWeatherType VanillaWeatherType { get; internal set; } = (LevelWeatherType)(-1);


		[JsonIgnore]
		internal WeatherOrigin Origin { get; set; } = WeatherOrigin.WeatherRegistry;


		[JsonProperty]
		public WeatherType Type { get; internal set; } = WeatherType.Modded;


		[field: SerializeField]
		public Color Color { get; set; } = Color.cyan;


		[SerializeField]
		public int DefaultWeight
		{
			get
			{
				return Config.DefaultWeight.Value;
			}
			set
			{
				_defaultWeight = value;
			}
		}

		[JsonIgnore]
		[field: SerializeField]
		public string[] DefaultLevelFilters { get; set; } = new string[1] { "Gordion" };


		public string[] DefaultLevelWeights { get; set; } = new string[1] { "MoonName@50" };


		public string[] DefaultWeatherToWeatherWeights { get; set; } = new string[1] { "WeatherName@50" };


		[SerializeField]
		public float ScrapAmountMultiplier
		{
			get
			{
				return Config.ScrapAmountMultiplier.Value;
			}
			set
			{
				_scrapAmountMultiplier = value;
			}
		}

		[SerializeField]
		public float ScrapValueMultiplier
		{
			get
			{
				return Config.ScrapValueMultiplier.Value;
			}
			set
			{
				_scrapValueMultiplier = value;
			}
		}

		[JsonIgnore]
		[field: SerializeField]
		public FilteringOption LevelFilteringOption { get; set; } = FilteringOption.Exclude;


		[JsonIgnore]
		public List<SelectableLevel> LevelFilters => Config.LevelFilters.Value.ToList();

		[JsonIgnore]
		public Dictionary<LevelWeatherType, int> WeatherWeights => Config.WeatherToWeatherWeights.Value.ToDictionary((WeatherRarity rarity) => rarity.Weather.VanillaWeatherType, (WeatherRarity rarity) => rarity.Weight);

		[JsonIgnore]
		public Dictionary<SelectableLevel, int> LevelWeights => Config.LevelWeights.Value.ToDictionary((LevelRarity rarity) => rarity.Level, (LevelRarity rarity) => rarity.Weight);

		public Weather(string name = "None", ImprovedWeatherEffect effect = null)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//IL_0021: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Unknown result type (might be due to invalid IL or missing references)
			Plugin.logger.LogDebug((object)("Called Weather constructor for weather " + name));
			Regex regex = new Regex("<.*?>");
			Name = regex.Replace(name, "");
			((Object)this).name = regex.Replace(name, "");
			Effect = effect;
			if ((Object)(object)effect != (Object)null)
			{
				((Object)Effect).name = name;
			}
		}

		internal virtual void Init()
		{
			_ = "Weather: " + ((Object)this).name + ((Origin != 0) ? $" ({Origin})" : "");
			Config.Init(this);
			LevelFilteringOption = ((!Config._filteringOptionConfig.Value) ? FilteringOption.Exclude : FilteringOption.Include);
			((Object)this).hideFlags = (HideFlags)61;
			Object.DontDestroyOnLoad((Object)(object)this);
			Object.Instantiate<Weather>(this);
		}

		private void Reset()
		{
			Type = WeatherType.Modded;
			ScrapAmountMultiplier = 1f;
			ScrapValueMultiplier = 1f;
			DefaultWeight = 50;
		}

		public void RemoveFromMoon(string moonNames)
		{
			ConfigHelper.ConvertStringToLevels(moonNames).ToList().ForEach(delegate(SelectableLevel level)
			{
				LevelFilters.Remove(level);
			});
		}

		public void RemoveFromMoon(SelectableLevel moon)
		{
			LevelFilters.Remove(moon);
		}
	}
	public class LevelWeatherVariables
	{
		public SelectableLevel Level;

		public int WeatherVariable1;

		public int WeatherVariable2;
	}
	public class LevelWeather : LevelWeatherVariables
	{
		public Weather Weather;

		public LevelWeatherVariables Variables;
	}
	public class EventManager
	{
		public static WeatherRegistryEvent SetupFinished = new WeatherRegistryEvent();

		public static WeatherRegistryEvent<(SelectableLevel level, Weather weather)> WeatherChanged = new WeatherRegistryEvent<(SelectableLevel, Weather)>();

		public static WeatherRegistryEvent DisableAllWeathers = new WeatherRegistryEvent();
	}
	public class Logger
	{
		private static ManualLogSource LogSource;

		private static ConfigEntry<bool> Enabled;

		public Logger(string name, ConfigEntry<bool> enabled)
		{
			LogSource = Logger.CreateLogSource(name);
			Enabled = enabled;
		}

		public static void Log(LogLevel level, object data)
		{
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			if (Enabled.Value)
			{
				LogSource.Log(level, data);
			}
		}

		public void LogInfo(object data)
		{
			Log((LogLevel)16, data);
		}

		public void LogWarning(object data)
		{
			Log((LogLevel)4, data);
		}

		public void LogError(object data)
		{
			Log((LogLevel)2, data);
		}

		public void LogDebug(object data)
		{
			Log((LogLevel)32, data);
		}

		public void LogFatal(object data)
		{
			Log((LogLevel)1, data);
		}

		public void LogMessage(object data)
		{
			Log((LogLevel)8, data);
		}
	}
	internal class LobbyCompatibilityCompatibility
	{
		public static void Init()
		{
			Plugin.logger.LogWarning((object)"LobbyCompatibility detected, registering plugin with LobbyCompatibility.");
			Version version = Version.Parse("0.1.10");
			PluginHelper.RegisterPlugin("mrov.WeatherRegistry", version, (CompatibilityLevel)2, (VersionStrictness)0);
		}
	}
	[HarmonyPatch(typeof(StartOfRound))]
	internal class OpeningDoorsSequencePatch
	{
		[HarmonyILManipulator]
		[HarmonyPatch(/*Could not decode attribute arguments.*/)]
		internal static void StartOfRound_openingDoorsSequence(ILContext il)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0007: Expected O, but got Unknown
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			ILCursor val = new ILCursor(il);
			if (!val.TryGotoNext((MoveType)2, new Func<Instruction, bool>[1]
			{
				(Instruction instr) => ILPatternMatchingExt.MatchStfld<StartOfRound>(instr, "shipDoorsEnabled")
			}))
			{
				Plugin.logger.LogError((object)"Failed IL weather hook for StartOfRound.openingDoorsSequence");
				return;
			}
			Plugin.logger.LogInfo((object)"IL weather hook for StartOfRound.openingDoorsSequence");
			val.EmitDelegate<Action>((Action)RunWeatherPatches);
			val.EmitDelegate<Action>((Action)SetWeatherEffects);
			if (!val.TryGotoNext((MoveType)2, new Func<Instruction, bool>[1]
			{
				(Instruction instr) => ILPatternMatchingExt.MatchLdfld<SelectableLevel>(instr, "LevelDescription")
			}))
			{
				Plugin.logger.LogError((object)"Failed IL hook for StartOfRound.openingDoorsSequence");
				return;
			}
			val.Emit(OpCodes.Ldloc_1);
			val.EmitDelegate<Func<string, StartOfRound, string>>((Func<string, StartOfRound, string>)delegate(string desc, StartOfRound self)
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000c: Invalid comparison between Unknown and I4
				string text = (((int)self.currentLevel.currentWeather != -1) ? WeatherManager.GetCurrentWeatherName(self.currentLevel) : "Clear");
				return string.Concat("WEATHER: " + text, "\n", desc);
			});
		}

		internal static void RunWeatherPatches()
		{
			TimeOfDay.Instance.nextTimeSync = 0f;
		}

		internal static void SetWeatherEffects()
		{
			//IL_0011: 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_0040: Unknown result type (might be due to invalid IL or missing references)
			//IL_004c: Expected O, but got Unknown
			Weather currentWeather = WeatherManager.GetCurrentWeather(StartOfRound.Instance.currentLevel);
			SunAnimator.OverrideSunAnimator(currentWeather.VanillaWeatherType);
			Plugin.logger.LogDebug((object)("Landing at " + ConfigHelper.GetNumberlessName(StartOfRound.Instance.currentLevel) + " with weather " + JsonConvert.SerializeObject((object)currentWeather, (Formatting)0, new JsonSerializerSettings
			{
				ReferenceLoopHandling = (ReferenceLoopHandling)1
			})));
		}
	}
	[BepInPlugin("mrov.WeatherRegistry", "WeatherRegistry", "0.1.10")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string GUID = "mrov.WeatherRegistry";

		internal static ManualLogSource logger;

		internal static Harmony harmony = new Harmony("mrov.WeatherRegistry");

		internal static bool IsLethalLibLoaded = false;

		internal static Hook WeatherTypeEnumHook;

		private void Awake()
		{
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0089: Expected O, but got Unknown
			logger = ((BaseUnityPlugin)this).Logger;
			harmony.PatchAll();
			ConfigManager.Init(((BaseUnityPlugin)this).Config);
			SunAnimator.Init();
			if (Chainloader.PluginInfos.ContainsKey("evaisa.lethallib"))
			{
				IsLethalLibLoaded = true;
				LethalLibPatch.Init();
			}
			else
			{
				logger.LogInfo((object)"LethalLib not detected!");
			}
			WeatherTypeEnumHook = new Hook((MethodBase)typeof(Enum).GetMethod("ToString", Array.Empty<Type>()), typeof(WeatherManager).GetMethod("LevelWeatherTypeEnumHook"));
			if (Chainloader.PluginInfos.ContainsKey("BMX.LobbyCompatibility"))
			{
				LobbyCompatibilityCompatibility.Init();
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Plugin mrov.WeatherRegistry is loaded!");
		}
	}
	public class Settings
	{
		public static Dictionary<string, Color> ScreenMapColors = new Dictionary<string, Color>();

		public static bool SelectWeathers = true;
	}
	public class WeatherCalculation
	{
		internal static Dictionary<string, LevelWeatherType> previousDayWeather = new Dictionary<string, LevelWeatherType>();

		public static Logger Logger = new Logger("WeatherRegistry", ConfigManager.LogWeatherChanges);

		internal static Dictionary<string, LevelWeatherType> NewWeathers(StartOfRound startOfRound)
		{
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_009c: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b8: 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_0141: Unknown result type (might be due to invalid IL or missing references)
			if (!((NetworkBehaviour)StartOfRound.Instance).IsHost)
			{
				Logger.LogInfo("Not a host, cannot generate weathers!");
				return null;
			}
			previousDayWeather.Clear();
			Dictionary<string, LevelWeatherType> dictionary = new Dictionary<string, LevelWeatherType>();
			new Random(startOfRound.randomMapSeed + 31);
			List<SelectableLevel> list = startOfRound.levels.ToList();
			int daysSpent = startOfRound.gameStats.daysSpent;
			_ = TimeOfDay.Instance.timesFulfilledQuota;
			_ = daysSpent % 3;
			foreach (SelectableLevel item in list)
			{
				previousDayWeather[item.PlanetName] = item.currentWeather;
				if (item.overrideWeather)
				{
					Logger.LogDebug($"Override weather present, changing weather to {item.overrideWeatherType}");
					dictionary[item.PlanetName] = item.overrideWeatherType;
					continue;
				}
				Logger.LogMessage("-------------");
				Logger.LogMessage(item.PlanetName ?? "");
				Logger.LogDebug($"previousDayWeather: {previousDayWeather[item.PlanetName]}");
				dictionary[item.PlanetName] = (LevelWeatherType)(-1);
				var (weather, dictionary2) = WeatherManager.PickNewRandomWeather(item);
				dictionary[item.PlanetName] = weather.VanillaWeatherType;
				WeatherManager.CurrentWeathers[item] = weather;
				Logger.LogMessage("Selected weather: " + weather.Name);
				try
				{
					Logger.LogMessage($"Chance for that was {dictionary2[weather]} / {dictionary2.Values.Sum()} ({(float)dictionary2[weather] / (float)dictionary2.Values.Sum() * 100f}%)");
				}
				catch
				{
				}
			}
			Logger.LogMessage("-------------");
			return dictionary;
		}
	}
	public static class WeatherController
	{
		public static void ChangeCurrentWeather(Weather weather)
		{
			ChangeWeather(StartOfRound.Instance.currentLevel, weather);
		}

		public static void ChangeCurrentWeather(LevelWeatherType weatherType)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			ChangeWeather(StartOfRound.Instance.currentLevel, weatherType);
		}

		public static void ChangeWeather(SelectableLevel level, LevelWeatherType weatherType)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			Weather weather = WeatherManager.GetWeather(weatherType);
			ChangeWeather(level, weather);
		}

		public static void ChangeWeather(SelectableLevel level, Weather weather)
		{
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			WeatherManager.CurrentWeathers[level] = weather;
			level.currentWeather = weather.VanillaWeatherType;
			EventManager.WeatherChanged.Invoke((level, weather));
			StartOfRound.Instance.SetMapScreenInfoToCurrentLevel();
		}
	}
	public static class WeatherManager
	{
		internal static bool IsSetupFinished = false;

		public static Dictionary<int, Weather> ModdedWeatherEnumExtension = new Dictionary<int, Weather>();

		public static Dictionary<SelectableLevel, Weather> CurrentWeathers = new Dictionary<SelectableLevel, Weather>();

		public static List<Weather> RegisteredWeathers { get; internal set; } = new List<Weather>();


		public static List<LevelWeather> LevelWeathers { get; internal set; } = new List<LevelWeather>();


		public static List<Weather> Weathers { get; internal set; } = new List<Weather>();


		public static Weather NoneWeather { get; internal set; }

		public static void RegisterWeather(Weather weather)
		{
			RegisteredWeathers.Add(weather);
		}

		public static Weather GetWeather(LevelWeatherType levelWeatherType)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			return Weathers.Find((Weather weather) => weather.VanillaWeatherType == levelWeatherType);
		}

		public static void Reset()
		{
			IsSetupFinished = false;
			Weathers.ForEach(delegate(Weather weather)
			{
				if (weather.Origin != WeatherOrigin.WeatherRegistry)
				{
					Object.Destroy((Object)(object)weather.Effect);
					Object.Destroy((Object)(object)weather);
				}
			});
			LevelWeathers.Clear();
			Weathers.Clear();
			ModdedWeatherEnumExtension.Clear();
			CurrentWeathers.Clear();
			Settings.ScreenMapColors.Clear();
			ConfigHelper.StringToWeather = null;
			ConfigHelper.StringToLevel = null;
			RegisteredWeathers.RemoveAll((Weather weather) => weather.Origin != WeatherOrigin.WeatherRegistry);
		}

		public static string LevelWeatherTypeEnumHook(Func<Enum, string> orig, Enum self)
		{
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Expected I4, but got Unknown
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected I4, but got Unknown
			if (self.GetType() == typeof(LevelWeatherType) && ModdedWeatherEnumExtension.ContainsKey((int)(LevelWeatherType)(object)self))
			{
				return ((Object)ModdedWeatherEnumExtension[(int)(LevelWeatherType)(object)self]).name;
			}
			return orig(self);
		}

		internal static List<LevelWeatherType> GetPlanetPossibleWeathers(SelectableLevel level)
		{
			List<LevelWeatherType> list = (from randomWeather in level.randomWeathers
				where (int)randomWeather.weatherType != -1
				select randomWeather into x
				select x.weatherType).Distinct().ToList();
			list.Insert(0, (LevelWeatherType)(-1));
			Plugin.logger.LogDebug((object)("Possible weathers: " + string.Join("; ", list.Select((LevelWeatherType x) => ((object)(LevelWeatherType)(ref x)).ToString()))));
			if (list == null || list.Count() == 0)
			{
				Plugin.logger.LogError((object)"Level's random weathers are null");
				return new List<LevelWeatherType>();
			}
			return list;
		}

		internal static Dictionary<Weather, int> GetPlanetWeightedList(SelectableLevel level)
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0085: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<Weather, int> dictionary = new Dictionary<Weather, int>();
			Logger logger = WeatherCalculation.Logger;
			List<LevelWeatherType> planetPossibleWeathers = GetPlanetPossibleWeathers(level);
			if (planetPossibleWeathers.Count == 0)
			{
				return new Dictionary<Weather, int>();
			}
			foreach (LevelWeatherType item in planetPossibleWeathers)
			{
				Weather weather = GetWeather(item);
				Dictionary<SelectableLevel, int> levelWeights = weather.LevelWeights;
				Dictionary<LevelWeatherType, int> weatherWeights = weather.WeatherWeights;
				int num = weather.DefaultWeight;
				int value2;
				if (levelWeights.TryGetValue(level, out var value))
				{
					logger.LogDebug($"{weather.Name} has level weight {value}");
					num = value;
				}
				else if (weatherWeights.TryGetValue(level.currentWeather, out value2) && StartOfRound.Instance.gameStats.daysSpent != 0)
				{
					logger.LogDebug($"{weather.Name} has weather>weather weight {value2}");
					num = value2;
				}
				else
				{
					logger.LogDebug($"{weather.Name} has default weight {num}");
				}
				dictionary.Add(weather, num);
			}
			return dictionary;
		}

		internal static (Weather, Dictionary<Weather, int>) PickNewRandomWeather(SelectableLevel level)
		{
			Dictionary<Weather, int> planetWeightedList = GetPlanetWeightedList(level);
			if (planetWeightedList.Count == 0)
			{
				Plugin.logger.LogError((object)"Weighted list is empty");
				return (NoneWeather, planetWeightedList);
			}
			int num = planetWeightedList.Values.Sum();
			if (num <= 0)
			{
				Plugin.logger.LogError((object)"Sum of all weights is 0");
				return (NoneWeather, planetWeightedList);
			}
			int num2 = new Random().Next(0, num);
			int num3 = 0;
			foreach (KeyValuePair<Weather, int> item in planetWeightedList.OrderByDescending((KeyValuePair<Weather, int> v) => v.Value))
			{
				num3 += item.Value;
				if (num2 <= num3)
				{
					return (item.Key, planetWeightedList);
				}
			}
			return (planetWeightedList.Keys.FirstOrDefault(), planetWeightedList);
		}

		internal static Weather GetCurrentWeather(SelectableLevel level)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			if (CurrentWeathers.ContainsKey(level))
			{
				return CurrentWeathers[level];
			}
			return GetWeather(level.currentWeather);
		}

		internal static string GetCurrentWeatherName(SelectableLevel level)
		{
			return GetCurrentWeather(level).Name;
		}

		internal static AnimationClip GetWeatherAnimationClip(LevelWeatherType weatherType)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			return GetWeather(weatherType).AnimationClip;
		}
	}
	internal class WeatherSync : NetworkBehaviour
	{
		public static GameObject WeatherSyncPrefab;

		private static WeatherSync _instance;

		public static NetworkManager networkManager;

		private static List<GameObject> queuedNetworkPrefabs = new List<GameObject>();

		public static bool networkHasStarted = false;

		private string LatestWeathersReceived = "";

		private static string DefaultValue = "{}";

		public NetworkVariable<FixedString4096Bytes> WeathersSynced = new NetworkVariable<FixedString4096Bytes>(FixedString4096Bytes.op_Implicit(DefaultValue), (NetworkVariableReadPermission)0, (NetworkVariableWritePermission)0);

		public static WeatherSync Instance
		{
			get
			{
				if ((Object)(object)_instance == (Object)null)
				{
					_instance = Object.FindObjectOfType<WeatherSync>();
				}
				if ((Object)(object)_instance == (Object)null)
				{
					Plugin.logger.LogError((object)"WeatherSync instance is null");
				}
				return _instance;
			}
			set
			{
				_instance = value;
			}
		}

		public string Weather
		{
			get
			{
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000b: Unknown result type (might be due to invalid IL or missing references)
				FixedString4096Bytes value = WeathersSynced.Value;
				return ((object)(FixedString4096Bytes)(ref value)).ToString();
			}
			set
			{
				//IL_0007: Unknown result type (might be due to invalid IL or missing references)
				WeathersSynced.Value = new FixedString4096Bytes(value);
			}
		}

		public override void OnNetworkSpawn()
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			((NetworkBehaviour)this).OnNetworkSpawn();
			((Object)((Component)this).gameObject).name = "WeatherSync";
			Instance = this;
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			Plugin.logger.LogWarning((object)$"WeathersSynced: {WeathersSynced.Value}");
			NetworkVariable<FixedString4096Bytes> weathersSynced = WeathersSynced;
			weathersSynced.OnValueChanged = (OnValueChangedDelegate<FixedString4096Bytes>)(object)Delegate.Combine((Delegate?)(object)weathersSynced.OnValueChanged, (Delegate?)(object)new OnValueChangedDelegate<FixedString4096Bytes>(WeathersReceived));
		}

		public void SetNew(string weathers)
		{
			Plugin.logger.LogInfo((object)("Setting new weathers: " + weathers));
			Plugin.logger.LogInfo((object)string.Format("Current weathers: {0} (is null? {1}) (is empty? {2}", Weather, Weather == null, Weather == ""));
			Weather = weathers;
		}

		public void WeathersReceived(FixedString4096Bytes oldWeathers, FixedString4096Bytes weathers)
		{
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			Plugin.logger.LogInfo((object)$"Weathers received: {weathers}");
			if (WeatherManager.IsSetupFinished)
			{
				ApplyWeathers(((object)(FixedString4096Bytes)(ref weathers)).ToString());
			}
		}

		public void ApplyWeathers(string weathers)
		{
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			Plugin.logger.LogInfo((object)("Weathers to apply: " + weathers));
			if (LatestWeathersReceived == weathers)
			{
				Plugin.logger.LogInfo((object)"Weathers are the same as last ones, skipping");
				return;
			}
			if (weathers == DefaultValue)
			{
				Plugin.logger.LogInfo((object)"Weathers are not set, skipping");
				return;
			}
			Dictionary<string, LevelWeatherType> dictionary = JsonConvert.DeserializeObject<Dictionary<string, LevelWeatherType>>(weathers);
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				val.currentWeather = dictionary[val.PlanetName];
			}
			LatestWeathersReceived = weathers;
			StartOfRound.Instance.SetMapScreenInfoToCurrentLevel();
		}

		public static void RegisterNetworkPrefab(GameObject prefab)
		{
			if (!networkHasStarted)
			{
				Plugin.logger.LogWarning((object)("Registering NetworkPrefab: " + (object)prefab));
				queuedNetworkPrefabs.Add(prefab);
			}
			else
			{
				Plugin.logger.LogWarning((object)("Attempted To Register NetworkPrefab: " + ((object)prefab)?.ToString() + " After GameNetworkManager Has Started!"));
			}
		}

		internal static void RegisterPrefabs(NetworkManager networkManager)
		{
			Plugin.logger.LogWarning((object)"Registering NetworkPrefabs in NetworkManager");
			List<GameObject> list = new List<GameObject>();
			foreach (NetworkPrefab prefab in networkManager.NetworkConfig.Prefabs.m_Prefabs)
			{
				list.Add(prefab.Prefab);
			}
			int num = 0;
			foreach (GameObject queuedNetworkPrefab in queuedNetworkPrefabs)
			{
				Plugin.logger.LogDebug((object)("Trying To Register Prefab: " + (object)queuedNetworkPrefab));
				if (!list.Contains(queuedNetworkPrefab))
				{
					networkManager.AddNetworkPrefab(queuedNetworkPrefab);
					list.Add(queuedNetworkPrefab);
				}
				else
				{
					num++;
				}
			}
			Plugin.logger.LogDebug((object)("Skipped Registering " + num + " NetworkObjects As They Were Already Registered."));
			networkHasStarted = true;
		}

		protected override void __initializeVariables()
		{
			if (WeathersSynced == null)
			{
				throw new Exception("WeatherSync.WeathersSynced cannot be null. All NetworkVariableBase instances must be initialized.");
			}
			((NetworkVariableBase)WeathersSynced).Initialize((NetworkBehaviour)(object)this);
			((NetworkBehaviour)this).__nameNetworkVariable((NetworkVariableBase)(object)WeathersSynced, "WeathersSynced");
			base.NetworkVariableFields.Add((NetworkVariableBase)(object)WeathersSynced);
			((NetworkBehaviour)this).__initializeVariables();
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		protected internal override string __getTypeName()
		{
			return "WeatherSync";
		}
	}
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "WeatherRegistry";

		public const string PLUGIN_NAME = "WeatherRegistry";

		public const string PLUGIN_VERSION = "0.1.10";
	}
}
namespace WeatherRegistry.Patches
{
	[HarmonyPatch(typeof(TimeOfDay))]
	public static class TimeOfDayPatch
	{
		internal static ManualLogSource logger = Logger.CreateLogSource("WeatherTweaks TimeOfDay");

		[HarmonyPostfix]
		[HarmonyPatch(typeof(TimeOfDay), "DisableAllWeather")]
		private static void DisableAllWeatherPatch(TimeOfDay __instance, bool deactivateObjects)
		{
			logger.LogDebug((object)"Disabling all weather");
			if (!deactivateObjects)
			{
				return;
			}
			logger.LogDebug((object)"DecativateObjects is true");
			foreach (ImprovedWeatherEffect item in WeatherManager.Weathers.Select((Weather weather) => weather.Effect))
			{
				item.DisableEffect(deactivateObjects);
			}
			EventManager.DisableAllWeathers.Invoke();
			SunAnimator.Clear();
		}
	}
	[HarmonyPatch(typeof(GameNetworkManager), "Start")]
	internal class GameNetworkManagerStartPatch
	{
		[HarmonyPrefix]
		public static void GameMethodPatch(GameNetworkManager __instance)
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0050: Unknown result type (might be due to invalid IL or missing references)
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			//IL_007b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Expected O, but got Unknown
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_0087: Expected O, but got Unknown
			//IL_008c: Expected O, but got Unknown
			WeatherSync.networkManager = ((Component)__instance).GetComponent<NetworkManager>();
			GameObject val = new GameObject("WeatherRegistrySyncInit")
			{
				hideFlags = (HideFlags)61
			};
			val.AddComponent<NetworkObject>();
			byte[] value = MD5.Create().ComputeHash(Encoding.UTF8.GetBytes("weatherregistryweathersync"));
			val.GetComponent<NetworkObject>().GlobalObjectIdHash = BitConverter.ToUInt32(value, 0);
			val.AddComponent<WeatherSync>();
			val.GetComponent<NetworkObject>().DontDestroyWithOwner = true;
			val.GetComponent<NetworkObject>().SceneMigrationSynchronization = true;
			val.GetComponent<NetworkObject>().DestroyWithScene = false;
			Object.DontDestroyOnLoad((Object)val);
			WeatherSync.WeatherSyncPrefab = val;
			WeatherSync.RegisterNetworkPrefab(val);
			WeatherSync.RegisterPrefabs(((Component)__instance).GetComponent<NetworkManager>());
			Plugin.logger.LogWarning((object)"WeatherSync initialized in GameNetworkManager.Start");
		}
	}
	public class LethalLibPatch
	{
		public static Dictionary<int, CustomWeather> GetLethalLibWeathers()
		{
			return Weathers.customWeathers;
		}

		public static List<Weather> ConvertLLWeathers()
		{
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<int, CustomWeather> lethalLibWeathers = GetLethalLibWeathers();
			List<Weather> list = new List<Weather>();
			foreach (KeyValuePair<int, CustomWeather> item in lethalLibWeathers)
			{
				CustomWeather value = item.Value;
				ImprovedWeatherEffect improvedWeatherEffect = new ImprovedWeatherEffect(value.weatherEffect.effectObject, value.weatherEffect.effectPermanentObject);
				((Object)improvedWeatherEffect).name = value.name;
				improvedWeatherEffect.SunAnimatorBool = value.weatherEffect.sunAnimatorBool;
				improvedWeatherEffect.DefaultVariable1 = value.weatherVariable1;
				improvedWeatherEffect.DefaultVariable2 = value.weatherVariable2;
				ImprovedWeatherEffect effect = improvedWeatherEffect;
				Weather weather = new Weather(value.name, effect)
				{
					VanillaWeatherType = (LevelWeatherType)item.Key,
					Origin = WeatherOrigin.LethalLib,
					Color = Defaults.LethalLibColor,
					DefaultWeight = 50
				};
				list.Add(weather);
				WeatherManager.ModdedWeatherEnumExtension.Add(item.Key, weather);
			}
			return list;
		}

		public static void Init()
		{
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Expected O, but got Unknown
			//IL_009a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Expected O, but got Unknown
			Plugin.logger.LogWarning((object)"Disabling LethalLib injections");
			((Hook)typeof(Weathers).GetField("weatherEnumHook", BindingFlags.Static | BindingFlags.NonPublic).GetValue(null)).Undo();
			Plugin.harmony.Patch((MethodBase)AccessTools.Method(typeof(Weathers), "RegisterLevelWeathers_StartOfRound_Awake", (Type[])null, (Type[])null), new HarmonyMethod(typeof(LethalLibPatch), "StartOfRoundAwakePrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			Plugin.harmony.Patch((MethodBase)AccessTools.Method(typeof(Weathers), "TimeOfDay_Awake", (Type[])null, (Type[])null), new HarmonyMethod(typeof(LethalLibPatch), "TimeOfDayAwakePrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		internal static bool StartOfRoundAwakePrefix(orig_Awake orig, StartOfRound self)
		{
			Plugin.logger.LogWarning((object)"Skipping LethalLib StartOfRound method");
			orig.Invoke(self);
			return false;
		}

		internal static bool TimeOfDayAwakePrefix(orig_Awake orig, TimeOfDay self)
		{
			Plugin.logger.LogWarning((object)"Skipping LethalLib TimeOfDay method");
			orig.Invoke(self);
			return false;
		}
	}
	[HarmonyPatch(typeof(StartOfRound))]
	public static class SetMapScreenInfoToCurrentLevelPatch
	{
		[HarmonyPatch("SetMapScreenInfoToCurrentLevel")]
		[HarmonyPostfix]
		[HarmonyPriority(0)]
		internal static void GameMethodPatch(ref TextMeshProUGUI ___screenLevelDescription, ref SelectableLevel ___currentLevel)
		{
			if (!WeatherManager.IsSetupFinished)
			{
				Plugin.logger.LogWarning((object)"WeatherManager is not set up yet.");
				return;
			}
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("ORBITING: " + ___currentLevel.PlanetName + "\n");
			stringBuilder.Append("WEATHER: " + GetColoredString(___currentLevel) + "\n");
			stringBuilder.Append(___currentLevel.LevelDescription ?? "");
			((TMP_Text)___screenLevelDescription).fontWeight = (FontWeight)700;
			((TMP_Text)___screenLevelDescription).text = stringBuilder.ToString();
		}

		private static string GetDisplayWeatherString(SelectableLevel level, Weather weather)
		{
			return weather.Name;
		}

		private static string GetColoredString(SelectableLevel level)
		{
			Weather currentWeather = WeatherManager.GetCurrentWeather(level);
			string displayWeatherString = GetDisplayWeatherString(level, currentWeather);
			if (!ConfigManager.ColoredWeathers.Value)
			{
				return displayWeatherString;
			}
			string outputString = "";
			new Regex("(\\/)|(\\?)|(>)|(\\+)").Split(displayWeatherString).ToList().ForEach(delegate(string word)
			{
				//IL_001d: Unknown result type (might be due to invalid IL or missing references)
				//IL_0016: Unknown result type (might be due to invalid IL or missing references)
				string text = word.Trim();
				Color value;
				string text2 = ColorUtility.ToHtmlStringRGB(Settings.ScreenMapColors.TryGetValue(text, out value) ? value : Color.black);
				outputString += ((text2 != "000000") ? ("<color=#" + text2 + ">" + word + "</color>") : (text ?? ""));
			});
			return outputString;
		}
	}
	[HarmonyPatch(typeof(StartOfRound))]
	internal class SetPlanetsWeatherPatch
	{
		[HarmonyPatch("SetPlanetsWeather")]
		[HarmonyPrefix]
		public static bool GameMethodPatch(int connectedPlayersOnServer, StartOfRound __instance)
		{
			//IL_00d5: Unknown result type (might be due to invalid IL or missing references)
			Plugin.logger.LogInfo((object)"SetPlanetsWeather called.");
			if (!WeatherManager.IsSetupFinished)
			{
				Plugin.logger.LogWarning((object)"WeatherManager is not set up yet.");
				return false;
			}
			if (!Settings.SelectWeathers)
			{
				Plugin.logger.LogWarning((object)"Weather selection is disabled.");
				return true;
			}
			if ((Object)(object)__instance == (Object)null)
			{
				Plugin.logger.LogWarning((object)"Instance is null");
				return true;
			}
			if (((NetworkBehaviour)__instance).IsHost)
			{
				WeatherManager.CurrentWeathers = new Dictionary<SelectableLevel, Weather>();
				Dictionary<string, LevelWeatherType> dictionary = WeatherCalculation.NewWeathers(__instance);
				Plugin.logger.LogDebug((object)$"Instance: {WeatherSync.Instance}");
				Plugin.logger.LogDebug((object)$"Weathers: {dictionary}");
				Plugin.logger.LogDebug((object)$"WeatherSync: {WeatherSync.Instance.WeathersSynced}");
				Plugin.logger.LogDebug((object)$"WeathersSynced: {WeatherSync.Instance.WeathersSynced.Value}");
				WeatherSync.Instance.SetNew(JsonConvert.SerializeObject((object)dictionary));
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(RoundManager))]
	public class SpawnScrapInLevelPatches
	{
		[HarmonyPatch("SpawnScrapInLevel")]
		[HarmonyPrefix]
		private static void ChangeMultipliers(RoundManager __instance)
		{
			Weather currentWeather = WeatherManager.GetCurrentWeather(__instance.currentLevel);
			__instance.scrapValueMultiplier = currentWeather.ScrapValueMultiplier * 0.4f;
			__instance.scrapAmountMultiplier = currentWeather.ScrapAmountMultiplier;
		}

		[HarmonyPatch("SpawnScrapInLevel")]
		[HarmonyPostfix]
		private static void LogMultipliers(RoundManager __instance)
		{
			Plugin.logger.LogInfo((object)$"Spawned scrap in level with multipliers: {__instance.scrapValueMultiplier}, {__instance.scrapAmountMultiplier}");
		}
	}
	internal class StartOfRoundPatch
	{
		[HarmonyPatch("OnDisable")]
		[HarmonyPrefix]
		public static void DisableWeathersPatch()
		{
			foreach (Weather weather in WeatherManager.Weathers)
			{
				weather.Effect.DisableEffect();
			}
		}
	}
	internal class SunAnimator
	{
		public class AnimationClipOverrides : List<KeyValuePair<AnimationClip, AnimationClip>>
		{
			public AnimationClip this[string name]
			{
				get
				{
					return Find((KeyValuePair<AnimationClip, AnimationClip> x) => ((Object)x.Key).name.Equals(name)).Value;
				}
				set
				{
					int num = FindIndex((KeyValuePair<AnimationClip, AnimationClip> x) => ((Object)x.Key).name.Equals(name));
					if (num != -1)
					{
						base[num] = new KeyValuePair<AnimationClip, AnimationClip>(base[num].Key, value);
					}
				}
			}

			public AnimationClipOverrides(int capacity)
				: base(capacity)
			{
			}
		}

		internal static ManualLogSource logger = Logger.CreateLogSource("WeatherRegistry SunAnimator");

		internal static Dictionary<string, LevelWeatherType> vanillaBools = new Dictionary<string, LevelWeatherType>
		{
			{
				"",
				(LevelWeatherType)(-1)
			},
			{
				"overcast",
				(LevelWeatherType)2
			},
			{
				"eclipse",
				(LevelWeatherType)5
			}
		};

		internal static Dictionary<LevelWeatherType, string> clipNames = new Dictionary<LevelWeatherType, string>
		{
			{
				(LevelWeatherType)(-1),
				""
			},
			{
				(LevelWeatherType)2,
				"Stormy"
			},
			{
				(LevelWeatherType)5,
				"Eclipse"
			}
		};

		internal static List<string> animatorControllerBlacklist = new List<string>(1) { "SunAnimContainerCompanyLevel" };

		internal static AnimatorOverrideController animatorOverrideController;

		public static void Init()
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_005d: Expected O, but got Unknown
			new Harmony("WeatherRegistry.SunAnimator").Patch((MethodBase)AccessTools.Method(typeof(Animator), "SetBool", new Type[2]
			{
				typeof(string),
				typeof(bool)
			}, (Type[])null), new HarmonyMethod(typeof(SunAnimator), "SetBoolStringPatch", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			logger.LogWarning((object)"Patching Animator.SetBool(string, bool)");
		}

		public static bool SetBoolPatch(Animator __instance, object nameOrId, bool value)
		{
			string text = nameOrId as string;
			if ((Object)(object)TimeOfDay.Instance == (Object)null)
			{
				return true;
			}
			if (text == "overcast" || text == "eclipse")
			{
				ConfigManager.SunAnimatorBlacklistLevels.Contains(StartOfRound.Instance.currentLevel);
				return true;
			}
			return true;
		}

		public static bool SetBoolStringPatch(Animator __instance, string name, bool value)
		{
			return SetBoolPatch(__instance, name, value);
		}

		public static void OverrideSunAnimator(LevelWeatherType weatherType)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			//IL_0008: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_0136: Unknown result type (might be due to invalid IL or missing references)
			//IL_013b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Expected O, but got Unknown
			//IL_027d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0293: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ca: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_034f: Unknown result type (might be due to invalid IL or missing references)
			//IL_03b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_03d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0397: Unknown result type (might be due to invalid IL or missing references)
			//IL_0497: Unknown result type (might be due to invalid IL or missing references)
			//IL_047b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0534: Unknown result type (might be due to invalid IL or missing references)
			//IL_053a: Invalid comparison between Unknown and I4
			//IL_04bc: Unknown result type (might be due to invalid IL or missing references)
			Plugin.logger.LogDebug((object)"OverrideSunAnimator called");
			if (ConfigManager.SunAnimatorBlacklistLevels.Contains(StartOfRound.Instance.currentLevel))
			{
				logger.LogWarning((object)$"Current level {StartOfRound.Instance.currentLevel} is blacklisted");
				return;
			}
			if ((Object)(object)TimeOfDay.Instance.sunAnimator == (Object)null)
			{
				logger.LogWarning((object)"sunAnimator is null, skipping");
				return;
			}
			AnimatorClipInfo[] currentAnimatorClipInfo = TimeOfDay.Instance.sunAnimator.GetCurrentAnimatorClipInfo(0);
			if (currentAnimatorClipInfo.Length == 0)
			{
				logger.LogWarning((object)"There are no SunAnimator clips, skipping");
				return;
			}
			logger.LogInfo((object)("Current clip: " + ((Object)((AnimatorClipInfo)(ref currentAnimatorClipInfo[0])).clip).name));
			string name = ((Object)TimeOfDay.Instance.sunAnimator.runtimeAnimatorController).name;
			logger.LogInfo((object)$"animatorControllerName: {name}, weatherType: {weatherType}");
			if (animatorControllerBlacklist.Contains(name))
			{
				logger.LogWarning((object)("TimeOfDay.Instance.sunAnimator controller " + name + " is blacklisted"));
				return;
			}
			if ((Object)(object)animatorOverrideController == (Object)null)
			{
				animatorOverrideController = new AnimatorOverrideController(TimeOfDay.Instance.sunAnimator.runtimeAnimatorController)
				{
					name = name + "override"
				};
			}
			AnimationClipOverrides clipOverrides = new AnimationClipOverrides(animatorOverrideController.overridesCount);
			logger.LogDebug((object)$"Overrides: {animatorOverrideController.overridesCount}");
			animatorOverrideController.GetOverrides((List<KeyValuePair<AnimationClip, AnimationClip>>)clipOverrides);
			List<AnimationClip> list = animatorOverrideController.runtimeAnimatorController.animationClips.ToList();
			Dictionary<LevelWeatherType, AnimationClip> clips = new Dictionary<LevelWeatherType, AnimationClip>();
			Weather weather = WeatherManager.GetWeather(weatherType);
			try
			{
				AnimationClip val = list.Find((AnimationClip clip) => ((Object)clip).name.Contains(clipNames[(LevelWeatherType)5]));
				AnimationClip val2 = list.Find((AnimationClip clip) => ((Object)clip).name.Contains(clipNames[(LevelWeatherType)2]));
				AnimationClip val3 = list.Find((AnimationClip clip) => !((Object)clip).name.Contains(clipNames[(LevelWeatherType)2]) && !((Object)clip).name.Contains(clipNames[(LevelWeatherType)5]));
				clips = new Dictionary<LevelWeatherType, AnimationClip>
				{
					{
						(LevelWeatherType)5,
						val
					},
					{
						(LevelWeatherType)2,
						val2
					},
					{
						(LevelWeatherType)4,
						val2
					},
					{
						(LevelWeatherType)3,
						val2
					},
					{
						(LevelWeatherType)1,
						val2
					},
					{
						(LevelWeatherType)(-1),
						val3
					}
				};
				if ((Object)(object)WeatherManager.GetWeatherAnimationClip(weatherType) != (Object)null)
				{
					AnimationClip weatherAnimationClip = WeatherManager.GetWeatherAnimationClip(weatherType);
					ArrayUtility.Add<AnimationClip>(TimeOfDay.Instance.sunAnimator.runtimeAnimatorController.animationClips, weatherAnimationClip);
					list.Add(weatherAnimationClip);
					clips[weatherType] = weatherAnimationClip;
					logger.LogInfo((object)$"Added animation clip for weather type {weatherType}");
					TimeOfDay.Instance.sunAnimator.runtimeAnimatorController.animationClips.ToList().ForEach(delegate(AnimationClip clip)
					{
						logger.LogInfo((object)("clip: " + ((Object)clip).name));
					});
				}
				else if (weather.Type != WeatherType.Vanilla)
				{
					logger.LogWarning((object)$"No custom animation clip found for weather type {weatherType}");
					logger.LogDebug((object)"Trying to apply vanilla animator bool");
					if (!vanillaBools.TryGetValue(weather.Effect.SunAnimatorBool, out var _))
					{
						logger.LogInfo((object)$"No vanilla bool found for weather type {weatherType}");
						return;
					}
					clips[weatherType] = clips[vanillaBools[weather.Effect.SunAnimatorBool]];
				}
				if ((Object)(object)val == (Object)null || (Object)(object)val2 == (Object)null || (Object)(object)val3 == (Object)null)
				{
					return;
				}
			}
			catch (Exception ex)
			{
				logger.LogError((object)("Detected a null clip: " + ex.Message));
				return;
			}
			logger.LogWarning((object)$"Clips: {clips.Count}");
			if (clips.Keys.Select((LevelWeatherType key) => key == weatherType).Count() == 0)
			{
				logger.LogWarning((object)$"No animation clip found for weather type {weatherType}");
				return;
			}
			if ((clips.TryGetValue(weatherType, out var value2) ? ((Object)value2).name : null) == null)
			{
				logger.LogWarning((object)$"No animation clip found for weather type {weatherType}");
				return;
			}
			clips.ToList().ForEach(delegate(KeyValuePair<LevelWeatherType, AnimationClip> clipPair)
			{
				//IL_0002: Unknown result type (might be due to invalid IL or missing references)
				//IL_0008: Unknown result type (might be due to invalid IL or missing references)
				//IL_0028: Unknown result type (might be due to invalid IL or missing references)
				//IL_0059: Unknown result type (might be due to invalid IL or missing references)
				if (clipPair.Key != weatherType)
				{
					clipOverrides[((Object)clipPair.Value).name] = clips[weatherType];
					logger.LogDebug((object)("Setting override from " + ((Object)clipPair.Value).name + " to " + ((Object)clips[weatherType]).name));
				}
				else
				{
					clipOverrides[((Object)clipPair.Value).name] = null;
					logger.LogDebug((object)("Setting override from " + ((Object)clipPair.Value).name + " to null"));
				}
			});
			logger.LogDebug((object)string.Format("Current bools: {0} {1}", TimeOfDay.Instance.sunAnimator.GetBool("overcast"), TimeOfDay.Instance.sunAnimator.GetBool("eclipsed")));
			if ((int)weatherType != -1)
			{
				animatorOverrideController.ApplyOverrides((IList<KeyValuePair<AnimationClip, AnimationClip>>)clipOverrides);
				TimeOfDay.Instance.sunAnimator.runtimeAnimatorController = (RuntimeAnimatorController)(object)animatorOverrideController;
			}
			else
			{
				TimeOfDay.Instance.sunAnimator.runtimeAnimatorController = animatorOverrideController.runtimeAnimatorController;
			}
			logger.LogInfo((object)("Current clip: " + ((Object)((AnimatorClipInfo)(ref TimeOfDay.Instance.sunAnimator.GetCurrentAnimatorClipInfo(0)[0])).clip).name));
		}

		internal static void LogOverrides(AnimationClipOverrides clipOverrides)
		{
			logger.LogDebug((object)$"Overrides: {clipOverrides.Count}");
			clipOverrides.ToList().ForEach(delegate(KeyValuePair<AnimationClip, AnimationClip> clip)
			{
				logger.LogInfo((object)("overrideclip " + (Object.op_Implicit((Object)(object)clip.Key) ? ((Object)clip.Key).name : "null") + " : " + (Object.op_Implicit((Object)(object)clip.Value) ? ((Object)clip.Value).name : "null")));
			});
		}

		internal static void Clear()
		{
			animatorOverrideController = null;
		}
	}
	[HarmonyPatch(typeof(Terminal))]
	public static class TerminalStartPatch
	{
		internal static Logger Logger = new Logger("WeatherRegistry", ConfigManager.LogStartup);

		internal static WeatherEffect[] vanillaEffectsArray { get; private set; } = null;


		[HarmonyPatch(typeof(StartOfRound), "Awake")]
		[HarmonyPrefix]
		[HarmonyPriority(800)]
		internal static void StartOfRoundAwakePrefix(RoundManager __instance)
		{
			Logger.LogInfo("StartOfRoundAwakePrefix Patch");
			if (((Component)GameNetworkManager.Instance).GetComponent<NetworkManager>().IsHost)
			{
				Logger.LogDebug("Host detected, spawning WeatherSync");
				((Component)Object.Instantiate<GameObject>(WeatherSync.WeatherSyncPrefab).GetComponent<WeatherSync>()).GetComponent<NetworkObject>().Spawn(false);
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch("Awake")]
		[HarmonyPriority(800)]
		public static bool TerminalPrefix(Terminal __instance)
		{
			if (WeatherManager.IsSetupFinished)
			{
				WeatherManager.IsSetupFinished = false;
			}
			return true;
		}

		[HarmonyPostfix]
		[HarmonyPatch("Start")]
		[HarmonyPriority(800)]
		public static void Postfix(Terminal __instance)
		{
			//IL_0095: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f1: Unknown result type (might be due to invalid IL or missing references)
			//IL_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0111: Unknown result type (might be due to invalid IL or missing references)
			//IL_0103: Unknown result type (might be due to invalid IL or missing references)
			//IL_0116: Unknown result type (might be due to invalid IL or missing references)
			//IL_0157: Unknown result type (might be due to invalid IL or missing references)
			//IL_015f: Unknown result type (might be due to invalid IL or missing references)
			//IL_032f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0334: Unknown result type (might be due to invalid IL or missing references)
			//IL_0346: Unknown result type (might be due to invalid IL or missing references)
			//IL_035d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0374: Unknown result type (might be due to invalid IL or missing references)
			//IL_038b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0392: Unknown result type (might be due to invalid IL or missing references)
			//IL_0399: Unknown result type (might be due to invalid IL or missing references)
			//IL_03a5: Expected O, but got Unknown
			//IL_0505: Unknown result type (might be due to invalid IL or missing references)
			Logger.LogInfo("Terminal Start Patch");
			WeatherManager.Reset();
			WeatherEffect[] effects = TimeOfDay.Instance.effects;
			List<WeatherEffect> list = effects.ToList();
			if (effects == null || effects.Count() == 0)
			{
				Logger.LogInfo("Effects are null");
			}
			else
			{
				Logger.LogInfo($"Effects: {effects.Count()}");
			}
			Logger.LogInfo("Creating NoneWeather type");
			Weather weather3 = new Weather("None", new ImprovedWeatherEffect(null, null))
			{
				Type = WeatherType.Clear,
				Color = Defaults.VanillaWeatherColors[(LevelWeatherType)(-1)],
				VanillaWeatherType = (LevelWeatherType)(-1),
				Origin = WeatherOrigin.Vanilla
			};
			WeatherManager.Weathers.Add(weather3);
			WeatherManager.NoneWeather = weather3;
			for (int i = 0; i < effects.Count(); i++)
			{
				WeatherEffect val = effects[i];
				Logger.LogInfo("Effect: " + val.name);
				LevelWeatherType val2 = (LevelWeatherType)i;
				bool num = Defaults.VanillaWeathers.Contains(val2);
				WeatherType type = (num ? WeatherType.Vanilla : WeatherType.Modded);
				Color color = (num ? Defaults.VanillaWeatherColors[val2] : Color.blue);
				ImprovedWeatherEffect effect = new ImprovedWeatherEffect(val.effectObject, val.effectPermanentObject)
				{
					SunAnimatorBool = val.sunAnimatorBool
				};
				Weather item = new Weather(((object)(LevelWeatherType)(ref val2)).ToString(), effect)
				{
					Type = type,
					Color = color,
					VanillaWeatherType = val2,
					Origin = WeatherOrigin.Vanilla
				};
				WeatherManager.Weathers.Add(item);
			}
			if (Plugin.IsLethalLibLoaded)
			{
				Logger.LogWarning("Getting LethalLib Weathers");
				foreach (Weather item3 in LethalLibPatch.ConvertLLWeathers())
				{
					Logger.LogWarning("LethalLib Weather: " + item3.Name);
					WeatherManager.RegisteredWeathers.Add(item3);
				}
			}
			int biggestKeyInModdedWeathersDictionary = Enum.GetValues(typeof(LevelWeatherType)).Length - 1;
			if (WeatherManager.ModdedWeatherEnumExtension.Count > 0)
			{
				biggestKeyInModdedWeathersDictionary = WeatherManager.ModdedWeatherEnumExtension.Keys.Max() + 1;
			}
			Logger.LogDebug(WeatherManager.ModdedWeatherEnumExtension.Count > 0);
			Logger.LogDebug("Biggest key in modded weathers dictionary: " + biggestKeyInModdedWeathersDictionary);
			WeatherManager.RegisteredWeathers.Where((Weather weather) => weather.Origin == WeatherOrigin.WeatherRegistry).ToList().ForEach(delegate(Weather weather)
			{
				int num3 = biggestKeyInModdedWeathersDictionary;
				weather.VanillaWeatherType = (LevelWeatherType)num3;
				Logger.LogInfo($"Registering weather {weather.Name} under ID {num3}");
				WeatherManager.ModdedWeatherEnumExtension.Add(num3, weather);
				biggestKeyInModdedWeathersDictionary++;
			});
			int num2 = 0;
			foreach (KeyValuePair<int, Weather> item4 in WeatherManager.ModdedWeatherEnumExtension)
			{
				if (item4.Key > num2)
				{
					num2 = item4.Key;
				}
			}
			while (list.Count <= num2)
			{
				list.Add(null);
			}
			foreach (KeyValuePair<int, Weather> item5 in WeatherManager.ModdedWeatherEnumExtension)
			{
				list[item5.Key] = new WeatherEffect
				{
					name = item5.Value.Name,
					effectObject = item5.Value.Effect.EffectObject,
					effectPermanentObject = item5.Value.Effect.WorldObject,
					sunAnimatorBool = item5.Value.Effect.SunAnimatorBool,
					effectEnabled = false,
					lerpPosition = false,
					transitioning = false
				};
				GameObject effectObject = list[item5.Key].effectObject;
				if (effectObject != null)
				{
					effectObject.SetActive(false);
				}
				GameObject effectPermanentObject = list[item5.Key].effectPermanentObject;
				if (effectPermanentObject != null)
				{
					effectPermanentObject.SetActive(false);
				}
			}
			TimeOfDay.Instance.effects = list.ToArray();
			List<Weather> list2 = WeatherManager.RegisteredWeathers.Distinct().ToList();
			list2.Sort(delegate(Weather a, Weather b)
			{
				//IL_0001: Unknown result type (might be due to invalid IL or missing references)
				//IL_0006: Unknown result type (might be due to invalid IL or missing references)
				//IL_000a: Unknown result type (might be due to invalid IL or missing references)
				LevelWeatherType vanillaWeatherType = a.VanillaWeatherType;
				return ((Enum)(LevelWeatherType)(ref vanillaWeatherType)).CompareTo((object?)b.VanillaWeatherType);
			});
			for (int j = 0; j < list2.Count; j++)
			{
				Logger.LogInfo("Registered Weather: " + list2[j].Name);
				Weather item2 = list2[j];
				WeatherManager.Weathers.Add(item2);
			}
			Logger.LogWarning($"Weathers: {WeatherManager.Weathers.Count}");
			List<SelectableLevel> list3 = StartOfRound.Instance.levels.ToList();
			foreach (Weather weather2 in WeatherManager.Weathers)
			{
				Settings.ScreenMapColors.Add(weather2.Name, weather2.Color);
				weather2.Init();
				List<SelectableLevel> list4 = new List<SelectableLevel>();
				if (weather2.LevelFilteringOption == FilteringOption.Include)
				{
					list4 = weather2.LevelFilters;
				}
				else if (weather2.LevelFilteringOption == FilteringOption.Exclude)
				{
					list4 = StartOfRound.Instance.levels.ToList();
					list4.RemoveAll((SelectableLevel level) => weather2.LevelFilters.Contains(level));
				}
				Logger.LogInfo("Weather " + ((Object)weather2).name + " has " + weather2.LevelFilteringOption.ToString() + " filtering option set up");
				AddWeatherToLevels(weather2, list3, list4);
			}
			ConsoleTable possibleWeathersTable = new ConsoleTable("Planet", "Random weathers");
			list3.Sort((SelectableLevel a, SelectableLevel b) => ConfigHelper.GetNumberlessName(a).CompareTo(ConfigHelper.GetNumberlessName(b)));
			list3.ForEach(delegate(SelectableLevel level)
			{
				List<LevelWeatherType> list5 = level.randomWeathers.Select((RandomWeatherWithVariables x) => x.weatherType).ToList();
				list5.Sort();
				string text = JsonConvert.SerializeObject((object)list5.Select((LevelWeatherType x) => ((object)(LevelWeatherType)(ref x)).ToString()).ToList());
				possibleWeathersTable.AddRow(ConfigHelper.GetNumberlessName(level), text);
			});
			Logger.LogInfo("Possible weathers:\n" + possibleWeathersTable.ToMinimalString());
			WeatherManager.IsSetupFinished = true;
			EventManager.SetupFinished.Invoke();
			StartOfRound.Instance.SetPlanetsWeather(0);
			StartOfRound.Instance.SetMapScreenInfoToCurrentLevel();
			if (!((NetworkBehaviour)StartOfRound.Instance).IsHost)
			{
				WeatherSync.Instance.ApplyWeathers(WeatherSync.Instance.Weather);
			}
		}

		private static void AddWeatherToLevels(Weather weather, List<SelectableLevel> levels, List<SelectableLevel> LevelsToApply)
		{
			List<LevelWeatherVariables> list = new List<LevelWeatherVariables>();
			weather.WeatherVariables.Clear();
			foreach (SelectableLevel level in levels)
			{
				Logger.LogDebug("Level: " + ConfigHelper.GetNumberlessName(level) + ", weather: " + weather.Name);
				List<RandomWeatherWithVariables> randomWeathers2 = level.randomWeathers.ToList();
				LevelWeather levelWeather = new LevelWeather
				{
					Weather = weather,
					Level = level,
					Variables = new LevelWeatherVariables()
				};
				RandomWeatherWithVariables val = null;
				val = ((IEnumerable<RandomWeatherWithVariables>)level.randomWeathers).FirstOrDefault((Func<RandomWeatherWithVariables, bool>)((RandomWeatherWithVariables randomWeather) => randomWeather.weatherType == weather.VanillaWeatherType));
				if (!InitializeRandomWeather(ref val, weather, level, ref randomWeathers2, LevelsToApply))
				{
					Logger.LogDebug("randomWeather is null, skipping");
					continue;
				}
				levelWeather.Variables.Level = level;
				levelWeather.Variables.WeatherVariable1 = val?.weatherVariable ?? 1;
				levelWeather.Variables.WeatherVariable2 = val?.weatherVariable2 ?? 1;
				WeatherManager.LevelWeathers.Add(levelWeather);
				list.Add(levelWeather.Variables);
				weather.WeatherVariables.Add(level, levelWeather.Variables);
			}
			static bool InitializeRandomWeather(ref RandomWeatherWithVariables randomWeather, Weather weather, SelectableLevel level, ref List<RandomWeatherWithVariables> randomWeathers, List<SelectableLevel> LevelsToApply)
			{
				//IL_0253: Unknown result type (might be due to invalid IL or missing references)
				//IL_0258: Unknown result type (might be due to invalid IL or missing references)
				//IL_025f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0264: Unknown result type (might be due to invalid IL or missing references)
				//IL_0269: Unknown result type (might be due to invalid IL or missing references)
				//IL_027f: Unknown result type (might be due to invalid IL or missing references)
				//IL_0296: Expected O, but got Unknown
				if (randomWeather == null && weather.Type == WeatherType.Vanilla)
				{
					return false;
				}
				if (weather.Type == WeatherType.Clear)
				{
					randomWeathers.RemoveAll((RandomWeatherWithVariables randomWeather) => randomWeather.weatherType == weather.VanillaWeatherType);
					level.randomWeathers = randomWeathers.ToArray();
					return false;
				}
				if (level.PlanetName == "71 Gordion" && !LevelsToApply.Contains(level))
				{
					Logger.LogDebug("Removing weather " + weather.Name + " from the company moon");
					randomWeathers.RemoveAll((RandomWeatherWithVariables randomWeather) => randomWeather.weatherType == weather.VanillaWeatherType);
					level.randomWeathers = randomWeathers.ToArray();
					return false;
				}
				switch (weather.Type)
				{
				case WeatherType.Vanilla:
					if (!LevelsToApply.Contains(level))
					{
						Logger.LogDebug("Level " + ((Object)level).name + " is not in the list of levels to apply weather to");
						if (randomWeather != null)
						{
							Logger.LogDebug("Removing weather " + weather.Name + " from level " + ((Object)level).name);
							randomWeathers.RemoveAll((RandomWeatherWithVariables randomWeather) => randomWeather.weatherType == weather.VanillaWeatherType);
							level.randomWeathers = randomWeathers.ToArray();
						}
						return false;
					}
					return true;
				case WeatherType.Modded:
				{
					if (randomWeather != null)
					{
						Logger.LogDebug("Removing weather " + weather.Name + " from level " + ((Object)level).name + " (added before lobby reload)");
						randomWeathers.RemoveAll((RandomWeatherWithVariables randomWeather) => randomWeather.weatherType == weather.VanillaWeatherType);
					}
					Logger.LogDebug("Adding modded weather " + weather.Name);
					if (!LevelsToApply.Contains(level))
					{
						Logger.LogDebug("Level " + ((Object)level).name + " is not in the list of levels to apply weather to");
						return false;
					}
					Logger.LogDebug($"Injecting modded weather {weather.Name} for level {((Object)level).name} (variables {weather.Effect.DefaultVariable1}/{weather.Effect.DefaultVariable2})");
					RandomWeatherWithVariables item = (randomWeather = new RandomWeatherWithVariables
					{
						weatherType = weather.VanillaWeatherType,
						weatherVariable = weather.Effect.DefaultVariable1,
						weatherVariable2 = weather.Effect.DefaultVariable2
					});
					randomWeathers.Add(item);
					level.randomWeathers = randomWeathers.ToArray();
					break;
				}
				}
				return true;
			}
		}
	}
}
namespace WeatherRegistry.Events
{
	public class WeatherRegistryEvent<T>
	{
		public delegate void ParameterEvent(T param);

		public bool HasListeners => Listeners != 0;

		public int Listeners { get; internal set; }

		private event ParameterEvent onParameterEvent;

		public void Invoke(T param)
		{
			this.onParameterEvent?.Invoke(param);
		}

		public void AddListener(ParameterEvent listener)
		{
			onParameterEvent += listener;
			Listeners++;
		}

		public void RemoveListener(ParameterEvent listener)
		{
			onParameterEvent -= listener;
			Listeners--;
		}
	}
	public class WeatherRegistryEvent
	{
		public delegate void Event();

		public bool HasListeners => Listeners != 0;

		public int Listeners { get; internal set; }

		private event Event onEvent;

		public void Invoke()
		{
			this.onEvent?.Invoke();
		}

		public void AddListener(Event listener)
		{
			onEvent += listener;
			Listeners++;
		}

		public void RemoveListener(Event listener)
		{
			onEvent -= listener;
			Listeners--;
		}
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}
namespace WeatherRegistry.NetcodePatcher
{
	[AttributeUsage(AttributeTargets.Module)]
	internal class NetcodePatchedAssemblyAttribute : Attribute
	{
	}
}