Decompiled source of RandomMoonFX Fork v0.1.1

RandomMoonFX_Fork.dll

Decompiled a minute ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using System.Text.RegularExpressions;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace RandomMoonFX_Fork
{
	public static class PluginInfo
	{
		public const string PLUGIN_GUID = "RandomMoonFX_Fork";

		public const string PLUGIN_NAME = "RandomMoonFX_Fork";

		public const string PLUGIN_VERSION = "1.0.0";
	}
}
namespace RandomMoonFX
{
	internal class Config
	{
		public readonly List<string> MoonsBlacklist = new List<string>();

		public readonly Dictionary<string, int> MoonsDistribution = new Dictionary<string, int>();

		public readonly ConfigEntry<bool> CelestialTintAnimation;

		public readonly ConfigEntry<bool> ChameleonAnimation;

		public readonly ConfigEntry<float> AnimationTimeOverride;

		public readonly ConfigEntry<bool> ActivateRandomMoons;

		public readonly ConfigEntry<bool> ExcludePreviouslyVisited;

		public readonly ConfigEntry<bool> ConstellationsCheck;

		public readonly ConfigEntry<string> MoonsBlacklistStr;

		public readonly ConfigEntry<bool> QuotaCheck;

		public readonly ConfigEntry<bool> RandomizeLastDay;

		public readonly ConfigEntry<string> CompanyRoutingMode;

		public readonly ConfigEntry<string> SelectedCompanyName;

		public readonly ConfigEntry<bool> ActivateFreeMoons;

		public readonly ConfigEntry<bool> ActivateMoonsDistributions;

		public readonly ConfigEntry<string> MoonsDistributionStr;

		public Config(ConfigFile cfg)
		{
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Expected O, but got Unknown
			cfg.SaveOnConfigSet = false;
			CelestialTintAnimation = cfg.Bind<bool>("Routing animation", "Celestial_Tint animation", true, "Enable compatibility with Celestial_Tint routing animation (which is a little bit longer than vanilla).\nWill be automatically false if Celestial_Tint is not installed.");
			ChameleonAnimation = cfg.Bind<bool>("Routing animation", "Chameleon animation", true, "Enable compatibility with Chameleon routing animation (which is longer than vanilla).\nWill be automatically false if Chameleon is not installed.");
			AnimationTimeOverride = cfg.Bind<float>("Routing animation", "Animation time override", -1f, "If not -1, will change the time of the routing animation.\nIf you have Celestial_Tint or Chameleon compatibility enabled the time will be changed automatically but you can still modify it with this config.\nDefault value is 1.5, Celestial_Tint is 4 and Chameleon is 7.5.");
			ActivateRandomMoons = cfg.Bind<bool>("Randomization method", "Activate Random Moons", true, "Allow the mod to randomize the moon. Disabling this config effectively prevent the mod to work.\nFor testing purpose.");
			ExcludePreviouslyVisited = cfg.Bind<bool>("Randomization method", "Exclude previously visited", false, "Enable this if you want to exclude already visited moons from the randomization method. This will reset when all moons have been seen once.");
			ConstellationsCheck = cfg.Bind<bool>("Randomization method", "LethalConstellations check", true, "Enable compatibility with LethalConstellations by preventing the randomization method to choose a moon that is not included in the current constellations.\nWill be automatically false if LethalConstellations is not installed.");
			MoonsBlacklistStr = cfg.Bind<string>("Randomization method", "Moons Blacklist", "", "Comma separated list of moons that will never be chosen by the randomization method, if you don't want to play on specifics moons.\nThis Experimentation,Embrion,Asteroid-14,Espira is a valid example.");
			QuotaCheck = cfg.Bind<bool>("Last day check", "Quota check", true, "If true, the ship will route to the Company on the last day if quota has not been met yet. If false, there will be no quota check and the ship will route to the Company only on the last day.");
			RandomizeLastDay = cfg.Bind<bool>("Last day check", "Randomize last day", false, "Enable this if you don't want to auto route to the Company on the last day if there is not enough scraps in the ship to meet quota (other players potential dead bodies included), this allows you to randomize a moon on the last day to mess around but you will be fired at the end of the day.");
			CompanyRoutingMode = cfg.Bind<string>("Last day check", "Company routing mode", "Random", new ConfigDescription("Choose how the mod works when auto-routing on the Company on the last day.\n'Random' will select a random Company moon (vanilla or modded).\n'Select' will route to the moon defined by the 'Selected Company' config.\n'Manual' will disable auto routing to the Company so players must route manually on the last day.", (AcceptableValueBase)(object)new AcceptableValueList<string>(new string[3] { "Random", "Select", "Manual" }), Array.Empty<object>()));
			SelectedCompanyName = cfg.Bind<string>("Last day check", "Selected Company", "Gordion", "When 'Company routing mode' is set to 'Select', you can use this config to choose which moon is going to be auto-routed to on the last day.\nIf the moon is not found, it will default to Gordion.");
			ActivateFreeMoons = cfg.Bind<bool>("Misc", "Activate Free Moons", true, "Prevent credits consumption when manually routing to a moon in the terminal. This is for avoiding people wasting money on a moon that is not going to be played because of the randomization method.\nThis config works even if 'Activate Random Moons' is false.");
			ActivateMoonsDistributions = cfg.Bind<bool>("Moons Distribution", "Activate Moons Distributions", false, "If enabled Moons Distribution list will work as white list.");
			MoonsDistributionStr = cfg.Bind<string>("Moons Distribution", "Moons Distribution", "Vow=1,Adamance=1,Rend=3,Dine=1,Titan=1,Artifice=5,Embrion=1", "You need to input list of moons with their distribution value.\nDefault value is 1, you can input whatever integer number you want, it will calculate distribution based on all moons value.\nExample of input:\nRend=1,Dine=1,Titan=1,Artifice=2");
			cfg.Save();
			cfg.SaveOnConfigSet = true;
		}

