Decompiled source of Expand World Events v1.7.0

ExpandWorldEvents.dll

Decompiled 2 months ago
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using Data;
using ExpandWorld.Event;
using ExpandWorld.Spawn;
using ExpandWorldData;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using ServerSync;
using Service;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")]
[assembly: AssemblyCompany("ExpandWorldEvents")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("ExpandWorldEvents")]
[assembly: AssemblyTitle("ExpandWorldEvents")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Microsoft.CodeAnalysis.Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

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

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

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[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 ExpandWorld
{
	public class Configuration
	{
		public static ConfigEntry<bool> configMultipleEvents;

		public static ConfigEntry<string> configEventMinimumDistance;

		public static ConfigEntry<bool> configCheckPerPlayer;

		public static ConfigEntry<string> configEventInterval;

		public static ConfigEntry<string> configEventChance;

		public static CustomSyncedValue<string> valueEventData;

		public static bool MultipleEvents => configMultipleEvents.Value;

		public static float EventMinimumDistance => ConfigWrapper.Floats[configEventMinimumDistance];

		public static bool CheckPerPlayer => configCheckPerPlayer.Value;

		public static float EventInterval => ConfigWrapper.Floats[configEventInterval];

		public static float EventChance => ConfigWrapper.Floats[configEventChance];

		public static void Init(ConfigWrapper wrapper)
		{
			string text = "1. General";
			configMultipleEvents = wrapper.Bind<bool>(text, "Multiple events", false, false, "If enabled, multiple events can be active at the same time.", true);
			configCheckPerPlayer = wrapper.Bind<bool>(text, "Check per player", false, false, "If enabled, the event check is done separately for each player.", true);
			configEventMinimumDistance = wrapper.BindFloat(text, "Minimum distance between events", 100f, false, "The minimum distance between events.", true);
			configEventChance = wrapper.BindFloat(text, "Random event chance", 20f, false, "The chance to try starting a random event.", true);
			configEventChance.SettingChanged += delegate
			{
				RandomEventSystem.Setup(RandEventSystem.instance);
			};
			configEventInterval = wrapper.BindFloat(text, "Random event interval", 46f, false, "How often the random events are checked (minutes).", true);
			configEventInterval.SettingChanged += delegate
			{
				RandomEventSystem.Setup(RandEventSystem.instance);
			};
			RandomEventSystem.Setup(RandEventSystem.instance);
			valueEventData = wrapper.AddValue("event_data");
			((CustomSyncedValueBase)valueEventData).ValueChanged += delegate
			{
				Manager.FromSetting(valueEventData.Value);
			};
		}
	}
	[HarmonyPatch(typeof(RandEventSystem), "Awake")]
	public class RandomEventSystem
	{
		public static void Setup(RandEventSystem rs)
		{
			if (Object.op_Implicit((Object)(object)rs))
			{
				rs.m_eventChance = Configuration.EventChance;
				rs.m_eventIntervalMin = Configuration.EventInterval;
			}
		}

		private static void Postfix(RandEventSystem __instance)
		{
			Setup(__instance);
		}
	}
	[BepInPlugin("expand_world_events", "Expand World Events", "1.7")]
	[BepInDependency("expand_world_data", "1.27")]
	public class EWE : BaseUnityPlugin
	{
		public const string GUID = "expand_world_events";

		public const string NAME = "Expand World Events";

		public const string VERSION = "1.7";

		public static ConfigSync ConfigSync = new ConfigSync("expand_world_events")
		{
			DisplayName = "Expand World Events",
			CurrentVersion = "1.7",
			ModRequired = true,
			IsLocked = true
		};

		public void Awake()
		{
			//IL_002f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Expected O, but got Unknown
			//IL_003e: Unknown result type (might be due to invalid IL or missing references)
			Configuration.Init(new ConfigWrapper("expand_events_config", ((BaseUnityPlugin)this).Config, ConfigSync, (Action)delegate
			{
			}));
			new Harmony("expand_world_events").PatchAll();
			try
			{
				Yaml.SetupWatcher(((BaseUnityPlugin)this).Config);
				if (Configuration.DataReload)
				{
					Manager.SetupWatcher();
				}
			}
			catch (Exception ex)
			{
				Log.Error(ex.StackTrace);
			}
		}

		public static RandomEvent GetCurrentRandomEvent(Vector3 pos)
		{
			//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)
			if (Configuration.MultipleEvents)
			{
				return MultipleEvents.Events.OrderBy((MultiEvent x) => Utils.DistanceXZ(x.Event.m_pos, pos)).FirstOrDefault()?.Event;
			}
			return RandEventSystem.instance.GetCurrentRandomEvent();
		}

		private void OnDestroy()
		{
			((BaseUnityPlugin)this).Config.Save();
		}
	}
}
namespace ExpandWorld.Spawn
{
	public class Data
	{
		public string prefab = "";

		[DefaultValue(true)]
		public bool enabled = true;

		[DefaultValue("")]
		public string biome = "";

		[DefaultValue("")]
		public string biomeArea = "";

		[DefaultValue(100f)]
		public float spawnChance = 100f;

		public int maxSpawned = 1;

		public float spawnInterval;

		[DefaultValue(1)]
		public int maxLevel = 1;

		[DefaultValue(1)]
		public int minLevel = 1;

		[DefaultValue(-10000f)]
		public float minAltitude = -10000f;

		[DefaultValue(10000f)]
		public float maxAltitude = 10000f;

		[DefaultValue(true)]
		public bool spawnAtDay = true;

		[DefaultValue(true)]
		public bool spawnAtNight = true;

		[DefaultValue("")]
		public string requiredGlobalKey = "";

		[DefaultValue("")]
		public string requiredEnvironments = "";

		public float spawnDistance = 10f;

		[DefaultValue(0f)]
		public float spawnRadiusMin;

		[DefaultValue(0f)]
		public float spawnRadiusMax;

		[DefaultValue(1)]
		public int groupSizeMin = 1;

		[DefaultValue(1)]
		public int groupSizeMax = 1;

		[DefaultValue(0f)]
		public float groupRadius;

		[DefaultValue(0f)]
		public float minTilt;

		[DefaultValue(35f)]
		public float maxTilt = 35f;

		[DefaultValue(true)]
		public bool inForest = true;

		[DefaultValue(true)]
		public bool outsideForest = true;

		[DefaultValue(0f)]
		public float minOceanDepth;

		[DefaultValue(0f)]
		public float maxOceanDepth;

		[DefaultValue(false)]
		public bool huntPlayer;

		[DefaultValue(0.5f)]
		public float groundOffset = 0.5f;

		[DefaultValue(0f)]
		public float levelUpMinCenterDistance;

		[DefaultValue(-1f)]
		public float overrideLevelupChance = -1f;

		[DefaultValue("")]
		public string faction = "";

		[DefaultValue("")]
		public string data = "";

		[DefaultValue(null)]
		public string[]? objects;
	}
	public class Loader
	{
		public static Dictionary<SpawnData, DataEntry?> Data = new Dictionary<SpawnData, DataEntry>();

		public static Dictionary<SpawnData, List<BlueprintObject>> Objects = new Dictionary<SpawnData, List<BlueprintObject>>();

		private static readonly int HashFaction = StringExtensionMethods.GetStableHashCode("faction");

		public static SpawnData FromData(Data data)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: 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)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0029: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_003f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: 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_005c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			//IL_0080: Unknown result type (might be due to invalid IL or missing references)
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0098: Unknown result type (might be due to invalid IL or missing references)
			//IL_00aa: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_00da: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00fe: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: 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_0122: Unknown result type (might be due to invalid IL or missing references)
			//IL_012e: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0146: Unknown result type (might be due to invalid IL or missing references)
			//IL_0152: Unknown result type (might be due to invalid IL or missing references)
			//IL_015e: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0176: Unknown result type (might be due to invalid IL or missing references)
			//IL_0182: Unknown result type (might be due to invalid IL or missing references)
			//IL_018f: Expected O, but got Unknown
			//IL_01f5: Unknown result type (might be due to invalid IL or missing references)
			//IL_01fb: Expected O, but got Unknown
			SpawnData val = new SpawnData
			{
				m_prefab = DataManager.ToPrefab(data.prefab),
				m_enabled = data.enabled,
				m_biome = DataManager.ToBiomes(data.biome),
				m_biomeArea = DataManager.ToBiomeAreas(data.biomeArea),
				m_maxSpawned = data.maxSpawned,
				m_spawnInterval = data.spawnInterval,
				m_spawnChance = data.spawnChance,
				m_spawnDistance = data.spawnDistance,
				m_spawnRadiusMin = data.spawnRadiusMin,
				m_spawnRadiusMax = data.spawnRadiusMax,
				m_requiredGlobalKey = data.requiredGlobalKey,
				m_requiredEnvironments = DataManager.ToList(data.requiredEnvironments, true),
				m_groupSizeMin = data.groupSizeMin,
				m_groupSizeMax = data.groupSizeMax,
				m_spawnAtDay = data.spawnAtDay,
				m_spawnAtNight = data.spawnAtNight,
				m_groupRadius = data.groupRadius,
				m_minAltitude = data.minAltitude,
				m_maxAltitude = data.maxAltitude,
				m_minTilt = data.minTilt,
				m_maxTilt = data.maxTilt,
				m_inForest = data.inForest,
				m_outsideForest = data.outsideForest,
				m_minOceanDepth = data.minOceanDepth,
				m_maxOceanDepth = data.maxOceanDepth,
				m_huntPlayer = data.huntPlayer,
				m_groundOffset = data.groundOffset,
				m_maxLevel = data.maxLevel,
				m_minLevel = data.minLevel,
				m_levelUpMinCenterDistance = data.levelUpMinCenterDistance,
				m_overrideLevelupChance = data.overrideLevelupChance
			};
			if (val.m_minAltitude == -10000f)
			{
				val.m_minAltitude = ((val.m_maxAltitude > 0f) ? 0f : (-1000f));
			}
			if (data.data != "")
			{
				Data[val] = DataHelper.Get(data.data);
			}
			if (data.faction != "")
			{
				DataEntry val2 = new DataEntry();
				val2.Strings[HashFaction] = DataValue.Simple(data.faction);
				if (Data.ContainsKey(val))
				{
					Data[val] = DataHelper.Merge((DataEntry[])(object)new DataEntry[2]
					{
						Data[val],
						val2
					});
				}
				else
				{
					Data.Add(val, val2);
				}
			}
			if (data.objects != null)
			{
				Objects[val] = data.objects.Select((string s) => Parse.Split(s, true, ',')).Select((Func<string[], BlueprintObject>)((string[] split) => new BlueprintObject(split[0], Parse.VectorXZY(split, 1), Quaternion.identity, Vector3.one, DataHelper.Get((split.Length > 5) ? split[5] : ""), Parse.Float(split, 4, 1f), false))).ToList();
			}
			return val;
		}

		public static Data ToData(SpawnData spawn)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_0035: Unknown result type (might be due to invalid IL or missing references)
			return new Data
			{
				prefab = ((Object)spawn.m_prefab).name,
				enabled = spawn.m_enabled,
				biome = DataManager.FromBiomes(spawn.m_biome),
				biomeArea = DataManager.FromBiomeAreas(spawn.m_biomeArea),
				maxSpawned = spawn.m_maxSpawned,
				spawnInterval = spawn.m_spawnInterval,
				spawnChance = spawn.m_spawnChance,
				spawnDistance = spawn.m_spawnDistance,
				spawnRadiusMin = spawn.m_spawnRadiusMin,
				spawnRadiusMax = spawn.m_spawnRadiusMax,
				requiredGlobalKey = spawn.m_requiredGlobalKey,
				requiredEnvironments = DataManager.FromList((IEnumerable<string>)spawn.m_requiredEnvironments),
				spawnAtDay = spawn.m_spawnAtDay,
				spawnAtNight = spawn.m_spawnAtNight,
				groupSizeMin = spawn.m_groupSizeMin,
				groupSizeMax = spawn.m_groupSizeMax,
				groupRadius = spawn.m_groupRadius,
				minAltitude = spawn.m_minAltitude,
				maxAltitude = spawn.m_maxAltitude,
				minTilt = spawn.m_minTilt,
				maxTilt = spawn.m_maxTilt,
				inForest = spawn.m_inForest,
				outsideForest = spawn.m_outsideForest,
				minOceanDepth = spawn.m_minOceanDepth,
				maxOceanDepth = spawn.m_maxOceanDepth,
				huntPlayer = spawn.m_huntPlayer,
				groundOffset = spawn.m_groundOffset,
				maxLevel = spawn.m_maxLevel,
				minLevel = spawn.m_minLevel,
				levelUpMinCenterDistance = spawn.m_levelUpMinCenterDistance,
				overrideLevelupChance = spawn.m_overrideLevelupChance
			};
		}
	}
	[HarmonyPatch(typeof(SpawnSystem), "Spawn")]
	public class SpawnZDO
	{
		private static void Prefix(SpawnData critter, Vector3 spawnPoint)
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			if (Loader.Data.TryGetValue(critter, out DataEntry value))
			{
				DataHelper.Init(critter.m_prefab, spawnPoint, Quaternion.identity, (Vector3?)null, value);
			}
		}

		private static string PrefabOverride(string prefab)
		{
			return prefab;
		}

		private static DataEntry? DataOverride(DataEntry? data, string prefab)
		{
			return data;
		}

		private static void Postfix(SpawnData critter, Vector3 spawnPoint)
		{
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_003d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Unknown result type (might be due to invalid IL or missing references)
			if (!Loader.Objects.TryGetValue(critter, out List<BlueprintObject> value))
			{
				return;
			}
			foreach (BlueprintObject item in value)
			{
				if (!(item.Chance < 1f) || !(Random.value > item.Chance))
				{
					Spawn.BPO(item, spawnPoint, Quaternion.identity, Vector3.one, (Func<DataEntry, string, DataEntry>)DataOverride, (Func<string, string>)PrefabOverride, (List<GameObject>)null);
				}
			}
		}
	}
}
namespace ExpandWorld.Event
{
	[HarmonyPatch(typeof(RandEventSystem))]
	public class CheckPerPlayer
	{
		[HarmonyPatch("UpdateRandomEvent")]
		[HarmonyPrefix]
		private static void FixedUpdate(RandEventSystem __instance, float dt)
		{
			//IL_0062: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Unknown result type (might be due to invalid IL or missing references)
			//IL_0086: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			if (Helper.IsClient() || !Configuration.CheckPerPlayer)
			{
				return;
			}
			__instance.m_eventTimer += dt;
			if (Game.m_eventRate == 0f || __instance.m_eventTimer <= __instance.m_eventIntervalMin * 60f * Game.m_eventRate)
			{
				return;
			}
			__instance.m_eventTimer = 0f - dt;
			RandEventSystem.RefreshPlayerEventData();
			foreach (PlayerEventData item in RandEventSystem.RefreshPlayerEventData())
			{
				if (!(Random.Range(0f, 100f) > __instance.m_eventChance / Game.m_eventRate))
				{
					List<KeyValuePair<RandomEvent, Vector3>> possibleRandomEvents = GetPossibleRandomEvents(__instance, item);
					if (possibleRandomEvents.Count != 0)
					{
						KeyValuePair<RandomEvent, Vector3> keyValuePair = possibleRandomEvents[Random.Range(0, possibleRandomEvents.Count)];
						__instance.SetRandomEvent(keyValuePair.Key, keyValuePair.Value);
					}
				}
			}
		}

