Decompiled source of TwoPlayerOnePC v1.2.0

plugins/SecondScreenPip.dll

Decompiled 4 days ago
using System;
using System.Collections;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using BepInEx;
using BepInEx.Configuration;
using UnityEngine;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: AssemblyVersion("0.0.0.0")]
namespace SecondScreenPip;

public enum PipRole
{
	Auto,
	Host,
	SecondWindow
}
[BepInDependency(/*Could not decode attribute arguments.*/)]
[BepInPlugin("local.secondscreenpip", "Second Screen PiP", "1.2.0")]
public class Plugin : BaseUnityPlugin
{
	private delegate bool EnumWindowsProc(IntPtr hWnd, IntPtr lParam);

	private const string MutexName = "Local\\RepoSecondScreenPip_Host";

	private ConfigEntry<PipRole> _role;

	private ConfigEntry<KeyCode> _toggleKey;

	private ConfigEntry<KeyCode> _launchKey;

	private ConfigEntry<KeyCode> _switchKey;

	private ConfigEntry<KeyCode> _cornerKey;

	private ConfigEntry<float> _opacity;

	private ConfigEntry<bool> _clickToSwitch;

	private ConfigEntry<bool> _wheelResize;

	private ConfigEntry<bool> _showStatus;

	private ConfigEntry<bool> _passArgs;

	private ConfigEntry<bool> _showOnStart;

	private ConfigEntry<string> _title;

	private ConfigEntry<int> _windowWidth;

	private ConfigEntry<int> _windowX;

	private ConfigEntry<int> _windowY;

	private ConfigEntry<int> _captureWidth;

	private ConfigEntry<int> _fps;

	private ConfigEntry<int> _jpgQuality;

	private ConfigEntry<bool> _flipVertical;

	private static Mutex _mutex;

	private bool _isSender;

	private string _dir;

	private string _frameFile;

	private string _tmpFile;

	private RenderTexture _full;

	private RenderTexture _small;

	private Texture2D _readTex;

	private bool _errorLogged;

	private bool _show;

	private Texture2D _tex;

	private DateTime _lastWrite = DateTime.MinValue;

	private float _lastFrameTime = -100f;

	private float _nextRead;

	private Rect _rect;

	private int _corner;

	private float _resizeTo = -1f;

	private int _recvFrames;

	private int _recvFps;

	private float _fpsT;

	private GUIStyle _statusStyle;

	private static MethodInfo _loadImage;

