Decompiled source of EngineerGaming v1.1.2

EngineerGaming/EngiGaming.dll

Decompiled 20 hours ago
using System;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using Microsoft.CodeAnalysis;
using RoR2;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;
using UnityEngine.Video;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("EngiGaming")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.1.1.0")]
[assembly: AssemblyInformationalVersion("1.1.1+2883ab40f2fa7677a3820c254d0b005b4fdf246f")]
[assembly: AssemblyProduct("EngiGaming")]
[assembly: AssemblyTitle("EngiGaming")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.1.1.0")]
[module: UnverifiableCode]
[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;
		}
	}
}
[BepInPlugin("com.hibiscus.engineergaming", "EngineerGaming", "1.1.1")]
public class EngiVideoPlugin : BaseUnityPlugin
{
	public const string PluginGuid = "com.hibiscus.engineergaming";

	public const string PluginName = "EngineerGaming";

	public const string PluginVersion = "1.1.1";

	private static readonly string[] NonGameplayScenes = new string[11]
	{
		"title", "splash", "intro", "outro", "lobby", "loadingbasic", "logbook", "crystalworld", "eclipseworld", "infinitetowerresultsscene",
		"empty"
	};

	private GameObject _canvasGO;

	private GameObject _videoGO;

	private VideoPlayer _videoPlayer;

	private AudioSource _audioSource;

	private RawImage _rawImage;

	private RenderTexture _rt;

	private bool _userWantsVideo;

	private bool _onLeft = true;

	private bool _hudReady;

	private float _nextPlaybackCheck;

	private ConfigEntry<KeyboardShortcut> _toggleKey;

	private ConfigEntry<KeyboardShortcut> _swapSideKey;

	private ConfigEntry<bool> _startEnabled;

	private ConfigEntry<bool> _showInMenus;

	private ConfigEntry<bool> _allCharacters;

	private bool _localIsEngi;

	private ConfigEntry<float> _heightPercent;

	private ConfigEntry<float> _margin;

	private ConfigEntry<float> _volume;

	private ConfigEntry<string> _fileName;

	private void Awake()
	{
		BindConfig();
		_userWantsVideo = _startEnabled.Value;
		CreateVideoHud();
		SceneManager.sceneLoaded += OnSceneLoaded;
		CharacterBody.onBodyStartGlobal += OnBodyStart;
		ApplyVisibility();
	}

	private void OnBodyStart(CharacterBody body)
	{
		//IL_0013: 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)
		if (body.isPlayerControlled && body.hasEffectiveAuthority)
		{
			_localIsEngi = body.bodyIndex == BodyCatalog.FindBodyIndex("EngiBody");
			ApplyVisibility();
		}
	}

