Decompiled source of BifrostPortal v1.0.3

BifrostPortal.dll

Decompiled 2 days ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using Jotunn;
using Jotunn.Configs;
using Jotunn.Entities;
using Jotunn.Managers;
using Jotunn.Utils;
using On;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: AssemblyTitle("BifrostPortal")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BifrostPortal")]
[assembly: AssemblyCopyright("Copyright UranusMaster© 2021")]
[assembly: AssemblyTrademark("")]
[assembly: ComVisible(false)]
[assembly: Guid("5C321774-11A2-4A28-95F2-39DE180FD7D0")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.0.0")]
namespace BifrostPortal;

[BepInPlugin("Uranus.BifrostPortal", "BifrostPortal", "1.0.0")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
[NetworkCompatibility(/*Could not decode attribute arguments.*/)]
internal class BifrostPortal : BaseUnityPlugin
{
	[CompilerGenerated]
	private sealed class <GameConnectPortalsPrefix>d__11 : IEnumerator<object>, IDisposable, IEnumerator
	{
		private int <>1__state;

		private object <>2__current;

		public orig_ConnectPortals orig;

		public Game self;

		public BifrostPortal <>4__this;

		private ZDOMan <zdoMan>5__1;

		private long <logTimestamp>5__2;

		private long <lastLogTimestamp>5__3;

		private bool <shouldLog>5__4;

		private int <index>5__5;

		private bool <getPrefabsComplete>5__6;

		private HashSet<int> <prefabHashcodes>5__7;

		private List<ZDO>.Enumerator <>s__8;

		private ZDO <zdo>5__9;

		private ZDOID <targetZdoid>5__10;

		private string <tag>5__11;

		private ZDO <targetZdo>5__12;

		private List<ZDO>.Enumerator <>s__13;

		private ZDO <zdo>5__14;

		private string <tag>5__15;

		private bool <isOneWayPortal>5__16;

		private ZDO <targetZdo>5__17;

		private List<ZDO> <portalList>5__18;

		object IEnumerator<object>.Current
		{
			[DebuggerHidden]
			get
			{
				return <>2__current;
			}
		}

		object IEnumerator.Current
		{
			[DebuggerHidden]
			get
			{
				return <>2__current;
			}
		}

		[DebuggerHidden]
		public <GameConnectPortalsPrefix>d__11(int <>1__state)
		{
			this.<>1__state = <>1__state;
		}

		[DebuggerHidden]
		void IDisposable.Dispose()
		{
		}

		private bool MoveNext()
		{
			//IL_01e9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ee: Unknown result type (might be due to invalid IL or missing references)
			//IL_022d: Unknown result type (might be due to invalid IL or missing references)
			//IL_02e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_02b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_02ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_038b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0390: Unknown result type (might be due to invalid IL or missing references)
			//IL_0442: Unknown result type (might be due to invalid IL or missing references)
			//IL_047c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0475: Unknown result type (might be due to invalid IL or missing references)
			//IL_0493: Unknown result type (might be due to invalid IL or missing references)
			//IL_04aa: Unknown result type (might be due to invalid IL or missing references)
			BifrostPortal bifrostPortal;
			ZDOMan zdoMan;
			HashSet<int> prefabHashcodes;
			List<ZDO> matchingZdos;
			ref int index;
			switch (<>1__state)
			{
			default:
				return false;
			case 0:
			{
				<>1__state = -1;
				<zdoMan>5__1 = ZDOMan.instance;
				<lastLogTimestamp>5__3 = 0L;
				<logTimestamp>5__2 = DateTimeOffset.Now.ToUnixTimeSeconds();
				<shouldLog>5__4 = (<logTimestamp>5__2 - <lastLogTimestamp>5__3 > _logIntervalSeconds) & _enableDebugLogging.Value;
				<portalList>5__18.Clear();
				<index>5__5 = 0;
				<prefabHashcodes>5__7 = new HashSet<int>();
				List<int> portalPrefabHash = self.PortalPrefabHash;
				for (int i = 0; i < portalPrefabHash.Count; i++)
				{
					<prefabHashcodes>5__7.Add(portalPrefabHash[i]);
				}
				<prefabHashcodes>5__7.Add(StringExtensionMethods.GetStableHashCode("structure_bifrost"));
				goto IL_010f;
			}
			case 1:
				<>1__state = -1;
				if (<getPrefabsComplete>5__6)
				{
					if (<shouldLog>5__4)
					{
						AddNativePortals(<zdoMan>5__1, <portalList>5__18);
						Logger.LogInfo((object)("Found " + <portalList>5__18.Count + " portal prefabs."));
					}
					<>s__8 = <portalList>5__18.GetEnumerator();
					try
					{
						while (<>s__8.MoveNext())
						{
							<zdo>5__9 = <>s__8.Current;
							<targetZdoid>5__10 = <zdo>5__9.GetConnectionZDOID((ConnectionType)1);
							if (!((ZDOID)(ref <targetZdoid>5__10)).IsNone())
							{
								<tag>5__11 = <zdo>5__9.GetString("tag", string.Empty);
								<targetZdo>5__12 = <zdoMan>5__1.GetZDO(<targetZdoid>5__10);
								if (<tag>5__11 == string.Empty || <targetZdo>5__12 == null || (<targetZdo>5__12.GetString("tag", string.Empty) != <tag>5__11 && !<tag>5__11.StartsWith(_onewayPortalTagPrefix.Value)))
								{
									EnsureLocalOwner(<zdo>5__9, <zdoMan>5__1);
									<zdo>5__9.SetConnection((ConnectionType)1, ZDOID.None);
									<zdoMan>5__1.ForceSendZDO(<zdo>5__9.m_uid);
								}
								<targetZdoid>5__10 = default(ZDOID);
								<tag>5__11 = null;
								<targetZdo>5__12 = null;
								<zdo>5__9 = null;
							}
						}
					}
					finally
					{
						((IDisposable)<>s__8/*cast due to .constrained prefix*/).Dispose();
					}
					<>s__8 = default(List<ZDO>.Enumerator);
					<>s__13 = <portalList>5__18.GetEnumerator();
					try
					{
						while (<>s__13.MoveNext())
						{
							<zdo>5__14 = <>s__13.Current;
							<tag>5__15 = <zdo>5__14.GetString("tag", string.Empty);
							if (<tag>5__15 == string.Empty)
							{
								continue;
							}
							ZDOID connectionZDOID = <zdo>5__14.GetConnectionZDOID((ConnectionType)1);
							if (((ZDOID)(ref connectionZDOID)).IsNone())
							{
								<isOneWayPortal>5__16 = <tag>5__15.StartsWith(_onewayPortalTagPrefix.Value);
								<targetZdo>5__17 = self.FindRandomUnconnectedPortal(<portalList>5__18, <zdo>5__14, <isOneWayPortal>5__16 ? <tag>5__15.Remove(0, _onewayPortalTagPrefix.Value.Length) : <tag>5__15);
								if (<targetZdo>5__17 != null)
								{
									EnsureLocalOwner(<zdo>5__14, <zdoMan>5__1);
									<zdo>5__14.SetConnection((ConnectionType)1, <targetZdo>5__17.m_uid);
									EnsureLocalOwner(<targetZdo>5__17, <zdoMan>5__1);
									<targetZdo>5__17.SetConnection((ConnectionType)1, <isOneWayPortal>5__16 ? ZDOID.None : <zdo>5__14.m_uid);
									<zdoMan>5__1.ForceSendZDO(<zdo>5__14.m_uid);
									<zdoMan>5__1.ForceSendZDO(<targetZdo>5__17.m_uid);
								}
								<tag>5__15 = null;
								<targetZdo>5__17 = null;
								<zdo>5__14 = null;
							}
						}
					}
					finally
					{
						((IDisposable)<>s__13/*cast due to .constrained prefix*/).Dispose();
					}
					<>s__13 = default(List<ZDO>.Enumerator);
					if (<shouldLog>5__4)
					{
						Logger.LogInfo((object)("ZDOMan.instance.m_objectsById.Count: " + <zdoMan>5__1.m_objectsByID.Count));
						<lastLogTimestamp>5__3 = <logTimestamp>5__2;
					}
					break;
				}
				goto IL_010f;
			case 2:
				break;
				IL_010f:
				bifrostPortal = <>4__this;
				zdoMan = <zdoMan>5__1;
				prefabHashcodes = <prefabHashcodes>5__7;
				matchingZdos = <portalList>5__18;
				index = ref <index>5__5;
				<prefabHashcodes>5__7.Add(-574667757);
				<getPrefabsComplete>5__6 = bifrostPortal.GetAllZdosMatchingPrefabHashcodes(zdoMan, prefabHashcodes, matchingZdos, ref index);
				<>2__current = null;
				<>1__state = 1;
				return true;
			}
			return false;
		}

		bool IEnumerator.MoveNext()
		{
			//ILSpy generated this explicit interface implementation from .override directive in MoveNext
			return this.MoveNext();
		}

		[DebuggerHidden]
		void IEnumerator.Reset()
		{
			throw new NotSupportedException();
		}
	}

	public const string PluginGUID = "Uranus.BifrostPortal";

	public const string PluginName = "BifrostPortal";

	public const string PluginVersion = "1.0.0";

	private AssetBundle bifrost_bundle;

	private static readonly long _logIntervalSeconds = 60L;

	private static ConfigEntry<float> _connectPortalCoroutineWait;

	private static ConfigEntry<string> _onewayPortalTagPrefix;

	private static ConfigEntry<int> _getMatchingZdosBreakCount;

	private static ConfigEntry<bool> _enableDebugLogging;

	private void Awake()
	{
		//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b2: Expected O, but got Unknown
		//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c4: Expected O, but got Unknown
		//IL_00cb: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d5: Expected O, but got Unknown
		AssetLoad();
		LoadPortalBifrost();
		Logger.ShowDate = true;
		_connectPortalCoroutineWait = ((BaseUnityPlugin)this).Config.Bind<float>("Portals", "connectPortalCoroutineWait", 5f, "Wait time (seconds) when ConnectPortal coroutine yields.");
		_onewayPortalTagPrefix = ((BaseUnityPlugin)this).Config.Bind<string>("Portals", "onewayPortalTagPrefix", ">>>", "Prefix for specifying a one-way portal.");
		_getMatchingZdosBreakCount = ((BaseUnityPlugin)this).Config.Bind<int>("Portals", "getMatchingZdosBreakCount", 400, "Max ZDOs to match before breaking/pausing in method.");
		_enableDebugLogging = ((BaseUnityPlugin)this).Config.Bind<bool>("Portals", "enableDebugLogging", false, "Enable periodic portal matching debug logs.");
		Game.ConnectPortals += new hook_ConnectPortals(GameConnectPortalsPrefix);
		ZNetScene.GetPrefab_int += new hook_GetPrefab_int(LegacyCompatibility.GetPrefab);
		ZNetScene.HasPrefab += new hook_HasPrefab(LegacyCompatibility.HasPrefab);
	}

	private void AssetLoad()
	{
		bifrost_bundle = AssetUtils.LoadAssetBundleFromResources("bifrost_bundle", Assembly.GetExecutingAssembly());
	}

	private void LoadPortalBifrost()
	{
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0019: Expected O, but got Unknown
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0064: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Expected O, but got Unknown
		//IL_006f: 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_0089: Unknown result type (might be due to invalid IL or missing references)
		//IL_0092: Expected O, but got Unknown
		//IL_0094: Unknown result type (might be due to invalid IL or missing references)
		//IL_0099: Unknown result type (might be due to invalid IL or missing references)
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b6: Expected O, but got Unknown
		//IL_00bd: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c3: Expected O, but got Unknown
		GameObject val = bifrost_bundle.LoadAsset<GameObject>("structure_bifrost");
		PieceConfig val2 = new PieceConfig();
		val2.AllowedInDungeons = false;
		val2.CraftingStation = "piece_workbench";
		val2.PieceTable = "_HammerPieceTable";
		val2.Enabled = true;
		val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[3]
		{
			new RequirementConfig
			{
				Item = "FineWood",
				Amount = 10,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "GreydwarfEye",
				Amount = 10,
				Recover = true
			},
			new RequirementConfig
			{
				Item = "SurtlingCore",
				Amount = 1,
				Recover = true
			}
		};
		CustomPiece val3 = new CustomPiece(val, val2);
		PieceManager.Instance.AddPiece(val3);
	}

	[IteratorStateMachine(typeof(<GameConnectPortalsPrefix>d__11))]
	private void GameConnectPortalsPrefix(orig_ConnectPortals orig, Game self)
	{
		orig.Invoke(self);
		((MonoBehaviour)self).StartCoroutine((IEnumerator)new <GameConnectPortalsPrefix>d__11(0)
		{
			<>4__this = this,
			orig = orig,
			self = self,
			<portalList>5__18 = new List<ZDO>()
		});
	}

	private bool GetAllZdosMatchingPrefabHashcodes(ZDOMan zdoMan, HashSet<int> prefabHashcodes, List<ZDO> matchingZdos, ref int index)
	{
		List<ZDO>[] objectsBySector = zdoMan.m_objectsBySector;
		foreach (List<ZDO> list in objectsBySector)
		{
			if (list == null)
			{
				continue;
			}
			for (int j = 0; j < list.Count; j++)
			{
				ZDO val = list[j];
				if (val.IsValid() && prefabHashcodes.Contains(val.GetPrefab()))
				{
					matchingZdos.Add(val);
				}
			}
		}
		return true;
	}

	private static void EnsureLocalOwner(ZDO zdo, ZDOMan zdoMan)
	{
		if (!zdo.IsOwner())
		{
			zdo.SetOwnerInternal(0L);
			zdo.SetOwner(ZDOMan.GetSessionID());
		}
	}

	private static void AddNativePortals(ZDOMan zdoMan, List<ZDO> portals)
	{
		List<ZDO> portalList = zdoMan.GetPortalList();
		for (int i = 0; i < portalList.Count; i++)
		{
			if (!portals.Contains(portalList[i]))
			{
				portals.Add(portalList[i]);
			}
		}
	}
}
public static class LegacyCompatibility
{
	public const int LegacyAsgardPortalHash = -574667757;

	public const int CurrentBifrostPortalHash = -1477735023;

	private static bool _loggedLegacyResolution;

	private static int MapHash(int hash)
	{
		if (hash != -574667757)
		{
			return hash;
		}
		if (!_loggedLegacyResolution)
		{
			_loggedLegacyResolution = true;
			Debug.Log((object)("[BifrostPortal Compatibility] Resolving legacy structure_asgard_portal hash " + -574667757 + " as structure_bifrost hash " + -1477735023));
		}
		return -1477735023;
	}

	public static GameObject GetPrefab(orig_GetPrefab_int orig, ZNetScene self, int hash)
	{
		return orig.Invoke(self, MapHash(hash));
	}

	public static bool HasPrefab(orig_HasPrefab orig, ZNetScene self, int hash)
	{
		return orig.Invoke(self, MapHash(hash));
	}
}