		private static List<KeyValuePair<RandomEvent, Vector3>> GetPossibleRandomEvents(RandEventSystem obj, PlayerEventData player)
		{
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0074: Unknown result type (might be due to invalid IL or missing references)
			obj.m_lastPossibleEvents.Clear();
			foreach (RandomEvent @event in obj.m_events)
			{
				List<PlayerEventData> list = new List<PlayerEventData> { player };
				if (@event.m_enabled && @event.m_random && obj.HaveGlobalKeys(@event, list))
				{
					List<Vector3> validEventPoints = obj.GetValidEventPoints(@event, list);
					if (validEventPoints.Count != 0)
					{
						Vector3 value = validEventPoints[Random.Range(0, validEventPoints.Count)];
						obj.m_lastPossibleEvents.Add(new KeyValuePair<RandomEvent, Vector3>(@event, value));
					}
				}
			}
			return obj.m_lastPossibleEvents;
		}
	}
	[HarmonyPatch(typeof(RandomEvent))]
	public class Commands
	{
		[HarmonyPatch("OnStart")]
		[HarmonyPostfix]
		private static void OnStart(RandomEvent __instance)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			if (!Helper.IsClient())
			{
				RandomEvent @event = RandEventSystem.instance.GetEvent(__instance.m_name);
				if (Loader.ExtraData.TryGetValue(@event, out ExtraData value) && value.StartCommands != null)
				{
					string[]? startCommands = value.StartCommands;
					Vector3 pos = __instance.m_pos;
					Quaternion identity = Quaternion.identity;
					CommandManager.Run((IEnumerable<string>)startCommands, pos, ((Quaternion)(ref identity)).eulerAngles);
				}
			}
		}

