Decompiled source of FactoryUndo v0.1.0

FactoryUndo.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using CommonAPI;
using CommonAPI.Systems;
using CommonAPI.Systems.ModLocalization;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using NebulaAPI;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("FactoryUndo")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyDescription("Undo and redo for building, dismantling, and upgrading")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0+a2afa3d962886bb25a72d1d0ae45167e1d694804")]
[assembly: AssemblyProduct("FactoryUndo")]
[assembly: AssemblyTitle("FactoryUndo")]
[assembly: AssemblyVersion("0.1.0.0")]
[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.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]
	[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 FactoryUndo
{
	internal static class BlueprintTweaksUndo
	{
		internal const string Guid = "org.kremnev8.plugin.BlueprintTweaks";

		private const string UndoNamespace = "BlueprintTweaks.FactoryUndo";

		internal static void Disable(Harmony harmony, ManualLogSource log)
		{
			//IL_016b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0172: Expected O, but got Unknown
			//IL_019e: Unknown result type (might be due to invalid IL or missing references)
			//IL_01a3: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ac: Expected O, but got Unknown
			ConfigEntry<bool> val = default(ConfigEntry<bool>);
			if (!Chainloader.PluginInfos.TryGetValue("org.kremnev8.plugin.BlueprintTweaks", out var value) || !value.Instance.Config.TryGetEntry<bool>("Features", "factoryUndo", ref val) || !val.Value)
			{
				return;
			}
			Type type = AccessTools.TypeByName("BlueprintTweaks.FactoryUndo.UndoManager");
			MethodInfo methodInfo = AccessTools.Method(type, "TryUndo", (Type[])null, (Type[])null);
			MethodInfo methodInfo2 = AccessTools.Method(type, "TryRedo", (Type[])null, (Type[])null);
			if (methodInfo == null || methodInfo2 == null)
			{
				log.LogWarning((object)"BlueprintTweaks' undo was not found, so it is still on");
				return;
			}
			foreach (MethodBase item in Harmony.GetAllPatchedMethods().ToList())
			{
				Patches patchInfo = Harmony.GetPatchInfo(item);
				foreach (Patch item2 in patchInfo.Prefixes.Concat(patchInfo.Postfixes).Concat(patchInfo.Transpilers).Concat(patchInfo.Finalizers))
				{
					if (item2.owner == "org.kremnev8.plugin.BlueprintTweaks" && item2.PatchMethod.DeclaringType?.Namespace == "BlueprintTweaks.FactoryUndo")
					{
						harmony.Unpatch(item, item2.PatchMethod);
					}
				}
			}
			HarmonyMethod val2 = new HarmonyMethod(typeof(BlueprintTweaksUndo), "Skip", (Type[])null);
			harmony.Patch((MethodBase)methodInfo, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			harmony.Patch((MethodBase)methodInfo2, val2, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
			HarmonyMethod val3 = new HarmonyMethod(typeof(BlueprintTweaksUndo), "HideKeys", (Type[])null)
			{
				priority = 0
			};
			harmony.Patch((MethodBase)AccessTools.Method(typeof(UIOptionWindow), "_OnCreate", (Type[])null, (Type[])null), val3, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
		}

		private static bool Skip()
		{
			return false;
		}

		private static void HideKeys()
		{
			DSPGame.key.builtinKeys = DSPGame.key.builtinKeys.Where(delegate(BuiltinKey key)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				string name = key.name;
				return !(name == "FactoryUndo") && !(name == "FactoryRedo");
			}).ToArray();
		}
	}
	internal readonly struct Connection
	{
		public readonly int Slot;

		public readonly bool IsOutput;

		public readonly TrackedObject Other;

		public readonly int OtherSlot;

		public Connection(int slot, bool isOutput, TrackedObject other, int otherSlot)
		{
			Slot = slot;
			IsOutput = isOutput;
			Other = other;
			OtherSlot = otherSlot;
		}
	}
	internal sealed class ObjectSnapshot(PrebuildData prebuild, string? extraInfo, List<Connection> connections)
	{
		private readonly PrebuildData _prebuild = prebuild;

		public readonly string? ExtraInfo = extraInfo;

		public readonly List<Connection> Connections = connections;

		public static ObjectSnapshot Capture(FactoryHistory history, int objId, List<Connection> connections)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_000e: Unknown result type (might be due to invalid IL or missing references)
			PlanetFactory factory = history.Factory;
			if (objId <= 0)
			{
				return new ObjectSnapshot(FromPrebuild(factory, -objId), factory.ReadExtraInfoOnPrebuild(-objId), connections);
			}
			return new ObjectSnapshot(FromEntity(factory, objId), factory.ReadExtraInfoOnEntity(objId), connections);
		}

		public static List<Connection> ReadConnections(FactoryHistory history, int objId)
		{
			List<Connection> list = new List<Connection>();
			PlanetFactory factory = history.Factory;
			PrefabDesc? obj = PrefabOf(factory, objId);
			if (obj != null && obj.isMonitor)
			{
				return list;
			}
			bool isOutput = default(bool);
			int num = default(int);
			int otherSlot = default(int);
			for (int i = 0; i < 16; i++)
			{
				factory.ReadObjectConn(objId, i, ref isOutput, ref num, ref otherSlot);
				if (num != 0)
				{
					PrefabDesc? obj2 = PrefabOf(factory, num);
					if (obj2 == null || !obj2.isMonitor)
					{
						list.Add(new Connection(i, isOutput, history.Track(num), otherSlot));
					}
				}
			}
			return list;
		}

		public PrebuildData ToPrebuild()
		{
			//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_002a: Unknown result type (might be due to invalid IL or missing references)
			PrebuildData prebuild = prebuild;
			prebuild.parameters = (int[])prebuild.parameters?.Clone();
			return prebuild;
		}

		private static PrefabDesc? PrefabOf(PlanetFactory factory, int objId)
		{
			short num = ((objId > 0) ? factory.entityPool[objId].modelIndex : factory.prebuildPool[-objId].modelIndex);
			return LDB.models.modelArray[num]?.prefabDesc;
		}

		private static PrebuildData FromPrebuild(PlanetFactory factory, int prebuildId)
		{
			//IL_000f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0032: Unknown result type (might be due to invalid IL or missing references)
			//IL_0037: 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_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: 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)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dc: Unknown result type (might be due to invalid IL or missing references)
			ref PrebuildData reference = ref factory.prebuildPool[prebuildId];
			return new PrebuildData
			{
				protoId = reference.protoId,
				modelIndex = reference.modelIndex,
				pos = reference.pos,
				rot = reference.rot,
				pos2 = reference.pos2,
				rot2 = reference.rot2,
				tilt = reference.tilt,
				pickOffset = reference.pickOffset,
				insertOffset = reference.insertOffset,
				recipeId = reference.recipeId,
				filterId = reference.filterId,
				parameters = (int[])reference.parameters?.Clone(),
				paramCount = reference.paramCount,
				content = reference.content
			};
		}

		private static PrebuildData FromEntity(PlanetFactory factory, int entityId)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: 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_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_0049: Unknown result type (might be due to invalid IL or missing references)
			//IL_0051: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: 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_006b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0070: Unknown result type (might be due to invalid IL or missing references)
			//IL_0084: Unknown result type (might be due to invalid IL or missing references)
			//IL_0091: Unknown result type (might be due to invalid IL or missing references)
			//IL_009e: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f9: 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_011b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0120: Unknown result type (might be due to invalid IL or missing references)
			//IL_0246: Unknown result type (might be due to invalid IL or missing references)
			//IL_0166: Unknown result type (might be due to invalid IL or missing references)
			//IL_0232: Unknown result type (might be due to invalid IL or missing references)
			ref EntityData reference = ref factory.entityPool[entityId];
			BuildingParameters zero = BuildingParameters.zero;
			((BuildingParameters)(ref zero)).CopyFromFactoryObject(entityId, factory, true, true);
			PrebuildData val = new PrebuildData
			{
				protoId = reference.protoId,
				modelIndex = reference.modelIndex,
				pos = reference.pos,
				rot = reference.rot,
				pos2 = reference.pos,
				rot2 = reference.rot,
				tilt = reference.tilt,
				recipeId = zero.recipeId,
				filterId = zero.filterId,
				content = zero.content
			};
			((BuildingParameters)(ref zero)).ToParamsArray(ref val.parameters, ref val.paramCount);
			if (reference.inserterId != 0)
			{
				ref InserterComponent reference2 = ref factory.factorySystem.inserterPool[reference.inserterId];
				val.pos2 = factory.factorySystem.inserterPosePool[reference.inserterId].pos2;
				val.rot2 = factory.factorySystem.inserterPosePool[reference.inserterId].rot2;
				val.pickOffset = reference2.pickOffset;
				val.insertOffset = reference2.insertOffset;
			}
			PrefabDesc val2 = LDB.models.modelArray[reference.modelIndex]?.prefabDesc;
			if (val2 != null && (int)val2.minerType != 0 && val2.minerPeriod > 0)
			{
				ref MinerComponent reference3 = ref factory.factorySystem.minerPool[reference.minerId];
				int destinationIndex = 0;
				if (val2.isVeinCollector)
				{
					val.filterId = factory.transport.stationPool[reference.stationId].storage[0].itemId;
					destinationIndex = 2048;
					((PrebuildData)(ref val)).InitParametersArray(reference3.veinCount + 2048);
					((BuildingParameters)(ref zero)).ToParamsArray(ref val.parameters, ref val.paramCount);
				}
				else
				{
					val.filterId = (int)factory.entitySignPool[entityId].iconId0;
					((PrebuildData)(ref val)).InitParametersArray(reference3.veinCount);
				}
				if (reference3.veinCount > 0)
				{
					Array.Copy(reference3.veins, 0, val.parameters, destinationIndex, reference3.veinCount);
				}
			}
			return val;
		}
	}
	[BepInPlugin("com.geostyx.dsp.factoryundo", "FactoryUndo", "0.1.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[CommonAPISubmoduleDependency(new string[] { "CustomKeyBindSystem", "LocalizationModule" })]
	public class Plugin : BaseUnityPlugin
	{
		private const string NothingToUndoText = "GeosFactoryUndoNothingToUndo";

		private const string NothingToRedoText = "GeosFactoryUndoNothingToRedo";

		private const string UndoBlockedText = "GeosFactoryUndoUndoBlocked";

		private const string RedoBlockedText = "GeosFactoryUndoRedoBlocked";

		private PressKeyBind _undoKey;

		private PressKeyBind _redoKey;

		private Harmony? _harmony;

		private void Awake()
		{
			//IL_0003: 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_003a: 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_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_007f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0126: Unknown result type (might be due to invalid IL or missing references)
			//IL_0130: Expected O, but got Unknown
			_undoKey = CustomKeyBindSystem.RegisterKeyBindWithReturn<PressKeyBind>(new BuiltinKey
			{
				key = new CombineKey(122, (byte)2, (ECombineKeyAction)0, false),
				conflictGroup = 2052,
				name = "GeosFactoryUndo",
				canOverride = true
			});
			_redoKey = CustomKeyBindSystem.RegisterKeyBindWithReturn<PressKeyBind>(new BuiltinKey
			{
				key = new CombineKey(122, (byte)3, (ECombineKeyAction)0, false),
				conflictGroup = 2052,
				name = "GeosFactoryRedo",
				canOverride = true
			});
			LocalizationModule.RegisterTranslation("KEYGeosFactoryUndo", "Undo factory change", "撤销工厂操作", "");
			LocalizationModule.RegisterTranslation("KEYGeosFactoryRedo", "Redo factory change", "重做工厂操作", "");
			LocalizationModule.RegisterTranslation("GeosFactoryUndoNothingToUndo", "Nothing to undo", "没有可撤销的操作", "");
			LocalizationModule.RegisterTranslation("GeosFactoryUndoNothingToRedo", "Nothing to redo", "没有可重做的操作", "");
			LocalizationModule.RegisterTranslation("GeosFactoryUndoUndoBlocked", "Undo blocked: a storage, tank, or station still holds items", "无法撤销:储物仓、储液罐或物流运输站内仍有物品", "");
			LocalizationModule.RegisterTranslation("GeosFactoryUndoRedoBlocked", "Redo blocked: a storage, tank, or station still holds items", "无法重做:储物仓、储液罐或物流运输站内仍有物品", "");
			_harmony = new Harmony("com.geostyx.dsp.factoryundo");
			_harmony.PatchAll(typeof(Recorder));
			BlueprintTweaksUndo.Disable(_harmony, ((BaseUnityPlugin)this).Logger);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"FactoryUndo 0.1.0 loaded");
		}

		private void OnDestroy()
		{
			Harmony? harmony = _harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			_harmony = null;
			Recorder.Clear();
		}

		private void Update()
		{
			//IL_0047: Unknown result type (might be due to invalid IL or missing references)
			Recorder.EndFrame();
			if (!VFInput.inputing && GameMain.isRunning && !NebulaModAPI.IsMultiplayerActive && !GameMain.isPaused && !GameMain.instance.isMenuDemo && !GameMain.inOtherScene && !GameMain.mainPlayer.respawning && !VFInput.inFullscreenGUI && !VFInput._buildConfirm.pressing)
			{
				if (_undoKey.keyValue)
				{
					Run(undo: true);
				}
				else if (_redoKey.keyValue)
				{
					Run(undo: false);
				}
			}
		}

		private static void Run(bool undo)
		{
			PlanetData localPlanet = GameMain.localPlanet;
			if (localPlanet?.factory == null || !localPlanet.factoryLoaded)
			{
				return;
			}
			FactoryHistory factoryHistory = Recorder.Find(localPlanet.factory);
			if (factoryHistory != null)
			{
				List<UndoStep> list = (undo ? factoryHistory.Undo : factoryHistory.Redo);
				List<UndoStep> list2 = (undo ? factoryHistory.Redo : factoryHistory.Undo);
				while (list.Count > 0)
				{
					UndoStep undoStep = list[list.Count - 1];
					ReplayOutcome replayOutcome = Replayer.Replay(factoryHistory, undoStep, undo);
					if (replayOutcome == ReplayOutcome.BlockedByItems)
					{
						UIRealtimeTip.Popup(Localization.Translate(undo ? "GeosFactoryUndoUndoBlocked" : "GeosFactoryUndoRedoBlocked"), false, 0);
						return;
					}
					list.RemoveAt(list.Count - 1);
					if (replayOutcome == ReplayOutcome.Applied)
					{
						list2.Add(undoStep);
						return;
					}
				}
			}
			UIRealtimeTip.Popup(Localization.Translate(undo ? "GeosFactoryUndoNothingToUndo" : "GeosFactoryUndoNothingToRedo"), false, 0);
		}
	}
	[HarmonyPatch]
	internal static class Recorder
	{
		private const int MaxHistory = 200;

		private static readonly Dictionary<PlanetFactory, FactoryHistory> Histories = new Dictionary<PlanetFactory, FactoryHistory>();

		private static readonly Dictionary<int, List<Connection>> CoverConnections = new Dictionary<int, List<Connection>>();

		private static FactoryHistory? _openHistory;

		private static UndoStep? _openStep;

		private static int _holdId;

		internal static bool Replaying;

		private static bool IsTracking
		{
			get
			{
				if (!DSPGame.IsMenuDemo)
				{
					return !NebulaModAPI.IsMultiplayerActive;
				}
				return false;
			}
		}

		private static bool IsRecording
		{
			get
			{
				if (!Replaying)
				{
					return IsTracking;
				}
				return false;
			}
		}

		internal static FactoryHistory? Find(PlanetFactory factory)
		{
			lock (Histories)
			{
				FactoryHistory value;
				return Histories.TryGetValue(factory, out value) ? value : null;
			}
		}

		internal static void EndFrame()
		{
			//IL_0016: Unknown result type (might be due to invalid IL or missing references)
			Flush();
			CoverConnections.Clear();
			if (GameMain.isRunning && !VFInput._buildConfirm.pressing)
			{
				_holdId++;
			}
		}

		internal static void Clear()
		{
			_openHistory = null;
			_openStep = null;
			CoverConnections.Clear();
			lock (Histories)
			{
				Histories.Clear();
			}
		}

		private static FactoryHistory HistoryOf(PlanetFactory factory)
		{
			lock (Histories)
			{
				if (!Histories.TryGetValue(factory, out FactoryHistory value))
				{
					value = new FactoryHistory(factory);
					Histories[factory] = value;
				}
				return value;
			}
		}

		private static bool Exists(PlanetFactory factory, int objId)
		{
			if (objId <= 0)
			{
				if (objId < 0)
				{
					return factory.prebuildPool[-objId].id == -objId;
				}
				return false;
			}
			return factory.entityPool[objId].id == objId;
		}

		private static void Record(FactoryHistory history, Change change)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			if (_openHistory != history)
			{
				Flush();
			}
			_openHistory = history;
			if (_openStep == null)
			{
				_openStep = new UndoStep(VFInput._buildConfirm.pressing ? new int?(_holdId) : ((int?)null));
			}
			_openStep.Changes.Add(change);
		}

		private static void Flush()
		{
			if (_openStep != null && _openHistory != null)
			{
				UndoStep openStep = _openStep;
				FactoryHistory? openHistory = _openHistory;
				_openStep = null;
				_openHistory = null;
				List<UndoStep> undo = openHistory.Undo;
				if (openStep.HoldId.HasValue && undo.Count > 0 && undo[undo.Count - 1].HoldId == openStep.HoldId)
				{
					undo[undo.Count - 1].Changes.AddRange(openStep.Changes);
				}
				else
				{
					undo.Add(openStep);
				}
				openHistory.Redo.Clear();
				if (undo.Count > 200)
				{
					undo.RemoveRange(0, undo.Count - 200);
				}
			}
		}

		private static void CaptureCover(PlanetFactory factory, int coverObjId)
		{
			if (IsTracking && Exists(factory, coverObjId))
			{
				CoverConnections[coverObjId] = ObjectSnapshot.ReadConnections(HistoryOf(factory), coverObjId);
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(BuildTool_Path), "CreatePrebuilds")]
		private static void BeforePathBuild(BuildTool_Path __instance, out PathStart? __state)
		{
			foreach (BuildPreview buildPreview in ((BuildTool)__instance).buildPreviews)
			{
				if (buildPreview.willRemoveCover)
				{
					CaptureCover(((BuildTool)__instance).factory, buildPreview.coverObjId);
				}
			}
			__state = (IsRecording ? StartOf(__instance) : null);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(BuildTool_Path), "CreatePrebuilds")]
		private static void AfterPathBuild(BuildTool_Path __instance, PathStart? __state)
		{
			if (__state != null && _openStep != null && _openHistory?.Factory == ((BuildTool)__instance).factory)
			{
				_openStep.PathBefore = __state;
				_openStep.PathAfter = ((((BuildTool)__instance).controller.cmd.stage == 1) ? StartOf(__instance) : null);
			}
		}

		private static PathStart StartOf(BuildTool_Path tool)
		{
			//IL_0028: Unknown result type (might be due to invalid IL or missing references)
			return new PathStart((tool.startObjectId != 0) ? HistoryOf(((BuildTool)tool).factory).Track(tool.startObjectId) : null, tool.startNearestAddonAreaIdx, tool.startTarget, tool.startTilt);
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(BuildTool_Inserter), "CreatePrebuilds")]
		private static void BeforeInserterBuild(BuildTool_Inserter __instance)
		{
			foreach (BuildPreview buildPreview in ((BuildTool)__instance).buildPreviews)
			{
				if (buildPreview.willRemoveCover)
				{
					CaptureCover(((BuildTool)__instance).factory, buildPreview.coverObjId);
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(BuildTool_BlueprintPaste), "CreatePrebuilds")]
		private static void BeforeBlueprintBuild(BuildTool_BlueprintPaste __instance)
		{
			for (int i = 0; i < __instance.bpCursor; i++)
			{
				CaptureCover(((BuildTool)__instance).factory, __instance.bpPool[i].coverObjId);
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlanetFactory), "AddPrebuildDataWithComponents")]
		private static void AfterAddPrebuild(PlanetFactory __instance, ref PrebuildData prebuild, int __result)
		{
			if (__result != 0 && !prebuild.isDestroyed && IsRecording)
			{
				FactoryHistory factoryHistory = HistoryOf(__instance);
				Record(factoryHistory, new Change(ChangeKind.Created, factoryHistory.Track(-__result)));
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(PlanetFactory), "AddEntityDataWithComponents")]
		private static void AfterAddEntity(PlanetFactory __instance, int prebuildId, int __result)
		{
			if (__result != 0 && prebuildId > 0)
			{
				Find(__instance)?.Move(-prebuildId, __result);
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(PlanetFactory), "RemoveEntityWithComponents")]
		private static void BeforeRemoveEntity(PlanetFactory __instance, int id)
		{
			Find(__instance)?.Forget(id);
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(PlanetFactory), "RemovePrebuildWithComponents")]
		private static void BeforeRemovePrebuild(PlanetFactory __instance, int id)
		{
			Find(__instance)?.Forget(-id);
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(PlanetFactory), "DismantleFinally")]
		private static void BeforeDismantle(PlanetFactory __instance, int objId)
		{
			if (IsTracking && Exists(__instance, objId))
			{
				FactoryHistory factoryHistory = HistoryOf(__instance);
				TrackedObject trackedObject = factoryHistory.Track(objId);
				if (!CoverConnections.TryGetValue(objId, out List<Connection> value))
				{
					value = ObjectSnapshot.ReadConnections(factoryHistory, objId);
				}
				trackedObject.Snapshot = ObjectSnapshot.Capture(factoryHistory, objId, value);
				if (!Replaying)
				{
					Record(factoryHistory, new Change(ChangeKind.Removed, trackedObject));
				}
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(PlanetFactory), "UpgradeFinally")]
		private static void BeforeUpgrade(PlanetFactory __instance, int objId, ItemProto replace_item_proto)
		{
			if (IsRecording && replace_item_proto != null && Exists(__instance, objId))
			{
				FactoryHistory factoryHistory = HistoryOf(__instance);
				int fromProtoId = ((objId > 0) ? __instance.entityPool[objId].protoId : __instance.prebuildPool[-objId].protoId);
				Record(factoryHistory, new Change(ChangeKind.Upgraded, factoryHistory.Track(objId))
				{
					FromProtoId = fromProtoId,
					ToProtoId = ((Proto)replace_item_proto).ID
				});
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(BuildingParameters), "PasteToFactoryObject")]
		private static void BeforePasteSettings(int objectId, PlanetFactory factory, out SettingsSnapshot? __state)
		{
			__state = ((IsRecording && Exists(factory, objectId)) ? SettingsSnapshot.Capture(factory, objectId) : null);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(BuildingParameters), "PasteToFactoryObject")]
		private static void AfterPasteSettings(bool __result, int objectId, PlanetFactory factory, SettingsSnapshot? __state)
		{
			if (__result && __state != null)
			{
				FactoryHistory factoryHistory = HistoryOf(factory);
				Record(factoryHistory, new Change(ChangeKind.Reconfigured, factoryHistory.Track(objectId))
				{
					Settings = __state
				});
			}
		}

		[HarmonyPrefix]
		[HarmonyPatch(typeof(GameMain), "End")]
		private static void BeforeGameEnd()
		{
			Clear();
		}
	}
	internal enum ReplayOutcome
	{
		Applied,
		NothingToApply,
		BlockedByItems
	}
	internal static class Replayer
	{
		internal static ReplayOutcome Replay(FactoryHistory history, UndoStep step, bool undo)
		{
			bool flag = false;
			PlanetFactory factory = history.Factory;
			List<TrackedObject> list = new List<TrackedObject>();
			List<TrackedObject> list2 = new List<TrackedObject>();
			List<Change> list3 = new List<Change>();
			List<Change> list4 = new List<Change>();
			int count = step.Changes.Count;
			for (int i = 0; i < count; i++)
			{
				Change change = step.Changes[undo ? (count - 1 - i) : i];
				switch (change.Kind)
				{
				case ChangeKind.Created:
					(undo ? list : list2).Add(change.Target);
					break;
				case ChangeKind.Removed:
					(undo ? list2 : list).Add(change.Target);
					break;
				case ChangeKind.Upgraded:
					list3.Add(change);
					break;
				case ChangeKind.Reconfigured:
					list4.Add(change);
					break;
				}
			}
			foreach (TrackedObject item in list)
			{
				if (HoldsItems(factory, item.Id))
				{
					return ReplayOutcome.BlockedByItems;
				}
			}
			Player mainPlayer = GameMain.mainPlayer;
			PlayerAction_Build actionBuild = mainPlayer.controller.actionBuild;
			actionBuild.SetFactoryReferences();
			actionBuild.SetToolsFactoryReferences();
			Recorder.Replaying = true;
			try
			{
				foreach (TrackedObject item2 in list)
				{
					if (item2.Id != 0 && actionBuild.DoDismantleObject(item2.Id))
					{
						flag = true;
					}
				}
				List<TrackedObject> list5 = new List<TrackedObject>();
				foreach (TrackedObject item3 in list2)
				{
					if (Restore(history, item3, mainPlayer))
					{
						list5.Add(item3);
						flag = true;
					}
				}
				foreach (TrackedObject item4 in list5)
				{
					Reconnect(factory, item4);
				}
				foreach (TrackedObject item5 in list5)
				{
					FinishRestore(factory, item5);
				}
				int num = default(int);
				foreach (Change item6 in list3)
				{
					ItemProto val = ((ProtoSet<ItemProto>)(object)LDB.items).Select(undo ? item6.FromProtoId : item6.ToProtoId);
					if (item6.Target.Id != 0 && val != null && actionBuild.DoUpgradeObject(item6.Target.Id, val.Grade, 0, ref num))
					{
						flag = true;
					}
				}
				if (list3.Count > 0)
				{
					factory.planet.physics.SetPlanetPhysicsColliderDirty();
				}
				foreach (Change item7 in list4)
				{
					int id = item7.Target.Id;
					SettingsSnapshot settingsSnapshot = ((id != 0) ? SettingsSnapshot.Capture(factory, id) : null);
					if (settingsSnapshot != null && item7.Settings.Restore(factory, id))
					{
						item7.Settings = settingsSnapshot;
						flag = true;
					}
				}
			}
			finally
			{
				Recorder.Replaying = false;
			}
			if (!flag)
			{
				return ReplayOutcome.NothingToApply;
			}
			MovePathStart(actionBuild, undo ? step.PathAfter : step.PathBefore, undo ? step.PathBefore : step.PathAfter);
			return ReplayOutcome.Applied;
		}

		private static void MovePathStart(PlayerAction_Build build, PathStart? from, PathStart? to)
		{
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: 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_0068: Unknown result type (might be due to invalid IL or missing references)
			BuildTool_Path pathTool = build.pathTool;
			if (from != null && to != null && (object)build.activeTool == pathTool && ((BuildTool)pathTool).controller.cmd.stage == 1 && !(pathTool.startTarget != from.Position))
			{
				pathTool.startObjectId = to.Target?.Id ?? 0;
				pathTool.startNearestAddonAreaIdx = to.NearestAddonAreaIdx;
				pathTool.startTarget = to.Position;
				pathTool.startTilt = to.Tilt;
			}
		}

		private static bool HoldsItems(PlanetFactory factory, int objId)
		{
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			if (objId <= 0)
			{
				return false;
			}
			ref EntityData reference = ref factory.entityPool[objId];
			if (reference.storageId != 0 && !factory.factoryStorage.storagePool[reference.storageId].isEmpty)
			{
				return true;
			}
			if (reference.tankId != 0 && factory.factoryStorage.tankPool[reference.tankId].fluidCount > 0)
			{
				return true;
			}
			StationComponent val = ((reference.stationId != 0) ? factory.transport.stationPool[reference.stationId] : null);
			if (val == null)
			{
				return false;
			}
			if (val.workDroneCount > 0 || val.workShipCount > 0)
			{
				return true;
			}
			StationStore[] storage = val.storage;
			for (int i = 0; i < storage.Length; i++)
			{
				if (storage[i].count > 0)
				{
					return true;
				}
			}
			return false;
		}

		private static bool Restore(FactoryHistory history, TrackedObject target, Player player)
		{
			//IL_0018: 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_001e: 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)
			if (target.Id != 0 || target.Snapshot == null)
			{
				return false;
			}
			PrebuildData val = target.Snapshot.ToPrebuild();
			int protoId = val.protoId;
			int num = 1;
			int num2 = default(int);
			if (player.inhandItemId == protoId && player.inhandItemCount > 0)
			{
				player.UseHandItems(num, ref num2);
			}
			else
			{
				player.package.TakeTailItems(ref protoId, ref num, ref num2, false);
			}
			val.itemRequired = ((num != 1) ? 1 : 0);
			int num3 = history.Factory.AddPrebuildDataWithComponents(val);
			if (num3 == 0)
			{
				return false;
			}
			history.Bind(target, -num3);
			if (!string.IsNullOrEmpty(target.Snapshot.extraInfo))
			{
				history.Factory.WriteExtraInfoOnPrebuild(num3, target.Snapshot.extraInfo);
			}
			return true;
		}

		private static void Reconnect(PlanetFactory factory, TrackedObject target)
		{
			ModelProto obj = LDB.models.modelArray[factory.prebuildPool[-target.Id].modelIndex];
			bool flag = obj != null && obj.prefabDesc?.isBelt == true;
			bool flag2 = default(bool);
			int num = default(int);
			int num2 = default(int);
			int num3 = default(int);
			foreach (Connection connection in target.Snapshot.connections)
			{
				int id = connection.Other.Id;
				if (id != 0 && (!flag || id <= 0 || factory.entityPool[id].inserterId == 0))
				{
					factory.ReadObjectConn(target.Id, connection.Slot, ref flag2, ref num, ref num2);
					factory.ReadObjectConn(id, connection.OtherSlot, ref flag2, ref num3, ref num2);
					if (num == 0 && num3 == 0)
					{
						factory.WriteObjectConn(target.Id, connection.Slot, connection.IsOutput, id, connection.OtherSlot);
					}
				}
			}
		}

		private static void FinishRestore(PlanetFactory factory, TrackedObject target)
		{
			int num = -target.Id;
			factory.PostRefreshPrebuildDisplay(num, false);
			PrefabDesc val = LDB.models.modelArray[factory.prebuildPool[num].modelIndex]?.prefabDesc;
			if (val != null && val.isStorage && !val.isBattleBase)
			{
				factory.transport.RefreshDispenserOnStoragePrebuildBuild(target.Id);
			}
		}
	}
	internal sealed class SettingsSnapshot
	{
		private const int StationSettings = 320;

		private const int StationDroneAutoReplenish = 330;

		private const int StationShipAutoReplenish = 331;

		private BuildingParameters _parameters;

		private SettingsSnapshot(BuildingParameters parameters)
		{
			//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)
			_parameters = parameters;
		}

		public static SettingsSnapshot? Capture(PlanetFactory factory, int objId)
		{
			//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_0015: Unknown result type (might be due to invalid IL or missing references)
			BuildingParameters zero = BuildingParameters.zero;
			if (!((BuildingParameters)(ref zero)).CopyFromFactoryObject(objId, factory, false, false))
			{
				return null;
			}
			return new SettingsSnapshot(zero);
		}

		public bool Restore(PlanetFactory factory, int objId)
		{
			//IL_00a2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a9: Invalid comparison between Unknown and I4
			//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Invalid comparison between Unknown and I4
			if (objId < 0)
			{
				ref PrebuildData reference = ref factory.prebuildPool[-objId];
				reference.recipeId = _parameters.recipeId;
				reference.filterId = _parameters.filterId;
				reference.content = _parameters.content;
				((BuildingParameters)(ref _parameters)).ToParamsArray(ref reference.parameters, ref reference.paramCount);
				return true;
			}
			ref EntityData reference2 = ref factory.entityPool[objId];
			if (reference2.splitterId != 0)
			{
				((SplitterComponent)(ref factory.cargoTraffic.splitterPool[reference2.splitterId])).UnsetPriority();
			}
			if (reference2.storageId != 0 && ((int)_parameters.type == 18 || ((int)_parameters.type == 3 && reference2.protoId == _parameters.itemId)))
			{
				StorageComponent val = factory.factoryStorage.storagePool[reference2.storageId];
				for (int i = 0; i < val.size; i++)
				{
					val.SetFilter(i, 0);
				}
			}
			bool result = ((BuildingParameters)(ref _parameters)).PasteToFactoryObject(objId, factory);
			int[] parameters = _parameters.parameters;
			if (reference2.assemblerId != 0 && parameters != null && parameters.Length > 0)
			{
				factory.factorySystem.assemblerPool[reference2.assemblerId].forceAccMode = parameters[0] > 0;
				result = true;
			}
			StationComponent val2 = ((reference2.stationId != 0) ? factory.transport.stationPool[reference2.stationId] : null);
			if (val2 != null && !val2.isVeinCollector && parameters != null && parameters.Length > 331 && parameters[320] > 0)
			{
				val2.droneAutoReplenish = parameters[330] > 0;
				val2.shipAutoReplenish = parameters[331] > 0;
				result = true;
			}
			return result;
		}
	}
	internal enum ChangeKind
	{
		Created,
		Removed,
		Upgraded,
		Reconfigured
	}
	internal sealed class TrackedObject
	{
		public int Id;

		public ObjectSnapshot? Snapshot;
	}
	internal sealed class Change(ChangeKind kind, TrackedObject target)
	{
		public readonly ChangeKind Kind = kind;

		public readonly TrackedObject Target = target;

		public int FromProtoId;

		public int ToProtoId;

		public SettingsSnapshot? Settings;
	}
	internal sealed class PathStart(TrackedObject? target, int nearestAddonAreaIdx, Vector3 position, float tilt)
	{
		public readonly TrackedObject? Target = target;

		public readonly int NearestAddonAreaIdx = nearestAddonAreaIdx;

		public readonly Vector3 Position = position;

		public readonly float Tilt = tilt;
	}
	internal sealed class UndoStep(int? holdId)
	{
		public readonly int? HoldId = holdId;

		public readonly List<Change> Changes = new List<Change>();

		public PathStart? PathBefore;

		public PathStart? PathAfter;
	}
	internal sealed class FactoryHistory(PlanetFactory factory)
	{
		public readonly PlanetFactory Factory = factory;

		public readonly List<UndoStep> Undo = new List<UndoStep>();

		public readonly List<UndoStep> Redo = new List<UndoStep>();

		private readonly Dictionary<int, TrackedObject> _live = new Dictionary<int, TrackedObject>();

		public TrackedObject Track(int objId)
		{
			lock (_live)
			{
				if (!_live.TryGetValue(objId, out TrackedObject value))
				{
					value = new TrackedObject
					{
						Id = objId
					};
					_live[objId] = value;
				}
				return value;
			}
		}

		public void Bind(TrackedObject target, int objId)
		{
			lock (_live)
			{
				target.Id = objId;
				_live[objId] = target;
			}
		}

		public void Move(int fromId, int toId)
		{
			lock (_live)
			{
				if (_live.TryGetValue(fromId, out TrackedObject value))
				{
					_live.Remove(fromId);
					value.Id = toId;
					_live[toId] = value;
				}
			}
		}

		public void Forget(int objId)
		{
			lock (_live)
			{
				if (_live.TryGetValue(objId, out TrackedObject value))
				{
					_live.Remove(objId);
					value.Id = 0;
				}
			}
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "com.geostyx.dsp.factoryundo";

		public const string PLUGIN_NAME = "FactoryUndo";

		public const string PLUGIN_VERSION = "0.1.0";
	}
}