	private void Awake()
	{
		//IL_03b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_03ba: Unknown result type (might be due to invalid IL or missing references)
		_role = ((BaseUnityPlugin)this).Config.Bind<PipRole>("General", "Role", PipRole.Auto, "Auto: первое окно игры - хост (показывает окошко), следующие - второе окно (передают экран). Host / SecondWindow - задать роль вручную.");
		_toggleKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("General", "ToggleKey", (KeyCode)289, "Показать / скрыть окошко (в окне хоста).");
		_launchKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("General", "LaunchKey", (KeyCode)283, "Запустить вторую копию REPO.exe (в окне хоста).");
		_switchKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("General", "SwitchKey", (KeyCode)285, "Переключиться на другое окно игры (работает в обоих окнах).");
		_cornerKey = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("General", "CornerKey", (KeyCode)290, "Переставить окошко в следующий угол экрана.");
		_opacity = ((BaseUnityPlugin)this).Config.Bind<float>("Window", "Opacity", 1f, "Прозрачность окошка, 0.3 - 1.");
		_clickToSwitch = ((BaseUnityPlugin)this).Config.Bind<bool>("Window", "ClickToSwitch", true, "Клик по картинке переключает на второе окно.");
		_wheelResize = ((BaseUnityPlugin)this).Config.Bind<bool>("Window", "WheelResize", true, "Колесо мыши над окошком меняет его размер.");
		_showStatus = ((BaseUnityPlugin)this).Config.Bind<bool>("Window", "ShowStatus", true, "Показывать LIVE и FPS поверх картинки.");
		_passArgs = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "LaunchPassArgs", false, "Передавать второй копии аргументы командной строки первой (обычно не нужно).");
		_showOnStart = ((BaseUnityPlugin)this).Config.Bind<bool>("General", "ShowOnStart", true, "Показывать окошко сразу при запуске.");
		_title = ((BaseUnityPlugin)this).Config.Bind<string>("Window", "Title", "Игрок 2", "Заголовок окошка.");
		_windowWidth = ((BaseUnityPlugin)this).Config.Bind<int>("Window", "Width", 360, "Ширина окошка в пикселях.");
		_windowX = ((BaseUnityPlugin)this).Config.Bind<int>("Window", "X", 20, "Позиция окошка по X.");
		_windowY = ((BaseUnityPlugin)this).Config.Bind<int>("Window", "Y", 20, "Позиция окошка по Y.");
		_captureWidth = ((BaseUnityPlugin)this).Config.Bind<int>("Capture", "Width", 640, "Ширина передаваемой картинки (выше = чётче, но тяжелее).");
		_fps = ((BaseUnityPlugin)this).Config.Bind<int>("Capture", "Fps", 12, "Сколько кадров в секунду передавать.");
		_jpgQuality = ((BaseUnityPlugin)this).Config.Bind<int>("Capture", "JpgQuality", 70, "Качество JPEG, 10-100.");
		_flipVertical = ((BaseUnityPlugin)this).Config.Bind<bool>("Capture", "FlipVertical", true, "Если картинка во втором окне получается вверх ногами - переключите это значение.");
		_dir = Path.Combine(Path.GetTempPath(), "RepoSecondScreenPip");
		_frameFile = Path.Combine(_dir, "frame.jpg");
		_tmpFile = Path.Combine(_dir, "frame.tmp");
		try
		{
			Directory.CreateDirectory(_dir);
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Temp dir: " + ex.Message));
		}
		bool createdNew = false;
		try
		{
			_mutex = new Mutex(initiallyOwned: true, "Local\\RepoSecondScreenPip_Host", out createdNew);
		}
		catch (Exception ex2)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Mutex: " + ex2.Message));
			createdNew = true;
		}
		switch (_role.Value)
		{
		case PipRole.Host:
			_isSender = false;
			break;
		case PipRole.SecondWindow:
			_isSender = true;
			break;
		default:
			_isSender = !createdNew;
			break;
		}
		Application.runInBackground = true;
		_show = _showOnStart.Value;
		_rect = new Rect((float)_windowX.Value, (float)_windowY.Value, (float)_windowWidth.Value, 100f);
		((BaseUnityPlugin)this).Logger.LogInfo((object)("Second Screen PiP loaded. Role: " + (_isSender ? "SecondWindow (sends screen)" : "Host (shows window)")));
		if (!_isSender)
		{
			return;
		}
		try
		{
			if (File.Exists(_frameFile))
			{
				File.Delete(_frameFile);
			}
		}
		catch
		{
		}
		((MonoBehaviour)this).StartCoroutine(CaptureLoop());
	}

	private void Update()
	{
		//IL_0013: Unknown result type (might be due to invalid IL or missing references)
		//IL_0034: 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_006d: Unknown result type (might be due to invalid IL or missing references)
		if (!Application.runInBackground)
		{
			Application.runInBackground = true;
		}
		if (Input.GetKeyDown(_switchKey.Value))
		{
			SwitchWindow();
		}
		if (!_isSender)
		{
			if (Input.GetKeyDown(_toggleKey.Value))
			{
				_show = !_show;
			}
			if (Input.GetKeyDown(_launchKey.Value))
			{
				LaunchSecondWindow();
			}
			if (Input.GetKeyDown(_cornerKey.Value))
			{
				NextCorner();
			}
			if (Time.unscaledTime - _fpsT >= 1f)
			{
				_recvFps = _recvFrames;
				_recvFrames = 0;
				_fpsT = Time.unscaledTime;
			}
			if (_show && Time.unscaledTime >= _nextRead)
			{
				_nextRead = Time.unscaledTime + 1f / (float)Mathf.Max(1, _fps.Value);
				TryLoadFrame();
			}
		}
	}

	[DllImport("user32.dll")]
	private static extern bool EnumWindows(EnumWindowsProc cb, IntPtr lParam);

	[DllImport("user32.dll")]
	private static extern bool IsWindowVisible(IntPtr hWnd);

	[DllImport("user32.dll")]
	private static extern bool IsIconic(IntPtr hWnd);

	[DllImport("user32.dll")]
	private static extern bool ShowWindow(IntPtr hWnd, int cmd);

	[DllImport("user32.dll")]
	private static extern bool SetForegroundWindow(IntPtr hWnd);

	[DllImport("user32.dll")]
	private static extern uint GetWindowThreadProcessId(IntPtr hWnd, out uint pid);

	[DllImport("user32.dll", CharSet = CharSet.Auto)]
	private static extern int GetClassName(IntPtr hWnd, StringBuilder name, int max);

	[DllImport("kernel32.dll")]
	private static extern uint GetCurrentProcessId();

	private void SwitchWindow()
	{
		try
		{
			uint me = GetCurrentProcessId();
			IntPtr target = IntPtr.Zero;
			EnumWindows(delegate(IntPtr h, IntPtr l)
			{
				if (!IsWindowVisible(h))
				{
					return true;
				}
				StringBuilder stringBuilder = new StringBuilder(64);
				GetClassName(h, stringBuilder, stringBuilder.Capacity);
				if (stringBuilder.ToString() != "UnityWndClass")
				{
					return true;
				}
				GetWindowThreadProcessId(h, out var pid);
				if (pid == me)
				{
					return true;
				}
				target = h;
				return false;
			}, IntPtr.Zero);
			if (target == IntPtr.Zero)
			{
				((BaseUnityPlugin)this).Logger.LogInfo((object)"Switch: другое окно игры не найдено.");
				return;
			}
			if (IsIconic(target))
			{
				ShowWindow(target, 9);
			}
			SetForegroundWindow(target);
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("Switch window failed: " + ex.Message));
		}
	}

	private void LaunchSecondWindow()
	{
		try
		{
			string[] commandLineArgs = Environment.GetCommandLineArgs();
			string text = commandLineArgs[0];
			if (!File.Exists(text))
			{
				text = Application.dataPath.Substring(0, Application.dataPath.Length - "_Data".Length) + ".exe";
			}
			StringBuilder stringBuilder = new StringBuilder();
			int num = 1;
			while (_passArgs.Value && num < commandLineArgs.Length)
			{
				if (stringBuilder.Length > 0)
				{
					stringBuilder.Append(' ');
				}
				stringBuilder.Append('"').Append(commandLineArgs[num].Replace("\"", "\\\"")).Append('"');
				num++;
			}
			Type type = Type.GetType("System.Diagnostics.ProcessStartInfo, System", throwOnError: false) ?? Type.GetType("System.Diagnostics.ProcessStartInfo, System.Diagnostics.Process", throwOnError: true);
			Type type2 = Type.GetType("System.Diagnostics.Process, System", throwOnError: false) ?? Type.GetType("System.Diagnostics.Process, System.Diagnostics.Process", throwOnError: true);
			object obj = Activator.CreateInstance(type, text, stringBuilder.ToString());
			type.GetProperty("WorkingDirectory").SetValue(obj, Path.GetDirectoryName(text), null);
			type.GetProperty("UseShellExecute").SetValue(obj, false, null);
			object value = type.GetProperty("EnvironmentVariables").GetValue(obj, null);
			Type type3 = value.GetType();
			ArrayList arrayList = new ArrayList((ICollection)type3.GetProperty("Keys").GetValue(value, null));
			MethodInfo method = type3.GetMethod("Remove", new Type[1] { typeof(string) });
			foreach (object item in arrayList)
			{
				string text2 = (string)item;
				if (text2.StartsWith("DOORSTOP", StringComparison.OrdinalIgnoreCase))
				{
					method.Invoke(value, new object[1] { text2 });
					((BaseUnityPlugin)this).Logger.LogInfo((object)("Launch: сброшена переменная " + text2));
				}
			}
			type2.GetMethod("Start", new Type[1] { type }).Invoke(null, new object[1] { obj });
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Launched second window: " + text + " " + stringBuilder));
		}
		catch (Exception ex)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)("Launch second window failed: " + ex.Message));
		}
	}

	private IEnumerator CaptureLoop()
	{
		WaitForEndOfFrame endOfFrame = new WaitForEndOfFrame();
		float next = 0f;
		while (true)
		{
			yield return endOfFrame;
			if (Time.unscaledTime < next)
			{
				continue;
			}
			next = Time.unscaledTime + 1f / (float)Mathf.Max(1, _fps.Value);
			try
			{
				CaptureFrame();
			}
			catch (Exception ex)
			{
				if (!_errorLogged)
				{
					_errorLogged = true;
					((BaseUnityPlugin)this).Logger.LogError((object)("Capture failed: " + ex));
				}
			}
		}
	}

	private void CaptureFrame()
	{
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		//IL_005b: Expected O, but got Unknown
		//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00da: Expected O, but got Unknown
		//IL_0104: Unknown result type (might be due to invalid IL or missing references)
		//IL_010e: Expected O, but got Unknown
		//IL_013c: Unknown result type (might be due to invalid IL or missing references)
		//IL_014b: Unknown result type (might be due to invalid IL or missing references)
		//IL_018e: Unknown result type (might be due to invalid IL or missing references)
		int width = Screen.width;
		int height = Screen.height;
		if (width < 16 || height < 16)
		{
			return;
		}
		if ((Object)(object)_full == (Object)null || ((Texture)_full).width != width || ((Texture)_full).height != height)
		{
			ReleaseRt(ref _full);
			_full = new RenderTexture(width, height, 0, (RenderTextureFormat)0);
			_full.Create();
		}
		int num = Mathf.Clamp(_captureWidth.Value, 160, 1920);
		int num2 = Mathf.Max(2, Mathf.RoundToInt((float)num * (float)height / (float)width));
		if ((Object)(object)_small == (Object)null || ((Texture)_small).width != num || ((Texture)_small).height != num2)
		{
			ReleaseRt(ref _small);
			_small = new RenderTexture(num, num2, 0, (RenderTextureFormat)0);
			_small.Create();
			if ((Object)(object)_readTex != (Object)null)
			{
				Object.Destroy((Object)(object)_readTex);
			}
			_readTex = new Texture2D(num, num2, (TextureFormat)3, false);
		}
		ScreenCapture.CaptureScreenshotIntoRenderTexture(_full);
		if (_flipVertical.Value)
		{
			Graphics.Blit((Texture)(object)_full, _small, new Vector2(1f, -1f), new Vector2(0f, 1f));
		}
		else
		{
			Graphics.Blit((Texture)(object)_full, _small);
		}
		RenderTexture active = RenderTexture.active;
		RenderTexture.active = _small;
		_readTex.ReadPixels(new Rect(0f, 0f, (float)num, (float)num2), 0, 0, false);
		RenderTexture.active = active;
		byte[] bytes = ImageConversion.EncodeToJPG(_readTex, Mathf.Clamp(_jpgQuality.Value, 10, 100));
		try
		{
			File.WriteAllBytes(_tmpFile, bytes);
			if (File.Exists(_frameFile))
			{
				File.Replace(_tmpFile, _frameFile, null);
			}
			else
			{
				File.Move(_tmpFile, _frameFile);
			}
		}
		catch (IOException)
		{
		}
	}

	private static void ReleaseRt(ref RenderTexture rt)
	{
		if (!((Object)(object)rt == (Object)null))
		{
			rt.Release();
			Object.Destroy((Object)(object)rt);
			rt = null;
		}
	}

	private void TryLoadFrame()
	{
		//IL_004d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0057: Expected O, but got Unknown
		try
		{
			if (!File.Exists(_frameFile))
			{
				return;
			}
			DateTime lastWriteTimeUtc = File.GetLastWriteTimeUtc(_frameFile);
			if (!(lastWriteTimeUtc == _lastWrite))
			{
				byte[] data = File.ReadAllBytes(_frameFile);
				if ((Object)(object)_tex == (Object)null)
				{
					_tex = new Texture2D(2, 2, (TextureFormat)3, false);
				}
				if (LoadJpg(_tex, data))
				{
					_lastWrite = lastWriteTimeUtc;
					_lastFrameTime = Time.unscaledTime;
					_recvFrames++;
				}
			}
		}
		catch (IOException)
		{
		}
		catch (Exception ex2)
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Read frame: " + ex2.Message));
		}
	}

	private static bool LoadJpg(Texture2D tex, byte[] data)
	{
		if (_loadImage == null)
		{
			_loadImage = typeof(ImageConversion).GetMethod("LoadImage", new Type[2]
			{
				typeof(Texture2D),
				typeof(byte[])
			});
			if (_loadImage == null)
			{
				throw new MissingMethodException("ImageConversion.LoadImage(Texture2D, byte[])");
			}
		}
		return (bool)_loadImage.Invoke(null, new object[2] { tex, data });
	}

	private void OnGUI()
	{
		//IL_0084: 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_00b3: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c4: Unknown result type (might be due to invalid IL or missing references)
		//IL_00d0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e5: Expected O, but got Unknown
		//IL_00e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e5: 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_0124: Unknown result type (might be due to invalid IL or missing references)
		//IL_012a: Invalid comparison between Unknown and I4
		if (!_isSender && _show)
		{
			float num = Mathf.Max(120f, ((Rect)(ref _rect)).width - 8f);
			float num2 = (((Object)(object)_tex != (Object)null && ((Texture)_tex).width > 0) ? ((float)((Texture)_tex).height / (float)((Texture)_tex).width) : 0.5625f);
			((Rect)(ref _rect)).height = 24f + num * num2 + 6f;
			Color color = GUI.color;
			GUI.color = new Color(1f, 1f, 1f, Mathf.Clamp(_opacity.Value, 0.3f, 1f));
			_rect = GUI.Window(6041089, _rect, new WindowFunction(DrawWindow), _title.Value);
			GUI.color = color;
			if (_resizeTo > 0f)
			{
				((Rect)(ref _rect)).width = _resizeTo;
				_resizeTo = -1f;
				SavePos();
			}
			if ((int)Event.current.rawType == 1 && ((int)((Rect)(ref _rect)).x != _windowX.Value || (int)((Rect)(ref _rect)).y != _windowY.Value))
			{
				SavePos();
			}
		}
	}

	private void DrawWindow(int id)
	{
		//IL_00a1: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00bd: 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_0282: Unknown result type (might be due to invalid IL or missing references)
		//IL_0161: Unknown result type (might be due to invalid IL or missing references)
		//IL_0193: Unknown result type (might be due to invalid IL or missing references)
		//IL_01bf: 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_00f0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fa: Expected O, but got Unknown
		//IL_01fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_022c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0232: Invalid comparison between Unknown and I4
		//IL_0242: Unknown result type (might be due to invalid IL or missing references)
		float num = Mathf.Max(120f, ((Rect)(ref _rect)).width - 8f);
		float num2 = (((Object)(object)_tex != (Object)null && ((Texture)_tex).width > 0) ? ((float)((Texture)_tex).height / (float)((Texture)_tex).width) : 0.5625f);
		Rect val = default(Rect);
		((Rect)(ref val))..ctor(4f, 22f, num, num * num2);
		bool flag = (Object)(object)_tex != (Object)null && Time.unscaledTime - _lastFrameTime < 2.5f;
		if ((Object)(object)_tex != (Object)null)
		{
			GUI.DrawTexture(val, (Texture)(object)_tex, (ScaleMode)0, false);
		}
		if (!flag)
		{
			GUI.Box(val, GUIContent.none);
			GUI.Label(val, "  Нет сигнала от 2-го окна.\n  Нажмите F2 или запустите вторую копию\n  (не сворачивайте её).");
		}
		else if (_showStatus.Value)
		{
			if (_statusStyle == null)
			{
				_statusStyle = new GUIStyle(GUI.skin.label);
				_statusStyle.fontSize = 11;
			}
			string text = "LIVE  " + _recvFps + " fps   [клик - переключить]";
			Rect val2 = default(Rect);
			((Rect)(ref val2))..ctor(((Rect)(ref val)).x + 6f, ((Rect)(ref val)).y + 3f, ((Rect)(ref val)).width - 8f, 18f);
			_statusStyle.normal.textColor = Color.black;
			GUI.Label(new Rect(((Rect)(ref val2)).x + 1f, ((Rect)(ref val2)).y + 1f, ((Rect)(ref val2)).width, ((Rect)(ref val2)).height), text, _statusStyle);
			_statusStyle.normal.textColor = new Color(0.4f, 1f, 0.5f);
			GUI.Label(val2, text, _statusStyle);
		}
		Event current = Event.current;
		if (((Rect)(ref val)).Contains(current.mousePosition))
		{
			if (_clickToSwitch.Value && (int)current.type == 0 && current.button == 0)
			{
				SwitchWindow();
				current.Use();
			}
			else if (_wheelResize.Value && (int)current.type == 6)
			{
				_resizeTo = Mathf.Clamp(((Rect)(ref _rect)).width - current.delta.y * 12f, 160f, 960f);
				current.Use();
			}
		}
		GUI.DragWindow(new Rect(0f, 0f, 10000f, 20f));
	}

	private void NextCorner()
	{
		_corner = (_corner + 1) % 4;
		float num = 20f;
		((Rect)(ref _rect)).x = ((_corner == 0 || _corner == 3) ? num : ((float)Screen.width - ((Rect)(ref _rect)).width - num));
		((Rect)(ref _rect)).y = ((_corner == 0 || _corner == 1) ? num : ((float)Screen.height - ((Rect)(ref _rect)).height - num));
		SavePos();
	}

	private void SavePos()
	{
		_windowX.Value = (int)((Rect)(ref _rect)).x;
		_windowY.Value = (int)((Rect)(ref _rect)).y;
		_windowWidth.Value = (int)((Rect)(ref _rect)).width;
	}

	private void OnDestroy()
	{
		if (!_isSender)
		{
			return;
		}
		try
		{
			if (File.Exists(_frameFile))
			{
				File.Delete(_frameFile);
			}
		}
		catch
		{
		}
	}

	private void OnApplicationQuit()
	{
		OnDestroy();
	}
}