Decompiled source of Widescreen v1.1.0

Widescreen.dll

Decompiled 2 days 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.Text;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("Widescreen")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.0.0")]
[assembly: AssemblyInformationalVersion("1.1.0")]
[assembly: AssemblyProduct("Widescreen")]
[assembly: AssemblyTitle("Widescreen")]
[assembly: AssemblyVersion("1.1.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 Widescreen
{
	[HarmonyPatch(typeof(CardBarButton), "OnPointerEnter")]
	internal static class CardPreviewPatch
	{
		private const float GapPixels = 8f;

		private static void Postfix(CardBarButton __instance)
		{
			if (!WidescreenPlugin.cardPreviewUnderCard.Value)
			{
				return;
			}
			CardBar componentInParent = ((Component)__instance).GetComponentInParent<CardBar>();
			GameObject val = (((Object)(object)componentInParent != (Object)null) ? Traverse.Create((object)componentInParent).Field("currentCard").GetValue<GameObject>() : null);
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			try
			{
				Place(__instance, val);
			}
			catch (Exception ex)
			{
				WidescreenPlugin.Log.LogWarning((object)("Couldn't move card preview: " + ex.Message));
			}
		}

		private static void Place(CardBarButton button, GameObject preview)
		{
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0033: Unknown result type (might be due to invalid IL or missing references)
			//IL_0047: 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_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_00dd: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00eb: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f7: Unknown result type (might be due to invalid IL or missing references)
			//IL_0106: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0112: Unknown result type (might be due to invalid IL or missing references)
			//IL_011e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0123: Unknown result type (might be due to invalid IL or missing references)
			//IL_0128: Unknown result type (might be due to invalid IL or missing references)
			//IL_012c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0133: Unknown result type (might be due to invalid IL or missing references)
			//IL_0138: Unknown result type (might be due to invalid IL or missing references)
			//IL_013a: Unknown result type (might be due to invalid IL or missing references)
			//IL_013f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0142: Unknown result type (might be due to invalid IL or missing references)
			//IL_0144: Unknown result type (might be due to invalid IL or missing references)
			//IL_0149: Unknown result type (might be due to invalid IL or missing references)
			//IL_0151: Unknown result type (might be due to invalid IL or missing references)
			//IL_0168: Unknown result type (might be due to invalid IL or missing references)
			//IL_016a: Unknown result type (might be due to invalid IL or missing references)
			Transform transform = ((Component)button).transform;
			Transform rt = ((transform is RectTransform) ? transform : null);
			Canvas componentInParent = ((Component)button).GetComponentInParent<Canvas>();
			Camera cam = (((Object)(object)componentInParent != (Object)null && (int)componentInParent.renderMode != 0) ? componentInParent.worldCamera : null);
			Rect val = ScreenRect((RectTransform)(object)rt, cam);
			Camera val2 = PreviewCamera(preview);
			if (!((Object)(object)val2 == (Object)null))
			{
				Rect val3 = PreviewScreenRect(preview, val2);
				if (!(((Rect)(ref val3)).height <= 0f))
				{
					float x = ((Rect)(ref val)).center.x;
					float num = ((Rect)(ref val)).yMin - 8f - ((Rect)(ref val3)).height / 2f;
					float num2 = Mathf.Clamp(x, ((Rect)(ref val3)).width / 2f, (float)Screen.width - ((Rect)(ref val3)).width / 2f);
					num = Mathf.Clamp(num, ((Rect)(ref val3)).height / 2f, (float)Screen.height - ((Rect)(ref val3)).height / 2f);
					Vector3 val4 = val2.WorldToScreenPoint(preview.transform.position);
					Vector3 val5 = new Vector3(((Rect)(ref val3)).center.x, ((Rect)(ref val3)).center.y, 0f) - new Vector3(val4.x, val4.y, 0f);
					Vector3 val6 = new Vector3(num2, num, val4.z) - val5;
					Vector3 val7 = val2.ScreenToWorldPoint(val6);
					preview.transform.position = val7;
					(preview.GetComponent<PinPosition>() ?? preview.AddComponent<PinPosition>()).Target = val7;
				}
			}
		}

		private static Rect ScreenRect(RectTransform rt, Camera cam)
		{
			//IL_00d1: Unknown result type (might be due to invalid IL or missing references)
			Vector3[] array = (Vector3[])(object)new Vector3[4];
			rt.GetWorldCorners(array);
			Vector2[] source = array.Select((Vector3 c) => RectTransformUtility.WorldToScreenPoint(cam, c)).ToArray();
			float num = source.Min((Vector2 p) => p.x);
			float num2 = source.Max((Vector2 p) => p.x);
			float num3 = source.Min((Vector2 p) => p.y);
			float num4 = source.Max((Vector2 p) => p.y);
			return Rect.MinMaxRect(num, num3, num2, num4);
		}

		private static Camera PreviewCamera(GameObject preview)
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Invalid comparison between Unknown and I4
			Canvas componentInChildren = preview.GetComponentInChildren<Canvas>();
			if ((Object)(object)componentInChildren != (Object)null && (int)componentInChildren.renderMode == 2 && (Object)(object)componentInChildren.worldCamera != (Object)null)
			{
				return componentInChildren.worldCamera;
			}
			int layerBit = 1 << preview.layer;
			return ((IEnumerable<Camera>)Camera.allCameras).FirstOrDefault((Func<Camera, bool>)((Camera c) => (c.cullingMask & layerBit) != 0 && (Object)(object)c.targetTexture == (Object)null)) ?? Camera.main;
		}

		private static Rect PreviewScreenRect(GameObject preview, Camera cam)
		{
			//IL_0002: Unknown result type (might be due to invalid IL or missing references)
			//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_005f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0053: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			Rect result = default(Rect);
			RectTransform[] componentsInChildren = preview.GetComponentsInChildren<RectTransform>(true);
			for (int i = 0; i < componentsInChildren.Length; i++)
			{
				Rect val = ScreenRect(componentsInChildren[i], cam);
				if (((Rect)(ref val)).width * ((Rect)(ref val)).height > ((Rect)(ref result)).width * ((Rect)(ref result)).height && ((Rect)(ref val)).height < (float)Screen.height * 1.5f)
				{
					result = val;
				}
			}
			return result;
		}
	}
	internal class PinPosition : MonoBehaviour
	{
		public Vector3 Target;

		private void LateUpdate()
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			((Component)this).transform.position = Target;
		}
	}
	[BepInPlugin("com.yofakeparent.rounds.widescreen", "Widescreen", "1.1.0")]
	[BepInProcess("Rounds.exe")]
	public class WidescreenPlugin : BaseUnityPlugin
	{
		public const string ModId = "com.yofakeparent.rounds.widescreen";

		public const string ModName = "Widescreen";

		public const string Version = "1.1.0";

		private const float ReferenceAspect = 1.7777778f;

		internal static ManualLogSource Log;

		private static ConfigEntry<bool> forceNativeResolution;

		internal static ConfigEntry<string> extraResolutions;

		internal static ConfigEntry<bool> cardPreviewUnderCard;

		private static ConfigEntry<bool> uiToScreenEdges;

		private static ConfigEntry<bool> stretchFixedWidthPanels;

		private static ConfigEntry<bool> fullCameraViewport;

		private static ConfigEntry<KeyCode> dumpKey;

		private readonly Dictionary<int, float> originalMatch = new Dictionary<int, float>();

		private int lastW;

		private int lastH;

		private static bool IsWiderThan16x9 => (float)Screen.width / (float)Screen.height > 1.7877778f;

		private void Awake()
		{
			//IL_00f8: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			forceNativeResolution = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "AlwaysForceNativeResolution", false, "In fullscreen, ignore the resolution picked in the options menu and always use the monitor's native one.");
			extraResolutions = ((BaseUnityPlugin)this).Config.Bind<string>("Display", "ExtraResolutions", "3440x1440", "Resolutions added to the in-game Resolution menu, comma separated (e.g. 3440x1440, 2560x1080, 5120x1440). Your monitor's native resolution is always added too.");
			cardPreviewUnderCard = ((BaseUnityPlugin)this).Config.Bind<bool>("UI", "CardPreviewUnderCard", true, "When hovering a card in the card bar, show the big card right under it instead of in the corner of the map.");
			fullCameraViewport = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "FullCameraViewport", true, "Remove any pillarboxing so cameras render across the whole screen.");
			uiToScreenEdges = ((BaseUnityPlugin)this).Config.Bind<bool>("UI", "UIToScreenEdges", true, "Scale the HUD by screen height so edge-anchored UI (cards, scores) sits at the real screen edges instead of being stretched over the map.");
			stretchFixedWidthPanels = ((BaseUnityPlugin)this).Config.Bind<bool>("UI", "StretchFixedWidthPanels", true, "Widen UI panels that were built as fixed 16:9-wide strips so their contents reach the screen edges.");
			dumpKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Debug", "DumpUIKey", (KeyCode)289, "Press to write every canvas and its layout to the BepInEx log (useful for reporting UI that still overlaps).");
			new Harmony("com.yofakeparent.rounds.widescreen").PatchAll(typeof(WidescreenPlugin).Assembly);
			SceneManager.sceneLoaded += delegate
			{
				((MonoBehaviour)this).StartCoroutine(ApplyNextFrame());
			};
			((MonoBehaviour)this).StartCoroutine(PeriodicApply());
			Log.LogInfo((object)"Widescreen 1.1.0 loaded");
		}

		private void Update()
		{
			//IL_003b: Unknown result type (might be due to invalid IL or missing references)
			if (Screen.width != lastW || Screen.height != lastH)
			{
				lastW = Screen.width;
				lastH = Screen.height;
				ApplyAll();
			}
			if (Input.GetKeyDown(dumpKey.Value))
			{
				DumpUI();
			}
		}

		private IEnumerator ApplyNextFrame()
		{
			yield return null;
			ApplyAll();
		}

		private IEnumerator PeriodicApply()
		{
			WaitForSecondsRealtime wait = new WaitForSecondsRealtime(1f);
			while (true)
			{
				yield return wait;
				ApplyAll();
			}
		}

		internal static void EnforceNativeResolution()
		{
			//IL_008c: Unknown result type (might be due to invalid IL or missing references)
			if (forceNativeResolution.Value && Screen.fullScreen)
			{
				int systemWidth = Display.main.systemWidth;
				int systemHeight = Display.main.systemHeight;
				if (systemWidth > 0 && systemHeight > 0 && (Screen.width != systemWidth || Screen.height != systemHeight))
				{
					Log.LogInfo((object)$"Switching to native resolution {systemWidth}x{systemHeight} (was {Screen.width}x{Screen.height}).");
					Screen.SetResolution(systemWidth, systemHeight, Screen.fullScreenMode);
				}
			}
		}

		private void ApplyAll()
		{
			//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ce: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Unknown result type (might be due to invalid IL or missing references)
			//IL_00de: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e4: Invalid comparison between Unknown and I4
			//IL_008a: Unknown result type (might be due to invalid IL or missing references)
			if (fullCameraViewport.Value)
			{
				Camera[] allCameras = Camera.allCameras;
				foreach (Camera val in allCameras)
				{
					if (!((Object)(object)val.targetTexture != (Object)null))
					{
						Rect rect = val.rect;
						if (((Rect)(ref rect)).x > 0f && ((Rect)(ref rect)).x < 0.5f && Mathf.Approximately(((Rect)(ref rect)).x + ((Rect)(ref rect)).width, 1f - ((Rect)(ref rect)).x))
						{
							val.rect = new Rect(0f, ((Rect)(ref rect)).y, 1f, ((Rect)(ref rect)).height);
						}
					}
				}
			}
			CanvasScaler[] array = Resources.FindObjectsOfTypeAll<CanvasScaler>();
			foreach (CanvasScaler val2 in array)
			{
				if ((Object)(object)val2 == (Object)null)
				{
					continue;
				}
				Scene scene = ((Component)val2).gameObject.scene;
				if (!((Scene)(ref scene)).IsValid() || (int)val2.uiScaleMode != 1)
				{
					continue;
				}
				int instanceID = ((Object)val2).GetInstanceID();
				if (!originalMatch.ContainsKey(instanceID))
				{
					originalMatch[instanceID] = val2.matchWidthOrHeight;
				}
				if (uiToScreenEdges.Value && IsWiderThan16x9)
				{
					val2.screenMatchMode = (ScreenMatchMode)0;
					val2.matchWidthOrHeight = 1f;
					if (stretchFixedWidthPanels.Value)
					{
						StretchFixedWidthChildren(val2);
					}
				}
				else
				{
					val2.matchWidthOrHeight = originalMatch[instanceID];
				}
			}
		}

		private static void StretchFixedWidthChildren(CanvasScaler scaler)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_003c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0042: Expected O, but got Unknown
			//IL_004e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_0082: 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_00be: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e3: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: 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_010f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0119: Unknown result type (might be due to invalid IL or missing references)
			float x = scaler.referenceResolution.x;
			Transform transform = ((Component)scaler).transform;
			RectTransform val = (RectTransform)(object)((transform is RectTransform) ? transform : null);
			if ((Object)(object)val == (Object)null || x <= 0f)
			{
				return;
			}
			foreach (Transform item in (Transform)val)
			{
				object obj = (object)item;
				RectTransform val2 = (RectTransform)((obj is RectTransform) ? obj : null);
				if (val2 != null && Mathf.Approximately(val2.anchorMin.x, 0.5f) && Mathf.Approximately(val2.anchorMax.x, 0.5f) && !(Mathf.Abs(val2.sizeDelta.x - x) > 2f) && !(Mathf.Abs(val2.anchoredPosition.x) > 2f))
				{
					val2.anchorMin = new Vector2(0f, val2.anchorMin.y);
					val2.anchorMax = new Vector2(1f, val2.anchorMax.y);
					val2.sizeDelta = new Vector2(0f, val2.sizeDelta.y);
					val2.anchoredPosition = new Vector2(0f, val2.anchoredPosition.y);
					Log.LogInfo((object)("Stretched fixed-width panel '" + Path((Transform)(object)val2) + "' to screen width."));
				}
			}
		}

		private static void DumpUI()
		{
			//IL_0063: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ea: Unknown result type (might be due to invalid IL or missing references)
			//IL_011d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0129: Unknown result type (might be due to invalid IL or missing references)
			//IL_0169: Unknown result type (might be due to invalid IL or missing references)
			//IL_0170: Expected O, but got Unknown
			//IL_01ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_01ba: Unknown result type (might be due to invalid IL or missing references)
			//IL_01c9: Unknown result type (might be due to invalid IL or missing references)
			//IL_01d8: Unknown result type (might be due to invalid IL or missing references)
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.AppendLine($"=== UI dump @ {Screen.width}x{Screen.height} (aspect {(float)Screen.width / (float)Screen.height:0.###}) ===");
			Camera[] allCameras = Camera.allCameras;
			foreach (Camera val in allCameras)
			{
				stringBuilder.AppendLine($"Camera '{((Object)val).name}' rect={val.rect} ortho={val.orthographic} size={val.orthographicSize:0.##} aspect={val.aspect:0.###}");
			}
			Canvas[] array = Object.FindObjectsOfType<Canvas>();
			foreach (Canvas val2 in array)
			{
				if (!val2.isRootCanvas)
				{
					continue;
				}
				CanvasScaler component = ((Component)val2).GetComponent<CanvasScaler>();
				stringBuilder.AppendLine($"Canvas '{Path(((Component)val2).transform)}' mode={val2.renderMode} scale={val2.scaleFactor:0.###}" + (((Object)(object)component != (Object)null) ? $" scaler={component.uiScaleMode} ref={component.referenceResolution} match={component.matchWidthOrHeight}" : ""));
				foreach (Transform item in ((Component)val2).transform)
				{
					Transform val3 = item;
					RectTransform val4 = (RectTransform)(object)((val3 is RectTransform) ? val3 : null);
					if (val4 != null)
					{
						stringBuilder.AppendLine($"    {((Object)val3).name} active={((Component)val3).gameObject.activeInHierarchy} anchors={val4.anchorMin}-{val4.anchorMax} pos={val4.anchoredPosition} size={val4.sizeDelta}");
					}
				}
			}
			Log.LogInfo((object)stringBuilder.ToString());
		}

		private static string Path(Transform t)
		{
			if (!((Object)(object)t.parent == (Object)null))
			{
				return Path(t.parent) + "/" + ((Object)t).name;
			}
			return ((Object)t).name;
		}
	}
	[HarmonyPatch(typeof(Optionshandler), "ApplyOptions")]
	internal static class ApplyOptionsPatch
	{
		private static void Postfix()
		{
			WidescreenPlugin.EnforceNativeResolution();
		}
	}
	[HarmonyPatch(typeof(Optionshandler), "SetFullScreen")]
	internal static class SetFullScreenPatch
	{
		private static void Postfix()
		{
			WidescreenPlugin.EnforceNativeResolution();
		}
	}
	[HarmonyPatch(typeof(Optionshandler), "SetResolution")]
	internal static class SetResolutionPatch
	{
		private static void Postfix()
		{
			WidescreenPlugin.EnforceNativeResolution();
		}
	}
	[HarmonyPatch(typeof(MultiOptions), "GetBestResolutions")]
	internal static class ResolutionMenuPatch
	{
		private static void Postfix(ref Resolution[] __result)
		{
			//IL_001b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0020: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ca: Unknown result type (might be due to invalid IL or missing references)
			List<Resolution> list = ((IEnumerable<Resolution>)(((object)__result) ?? ((object)new Resolution[0]))).ToList();
			Resolution item;
			int num;
			if (list.Count <= 0)
			{
				item = Screen.currentResolution;
				num = ((Resolution)(ref item)).refreshRate;
			}
			else
			{
				num = list.Max((Resolution r) => ((Resolution)(ref r)).refreshRate);
			}
			int refreshRate = num;
			foreach (var item2 in Wanted())
			{
				var (w, h) = item2;
				if (!list.Any((Resolution r) => ((Resolution)(ref r)).width == w && ((Resolution)(ref r)).height == h))
				{
					item = default(Resolution);
					((Resolution)(ref item)).width = w;
					((Resolution)(ref item)).height = h;
					((Resolution)(ref item)).refreshRate = refreshRate;
					list.Add(item);
				}
			}
			__result = (from r in list
				orderby ((Resolution)(ref r)).width, ((Resolution)(ref r)).height
				select r).ToArray();
		}

		private static IEnumerable<(int, int)> Wanted()
		{
			if (Display.main.systemWidth > 0 && Display.main.systemHeight > 0)
			{
				yield return (Display.main.systemWidth, Display.main.systemHeight);
			}
			string[] array = WidescreenPlugin.extraResolutions.Value.Split(new char[1] { ',' });
			for (int i = 0; i < array.Length; i++)
			{
				string[] array2 = array[i].Trim().ToLowerInvariant().Split('x', '×');
				if (array2.Length == 2 && int.TryParse(array2[0].Trim(), out var result) && int.TryParse(array2[1].Trim(), out var result2) && result >= 640 && result2 >= 360)
				{
					yield return (result, result2);
				}
			}
		}
	}
}