Decompiled source of MultiDroneLaunch v1.1.0

plugins/MultiDroneLaunch.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
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("MultiDroneLaunch")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0")]
[assembly: AssemblyProduct("MultiDroneLaunch")]
[assembly: AssemblyTitle("MultiDroneLaunch")]
[assembly: AssemblyVersion("1.0.0.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace MultiDroneLaunch
{
	public static class DroneSpeed
	{
		[HarmonyPatch]
		public static class DroneUpdatePatch
		{
			public static MethodBase TargetMethod()
			{
				MethodInfo[] methods = typeof(DroneComponent).GetMethods(BindingFlags.Instance | BindingFlags.Public);
				foreach (MethodInfo methodInfo in methods)
				{
					if (!(methodInfo.Name != "InternalUpdate"))
					{
						ParameterInfo[] parameters = methodInfo.GetParameters();
						if (parameters.Length >= 6 && parameters[2].ParameterType == typeof(Vector3).MakeByRefType() && parameters[4].ParameterType == typeof(float) && parameters[5].ParameterType == typeof(double).MakeByRefType())
						{
							return methodInfo;
						}
					}
				}
				throw new MissingMethodException("DroneComponent.InternalUpdate (mecha overload) was not found");
			}

			public static void Prefix(ref DroneComponent __instance, ref CraftData craft, ref Vector3 ejectPos, ref float dt)
			{
				//IL_0033: Unknown result type (might be due to invalid IL or missing references)
				//IL_0038: Unknown result type (might be due to invalid IL or missing references)
				//IL_003e: Unknown result type (might be due to invalid IL or missing references)
				//IL_0043: Unknown result type (might be due to invalid IL or missing references)
				//IL_0048: 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_005c: Unknown result type (might be due to invalid IL or missing references)
				//IL_0061: Unknown result type (might be due to invalid IL or missing references)
				dt *= _scale;
				DroneUpdates++;
				float catchRadius = _catchRadius;
				if (catchRadius > 0.5f && __instance.stage == 4)
				{
					Vector3 val = VectorLF3.op_Implicit(craft.pos) - ejectPos;
					if (((Vector3)(ref val)).sqrMagnitude < catchRadius * catchRadius)
					{
						craft.pos = VectorLF3.op_Implicit(ejectPos);
						ReturnsCaught++;
					}
				}
			}
		}

		[HarmonyPatch]
		public static class SpeedLimitPatch
		{
			public static IEnumerable<MethodBase> TargetMethods()
			{
				string[] array = new string[3] { "BuildProcedure", "PreLaunchDrone", "RepairProcedure" };
				foreach (string text in array)
				{
					MethodInfo methodInfo = AccessTools.Method(typeof(ConstructionModuleComponent), text, (Type[])null, (Type[])null);
					if (methodInfo != null)
					{
						yield return methodInfo;
					}
				}
			}

			public static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> instructions, MethodBase __originalMethod)
			{
				FieldInfo operand = AccessTools.Field(typeof(DroneSpeed), "MaxBuildSpeed");
				List<CodeInstruction> list = new List<CodeInstruction>(instructions);
				bool flag = false;
				for (int i = 1; i < list.Count; i++)
				{
					if (flag)
					{
						break;
					}
					if (list[i].opcode == OpCodes.Ldc_R4 && list[i].operand is float num && num == 20f && (list[i - 1].opcode == OpCodes.Call || list[i - 1].opcode == OpCodes.Callvirt) && list[i - 1].operand is MethodInfo { Name: "get_speed" } methodInfo && methodInfo.DeclaringType == typeof(Player))
					{
						list[i].opcode = OpCodes.Ldsfld;
						list[i].operand = operand;
						flag = true;
					}
				}
				if (flag)
				{
					SpeedChecksReplaced++;
				}
				else
				{
					ManualLogSource log = Plugin.Log;
					if (log != null)
					{
						log.LogWarning((object)(__originalMethod?.Name + ": player.speed > 20 not found, its limit stays 20 m/s"));
					}
				}
				return list;
			}
		}

		public const float VanillaBuildSpeed = 20f;

		public static float MaxBuildSpeed = 20f;

		public static bool RealTimeDrones;

		public static float MaxRealTimeScale = 4f;

		private static volatile float _scale = 1f;

		private static volatile float _catchRadius = 0.5f;

		public static int SpeedChecksReplaced;

		public static long DroneUpdates;

		public static long ReturnsCaught;

		private static bool CatchActive
		{
			get
			{
				if (!RealTimeDrones)
				{
					return MaxBuildSpeed > 20f;
				}
				return true;
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(GameMain), "FixedUpdate")]
		public static void FixedUpdate_Prefix()
		{
			float fixedDeltaTime = Time.fixedDeltaTime;
			float num = fixedDeltaTime * 60f;
			_scale = ((!RealTimeDrones || num < 1f) ? 1f : ((num > MaxRealTimeScale) ? MaxRealTimeScale : num));
			Player mainPlayer = GameMain.mainPlayer;
			float num2 = ((mainPlayer != null && CatchActive) ? mainPlayer.speed : 0f);
			_catchRadius = Math.Max(0.5f, num2 * fixedDeltaTime * 1.5f + 0.5f);
		}
	}
	public static class Launcher
	{
		public static bool Enabled = true;

		public static int ExtraPerTick = 10;

		public static long ExtraLaunches;

		public static long TicksWithExtra;

		public static bool Timing;

		public static long TimedTicks;

		public static long TimedCalls;

		private static Harmony live;

		[HarmonyPostfix]
		[HarmonyPatch(typeof(ConstructionSystem), "DetermineLaunch")]
		public static void DetermineLaunch_Postfix(ConstructionSystem __instance)
		{
			//IL_006d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0073: Invalid comparison between Unknown and I4
			if (!Enabled || ExtraPerTick <= 0)
			{
				return;
			}
			PlanetFactory factory = __instance.factory;
			Player player = __instance.player;
			if (factory == null || player == null || player.factory != factory || player.mecha == null)
			{
				return;
			}
			ConstructionModuleComponent constructionModule = player.mecha.constructionModule;
			if (constructionModule == null || !constructionModule.droneEnabled || !constructionModule.droneConstructEnabled || constructionModule.droneIdleCount <= 0 || player.speed > DroneSpeed.MaxBuildSpeed || (int)player.movementState >= 3 || (constructionModule.dronePriority == 2 && constructionModule.repairTargets != null && constructionModule.repairTargets[0].objectId != 0))
			{
				return;
			}
			ConstructTarget[] buildTargets = constructionModule.buildTargets;
			if (buildTargets == null)
			{
				return;
			}
			PrebuildData[] prebuildPool = factory.prebuildPool;
			int num = 0;
			for (int i = 0; i + 3 < buildTargets.Length; i += 4)
			{
				if (num >= ExtraPerTick)
				{
					break;
				}
				if (constructionModule.droneIdleCount <= 0)
				{
					break;
				}
				int num2 = Free(prebuildPool, buildTargets[i].objectId);
				if (num2 != 0)
				{
					int num3 = Free(prebuildPool, buildTargets[i + 1].objectId);
					int num4 = Free(prebuildPool, buildTargets[i + 2].objectId);
					int num5 = Free(prebuildPool, buildTargets[i + 3].objectId);
					if (num4 == num3)
					{
						num4 = 0;
					}
					if (num5 == num3 || num5 == num4)
					{
						num5 = 0;
					}
					constructionModule.EjectMechaDrone(factory, player, -num2, -num3, -num4, -num5);
					HashSet<int> rmv = __instance._rmv_prebuildId_list ?? (__instance._rmv_prebuildId_list = new HashSet<int>());
					Take(prebuildPool, rmv, num2);
					Take(prebuildPool, rmv, num3);
					Take(prebuildPool, rmv, num4);
					Take(prebuildPool, rmv, num5);
					num++;
				}
			}
			if (num > 0)
			{
				ExtraLaunches += num;
				TicksWithExtra++;
			}
		}

		private static int Free(PrebuildData[] pool, int id)
		{
			if (id <= 0 || id >= pool.Length)
			{
				return 0;
			}
			ref PrebuildData reference = ref pool[id];
			if (reference.id != id || reference.isDestroyed || reference.itemRequired != 0 || reference.builderLaunched)
			{
				return 0;
			}
			return id;
		}

		private static void Take(PrebuildData[] pool, HashSet<int> rmv, int id)
		{
			if (id > 0)
			{
				pool[id].builderLaunched = true;
				rmv.Add(id);
			}
		}

		public static string LiveApply(int extraPerTick, float maxBuildSpeed = 20f, bool realTimeDrones = false)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0034: Expected O, but got Unknown
			ExtraPerTick = extraPerTick;
			DroneSpeed.MaxBuildSpeed = maxBuildSpeed;
			DroneSpeed.RealTimeDrones = realTimeDrones;
			Enabled = true;
			if (live != null)
			{
				return "已经打过补丁";
			}
			live = new Harmony("com.github.jiesiluo.multidronelaunch.live");
			live.PatchAll(typeof(Launcher));
			live.PatchAll(typeof(DroneSpeed));
			live.PatchAll(typeof(DroneSpeed.DroneUpdatePatch));
			live.PatchAll(typeof(DroneSpeed.SpeedLimitPatch));
			live.PatchAll(typeof(LiveTiming));
			return "补丁已打上";
		}

		public static string LiveRemove()
		{
			if (live == null)
			{
				return "没有补丁";
			}
			live.UnpatchSelf();
			live = null;
			return "补丁已撤掉";
		}
	}
	public static class LiveTiming
	{
		private static readonly Stopwatch sw = new Stopwatch();

		[HarmonyPrefix]
		[HarmonyPriority(800)]
		[HarmonyPatch(typeof(ConstructionSystem), "DetermineLaunch")]
		public static void Prefix()
		{
			if (Launcher.Timing)
			{
				sw.Restart();
			}
		}

		[HarmonyPostfix]
		[HarmonyPriority(0)]
		[HarmonyPatch(typeof(ConstructionSystem), "DetermineLaunch")]
		public static void Postfix()
		{
			if (Launcher.Timing)
			{
				sw.Stop();
				Launcher.TimedTicks += sw.ElapsedTicks;
				Launcher.TimedCalls++;
			}
		}
	}
	[BepInPlugin("com.github.jiesiluo.multidronelaunch", "Multi Drone Launch", "1.1.0")]
	public class Plugin : BaseUnityPlugin
	{
		public const string Guid = "com.github.jiesiluo.multidronelaunch";

		public const string Name = "Multi Drone Launch";

		public const string Version = "1.1.0";

		internal static ManualLogSource Log;

		private void Awake()
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Expected O, but got Unknown
			//IL_00e6: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f0: Expected O, but got Unknown
			//IL_0145: Unknown result type (might be due to invalid IL or missing references)
			//IL_014f: Expected O, but got Unknown
			//IL_01ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01f3: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			ConfigEntry<bool> enabled = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "Enabled", true, "Let the mecha send out more than one construction drone per logic tick. 机甲每个逻辑帧可以派出多架建设无人机。");
			ConfigEntry<int> extra = ((BaseUnityPlugin)this).Config.Bind<int>("General", "ExtraPerTick", 10, new ConfigDescription("How many drones the mecha may send out per tick on top of the game's one. 每帧在原版一架之外最多再派几架(0 = 原版)。", (AcceptableValueBase)(object)new AcceptableValueRange<int>(0, 200), Array.Empty<object>()));
			Launcher.Enabled = enabled.Value;
			Launcher.ExtraPerTick = extra.Value;
			enabled.SettingChanged += delegate
			{
				Launcher.Enabled = enabled.Value;
			};
			extra.SettingChanged += delegate
			{
				Launcher.ExtraPerTick = extra.Value;
			};
			ConfigEntry<float> maxBuildSpeed = ((BaseUnityPlugin)this).Config.Bind<float>("Speed", "MaxBuildSpeed", 20f, new ConfigDescription("Mecha drones keep searching, launching and repairing while the mecha moves up to this speed (m/s). The game stops them above 20; the mecha flies at up to walk speed × 2.5. 机甲速度在多少以内(米/秒)无人机继续找目标、起飞和维修。原版超过 20 就停;机甲飞行最高为步行速度的 2.5 倍。", (AcceptableValueBase)(object)new AcceptableValueRange<float>(20f, 60f), Array.Empty<object>()));
			ConfigEntry<bool> realTime = ((BaseUnityPlugin)this).Config.Bind<bool>("Speed", "RealTimeDrones", false, "Mecha drones fly at their speed in real time when the game runs below 60 logic ticks a second, instead of slowing down with it and falling behind the mecha. 游戏每秒逻辑帧不足 60 时,机甲无人机仍按真实时间以原速飞行,不再跟着变慢、追不上机甲。");
			ConfigEntry<float> maxScale = ((BaseUnityPlugin)this).Config.Bind<float>("Speed", "MaxRealTimeScale", 4f, new ConfigDescription("RealTimeDrones makes up for the slowdown up to this factor (4 = down to 15 logic ticks a second). RealTimeDrones 最多补到几倍(4 = 低至每秒 15 个逻辑帧)。", (AcceptableValueBase)(object)new AcceptableValueRange<float>(1f, 6f), Array.Empty<object>()));
			DroneSpeed.MaxBuildSpeed = maxBuildSpeed.Value;
			DroneSpeed.RealTimeDrones = realTime.Value;
			DroneSpeed.MaxRealTimeScale = maxScale.Value;
			maxBuildSpeed.SettingChanged += delegate
			{
				DroneSpeed.MaxBuildSpeed = maxBuildSpeed.Value;
			};
			realTime.SettingChanged += delegate
			{
				DroneSpeed.RealTimeDrones = realTime.Value;
			};
			maxScale.SettingChanged += delegate
			{
				DroneSpeed.MaxRealTimeScale = maxScale.Value;
			};
			Harmony val = new Harmony("com.github.jiesiluo.multidronelaunch");
			val.PatchAll(typeof(Launcher));
			val.PatchAll(typeof(DroneSpeed));
			val.PatchAll(typeof(DroneSpeed.DroneUpdatePatch));
			val.PatchAll(typeof(DroneSpeed.SpeedLimitPatch));
			((BaseUnityPlugin)this).Logger.LogInfo((object)(string.Format("Multi Drone Launch {0}: up to {1} extra drones a tick, enabled = {2}; ", "1.1.0", Launcher.ExtraPerTick, Launcher.Enabled) + $"build speed {DroneSpeed.MaxBuildSpeed} m/s ({DroneSpeed.SpeedChecksReplaced}/3 checks), real-time drones = {DroneSpeed.RealTimeDrones}"));
		}
	}
}