	private void BindConfig()
	{
		//IL_001b: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: 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_012e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0138: Expected O, but got Unknown
		//IL_016c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0176: Expected O, but got Unknown
		_toggleKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Controls", "ToggleKey", new KeyboardShortcut((KeyCode)288, Array.Empty<KeyCode>()), "Show/hide the video overlay.");
		_swapSideKey = ((BaseUnityPlugin)this).Config.Bind<KeyboardShortcut>("Controls", "SwapSideKey", new KeyboardShortcut((KeyCode)289, Array.Empty<KeyCode>()), "Move the overlay between the left and right edge of the screen.");
		_startEnabled = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "StartEnabled", true, "Show the overlay automatically when a stage starts, without pressing the toggle key.");
		_showInMenus = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "ShowInMenus", false, "Also show the overlay in the main menu and other non-gameplay scenes.");
		_allCharacters = ((BaseUnityPlugin)this).Config.Bind<bool>("Display", "AllCharacters", false, "Show the overlay during a run for every survivor, not only for Engineer.");
		_heightPercent = ((BaseUnityPlugin)this).Config.Bind<float>("Display", "HeightPercent", 55f, new ConfigDescription("Overlay height as a percentage of the screen height. Width follows the video's own aspect ratio.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(10f, 100f), Array.Empty<object>()));
		_margin = ((BaseUnityPlugin)this).Config.Bind<float>("Display", "Margin", 20f, new ConfigDescription("Distance in pixels between the overlay and the screen edge.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 500f), Array.Empty<object>()));
		_volume = ((BaseUnityPlugin)this).Config.Bind<float>("Audio", "Volume", 0.5f, new ConfigDescription("Volume of the video's audio track.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 1f), Array.Empty<object>()));
		_fileName = ((BaseUnityPlugin)this).Config.Bind<string>("Video", "FileName", "video.mp4", "Name of the video file inside the mod folder. If it is missing, the first video file found in that folder is used.");
	}

	private string ResolveVideoPath()
	{
		string directoryName = Path.GetDirectoryName(((BaseUnityPlugin)this).Info.Location);
		if (string.IsNullOrEmpty(directoryName))
		{
			return null;
		}
		string text = Path.Combine(directoryName, _fileName.Value);
		if (File.Exists(text))
		{
			return text;
		}
		string[] array = new string[4] { "*.mp4", "*.webm", "*.mov", "*.m4v" };
		foreach (string searchPattern in array)
		{
			string[] files = Directory.GetFiles(directoryName, searchPattern);
			if (files.Length != 0)
			{
				((BaseUnityPlugin)this).Logger.LogWarning((object)(_fileName.Value + " not found, falling back to " + Path.GetFileName(files[0]) + "."));
				return files[0];
			}
		}
		((BaseUnityPlugin)this).Logger.LogError((object)("No video file found in " + directoryName + ". Put a video named " + _fileName.Value + " there."));
		return null;
	}

	private void CreateVideoHud()
	{
		//IL_0011: Unknown result type (might be due to invalid IL or missing references)
		//IL_001b: Expected O, but got Unknown
		//IL_0047: Unknown result type (might be due to invalid IL or missing references)
		//IL_004d: Expected O, but got Unknown
		//IL_0076: Unknown result type (might be due to invalid IL or missing references)
		//IL_0092: Unknown result type (might be due to invalid IL or missing references)
		//IL_009c: Expected O, but got Unknown
		//IL_0198: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a2: Expected O, but got Unknown
		//IL_01af: Unknown result type (might be due to invalid IL or missing references)
		//IL_01b9: Expected O, but got Unknown
		string text = ResolveVideoPath();
		if (text != null)
		{
			_canvasGO = new GameObject("EngineerGamingCanvas");
			Object.DontDestroyOnLoad((Object)(object)_canvasGO);
			Canvas obj = _canvasGO.AddComponent<Canvas>();
			obj.renderMode = (RenderMode)0;
			obj.sortingOrder = 9999;
			GameObject val = new GameObject("VideoRaw");
			val.transform.SetParent(_canvasGO.transform, false);
			_rawImage = val.AddComponent<RawImage>();
			((Graphic)_rawImage).color = Color.white;
			((Graphic)_rawImage).raycastTarget = false;
			_videoGO = new GameObject("VideoPlayer");
			_videoGO.transform.SetParent(_canvasGO.transform, false);
			_videoGO.SetActive(false);
			_audioSource = _videoGO.AddComponent<AudioSource>();
			_audioSource.playOnAwake = false;
			_audioSource.spatialBlend = 0f;
			_audioSource.volume = _volume.Value;
			_videoPlayer = _videoGO.AddComponent<VideoPlayer>();
			_videoPlayer.playOnAwake = false;
			_videoPlayer.isLooping = true;
			_videoPlayer.waitForFirstFrame = true;
			_videoPlayer.source = (VideoSource)1;
			_videoPlayer.url = text;
			_videoPlayer.renderMode = (VideoRenderMode)2;
			_videoPlayer.audioOutputMode = (VideoAudioOutputMode)1;
			_videoPlayer.SetTargetAudioSource((ushort)0, _audioSource);
			_videoPlayer.EnableAudioTrack((ushort)0, true);
			_videoPlayer.prepareCompleted += new EventHandler(OnVideoPrepared);
			_videoPlayer.errorReceived += new ErrorEventHandler(OnVideoError);
			_videoGO.SetActive(true);
			EnsureRenderTexture(360, 640);
			UpdateVideoPosition();
			_hudReady = true;
			_canvasGO.SetActive(false);
			((BaseUnityPlugin)this).Logger.LogInfo((object)("Video overlay ready (" + Path.GetFileName(text) + ")."));
		}
	}

	private void EnsureRenderTexture(int width, int height)
	{
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		//IL_004a: Expected O, but got Unknown
		if (width > 0 && height > 0 && (!((Object)(object)_rt != (Object)null) || ((Texture)_rt).width != width || ((Texture)_rt).height != height))
		{
			RenderTexture rt = _rt;
			_rt = new RenderTexture(width, height, 0, (RenderTextureFormat)7);
			_rt.Create();
			if ((Object)(object)_videoPlayer != (Object)null)
			{
				_videoPlayer.targetTexture = _rt;
			}
			if ((Object)(object)_rawImage != (Object)null)
			{
				_rawImage.texture = (Texture)(object)_rt;
			}
			if ((Object)(object)rt != (Object)null)
			{
				rt.Release();
				Object.Destroy((Object)(object)rt);
			}
		}
	}

	private void OnVideoPrepared(VideoPlayer vp)
	{
		int width = (int)vp.width;
		int height = (int)vp.height;
		if (width > 0 && height > 0)
		{
			EnsureRenderTexture(width, height);
		}
		ResizeOverlay();
		if ((Object)(object)_canvasGO != (Object)null && _canvasGO.activeSelf && !vp.isPlaying)
		{
			vp.Play();
		}
	}

	private void OnVideoError(VideoPlayer vp, string message)
	{
		((BaseUnityPlugin)this).Logger.LogError((object)("VideoPlayer error: " + message));
	}

	private void ResizeOverlay()
	{
		//IL_0073: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)_rawImage == (Object)null))
		{
			float num = 0.5625f;
			if ((Object)(object)_rt != (Object)null && ((Texture)_rt).height > 0)
			{
				num = (float)((Texture)_rt).width / (float)((Texture)_rt).height;
			}
			float num2 = (float)Screen.height * (_heightPercent.Value / 100f);
			((Graphic)_rawImage).rectTransform.sizeDelta = new Vector2(num2 * num, num2);
		}
	}

	private static bool IsGameplayScene(Scene scene)
	{
		//IL_0000: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Invalid comparison between Unknown and I4
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0036: Invalid comparison between Unknown and I4
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_003f: Invalid comparison between Unknown and I4
		//IL_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Invalid comparison between Unknown and I4
		try
		{
			SceneDef val = SceneCatalog.GetSceneDefFromScene(scene);
			if ((Object)(object)val == (Object)null)
			{
				val = SceneCatalog.FindSceneDef(((Scene)(ref scene)).name);
			}
			if ((Object)(object)val != (Object)null)
			{
				return (int)val.sceneType == 1 || (int)val.sceneType == 5 || (int)val.sceneType == 2 || (int)val.sceneType == 4;
			}
		}
		catch (Exception)
		{
		}
		string name = ((Scene)(ref scene)).name;
		if (string.IsNullOrEmpty(name))
		{
			return false;
		}
		string[] nonGameplayScenes = NonGameplayScenes;
		foreach (string value in nonGameplayScenes)
		{
			if (name.Equals(value, StringComparison.OrdinalIgnoreCase))
			{
				return false;
			}
		}
		return true;
	}

	private void OnSceneLoaded(Scene scene, LoadSceneMode mode)
	{
		//IL_0016: Unknown result type (might be due to invalid IL or missing references)
		if (!_hudReady)
		{
			CreateVideoHud();
		}
		_localIsEngi = false;
		ApplyVisibility(scene);
	}

	private void ApplyVisibility()
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		ApplyVisibility(SceneManager.GetActiveScene());
	}

	private void ApplyVisibility(Scene scene)
	{
		//IL_0017: Unknown result type (might be due to invalid IL or missing references)
		if (!_hudReady || (Object)(object)_canvasGO == (Object)null)
		{
			return;
		}
		bool flag = ((!IsGameplayScene(scene)) ? _showInMenus.Value : (_allCharacters.Value || _localIsEngi));
		bool flag2 = _userWantsVideo && flag;
		if (_canvasGO.activeSelf != flag2)
		{
			_canvasGO.SetActive(flag2);
		}
		if ((Object)(object)_videoPlayer == (Object)null)
		{
			return;
		}
		if (flag2)
		{
			ResizeOverlay();
			if ((Object)(object)_audioSource != (Object)null)
			{
				_audioSource.volume = _volume.Value;
			}
			if (!_videoPlayer.isPrepared)
			{
				_videoPlayer.Prepare();
			}
			else if (!_videoPlayer.isPlaying)
			{
				_videoPlayer.Play();
			}
		}
		else if (_videoPlayer.isPlaying)
		{
			_videoPlayer.Pause();
		}
	}

	private void Update()
	{
		//IL_000f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0014: Unknown result type (might be due to invalid IL or missing references)
		//IL_0067: Unknown result type (might be due to invalid IL or missing references)
		//IL_006c: Unknown result type (might be due to invalid IL or missing references)
		if (_hudReady)
		{
			KeyboardShortcut value = _toggleKey.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				_userWantsVideo = !_userWantsVideo;
				ApplyVisibility();
				((BaseUnityPlugin)this).Logger.LogInfo((object)("Video overlay " + (_userWantsVideo ? "enabled" : "disabled") + "."));
			}
			value = _swapSideKey.Value;
			if (((KeyboardShortcut)(ref value)).IsDown())
			{
				_onLeft = !_onLeft;
				UpdateVideoPosition();
			}
			KeepPlayingWhileVisible();
		}
	}

	private void KeepPlayingWhileVisible()
	{
		if (!((Object)(object)_canvasGO == (Object)null) && _canvasGO.activeSelf && !((Object)(object)_videoPlayer == (Object)null) && !_videoPlayer.isPlaying && !(Time.unscaledTime < _nextPlaybackCheck))
		{
			_nextPlaybackCheck = Time.unscaledTime + 1f;
			if (_videoPlayer.isPrepared)
			{
				_videoPlayer.Play();
			}
			else
			{
				_videoPlayer.Prepare();
			}
		}
	}

	private void UpdateVideoPosition()
	{
		//IL_0058: Unknown result type (might be due to invalid IL or missing references)
		//IL_0069: Unknown result type (might be due to invalid IL or missing references)
		//IL_007a: Unknown result type (might be due to invalid IL or missing references)
		//IL_008a: Unknown result type (might be due to invalid IL or missing references)
		if (!((Object)(object)_rawImage == (Object)null))
		{
			RectTransform rectTransform = ((Graphic)_rawImage).rectTransform;
			float num = (_onLeft ? 0f : 1f);
			float num2 = (_onLeft ? _margin.Value : (0f - _margin.Value));
			rectTransform.anchorMin = new Vector2(num, 0.5f);
			rectTransform.anchorMax = new Vector2(num, 0.5f);
			rectTransform.pivot = new Vector2(num, 0.5f);
			rectTransform.anchoredPosition = new Vector2(num2, 0f);
		}
	}

	private void OnDestroy()
	{
		//IL_003d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0047: Expected O, but got Unknown
		//IL_0054: Unknown result type (might be due to invalid IL or missing references)
		//IL_005e: Expected O, but got Unknown
		SceneManager.sceneLoaded -= OnSceneLoaded;
		CharacterBody.onBodyStartGlobal -= OnBodyStart;
		if ((Object)(object)_videoPlayer != (Object)null)
		{
			_videoPlayer.prepareCompleted -= new EventHandler(OnVideoPrepared);
			_videoPlayer.errorReceived -= new ErrorEventHandler(OnVideoError);
		}
		if ((Object)(object)_rt != (Object)null)
		{
			_rt.Release();
			Object.Destroy((Object)(object)_rt);
			_rt = null;
		}
	}
}