		public void SetupCustomConfigs()
		{
			if (MoonsBlacklistStr != null && MoonsBlacklistStr.Value != "")
			{
				foreach (string item in from text in MoonsBlacklistStr.Value.Split(',')
					select text.Trim())
				{
					MoonsBlacklist.Add(Utils.GetNormalizedMoonName(item));
				}
			}
			if (MoonsDistributionStr == null || !(MoonsDistributionStr.Value != ""))
			{
				return;
			}
			foreach (string item2 in from text in MoonsDistributionStr.Value.Split(',')
				select text.Trim())
			{
				string normalizedMoonName = Utils.GetNormalizedMoonName(item2.Split('=')[0]);
				string s = item2.Split('=')[1];
				if (int.TryParse(s, out var result))
				{
					MoonsDistribution.Add(normalizedMoonName, result);
				}
				else
				{
					MoonsDistribution.Add(normalizedMoonName, 0);
				}
			}
		}
	}
	[HarmonyPatch(typeof(StartOfRound))]
	internal class StartOfRoundPatch
	{
		[HarmonyPrefix]
		[HarmonyPatch("StartGame")]
		public static bool RandomizeMoonPatch()
		{
			if (Plugin.instance.CompanyRoutingMode == Plugin.CompanyRM.Manual && Plugin.instance.LastDayOfQuota())
			{
				return true;
			}
			if (Plugin.instance.IsStarting)
			{
				Plugin.instance.IsStarting = false;
				return true;
			}
			Plugin.instance.RouteRandomPlanet();
			return false;
		}

		[HarmonyPostfix]
		[HarmonyPatch("TravelToLevelEffects")]
		public static IEnumerator StartMoonPatch(IEnumerator result)
		{
			while (result.MoveNext())
			{
				yield return result.Current;
			}
			if ((Plugin.instance.CompanyRoutingMode != Plugin.CompanyRM.Manual || !Plugin.instance.LastDayOfQuota()) && Plugin.instance.IsStarting)
			{
				StartMatchLever lever = Object.FindObjectOfType<StartMatchLever>();
				lever.triggerScript.interactable = false;
				yield return (object)new WaitForSeconds(Plugin.instance.AnimationTime);
				lever.triggerScript.interactable = true;
				Plugin.instance.StartRandomPlanet();
			}
		}
	}
	[HarmonyPatch(typeof(StartMatchLever))]
	internal class StartMatchLeverPatch
	{
		[HarmonyPrefix]
		[HarmonyPatch("BeginHoldingInteractOnLever")]
		public static bool DisabledLastDayWarningPatch()
		{
			if (StartOfRound.Instance.CanChangeLevels() && Plugin.instance.LastDayOfQuota() && Plugin.instance.CompanyRoutingMode != Plugin.CompanyRM.Manual)
			{
				return false;
			}
			return true;
		}