		[HarmonyPatch("OnStop")]
		[HarmonyPostfix]
		private static void OnStop(RandomEvent __instance)
		{
			//IL_0037: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0041: Unknown result type (might be due to invalid IL or missing references)
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			if (!Helper.IsClient())
			{
				RandomEvent @event = RandEventSystem.instance.GetEvent(__instance.m_name);
				if (Loader.ExtraData.TryGetValue(@event, out ExtraData value) && value.EndCommands != null)
				{
					string[]? endCommands = value.EndCommands;
					Vector3 pos = __instance.m_pos;
					Quaternion identity = Quaternion.identity;
					CommandManager.Run((IEnumerable<string>)endCommands, pos, ((Quaternion)(ref identity)).eulerAngles);
				}
			}
		}
	}
	public class Data
	{
		public string name = "";

		[DefaultValue(true)]
		public bool enabled = true;

		[DefaultValue(60f)]
		public float duration = 60f;

		[DefaultValue("3")]
		public string nearBaseOnly = "3";

		[DefaultValue("")]
		public string biome = "";

		[DefaultValue("")]
		public string requiredGlobalKeys = "";

		[DefaultValue("")]
		public string notRequiredGlobalKeys = "";

		[DefaultValue("")]
		public string requiredPlayerKeys = "";

		[DefaultValue("")]
		public string notRequiredPlayerKeys = "";

		[DefaultValue("")]
		public string requiredKnownItems = "";

		[DefaultValue("")]
		public string notRequiredKnownItems = "";

		[DefaultValue("")]
		public string requiredEnvironments = "";

		[DefaultValue("")]
		public string startMessage = "";

		[DefaultValue("")]
		public string endMessage = "";

		public string forceMusic = "";

		[DefaultValue("")]
		public string forceEnvironment = "";

		public ExpandWorld.Spawn.Data[] spawns = new ExpandWorld.Spawn.Data[0];

		[DefaultValue(true)]
		public bool pauseIfNoPlayerInArea = true;

		[DefaultValue(true)]
		public bool random = true;

		[DefaultValue(100f)]
		public float playerDistance = 100f;

		[DefaultValue("")]
		public string playerLimit = "";

		[DefaultValue("")]
		public string eventLimit = "";

		[DefaultValue(null)]
		public string[]? startCommands;

		[DefaultValue(null)]
		public string[]? endCommands;
	}
	public class ExtraData
	{
		public List<string> RequiredEnvironments = new List<string>();

		public float PlayerDistance = 100f;

		public Range<int>? PlayerLimit;

		public int BaseValue = 3;

		public Range<int>? EventLimit;

		public string[]? StartCommands;

		public string[]? EndCommands;

		public ExtraData(Data data)
		{
			RequiredEnvironments = DataManager.ToList(data.requiredEnvironments, true);
			PlayerDistance = data.playerDistance;
			if (data.playerLimit != "")
			{
				PlayerLimit = Parse.IntRange(data.playerLimit);
			}
			if (data.eventLimit != "")
			{
				EventLimit = Parse.IntRange(data.eventLimit);
			}
			if (data.nearBaseOnly != "true")
			{
				BaseValue = Parse.Int(data.nearBaseOnly, 0);
			}
			StartCommands = data.startCommands;
			EndCommands = data.endCommands;
		}
	}
	public class Loader
	{
		public static Dictionary<RandomEvent, ExtraData> ExtraData = new Dictionary<RandomEvent, ExtraData>();

		public static RandomEvent FromData(Data data)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_0072: Unknown result type (might be due to invalid IL or missing references)
			//IL_007e: Unknown result type (might be due to invalid IL or missing references)
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ac: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b3: 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_00bd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f3: Unknown result type (might be due to invalid IL or missing references)
			//IL_0105: Unknown result type (might be due to invalid IL or missing references)
			//IL_0117: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_0135: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Unknown result type (might be due to invalid IL or missing references)
			//IL_014d: Unknown result type (might be due to invalid IL or missing references)
			//IL_015a: Expected O, but got Unknown
			RandomEvent val = new RandomEvent
			{
				m_name = data.name,
				m_spawn = (from s in data.spawns.Select(ExpandWorld.Spawn.Loader.FromData)
					where Object.op_Implicit((Object)(object)s.m_prefab)
					select s).ToList(),
				m_enabled = data.enabled,
				m_random = data.random,
				m_duration = data.duration,
				m_nearBaseOnly = (data.nearBaseOnly != "false"),
				m_pauseIfNoPlayerInArea = data.pauseIfNoPlayerInArea,
				m_biome = DataManager.ToBiomes(data.biome),
				m_requiredGlobalKeys = DataManager.ToList(data.requiredGlobalKeys, true),
				m_notRequiredGlobalKeys = DataManager.ToList(data.notRequiredGlobalKeys, true),
				m_altRequiredPlayerKeysAny = DataManager.ToList(data.requiredPlayerKeys, true),
				m_altNotRequiredPlayerKeys = DataManager.ToList(data.notRequiredPlayerKeys, true),
				m_altRequiredKnownItems = DataManager.ToItemList(data.requiredKnownItems, true),
				m_altRequiredNotKnownItems = DataManager.ToItemList(data.notRequiredKnownItems, true),
				m_startMessage = data.startMessage,
				m_endMessage = data.endMessage,
				m_forceMusic = data.forceMusic,
				m_forceEnvironment = data.forceEnvironment
			};
			ExtraData[val] = new ExtraData(data);
			return val;
		}

		public static Data ToData(RandomEvent random)
		{
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			return new Data
			{
				name = random.m_name,
				spawns = random.m_spawn.Select(ExpandWorld.Spawn.Loader.ToData).ToArray(),
				enabled = random.m_enabled,
				random = random.m_random,
				duration = random.m_duration,
				nearBaseOnly = (random.m_nearBaseOnly ? "3" : "0"),
				pauseIfNoPlayerInArea = random.m_pauseIfNoPlayerInArea,
				biome = DataManager.FromBiomes(random.m_biome),
				requiredGlobalKeys = DataManager.FromList((IEnumerable<string>)random.m_requiredGlobalKeys),
				notRequiredGlobalKeys = DataManager.FromList((IEnumerable<string>)random.m_notRequiredGlobalKeys),
				requiredPlayerKeys = DataManager.FromList((IEnumerable<string>)random.m_altRequiredPlayerKeysAny),
				notRequiredPlayerKeys = DataManager.FromList((IEnumerable<string>)random.m_altNotRequiredPlayerKeys),
				requiredKnownItems = DataManager.FromList((IEnumerable<ItemDrop>)random.m_altRequiredKnownItems),
				notRequiredKnownItems = DataManager.FromList((IEnumerable<ItemDrop>)random.m_altRequiredNotKnownItems),
				startMessage = random.m_startMessage,
				endMessage = random.m_endMessage,
				forceMusic = random.m_forceMusic,
				forceEnvironment = random.m_forceEnvironment
			};
		}
	}
	[HarmonyPatch(typeof(RandEventSystem), "SetRandomEvent")]
	[HarmonyPriority(800)]
	public class MultipleConfigurationsPerEvent
	{
		private static void Prefix(RandEventSystem __instance, ref RandomEvent ev)
		{
			ev = __instance.GetEvent(ev?.m_name);
		}
	}
	public class Manager
	{
		public static string FileName = "expand_events.yaml";

		public static string FilePath = Path.Combine(Yaml.Directory, FileName);

		public static string Pattern = "expand_events*.yaml";

		public static List<RandomEvent> Originals = new List<RandomEvent>();

		public static void ToFile()
		{
			if (!Helper.IsClient() && !File.Exists(FilePath))
			{
				string contents = Yaml.Serializer().Serialize((object)RandEventSystem.instance.m_events.Select(Loader.ToData).ToList());
				File.WriteAllText(FilePath, contents);
			}
		}

		public static void FromFile()
		{
			if (!Helper.IsClient())
			{
				Set(DataManager.Read(Pattern));
				RandEventSystem.instance.m_events.Distinct(new Comparer());
				Configuration.valueEventData.Value = Yaml.Serializer().Serialize((object)RandEventSystem.instance.m_events.Select(Loader.ToData).ToList());
			}
		}

		public static void FromSetting(string yaml)
		{
			if (Helper.IsClient())
			{
				Set(yaml);
			}
		}

		private static void Set(string yaml)
		{
			if (Helper.IsServer() && Originals.Count == 0)
			{
				List<RandomEvent> list = new List<RandomEvent>();
				foreach (RandomEvent @event in RandEventSystem.instance.m_events)
				{
					list.Add(@event);
				}
				Originals = list;
			}
			Loader.ExtraData.Clear();
			if (yaml == "")
			{
				return;
			}
			try
			{
				List<RandomEvent> list2 = Yaml.Deserialize<Data>(yaml, FileName).Select(Loader.FromData).ToList();
				if (list2.Count == 0)
				{
					Log.Warning("Failed to load any event data.");
				}
				else if (!Configuration.DataMigration || !Helper.IsServer() || !AddMissingEntries(list2))
				{
					Log.Info($"Reloading event data ({list2.Count} entries).");
					RandEventSystem.instance.m_events = list2;
				}
			}
			catch (Exception ex)
			{
				Log.Error(ex.Message);
				Log.Error(ex.StackTrace);
			}
		}

		private static bool AddMissingEntries(List<RandomEvent> entries)
		{
			HashSet<string> missingKeys = Originals.Select((RandomEvent e) => e.m_name).Distinct().ToHashSet();
			foreach (RandomEvent entry in entries)
			{
				missingKeys.Remove(entry.m_name);
			}
			if (missingKeys.Count == 0)
			{
				return false;
			}
			List<RandomEvent> list = Originals.Where((RandomEvent item) => missingKeys.Contains(item.m_name)).ToList();
			Log.Warning($"Adding {list.Count} missing events to the expand_events.yaml file.");
			foreach (RandomEvent item in list)
			{
				Log.Warning(item.m_name);
			}
			string text = File.ReadAllText(FilePath);
			string text2 = Yaml.Serializer().Serialize((object)list.Select(Loader.ToData));
			text = text + "\n" + text2;
			File.WriteAllText(FilePath, text);
			return true;
		}

		public static void SetupWatcher()
		{
			Yaml.SetupWatcher(Pattern, (Action)FromFile);
		}
	}
	[HarmonyPatch(typeof(ZoneSystem), "Start")]
	[HarmonyPriority(0)]
	public class InitializeContent
	{
		private static void Postfix()
		{
			if (Helper.IsServer())
			{
				Manager.ToFile();
				Manager.FromFile();
			}
		}
	}
	public class Comparer : IEqualityComparer<RandomEvent>
	{
		public bool Equals(RandomEvent x, RandomEvent y)
		{
			return x.m_name == y.m_name;
		}

		public int GetHashCode(RandomEvent obj)
		{
			return StringExtensionMethods.GetStableHashCode(obj.m_name);
		}
	}
	[HarmonyPatch(typeof(RandEventSystem), "InValidBiome")]
	public class ExtraChecks
	{
		private static bool Postfix(bool result, RandomEvent ev, Vector3 point)
		{
			//IL_0016: 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)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			if (!result)
			{
				return false;
			}
			if (!Loader.ExtraData.TryGetValue(ev, out ExtraData value))
			{
				return true;
			}
			if (!EnvCheck(point, value.RequiredEnvironments))
			{
				return false;
			}
			if (!PlayerCheck(point, value.PlayerLimit, value.PlayerDistance))
			{
				return false;
			}
			if (!EventCheck(point, value.EventLimit))
			{
				return false;
			}
			return true;
		}

		private static bool EnvCheck(Vector3 pos, List<string> required)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			//IL_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_0031: Unknown result type (might be due to invalid IL or missing references)
			if (required.Count == 0)
			{
				return true;
			}
			Biome biome = WorldGenerator.instance.GetBiome(pos);
			EnvMan instance = EnvMan.instance;
			List<EnvEntry> availableEnvironments = instance.GetAvailableEnvironments(biome);
			if (availableEnvironments == null || availableEnvironments.Count == 0)
			{
				return false;
			}
			State state = Random.state;
			Random.InitState((int)((long)ZNet.instance.GetTimeSeconds() / instance.m_environmentDuration));
			EnvSetup val = instance.SelectWeightedEnvironment(availableEnvironments);
			Random.state = state;
			return required.Contains(val.m_name.ToLower());
		}

		private static bool PlayerCheck(Vector3 pos, Range<int>? limit, float distance)
		{
			//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)
			if (limit == null)
			{
				return true;
			}
			int num = (from p in RandEventSystem.RefreshPlayerEventData()
				where Utils.DistanceXZ(pos, p.position) <= distance
				select p).Count();
			if (limit.Min <= num)
			{
				return num <= limit.Max;
			}
			return false;
		}

		private static bool EventCheck(Vector3 pos, Range<int>? limit)
		{
			//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)
			if (limit == null)
			{
				return true;
			}
			if (!Configuration.MultipleEvents)
			{
				return true;
			}
			int num = MultipleEvents.Events.Where((MultiEvent p) => Utils.DistanceXZ(pos, p.Event.m_pos) <= Configuration.EventMinimumDistance).Sum((MultiEvent p) => p.Count);
			if (limit.Min <= num)
			{
				return num <= limit.Max;
			}
			return false;
		}
	}
	[HarmonyPatch(typeof(RandEventSystem), "CheckBase")]
	public class CheckBase
	{
		private static bool Prefix(RandomEvent ev, PlayerEventData player, ref bool __result)
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			if (!Loader.ExtraData.TryGetValue(ev, out ExtraData value))
			{
				return true;
			}
			__result = player.baseValue >= value.BaseValue;
			return false;
		}
	}
	public class MultiEvent
	{
		public RandomEvent Event;

		public int Count;

		public MultiEvent(RandomEvent ev, int count)
		{
			Event = ev;
			Count = count;
			base..ctor();
		}
	}
	[HarmonyPatch(typeof(RandEventSystem))]
	public class MultipleEvents
	{
		public static readonly List<MultiEvent> Events = new List<MultiEvent>();

		[HarmonyPatch("FixedUpdate")]
		[HarmonyPrefix]
		private static bool FixedUpdate(RandEventSystem __instance)
		{
			//IL_0122: Unknown result type (might be due to invalid IL or missing references)
			RandEventSystem __instance2 = __instance;
			if (Helper.IsClient() || !Configuration.MultipleEvents)
			{
				return true;
			}
			float fixedDeltaTime = Time.fixedDeltaTime;
			RandEventSystem val = __instance2;
			val.UpdateForcedEvents(fixedDeltaTime);
			val.UpdateRandomEvent(fixedDeltaTime);
			RandomEvent forcedEvent = val.m_forcedEvent;
			if (forcedEvent != null)
			{
				forcedEvent.Update(true, true, true, fixedDeltaTime);
			}
			List<MultiEvent> list = Events.Where(delegate(MultiEvent x)
			{
				bool flag = __instance2.IsAnyPlayerInEventArea(x.Event);
				return x.Event.Update(true, true, flag, Time.fixedDeltaTime);
			}).ToList();
			list.ForEach(delegate(MultiEvent x)
			{
				x.Event.OnStop();
			});
			Events.RemoveAll(list.Contains);
			if (val.m_forcedEvent != null)
			{
				val.SetActiveEvent(val.m_forcedEvent, false);
			}
			else if (Object.op_Implicit((Object)(object)Player.m_localPlayer))
			{
				RandomEvent val2 = (val.m_randomEvent = Events.OrderBy((MultiEvent x) => Utils.DistanceXZ(x.Event.m_pos, ((Component)Player.m_localPlayer).transform.position)).FirstOrDefault()?.Event);
				if (val2 != null && val.IsInsideRandomEventArea(val2, ((Component)Player.m_localPlayer).transform.position))
				{
					__instance2.SetActiveEvent(val2, false);
				}
				else
				{
					val.SetActiveEvent((RandomEvent)null, false);
				}
			}
			else
			{
				val.SetActiveEvent((RandomEvent)null, false);
			}
			return false;
		}

		[HarmonyPatch("SetRandomEvent")]
		[HarmonyPrefix]
		private static bool SetRandomEvent(RandEventSystem __instance, RandomEvent ev, Vector3 pos)
		{
			//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_00cf: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			if (Helper.IsClient() || !Configuration.MultipleEvents)
			{
				return true;
			}
			if (ev == null)
			{
				List<MultiEvent> list = Events.ToList();
				list.ForEach(delegate(MultiEvent x)
				{
					x.Event.OnStop();
				});
				Events.RemoveAll(list.Contains);
				return false;
			}
			List<MultiEvent> list2 = Events.Where((MultiEvent x) => Utils.DistanceXZ(x.Event.m_pos, pos) < Configuration.EventMinimumDistance).ToList();
			list2.ForEach(delegate(MultiEvent x)
			{
				x.Event.OnStop();
			});
			Events.RemoveAll(list2.Contains);
			RandomEvent val = ev.Clone();
			val.m_pos = pos;
			val.OnStart();
			int count = list2.Sum((MultiEvent x) => x.Count) + 1;
			Events.Add(new MultiEvent(val, count));
			__instance.SendCurrentRandomEvent();
			return false;
		}

		[HarmonyPatch("SendCurrentRandomEvent")]
		[HarmonyPrefix]
		private static bool SendCurrentRandomEvent()
		{
			//IL_0068: Unknown result type (might be due to invalid IL or missing references)
			if (Helper.IsClient() || !Configuration.MultipleEvents || Events.Count == 0)
			{
				return true;
			}
			if (Events.Count == 1)
			{
				RandomEvent @event = Events.First().Event;
				ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "SetEvent", new object[3] { @event.m_name, @event.m_time, @event.m_pos });
				return false;
			}
			ZNet.instance.GetPeers().ForEach(delegate(ZNetPeer peer)
			{
				//IL_0071: Unknown result type (might be due to invalid IL or missing references)
				if (peer.m_rpc != null)
				{
					RandomEvent event2 = Events.OrderBy((MultiEvent x) => Utils.DistanceXZ(x.Event.m_pos, peer.m_refPos)).First().Event;
					ZRoutedRpc.instance.InvokeRoutedRPC(peer.m_uid, "SetEvent", new object[3] { event2.m_name, event2.m_time, event2.m_pos });
				}
			});
			return false;
		}
	}
}