Decompiled source of KeepUnknownPieces v1.0.0

KeepUnknownPieces.dll

Decompiled 2 days ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using BepInEx;
using BepInEx.Logging;
using HarmonyLib;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace KeepUnknownPieces;

[BepInPlugin("kenny.keepunknownpieces", "Keep Unknown Pieces", "1.0.0")]
public class Plugin : BaseUnityPlugin
{
	internal static int kept;

	internal static ManualLogSource Log;

	private static bool swapped;

	private void Awake()
	{
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Expected O, but got Unknown
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0067: Expected O, but got Unknown
		Log = ((BaseUnityPlugin)this).Logger;
		Harmony val = new Harmony("kenny.keepunknownpieces");
		MethodInfo methodInfo = AccessTools.Method(typeof(ZNetScene), "CreateObjectsSorted", (Type[])null, (Type[])null);
		if (methodInfo == null)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)"Valheim changed (CreateObjectsSorted not found); nothing patched. Tell Claude.");
			return;
		}
		val.Patch((MethodBase)methodInfo, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "Transpiler", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
		((BaseUnityPlugin)this).Logger.LogInfo((object)(swapped ? "Unknown objects in the save are kept, not deleted." : "Valheim changed (delete call not found); nothing patched. Tell Claude."));
	}

	private static IEnumerable<CodeInstruction> Transpiler(IEnumerable<CodeInstruction> code)
	{
		MethodInfo destroy = AccessTools.Method(typeof(ZDOMan), "DestroyZDO", (Type[])null, (Type[])null);
		MethodInfo keep = AccessTools.Method(typeof(Plugin), "Keep", (Type[])null, (Type[])null);
		foreach (CodeInstruction item in code)
		{
			if ((item.opcode == OpCodes.Callvirt || item.opcode == OpCodes.Call) && item.operand as MethodInfo == destroy)
			{
				item.opcode = OpCodes.Call;
				item.operand = keep;
				swapped = true;
			}
			yield return item;
		}
	}

	public static void Keep(ZDOMan man, ZDO zdo)
	{
		kept++;
		if (kept <= 20)
		{
			Log.LogWarning((object)("Kept an object Valheim didn't recognise (prefab hash " + ((zdo != null) ? zdo.GetPrefab().ToString() : "?") + "): a mod that adds it may be missing or broken. It comes back when that mod loads."));
		}
	}
}