		[HarmonyPostfix]
		[HarmonyPatch("BeginHoldingInteractOnLever")]
		public static void DisabledLongHoldTime(ref StartMatchLever __instance)
		{
			if (TimeOfDay.Instance.daysUntilDeadline <= 0 && __instance.playersManager.inShipPhase && StartOfRound.Instance.currentLevel.planetHasTime && Plugin.instance.LastDayOfQuota() && Plugin.instance.CompanyRoutingMode != Plugin.CompanyRM.Manual)
			{
				__instance.triggerScript.timeToHold = 0.7f;
			}
		}
	}
	[HarmonyPatch(typeof(Terminal))]
	internal class TerminalPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch("Awake")]
		public static void AwakePatch()
		{
			Plugin.instance.terminal = Object.FindObjectOfType<Terminal>();
		}

		[HarmonyPrefix]
		[HarmonyPatch("LoadNewNode")]
		public static void LoadNewNodePrePatch(ref TerminalNode node)
		{
			if ((Object)(object)Plugin.instance.terminal != (Object)null && (Object)(object)node != (Object)null && node.buyRerouteToMoon == -2)
			{
				Plugin.instance.terminalCostOfItems = Plugin.instance.terminal.totalCostOfItems;
				Plugin.instance.terminal.totalCostOfItems = 0;
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch("LoadNewNode")]
		public static void LoadNewNodePostPatch(ref TerminalNode node)
		{
			if ((Object)(object)Plugin.instance.terminal != (Object)null && (Object)(object)node != (Object)null && Plugin.instance.terminalCostOfItems != -5)
			{
				Plugin.instance.terminal.totalCostOfItems = 0;
				Plugin.instance.terminalCostOfItems = -5;
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch("LoadNewNodeIfAffordable")]
		public static void LoadNewNodeIfAffordablePatch(ref TerminalNode node)
		{
			if ((Object)(object)Plugin.instance.terminal != (Object)null && (Object)(object)node != (Object)null && node.buyRerouteToMoon != -1)
			{
				node.itemCost = 0;
			}
		}
	}
	[BepInPlugin("zigzag.randommoonfx", "RandomMoonFX", "1.4.2")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public enum CompanyRM
		{
			Random,
			Select,
			Manual
		}

		private const string GUID = "zigzag.randommoonfx";

		private const string NAME = "RandomMoonFX";

		private const string VERSION = "1.4.2";

		public static Plugin instance;

		private readonly Harmony harmony = new Harmony("zigzag.randommoonfx");

		private readonly int GordionID = 3;

		public float AnimationTime = 1.5f;

		public bool IsStarting = false;

		public CompanyRM CompanyRoutingMode;

		public string SelectedCompanyName = "";

		public int SelectedCompanyID = -1;

		public Terminal? terminal;

		public int terminalCostOfItems = -5;

		public bool constellationsCompatibility = false;

		public List<string> VisitedMoons = new List<string>();

		public List<SelectableLevel> CompanyMoons = new List<SelectableLevel>();

		internal static Config config { get; private set; }

		private void Awake()
		{
			instance = this;
			SetParameters();
			if (config.ActivateRandomMoons.Value)
			{
				harmony.CreateClassProcessor(typeof(StartOfRoundPatch), true).Patch();
				harmony.CreateClassProcessor(typeof(StartMatchLeverPatch), true).Patch();
			}
			if (config.ActivateFreeMoons.Value)
			{
				harmony.CreateClassProcessor(typeof(TerminalPatch), true).Patch();
			}
			((BaseUnityPlugin)this).Logger.LogInfo((object)"RandomMoonFX is loaded !");
		}

		private void SetParameters()
		{
			config = new Config(((BaseUnityPlugin)this).Config);
			config.SetupCustomConfigs();
			string value = config.CompanyRoutingMode.Value;
			if (1 == 0)
			{
			}
			CompanyRM companyRoutingMode = value switch
			{
				"Random" => CompanyRM.Random, 
				"Select" => CompanyRM.Select, 
				"Manual" => CompanyRM.Manual, 
				_ => CompanyRM.Random, 
			};
			if (1 == 0)
			{
			}
			CompanyRoutingMode = companyRoutingMode;
			SelectedCompanyName = Utils.GetNormalizedMoonName(config.SelectedCompanyName.Value);
			if (config.ChameleonAnimation.Value && Chainloader.PluginInfos.ContainsKey("butterystancakes.lethalcompany.chameleon"))
			{
				AnimationTime = 7.5f;
			}
			if (config.CelestialTintAnimation.Value && Chainloader.PluginInfos.ContainsKey("CelestialTint"))
			{
				AnimationTime = 4f;
			}
			if (config.AnimationTimeOverride.Value >= 0f)
			{
				AnimationTime = config.AnimationTimeOverride.Value;
			}
			if (config.ConstellationsCheck.Value && Chainloader.PluginInfos.ContainsKey("com.github.darmuh.LethalConstellations"))
			{
				constellationsCompatibility = true;
			}
		}

		public bool LastDayOfQuota()
		{
			if (Utils.IsLastDayRandom())
			{
				return false;
			}
			if (config.QuotaCheck.Value)
			{
				return TimeOfDay.Instance.daysUntilDeadline == 0 && TimeOfDay.Instance.profitQuota > TimeOfDay.Instance.quotaFulfilled;
			}
			return TimeOfDay.Instance.daysUntilDeadline == 0;
		}

		public void RouteRandomPlanet()
		{
			Utils.SearchCompanyMoons();
			if (LastDayOfQuota())
			{
				int num = GordionID;
				switch (CompanyRoutingMode)
				{
				default:
					return;
				case CompanyRM.Random:
				{
					SelectableLevel val2 = CompanyMoons[Random.Range(0, CompanyMoons.Count)];
					((BaseUnityPlugin)this).Logger.LogInfo((object)("Navigating to Company " + val2.PlanetName));
					num = val2.levelID;
					break;
				}
				case CompanyRM.Select:
					if (SelectedCompanyID == -1)
					{
						SelectableLevel[] levels = StartOfRound.Instance.levels;
						foreach (SelectableLevel val in levels)
						{
							if (SelectedCompanyName == Utils.GetNormalizedMoonName(val))
							{
								SelectedCompanyID = val.levelID;
								break;
							}
						}
					}
					if (SelectedCompanyID != -1)
					{
						((BaseUnityPlugin)this).Logger.LogInfo((object)("Force navigating to " + SelectedCompanyName));
						num = SelectedCompanyID;
					}
					else
					{
						((BaseUnityPlugin)this).Logger.LogError((object)("Selected Company Moon " + SelectedCompanyName + " was not found. Force navigating to the Company Building instead."));
					}
					break;
				}
				StartOfRound.Instance.ChangeLevelServerRpc(num, Object.FindObjectOfType<Terminal>().groupCredits);
			}
			else
			{
				SelectableLevel val3 = TimeOfDay.Instance.currentLevel;
				while (val3.PlanetName == TimeOfDay.Instance.currentLevel.PlanetName)
				{
					val3 = ((!config.ActivateMoonsDistributions.Value) ? StartOfRound.Instance.levels[Random.Range(0, StartOfRound.Instance.levels.Length)] : Utils.GetARandomMoonByDistribution());
					if (!Utils.IsMoonValid(val3))
					{
						val3 = TimeOfDay.Instance.currentLevel;
					}
				}
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Navigating to " + val3.PlanetName));
				StartOfRound.Instance.ChangeLevelServerRpc(val3.levelID, Object.FindObjectOfType<Terminal>().groupCredits);
			}
			IsStarting = true;
		}

		public void StartRandomPlanet()
		{
			StartOfRound.Instance.StartGameServerRpc();
		}
	}
	internal class Utils
	{
		public static bool IsLastDayRandom()
		{
			if (TimeOfDay.Instance.daysUntilDeadline != 0 || !Plugin.config.RandomizeLastDay.Value)
			{
				return false;
			}
			bool? inShip = true;
			int num = 5 * (StartOfRound.Instance.allPlayerObjects.Length - 1);
			int num2 = Object.FindObjectsOfType<GrabbableObject>().Where(delegate(GrabbableObject o)
			{
				int result;
				if (o.itemProperties.isScrap && o.itemProperties.minValue > 0 && !(o is RagdollGrabbableObject))
				{
					StunGrenadeItem val = (StunGrenadeItem)(object)((o is StunGrenadeItem) ? o : null);
					if (val == null || !val.hasExploded || !val.DestroyGrenade)
					{
						result = ((!inShip.HasValue || (o.isInShipRoom == inShip && o.isInElevator == inShip)) ? 1 : 0);
						goto IL_0094;
					}
				}
				result = 0;
				goto IL_0094;
				IL_0094:
				return (byte)result != 0;
			}).ToList()
				.Sum((GrabbableObject s) => s.scrapValue);
			if (num2 + num + TimeOfDay.Instance.quotaFulfilled >= TimeOfDay.Instance.profitQuota)
			{
				return false;
			}
			return true;
		}

		public static bool IsMoonValid(SelectableLevel selectableLevel)
		{
			if (selectableLevel.PlanetName == "44 Liquidation" || Plugin.instance.CompanyMoons.Exists((SelectableLevel i) => i.PlanetName == selectableLevel.PlanetName))
			{
				return false;
			}
			if (!Plugin.config.ExcludePreviouslyVisited.Value || Plugin.instance.constellationsCompatibility)
			{
				return true;
			}
			if (Plugin.instance.VisitedMoons.Count == 0 || !Plugin.instance.VisitedMoons.Contains(selectableLevel.PlanetName))
			{
				Plugin.instance.VisitedMoons.Add(selectableLevel.PlanetName);
				return true;
			}
			if (Plugin.instance.VisitedMoons.Count >= StartOfRound.Instance.levels.Length - 1 - Plugin.instance.CompanyMoons.Count - Plugin.config.MoonsBlacklist.Count)
			{
				Plugin.instance.VisitedMoons.Clear();
				Plugin.instance.VisitedMoons.Add(selectableLevel.PlanetName);
				return true;
			}
			return false;
		}

		public static bool IsMoonBlacklisted(SelectableLevel selectableLevel)
		{
			if (Plugin.config.MoonsBlacklist.Count == 0)
			{
				return false;
			}
			return Plugin.config.MoonsBlacklist.Exists((string i) => i == GetNormalizedMoonName(selectableLevel));
		}

		public static void SearchCompanyMoons()
		{
			if (Plugin.instance.CompanyMoons.Count > 0)
			{
				return;
			}
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel val in levels)
			{
				if (!val.planetHasTime && !val.spawnEnemiesAndScrap && !IsMoonBlacklisted(val))
				{
					Plugin.instance.CompanyMoons.Add(val);
				}
			}
		}

		public static string GetNormalizedMoonName(SelectableLevel selectableLevel)
		{
			return GetNormalizedMoonName(selectableLevel.PlanetName);
		}

		public static string GetNormalizedMoonName(string planetName)
		{
			string text = Regex.Replace(planetName, "^[0-9]+", string.Empty);
			if (text[0] == ' ' || text[0] == '-')
			{
				string text2 = text;
				text = text2.Substring(1, text2.Length - 1);
			}
			return text;
		}

		public static SelectableLevel GetARandomMoonByDistribution()
		{
			//IL_0012: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Expected O, but got Unknown
			Dictionary<string, int> MoonsDistributionFiltered = new Dictionary<string, int>();
			SelectableLevel val = new SelectableLevel();
			Random random = new Random();
			int maxValue = Plugin.config.MoonsDistribution.Values.Sum();
			int num = random.Next(maxValue);
			int num2 = 0;
			SelectableLevel[] levels = StartOfRound.Instance.levels;
			foreach (SelectableLevel selectableLevel in levels)
			{
				string normalizedMoonName = GetNormalizedMoonName(selectableLevel);
				if (Plugin.config.MoonsDistribution.TryGetValue(normalizedMoonName, out var value))
				{
					MoonsDistributionFiltered.Add(normalizedMoonName, value);
				}
			}
			foreach (KeyValuePair<string, int> moonName in MoonsDistributionFiltered)
			{
				num2 += moonName.Value;
				if (num2 > num)
				{
					val = ((IEnumerable<SelectableLevel>)StartOfRound.Instance.levels).FirstOrDefault((Func<SelectableLevel, bool>)((SelectableLevel name) => GetNormalizedMoonName(name.PlanetName) == moonName.Key));
					break;
				}
			}
			if ((Object)(object)val == (Object)null)
			{
				val = ((IEnumerable<SelectableLevel>)StartOfRound.Instance.levels).FirstOrDefault((Func<SelectableLevel, bool>)((SelectableLevel name) => GetNormalizedMoonName(name.PlanetName) == MoonsDistributionFiltered.Last().Key));
			}
			return val;
		}
	}
}