using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using ExitGames.Client.Photon; using HarmonyLib; using Microsoft.Win32.SafeHandles; using Photon.Pun; using Photon.Realtime; using Steamworks; using Steamworks.Data; using Unity.Collections; using UnityEngine; using UnityEngine.Experimental.Rendering; using UnityEngine.InputSystem; using UnityEngine.InputSystem.Controls; using UnityEngine.InputSystem.Layouts; using UnityEngine.InputSystem.Utilities; using UnityEngine.Networking; using UnityEngine.Rendering; using UnityEngine.UI; [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("REPOPS1")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.1.0.0")] [assembly: AssemblyInformationalVersion("0.1.0")] [assembly: AssemblyProduct("REPOPS1")] [assembly: AssemblyTitle("REPOPS1")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.1.0.0")] [module: UnverifiableCode] namespace REPOPS1; internal static class CoverDownload { private static readonly HashSet Tried = new HashSet(StringComparer.OrdinalIgnoreCase); private static readonly Queue<(GameEntry game, Action done)> Waiting = new Queue<(GameEntry, Action)>(); private static readonly Dictionary> Index = new Dictionary>(); private static bool _busy; public static void Want(GameEntry game, Action done) { if (REPOPS1Plugin.DownloadCovers.Value && game != null && Tried.Add(game.Path)) { Waiting.Enqueue((game, done)); Next(); } } private static void Next() { while (!_busy && Waiting.Count > 0) { (GameEntry, Action) tuple = Waiting.Dequeue(); GameEntry game = tuple.Item1; Action done = tuple.Item2; string system = SystemFor(game); if (system == null) { continue; } string name = Path.GetFileNameWithoutExtension(game.Path); _busy = true; Fetch(PictureUrl(system, name), delegate(byte[] data) { if (data != null) { Save(game, name, data, name, done); Finish(); } else { WithIndex(system, delegate(List list) { string match = ((list != null) ? BestMatch(name, list) : null); if (match == null) { REPOPS1Plugin.Log.LogInfo((object)("No cover in the library for \"" + name + "\".")); Finish(); } else { Fetch(PictureUrl(system, match), delegate(byte[] found) { if (found != null) { Save(game, name, found, match, done); } else { REPOPS1Plugin.Log.LogInfo((object)("Cover \"" + match + "\" for \"" + name + "\" could not be fetched.")); } Finish(); }); } }); } }); } } private static void Finish() { _busy = false; Next(); } private static void Save(GameEntry game, string name, byte[] data, string libraryName, Action done) { try { string text = GameShelf.CoversFolder(game.Path); Directory.CreateDirectory(text); File.WriteAllBytes(Path.Combine(text, name + ".png"), data); REPOPS1Plugin.Log.LogInfo((object)((libraryName == name) ? ("Cover saved: " + name + ".png") : ("Cover saved: " + name + ".png (the library's \"" + libraryName + "\")"))); done?.Invoke(); } catch (Exception ex) { REPOPS1Plugin.Log.LogWarning((object)("Cover for \"" + name + "\": " + ex.Message)); } } private static string PictureUrl(string system, string name) { return "https://thumbnails.libretro.com/" + Uri.EscapeDataString(system) + "/Named_Boxarts/" + Uri.EscapeDataString(Regex.Replace(name, "[&*/:`<>?\\\\|\"]", "_")) + ".png"; } private static void Fetch(string url, Action then) { UnityWebRequest req = UnityWebRequest.Get(url); req.timeout = 30; ((AsyncOperation)req.SendWebRequest()).completed += delegate { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Invalid comparison between Unknown and I4 byte[] obj = null; try { if ((int)req.result == 1 && req.downloadHandler.data.Length > 1000) { obj = req.downloadHandler.data; } } catch (Exception) { } finally { req.Dispose(); } then(obj); }; } private static void WithIndex(string system, Action> then) { if (Index.TryGetValue(system, out var value)) { then(value); return; } UnityWebRequest req = UnityWebRequest.Get("https://thumbnails.libretro.com/" + Uri.EscapeDataString(system) + "/Named_Boxarts/"); req.timeout = 60; ((AsyncOperation)req.SendWebRequest()).completed += delegate { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Invalid comparison between Unknown and I4 List list = null; try { if ((int)req.result == 1) { list = new List(); foreach (Match item in Regex.Matches(req.downloadHandler.text, "href=\"([^\"]+)\\.png\"")) { list.Add(Uri.UnescapeDataString(item.Groups[1].Value)); } REPOPS1Plugin.Log.LogInfo((object)$"Cover library for {system}: {list.Count} pictures."); } } catch (Exception ex) { REPOPS1Plugin.Log.LogWarning((object)("Cover library list: " + ex.Message)); } finally { req.Dispose(); } Index[system] = list; then(list); }; } private static string BestMatch(string fileName, List library) { string text = Normalize(fileName); if (text.Length == 0) { return null; } HashSet hashSet = Tags(fileName); string result = null; int num = int.MaxValue; foreach (string item in library) { if (Normalize(item) != text) { continue; } HashSet hashSet2 = Tags(item); int num2 = 50; foreach (string item2 in hashSet) { if (hashSet2.Contains(item2)) { num2 -= 20; } } if (hashSet2.Contains("usa")) { num2 -= 8; } else if (hashSet2.Contains("world")) { num2 -= 6; } else if (hashSet2.Contains("europe")) { num2 -= 4; } else if (hashSet2.Contains("japan")) { num2 -= 2; } num2 += hashSet2.Count; if (num2 < num) { num = num2; result = item; } } return result; } private static string Normalize(string name) { string text = Regex.Replace(name ?? "", "\\([^)]*\\)|\\[[^\\]]*\\]", " "); StringBuilder stringBuilder = new StringBuilder(); string text2 = text.ToLowerInvariant(); foreach (char c in text2) { stringBuilder.Append(char.IsLetterOrDigit(c) ? c : ' '); } return Regex.Replace(stringBuilder.ToString(), "\\s+", " ").Trim(); } private static HashSet Tags(string name) { HashSet hashSet = new HashSet(StringComparer.OrdinalIgnoreCase); foreach (Match item in Regex.Matches(name ?? "", "\\(([^)]*)\\)")) { string[] array = item.Groups[1].Value.Split(','); foreach (string text in array) { if (text.Trim().Length > 0) { hashSet.Add(text.Trim().ToLowerInvariant()); } } } return hashSet; } private static string SystemFor(GameEntry game) { string fileName = Path.GetFileName(Path.GetDirectoryName(game.CorePath) ?? ""); string[] array = (REPOPS1Plugin.CoverSystems.Value ?? "").Split(';'); foreach (string text in array) { int num = text.IndexOf('='); if (num > 0 && text.Substring(0, num).Trim().Equals(fileName, StringComparison.OrdinalIgnoreCase)) { return text.Substring(num + 1).Trim(); } } return null; } } internal static class D3D11Host { [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int QueryInterfaceFn(IntPtr self, ref Guid iid, out IntPtr obj); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate uint ReleaseFn(IntPtr self); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void GetDeviceFn(IntPtr self, out IntPtr device); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int GetFeatureLevelFn(IntPtr self); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void GetImmediateContextFn(IntPtr self, out IntPtr context); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private unsafe delegate int CreateDeviceContextStateFn(IntPtr self, uint flags, int* levels, uint count, uint sdk, ref Guid emulated, int* chosen, out IntPtr state); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void SwapDeviceContextStateFn(IntPtr self, IntPtr state, out IntPtr previous); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void GetResourceFn(IntPtr self, out IntPtr resource); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private unsafe delegate void PSGetShaderResourcesFn(IntPtr ctx, uint start, uint count, IntPtr* views); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private unsafe delegate void OMGetRenderTargetsFn(IntPtr ctx, uint count, IntPtr* views, IntPtr depth); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void Tex2DGetDescFn(IntPtr self, out Texture2DDesc desc); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void CopySubresourceRegionFn(IntPtr ctx, IntPtr dst, uint dstSub, uint x, uint y, uint z, IntPtr src, uint srcSub, ref Box box); private struct Texture2DDesc { public uint Width; public uint Height; public uint MipLevels; public uint ArraySize; public uint Format; public uint SampleCount; public uint SampleQuality; public uint Usage; public uint BindFlags; public uint CpuAccess; public uint Misc; } private struct Box { public uint Left; public uint Top; public uint Front; public uint Right; public uint Bottom; public uint Back; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void RenderEventFn(int eventId); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int FeatureLevelFn(IntPtr self); public const uint ContextDirect3D = 7u; private const int InterfaceD3D11 = 3; private const uint D3D11SdkVersion = 7u; private static readonly Guid IidDevice1 = new Guid("a04bfb29-08ef-43d6-a49c-a9bdbdcbe686"); private static readonly Guid IidContext1 = new Guid("bb2c6faa-b5fb-4082-8e6b-388b8cfa90e1"); private static IntPtr _device; private static IntPtr _context; private static IntPtr _device1; private static IntPtr _context1; private static IntPtr _coreState; private static IntPtr _compile; private static int _featureLevel; private static bool _tried; private static bool _warnedState; private static volatile bool _loggedFrame; private static int _calls; private static int _shownCalls; private static RenderEventFn _renderEvent; private static IntPtr _renderEventPtr; private const int EvRun = 1; private const int EvShutdown = 2; private const int EvCapture = 3; private static LibretroCore _core; private static volatile int _runs; private static volatile bool _resetPending; private static volatile bool _shutdownDone; private static readonly ConcurrentQueue> Jobs = new ConcurrentQueue>(); private static FeatureLevelFn _level110; private static IntPtr _originalLevelFn; private static IntPtr _dst; private static volatile int _dstW; private static volatile int _dstH; private static volatile int _wantW; private static volatile int _wantH; private static volatile uint _wantFormat; private static volatile int _copied; private static Texture2D _tex; private static int _seenCopies; public static bool Available { get; private set; } public static IntPtr Interface { get; private set; } internal static IntPtr Device => _device; public static bool ShutdownDone => _shutdownDone; private static IntPtr Slot(IntPtr com, int index) { return Marshal.ReadIntPtr(Marshal.ReadIntPtr(com), index * IntPtr.Size); } private static T Call(IntPtr com, int slot) where T : Delegate { return Marshal.GetDelegateForFunctionPointer(Slot(com, slot)); } private static void Release(IntPtr com) { if (com != IntPtr.Zero) { Call(com, 2)(com); } } public static bool Init() { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Invalid comparison between Unknown and I4 //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Expected O, but got Unknown //IL_0025: Unknown result type (might be due to invalid IL or missing references) if (_tried) { return Available; } _tried = true; try { if ((int)SystemInfo.graphicsDeviceType != 2) { REPOPS1Plugin.Log.LogWarning((object)$"GPU rendering needs Direct3D 11; the game runs on {SystemInfo.graphicsDeviceType}. Using software."); return false; } Texture2D val = new Texture2D(4, 4, (TextureFormat)4, false); val.Apply(false); IntPtr nativeTexturePtr = ((Texture)val).GetNativeTexturePtr(); Call(nativeTexturePtr, 3)(nativeTexturePtr, out _device); Object.Destroy((Object)val); if (_device == IntPtr.Zero) { return false; } Call(_device, 40)(_device, out _context); _featureLevel = Call(_device, 37)(_device); Guid iid = IidDevice1; if (Call(_device, 0)(_device, ref iid, out _device1) < 0) { REPOPS1Plugin.Log.LogWarning((object)"No ID3D11Device1: using software."); return false; } iid = IidContext1; if (Call(_context, 0)(_context, ref iid, out _context1) < 0) { REPOPS1Plugin.Log.LogWarning((object)"No ID3D11DeviceContext1: using software."); return false; } IntPtr intPtr = Kernel32.LoadLibraryW("d3dcompiler_47.dll"); _compile = ((intPtr != IntPtr.Zero) ? Kernel32.GetProcAddress(intPtr, "D3DCompile") : IntPtr.Zero); Interface = Marshal.AllocHGlobal(48); Marshal.WriteInt32(Interface, 0, 3); Marshal.WriteInt32(Interface, 4, 1); Marshal.WriteIntPtr(Interface, 8, IntPtr.Zero); Marshal.WriteIntPtr(Interface, 16, _device); Marshal.WriteIntPtr(Interface, 24, _context); Marshal.WriteInt32(Interface, 32, _featureLevel); Marshal.WriteIntPtr(Interface, 40, _compile); _renderEvent = OnRenderEvent; _renderEventPtr = Marshal.GetFunctionPointerForDelegate(_renderEvent); Available = true; REPOPS1Plugin.Log.LogInfo((object)$"GPU rendering ready (D3D11, feature level 0x{_featureLevel:X})."); } catch (Exception ex) { REPOPS1Plugin.Log.LogError((object)("GPU rendering unavailable: " + ex.Message)); Available = false; } return Available; } public static void IssueCapture() { if (Init()) { GL.IssuePluginEvent(_renderEventPtr, 3); } } public static void Enqueue(Action job) { Jobs.Enqueue(job); if (_core != null) { GL.IssuePluginEvent(_renderEventPtr, 1); } } private static int Level110(IntPtr self) { return 45056; } private static void PatchFeatureLevel(bool on) { if (_device == IntPtr.Zero || (!REPOPS1Plugin.D3D11Level110.Value && on)) { return; } try { IntPtr intPtr = Marshal.ReadIntPtr(_device) + 37 * IntPtr.Size; if (on && _originalLevelFn == IntPtr.Zero) { if (_level110 == null) { _level110 = Level110; } _originalLevelFn = Marshal.ReadIntPtr(intPtr); WriteSlot(intPtr, Marshal.GetFunctionPointerForDelegate(_level110)); Marshal.WriteInt32(Interface, 32, 45056); } else if (!on && _originalLevelFn != IntPtr.Zero) { WriteSlot(intPtr, _originalLevelFn); _originalLevelFn = IntPtr.Zero; Marshal.WriteInt32(Interface, 32, _featureLevel); } } catch (Exception ex) { REPOPS1Plugin.Log.LogWarning((object)("Feature level switch failed: " + ex.Message)); } } private static void WriteSlot(IntPtr slot, IntPtr fn) { if (!Kernel32.VirtualProtect(slot, (UIntPtr)(ulong)IntPtr.Size, 4u, out var oldProtect)) { throw new InvalidOperationException("VirtualProtect failed"); } Marshal.WriteIntPtr(slot, fn); Kernel32.VirtualProtect(slot, (UIntPtr)(ulong)IntPtr.Size, oldProtect, out var _); } public static void BeforeLoad() { PatchFeatureLevel(on: true); } public static void AfterCore() { PatchFeatureLevel(on: false); } public static void Begin(LibretroCore core) { _loggedFrame = false; _calls = (_shownCalls = 0); _core = core; _resetPending = true; _shutdownDone = false; } public static void Run(int frames) { if (_core != null && (frames > 0 || _resetPending || !Jobs.IsEmpty)) { _runs = frames; GL.IssuePluginEvent(_renderEventPtr, 1); } } public static void Shutdown() { if (_core == null) { _shutdownDone = true; } else { GL.IssuePluginEvent(_renderEventPtr, 2); } } private unsafe static void OnRenderEvent(int id) { if (id == 3) { try { WindowCapture.RenderTick(); return; } catch (Exception ex) { REPOPS1Plugin.Log.LogError((object)("Window capture failed: " + ex.Message)); return; } } LibretroCore core = _core; if (core == null) { return; } IntPtr previous = IntPtr.Zero; try { if (_coreState == IntPtr.Zero) { int featureLevel = _featureLevel; Guid emulated = IidDevice1; CreateDeviceContextStateFn createDeviceContextStateFn = Call(_device1, 47); int num = default(int); if (createDeviceContextStateFn(_device1, 0u, &featureLevel, 1u, 7u, ref emulated, &num, out _coreState) < 0 || _coreState == IntPtr.Zero) { createDeviceContextStateFn(_device1, 1u, &featureLevel, 1u, 7u, ref emulated, &num, out _coreState); } if (_coreState == IntPtr.Zero && !_warnedState) { _warnedState = true; REPOPS1Plugin.Log.LogWarning((object)"No separate GPU state for the core: R.E.P.O's picture may glitch. Set Video/Renderer = Software if it does."); } } if (_coreState != IntPtr.Zero) { Call(_context1, 131)(_context1, _coreState, out previous); } if (id == 2) { Action result; while (Jobs.TryDequeue(out result)) { try { result(core); } catch (Exception) { } } core.ShutdownOnRenderThread(); _core = null; _shutdownDone = true; return; } if (_resetPending) { _resetPending = false; core.ContextReset(); } Action result2; while (Jobs.TryDequeue(out result2)) { try { result2(core); } catch (Exception ex3) { REPOPS1Plugin.Log.LogError((object)("Core job failed: " + ex3.Message)); } } for (int i = 0; i < _runs; i++) { core.Run(); } _runs = 0; } catch (Exception ex4) { REPOPS1Plugin.Log.LogError((object)("GPU frame failed: " + ex4.Message)); } finally { if (previous != IntPtr.Zero) { Call(_context1, 131)(_context1, previous, out var previous2); Release(previous2); Release(previous); } } } public unsafe static void OnFrame(IntPtr srv, int width, int height) { bool flag = srv == IntPtr.Zero || width <= 0; if (_calls < 3 || (!flag && _shownCalls < 3)) { _calls++; if (!flag) { _shownCalls++; } REPOPS1Plugin.Log.LogInfo((object)$"GPU video callback #{_calls}: data 0x{srv.ToInt64():X}, {width}x{height}."); } if (srv == IntPtr.Zero || width <= 0 || height <= 0) { return; } IntPtr resource; if (srv == new IntPtr(-1)) { IntPtr* ptr = stackalloc IntPtr[1]; *ptr = IntPtr.Zero; Call(_context, 73)(_context, 0u, 1u, ptr); if (*ptr == IntPtr.Zero) { Call(_context, 89)(_context, 1u, ptr, IntPtr.Zero); } if (*ptr == IntPtr.Zero) { if (!_loggedFrame) { _loggedFrame = true; REPOPS1Plugin.Log.LogWarning((object)"GPU frame: \"ready\" signal but nothing bound to read it from."); } return; } Call(*ptr, 7)(*ptr, out resource); Release(*ptr); } else { Call(srv, 7)(srv, out resource); } if (resource == IntPtr.Zero) { return; } try { Call(resource, 10)(resource, out var desc); if (_loggedFrame && (width != _wantW || height != _wantH)) { REPOPS1Plugin.Log.LogInfo((object)$"GPU frame size now {width}x{height}."); } _wantW = width; _wantH = height; _wantFormat = desc.Format; if (!_loggedFrame) { _loggedFrame = true; REPOPS1Plugin.Log.LogInfo((object)$"GPU frame: {width}x{height} shown of a {desc.Width}x{desc.Height} texture, DXGI format {desc.Format}, {desc.SampleCount} sample(s)."); } IntPtr dst = _dst; if (!(dst == IntPtr.Zero) && _dstW == width && _dstH == height) { Box box = new Box { Left = 0u, Top = 0u, Front = 0u, Right = (uint)Math.Min(width, (int)desc.Width), Bottom = (uint)Math.Min(height, (int)desc.Height), Back = 1u }; Call(_context, 46)(_context, dst, 0u, 0u, 0u, 0u, resource, 0u, ref box); _copied++; } } finally { Release(resource); } } internal static void CopyIn(IntPtr tex, int x, int y, int width, int height) { Call(tex, 10)(tex, out var desc); width = Math.Min(width, (int)desc.Width - x); height = Math.Min(height, (int)desc.Height - y); if (width > 0 && height > 0) { if (!_loggedFrame) { _loggedFrame = true; REPOPS1Plugin.Log.LogInfo((object)$"Captured frame: {width}x{height} of a {desc.Width}x{desc.Height} window picture, DXGI format {desc.Format}."); } _wantW = width; _wantH = height; _wantFormat = desc.Format; IntPtr dst = _dst; if (!(dst == IntPtr.Zero) && _dstW == width && _dstH == height) { Box box = new Box { Left = (uint)x, Top = (uint)y, Front = 0u, Right = (uint)(x + width), Bottom = (uint)(y + height), Back = 1u }; Call(_context, 46)(_context, dst, 0u, 0u, 0u, 0u, tex, 0u, ref box); _copied++; } } } public static void ResetFrameLog() { _loggedFrame = false; } public static bool UpdateTexture(ref Texture2D texture) { //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: 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_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_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Expected O, but got Unknown //IL_00c8: Expected O, but got Unknown int wantW = _wantW; int wantH = _wantH; if (wantW > 0 && wantH > 0 && ((Object)(object)_tex == (Object)null || ((Texture)_tex).width != wantW || ((Texture)_tex).height != wantH || (Object)(object)_tex != (Object)(object)texture)) { TextureFormat val = (TextureFormat)((_wantFormat == 87 || _wantFormat == 91) ? 14 : 4); if ((Object)(object)_tex != (Object)null && (Object)(object)_tex != (Object)(object)texture) { Object.Destroy((Object)(object)_tex); } if ((Object)(object)texture != (Object)null) { Object.Destroy((Object)(object)texture); } Texture2D val2 = new Texture2D(wantW, wantH, val, false) { name = "REPOPS1 Screen (GPU)", wrapMode = (TextureWrapMode)1 }; Texture2D tex = val2; texture = val2; _tex = tex; texture.Apply(false, true); _dst = ((Texture)texture).GetNativeTexturePtr(); _dstW = wantW; _dstH = wantH; } int copied = _copied; if (copied == _seenCopies) { return false; } _seenCopies = copied; return true; } public static void ForgetTexture() { _dst = IntPtr.Zero; _dstW = (_dstH = 0); _wantW = (_wantH = 0); _tex = null; } } internal sealed class EmuAudio : MonoBehaviour { private const int Capacity = 32768; private const double MaxLatencySeconds = 0.12; private readonly object _lock = new object(); private readonly float[] _ring = new float[65536]; private int _read; private int _write; private int _count; private double _pos; private double _srcRate = 44100.0; private double _outRate = 48000.0; private AudioSource _source; public float Volume = 1f; private void Awake() { _outRate = AudioSettings.outputSampleRate; _source = ((Component)this).gameObject.AddComponent(); _source.clip = AudioClip.Create("PS1 Audio", (int)_outRate, 2, (int)_outRate, false); _source.loop = true; _source.spatialBlend = 0f; _source.playOnAwake = false; _source.Play(); } public void SetSpatial(bool spatial) { float num = (spatial ? 1f : 0f); if (_source.spatialBlend != num) { _source.spatialBlend = num; _source.rolloffMode = (AudioRolloffMode)1; _source.minDistance = 1.5f; _source.maxDistance = 12f; _source.dopplerLevel = 0f; } } private void OnDestroy() { if ((Object)(object)_source != (Object)null && (Object)(object)_source.clip != (Object)null) { Object.Destroy((Object)(object)_source.clip); } } public void Push(byte[] pcm, int offset, int length) { lock (_lock) { for (int i = offset; i + 3 < offset + length; i += 4) { Write((short)(pcm[i] | (pcm[i + 1] << 8)), (short)(pcm[i + 2] | (pcm[i + 3] << 8))); } } } public void SetSourceRate(double rate) { if (rate > 0.0) { lock (_lock) { _srcRate = rate; } } } public void Clear() { lock (_lock) { _read = (_write = (_count = 0)); _pos = 0.0; } } public unsafe void Push(IntPtr data, int frames) { short* ptr = (short*)(void*)data; lock (_lock) { for (int i = 0; i < frames; i++) { Write(ptr[i * 2], ptr[i * 2 + 1]); } } } public void Push(short left, short right) { lock (_lock) { Write(left, right); } } private void Write(short left, short right) { if (_count == 32768) { _read = (_read + 1) % 32768; _count--; } _ring[_write * 2] = (float)left / 32768f; _ring[_write * 2 + 1] = (float)right / 32768f; _write = (_write + 1) % 32768; _count++; } private void OnAudioFilterRead(float[] data, int channels) { float volume = Volume; lock (_lock) { double num = _srcRate / _outRate; int num2 = (int)(_srcRate * 0.12); if (_count > num2) { int num3 = _count - num2 / 2; _read = (_read + num3) % 32768; _count -= num3; } for (int i = 0; i < data.Length; i += channels) { if (_count < 2) { Array.Clear(data, i, data.Length - i); break; } int num4 = _read * 2; int num5 = (_read + 1) % 32768 * 2; float num6 = (float)_pos; data[i] = (_ring[num4] + (_ring[num5] - _ring[num4]) * num6) * volume; if (channels > 1) { data[i + 1] = (_ring[num4 + 1] + (_ring[num5 + 1] - _ring[num4 + 1]) * num6) * volume; } for (int j = 2; j < channels; j++) { data[i + j] = 0f; } _pos += num; while (_pos >= 1.0 && _count > 1) { _pos -= 1.0; _read = (_read + 1) % 32768; _count--; } } } } } internal struct PadState { public ushort Buttons; public short Lx; public short Ly; public short Rx; public short Ry; public const int Size = 10; public short Read(uint device, uint index, uint id) { switch (device) { case 1u: if (id == 256) { return (short)Buttons; } return (short)((id < 16 && (Buttons & (1 << (int)id)) != 0) ? 1 : 0); default: return 0; case 5u: if (index == 2) { return (short)((id < 16 && (Buttons & (1 << (int)id)) != 0) ? 32767 : 0); } if (id > 1) { return 0; } switch (index) { case 0u: if (id != 0) { return Ly; } return Lx; case 1u: if (id != 0) { return Ry; } return Rx; default: return 0; } } } public void Write(byte[] b, int at) { b[at] = (byte)Buttons; b[at + 1] = (byte)(Buttons >> 8); Put(b, at + 2, Lx); Put(b, at + 4, Ly); Put(b, at + 6, Rx); Put(b, at + 8, Ry); } public static PadState From(byte[] b, int at) { return new PadState { Buttons = (ushort)(b[at] | (b[at + 1] << 8)), Lx = Get(b, at + 2), Ly = Get(b, at + 4), Rx = Get(b, at + 6), Ry = Get(b, at + 8) }; } private static void Put(byte[] b, int at, short v) { b[at] = (byte)v; b[at + 1] = (byte)(v >> 8); } private static short Get(byte[] b, int at) { return (short)(b[at] | (b[at + 1] << 8)); } } internal static class EmuInput { private static int _stickHeldX; private static int _stickHeld; private static readonly HashSet Virtual = new HashSet(); public static PadState Sample(bool active) { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) PadState s = default(PadState); if (!active || PS1Identity.ChatActive) { return s; } for (uint num = 0u; num < 16; num++) { KeyCode val = REPOPS1Plugin.PadKey(num); if ((int)val != 0 && Input.GetKey(val)) { s.Buttons |= (ushort)(1 << (int)num); } } ReadOnlyArray all = Gamepad.all; for (int i = 0; i < all.Count; i++) { AddPad(ref s, all[i]); } return s; } private static void AddPad(ref PadState s, Gamepad gp) { //IL_0155: Unknown result type (might be due to invalid IL or missing references) //IL_015a: 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_0166: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) //IL_019a: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Unknown result type (might be due to invalid IL or missing references) if (gp != null && ((InputDevice)gp).enabled && !Ours((InputDevice)(object)gp)) { Or(ref s, 0u, gp.buttonSouth.isPressed); Or(ref s, 8u, gp.buttonEast.isPressed); Or(ref s, 1u, gp.buttonWest.isPressed); Or(ref s, 9u, gp.buttonNorth.isPressed); Or(ref s, 10u, gp.leftShoulder.isPressed); Or(ref s, 11u, gp.rightShoulder.isPressed); Or(ref s, 12u, gp.leftTrigger.isPressed); Or(ref s, 13u, gp.rightTrigger.isPressed); Or(ref s, 14u, gp.leftStickButton.isPressed); Or(ref s, 15u, gp.rightStickButton.isPressed); Or(ref s, 3u, gp.startButton.isPressed); Or(ref s, 2u, gp.selectButton.isPressed); Or(ref s, 4u, gp.dpad.up.isPressed); Or(ref s, 5u, gp.dpad.down.isPressed); Or(ref s, 6u, gp.dpad.left.isPressed); Or(ref s, 7u, gp.dpad.right.isPressed); Vector2 val = ((InputControl)(object)gp.leftStick).ReadValue(); Vector2 val2 = ((InputControl)(object)gp.rightStick).ReadValue(); Stronger(ref s.Lx, Axis(val.x)); Stronger(ref s.Ly, Axis(0f - val.y)); Stronger(ref s.Rx, Axis(val2.x)); Stronger(ref s.Ry, Axis(0f - val2.y)); } } private static void Stronger(ref short current, short v) { if (Mathf.Abs((int)v) > Mathf.Abs((int)current)) { current = v; } } public static bool PadPressed(Func button) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) ReadOnlyArray all = Gamepad.all; for (int i = 0; i < all.Count; i++) { if (all[i] != null && !Ours((InputDevice)(object)all[i]) && button(all[i]).wasPressedThisFrame) { return true; } } return false; } public static int StickStepX() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: 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) float num = 0f; ReadOnlyArray all = Gamepad.all; for (int i = 0; i < all.Count; i++) { if (!Ours((InputDevice)(object)all[i])) { float x = ((InputControl)(object)all[i].leftStick).ReadValue().x; if (Mathf.Abs(x) > Mathf.Abs(num)) { num = x; } } } int num2 = ((num > 0.6f) ? 1 : ((num < -0.6f) ? (-1) : 0)); if (num2 == _stickHeldX) { return 0; } _stickHeldX = num2; return num2; } public static bool ComboPressed() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) ReadOnlyArray all = Gamepad.all; for (int i = 0; i < all.Count; i++) { Gamepad val = all[i]; if (!Ours((InputDevice)(object)val) && val.leftStickButton.isPressed && val.rightStickButton.isPressed && (val.leftStickButton.wasPressedThisFrame || val.rightStickButton.wasPressedThisFrame)) { return true; } } return false; } public static int StickStep() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: 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) float num = 0f; ReadOnlyArray all = Gamepad.all; for (int i = 0; i < all.Count; i++) { if (!Ours((InputDevice)(object)all[i])) { float y = ((InputControl)(object)all[i].leftStick).ReadValue().y; if (Mathf.Abs(y) > Mathf.Abs(num)) { num = y; } } } int num2 = ((num > 0.6f) ? (-1) : ((num < -0.6f) ? 1 : 0)); if (num2 == _stickHeld) { return 0; } _stickHeld = num2; return num2; } public static int RealPadCount() { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) int num = 0; Enumerator enumerator = Gamepad.all.GetEnumerator(); try { while (enumerator.MoveNext()) { Gamepad current = enumerator.Current; if (((InputDevice)current).enabled && !Ours((InputDevice)(object)current)) { num++; } } return num; } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } } private static bool Ours(InputDevice d) { if (Virtual.Contains(d.deviceId)) { return true; } if (!VirtualPad.IsVirtual(d)) { return false; } Virtual.Add(d.deviceId); if (d.enabled) { InputSystem.DisableDevice(d, false); } REPOPS1Plugin.Log.LogInfo((object)("Controller " + ((InputControl)d).displayName + " is the mod's virtual pad: ignored.")); return true; } public static void WatchDevices() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) Enumerator enumerator = Gamepad.all.GetEnumerator(); try { while (enumerator.MoveNext()) { Gamepad current = enumerator.Current; REPOPS1Plugin.Log.LogInfo((object)("Controller found: " + ((InputControl)current).displayName + " (" + ((InputControl)current).layout + ").")); } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } InputSystem.onDeviceChange += delegate(InputDevice device, InputDeviceChange change) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Invalid comparison between Unknown and I4 //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) if (device is Gamepad && (int)change == 0 && !Ours(device)) { InputDeviceDescription description = device.description; if (((InputDeviceDescription)(ref description)).interfaceName == "XInput" && Time.unscaledTime - VirtualPad.PluggedAt < 3f) { Virtual.Add(device.deviceId); InputSystem.DisableDevice(device, false); REPOPS1Plugin.Log.LogInfo((object)("Controller " + ((InputControl)device).displayName + " is the mod's virtual pad: ignored.")); } } if (device is Gamepad && ((int)change == 0 || (int)change == 1)) { REPOPS1Plugin.Log.LogInfo((object)("Controller " + (((int)change == 0) ? "connected" : "removed") + ": " + ((InputControl)device).displayName + " (" + ((InputControl)device).layout + ").")); } }; } private static void Or(ref PadState s, uint id, bool pressed) { if (pressed) { s.Buttons |= (ushort)(1 << (int)id); } } private static short Axis(float v) { return (short)Mathf.Clamp(Mathf.RoundToInt(v * 32767f), -32767, 32767); } } internal sealed class MenuItem { public string Title; public string System; public string Folder; public GameEntry Local; public int RemoteIndex = -1; public bool Join; public bool Running; } internal sealed class EmuSession : MonoBehaviour { public enum ChooseResult { Started, NeedsConfirm } public const int Ports = 4; private static readonly List NoKeys = new List(); private LibretroCore _core; private ExternalEmulator _ext; private string _extProblem; private readonly EmuVideo _video = new EmuVideo(); private EmuAudio _audio; private readonly int[] _portOwner = new int[4] { -1, -1, -1, -1 }; private readonly PadState[] _pads = new PadState[4]; private readonly Dictionary _remotePads = new Dictionary(); private GameObject _screen; private RawImage _picture; private AspectRatioFitter _fitter; private string _error; private string _note; private float _noteUntil; private List _games = new List(); private bool _scanned; private readonly List _menu = new List(); private int _sel; private string _playing; private string _playingPath; private GUIStyle _titleStyle; private GUIStyle _rowStyle; private GUIStyle _smallStyle; private double _acc; private float _helpUntil; private CursorLockMode _prevLock; private bool _prevVisible; private QuickMenu _quick; private EmuThread _thread; private static readonly HashSet NoGpuCores = new HashSet(StringComparer.OrdinalIgnoreCase); private static Material _opaque; private LibretroCore _dying; private float _dyingSince; private GameEntry _playingEntry; private GameEntry _pendingStart; public static int WantedPad = -1; private int _menuVersion = -1; private float _padAskAt; private float _playedFor; private float _libraryAt; private string _confirmKey; private float _confirmAt; private bool _menuOpen; private readonly GameShelf _shelf = new GameShelf(); private List _view = new List(); public static EmuSession Instance { get; private set; } public static bool Open { get; private set; } public static bool RemoteMode { get; private set; } public Texture2D ScreenTexture => _video.Texture; public int FrameCount => _video.FrameCount; public bool HasGame => Loaded; public string GameTitle { get { if (!Loaded) { return ""; } return _playing; } } public double SampleRate { get { if (_core == null) { return 44100.0; } return _core.AvInfo.Timing.SampleRate; } } public float Aspect { get { if (!((Object)(object)_fitter != (Object)null)) { return 1.3333334f; } return _fitter.aspectRatio; } } public List Library => _games; private bool Loaded { get { if (_core == null) { return _ext != null; } return true; } } public static int LocalActor { get { if (!PhotonNetwork.InRoom || PhotonNetwork.LocalPlayer == null) { return 0; } return PhotonNetwork.LocalPlayer.ActorNumber; } } private static Material OpaqueMaterial { get { //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Expected O, but got Unknown //IL_0071: Expected O, but got Unknown if ((Object)(object)_opaque != (Object)null) { return _opaque; } Shader val = Shader.Find("Unlit/Texture") ?? Shader.Find("Hidden/BlitCopy") ?? Shader.Find("UI/Default"); REPOPS1Plugin.Log.LogInfo((object)("Fullscreen picture shader: " + (((Object)(object)val != (Object)null) ? ((Object)val).name : "none"))); Material val2 = new Material(val); _opaque = val2; return val2; } } public bool HwActive { get { if (_core != null) { return _core.HwActive; } return false; } } public string GameTitleForMenu { get { if (!RemoteMode) { return _playing; } if (!((Object)(object)PS1Stream.Instance != (Object)null)) { return ""; } return PS1Stream.Instance.RemoteTitle; } } public bool Running { get; private set; } public string RunningTitle { get { if (!Loaded) { if (!RemoteMode) { return null; } return PS1Stream.Instance?.RemoteTitle; } return _playing; } } public int DiscCount { get { if (_ext != null || _core == null) { return 0; } return _core.DiscCount; } } public int LocalPad { get { if (RemoteMode) { if (!((Object)(object)PS1Stream.Instance != (Object)null)) { return -1; } return PS1Stream.Instance.MyPad; } int localActor = LocalActor; for (int i = 0; i < 4; i++) { if (_portOwner[i] == localActor) { return i; } } return -1; } } public int PortOwner(int port) { return _portOwner[port]; } private void Awake() { Instance = this; _quick = new QuickMenu(this); _audio = ((Component)this).gameObject.AddComponent(); BuildScreen(); EmuInput.WatchDevices(); } private void Update() { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Unknown result type (might be due to invalid IL or missing references) FinishDying(); int num; if (Open) { if (RemoteMode) { num = 1; goto IL_0031; } if (Loaded) { num = ((!_menuOpen) ? 1 : 0); if (num != 0) { goto IL_0031; } } else { num = 0; } } else { num = 0; } goto IL_0077; IL_0098: if (num != 0 && Input.GetKeyDown((KeyCode)291)) { SaveFrame(); } else if (Input.GetKeyDown(REPOPS1Plugin.ToggleKey.Value) && (Open || PS1Room.Inside || REPOPS1Plugin.PlayAnywhere.Value) && !PS1Identity.ChatActive) { if (Open) { Close(); } else { OpenScreen(); } } else if (Open && Input.GetKeyDown((KeyCode)27)) { Close(); } if (num == 0 && _quick.IsOpen) { _quick.Close(); } if (Open) { BlockGameInput(); Cursor.lockState = (CursorLockMode)1; Cursor.visible = false; if (Input.GetKeyDown(REPOPS1Plugin.ChangeGameKey.Value) && !PS1Identity.ChatActive) { if (RemoteMode) { LeaveRemote(); } else if (Loaded) { _menuOpen = !_menuOpen; _confirmKey = null; if (_menuOpen) { RefreshMenu(rescan: true); } } } if (_quick.IsOpen) { _quick.Tick(); } else if (RemoteMode) { RemoteTick(); } else if (!Loaded || _menuOpen) { MenuInput(); } if (RemoteMode && _quick.IsOpen) { RemoteTick(); } } RunConsole(); RouteAudio(); return; IL_0077: if (_quick.IsOpen && Input.GetKeyDown((KeyCode)27)) { _quick.Close(); } goto IL_0098; IL_0031: if (PS1Identity.ChatActive || (!Input.GetKeyDown(REPOPS1Plugin.QuickMenuKey.Value) && !EmuInput.ComboPressed())) { goto IL_0077; } if (_quick.IsOpen) { _quick.Close(); } else { _quick.Open(); } goto IL_0098; } private void RunConsole() { Running = false; if (_ext != null) { RunExternal(); } else { if (_core == null) { return; } int localActor = LocalActor; if (Open && !RemoteMode && !_menuOpen && !_quick.IsOpen) { TakePort(localActor); } else { ReleasePort(localActor); } DropGonePlayers(); bool flag = false; for (int i = 0; i < 4; i++) { int num = _portOwner[i]; if (num < 0) { _pads[i] = default(PadState); continue; } flag = true; _pads[i] = ((num == localActor) ? EmuInput.Sample(Application.isFocused) : (_remotePads.TryGetValue(num, out var value) ? value : default(PadState))); } if (_thread != null) { _thread.Allow = flag; } if (!flag) { _acc = 0.0; return; } Running = true; if (_playingPath != null && ((Open && !RemoteMode) || HasRemotePlayers())) { _playedFor += Time.unscaledDeltaTime; if (_playedFor >= 5f) { PlayStats.Played(_playingPath, _playedFor); _playedFor = 0f; } } PlayStats.Tick(); double num2 = _core.AvInfo.Timing.Fps; if (num2 < 1.0) { num2 = 60.0; } double num3 = 1.0 / num2; _acc += Time.unscaledDeltaTime; int num4 = 0; while (_acc >= num3 && num4 < 4) { _acc -= num3; num4++; } if (_acc > num3 * 4.0) { _acc = 0.0; } if (_core.HwActive) { D3D11Host.Run(num4); } else if (_thread == null) { for (int j = 0; j < num4; j++) { _core.Run(); } } if (_core.ShutdownRequested) { Unload(); RefreshMenu(rescan: false); return; } if (_core.HwActive && LibretroCore.GpuFailed && _playingEntry != null) { NoGpuCores.Add(_playingEntry.CorePath); REPOPS1Plugin.Log.LogWarning((object)"This core can't draw with the GPU here; starting the game again with its software renderer."); Note("This emulator can't use the GPU here: switching it to its software renderer..."); GameEntry playingEntry = _playingEntry; LibretroCore.GpuFailed = false; Unload(); StartGame(playingEntry); return; } if (_core.AvChanged) { ApplyAvInfo(); } ApplyLayout(); _video.Smooth = REPOPS1Plugin.Smooth.Value; if (_core.HwActive) { _video.UploadHw(); } else { _video.Upload(); } if (!RemoteMode) { _picture.texture = _video.Display; ((Behaviour)_picture).enabled = (Object)(object)_video.Texture != (Object)null; ((Graphic)_picture).material = (_core.HwActive ? OpaqueMaterial : null); } } } private void RunExternal() { int localActor = LocalActor; if (Open && !RemoteMode && !_menuOpen && !_quick.IsOpen) { TakePort(localActor); } else { ReleasePort(localActor); } DropGonePlayers(); bool flag = false; PadState[] array = new PadState[4]; bool flag2 = false; for (int i = 0; i < 4; i++) { int num = _portOwner[i]; flag = flag || num >= 0; PadState value; if (num == localActor) { flag2 = true; } else if (num >= 0 && _remotePads.TryGetValue(num, out value)) { array[i] = value; } } if (flag2) { array[0] = Merge(array[0], EmuInput.Sample(Application.isFocused)); } ExternalEmulator.SetPads(array); Running = flag; if (_ext.Exited) { Note("The emulator closed."); Unload(); RefreshMenu(rescan: false); return; } _ext.Tick(flag); if (_ext.Problem != null && _ext.Problem != _extProblem) { _extProblem = _ext.Problem; Note(_extProblem); REPOPS1Plugin.Log.LogWarning((object)_extProblem); } if (flag && _playingPath != null && (_playedFor += Time.unscaledDeltaTime) >= 5f) { PlayStats.Played(_playingPath, _playedFor); _playedFor = 0f; } PlayStats.Tick(); ApplyLayout(); _video.Smooth = REPOPS1Plugin.Smooth.Value; _video.UploadHw(); Texture2D texture = _video.Texture; if ((Object)(object)texture != (Object)null && ((Texture)texture).height > 0) { _fitter.aspectRatio = (float)((Texture)texture).width / (float)((Texture)texture).height; } if (!RemoteMode) { _picture.texture = _video.Display; ((Behaviour)_picture).enabled = (Object)(object)_video.Texture != (Object)null; ((Graphic)_picture).material = OpaqueMaterial; } } public static int PlayerOfPort(uint port) { switch (port) { default: return -1; case 3u: case 4u: return (int)(port - 1); case 1u: case 2u: return 1; case 0u: return 0; } } private static PadState Merge(PadState a, PadState b) { a.Buttons |= b.Buttons; if (Math.Abs((int)b.Lx) > Math.Abs((int)a.Lx)) { a.Lx = b.Lx; } if (Math.Abs((int)b.Ly) > Math.Abs((int)a.Ly)) { a.Ly = b.Ly; } if (Math.Abs((int)b.Rx) > Math.Abs((int)a.Rx)) { a.Rx = b.Rx; } if (Math.Abs((int)b.Ry) > Math.Abs((int)a.Ry)) { a.Ry = b.Ry; } return a; } public void TakePort(int actor) { for (int i = 0; i < 4; i++) { if (_portOwner[i] == actor) { return; } } int num = ((actor == LocalActor) ? WantedPad : PS1Presence.WantOf(actor)); if (num >= 0 && num < 4 && _portOwner[num] < 0) { _portOwner[num] = actor; REPOPS1Plugin.Log.LogInfo((object)$"Pad {num + 1}: player {actor}."); return; } for (int j = 0; j < 4; j++) { if (_portOwner[j] < 0) { _portOwner[j] = actor; REPOPS1Plugin.Log.LogInfo((object)$"Pad {j + 1}: player {actor}."); break; } } } public void ReleasePort(int actor) { for (int i = 0; i < 4; i++) { if (_portOwner[i] == actor) { _portOwner[i] = -1; REPOPS1Plugin.Log.LogInfo((object)$"Pad {i + 1}: free."); } } if (actor != LocalActor) { _remotePads.Remove(actor); } } private void DropGonePlayers() { int localActor = LocalActor; for (int i = 0; i < 4; i++) { int num = _portOwner[i]; if (num >= 0 && num != localActor && ((Object)(object)PS1Stream.Instance == (Object)null || !PS1Stream.Instance.IsWatching(num))) { ReleasePort(num); } } } public void RemotePad(int actor, PadState pad) { _remotePads[actor] = pad; } private bool HasRemotePlayers() { int localActor = LocalActor; for (int i = 0; i < 4; i++) { if (_portOwner[i] >= 0 && _portOwner[i] != localActor) { return true; } } return false; } public void RemoteStart(int actor, int index) { if (Open && !RemoteMode && Loaded) { TakePort(actor); return; } EnsureLibrary(); if (index < 0 || index >= _games.Count) { return; } if (Loaded && SamePath(_games[index].Path, _playingPath)) { TakePort(actor); return; } REPOPS1Plugin.Log.LogInfo((object)$"Player {actor} started {_games[index].Title} on this PC."); StartGame(_games[index]); if (Loaded) { TakePort(actor); } } public void RemoteStop(int actor) { bool flag = false; for (int i = 0; i < 4; i++) { flag |= _portOwner[i] == actor; } if (flag && Loaded) { REPOPS1Plugin.Log.LogInfo((object)$"Player {actor} stopped the game on this PC."); Unload(); if (Open && !RemoteMode) { RefreshMenu(rescan: false); } } } public void EnsureLibrary() { if (!_scanned) { _scanned = true; } } private void RouteAudio() { //IL_003a: Unknown result type (might be due to invalid IL or missing references) Transform tv = PS1Room.Tv; bool flag = !Open && PS1Room.Inside && (Object)(object)tv != (Object)null; _audio.SetSpatial(flag); if (flag) { ((Component)_audio).transform.position = tv.position; } _audio.Volume = ((_core != null && ((Open && !RemoteMode) || flag)) ? REPOPS1Plugin.Volume.Value : 0f); } private void EnterRemote(int startIndex) { if (!HasRemotePlayers()) { Unload(); } RemoteMode = true; if (startIndex >= 0) { PS1Stream.Instance.SendStart(startIndex); } else { PS1Stream.Instance.SendTakePad(); } _helpUntil = Time.unscaledTime + 5f; } private void LeaveRemote() { if (RemoteMode) { RemoteMode = false; PS1Stream.Instance?.SendReleasePad(); _picture.texture = null; ((Behaviour)_picture).enabled = false; if (Open) { RefreshMenu(rescan: false); } } } private void RemoteTick() { PS1Stream instance = PS1Stream.Instance; if ((Object)(object)instance == (Object)null || !instance.Connected) { LeaveRemote(); Note("The game's PC is gone."); return; } if (!instance.RemoteHasGame && Time.unscaledTime - _helpUntil > 0f) { LeaveRemote(); Note("The game was closed."); return; } instance.SendPad(_quick.IsOpen ? default(PadState) : EmuInput.Sample(Application.isFocused)); if (instance.MyPad < 0 && Time.unscaledTime >= _padAskAt) { _padAskAt = Time.unscaledTime + 2f; instance.SendTakePad(); } _picture.texture = (Texture)(object)(instance.HasViewFrame ? instance.ViewTexture : null); ((Behaviour)_picture).enabled = instance.HasViewFrame; _fitter.aspectRatio = instance.RemoteAspect; ApplyLayout(); } public void OpenScreen() { //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) if (!Open) { Open = true; _prevLock = Cursor.lockState; _prevVisible = Cursor.visible; _screen.SetActive(true); _helpUntil = Time.unscaledTime + 5f; _menuOpen = false; if (!Loaded) { RefreshMenu(rescan: true); } } } public void Close() { //IL_0021: Unknown result type (might be due to invalid IL or missing references) if (Open) { LeaveRemote(); Open = false; _screen.SetActive(false); Cursor.lockState = _prevLock; Cursor.visible = _prevVisible; } } private static void BlockGameInput() { InputManager instance = InputManager.instance; if ((Object)(object)instance != (Object)null) { instance.DisableMovement(0.2f); instance.DisableAiming(0.2f); instance.DisableControlsExcept(0.2f, NoKeys); } PlayerController instance2 = PlayerController.instance; if (instance2 != null) { instance2.InputDisable(0.25f); } } public void Note(string text) { _note = text; _noteUntil = Time.unscaledTime + 4f; } private void OnGUI() { //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005d: 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_0070: Expected O, but got Unknown //IL_007b: 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_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Expected O, but got Unknown //IL_00c3: 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_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00cf: 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_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: 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_0149: 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_0359: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_01af: Unknown result type (might be due to invalid IL or missing references) //IL_0298: Unknown result type (might be due to invalid IL or missing references) //IL_0314: Unknown result type (might be due to invalid IL or missing references) if (!Open) { return; } if (_titleStyle == null) { _titleStyle = new GUIStyle(GUI.skin.label) { fontSize = 34, alignment = (TextAnchor)4, richText = true }; _rowStyle = new GUIStyle(GUI.skin.label) { fontSize = 22, alignment = (TextAnchor)3, richText = true, clipping = (TextClipping)1 }; _smallStyle = new GUIStyle(GUI.skin.label) { fontSize = 18, alignment = (TextAnchor)4, richText = true, wordWrap = true }; GUIStyleState normal = _titleStyle.normal; GUIStyleState normal2 = _rowStyle.normal; Color val = (_smallStyle.normal.textColor = Color.white); Color textColor = (normal2.textColor = val); normal.textColor = textColor; } if (Time.unscaledTime < _noteUntil) { GUI.Label(new Rect(0f, (float)Screen.height * 0.02f, (float)Screen.width, 30f), "" + Escape(_note) + "", _smallStyle); } string text = $"{REPOPS1Plugin.ToggleKey.Value} / Esc: back to the room {REPOPS1Plugin.ChangeGameKey.Value}: other game"; if (RemoteMode) { PS1Stream instance = PS1Stream.Instance; if (_quick.IsOpen) { _quick.Draw(); return; } if ((Object)(object)instance != (Object)null && !instance.HasViewFrame) { GUI.Label(new Rect(0f, (float)Screen.height * 0.45f, (float)Screen.width, 40f), "Connecting to the game...", _smallStyle); } if (Time.unscaledTime < _helpUntil || ((Object)(object)instance != (Object)null && instance.MyPad < 0)) { GUI.Label(new Rect(0f, 40f, (float)Screen.width, 40f), (((Object)(object)instance != (Object)null && instance.MyPad >= 0) ? $"Pad {instance.MyPad + 1}" : "All pads taken: watching") + " " + text, _smallStyle); } } else if (Loaded && !_menuOpen) { if (_quick.IsOpen) { _quick.Draw(); } else if (Time.unscaledTime < _helpUntil) { GUI.Label(new Rect(0f, 40f, (float)Screen.width, 40f), Escape(_playing) + " (" + ((_ext != null) ? "PCSX2" : (HwActive ? ("GPU " + REPOPS1Plugin.ResolutionScale.Value + "x") : "Software")) + ") " + text + $" {REPOPS1Plugin.QuickMenuKey.Value} / L3 + R3: menu", _smallStyle); } } else if (_dying != null) { GUI.Label(new Rect(0f, (float)Screen.height * 0.45f, (float)Screen.width, 40f), "Closing the game...", _smallStyle); } else { DrawMenu(); } } private void RefreshMenu(bool rescan) { if (rescan) { ((BaseUnityPlugin)REPOPS1Plugin.Instance).Config.Reload(); _scanned = false; _shelf.Refresh(); } EnsureLibrary(); _menu.Clear(); PS1Stream instance = PS1Stream.Instance; if ((Object)(object)instance != (Object)null && instance.Connected) { if (instance.RemoteHasGame) { _menu.Add(new MenuItem { Title = "Join: " + instance.RemoteTitle, System = "on " + instance.RemoteOwnerName, Join = true }); } List remoteLibrary = instance.RemoteLibrary; for (int i = 0; i < remoteLibrary.Count; i++) { _menu.Add(new MenuItem { Title = remoteLibrary[i].Title, System = remoteLibrary[i].System + " (" + instance.RemoteOwnerName + ")", Folder = remoteLibrary[i].Folder, RemoteIndex = i }); } } foreach (GameEntry game in _games) { _menu.Add(new MenuItem { Title = game.Title, System = game.System, Folder = GameLibrary.SystemFolder(game), Local = game, Running = (Loaded && SamePath(game.Path, _playingPath)) }); } _sel = Mathf.Clamp(_sel, 0, Math.Max(0, _menu.Count - 1)); } private void MenuInput() { PS1Stream instance = PS1Stream.Instance; int num = (((Object)(object)instance != (Object)null) ? instance.RemoteVersion : 0); if (num != _menuVersion) { _menuVersion = num; RefreshMenu(rescan: false); } int num2 = 0; if (Input.GetKeyDown((KeyCode)101) || EmuInput.PadPressed((Gamepad g) => g.rightShoulder)) { num2 = 1; } if (Input.GetKeyDown((KeyCode)113) || EmuInput.PadPressed((Gamepad g) => g.leftShoulder)) { num2 = -1; } if (num2 != 0) { _shelf.Tab = (_shelf.Tab + num2 + GameShelf.Tabs.Length) % GameShelf.Tabs.Length; _sel = 0; _confirmKey = null; } if (Loaded && EmuInput.PadPressed((Gamepad g) => g.buttonEast)) { _menuOpen = false; return; } _view = _shelf.Filter(_menu); if (_view.Count != 0) { int num3 = EmuInput.StickStepX(); if (Input.GetKeyDown((KeyCode)275) || Input.GetKeyDown((KeyCode)100) || EmuInput.PadPressed((Gamepad g) => g.dpad.right)) { num3 = 1; } if (Input.GetKeyDown((KeyCode)276) || Input.GetKeyDown((KeyCode)97) || EmuInput.PadPressed((Gamepad g) => g.dpad.left)) { num3 = -1; } if (num3 != 0) { _confirmKey = null; } _sel = Mathf.Clamp(_sel + num3, 0, _view.Count - 1); if ((Input.GetKeyDown((KeyCode)102) || EmuInput.PadPressed((Gamepad g) => g.buttonNorth)) && _view[_sel].Local != null) { PlayStats.ToggleFavourite(_view[_sel].Local.Path); } if ((Input.GetKeyDown((KeyCode)13) || Input.GetKeyDown((KeyCode)271) || EmuInput.PadPressed((Gamepad g) => g.buttonSouth) || EmuInput.PadPressed((Gamepad g) => g.startButton)) && Choose(_view[_sel]) == ChooseResult.NeedsConfirm) { Note("This closes the game that is running (unsaved progress is lost). Press Enter again to start it."); } } } public ChooseResult Choose(MenuItem item) { PS1Stream instance = PS1Stream.Instance; if (item.Local != null && Loaded && SamePath(item.Local.Path, _playingPath)) { _menuOpen = false; return ChooseResult.Started; } if ((item.Join || (item.RemoteIndex >= 0 && item.Title == instance?.RemoteTitle)) && (Object)(object)instance != (Object)null && instance.RemoteHasGame) { _menuOpen = false; EnterRemote(-1); return ChooseResult.Started; } bool num = (Loaded && (item.Local != null || !HasRemotePlayers())) || (item.RemoteIndex >= 0 && (Object)(object)instance != (Object)null && instance.RemoteHasGame); string text = ((item.Local != null) ? item.Local.Path : ("remote:" + item.RemoteIndex)); if (num && (_confirmKey != text || Time.unscaledTime - _confirmAt > 6f)) { _confirmKey = text; _confirmAt = Time.unscaledTime; return ChooseResult.NeedsConfirm; } _confirmKey = null; _menuOpen = false; if (item.Local != null) { StartGame(item.Local); } else if (item.RemoteIndex >= 0) { EnterRemote(item.RemoteIndex); } return ChooseResult.Started; } public List ShelfItems() { if (Time.unscaledTime - _libraryAt > 10f) { _libraryAt = Time.unscaledTime; _scanned = false; } if (!Open) { RefreshMenu(rescan: false); } List list = new List(); foreach (MenuItem item in _menu) { if (!item.Join) { list.Add(item); } } return list; } public Texture2D CoverFor(MenuItem m, out bool real) { return _shelf.Cover(m, out real); } private static bool SamePath(string a, string b) { if (a != null && b != null) { return string.Equals(Path.GetFullPath(a), Path.GetFullPath(b), StringComparison.OrdinalIgnoreCase); } return false; } private void DrawMenu() { //IL_00a8: Unknown result type (might be due to invalid IL or missing references) _view = _shelf.Filter(_menu); _shelf.Draw(_view, Mathf.Clamp(_sel, 0, Math.Max(0, _view.Count - 1)), (_menu.Count == 0) ? ((_error ?? "No games.") + " Edit BepInEx/config/repops1.platform.cfg.") : null, _playing); if (_error != null && _menu.Count > 0) { GUI.Label(new Rect(0f, (float)Screen.height * 0.88f, (float)Screen.width, 30f), "" + Escape(_error) + "", _smallStyle); } } private static string Escape(string s) { return (s ?? "").Replace("<", "‹").Replace(">", "›"); } private void OnApplicationQuit() { if (_ext != null) { _ext.Stop(); _ext = null; } if (_core != null && !_core.HwActive) { Unload(); } } private void StartGame(GameEntry game) { string text = GameLibrary.MissingTrack(game.Path); if (text != null) { _error = game.Title + ": the file \"" + text + "\" is missing next to the .cue (unzip all of the game's files)."; Note(_error); return; } string text2 = ExternalFor(game); if (text2 != null && _dying == null && (_core == null || !_core.HwActive)) { Unload(); try { _ext = ExternalEmulator.Start(text2, game.Path); _extProblem = null; _error = null; _playing = game.Title; _playingPath = game.Path; _playingEntry = game; PlayStats.Played(game.Path, 0f); PlayStats.Save(); _helpUntil = Time.unscaledTime + 5f; Note("Starting " + Path.GetFileNameWithoutExtension(text2) + "..."); return; } catch (Exception ex) { REPOPS1Plugin.Log.LogError((object)("Could not start " + text2 + ": " + ex)); _error = game.Title + ": could not start " + text2 + " (" + ex.Message + ")"; Note(_error); return; } } if ((_core != null && _core.HwActive) || _dying != null) { _pendingStart = game; Unload(); return; } Unload(); string text3 = REPOPS1Plugin.SystemDirectory.Value.Trim().Trim('"'); if (text3.Length == 0) { text3 = Path.Combine(Paths.ConfigPath, "REPOPS1", "system"); } string fileName = Path.GetFileName(Path.GetDirectoryName(game.CorePath) ?? ""); string text4 = Path.Combine(text3, fileName); if (text4 != text3 && Directory.Exists(text4)) { text3 = text4; } if (ParseOptions(REPOPS1Plugin.SystemFolders.Value).TryGetValue(fileName, out var value) && Directory.Exists(value.Trim('"'))) { text3 = value.Trim('"'); } string text5 = Path.Combine(Paths.ConfigPath, "REPOPS1", "saves"); Directory.CreateDirectory(text3); Directory.CreateDirectory(text5); LibretroCore.LastCoreError = null; LibretroCore.GpuFailed = false; LibretroCore core = new LibretroCore(ParseOptions(REPOPS1Plugin.CoreOptions.Value)); core.Video = delegate(IntPtr data, int w, int h, int pitch) { _video.OnFrame(data, w, h, pitch, core.PixelFormat); }; core.AudioBatch = delegate(IntPtr data, int frames) { _audio.Push(data, frames); PS1Stream.HostAudio(data, frames); }; core.AudioSample = delegate(short l, short r) { _audio.Push(l, r); PS1Stream.HostAudio(l, r); }; core.InputState = delegate(uint port, uint device, uint index, uint id) { int num = PlayerOfPort(port); return (short)((num >= 0) ? _pads[num].Read(device, index, id) : 0); }; core.Message = Note; core.HwWanted = REPOPS1Plugin.Renderer.Value == "GPU" && !NoGpuCores.Contains(game.CorePath) && D3D11Host.Init(); if (core.HwWanted) { D3D11Host.BeforeLoad(); } core.Scale = REPOPS1Plugin.ResolutionScale.Value; core.Enhance = REPOPS1Plugin.Enhancements.Value; core.Widescreen = REPOPS1Plugin.Widescreen.Value; try { core.Load(game.CorePath, game.Path, text3, text5); _core = core; _error = null; _playing = game.Title; _playingPath = game.Path; _playingEntry = game; PlayStats.Played(game.Path, 0f); PlayStats.Save(); if (core.HwActive) { D3D11Host.Begin(core); } else { D3D11Host.AfterCore(); if (REPOPS1Plugin.EmulationThread.Value) { _thread = new EmuThread(core); } } _acc = 0.0; _audio.Clear(); _helpUntil = Time.unscaledTime + 5f; REPOPS1Plugin.Log.LogInfo((object)("Running " + Path.GetFileName(game.Path) + " on " + core.LibraryName)); } catch (Exception ex2) { REPOPS1Plugin.Log.LogError((object)("Could not start the emulator: " + ex2)); D3D11Host.AfterCore(); core.Dispose(); _error = game.Title + ": " + (LibretroCore.LastCoreError ?? ex2.Message); Note(_error); } } private static string ExternalFor(GameEntry game) { if (!ParseOptions(REPOPS1Plugin.ExternalEmulators.Value).TryGetValue(GameLibrary.SystemFolder(game), out var value)) { return null; } value = value.Trim().Trim('"'); if (File.Exists(value)) { return value; } REPOPS1Plugin.Log.LogWarning((object)("ExternalEmulators: " + value + " not found; using the core.")); return null; } private void Unload() { _playingPath = null; _menuOpen = false; if (_ext != null) { _ext.Stop(); _ext = null; } if (_core != null && _core.HwActive) { _dying = _core; _dyingSince = Time.unscaledTime; D3D11Host.Shutdown(); } else if (_core != null) { if (_thread == null || _thread.Stop(3000)) { _core.Dispose(); } else { REPOPS1Plugin.Log.LogError((object)"The emulator thread did not stop in 3 s; leaving the core loaded."); } } _thread = null; _core = null; _video.Dispose(); for (int i = 0; i < 4; i++) { _portOwner[i] = -1; } _remotePads.Clear(); _audio.Clear(); if (!RemoteMode) { _picture.texture = null; ((Behaviour)_picture).enabled = false; } } private void OnCore(Action job) { if (_core != null) { if (_core.HwActive) { D3D11Host.Enqueue(job); } else if (_thread != null) { _thread.Enqueue(job); } else { job(_core); } } } private string SlotPath(int slot) { string text = ((_playingEntry != null) ? Path.GetFileNameWithoutExtension(_playingEntry.Path) : "game"); char[] invalidFileNameChars = Path.GetInvalidFileNameChars(); foreach (char oldChar in invalidFileNameChars) { text = text.Replace(oldChar, '_'); } return Path.Combine(Paths.ConfigPath, "REPOPS1", "states", $"{text}.slot{slot}.state"); } public string SlotInfo(int slot) { string path = SlotPath(slot); if (!File.Exists(path)) { return "empty"; } return File.GetLastWriteTime(path).ToString("dd/MM HH:mm"); } public void SaveSlot(int slot) { if (_ext != null) { _ext.SaveState(); Note("Saved (PCSX2's current slot)."); return; } string path = SlotPath(slot); OnCore(delegate(LibretroCore c) { byte[] array = c.SaveState(); if (array == null) { Note("This game can't be saved right now."); } else { Directory.CreateDirectory(Path.GetDirectoryName(path)); File.WriteAllBytes(path, array); Note($"Saved to slot {slot}."); } }); } public bool LoadSlot(int slot) { if (_ext != null) { _ext.LoadState(); Note("Loaded (PCSX2's current slot)."); return true; } string path = SlotPath(slot); if (!File.Exists(path)) { Note($"Slot {slot} is empty."); return false; } byte[] state = File.ReadAllBytes(path); OnCore(delegate(LibretroCore c) { Note(c.LoadState(state) ? $"Loaded slot {slot}." : $"Slot {slot} doesn't fit this game or core."); }); return true; } public void ResetGame() { OnCore(delegate(LibretroCore c) { c.Reset(); }); } public void NextDisc() { OnCore(delegate(LibretroCore c) { int num = c.NextDisc(); Note((num < 0) ? "Couldn't change the disc." : $"Disc {num + 1} of {c.DiscCount} is in."); }); } public void ApplyVideoSettings() { if (_core == null) { return; } Dictionary dictionary = ParseOptions(REPOPS1Plugin.CoreOptions.Value); bool flag = false; foreach (string item in new List(dictionary.Keys)) { if (LibretroCore.IsPolicyKey(item)) { dictionary.Remove(item); flag = true; } } if (flag) { REPOPS1Plugin.CoreOptions.Value = JoinOptions(dictionary); } _core.Scale = REPOPS1Plugin.ResolutionScale.Value; _core.Enhance = REPOPS1Plugin.Enhancements.Value; _core.Widescreen = REPOPS1Plugin.Widescreen.Value; _ = _core; OnCore(delegate(LibretroCore c) { c.ClearPolicyOverrides(); c.RefreshPolicy(); }); } public string CoreScaleValue() { if (_core == null) { return null; } foreach (string item in _core.OptionKeys()) { string text = item.ToLowerInvariant(); if (text.Contains("resolutionscale") || text.Contains("upscale") || text.Contains("internal_resolution")) { return _core.OptionValue(item); } } return null; } public void PowerOff() { if (RemoteMode) { LeaveRemote(); } else if (Loaded) { Note("Game turned off."); Unload(); if (Open) { RefreshMenu(rescan: true); } } } public List CoreOptionKeys() { if (_core == null) { return new List(); } return _core.OptionKeys(); } public string CoreOptionValue(string key) { return _core?.OptionValue(key); } public string[] CoreOptionChoices(string key) { if (_core == null) { return new string[0]; } return _core.Choices(key); } public void SetCoreOption(string key, string value) { if (_core == null) { return; } if (key.IndexOf("renderer", StringComparison.OrdinalIgnoreCase) >= 0) { Note("The renderer changes with the next game you start (Picture: Renderer). This one keeps running."); return; } OnCore(delegate(LibretroCore c) { c.SetOption(key, value); }); Dictionary dictionary = ParseOptions(REPOPS1Plugin.CoreOptions.Value); dictionary[key] = value; REPOPS1Plugin.CoreOptions.Value = JoinOptions(dictionary); } private static string JoinOptions(Dictionary options) { List list = new List(); foreach (KeyValuePair option in options) { list.Add(option.Key + "=" + option.Value); } return string.Join("; ", list); } public void ShowGameList() { if (RemoteMode) { LeaveRemote(); return; } _menuOpen = true; _confirmKey = null; RefreshMenu(rescan: true); } private void FinishDying() { if (_dying != null) { if (D3D11Host.ShutdownDone) { _dying.Dispose(); _dying = null; D3D11Host.AfterCore(); } else if (Time.unscaledTime - _dyingSince > 10f) { REPOPS1Plugin.Log.LogError((object)"The GPU core did not shut down in 10 s; leaving it loaded."); _dying = null; } } if (_dying == null && _pendingStart != null) { GameEntry pendingStart = _pendingStart; _pendingStart = null; StartGame(pendingStart); } } private void ApplyAvInfo() { RetroSystemAvInfo avInfo = _core.AvInfo; _core.AvChanged = false; _audio.SetSourceRate(avInfo.Timing.SampleRate); RetroGameGeometry geometry = avInfo.Geometry; _fitter.aspectRatio = ((geometry.AspectRatio > 0f) ? geometry.AspectRatio : ((geometry.BaseHeight != 0) ? ((float)geometry.BaseWidth / (float)geometry.BaseHeight) : 1.3333334f)); } private void ApplyLayout() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) AspectMode val = (AspectMode)((!REPOPS1Plugin.Stretch.Value) ? 3 : 0); if (_fitter.aspectMode != val) { _fitter.aspectMode = val; Fill(((Graphic)_picture).rectTransform); } } private static Dictionary ParseOptions(string text) { Dictionary dictionary = new Dictionary(); string[] array = (text ?? "").Split(';'); foreach (string text2 in array) { int num = text2.IndexOf('='); if (num > 0) { dictionary[text2.Substring(0, num).Trim()] = text2.Substring(num + 1).Trim(); } } return dictionary; } private void SaveFrame() { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown //IL_007d: 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_00f4: Unknown result type (might be due to invalid IL or missing references) Texture2D val = _video?.Texture; if ((Object)(object)val == (Object)null) { Note("No frame to save."); return; } RenderTexture temporary = RenderTexture.GetTemporary(((Texture)val).width, ((Texture)val).height, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)2); RenderTexture active = RenderTexture.active; try { Graphics.Blit((Texture)(object)val, temporary); RenderTexture.active = temporary; Texture2D val2 = new Texture2D(((Texture)val).width, ((Texture)val).height, (TextureFormat)3, false); val2.ReadPixels(new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), 0, 0); val2.Apply(); string text = Path.Combine(Paths.BepInExRootPath, "REPOPS1 frame.png"); File.WriteAllBytes(text, ImageConversion.EncodeToPNG(val2)); Object.Destroy((Object)(object)val2); REPOPS1Plugin.Log.LogInfo((object)$"Frame saved: {text} ({((Texture)val).width}x{((Texture)val).height}, {((Texture)val).graphicsFormat}, colour space {QualitySettings.activeColorSpace})."); Note("Frame saved next to the log."); } catch (Exception ex) { REPOPS1Plugin.Log.LogWarning((object)("Frame save: " + ex.Message)); } finally { RenderTexture.active = active; RenderTexture.ReleaseTemporary(temporary); } } private void BuildScreen() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Expected O, but got Unknown //IL_007f: 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_00b8: Expected O, but got Unknown //IL_00f0: Unknown result type (might be due to invalid IL or missing references) _screen = new GameObject("REPOPS1 Screen"); _screen.transform.SetParent(((Component)this).transform, false); Canvas obj = _screen.AddComponent(); obj.renderMode = (RenderMode)0; obj.sortingOrder = 32000; GameObject val = new GameObject("Background", new Type[1] { typeof(RectTransform) }); val.transform.SetParent(_screen.transform, false); RawImage obj2 = val.AddComponent(); ((Graphic)obj2).color = Color.black; ((Graphic)obj2).raycastTarget = false; Fill(((Graphic)obj2).rectTransform); GameObject val2 = new GameObject("Picture", new Type[1] { typeof(RectTransform) }); val2.transform.SetParent(val.transform, false); _picture = val2.AddComponent(); _picture.uvRect = new Rect(0f, 1f, 1f, -1f); ((Graphic)_picture).raycastTarget = false; ((Behaviour)_picture).enabled = false; Fill(((Graphic)_picture).rectTransform); _fitter = val2.AddComponent(); _fitter.aspectRatio = 1.3333334f; _fitter.aspectMode = (AspectMode)3; _screen.SetActive(false); } private static void Fill(RectTransform rt) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000c: 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_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) rt.anchorMin = Vector2.zero; rt.anchorMax = Vector2.one; Vector2 offsetMin = (rt.offsetMax = Vector2.zero); rt.offsetMin = offsetMin; } } internal sealed class EmuThread { private readonly LibretroCore _core; private readonly Thread _thread; private readonly ConcurrentQueue> _jobs = new ConcurrentQueue>(); private volatile bool _stop; public volatile bool Allow; public EmuThread(LibretroCore core) { _core = core; _thread = new Thread(Loop) { IsBackground = true, Name = "REPOPS1 Emulator", Priority = ThreadPriority.AboveNormal }; _thread.Start(); } public void Enqueue(Action job) { _jobs.Enqueue(job); } public bool Stop(int timeoutMs) { _stop = true; return _thread.Join(timeoutMs); } private void Loop() { Stopwatch stopwatch = Stopwatch.StartNew(); double num = 0.0; while (!_stop) { Action result; while (_jobs.TryDequeue(out result)) { try { result(_core); } catch (Exception ex) { REPOPS1Plugin.Log.LogError((object)("Core job failed: " + ex.Message)); } } if (!Allow || _core.ShutdownRequested) { Thread.Sleep(4); num = stopwatch.Elapsed.TotalSeconds; continue; } double fps = _core.AvInfo.Timing.Fps; double num2 = 1.0 / ((fps > 1.0) ? fps : 60.0); double totalSeconds = stopwatch.Elapsed.TotalSeconds; if (totalSeconds < num) { double num3 = (num - totalSeconds) * 1000.0; if (num3 > 2.0) { Thread.Sleep((int)(num3 - 1.5)); } while (stopwatch.Elapsed.TotalSeconds < num) { Thread.SpinWait(64); } } try { _core.Run(); } catch (Exception ex2) { REPOPS1Plugin.Log.LogError((object)("Emulator frame failed: " + ex2.Message)); break; } num += num2; if (stopwatch.Elapsed.TotalSeconds - num > 0.25) { num = stopwatch.Elapsed.TotalSeconds; } } } } internal sealed class EmuVideo { public bool Smooth; private readonly object _lock = new object(); private byte[] _buf; private int _w; private int _h; private bool _dirty; private RenderTexture _mips; public Texture2D Texture { get; private set; } public int FrameCount { get; private set; } public Texture Display { get { if (!((Object)(object)_mips != (Object)null)) { return (Texture)(object)Texture; } return (Texture)(object)_mips; } } public void OnFrame(IntPtr data, int width, int height, int pitch, int pixelFormat) { if (data == IntPtr.Zero || width <= 0 || height <= 0) { return; } lock (_lock) { Fill(data, width, height, pitch, pixelFormat); } } private unsafe void Fill(IntPtr data, int width, int height, int pitch, int pixelFormat) { if (_buf == null || width != _w || height != _h) { _buf = new byte[width * height * 4]; _w = width; _h = height; } byte* ptr = (byte*)(void*)data; fixed (byte* buf = _buf) { for (int i = 0; i < height; i++) { byte* ptr2 = buf + i * width * 4; switch (pixelFormat) { case 1: { uint* ptr4 = (uint*)(ptr + i * pitch); int num6 = 0; while (num6 < width) { uint num7 = ptr4[num6]; *ptr2 = (byte)(num7 >> 16); ptr2[1] = (byte)(num7 >> 8); ptr2[2] = (byte)num7; ptr2[3] = byte.MaxValue; num6++; ptr2 += 4; } break; } case 2: { ushort* ptr5 = (ushort*)(ptr + i * pitch); int num8 = 0; while (num8 < width) { ushort num9 = ptr5[num8]; int num10 = num9 >> 11; int num11 = (num9 >> 5) & 0x3F; int num12 = num9 & 0x1F; *ptr2 = (byte)((num10 << 3) | (num10 >> 2)); ptr2[1] = (byte)((num11 << 2) | (num11 >> 4)); ptr2[2] = (byte)((num12 << 3) | (num12 >> 2)); ptr2[3] = byte.MaxValue; num8++; ptr2 += 4; } break; } default: { ushort* ptr3 = (ushort*)(ptr + i * pitch); int num = 0; while (num < width) { ushort num2 = ptr3[num]; int num3 = (num2 >> 10) & 0x1F; int num4 = (num2 >> 5) & 0x1F; int num5 = num2 & 0x1F; *ptr2 = (byte)((num3 << 3) | (num3 >> 2)); ptr2[1] = (byte)((num4 << 3) | (num4 >> 2)); ptr2[2] = (byte)((num5 << 3) | (num5 >> 2)); ptr2[3] = byte.MaxValue; num++; ptr2 += 4; } break; } } } } _dirty = true; } public void UploadHw() { //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: 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_00e4: 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_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Expected O, but got Unknown Texture2D texture = Texture; if (D3D11Host.UpdateTexture(ref texture)) { FrameCount++; } Texture = texture; if ((Object)(object)Texture == (Object)null) { return; } ((Texture)Texture).filterMode = (FilterMode)(Smooth ? 1 : 0); if (((Texture)Texture).height < Screen.height * 2) { ((Texture)Texture).filterMode = (FilterMode)1; FreeMips(); return; } if ((Object)(object)_mips == (Object)null || ((Texture)_mips).width != ((Texture)Texture).width || ((Texture)_mips).height != ((Texture)Texture).height) { FreeMips(); _mips = new RenderTexture(((Texture)Texture).width, ((Texture)Texture).height, 0, (RenderTextureFormat)0) { useMipMap = true, autoGenerateMips = true, filterMode = (FilterMode)1, wrapMode = (TextureWrapMode)1, name = "REPOPS1 Screen (mips)" }; _mips.Create(); } Graphics.Blit((Texture)(object)Texture, _mips); } private void FreeMips() { if (!((Object)(object)_mips == (Object)null)) { _mips.Release(); Object.Destroy((Object)(object)_mips); _mips = null; } } public void Upload() { //IL_0068: 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) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Expected O, but got Unknown lock (_lock) { if (!_dirty || _buf == null) { if ((Object)(object)Texture != (Object)null) { ((Texture)Texture).filterMode = (FilterMode)(Smooth ? 1 : 0); } return; } if ((Object)(object)Texture == (Object)null) { Texture = new Texture2D(_w, _h, (TextureFormat)4, false) { name = "REPOPS1 Screen", wrapMode = (TextureWrapMode)1 }; } else if (((Texture)Texture).width != _w || ((Texture)Texture).height != _h || !((Texture)Texture).isReadable) { Texture.Reinitialize(_w, _h, (TextureFormat)4, false); } Texture.LoadRawTextureData(_buf); _dirty = false; } ((Texture)Texture).filterMode = (FilterMode)(Smooth ? 1 : 0); Texture.Apply(false); FrameCount++; } public void Dispose() { if ((Object)(object)Texture != (Object)null) { Object.Destroy((Object)(object)Texture); } Texture = null; FreeMips(); lock (_lock) { _w = (_h = 0); _buf = null; _dirty = false; } D3D11Host.ForgetTexture(); } } internal sealed class ExternalEmulator { private struct Rect { public int Left; public int Top; public int Right; public int Bottom; } private struct Point { public int X; public int Y; } private delegate bool EnumProc(IntPtr hwnd, IntPtr param); private const int VkSpace = 32; private const int VkF1 = 112; private const int VkF3 = 114; private readonly Process _process; private readonly IntPtr _repoWindow; private readonly float _startedAt; private IntPtr _window; private bool _paused; private bool _placed; private float _lastPlayed = Time.unscaledTime; private float _nextLook; private static readonly VirtualPad[] Pads = new VirtualPad[4]; private static bool _padsTried; public string Problem { get; private set; } public bool HasPicture => WindowCapture.Frames > 0; public bool Exited => _process.HasExited; private ExternalEmulator(Process p, IntPtr repo) { _process = p; _repoWindow = repo; _startedAt = Time.unscaledTime; } public static ExternalEmulator Start(string exe, string game) { IntPtr foregroundWindow = GetForegroundWindow(); try { if (!_padsTried) { _padsTried = true; for (int i = 0; i < Pads.Length; i++) { Pads[i] = VirtualPad.Create(); } } for (int j = 0; j < Pads.Length; j++) { if (Pads[j] == null || Pads[j].XInputSlot < 0) { REPOPS1Plugin.Log.LogWarning((object)$"Virtual pad {j + 1}: no XInput slot, so P{j + 1} can't play PS2."); continue; } int[] array = j switch { 1 => new int[2] { 2, 3 }, 0 => new int[1] { 1 }, _ => new int[1] { j + 2 }, }; foreach (int n in array) { BindPad(exe, n, Pads[j].XInputSlot); } } } catch (Exception ex) { REPOPS1Plugin.Log.LogWarning((object)("Virtual pad: " + ex.Message)); } Process process = Process.Start(new ProcessStartInfo(exe, "-batch -nogui -- \"" + game + "\"") { UseShellExecute = false, WorkingDirectory = (Path.GetDirectoryName(exe) ?? "") }); try { process.PriorityClass = ProcessPriorityClass.AboveNormal; } catch { } REPOPS1Plugin.Log.LogInfo((object)$"Started {Path.GetFileName(exe)} (process {process.Id}) for {Path.GetFileName(game)}."); WindowCapture.Frames = 0; WindowCapture.Failed = false; return new ExternalEmulator(process, foregroundWindow); } public void Tick(bool playing) { if (_process.HasExited) { WindowCapture.Window = IntPtr.Zero; return; } if (_window == IntPtr.Zero || !IsWindow(_window)) { _window = IntPtr.Zero; if (Time.unscaledTime >= _nextLook) { _nextLook = Time.unscaledTime + 0.25f; _window = FindWindow(_process.Id); if (_window != IntPtr.Zero) { Place(); } else if (Time.unscaledTime - _startedAt > 30f && Problem == null) { Problem = "The emulator's window never appeared."; } } } if (!(_window == IntPtr.Zero)) { if (!_placed && Time.unscaledTime - _startedAt > 3f) { Place(); } UpdateCrop(); WindowCapture.Window = _window; if (WindowCapture.Failed) { Problem = "Windows could not capture the emulator's window (see the log)."; } D3D11Host.IssueCapture(); if (playing) { _lastPlayed = Time.unscaledTime; } bool flag = Time.unscaledTime - _lastPlayed > 5f; if (HasPicture && flag != _paused) { _paused = flag; Key(32); } } } public void SaveState() { Key(112); } public void LoadState() { Key(114); } public void Stop() { WindowCapture.Window = IntPtr.Zero; D3D11Host.IssueCapture(); try { if (!_process.HasExited) { if (_window != IntPtr.Zero) { PostMessage(_window, 16u, IntPtr.Zero, IntPtr.Zero); } if (!_process.WaitForExit(3000)) { _process.Kill(); REPOPS1Plugin.Log.LogInfo((object)"The emulator did not close in 3 s: ended it."); } } } catch (Exception ex) { REPOPS1Plugin.Log.LogWarning((object)("Closing the emulator: " + ex.Message)); } finally { SetPads(null); } } public static void SetPads(PadState[] pads) { for (int i = 0; i < Pads.Length; i++) { Pads[i]?.Send((pads != null && i < pads.Length) ? pads[i] : default(PadState)); } } private static string Pcsx2Ini(string exe) { string path = Path.GetDirectoryName(exe) ?? ""; if (File.Exists(Path.Combine(path, "portable.ini")) || File.Exists(Path.Combine(path, "portable.txt"))) { return Path.Combine(path, "inis", "PCSX2.ini"); } return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal), "PCSX2", "inis", "PCSX2.ini"); } private static void BindPad(string exe, int n, int slot) { string text = Pcsx2Ini(exe); if (!File.Exists(text)) { REPOPS1Plugin.Log.LogWarning((object)("Virtual pad: PCSX2's settings not found at " + text)); return; } string text2 = $"XInput-{slot}/"; string text3 = $"[Pad{n}]"; string[] collection = new string[27] { text3, "Type = DualShock2", "Up = " + text2 + "DPadUp", "Right = " + text2 + "DPadRight", "Down = " + text2 + "DPadDown", "Left = " + text2 + "DPadLeft", "Triangle = " + text2 + "Y", "Circle = " + text2 + "B", "Cross = " + text2 + "A", "Square = " + text2 + "X", "Select = " + text2 + "Back", "Start = " + text2 + "Start", "L1 = " + text2 + "LeftShoulder", "L2 = " + text2 + "+LeftTrigger", "R1 = " + text2 + "RightShoulder", "R2 = " + text2 + "+RightTrigger", "L3 = " + text2 + "LeftStick", "R3 = " + text2 + "RightStick", "LUp = " + text2 + "-LeftY", "LRight = " + text2 + "+LeftX", "LDown = " + text2 + "+LeftY", "LLeft = " + text2 + "-LeftX", "RUp = " + text2 + "-RightY", "RRight = " + text2 + "+RightX", "RDown = " + text2 + "+RightY", "RLeft = " + text2 + "-RightX", "" }; List list = new List(); string text4 = null; bool flag = false; string[] array = File.ReadAllLines(text); foreach (string text5 in array) { string text6 = text5.Trim(); if (text6.StartsWith("[") && text6.EndsWith("]")) { text4 = text6; if (text4 == text3) { list.AddRange(collection); flag = true; } } if (!(text4 == text3)) { if (text4 == "[Pad]" && text6.StartsWith("MultitapPort1")) { list.Add("MultitapPort1 = true"); } else if ((text4 == "[InputSources]" && text6.StartsWith("XInput ")) || (text4 == "[InputSources]" && text6.StartsWith("XInput="))) { list.Add("XInput = true"); } else { list.Add(text5); } } } if (!flag) { list.AddRange(collection); } File.WriteAllLines(text, list); REPOPS1Plugin.Log.LogInfo((object)$"PCSX2 pad {n} set to virtual pad (XInput {slot})."); } private void Place() { _placed = Time.unscaledTime - _startedAt > 3f; long num = GetWindowLongPtr(_window, -16).ToInt64(); num &= -13565953; num |= 0x80000000u; SetWindowLongPtr(_window, -16, new IntPtr(num)); IntPtr after = ((_repoWindow != IntPtr.Zero) ? _repoWindow : new IntPtr(1)); SetWindowPos(_window, after, 0, 0, Screen.width, Screen.height, 48u); if (_repoWindow != IntPtr.Zero) { SetForegroundWindow(_repoWindow); } } private void UpdateCrop() { if (GetClientRect(_window, out var rect)) { Point p = default(Point); ClientToScreen(_window, ref p); if (DwmGetWindowAttribute(_window, 9, out var value, Marshal.SizeOf()) != 0) { GetWindowRect(_window, out value); } WindowCapture.CropX = Math.Max(0, p.X - value.Left); WindowCapture.CropY = Math.Max(0, p.Y - value.Top); WindowCapture.CropW = rect.Right - rect.Left; WindowCapture.CropH = rect.Bottom - rect.Top; } } private void Key(int vk) { if (!(_window == IntPtr.Zero)) { uint num = MapVirtualKey((uint)vk, 0u); PostMessage(_window, 256u, new IntPtr(vk), new IntPtr(1 | (num << 16))); PostMessage(_window, 257u, new IntPtr(vk), new IntPtr((int)(1 | (num << 16)) | -1073741824)); } } private static IntPtr FindWindow(int pid) { IntPtr best = IntPtr.Zero; long bestArea = 0L; EnumWindows(delegate(IntPtr h, IntPtr _) { GetWindowThreadProcessId(h, out var pid2); if (pid2 != pid || !IsWindowVisible(h)) { return true; } if (!GetWindowRect(h, out var rect)) { return true; } long num = (long)(rect.Right - rect.Left) * (long)(rect.Bottom - rect.Top); if (num > bestArea && num > 40000) { best = h; bestArea = num; } return true; }, IntPtr.Zero); return best; } [DllImport("user32")] private static extern IntPtr GetForegroundWindow(); [DllImport("user32")] private static extern bool SetForegroundWindow(IntPtr hwnd); [DllImport("user32")] private static extern bool EnumWindows(EnumProc proc, IntPtr param); [DllImport("user32")] private static extern uint GetWindowThreadProcessId(IntPtr hwnd, out int pid); [DllImport("user32")] private static extern bool IsWindowVisible(IntPtr hwnd); [DllImport("user32")] private static extern bool IsWindow(IntPtr hwnd); [DllImport("user32")] private static extern bool GetWindowRect(IntPtr hwnd, out Rect rect); [DllImport("user32")] private static extern bool GetClientRect(IntPtr hwnd, out Rect rect); [DllImport("user32")] private static extern bool ClientToScreen(IntPtr hwnd, ref Point p); [DllImport("user32", CharSet = CharSet.Unicode)] private static extern int GetWindowText(IntPtr hwnd, StringBuilder text, int max); [DllImport("user32")] private static extern IntPtr GetWindowLongPtr(IntPtr hwnd, int index); [DllImport("user32")] private static extern IntPtr SetWindowLongPtr(IntPtr hwnd, int index, IntPtr value); [DllImport("user32")] private static extern bool SetWindowPos(IntPtr hwnd, IntPtr after, int x, int y, int w, int h, uint flags); [DllImport("user32")] private static extern bool PostMessage(IntPtr hwnd, uint msg, IntPtr w, IntPtr l); [DllImport("user32")] private static extern uint MapVirtualKey(uint code, uint type); [DllImport("dwmapi")] private static extern int DwmGetWindowAttribute(IntPtr hwnd, int attr, out Rect value, int size); } internal sealed class GameEntry { public string Path; public string Title; public string CorePath; public string System; } internal static class GameLibrary { private sealed class CoreInfo { public string Path; public string Name; public HashSet Extensions; } private const int MaxGames = 1000; private const int MaxDepth = 4; private static readonly string[] IndexExtensions = new string[4] { ".cue", ".m3u", ".ccd", ".gdi" }; private static readonly Dictionary CoreCache = new Dictionary(StringComparer.OrdinalIgnoreCase); private static readonly Regex DiscName = new Regex("^(.*?)\\s*\\(Disc (\\d+)\\)(.*)$", RegexOptions.IgnoreCase); public static List Scan(out string problem) { problem = null; string problem2; List cores = LoadCores(out problem2); List list = new List(); string text = Clean(REPOPS1Plugin.GamePath.Value); if (text.Length > 0 && File.Exists(text)) { Add(list, text, cores); } List list2 = GameRoots(); foreach (string item in list2) { Walk(item, 0, list, cores); } string text2 = ((list2.Count > 0) ? list2[0] : ""); list = (from g in list.GroupBy((GameEntry g) => g.Path, StringComparer.OrdinalIgnoreCase) select g.First()).ToList(); list = (from g in JoinDiscs(list, cores) orderby g.System select g).ThenBy((GameEntry g) => g.Title, StringComparer.OrdinalIgnoreCase).ToList(); if (list.Count == 0) { problem = problem2 ?? ((text2.Length == 0 && text.Length == 0) ? "Set GamesFolder (your own games) and CoresFolder (libretro cores) in the config." : "No games found that a core in CoresFolder can play."); } return list; } private static List JoinDiscs(List games, List cores) { List list = new List(); foreach (IGrouping item in games.GroupBy(delegate(GameEntry g) { Match match2 = DiscName.Match(g.Title); return (!match2.Success) ? ("\0" + g.Path) : (Path.GetDirectoryName(g.Path) + "|" + g.CorePath + "|" + (match2.Groups[1].Value + match2.Groups[3].Value).Trim()); }, StringComparer.OrdinalIgnoreCase)) { List list2 = item.ToList(); CoreInfo coreInfo = cores.FirstOrDefault((CoreInfo c) => string.Equals(c.Path, list2[0].CorePath, StringComparison.OrdinalIgnoreCase)); if (list2.Count < 2 || item.Key[0] == '\0' || coreInfo == null || !coreInfo.Extensions.Contains("m3u")) { list.AddRange(list2); continue; } list2 = list2.OrderBy((GameEntry g) => int.Parse(DiscName.Match(g.Title).Groups[2].Value)).ToList(); Match match = DiscName.Match(list2[0].Title); string text = (match.Groups[1].Value + match.Groups[3].Value).Trim(); try { string text2 = Path.Combine(Paths.ConfigPath, "REPOPS1", "discs"); Directory.CreateDirectory(text2); string path = Path.Combine(text2, string.Concat(string.Concat(text.Split(Path.GetInvalidFileNameChars())), ".m3u")); string text3 = string.Join("\n", list2.Select((GameEntry g) => g.Path)) + "\n"; if (!File.Exists(path) || File.ReadAllText(path) != text3) { File.WriteAllText(path, text3); } list.Add(new GameEntry { Path = path, Title = text, CorePath = list2[0].CorePath, System = list2[0].System }); } catch (Exception ex) { REPOPS1Plugin.Log.LogWarning((object)("Couldn't join the discs of " + text + ": " + ex.Message)); list.AddRange(list2); } } return list; } private static void Walk(string dir, int depth, List games, List cores) { string[] files; try { files = Directory.GetFiles(dir); } catch (Exception) { return; } HashSet hashSet = new HashSet(from path in files where IndexExtensions.Contains(Path.GetExtension(path).ToLowerInvariant()) select Path.GetFileNameWithoutExtension(path), StringComparer.OrdinalIgnoreCase); string[] array = files; foreach (string f in array) { if (games.Count >= 1000) { return; } string value = Path.GetExtension(f).ToLowerInvariant(); if (IndexExtensions.Contains(value) || hashSet.Count <= 0 || !hashSet.Any((string n) => Path.GetFileNameWithoutExtension(f).StartsWith(n, StringComparison.OrdinalIgnoreCase))) { Add(games, f, cores); } } if (depth >= 4) { return; } try { array = Directory.GetDirectories(dir); for (int num = 0; num < array.Length; num++) { Walk(array[num], depth + 1, games, cores); } } catch (Exception) { } } private static void Add(List games, string file, List cores) { string text = Path.GetExtension(file).TrimStart('.').ToLowerInvariant(); if (text.Length != 0) { CoreInfo coreInfo = PickCore(text, cores, file); if (coreInfo != null) { games.Add(new GameEntry { Path = file, Title = Path.GetFileNameWithoutExtension(file), CorePath = coreInfo.Path, System = coreInfo.Name }); } } } private static CoreInfo PickCore(string ext, List cores, string gamePath = null) { if (gamePath != null) { HashSet hashSet = new HashSet(Path.GetFullPath(gamePath).Split('\\', '/'), StringComparer.OrdinalIgnoreCase); foreach (CoreInfo core in cores) { string fileName = Path.GetFileName(Path.GetDirectoryName(core.Path) ?? ""); if (fileName.Length > 0 && hashSet.Contains(fileName) && core.Extensions.Contains(ext)) { return core; } } } string[] array = (REPOPS1Plugin.CoreForExtension.Value ?? "").Split(';'); foreach (string text in array) { int num = text.IndexOf('='); if (num > 0 && text.Substring(0, num).Trim().TrimStart('.') .Equals(ext, StringComparison.OrdinalIgnoreCase)) { string want = text.Substring(num + 1).Trim(); CoreInfo coreInfo = cores.FirstOrDefault((CoreInfo c) => Path.GetFileName(c.Path).IndexOf(want, StringComparison.OrdinalIgnoreCase) >= 0); if (coreInfo != null) { return coreInfo; } } } return cores.FirstOrDefault((CoreInfo c) => c.Extensions.Contains(ext)); } private static List LoadCores(out string problem) { problem = null; List list = new List(); List list2 = new List(); string text = Clean(REPOPS1Plugin.CoresFolder.Value); if (text.Length > 0 && Directory.Exists(text)) { list2.AddRange(Directory.GetFiles(text, "*_libretro.dll", SearchOption.AllDirectories).OrderBy((string p) => p, StringComparer.OrdinalIgnoreCase)); } string text2 = Clean(REPOPS1Plugin.CorePath.Value); if (text2.Length > 0 && File.Exists(text2)) { list2.Add(text2); } foreach (string item in list2) { CoreInfo info = ReadCore(item); if (info != null && list.All((CoreInfo c) => !c.Path.Equals(info.Path, StringComparison.OrdinalIgnoreCase))) { list.Add(info); } } if (list.Count == 0) { problem = "No libretro cores found: put *_libretro.dll files in CoresFolder."; } return list; } private static CoreInfo ReadCore(string path) { if (CoreCache.TryGetValue(path, out var value)) { return value; } CoreInfo coreInfo = null; IntPtr intPtr = Kernel32.LoadLibraryW(path); if (intPtr == IntPtr.Zero) { REPOPS1Plugin.Log.LogWarning((object)("Could not load core " + path)); return null; } try { IntPtr procAddress = Kernel32.GetProcAddress(intPtr, "retro_get_system_info"); if (procAddress != IntPtr.Zero) { Marshal.GetDelegateForFunctionPointer(procAddress)(out var info); IEnumerable collection = from e in (Marshal.PtrToStringAnsi(info.ValidExtensions) ?? "").Split('|') select e.Trim().TrimStart('.').ToLowerInvariant() into e where e.Length > 0 select e; coreInfo = new CoreInfo { Path = path, Name = (Marshal.PtrToStringAnsi(info.LibraryName) ?? Path.GetFileNameWithoutExtension(path)), Extensions = new HashSet(collection) }; REPOPS1Plugin.Log.LogInfo((object)("Core " + coreInfo.Name + ": plays " + string.Join(", ", coreInfo.Extensions))); } } catch (Exception ex) { REPOPS1Plugin.Log.LogWarning((object)("Core " + path + ": " + ex.Message)); } finally { Kernel32.FreeLibrary(intPtr); } CoreCache[path] = coreInfo; return coreInfo; } public static string MissingTrack(string gamePath) { if (!gamePath.EndsWith(".cue", StringComparison.OrdinalIgnoreCase)) { return null; } try { string path = Path.GetDirectoryName(gamePath) ?? ""; string[] array = File.ReadAllLines(gamePath); for (int i = 0; i < array.Length; i++) { string text = array[i].Trim(); if (text.StartsWith("FILE ", StringComparison.OrdinalIgnoreCase)) { int num = text.IndexOf('"'); int num2 = ((num >= 0) ? text.IndexOf('"', num + 1) : (-1)); string text2 = ((num2 > num) ? text.Substring(num + 1, num2 - num - 1) : text.Substring(5).Split(' ')[0]); if (!File.Exists(Path.Combine(path, text2))) { return text2; } } } } catch (Exception) { } return null; } public static List GameRoots() { List list = new List(); string[] array = (REPOPS1Plugin.GamesFolder.Value ?? "").Split(';'); for (int i = 0; i < array.Length; i++) { string text = Clean(array[i]); if (text.Length > 0 && Directory.Exists(text)) { list.Add(text); } } return list; } public static string RootOf(string gamePath) { string fullPath = Path.GetFullPath(gamePath); foreach (string item in GameRoots()) { string text = Path.GetFullPath(item).TrimEnd('\\', '/') + Path.DirectorySeparatorChar; if (fullPath.StartsWith(text, StringComparison.OrdinalIgnoreCase)) { return text.TrimEnd(Path.DirectorySeparatorChar); } } return Path.GetDirectoryName(fullPath) ?? ""; } public static string SystemFolder(GameEntry g) { string text = Path.GetDirectoryName(g?.CorePath ?? "") ?? ""; string fileName = Path.GetFileName(text); string b = Clean(REPOPS1Plugin.CoresFolder.Value).TrimEnd('\\', '/'); if (fileName.Length == 0 || string.Equals(text.TrimEnd('\\', '/'), b, StringComparison.OrdinalIgnoreCase)) { return g?.System ?? ""; } return fileName; } private static string Clean(string s) { return (s ?? "").Trim().Trim('"'); } } internal sealed class GameShelf { public static readonly string[] Tabs = new string[7] { "All games", "Recently played", "Favourites", "USA", "Europe", "Japan", "Friends' games" }; public int Tab; private float _shown; private Texture2D _grid; private Texture2D _sky; private Texture2D _glow; private GUIStyle _title; private GUIStyle _boxTitle; private GUIStyle _chip; private GUIStyle _tab; private GUIStyle _tabOn; private GUIStyle _hint; private GUIStyle _hintLeft; private GUIStyle _clock; private readonly Dictionary _covers = new Dictionary(); private Material _boxMat; private readonly HashSet _realCover = new HashSet(); private static readonly Dictionary FolderCache = new Dictionary(StringComparer.OrdinalIgnoreCase); public static int CoverVersion { get; private set; } public List Filter(List all) { List list = new List(); foreach (MenuItem item in all) { string text = item.Local?.Path; if (Tab switch { 1 => item.Join || (text != null && PlayStats.Get(text).LastPlayed > 0), 2 => text != null && PlayStats.Get(text).Favourite, 3 => Region(item.Title) == "USA", 4 => Region(item.Title) == "Europe", 5 => Region(item.Title) == "Japan", 6 => item.Join || item.RemoteIndex >= 0, _ => true, }) { list.Add(item); } } if (Tab == 1) { list.Sort((MenuItem a, MenuItem b) => Last(b).CompareTo(Last(a))); } return list; } private static long Last(MenuItem m) { if (!m.Join) { if (m.Local == null) { return 0L; } return PlayStats.Get(m.Local.Path).LastPlayed; } return long.MaxValue; } public static string Region(string title) { string text = title ?? ""; if (text.Contains("(USA") || text.Contains("USA)")) { return "USA"; } if (text.Contains("(Europe") || text.Contains("Europe)") || text.Contains("(PAL")) { return "Europe"; } if (text.Contains("(Japan") || text.Contains("Japan)")) { return "Japan"; } return ""; } private static string CleanTitle(string t) { StringBuilder stringBuilder = new StringBuilder(); int num = 0; StringBuilder stringBuilder2 = new StringBuilder(); string text = t ?? ""; foreach (char c in text) { switch (c) { case '(': num++; stringBuilder2.Clear(); continue; case ')': if (num > 0) { num--; string text2 = stringBuilder2.ToString(); if (text2.StartsWith("Disc", StringComparison.OrdinalIgnoreCase)) { stringBuilder.Append('(').Append(text2).Append(')'); } continue; } break; } if (num > 0) { stringBuilder2.Append(c); } else { stringBuilder.Append(c); } } return stringBuilder.ToString().Replace(" ", " ").Trim(); } public void Draw(List view, int sel, string error, string runningTitle) { //IL_0067: 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_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Expected O, but got Unknown //IL_00d1: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: 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_0124: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0108: 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_01ed: 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) Setup(); float num = Screen.width; float num2 = Screen.height; _shown = Mathf.Lerp(_shown, (float)sel, 1f - Mathf.Exp((0f - Time.unscaledDeltaTime) * 12f)); if (Mathf.Abs(_shown - (float)sel) > 30f) { _shown = sel; } GUI.DrawTexture(new Rect(0f, 0f, num, num2), (Texture)(object)_sky); DrawGrid(num, num2); GUI.Label(new Rect(num * 0.04f, num2 * 0.035f, num * 0.3f, 50f), "GAME ROOM console", _title); float num3 = num * 0.27f; Rect val2 = default(Rect); for (int i = 0; i < Tabs.Length; i++) { Vector2 val = _tab.CalcSize(new GUIContent(Tabs[i])); ((Rect)(ref val2))..ctor(num3, num2 * 0.045f, val.x + 34f, 38f); if (i == Tab) { Color color = GUI.color; GUI.color = Color.white; GUI.DrawTexture(val2, (Texture)(object)_glow); GUI.color = color; } GUI.Label(val2, Tabs[i], (i == Tab) ? _tabOn : _tab); num3 += ((Rect)(ref val2)).width + 8f; } if (view.Count == 0) { GUI.Label(new Rect(num * 0.1f, num2 * 0.4f, num * 0.8f, num2 * 0.2f), error ?? ((Tab == 0) ? "No games." : "Nothing here yet. Q / E or L1 / R1: other tabs."), _hint); Hints(num, num2); return; } MenuItem menuItem = view[Mathf.Clamp(sel, 0, view.Count - 1)]; GUI.Label(new Rect(0f, num2 * 0.15f, num, 56f), "" + Esc(CleanTitle(menuItem.Title)) + "", _title); DrawChips(menuItem, num, num2 * 0.235f, runningTitle); List list = new List(); for (int j = 0; j < view.Count; j++) { if (Mathf.Abs((float)j - _shown) < 8f) { list.Add(j); } } list.Sort((int a, int b) => Mathf.Abs((float)b - _shown).CompareTo(Mathf.Abs((float)a - _shown))); foreach (int item in list) { DrawBox(view[item], (float)item - _shown, item == sel, num, num2); } Hints(num, num2); Clock(num, num2); } private void DrawBox(MenuItem m, float d, bool chosen, float w, float h) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Invalid comparison between Unknown and I4 //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Expected O, but got Unknown //IL_01d7: Unknown result type (might be due to invalid IL or missing references) //IL_0248: Unknown result type (might be due to invalid IL or missing references) //IL_028e: Unknown result type (might be due to invalid IL or missing references) //IL_0373: Unknown result type (might be due to invalid IL or missing references) //IL_038c: Unknown result type (might be due to invalid IL or missing references) //IL_03b0: Unknown result type (might be due to invalid IL or missing references) //IL_03df: Unknown result type (might be due to invalid IL or missing references) //IL_0408: Unknown result type (might be due to invalid IL or missing references) //IL_0437: Unknown result type (might be due to invalid IL or missing references) //IL_04cc: Unknown result type (might be due to invalid IL or missing references) if ((int)Event.current.type == 7) { bool real; Texture2D val = Cover(m, out real); float num = Mathf.Abs(d); float num2 = h * 0.4f; float num3 = num2 * Mathf.Clamp((float)((Texture)val).width / (float)Mathf.Max(1, ((Texture)val).height), 0.6f, 1.4f); float turn = Mathf.Clamp(d, -1f, 1f) * 62f * (MathF.PI / 180f); float num4 = Mathf.Min(num, 1f) * num3 * 0.92f + Mathf.Max(num - 1f, 0f) * num3 * 0.36f; float cx = Mathf.Sign(d) * num4; float cz = Mathf.Min(num, 1f) * num3 * 0.55f; float horizon = h * 0.5f; float floor = h * 0.78f; float num5 = Mathf.Clamp01(1.25f - num * 0.13f); if ((Object)(object)_boxMat == (Object)null) { _boxMat = new Material(Shader.Find("Sprites/Default") ?? Shader.Find("UI/Default")); } _boxMat.mainTexture = (Texture)(object)val; _boxMat.SetPass(0); GL.PushMatrix(); GL.LoadOrtho(); GL.Begin(7); for (int i = 0; i < 12; i++) { float num6 = (float)i / 12f; float num7 = (float)(i + 1) / 12f; Project(cx, cz, turn, num3, (num6 - 0.5f) * num3, 1400f, w, horizon, floor, out var sx, out var bottom, out var k); Project(cx, cz, turn, num3, (num7 - 0.5f) * num3, 1400f, w, horizon, floor, out var sx2, out var bottom2, out var k2); float yDown = bottom - num2 * k; float yDown2 = bottom2 - num2 * k2; GL.Color(new Color(1f, 1f, 1f, num5)); Vert(sx, bottom, num6, 0f, w, h); Vert(sx2, bottom2, num7, 0f, w, h); Vert(sx2, yDown2, num7, 1f, w, h); Vert(sx, yDown, num6, 1f, w, h); GL.Color(new Color(1f, 1f, 1f, 0.28f * num5)); Vert(sx, bottom, num6, 0f, w, h); Vert(sx2, bottom2, num7, 0f, w, h); GL.Color(new Color(1f, 1f, 1f, 0f)); Vert(sx2, bottom2 + num2 * k2 * 0.55f, num7, 0.55f, w, h); Vert(sx, bottom + num2 * k * 0.55f, num6, 0.55f, w, h); } GL.End(); GL.PopMatrix(); if (chosen) { Project(cx, cz, turn, num3, (0f - num3) / 2f, 1400f, w, horizon, floor, out var sx3, out var bottom3, out var k3); Project(cx, cz, turn, num3, num3 / 2f, 1400f, w, horizon, floor, out var sx4, out var _, out var _); Rect val2 = default(Rect); ((Rect)(ref val2))..ctor(sx3 - 6f, bottom3 - num2 * k3 - 6f, sx4 - sx3 + 12f, num2 * k3 + 12f); Color color = GUI.color; GUI.color = new Color(1f, 0.35f, 0.95f, 0.9f); GUI.DrawTexture(new Rect(((Rect)(ref val2)).x, ((Rect)(ref val2)).y, ((Rect)(ref val2)).width, 3f), (Texture)(object)Texture2D.whiteTexture); GUI.DrawTexture(new Rect(((Rect)(ref val2)).x, ((Rect)(ref val2)).yMax - 3f, ((Rect)(ref val2)).width, 3f), (Texture)(object)Texture2D.whiteTexture); GUI.DrawTexture(new Rect(((Rect)(ref val2)).x, ((Rect)(ref val2)).y, 3f, ((Rect)(ref val2)).height), (Texture)(object)Texture2D.whiteTexture); GUI.DrawTexture(new Rect(((Rect)(ref val2)).xMax - 3f, ((Rect)(ref val2)).y, 3f, ((Rect)(ref val2)).height), (Texture)(object)Texture2D.whiteTexture); GUI.color = color; } if (!real && num < 0.6f) { Project(cx, cz, turn, num3, 0f, 1400f, w, horizon, floor, out var sx5, out var bottom5, out var k5); _boxTitle.fontSize = Mathf.Max(14, (int)(num2 * k5 * 0.07f)); GUI.Label(new Rect(sx5 - num3 * k5 * 0.4f, bottom5 - num2 * k5 * 0.72f, num3 * k5 * 0.8f, num2 * k5 * 0.45f), Esc(CleanTitle(m.Title)), _boxTitle); } } } private static void Project(float cx, float cz, float turn, float boxW, float lx, float f, float w, float horizon, float floor, out float sx, out float bottom, out float k) { float num = cx + lx * Mathf.Cos(turn); float num2 = cz + lx * Mathf.Sin(turn); k = f / (f + num2); sx = w / 2f + num * k; bottom = horizon + (floor - horizon) * k; } private static void Vert(float x, float yDown, float u, float v, float w, float h) { GL.TexCoord2(u, v); GL.Vertex3(x / w, 1f - yDown / h, 0f); } private void Clock(float w, float h) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) string s = ((PhotonNetwork.LocalPlayer != null) ? PhotonNetwork.LocalPlayer.NickName : ""); GUI.Label(new Rect(w * 0.66f, h * 0.9f, w * 0.31f, 30f), "● " + Esc(s) + " " + DateTime.Now.ToString("HH:mm") + "", _clock); } private void DrawGrid(float w, float h) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) float num = h * 0.5f; GUI.DrawTexture(new Rect(0f, num, w, h - num), (Texture)(object)_grid); } private void Hints(float w, float h) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) bool flag = false; Enumerator enumerator = Gamepad.all.GetEnumerator(); try { while (enumerator.MoveNext()) { Gamepad current = enumerator.Current; if (((InputControl)current).layout.IndexOf("DualSense", StringComparison.OrdinalIgnoreCase) >= 0 || ((InputControl)current).layout.IndexOf("DualShock", StringComparison.OrdinalIgnoreCase) >= 0) { flag = true; } } } finally { ((IDisposable)enumerator/*cast due to .constrained prefix*/).Dispose(); } string text = (flag ? "✕" : "A"); string text2 = (flag ? "○" : "B"); string text3 = (flag ? "△" : "Y"); GUI.Label(new Rect(w * 0.03f, h * 0.9f, w * 0.65f, 30f), "" + text + " Play " + text2 + " Back " + text3 + " / F Favourite L1 R1 / Q E Tabs ◀ ▶ Choose Esc Room", _hintLeft); } public Texture2D Cover(MenuItem m, out bool real) { //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0093: 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_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Expected O, but got Unknown string key = ((m.Local != null) ? m.Local.Path : ("remote:" + m.Title)); if (_covers.TryGetValue(key, out var value) && (Object)(object)value != (Object)null) { real = _realCover.Contains(key); return value; } value = null; string text = ((m.Local != null) ? FindCoverFile(m.Local.Path) : null); if (text != null) { try { value = new Texture2D(2, 2) { name = "REPOPS1 Cover", wrapMode = (TextureWrapMode)1, filterMode = (FilterMode)2 }; if (!ImageConversion.LoadImage(value, File.ReadAllBytes(text))) { Object.Destroy((Object)(object)value); value = null; } } catch (Exception) { value = null; } } real = (Object)(object)value != (Object)null; if (real) { _realCover.Add(key); } else { value = MakeCover(m.Title); if (m.Local != null) { CoverDownload.Want(m.Local, delegate { _covers.Remove(key); FolderCache.Clear(); CoverVersion++; }); } } _covers[key] = value; return value; } public static string CoversFolder(string gamePath) { return Path.Combine(GameLibrary.RootOf(gamePath), "Covers"); } private static string FindCoverFile(string gamePath) { string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(gamePath); string fullPath = Path.GetFullPath(GameLibrary.RootOf(gamePath) + Path.DirectorySeparatorChar); string directoryName = Path.GetDirectoryName(gamePath); while (!string.IsNullOrEmpty(directoryName)) { string[] array = new string[2] { directoryName, Path.Combine(directoryName, "Covers") }; for (int i = 0; i < array.Length; i++) { string text = ExactFile(array[i], fileNameWithoutExtension); if (text != null) { return text; } } if (!Path.GetFullPath(directoryName + Path.DirectorySeparatorChar).StartsWith(fullPath, StringComparison.OrdinalIgnoreCase) || fullPath.Length <= 4) { break; } directoryName = Path.GetDirectoryName(directoryName); } return null; } private static string ExactFile(string folder, string name) { if (!FolderCache.TryGetValue(folder, out var value)) { try { value = (Directory.Exists(folder) ? Directory.GetFiles(folder) : new string[0]); } catch (Exception) { value = new string[0]; } FolderCache[folder] = value; } string[] array = value; foreach (string text in array) { switch (Path.GetExtension(text).ToLowerInvariant()) { case ".png": case ".jpg": case ".jpeg": if (string.Equals(Path.GetFileNameWithoutExtension(text), name, StringComparison.Ordinal)) { return text; } break; } } return null; } public void Refresh() { CoverVersion++; foreach (Texture2D value in _covers.Values) { if ((Object)(object)value != (Object)null) { Object.Destroy((Object)(object)value); } } _covers.Clear(); _realCover.Clear(); FolderCache.Clear(); } private void DrawChips(MenuItem m, float w, float y, string runningTitle) { //IL_011b: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Expected O, but got Unknown //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_018a: Unknown result type (might be due to invalid IL or missing references) //IL_0194: Unknown result type (might be due to invalid IL or missing references) //IL_01a0: Unknown result type (might be due to invalid IL or missing references) List list = new List(); string text = Region(m.Title); if (text.Length > 0) { list.Add(text); } if (!string.IsNullOrEmpty(m.System)) { list.Add(m.System); } if (m.Title.IndexOf("(Disc", StringComparison.OrdinalIgnoreCase) >= 0) { list.Add("multi-disc"); } if (m.Join) { list.Add("join the game"); } if (m.Running) { list.Add("running now"); } if (m.Local != null) { PlayStats.Entry entry = PlayStats.Get(m.Local.Path); if (entry.Seconds >= 60) { list.Add("played " + FormatTime(entry.Seconds)); } if (entry.LastPlayed > 0) { list.Add(FormatDay(entry.LastPlayed)); } if (entry.Favourite) { list.Add("favourite"); } } float num = 0f; float[] array = new float[list.Count]; for (int i = 0; i < list.Count; i++) { array[i] = _chip.CalcSize(new GUIContent(list[i])).x + 30f; num += array[i] + 10f; } float num2 = (w - num) / 2f; Color color = GUI.color; for (int j = 0; j < list.Count; j++) { Rect val = new Rect(num2, y, array[j], 30f); GUI.color = new Color(0.36f, 0.22f, 0.75f, 0.85f); GUI.DrawTexture(val, (Texture)(object)_glow); GUI.color = color; GUI.Label(val, list[j], _chip); num2 += array[j] + 10f; } } private static Texture2D MakeCover(string title) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_0191: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Unknown result type (might be due to invalid IL or missing references) //IL_01a3: Unknown result type (might be due to invalid IL or missing references) //IL_01aa: Unknown result type (might be due to invalid IL or missing references) //IL_01b3: Expected O, but got Unknown //IL_006c: 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) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0075: 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_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_0131: 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_013d: 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) float num = (float)(Hash(title) % 1000) / 1000f; Color val = Color.HSVToRGB(num, 0.65f, 0.55f); Color val2 = Color.HSVToRGB(Mathf.Repeat(num + 0.12f, 1f), 0.8f, 0.18f); Color32[] array = (Color32[])(object)new Color32[34400]; for (int i = 0; i < 200; i++) { for (int j = 0; j < 172; j++) { float num2 = (float)i / 200f; Color val3 = Color.Lerp(val2, val, num2); float num3 = Mathf.Abs(Mathf.Sin(((float)j + (float)i * 0.6f) * 0.05f + num * 6f)); val3 = Color.Lerp(val3, Color.white, (num3 > 0.985f) ? 0.25f : 0f); if (j < 12) { val3 = Color.Lerp(val3, Color.black, 0.55f); } if (j < 2 || j >= 170 || i < 2 || i >= 198) { ((Color)(ref val3))..ctor(0.95f, 0.95f, 1f); } else if (j >= 166 || i < 6 || i >= 194 || (j >= 12 && j < 15)) { val3 = Color.Lerp(val3, Color.white, 0.35f); } array[i * 172 + j] = Color32.op_Implicit(val3); } } Texture2D val4 = new Texture2D(172, 200, (TextureFormat)4, false) { name = "REPOPS1 Cover", wrapMode = (TextureWrapMode)1 }; val4.SetPixels32(array); val4.Apply(false, true); return val4; } private static int Hash(string s) { int num = 23; string text = s ?? ""; foreach (char c in text) { num = num * 31 + c; } return num & 0x7FFFFFFF; } private void Setup() { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Expected O, but got Unknown //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Expected O, but got Unknown //IL_009b: 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_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Expected O, but got Unknown //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00d3: Expected O, but got Unknown //IL_00de: 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_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Expected O, but got Unknown //IL_010c: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Expected O, but got Unknown //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Expected O, but got Unknown //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Unknown result type (might be due to invalid IL or missing references) //IL_0165: Unknown result type (might be due to invalid IL or missing references) //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_01a3: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_01a5: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: Unknown result type (might be due to invalid IL or missing references) //IL_01ac: Unknown result type (might be due to invalid IL or missing references) //IL_01ad: Unknown result type (might be due to invalid IL or missing references) //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_01d3: Unknown result type (might be due to invalid IL or missing references) //IL_01f7: Unknown result type (might be due to invalid IL or missing references) //IL_0211: Unknown result type (might be due to invalid IL or missing references) //IL_0225: Unknown result type (might be due to invalid IL or missing references) if (_title == null) { _title = new GUIStyle(GUI.skin.label) { fontSize = 36, alignment = (TextAnchor)4, richText = true }; _boxTitle = new GUIStyle(GUI.skin.label) { alignment = (TextAnchor)4, wordWrap = true, richText = true, fontStyle = (FontStyle)1 }; _chip = new GUIStyle(GUI.skin.label) { fontSize = 15, alignment = (TextAnchor)4, richText = true }; _tab = new GUIStyle(GUI.skin.label) { fontSize = 17, alignment = (TextAnchor)4, richText = true }; _tabOn = new GUIStyle(_tab) { fontStyle = (FontStyle)1 }; _hint = new GUIStyle(GUI.skin.label) { fontSize = 16, alignment = (TextAnchor)4, richText = true, wordWrap = true }; _hintLeft = new GUIStyle(_hint) { alignment = (TextAnchor)3, wordWrap = false }; _clock = new GUIStyle(_hint) { alignment = (TextAnchor)5, wordWrap = false }; GUIStyleState normal = _hintLeft.normal; Color textColor = (_clock.normal.textColor = Color.white); normal.textColor = textColor; GUIStyleState normal2 = _title.normal; GUIStyleState normal3 = _boxTitle.normal; GUIStyleState normal4 = _chip.normal; Color val = (_hint.normal.textColor = Color.white); Color val2 = (normal4.textColor = val); textColor = (normal3.textColor = val2); normal2.textColor = textColor; _tab.normal.textColor = new Color(0.8f, 0.75f, 0.95f); _tabOn.normal.textColor = new Color(0.12f, 0.05f, 0.2f); _sky = Gradient(new Color(0.07f, 0.03f, 0.14f), new Color(0.2f, 0.06f, 0.26f)); _grid = MakeGrid(); _glow = MakeRounded(); } } private static Texture2D Gradient(Color top, Color bottom) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0025: 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) Texture2D val = new Texture2D(1, 64, (TextureFormat)4, false) { wrapMode = (TextureWrapMode)1, name = "REPOPS1 Sky" }; for (int i = 0; i < 64; i++) { val.SetPixel(0, i, Color.Lerp(bottom, top, (float)i / 63f)); } val.Apply(false, true); return val; } private static Texture2D MakeGrid() { //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_0162: 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_0174: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_0182: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Expected O, but got Unknown //IL_010a: 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_0112: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0117: 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_0126: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) Color32[] array = (Color32[])(object)new Color32[98304]; Color val = default(Color); ((Color)(ref val))..ctor(1f, 0.2f, 0.85f); for (int i = 0; i < 192; i++) { float num = 1f - (float)i / 192f; float num2 = Mathf.Clamp01(1.15f - num); for (int j = 0; j < 512; j++) { float num3 = ((float)j - 256f) / 256f / Mathf.Lerp(1f, 0.12f, num); bool num4 = Mathf.Abs(num3 * 9f - Mathf.Round(num3 * 9f)) < 0.05f / Mathf.Lerp(1f, 0.35f, num); float num5 = 1f / Mathf.Lerp(1f, 0.08f, num); bool flag = Mathf.Abs(num5 * 1.2f - Mathf.Round(num5 * 1.2f)) < 0.06f * num5 * 0.5f; Color val2 = (Color)((num4 || flag) ? Color.Lerp(Color.clear, val, num2) : new Color(0.15f, 0.02f, 0.2f, 0.9f * num2)); array[i * 512 + j] = Color32.op_Implicit(val2); } } Texture2D val3 = new Texture2D(512, 192, (TextureFormat)4, false) { wrapMode = (TextureWrapMode)1, name = "REPOPS1 Grid", filterMode = (FilterMode)1 }; val3.SetPixels32(array); val3.Apply(false, true); return val3; } private static Texture2D MakeRounded() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown //IL_00bc: Unknown result type (might be due to invalid IL or missing references) Texture2D val = new Texture2D(64, 64, (TextureFormat)4, false) { wrapMode = (TextureWrapMode)1, name = "REPOPS1 Round" }; for (int i = 0; i < 64; i++) { for (int j = 0; j < 64; j++) { float num = Mathf.Max(0f, Mathf.Abs((float)j - 32f + 0.5f) - 32f + 14f) / 14f; float num2 = Mathf.Max(0f, Mathf.Abs((float)i - 32f + 0.5f) - 32f + 14f) / 14f; float num3 = Mathf.Clamp01(1f - Mathf.Sqrt(num * num + num2 * num2)); val.SetPixel(j, i, new Color(1f, 1f, 1f, num3)); } } val.Apply(false, true); return val; } private static string Esc(string s) { return (s ?? "").Replace("<", "‹").Replace(">", "›"); } private static string FormatTime(long seconds) { if (seconds < 3600) { return $"{seconds / 60} min"; } return $"{seconds / 3600} h {seconds % 3600 / 60} min"; } private static string FormatDay(long ticks) { DateTime date = new DateTime(ticks).Date; if (date == DateTime.Today) { return "today"; } if (date == DateTime.Today.AddDays(-1.0)) { return "yesterday"; } return date.ToString("d MMM", CultureInfo.InvariantCulture); } } internal static class PlayStats { internal sealed class Entry { public long LastPlayed; public long Seconds; public bool Favourite; } private static Dictionary _all; private static float _dirtySince = -1f; private static string FilePath => Path.Combine(Paths.ConfigPath, "REPOPS1", "library.txt"); public static Entry Get(string path) { Load(); string key = (path ?? "").ToLowerInvariant(); if (!_all.TryGetValue(key, out var value)) { value = (_all[key] = new Entry()); } return value; } public static void Played(string path, float seconds) { Entry entry = Get(path); entry.LastPlayed = DateTime.Now.Ticks; entry.Seconds += (long)seconds; MarkDirty(); } public static void ToggleFavourite(string path) { Entry entry = Get(path); entry.Favourite = !entry.Favourite; MarkDirty(); Save(); } private static void MarkDirty() { if (_dirtySince < 0f) { _dirtySince = Time.unscaledTime; } } public static void Tick() { if (_dirtySince >= 0f && Time.unscaledTime - _dirtySince > 30f) { Save(); } } public static void Save() { if (_all == null) { return; } _dirtySince = -1f; try { Directory.CreateDirectory(Path.GetDirectoryName(FilePath)); StringBuilder stringBuilder = new StringBuilder(); foreach (KeyValuePair item in _all) { if (item.Value.LastPlayed > 0 || item.Value.Favourite) { stringBuilder.Append(item.Key).Append('\t').Append(item.Value.LastPlayed) .Append('\t') .Append(item.Value.Seconds) .Append('\t') .Append(item.Value.Favourite ? 1 : 0) .Append('\n'); } } File.WriteAllText(FilePath, stringBuilder.ToString()); } catch (Exception ex) { REPOPS1Plugin.Log.LogWarning((object)("Could not save the game library: " + ex.Message)); } } private static void Load() { if (_all != null) { return; } _all = new Dictionary(); try { if (!File.Exists(FilePath)) { return; } string[] array = File.ReadAllLines(FilePath); for (int i = 0; i < array.Length; i++) { string[] array2 = array[i].Split('\t'); if (array2.Length >= 4) { long.TryParse(array2[1], out var result); long.TryParse(array2[2], out var result2); _all[array2[0]] = new Entry { LastPlayed = result, Seconds = result2, Favourite = (array2[3] == "1") }; } } } catch (Exception ex) { REPOPS1Plugin.Log.LogWarning((object)("Could not read the game library: " + ex.Message)); } } } internal sealed class LibretroCore : IDisposable { public Action Video; public Action AudioBatch; public Action AudioSample; public Func InputState; public Action Message; public bool HwWanted; public int Scale = 1; public bool Enhance; public bool Widescreen; private IntPtr _ctxReset; private IntPtr _ctxDestroy; private bool _shutDown; private IntPtr _lib; private bool _gameLoaded; private bool _initDone; private readonly List _allocs = new List(); private IntPtr _systemDir; private IntPtr _saveDir; private IntPtr _gameData; private readonly Dictionary _options = new Dictionary(); private readonly Dictionary _choices = new Dictionary(); private readonly Dictionary _defaults = new Dictionary(); private readonly Dictionary _overrides; private readonly Dictionary _optionValuePtrs = new Dictionary(); private bool _optionsDirty; private RetroEnvironmentFn _envCb; private RetroVideoRefreshFn _videoCb; private RetroAudioSampleFn _audioCb; private RetroAudioSampleBatchFn _audioBatchCb; private RetroInputPollFn _pollCb; private RetroInputStateFn _stateCb; private RetroLogFn _logCb; public static string LastCoreError; public static volatile bool GpuFailed; private readonly HashSet _unanswered = new HashSet(); private RetroVoidFn _deinit; private RetroVoidFn _run; private RetroVoidFn _unloadGame; private RetroVoidFn _reset; private RetroSerializeSizeFn _serializeSize; private RetroSerializeFn _serialize; private RetroSerializeFn _unserialize; private RetroSetEjectFn _setEject; private RetroGetUintFn _getDiscIndex; private RetroGetUintFn _getDiscCount; private RetroSetIndexFn _setDiscIndex; public int PixelFormat { get; private set; } public RetroSystemAvInfo AvInfo { get; private set; } public bool AvChanged { get; set; } public bool ShutdownRequested { get; private set; } public string LibraryName { get; private set; } public bool HwActive { get; private set; } public int DiscCount { get { if (_getDiscCount != null) { return (int)_getDiscCount(); } return 0; } } public int DiscIndex { get { if (_getDiscIndex != null) { return (int)_getDiscIndex(); } return 0; } } private static void OnCoreLog(int level, IntPtr fmt, IntPtr a1, IntPtr a2, IntPtr a3, IntPtr a4, IntPtr a5, IntPtr a6) { try { string text = Format(Str(fmt) ?? "", new IntPtr[6] { a1, a2, a3, a4, a5, a6 }).TrimEnd(); if (text.Length != 0 && (level >= 1 || REPOPS1Plugin.CoreDebugLog.Value)) { string text2 = "Core log: " + text; if (level >= 3) { REPOPS1Plugin.Log.LogError((object)text2); LastCoreError = text; } if (text.IndexOf("there will be no picture", StringComparison.OrdinalIgnoreCase) >= 0 || text.IndexOf("no device could be created", StringComparison.OrdinalIgnoreCase) >= 0) { GpuFailed = true; } else if (level == 2) { REPOPS1Plugin.Log.LogWarning((object)text2); } else { REPOPS1Plugin.Log.LogInfo((object)text2); } } } catch { } } public LibretroCore(Dictionary optionOverrides) { _overrides = optionOverrides ?? new Dictionary(); } public void Load(string corePath, string gamePath, string systemDir, string saveDir) { if (!File.Exists(corePath)) { throw new FileNotFoundException("Core not found", corePath); } if (!File.Exists(gamePath)) { throw new FileNotFoundException("Game not found", gamePath); } _lib = Kernel32.LoadLibraryW(corePath); if (_lib == IntPtr.Zero) { throw new Win32Exception(Marshal.GetLastWin32Error(), "LoadLibrary failed for " + corePath); } if (Export("retro_api_version")() != 1) { throw new InvalidOperationException("Unsupported libretro API version"); } _systemDir = Utf8(systemDir); _saveDir = Utf8(saveDir); _envCb = OnEnvironment; _videoCb = OnVideo; _audioCb = OnAudioSample; _audioBatchCb = OnAudioBatch; _pollCb = delegate { }; _stateCb = OnInputState; Export("retro_set_environment")(Marshal.GetFunctionPointerForDelegate(_envCb)); Export("retro_set_video_refresh")(Marshal.GetFunctionPointerForDelegate(_videoCb)); Export("retro_set_audio_sample")(Marshal.GetFunctionPointerForDelegate(_audioCb)); Export("retro_set_audio_sample_batch")(Marshal.GetFunctionPointerForDelegate(_audioBatchCb)); Export("retro_set_input_poll")(Marshal.GetFunctionPointerForDelegate(_pollCb)); Export("retro_set_input_state")(Marshal.GetFunctionPointerForDelegate(_stateCb)); _deinit = Export("retro_deinit"); _run = Export("retro_run"); _unloadGame = Export("retro_unload_game"); _reset = Export("retro_reset"); _serializeSize = Export("retro_serialize_size"); _serialize = Export("retro_serialize"); _unserialize = Export("retro_unserialize"); Export("retro_init")(); _initDone = true; Export("retro_get_system_info")(out var info); LibraryName = Marshal.PtrToStringAnsi(info.LibraryName) + " " + Marshal.PtrToStringAnsi(info.LibraryVersion); RetroGameInfo game = new RetroGameInfo { Path = Utf8(gamePath) }; if (info.NeedFullpath == 0) { byte[] array = File.ReadAllBytes(gamePath); _gameData = Marshal.AllocHGlobal(array.Length); Marshal.Copy(array, 0, _gameData, array.Length); game.Data = _gameData; game.Size = (UIntPtr)(ulong)array.Length; } if (!Export("retro_load_game")(ref game)) { throw new InvalidOperationException("The core could not load the game (check the file and the BIOS folder)."); } _gameLoaded = true; Export("retro_get_system_av_info")(out var info2); AvInfo = info2; AvChanged = true; for (uint num = 0u; num < 5; num++) { Export("retro_set_controller_port_device")(num, 1u); } } public void Run() { _run(); } public void Reset() { _reset(); } public int NextDisc() { int discCount = DiscCount; if (discCount < 2) { return -1; } uint num = (uint)((DiscIndex + 1) % discCount); _setEject(ejected: true); bool num2 = _setDiscIndex(num); _setEject(ejected: false); if (!num2) { return -1; } return (int)num; } private void ReadDiskControl(IntPtr data) { IntPtr[] array = new IntPtr[5]; Marshal.Copy(data, array, 0, 5); if (Array.IndexOf(array, IntPtr.Zero) < 0) { _setEject = Marshal.GetDelegateForFunctionPointer(array[0]); _getDiscIndex = Marshal.GetDelegateForFunctionPointer(array[2]); _setDiscIndex = Marshal.GetDelegateForFunctionPointer(array[3]); _getDiscCount = Marshal.GetDelegateForFunctionPointer(array[4]); } } public byte[] SaveState() { int num = (int)(ulong)_serializeSize(); if (num <= 0) { return null; } IntPtr intPtr = Marshal.AllocHGlobal(num); try { if (!_serialize(intPtr, (UIntPtr)(ulong)num)) { return null; } byte[] array = new byte[num]; Marshal.Copy(intPtr, array, 0, num); return array; } finally { Marshal.FreeHGlobal(intPtr); } } public bool LoadState(byte[] state) { IntPtr intPtr = Marshal.AllocHGlobal(state.Length); try { Marshal.Copy(state, 0, intPtr, state.Length); return _unserialize(intPtr, (UIntPtr)(ulong)state.Length); } finally { Marshal.FreeHGlobal(intPtr); } } public string FindOption(params string[] parts) { foreach (string key in _options.Keys) { bool flag = true; foreach (string value in parts) { flag &= key.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0; } if (flag) { return key; } } return null; } public void RefreshPolicy() { foreach (string item in new List(_options.Keys)) { if (!_overrides.ContainsKey(item) && item.IndexOf("renderer", StringComparison.OrdinalIgnoreCase) < 0) { string text = _options[item]; _options[item] = (_defaults.TryGetValue(item, out var value) ? value : text); ApplyPolicy(item, Choices(item)); if (_options[item] != text) { _optionValuePtrs.Remove(item); _optionsDirty = true; } } } } public List OptionKeys() { return new List(_options.Keys); } private static bool IsScaleKey(string k) { if (!k.Contains("resolutionscale") && !k.Contains("resolution_scale") && !k.Contains("internal_resolution")) { return k.Contains("upscale_multiplier"); } return true; } public static bool IsPolicyKey(string key) { string text = (key ?? "").ToLowerInvariant(); if (!IsScaleKey(text) && !text.Contains("widescreen") && !text.EndsWith("blending_accuracy") && !text.EndsWith("anisotropic_filtering") && (!text.Contains("display") || !text.Contains("aspectratio")) && !text.EndsWith("truecolor") && !text.EndsWith("pgxpenable")) { return text.EndsWith("pgxptexturecorrection"); } return true; } public void ClearPolicyOverrides() { foreach (string item in new List(_overrides.Keys)) { if (IsPolicyKey(item)) { _overrides.Remove(item); _optionValuePtrs.Remove(item); _optionsDirty = true; } } } public string[] Choices(string key) { if (key == null || !_choices.TryGetValue(key, out var value)) { return new string[0]; } return value; } public string OptionValue(string key) { if (key != null) { if (!_overrides.TryGetValue(key, out var value)) { if (!_options.TryGetValue(key, out var value2)) { return null; } return value2; } return value; } return null; } public void SetOption(string key, string value) { if (key != null && value != null && !(OptionValue(key) == value)) { _overrides[key] = value; _optionValuePtrs.Remove(key); _optionsDirty = true; } } public void ContextReset() { if (_ctxReset != IntPtr.Zero) { Marshal.GetDelegateForFunctionPointer(_ctxReset)(); } } public void ShutdownOnRenderThread() { try { if (_ctxDestroy != IntPtr.Zero) { Marshal.GetDelegateForFunctionPointer(_ctxDestroy)(); } if (_gameLoaded) { _unloadGame(); } if (_initDone) { _deinit(); } } catch (Exception ex) { REPOPS1Plugin.Log.LogError((object)("Core shutdown failed: " + ex.Message)); } _gameLoaded = (_initDone = false); _shutDown = true; } public void Dispose() { try { if (!_shutDown && !HwActive) { if (_gameLoaded) { _unloadGame(); } if (_initDone) { _deinit(); } } } catch (Exception ex) { REPOPS1Plugin.Log.LogError((object)("Core shutdown failed: " + ex.Message)); } _gameLoaded = (_initDone = false); if (_lib != IntPtr.Zero) { Kernel32.FreeLibrary(_lib); _lib = IntPtr.Zero; } foreach (IntPtr alloc in _allocs) { Marshal.FreeHGlobal(alloc); } _allocs.Clear(); _optionValuePtrs.Clear(); if (_gameData != IntPtr.Zero) { Marshal.FreeHGlobal(_gameData); _gameData = IntPtr.Zero; } } private static string Format(string f, IntPtr[] args) { StringBuilder stringBuilder = new StringBuilder(); int num = 0; for (int i = 0; i < f.Length; i++) { if (f[i] != '%' || i + 1 >= f.Length) { stringBuilder.Append(f[i]); continue; } int j; for (j = i + 1; j < f.Length && "-+ #0123456789.lhzjtLI".IndexOf(f[j]) >= 0; j++) { } if (j >= f.Length) { break; } char c = f[j]; i = j; if (c == '%') { stringBuilder.Append('%'); continue; } IntPtr intPtr = ((num < args.Length) ? args[num++] : IntPtr.Zero); switch (c) { case 's': stringBuilder.Append((intPtr == IntPtr.Zero) ? "(null)" : Marshal.PtrToStringAnsi(intPtr)); break; case 'd': case 'i': stringBuilder.Append((int)intPtr.ToInt64()); break; case 'u': stringBuilder.Append((uint)intPtr.ToInt64()); break; case 'X': case 'x': stringBuilder.Append(((uint)intPtr.ToInt64()).ToString((c == 'x') ? "x" : "X")); break; case 'c': stringBuilder.Append((char)(intPtr.ToInt64() & 0xFF)); break; case 'e': case 'f': case 'g': stringBuilder.Append(BitConverter.Int64BitsToDouble(intPtr.ToInt64()).ToString("0.###", CultureInfo.InvariantCulture)); break; case 'p': stringBuilder.Append("0x").Append(intPtr.ToInt64().ToString("X")); break; default: stringBuilder.Append('%').Append(c); break; } } return stringBuilder.ToString(); } private T Export(string name) where T : Delegate { IntPtr procAddress = Kernel32.GetProcAddress(_lib, name); if (procAddress == IntPtr.Zero) { throw new EntryPointNotFoundException("Core is missing " + name); } return Marshal.GetDelegateForFunctionPointer(procAddress); } private IntPtr Utf8(string s) { byte[] bytes = Encoding.UTF8.GetBytes(s ?? ""); IntPtr intPtr = Marshal.AllocHGlobal(bytes.Length + 1); Marshal.Copy(bytes, 0, intPtr, bytes.Length); Marshal.WriteByte(intPtr, bytes.Length, 0); _allocs.Add(intPtr); return intPtr; } private static string Str(IntPtr p) { if (!(p == IntPtr.Zero)) { return Marshal.PtrToStringAnsi(p); } return null; } private bool OnEnvironment(uint cmd, IntPtr data) { try { switch (cmd & 0xFFFCFFFFu) { case 3u: Marshal.WriteByte(data, 1); return true; case 9u: Marshal.WriteIntPtr(data, _systemDir); return true; case 31u: Marshal.WriteIntPtr(data, _saveDir); return true; case 10u: { int num = Marshal.ReadInt32(data); if (num < 0 || num > 2) { return false; } PixelFormat = num; return true; } case 52u: return false; case 16u: ReadVariables(data); return true; case 15u: return GetVariable(data); case 17u: Marshal.WriteByte(data, _optionsDirty ? ((byte)1) : ((byte)0)); _optionsDirty = false; return true; case 32u: AvInfo = Marshal.PtrToStructure(data); AvChanged = true; return true; case 37u: { RetroSystemAvInfo avInfo = AvInfo; avInfo.Geometry = Marshal.PtrToStructure(data); AvInfo = avInfo; AvChanged = true; return true; } case 6u: case 60u: { string text = Str(Marshal.ReadIntPtr(data)); REPOPS1Plugin.Log.LogInfo((object)("Core: " + text)); Message?.Invoke(text); return true; } case 51u: return true; case 27u: if (_logCb == null) { _logCb = OnCoreLog; } Marshal.WriteIntPtr(data, Marshal.GetFunctionPointerForDelegate(_logCb)); return true; case 59u: Marshal.WriteInt32(data, 1); return true; case 57u: Marshal.WriteInt32(data, 1); return true; case 13u: case 58u: ReadDiskControl(data); return true; case 7u: ShutdownRequested = true; return true; case 8u: case 11u: return true; case 14u: return AcceptHwRender(data); case 41u: if (!HwActive) { return false; } Marshal.WriteIntPtr(data, D3D11Host.Interface); return true; case 56u: if (!HwWanted || !D3D11Host.Available) { return false; } Marshal.WriteInt32(data, 7); return true; default: if (_unanswered.Add(cmd)) { REPOPS1Plugin.Log.LogInfo((object)string.Format("Core asked for environment command {0}{1}: not supported.", cmd & 0xFFFCFFFFu, ((cmd & 0x10000) != 0) ? " (experimental)" : "")); } return false; } } catch (Exception ex) { REPOPS1Plugin.Log.LogError((object)$"Environment command {cmd} failed: {ex.Message}"); return false; } } private void ReadVariables(IntPtr data) { int num = Marshal.SizeOf(); IntPtr ptr = data; while (true) { RetroVariable retroVariable = Marshal.PtrToStructure(ptr); if (retroVariable.Key == IntPtr.Zero) { break; } string text = Str(retroVariable.Key); string text2 = Str(retroVariable.Value) ?? ""; int num2 = text2.IndexOf(';'); string text3 = ((num2 >= 0) ? text2.Substring(num2 + 1).Trim() : text2); int num3 = text3.IndexOf('|'); _options[text] = ((num3 >= 0) ? text3.Substring(0, num3) : text3); _choices[text] = text3.Split('|'); _defaults[text] = _options[text]; if (!_overrides.ContainsKey(text)) { ApplyPolicy(text, text3.Split('|')); } REPOPS1Plugin.Log.LogInfo((object)("Core option " + text + " = " + (_overrides.TryGetValue(text, out var value) ? value : _options[text]) + " [" + text3 + "]")); ptr += num; } _optionsDirty = true; } private void ApplyPolicy(string key, string[] choices) { bool flag = HwWanted && D3D11Host.Available; string text = key.ToLowerInvariant(); string text2 = null; if (text.EndsWith("multitapmode")) { text2 = Pick(new string[1] { "Port1Only" }); } else if (text.Contains("renderer")) { text2 = (flag ? Pick(new string[4] { "D3D11", "Direct3D 11", "d3d11", "Hardware" }) : Pick(new string[3] { "Software", "Software (SW)", "software" })); } else if (flag && IsScaleKey(text)) { int num = 0; string[] array = choices; foreach (string text3 in array) { Match match = Regex.Match(text3, "\\d+"); if (match.Success && int.TryParse(match.Value, out var result) && result <= Math.Max(1, Scale) && result > num) { num = result; text2 = text3; } } } else if (flag && text.Contains("gpu") && text.Contains("usethread")) { text2 = Pick(new string[1] { "false" }); } else if (flag && text.EndsWith("blending_accuracy")) { text2 = Pick(new string[2] { "High", "Medium" }); } else if (flag && text.EndsWith("anisotropic_filtering")) { text2 = Pick(new string[2] { "16x", "8x" }); } else if (flag && Enhance && (text.EndsWith("truecolor") || text.EndsWith("pgxpenable") || text.EndsWith("pgxptexturecorrection"))) { text2 = Pick(new string[1] { "true" }); } else if (text.Contains("sw_renderer_threads") || text.Contains("software_threads") || text.Contains("renderer_threads")) { string text4 = Math.Max(2, Math.Min(8, Environment.ProcessorCount / 2)).ToString(); text2 = Pick(new string[1] { text4 }); } else if (text.Contains("widescreen")) { text2 = ((!Widescreen) ? Pick(new string[3] { "false", "disabled", "off" }) : (Pick(new string[2] { "true", "enabled" }) ?? Array.Find(choices, (string x) => x.IndexOf("16:9", StringComparison.Ordinal) >= 0))); } else if (text.Contains("display") && text.Contains("aspectratio") && Widescreen) { text2 = Pick(new string[1] { "16:9" }); } if (text2 != null) { _options[key] = text2; } string Pick(params string[] wanted) { foreach (string value in wanted) { string[] array2 = choices; foreach (string text5 in array2) { if (text5.Equals(value, StringComparison.OrdinalIgnoreCase)) { return text5; } } } return null; } } private bool AcceptHwRender(IntPtr cb) { if (!HwWanted || !D3D11Host.Available) { return false; } uint num = (uint)Marshal.ReadInt32(cb, 0); uint num2 = (uint)Marshal.ReadInt32(cb, 36); uint num3 = (uint)Marshal.ReadInt32(cb, 40); REPOPS1Plugin.Log.LogInfo((object)$"Core asks for a GPU context: type {num}, version {num2}.{num3}, depth {Marshal.ReadByte(cb, 32)}, stencil {Marshal.ReadByte(cb, 33)}."); if (num != 7 || (num2 != 0 && num2 != 11)) { REPOPS1Plugin.Log.LogInfo((object)$"Core asked for GPU context {num} v{num2}: not offered (only Direct3D 11)."); return false; } _ctxReset = Marshal.ReadIntPtr(cb, 8); _ctxDestroy = Marshal.ReadIntPtr(cb, 48); HwActive = true; REPOPS1Plugin.Log.LogInfo((object)("Core renders with Direct3D 11 (upscale " + Scale + "x).")); return true; } private bool GetVariable(IntPtr data) { RetroVariable structure = Marshal.PtrToStructure(data); string text = Str(structure.Key); if (text == null) { return false; } if (!_overrides.TryGetValue(text, out var value) && !_options.TryGetValue(text, out value)) { return false; } if (!_optionValuePtrs.TryGetValue(text, out var value2)) { value2 = Utf8(value); _optionValuePtrs[text] = value2; } structure.Value = value2; Marshal.StructureToPtr(structure, data, fDeleteOld: false); return true; } private void OnVideo(IntPtr data, uint width, uint height, UIntPtr pitch) { try { if (HwActive) { D3D11Host.OnFrame(data, (int)width, (int)height); } else { Video?.Invoke(data, (int)width, (int)height, (int)(uint)pitch); } } catch (Exception ex) { REPOPS1Plugin.Log.LogError((object)("Video callback: " + ex.Message)); } } private void OnAudioSample(short left, short right) { try { AudioSample?.Invoke(left, right); } catch (Exception ex) { REPOPS1Plugin.Log.LogError((object)("Audio callback: " + ex.Message)); } } private UIntPtr OnAudioBatch(IntPtr data, UIntPtr frames) { try { AudioBatch?.Invoke(data, (int)(uint)frames); } catch (Exception ex) { REPOPS1Plugin.Log.LogError((object)("Audio callback: " + ex.Message)); } return frames; } private short OnInputState(uint port, uint device, uint index, uint id) { try { return InputState?.Invoke(port, device, index, id) ?? 0; } catch { return 0; } } } internal static class Retro { public const uint ApiVersion = 1u; public const uint DeviceJoypad = 1u; public const uint DeviceAnalog = 5u; public const uint JoypadMask = 256u; public const uint AnalogButtonIndex = 2u; public const uint PadB = 0u; public const uint PadY = 1u; public const uint PadSelect = 2u; public const uint PadStart = 3u; public const uint PadUp = 4u; public const uint PadDown = 5u; public const uint PadLeft = 6u; public const uint PadRight = 7u; public const uint PadA = 8u; public const uint PadX = 9u; public const uint PadL = 10u; public const uint PadR = 11u; public const uint PadL2 = 12u; public const uint PadR2 = 13u; public const uint PadL3 = 14u; public const uint PadR3 = 15u; public const int Pixel0RGB1555 = 0; public const int PixelXRGB8888 = 1; public const int PixelRGB565 = 2; public const uint EnvGetCanDupe = 3u; public const uint EnvSetMessage = 6u; public const uint EnvShutdown = 7u; public const uint EnvSetPerformanceLevel = 8u; public const uint EnvGetSystemDirectory = 9u; public const uint EnvSetPixelFormat = 10u; public const uint EnvSetInputDescriptors = 11u; public const uint EnvSetHwRender = 14u; public const uint EnvGetVariable = 15u; public const uint EnvSetVariables = 16u; public const uint EnvGetVariableUpdate = 17u; public const uint EnvGetSaveDirectory = 31u; public const uint EnvSetSystemAvInfo = 32u; public const uint EnvSetGeometry = 37u; public const uint EnvGetCoreOptionsVersion = 52u; public const uint EnvGetMessageInterfaceVersion = 59u; public const uint EnvSetMessageExt = 60u; public const uint EnvSetDiskControlInterface = 13u; public const uint EnvGetDiskControlInterfaceVersion = 57u; public const uint EnvSetDiskControlExtInterface = 58u; public const uint EnvGetHwRenderInterface = 41u; public const uint EnvGetPreferredHwRender = 56u; public const uint EnvGetLogInterface = 27u; public const uint EnvGetInputBitmasks = 51u; public const uint EnvFlagMask = 196608u; } internal struct RetroSystemInfo { public IntPtr LibraryName; public IntPtr LibraryVersion; public IntPtr ValidExtensions; public byte NeedFullpath; public byte BlockExtract; } internal struct RetroGameGeometry { public uint BaseWidth; public uint BaseHeight; public uint MaxWidth; public uint MaxHeight; public float AspectRatio; } internal struct RetroSystemTiming { public double Fps; public double SampleRate; } internal struct RetroSystemAvInfo { public RetroGameGeometry Geometry; public RetroSystemTiming Timing; } internal struct RetroGameInfo { public IntPtr Path; public IntPtr Data; public UIntPtr Size; public IntPtr Meta; } internal struct RetroVariable { public IntPtr Key; public IntPtr Value; } internal struct RetroMessage { public IntPtr Msg; public uint Frames; } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] internal delegate bool RetroEnvironmentFn(uint cmd, IntPtr data); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void RetroVideoRefreshFn(IntPtr data, uint width, uint height, UIntPtr pitch); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void RetroAudioSampleFn(short left, short right); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate UIntPtr RetroAudioSampleBatchFn(IntPtr data, UIntPtr frames); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void RetroInputPollFn(); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void RetroLogFn(int level, IntPtr fmt, IntPtr a1, IntPtr a2, IntPtr a3, IntPtr a4, IntPtr a5, IntPtr a6); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate short RetroInputStateFn(uint port, uint device, uint index, uint id); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void RetroVoidFn(); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate uint RetroApiVersionFn(); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void RetroSetCallbackFn(IntPtr callback); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void RetroGetSystemInfoFn(out RetroSystemInfo info); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void RetroGetSystemAvInfoFn(out RetroSystemAvInfo info); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] internal delegate bool RetroLoadGameFn(ref RetroGameInfo game); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate void RetroSetControllerPortDeviceFn(uint port, uint device); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] internal delegate bool RetroSetEjectFn([MarshalAs(UnmanagedType.U1)] bool ejected); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate uint RetroGetUintFn(); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] internal delegate bool RetroSetIndexFn(uint index); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] internal delegate UIntPtr RetroSerializeSizeFn(); [UnmanagedFunctionPointer(CallingConvention.Cdecl)] [return: MarshalAs(UnmanagedType.U1)] internal delegate bool RetroSerializeFn(IntPtr data, UIntPtr size); internal static class Kernel32 { [DllImport("kernel32", CharSet = CharSet.Unicode, SetLastError = true)] public static extern IntPtr LoadLibraryW(string path); [DllImport("kernel32", BestFitMapping = false, CharSet = CharSet.Ansi, SetLastError = true)] public static extern IntPtr GetProcAddress(IntPtr module, string name); [DllImport("kernel32", SetLastError = true)] public static extern bool FreeLibrary(IntPtr module); [DllImport("kernel32", SetLastError = true)] public static extern bool VirtualProtect(IntPtr address, UIntPtr size, uint newProtect, out uint oldProtect); } internal static class PS1Identity { private static readonly FieldRef SteamIdRef = AccessTools.FieldRefAccess("steamID"); private static readonly FieldRef ChatActiveRef = AccessTools.FieldRefAccess("chatActive"); public static bool ChatActive { get { if ((Object)(object)ChatManager.instance != (Object)null) { return ChatActiveRef.Invoke(ChatManager.instance); } return false; } } public static string SteamIdOfActor(int actor) { try { foreach (PlayerAvatar item in SemiFunc.PlayerGetAll()) { if ((Object)(object)item != (Object)null && (Object)(object)item.photonView != (Object)null && item.photonView.OwnerActorNr == actor) { return SteamIdRef.Invoke(item); } } } catch (Exception) { } return null; } } internal sealed class PS1Presence : MonoBehaviour { public const string Key = "repops1"; public const string PadKey = "repops1.pad"; public const string WantKey = "repops1.want"; private int _sentWant = -2; public const int None = 0; public const int InRoom = 1; public const int Playing = 2; public const int PlayingRemote = 3; private int _sent = -1; private int _sentPad = -2; private float _sentAt; private readonly Dictionary _tags = new Dictionary(); private readonly HashSet _seen = new HashSet(); private readonly List _gone = new List(); private static string _insideText = ""; private static float _insideAt = -1f; public static int WantOf(int actor) { Room currentRoom = PhotonNetwork.CurrentRoom; Player val = ((currentRoom != null) ? currentRoom.GetPlayer(actor, false) : null); if (val != null && val.CustomProperties != null && ((Dictionary)(object)val.CustomProperties).TryGetValue((object)"repops1.want", out object value) && value is int) { return (int)value; } return -1; } public static int PadOf(Player p) { if (p != null && p.CustomProperties != null && ((Dictionary)(object)p.CustomProperties).TryGetValue((object)"repops1.pad", out object value) && value is int) { return (int)value; } return -1; } public static string PadHolder(int pad) { EmuSession instance = EmuSession.Instance; if ((Object)(object)instance != (Object)null && EmuSession.Open && instance.LocalPad == pad) { Player localPlayer = PhotonNetwork.LocalPlayer; return Clean(((localPlayer != null) ? localPlayer.NickName : null) ?? "You"); } if (!PhotonNetwork.InRoom) { return null; } Player[] playerListOthers = PhotonNetwork.PlayerListOthers; foreach (Player val in playerListOthers) { if (StateOf(val) >= 2 && PadOf(val) == pad) { return Clean(val.NickName); } } return null; } public static int StateOf(Player p) { if (p != null && p.CustomProperties != null && ((Dictionary)(object)p.CustomProperties).TryGetValue((object)"repops1", out object value) && value is int) { return (int)value; } return 0; } public static string InsideList() { if (!PhotonNetwork.InRoom) { return ""; } if (Time.unscaledTime - _insideAt < 0.5f) { return _insideText; } _insideAt = Time.unscaledTime; StringBuilder stringBuilder = new StringBuilder(); Player[] playerList = PhotonNetwork.PlayerList; foreach (Player val in playerList) { int num = StateOf(val); if (num != 0) { if (stringBuilder.Length > 0) { stringBuilder.Append('\n'); } stringBuilder.Append(Clean(val.NickName)).Append((num >= 2) ? " - playing" : " - inside"); } } return _insideText = stringBuilder.ToString(); } private void Update() { //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Expected O, but got Unknown //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Expected O, but got Unknown //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Expected O, but got Unknown //IL_00d0: Expected O, but got Unknown int num = ((!EmuSession.Open) ? (PS1Room.Inside ? 1 : 0) : (EmuSession.RemoteMode ? 3 : ((!EmuSession.Instance.HasGame) ? 1 : 2))); int num2 = ((EmuSession.Open && (Object)(object)EmuSession.Instance != (Object)null) ? EmuSession.Instance.LocalPad : (-1)); int wantedPad = EmuSession.WantedPad; if (PhotonNetwork.InRoom && (num != _sent || num2 != _sentPad || wantedPad != _sentWant || Time.unscaledTime - _sentAt > 30f)) { Player localPlayer = PhotonNetwork.LocalPlayer; Hashtable val = new Hashtable(); ((Dictionary)val).Add((object)"repops1", (object)num); ((Dictionary)val).Add((object)"repops1.pad", (object)num2); ((Dictionary)val).Add((object)"repops1.want", (object)wantedPad); localPlayer.SetCustomProperties(val, (Hashtable)null, (WebFlags)null); _sentWant = wantedPad; _sent = num; _sentPad = num2; _sentAt = Time.unscaledTime; } if (!PhotonNetwork.InRoom) { _sent = -1; _sentPad = -2; _sentWant = -2; } UpdateTags(); } private void UpdateTags() { //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: 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_0116: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) Camera main = Camera.main; HashSet seen = _seen; seen.Clear(); if ((Object)(object)main != (Object)null && PhotonNetwork.InRoom) { foreach (PlayerAvatar item in SemiFunc.PlayerGetAll()) { if ((Object)(object)item == (Object)null || (Object)(object)item.photonView == (Object)null || item.photonView.IsMine) { continue; } int ownerActorNr = item.photonView.OwnerActorNr; if (StateOf(item.photonView.Owner) >= 2) { seen.Add(ownerActorNr); if (!_tags.TryGetValue(ownerActorNr, out var value) || (Object)(object)value == (Object)null) { value = (_tags[ownerActorNr] = MakeTag()); } value.text = "Playing Now"; ((Component)value).transform.position = ((Component)item).transform.position + Vector3.up * 2.2f; ((Component)value).transform.rotation = Quaternion.LookRotation(((Component)value).transform.position - ((Component)main).transform.position); } } } List gone = _gone; gone.Clear(); foreach (KeyValuePair tag in _tags) { if (!seen.Contains(tag.Key)) { gone.Add(tag.Key); } } foreach (int item2 in gone) { if ((Object)(object)_tags[item2] != (Object)null) { Object.Destroy((Object)(object)((Component)_tags[item2]).gameObject); } _tags.Remove(item2); } } private static TextMesh MakeTag() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0023: 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) GameObject val = new GameObject("REPOPS1_Tag"); Object.DontDestroyOnLoad((Object)val); ((Object)val).hideFlags = (HideFlags)61; Font builtinResource = Resources.GetBuiltinResource("LegacyRuntime.ttf"); TextMesh val2 = val.AddComponent(); val2.font = builtinResource; ((Renderer)val.GetComponent()).sharedMaterial = builtinResource.material; val2.characterSize = 0.03f; val2.fontSize = 64; val2.color = new Color(0.35f, 1f, 0.45f); val2.anchor = (TextAnchor)4; val2.alignment = (TextAlignment)1; return val2; } private static string Clean(string s) { return (s ?? "").Replace("<", "").Replace(">", "").Replace("\n", " ") .Trim(); } } internal sealed class PS1Room : MonoBehaviour { private sealed class GameBox { public MenuItem Item; public Transform T; public Transform Home; public Vector3 HomePos; public Quaternion HomeRot; } private const float Lift = 400f; private const float Half = 7f; private const float Height = 4.2f; private static readonly List NoKeys = new List(); private static readonly FieldRef SpawnedRef = AccessTools.FieldRefAccess("spawned"); private static readonly FieldRef SpawnPosRef = AccessTools.FieldRefAccess("spawnPosition"); private static readonly FieldRef SpawnRotRef = AccessTools.FieldRefAccess("spawnRotation"); private static readonly FieldRef AvatarRbRef = AccessTools.FieldRefAccess("rb"); private GameObject _portal; private GameObject _room; private int _portalLevel; private string _portalSpot; private Transform _portalCenter; private Transform _controller; private Transform _exit; private Material _portalScreen; private Material _tvScreen; private TextMesh _portalList; private Light _tvLight; private bool _moving; private float _fade; private float _readyAt; private Texture2D _black; private GUIStyle _hint; private const string PortalKey = "repops1.portal"; private const string HostKey = "repops1.host"; private const float TruckRadius = 12f; private static float[] _offlineSpot; private int _worldSpotLevel; private bool _placing; private GameObject _ghost; private float _ghostTurn; private float _placeStartedAt; private Vector3 _ghostPos; private float _ghostYaw; private string _note; private float _noteUntil; private const int Rows = 5; private const int PerRow = 10; private const int MaxUnits = 4; private const float UnitWidth = 2.3f; private const float UnitGap = 0.4f; private const float BoxStep = 0.22f; private readonly List _boxes = new List(); private readonly List _boxMats = new List(); private GameObject _shelfRoot; private string _shelfSig; private float _shelfCheckAt; private GameBox _held; private string _shelfHint; private Transform _consoleT; private Transform _lid; private bool _inserting; private readonly List _extraScreens = new List(); private readonly List<(Transform pad, Material glow, TextMesh name)> _pads = new List<(Transform, Material, TextMesh)>(); private const int PosterCount = 5; private static Font _font; private static readonly Dictionary LitCache = new Dictionary(); private static readonly Dictionary GlowCache = new Dictionary(); public static bool Inside { get; private set; } public static Transform RoomRoot { get; private set; } public static Transform Tv { get; private set; } private static Font TextFont { get { if (!((Object)(object)_font != (Object)null)) { return _font = Resources.GetBuiltinResource("LegacyRuntime.ttf"); } return _font; } } private void Update() { //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Invalid comparison between Unknown and I4 //IL_0178: Unknown result type (might be due to invalid IL or missing references) //IL_0187: Unknown result type (might be due to invalid IL or missing references) //IL_019a: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) PlayerAvatar instance = PlayerAvatar.instance; PlayerController instance2 = PlayerController.instance; bool flag = (Object)(object)instance != (Object)null && (Object)(object)instance2 != (Object)null && SpawnedRef.Invoke(instance) && (Object)(object)LevelGenerator.Instance != (Object)null && LevelGenerator.Instance.Generated && (Object)(object)GameDirector.instance != (Object)null && (int)GameDirector.instance.currentState == 2 && !SemiFunc.RunIsLobbyMenu() && (SemiFunc.RunIsLobby() || SemiFunc.RunIsLevel() || SemiFunc.RunIsShop()); if (!HostHasRoom()) { flag = false; } if (!flag) { if (Inside || (Object)(object)_room != (Object)null) { Abort(); } DestroyPortal(); StopPlacing(); return; } UpdatePortal(); AnimateScreens(); if (_placing) { UpdatePlacing(); return; } if (Input.GetKeyDown(REPOPS1Plugin.PlacePortalKey.Value) && !Inside && !EmuSession.Open && !_moving) { SemiFunc.IsMasterClientOrSingleplayer(); Note("Only the host can move the game room portal."); } if (_moving || EmuSession.Open || Time.time < _readyAt) { return; } if (!Inside) { if ((Object)(object)_portal != (Object)null && (WalkedInto(_portal.transform) || (LookingAt(_portalCenter) && Interact()))) { ((MonoBehaviour)this).StartCoroutine(Enter()); } return; } if (instance2.rb.position.y < RoomRoot.position.y - 3f) { Teleport(RoomSpawn(), RoomRoot.rotation); } if (!ShelfTick()) { if (LookingAtPad() && Interact()) { EmuSession.WantedPad = PadLookedAt(); EmuSession.Instance.OpenScreen(); } else if (WalkedInto(_exit) || (LookingAt(_exit) && Interact())) { ((MonoBehaviour)this).StartCoroutine(Exit()); } } } private IEnumerator Enter() { _moving = true; yield return FadeTo(1f, 0.5f); try { BuildRoom(); Teleport(RoomSpawn(), RoomRoot.rotation); Inside = true; REPOPS1Plugin.Log.LogInfo((object)"Game room: entered."); } catch (Exception ex) { REPOPS1Plugin.Log.LogError((object)("Game room failed: " + ex)); DestroyRoom(); } yield return (object)new WaitForSecondsRealtime(0.2f); yield return FadeTo(0f, 0.8f); _readyAt = Time.time + 1f; _moving = false; } private IEnumerator Exit() { _moving = true; EmuSession.Instance.Close(); yield return FadeTo(1f, 0.5f); if ((Object)(object)PlayerController.instance != (Object)null) { Teleport(PortalFront(out var rot), rot); } DestroyRoom(); REPOPS1Plugin.Log.LogInfo((object)"Game room: left to the truck."); yield return (object)new WaitForSecondsRealtime(0.2f); yield return FadeTo(0f, 0.8f); _readyAt = Time.time + 2f; _moving = false; } private void Abort() { ((MonoBehaviour)this).StopAllCoroutines(); EmuSession.Instance.Close(); DestroyRoom(); _moving = false; _fade = 0f; REPOPS1Plugin.Log.LogInfo((object)"Game room closed: the level changed."); } private void DestroyRoom() { Inside = false; if ((Object)(object)_room != (Object)null) { Object.Destroy((Object)(object)_room); } if ((Object)(object)_tvScreen != (Object)null) { Object.Destroy((Object)(object)_tvScreen); } foreach (Material extraScreen in _extraScreens) { if ((Object)(object)extraScreen != (Object)null) { Object.Destroy((Object)(object)extraScreen); } } ClearShelfBoxes(); _consoleT = null; _lid = null; _extraScreens.Clear(); _room = null; RoomRoot = null; Tv = null; _controller = (_exit = null); _tvScreen = null; _tvLight = null; } private IEnumerator FadeTo(float target, float seconds) { float start = _fade; for (float t = 0f; t < seconds; t += Time.unscaledDeltaTime) { _fade = Mathf.Lerp(start, target, t / seconds); yield return null; } _fade = target; } private static void Teleport(Vector3 pos, Quaternion rot) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) PlayerController instance = PlayerController.instance; ((Component)instance).transform.position = pos; ((Component)instance).transform.rotation = rot; instance.rb.position = pos; instance.rb.rotation = rot; instance.rb.linearVelocity = Vector3.zero; PlayerAvatar instance2 = PlayerAvatar.instance; if ((Object)(object)instance2 != (Object)null) { Rigidbody val = AvatarRbRef.Invoke(instance2); if ((Object)(object)val != (Object)null) { val.position = pos; val.rotation = rot; val.linearVelocity = Vector3.zero; } ((Component)instance2).transform.position = pos; ((Component)instance2).transform.rotation = rot; } if ((Object)(object)CameraAim.Instance != (Object)null) { CameraAim.Instance.SetPlayerAim(rot, true); } } private static bool Interact() { if (!PS1Identity.ChatActive) { return SemiFunc.InputDown((InputKey)2); } return false; } private static bool LookingAt(Transform target, float angle = 22f) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0045: 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) Camera main = Camera.main; if ((Object)(object)main == (Object)null || (Object)(object)target == (Object)null) { return false; } Vector3 val = target.position - ((Component)main).transform.position; if (((Vector3)(ref val)).magnitude < 2.6f) { return Vector3.Angle(((Component)main).transform.forward, val) < angle; } return false; } private static bool WalkedInto(Transform door) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: 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_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0052: 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) if ((Object)(object)door == (Object)null || !((Component)door).gameObject.activeInHierarchy) { return false; } Vector3 val = door.InverseTransformPoint(PlayerController.instance.rb.position); if (Mathf.Abs(val.x) < 0.6f && Mathf.Abs(val.z) < 0.25f && val.y > -0.6f) { return val.y < 2.4f; } return false; } private static Transform TruckAnchor() { if (!((Object)(object)TruckScreenText.instance != (Object)null)) { return null; } return ((Component)TruckScreenText.instance).transform; } private static bool HostHasRoom() { if (!PhotonNetwork.InRoom || PhotonNetwork.OfflineMode || PhotonNetwork.IsMasterClient) { return false; } return ((Dictionary)(object)((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties)?.ContainsKey((object)"repops1.host") ?? false; } private static float[] SharedSpot() { if (!PhotonNetwork.InRoom) { return _offlineSpot; } Hashtable customProperties = ((RoomInfo)PhotonNetwork.CurrentRoom).CustomProperties; if (customProperties == null || !((Dictionary)(object)customProperties).TryGetValue((object)"repops1.portal", out object value) || !(value is float[] array) || array.Length != 5) { return null; } return array; } private static void ShareSpot(float[] spot) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Expected O, but got Unknown //IL_0024: Expected O, but got Unknown if (PhotonNetwork.InRoom) { Room currentRoom = PhotonNetwork.CurrentRoom; Hashtable val = new Hashtable(); ((Dictionary)val).Add((object)"repops1.portal", (object)spot); currentRoom.SetCustomProperties(val, (Hashtable)null, (WebFlags)null); } else { _offlineSpot = spot; } } private static float[] SavedTruckSpot() { if (!ParseFloats(REPOPS1Plugin.PortalSpot.Value, 4, out var v)) { return null; } return new float[5] { 0f, v[0], v[1], v[2], v[3] }; } private void UpdatePortal() { //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) int instanceID = ((Object)LevelGenerator.Instance).GetInstanceID(); SemiFunc.IsMasterClientOrSingleplayer(); string text = SpotSignature(); if ((Object)(object)_portal != (Object)null && (instanceID != _portalLevel || text != _portalSpot)) { DestroyPortal(); } if ((Object)(object)_portal == (Object)null && PortalPose(out var pos, out var rot)) { _portalLevel = instanceID; _portalSpot = text; BuildPortal(pos, rot); } if ((Object)(object)_portal != (Object)null) { _portal.SetActive(!Inside && !_placing); } } private static string SpotSignature() { float[] array = SharedSpot(); if (array != null) { return string.Join(",", array); } return ""; } private static bool PortalPose(out Vector3 pos, out Quaternion rot) { //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: 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_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: 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_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_0121: 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_0138: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_016c: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_0176: Unknown result type (might be due to invalid IL or missing references) Transform val = TruckAnchor(); float[] array = SharedSpot(); if (array != null && array[0] == 1f) { pos = new Vector3(array[1], array[2], array[3]); rot = Quaternion.Euler(0f, array[4], 0f); return true; } if (array != null && (Object)(object)val != (Object)null) { pos = val.TransformPoint(new Vector3(array[1], array[2], array[3])); rot = Quaternion.Euler(0f, val.eulerAngles.y + array[4], 0f); return true; } pos = SpawnPosRef.Invoke(PlayerAvatar.instance); if (pos == Vector3.zero) { rot = Quaternion.identity; return false; } float y = ((Quaternion)(ref SpawnRotRef.Invoke(PlayerAvatar.instance))).eulerAngles.y; if (!ParseFloats(REPOPS1Plugin.PortalOffset.Value, 3, out var v)) { v = new float[3] { 1.3f, 1.8f, 90f }; } rot = Quaternion.Euler(0f, y + v[2], 0f); pos += Quaternion.Euler(0f, y, 0f) * new Vector3(v[0], 0f, v[1]) - rot * Vector3.forward * 0.4f; return true; } private void Note(string text) { _note = text; _noteUntil = Time.unscaledTime + 4f; } private void StartPlacing() { //IL_0032: Unknown result type (might be due to invalid IL or missing references) _placing = true; _ghostTurn = 0f; _placeStartedAt = Time.unscaledTime; _ghost = MakePortal("REPOPS1_PortalPreview", new Color(0.3f, 1f, 0.5f), ownScreen: false, out var _, out var _, out var _); } private void StopPlacing() { _placing = false; if ((Object)(object)_ghost != (Object)null) { Object.Destroy((Object)(object)_ghost); } _ghost = null; } private void UpdatePlacing() { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: 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_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0066: 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) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: 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_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: 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_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) //IL_0135: 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_0152: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_015d: Unknown result type (might be due to invalid IL or missing references) //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_017f: Unknown result type (might be due to invalid IL or missing references) //IL_018f: Unknown result type (might be due to invalid IL or missing references) //IL_01a0: Unknown result type (might be due to invalid IL or missing references) //IL_01b8: Unknown result type (might be due to invalid IL or missing references) Camera main = Camera.main; if ((Object)(object)main == (Object)null || (Object)(object)_ghost == (Object)null) { StopPlacing(); return; } Vector3 val = ((Component)main).transform.position + ((Component)main).transform.forward * 0.5f; RaycastHit val3 = default(RaycastHit); Vector3 val2 = (Physics.Raycast(val, ((Component)main).transform.forward, ref val3, 8f, -1, (QueryTriggerInteraction)1) ? (((RaycastHit)(ref val3)).point + ((RaycastHit)(ref val3)).normal * ((((RaycastHit)(ref val3)).normal.y < 0.5f) ? 0.45f : 0f)) : (val + ((Component)main).transform.forward * 3f)); RaycastHit val4 = default(RaycastHit); if (Physics.Raycast(val2 + Vector3.up * 0.5f, Vector3.down, ref val4, 6f, -1, (QueryTriggerInteraction)1)) { val2 = ((RaycastHit)(ref val4)).point; } _ghostTurn += Input.mouseScrollDelta.y * 15f; if (Input.GetKeyDown((KeyCode)114)) { _ghostTurn += 90f; } Vector3 val5 = Vector3.ProjectOnPlane(((Component)main).transform.forward, Vector3.up); float num; if (!(((Vector3)(ref val5)).sqrMagnitude > 0.001f)) { num = 0f; } else { Quaternion val6 = Quaternion.LookRotation(val5); num = ((Quaternion)(ref val6)).eulerAngles.y; } _ghostYaw = Mathf.Repeat(num + _ghostTurn, 360f); _ghostPos = val2; _ghost.transform.SetPositionAndRotation(val2, Quaternion.Euler(0f, _ghostYaw, 0f)); if (Input.GetKeyDown((KeyCode)27) || (Input.GetKeyDown(REPOPS1Plugin.PlacePortalKey.Value) && Time.unscaledTime - _placeStartedAt > 0.2f)) { StopPlacing(); Note("Portal not moved."); } else if (Input.GetKeyDown((KeyCode)101) && !PS1Identity.ChatActive) { CommitPlacing(); } } private void CommitPlacing() { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_0037: 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_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_0084: 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_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) Transform val = TruckAnchor(); if ((Object)(object)val != (Object)null) { Vector3 val2 = val.position - _ghostPos; if (((Vector3)(ref val2)).magnitude < 12f) { Vector3 val3 = val.InverseTransformPoint(_ghostPos); float num = Mathf.Repeat(_ghostYaw - val.eulerAngles.y, 360f); REPOPS1Plugin.PortalSpot.Value = string.Format(CultureInfo.InvariantCulture, "{0:0.00}, {1:0.00}, {2:0.00}, {3:0}", val3.x, val3.y, val3.z, num); ShareSpot(new float[5] { 0f, val3.x, val3.y, val3.z, num }); Note("Portal placed in the truck: it stays there every level."); goto IL_0149; } } _worldSpotLevel = ((Object)LevelGenerator.Instance).GetInstanceID(); ShareSpot(new float[5] { 1f, _ghostPos.x, _ghostPos.y, _ghostPos.z, _ghostYaw }); Note("Portal placed here for this level."); goto IL_0149; IL_0149: REPOPS1Plugin.Log.LogInfo((object)$"PS1 portal placed at {_ghostPos}, turn {_ghostYaw:0}."); StopPlacing(); _readyAt = Time.time + 2f; } private Vector3 PortalFront(out Quaternion rot) { //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_portal == (Object)null && PortalPose(out var pos, out var rot2)) { BuildPortal(pos, rot2); } if ((Object)(object)_portal == (Object)null) { rot = SpawnRotRef.Invoke(PlayerAvatar.instance); return SpawnPosRef.Invoke(PlayerAvatar.instance); } Transform transform = _portal.transform; rot = Quaternion.Euler(0f, transform.eulerAngles.y + 180f, 0f); return transform.position - transform.forward * 1.2f + Vector3.up * 0.2f; } private void BuildPortal(Vector3 pos, Quaternion rot) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) _portal = MakePortal("REPOPS1_Portal", new Color(0.55f, 0.2f, 0.9f), ownScreen: true, out _portalScreen, out _portalCenter, out _portalList); _portal.transform.SetPositionAndRotation(pos, rot); } private void DestroyPortal() { if ((Object)(object)_portal != (Object)null) { Object.Destroy((Object)(object)_portal); } if ((Object)(object)_portalScreen != (Object)null) { Object.Destroy((Object)(object)_portalScreen); } _portal = null; _portalScreen = null; _portalCenter = null; _portalList = null; } private static GameObject MakePortal(string name, Color frameColor, bool ownScreen, out Material screenMat, out Transform center, out TextMesh list) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown //IL_000c: 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_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0038: 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_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: 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_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_0105: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_012a: 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_0170: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: 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_01cb: Expected O, but got Unknown GameObject val = new GameObject(name); Object.DontDestroyOnLoad((Object)val); ((Object)val).hideFlags = (HideFlags)61; Transform transform = val.transform; Material m = Glow(frameColor); Part(transform, "PostL", (PrimitiveType)3, new Vector3(-0.62f, 1.1f, 0f), new Vector3(0.12f, 2.2f, 0.12f), m); Part(transform, "PostR", (PrimitiveType)3, new Vector3(0.62f, 1.1f, 0f), new Vector3(0.12f, 2.2f, 0.12f), m); Part(transform, "Top", (PrimitiveType)3, new Vector3(0f, 2.26f, 0f), new Vector3(1.36f, 0.14f, 0.12f), m); GameObject val2 = Part(transform, "Screen", (PrimitiveType)5, new Vector3(0f, 1.1f, 0.02f), new Vector3(1.12f, 2.1f, 1f), ownScreen ? NewGlow(Color.white) : Glow(Color.white)); screenMat = val2.GetComponent().sharedMaterial; center = new GameObject("Center").transform; center.SetParent(transform, false); center.localPosition = new Vector3(0f, 1.1f, 0f); Label(transform, "GAME ROOM", new Vector3(0f, 2.55f, -0.05f), 0.05f, new Color(1f, 0.85f, 1f)); list = Label(transform, "", new Vector3(0f, 0.25f, -0.08f), 0.025f, Color.white); return val; } private Vector3 RoomSpawn() { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) return RoomRoot.TransformPoint(new Vector3(0f, 0.2f, -5.2f)); } private void BuildRoom() { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: 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_0069: Expected O, but got Unknown //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_0111: 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_0147: Unknown result type (might be due to invalid IL or missing references) //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_01ce: Unknown result type (might be due to invalid IL or missing references) //IL_01e9: Unknown result type (might be due to invalid IL or missing references) //IL_020b: Unknown result type (might be due to invalid IL or missing references) //IL_021f: Unknown result type (might be due to invalid IL or missing references) //IL_0243: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Unknown result type (might be due to invalid IL or missing references) //IL_027d: 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_028b: Unknown result type (might be due to invalid IL or missing references) //IL_029f: Unknown result type (might be due to invalid IL or missing references) //IL_02b2: Unknown result type (might be due to invalid IL or missing references) //IL_02c3: Unknown result type (might be due to invalid IL or missing references) //IL_02c8: Unknown result type (might be due to invalid IL or missing references) //IL_02d7: Unknown result type (might be due to invalid IL or missing references) //IL_02e5: Unknown result type (might be due to invalid IL or missing references) //IL_02f9: Unknown result type (might be due to invalid IL or missing references) //IL_030c: Unknown result type (might be due to invalid IL or missing references) //IL_031d: Unknown result type (might be due to invalid IL or missing references) //IL_0322: Unknown result type (might be due to invalid IL or missing references) //IL_0331: Unknown result type (might be due to invalid IL or missing references) //IL_033f: Unknown result type (might be due to invalid IL or missing references) //IL_0353: Unknown result type (might be due to invalid IL or missing references) //IL_041c: Unknown result type (might be due to invalid IL or missing references) //IL_0430: Unknown result type (might be due to invalid IL or missing references) //IL_0454: Unknown result type (might be due to invalid IL or missing references) //IL_0468: 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_0370: Unknown result type (might be due to invalid IL or missing references) //IL_0381: Unknown result type (might be due to invalid IL or missing references) //IL_0386: Unknown result type (might be due to invalid IL or missing references) //IL_0395: Unknown result type (might be due to invalid IL or missing references) //IL_039d: Unknown result type (might be due to invalid IL or missing references) //IL_03ae: Unknown result type (might be due to invalid IL or missing references) //IL_03b3: Unknown result type (might be due to invalid IL or missing references) //IL_0564: Unknown result type (might be due to invalid IL or missing references) //IL_0578: Unknown result type (might be due to invalid IL or missing references) //IL_0599: Unknown result type (might be due to invalid IL or missing references) //IL_05ad: Unknown result type (might be due to invalid IL or missing references) //IL_05d4: Unknown result type (might be due to invalid IL or missing references) //IL_05e8: Unknown result type (might be due to invalid IL or missing references) //IL_05ed: Unknown result type (might be due to invalid IL or missing references) //IL_0631: Unknown result type (might be due to invalid IL or missing references) //IL_03e3: Unknown result type (might be due to invalid IL or missing references) //IL_03cd: Unknown result type (might be due to invalid IL or missing references) //IL_065e: Unknown result type (might be due to invalid IL or missing references) //IL_0672: Unknown result type (might be due to invalid IL or missing references) //IL_069d: Unknown result type (might be due to invalid IL or missing references) //IL_06b1: Unknown result type (might be due to invalid IL or missing references) //IL_06d2: Unknown result type (might be due to invalid IL or missing references) //IL_06f9: Unknown result type (might be due to invalid IL or missing references) //IL_070d: Unknown result type (might be due to invalid IL or missing references) //IL_072e: Unknown result type (might be due to invalid IL or missing references) //IL_075c: Unknown result type (might be due to invalid IL or missing references) //IL_0770: Unknown result type (might be due to invalid IL or missing references) //IL_0794: Unknown result type (might be due to invalid IL or missing references) //IL_07a8: Unknown result type (might be due to invalid IL or missing references) //IL_07cb: Unknown result type (might be due to invalid IL or missing references) //IL_07e4: Unknown result type (might be due to invalid IL or missing references) //IL_080a: Unknown result type (might be due to invalid IL or missing references) //IL_081e: Unknown result type (might be due to invalid IL or missing references) //IL_0842: Unknown result type (might be due to invalid IL or missing references) //IL_0856: Unknown result type (might be due to invalid IL or missing references) //IL_087a: Unknown result type (might be due to invalid IL or missing references) //IL_088e: Unknown result type (might be due to invalid IL or missing references) //IL_08b2: Unknown result type (might be due to invalid IL or missing references) //IL_08c6: Unknown result type (might be due to invalid IL or missing references) //IL_04cb: Unknown result type (might be due to invalid IL or missing references) //IL_04dc: Unknown result type (might be due to invalid IL or missing references) //IL_04f0: Unknown result type (might be due to invalid IL or missing references) //IL_0502: Unknown result type (might be due to invalid IL or missing references) //IL_0504: Unknown result type (might be due to invalid IL or missing references) //IL_050e: Unknown result type (might be due to invalid IL or missing references) //IL_0513: Unknown result type (might be due to invalid IL or missing references) //IL_0527: Unknown result type (might be due to invalid IL or missing references) //IL_08f3: Unknown result type (might be due to invalid IL or missing references) //IL_0907: Unknown result type (might be due to invalid IL or missing references) //IL_0968: Unknown result type (might be due to invalid IL or missing references) //IL_097c: Unknown result type (might be due to invalid IL or missing references) //IL_0936: Unknown result type (might be due to invalid IL or missing references) //IL_0920: Unknown result type (might be due to invalid IL or missing references) //IL_09cb: Unknown result type (might be due to invalid IL or missing references) //IL_09dc: Unknown result type (might be due to invalid IL or missing references) //IL_09fa: Unknown result type (might be due to invalid IL or missing references) //IL_0a0d: Unknown result type (might be due to invalid IL or missing references) //IL_0a1e: Unknown result type (might be due to invalid IL or missing references) //IL_0a23: Unknown result type (might be due to invalid IL or missing references) //IL_0a37: Unknown result type (might be due to invalid IL or missing references) //IL_0a4b: Unknown result type (might be due to invalid IL or missing references) //IL_0a5c: Unknown result type (might be due to invalid IL or missing references) //IL_0a61: Unknown result type (might be due to invalid IL or missing references) //IL_0a6b: Unknown result type (might be due to invalid IL or missing references) //IL_0a94: Unknown result type (might be due to invalid IL or missing references) //IL_0aa5: Unknown result type (might be due to invalid IL or missing references) //IL_0aaa: Unknown result type (might be due to invalid IL or missing references) //IL_0ac3: Unknown result type (might be due to invalid IL or missing references) //IL_0b4b: Unknown result type (might be due to invalid IL or missing references) //IL_0b5f: Unknown result type (might be due to invalid IL or missing references) //IL_0b70: Unknown result type (might be due to invalid IL or missing references) //IL_0ba1: Unknown result type (might be due to invalid IL or missing references) //IL_0bba: Unknown result type (might be due to invalid IL or missing references) //IL_0c21: Unknown result type (might be due to invalid IL or missing references) //IL_0cc7: Unknown result type (might be due to invalid IL or missing references) //IL_0c71: Unknown result type (might be due to invalid IL or missing references) //IL_0c85: Unknown result type (might be due to invalid IL or missing references) //IL_0d6b: Unknown result type (might be due to invalid IL or missing references) //IL_0d95: Unknown result type (might be due to invalid IL or missing references) //IL_0dba: Unknown result type (might be due to invalid IL or missing references) //IL_0ddb: Unknown result type (might be due to invalid IL or missing references) //IL_0def: Unknown result type (might be due to invalid IL or missing references) //IL_0e14: Unknown result type (might be due to invalid IL or missing references) //IL_0e28: Unknown result type (might be due to invalid IL or missing references) //IL_0d17: Unknown result type (might be due to invalid IL or missing references) //IL_0d2b: Unknown result type (might be due to invalid IL or missing references) //IL_0e56: Unknown result type (might be due to invalid IL or missing references) //IL_0e6a: Unknown result type (might be due to invalid IL or missing references) //IL_1215: Unknown result type (might be due to invalid IL or missing references) //IL_1229: Unknown result type (might be due to invalid IL or missing references) //IL_123d: Unknown result type (might be due to invalid IL or missing references) //IL_1268: Unknown result type (might be due to invalid IL or missing references) //IL_127c: Unknown result type (might be due to invalid IL or missing references) //IL_129d: Unknown result type (might be due to invalid IL or missing references) //IL_12c3: Unknown result type (might be due to invalid IL or missing references) //IL_12dc: Unknown result type (might be due to invalid IL or missing references) //IL_12ff: Unknown result type (might be due to invalid IL or missing references) //IL_1313: Unknown result type (might be due to invalid IL or missing references) //IL_1338: Unknown result type (might be due to invalid IL or missing references) //IL_134c: Unknown result type (might be due to invalid IL or missing references) //IL_1371: Unknown result type (might be due to invalid IL or missing references) //IL_1385: Unknown result type (might be due to invalid IL or missing references) //IL_13aa: Unknown result type (might be due to invalid IL or missing references) //IL_13be: Unknown result type (might be due to invalid IL or missing references) //IL_13d2: Unknown result type (might be due to invalid IL or missing references) //IL_13f6: Unknown result type (might be due to invalid IL or missing references) //IL_1416: Unknown result type (might be due to invalid IL or missing references) //IL_142f: Unknown result type (might be due to invalid IL or missing references) //IL_1461: Unknown result type (might be due to invalid IL or missing references) //IL_1475: Unknown result type (might be due to invalid IL or missing references) //IL_0e98: Unknown result type (might be due to invalid IL or missing references) //IL_0eac: Unknown result type (might be due to invalid IL or missing references) //IL_0ee5: Unknown result type (might be due to invalid IL or missing references) //IL_0eef: Unknown result type (might be due to invalid IL or missing references) //IL_0f16: Unknown result type (might be due to invalid IL or missing references) //IL_0f2a: Unknown result type (might be due to invalid IL or missing references) //IL_0f4f: Unknown result type (might be due to invalid IL or missing references) //IL_0f63: Unknown result type (might be due to invalid IL or missing references) //IL_0f88: Unknown result type (might be due to invalid IL or missing references) //IL_0f9c: Unknown result type (might be due to invalid IL or missing references) //IL_0fc1: Unknown result type (might be due to invalid IL or missing references) //IL_0fd5: Unknown result type (might be due to invalid IL or missing references) //IL_0fe9: Unknown result type (might be due to invalid IL or missing references) //IL_1020: Unknown result type (might be due to invalid IL or missing references) //IL_1034: Unknown result type (might be due to invalid IL or missing references) //IL_104c: Unknown result type (might be due to invalid IL or missing references) //IL_107f: Unknown result type (might be due to invalid IL or missing references) //IL_1093: Unknown result type (might be due to invalid IL or missing references) //IL_1098: Unknown result type (might be due to invalid IL or missing references) //IL_10c0: Unknown result type (might be due to invalid IL or missing references) //IL_1101: Unknown result type (might be due to invalid IL or missing references) //IL_1115: Unknown result type (might be due to invalid IL or missing references) //IL_1190: Unknown result type (might be due to invalid IL or missing references) //IL_11bf: Unknown result type (might be due to invalid IL or missing references) //IL_11a9: Unknown result type (might be due to invalid IL or missing references) //IL_1149: Unknown result type (might be due to invalid IL or missing references) DestroyRoom(); Transform val = TruckAnchor(); Vector3 val2; float y; if ((Object)(object)val != (Object)null) { val2 = val.position; y = val.eulerAngles.y; } else { val2 = SpawnPosRef.Invoke(PlayerAvatar.instance); y = ((Quaternion)(ref SpawnRotRef.Invoke(PlayerAvatar.instance))).eulerAngles.y; } _room = new GameObject("REPOPS1_Room"); Object.DontDestroyOnLoad((Object)(object)_room); ((Object)_room).hideFlags = (HideFlags)61; _room.transform.SetPositionAndRotation(val2 + Vector3.up * 400f, Quaternion.Euler(0f, y, 0f)); RoomRoot = _room.transform; Transform roomRoot = RoomRoot; Material m = Lit(new Color(0.22f, 0.13f, 0.08f)); Material m2 = Lit(new Color(0.3f, 0.08f, 0.22f)); Material m3 = Lit(new Color(0.13f, 0.1f, 0.2f)); Material m4 = Lit(new Color(0.08f, 0.06f, 0.12f)); Material val3 = Lit(new Color(0.05f, 0.04f, 0.06f)); Material val4 = Lit(new Color(0.32f, 0.19f, 0.1f)); Material val5 = Lit(new Color(0.55f, 0.55f, 0.58f)); Material m5 = Lit(new Color(0.18f, 0.16f, 0.36f)); Material m6 = Lit(new Color(0.12f, 0.4f, 0.16f)); Material val6 = Glow(new Color(1f, 0.25f, 0.8f)); Material val7 = Glow(new Color(0.2f, 0.9f, 1f)); Part(roomRoot, "Floor", (PrimitiveType)3, new Vector3(0f, -0.1f, 0f), new Vector3(14f, 0.2f, 14f), m, collide: true); Part(roomRoot, "Ceiling", (PrimitiveType)3, new Vector3(0f, 4.2999997f, 0f), new Vector3(14f, 0.2f, 14f), val3, collide: true); for (int i = 0; i < 4; i++) { Quaternion val8 = Quaternion.Euler(0f, (float)(i * 90), 0f); GameObject obj = Part(roomRoot, "Wall", (PrimitiveType)3, Vector3.zero, new Vector3(14f, 4.2f, 0.2f), m3, collide: true); obj.transform.localPosition = val8 * new Vector3(0f, 2.1f, 7.1f); obj.transform.localRotation = val8; GameObject obj2 = Part(roomRoot, "Panelling", (PrimitiveType)3, Vector3.zero, new Vector3(14f, 1.1f, 0.06f), m4); obj2.transform.localPosition = val8 * new Vector3(0f, 0.55f, 6.97f); obj2.transform.localRotation = val8; GameObject obj3 = Part(roomRoot, "Neon", (PrimitiveType)3, Vector3.zero, new Vector3(13.6f, 0.05f, 0.05f), (i % 2 == 0) ? val6 : val7); obj3.transform.localPosition = val8 * new Vector3(0f, 4.0499997f, 6.94f); obj3.transform.localRotation = val8; AddLight(roomRoot, val8 * new Vector3(0f, 3.6999998f, 6.2f), (i % 2 == 0) ? new Color(1f, 0.3f, 0.85f) : new Color(0.3f, 0.85f, 1f), 1.1f, 9f); } Part(roomRoot, "Rug", (PrimitiveType)3, new Vector3(0f, 0.005f, 0.8f), new Vector3(6f, 0.01f, 5f), m2); Part(roomRoot, "RugBorder", (PrimitiveType)3, new Vector3(0f, 0.004f, 0.8f), new Vector3(6.3f, 0.01f, 5.3f), Lit(new Color(0.85f, 0.7f, 0.3f))); Vector3 val9 = default(Vector3); for (int j = 0; j < 4; j++) { ((Vector3)(ref val9))..ctor((j % 2 == 0) ? (-3.5f) : 3.5f, 4.18f, (j < 2) ? (-3f) : 3f); Part(roomRoot, "CeilingLight", (PrimitiveType)3, val9, new Vector3(1.4f, 0.04f, 1.4f), Glow(new Color(1f, 0.92f, 0.8f))); AddLight(roomRoot, val9 + Vector3.down * 0.4f, new Color(1f, 0.88f, 0.75f), 1.3f, 10f); } float num = 6.2f; Part(roomRoot, "TvStand", (PrimitiveType)3, new Vector3(0f, 0.28f, num), new Vector3(2.8f, 0.56f, 0.95f), val4, collide: true); Part(roomRoot, "TvBody", (PrimitiveType)3, new Vector3(0f, 1.35f, num), new Vector3(2.1f, 1.6f, 1.25f), val3, collide: true); GameObject val10 = Part(roomRoot, "TvScreen", (PrimitiveType)5, new Vector3(0f, 1.38f, num - 0.63f), new Vector3(1.8f, 1.35f, 1f), NewGlow(Color.black)); _tvScreen = val10.GetComponent().sharedMaterial; Tv = val10.transform; BuildConsole(roomRoot, new Vector3(0f, 0.56f, num - 0.2f), val5, val3); for (int k = -1; k <= 1; k += 2) { Part(roomRoot, "Speaker", (PrimitiveType)3, new Vector3((float)k * 2.1f, 0.75f, num), new Vector3(0.6f, 1.5f, 0.55f), val3, collide: true); Part(roomRoot, "Woofer", (PrimitiveType)2, new Vector3((float)k * 2.1f, 0.55f, num - 0.28f), new Vector3(0.38f, 0.01f, 0.38f), m4).transform.localRotation = Quaternion.Euler(90f, 0f, 0f); Part(roomRoot, "Tweeter", (PrimitiveType)2, new Vector3((float)k * 2.1f, 1.15f, num - 0.28f), new Vector3(0.16f, 0.01f, 0.16f), m4).transform.localRotation = Quaternion.Euler(90f, 0f, 0f); } Part(roomRoot, "SignFrame", (PrimitiveType)3, new Vector3(0f, 2.95f, 6.9f), new Vector3(3.6f, 0.06f, 0.05f), val6); Part(roomRoot, "SignFrame", (PrimitiveType)3, new Vector3(0f, 3.6f, 6.9f), new Vector3(3.6f, 0.06f, 0.05f), val7); Label(roomRoot, "GAME ROOM", new Vector3(0f, 3.28f, 6.86f), 0.09f, new Color(1f, 0.85f, 1f)); Part(roomRoot, "Seat", (PrimitiveType)3, new Vector3(0f, 0.24f, -0.6f), new Vector3(3.6f, 0.48f, 1f), m5, collide: true); Part(roomRoot, "Back", (PrimitiveType)3, new Vector3(0f, 0.72f, -1.15f), new Vector3(3.6f, 1f, 0.25f), m5, collide: true); Part(roomRoot, "ArmL", (PrimitiveType)3, new Vector3(-1.9f, 0.42f, -0.65f), new Vector3(0.25f, 0.84f, 1.1f), m5, collide: true); Part(roomRoot, "ArmR", (PrimitiveType)3, new Vector3(1.9f, 0.42f, -0.65f), new Vector3(0.25f, 0.84f, 1.1f), m5, collide: true); for (int l = -1; l <= 1; l += 2) { Part(roomRoot, "BeanBag", (PrimitiveType)0, new Vector3((float)l * 3.2f, 0.32f, 1f), new Vector3(1.1f, 0.65f, 1.1f), Lit((l < 0) ? new Color(0.6f, 0.15f, 0.3f) : new Color(0.15f, 0.35f, 0.6f)), collide: true); } Part(roomRoot, "Table", (PrimitiveType)3, new Vector3(0f, 0.22f, 1.1f), new Vector3(1.8f, 0.44f, 0.8f), val4, collide: true); Vector3 val11 = default(Vector3); for (int n = 0; n < 4; n++) { ((Vector3)(ref val11))..ctor(-0.66f + (float)n * 0.44f, 0.47f, 1.1f); GameObject val12 = Part(roomRoot, "Controller" + (n + 1), (PrimitiveType)3, val11, new Vector3(0.3f, 0.06f, 0.16f), val5); Material val13 = NewGlow(new Color(0.3f, 0.8f, 1f)); Part(roomRoot, "PadGlow", (PrimitiveType)3, val11 + new Vector3(0f, 0.035f, 0f), new Vector3(0.1f, 0.01f, 0.06f), val13); TextMesh item = Label(roomRoot, "", val11 + new Vector3(0f, 0.32f, 0f), 0.02f, Color.white); Label(roomRoot, "P" + (n + 1), val11 + new Vector3(0f, 0.08f, -0.09f), 0.014f, new Color(0.8f, 0.85f, 1f)); _pads.Add((val12.transform, val13, item)); } _controller = _pads[0].pad; for (int num2 = 0; num2 < 5; num2++) { float num3 = Mathf.Repeat(0.75f + (float)num2 * 0.07f, 1f); Part(roomRoot, "PosterFrame", (PrimitiveType)3, new Vector3(6.95f, 2.1f, PosterZ(num2)), new Vector3(0.04f, 1.12f, 1.02f), Glow(Color.HSVToRGB(num3, 0.6f, 0.85f))); } Label(roomRoot, "PRESS START", new Vector3(0f, 3.2f, -6.88f), 0.07f, new Color(1f, 0.9f, 0.35f), 180f); string[] array = new string[8] { "..X.....X..", "...X...X...", "..XXXXXXX..", ".XX.XXX.XX.", "XXXXXXXXXXX", "X.XXXXXXX.X", "X.X.....X.X", "...XX.XX..." }; Material m7 = Glow(new Color(0.35f, 1f, 0.45f)); for (int num4 = 0; num4 < array.Length; num4++) { for (int num5 = 0; num5 < array[num4].Length; num5++) { if (array[num4][num5] == 'X') { Part(roomRoot, "Pixel", (PrimitiveType)3, new Vector3(-3.2f + (float)num5 * 0.09f, 2.9f - (float)num4 * 0.09f, -6.95f), new Vector3(0.085f, 0.085f, 0.03f), m7); } } } Material m8 = Glow(new Color(1f, 0.45f, 0.75f)); for (int num6 = 0; num6 < array.Length; num6++) { for (int num7 = 0; num7 < array[num6].Length; num7++) { if (array[num6][num7] == 'X') { Part(roomRoot, "Pixel", (PrimitiveType)3, new Vector3(2.3f + (float)num7 * 0.09f, 2.9f - (float)num6 * 0.09f, -6.95f), new Vector3(0.085f, 0.085f, 0.03f), m8); } } } for (int num8 = -1; num8 <= 1; num8 += 2) { Transform transform = new GameObject("Arcade").transform; transform.SetParent(roomRoot, false); transform.localPosition = new Vector3((float)num8 * 5.9f, 0f, -6f); transform.localRotation = Quaternion.Euler(0f, 180f + (float)num8 * -35f, 0f); Part(transform, "Body", (PrimitiveType)3, new Vector3(0f, 1.3f, 0f), new Vector3(1.4f, 2.6f, 0.9f), val3, collide: true); Part(transform, "SideL", (PrimitiveType)3, new Vector3(-0.71f, 1.3f, 0f), new Vector3(0.03f, 2.62f, 0.92f), (num8 < 0) ? val6 : val7); Part(transform, "SideR", (PrimitiveType)3, new Vector3(0.71f, 1.3f, 0f), new Vector3(0.03f, 2.62f, 0.92f), (num8 < 0) ? val6 : val7); Part(transform, "Marquee", (PrimitiveType)3, new Vector3(0f, 2.45f, -0.42f), new Vector3(1.36f, 0.26f, 0.1f), (num8 < 0) ? val6 : val7); Label(transform, (num8 < 0) ? "PLAYER 1" : "PLAYER 2", new Vector3(0f, 2.45f, -0.48f), 0.03f, Color.white); Part(transform, "Bezel", (PrimitiveType)3, new Vector3(0f, 1.66f, -0.44f), new Vector3(1.3f, 1.3f, 0.04f), m4); Part(transform, "Panel", (PrimitiveType)3, new Vector3(0f, 0.98f, -0.56f), new Vector3(1.36f, 0.08f, 0.45f), val5); Part(transform, "Stick", (PrimitiveType)2, new Vector3(-0.32f, 1.07f, -0.62f), new Vector3(0.03f, 0.07f, 0.03f), val3); Part(transform, "Ball", (PrimitiveType)0, new Vector3(-0.32f, 1.15f, -0.62f), new Vector3(0.07f, 0.07f, 0.07f), Glow(new Color(1f, 0.2f, 0.2f))); for (int num9 = 0; num9 < 3; num9++) { Part(transform, "Button", (PrimitiveType)2, new Vector3(0.05f + (float)num9 * 0.14f, 1.03f, -0.62f), new Vector3(0.08f, 0.01f, 0.08f), Glow(Color.HSVToRGB((float)num9 * 0.3f, 0.7f, 1f))); } GameObject val14 = Part(transform, "Screen", (PrimitiveType)5, new Vector3(0f, 1.66f, -0.47f), new Vector3(1.18f, 1.18f, 1f), NewGlow(Color.black)); val14.transform.localRotation = Quaternion.Euler(-6f, 0f, 0f); for (int num10 = 0; num10 < 4; num10++) { Part(transform, "FloorTile", (PrimitiveType)3, new Vector3(((float)(num10 % 2) - 0.5f) * 0.62f, 0.006f, -1f - (float)(num10 / 2) * 0.62f), new Vector3(0.58f, 0.01f, 0.58f), Glow(Color.HSVToRGB(Mathf.Repeat(((num8 < 0) ? 0.85f : 0.5f) + (float)num10 * 0.08f, 1f), 0.75f, 0.7f))); } _extraScreens.Add(val14.GetComponent().sharedMaterial); AddLight(transform, new Vector3(0f, 1.6f, -1.1f), (num8 < 0) ? new Color(1f, 0.3f, 0.85f) : new Color(0.3f, 0.85f, 1f), 0.9f, 4.5f); } BuildDecor(roomRoot, val3, val5, val4, val6, val7); for (int num11 = -1; num11 <= 1; num11 += 2) { Part(roomRoot, "Pot", (PrimitiveType)2, new Vector3((float)num11 * 6.4f, 0.3f, 6.4f), new Vector3(0.5f, 0.3f, 0.5f), Lit(new Color(0.6f, 0.35f, 0.25f)), collide: true); Part(roomRoot, "Leaves", (PrimitiveType)0, new Vector3((float)num11 * 6.4f, 1.05f, 6.4f), new Vector3(0.9f, 1.1f, 0.9f), m6); } Transform transform2 = new GameObject("Exit").transform; transform2.SetParent(roomRoot, false); transform2.localPosition = new Vector3(0f, 0f, -6.65f); Material m9 = Glow(new Color(1f, 0.6f, 0.2f)); Part(transform2, "PostL", (PrimitiveType)3, new Vector3(-0.6f, 1.05f, 0f), new Vector3(0.1f, 2.1f, 0.1f), m9); Part(transform2, "PostR", (PrimitiveType)3, new Vector3(0.6f, 1.05f, 0f), new Vector3(0.1f, 2.1f, 0.1f), m9); Part(transform2, "Top", (PrimitiveType)3, new Vector3(0f, 2.12f, 0f), new Vector3(1.3f, 0.1f, 0.1f), m9); Part(transform2, "Panel", (PrimitiveType)5, new Vector3(0f, 1.05f, -0.03f), new Vector3(1.1f, 2f, 1f), Glow(new Color(0.15f, 0.08f, 0.02f))).transform.localRotation = Quaternion.Euler(0f, 180f, 0f); Label(transform2, "EXIT", new Vector3(0f, 2.4f, 0.02f), 0.04f, new Color(1f, 0.75f, 0.4f), 180f); _exit = transform2; RebuildShelfBoxes(); _tvLight = AddLight(roomRoot, new Vector3(0f, 1.4f, num - 1.6f), new Color(0.55f, 0.65f, 1f), 1.8f, 9f); } private void BuildDecor(Transform r, Material dark, Material plastic, Material wood, Material pink, Material cyan) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0068: 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) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0147: 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) //IL_0184: Unknown result type (might be due to invalid IL or missing references) //IL_01a4: Unknown result type (might be due to invalid IL or missing references) //IL_01b8: Unknown result type (might be due to invalid IL or missing references) //IL_01cc: Unknown result type (might be due to invalid IL or missing references) //IL_01f3: Unknown result type (might be due to invalid IL or missing references) //IL_0207: Unknown result type (might be due to invalid IL or missing references) //IL_021b: Unknown result type (might be due to invalid IL or missing references) //IL_0242: Unknown result type (might be due to invalid IL or missing references) //IL_0256: Unknown result type (might be due to invalid IL or missing references) //IL_0279: Unknown result type (might be due to invalid IL or missing references) //IL_0283: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_02c6: Unknown result type (might be due to invalid IL or missing references) //IL_02cb: Unknown result type (might be due to invalid IL or missing references) //IL_02d5: Unknown result type (might be due to invalid IL or missing references) //IL_02f3: Unknown result type (might be due to invalid IL or missing references) //IL_0326: Unknown result type (might be due to invalid IL or missing references) //IL_033a: Unknown result type (might be due to invalid IL or missing references) //IL_035d: Unknown result type (might be due to invalid IL or missing references) //IL_0371: Unknown result type (might be due to invalid IL or missing references) //IL_038e: Unknown result type (might be due to invalid IL or missing references) //IL_03a2: Unknown result type (might be due to invalid IL or missing references) //IL_03bc: Unknown result type (might be due to invalid IL or missing references) //IL_03df: Unknown result type (might be due to invalid IL or missing references) //IL_03f9: Unknown result type (might be due to invalid IL or missing references) //IL_0419: Unknown result type (might be due to invalid IL or missing references) //IL_042d: Unknown result type (might be due to invalid IL or missing references) //IL_0441: Unknown result type (might be due to invalid IL or missing references) //IL_0468: 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_049f: Unknown result type (might be due to invalid IL or missing references) //IL_04b3: Unknown result type (might be due to invalid IL or missing references) //IL_04e9: Unknown result type (might be due to invalid IL or missing references) //IL_04fd: Unknown result type (might be due to invalid IL or missing references) //IL_05e4: Unknown result type (might be due to invalid IL or missing references) //IL_05ff: Unknown result type (might be due to invalid IL or missing references) //IL_061a: Unknown result type (might be due to invalid IL or missing references) //IL_0546: Unknown result type (might be due to invalid IL or missing references) //IL_0530: Unknown result type (might be due to invalid IL or missing references) //IL_051a: Unknown result type (might be due to invalid IL or missing references) //IL_066a: Unknown result type (might be due to invalid IL or missing references) //IL_067e: Unknown result type (might be due to invalid IL or missing references) //IL_07a4: Unknown result type (might be due to invalid IL or missing references) //IL_07b8: Unknown result type (might be due to invalid IL or missing references) //IL_07f4: Unknown result type (might be due to invalid IL or missing references) //IL_080d: Unknown result type (might be due to invalid IL or missing references) //IL_06f8: Unknown result type (might be due to invalid IL or missing references) //IL_070c: Unknown result type (might be due to invalid IL or missing references) //IL_083f: Unknown result type (might be due to invalid IL or missing references) //IL_0853: Unknown result type (might be due to invalid IL or missing references) //IL_087b: Unknown result type (might be due to invalid IL or missing references) //IL_088f: Unknown result type (might be due to invalid IL or missing references) //IL_08b6: Unknown result type (might be due to invalid IL or missing references) //IL_08ca: Unknown result type (might be due to invalid IL or missing references) //IL_08de: Unknown result type (might be due to invalid IL or missing references) //IL_0903: Unknown result type (might be due to invalid IL or missing references) //IL_0917: Unknown result type (might be due to invalid IL or missing references) Color[] array = (Color[])(object)new Color[4] { new Color(1f, 0.35f, 0.8f), new Color(1f, 0.85f, 0.3f), new Color(0.3f, 0.9f, 1f), new Color(0.4f, 1f, 0.5f) }; Material[] array2 = (Material[])(object)new Material[array.Length]; for (int i = 0; i < array.Length; i++) { array2[i] = Glow(array[i]); } for (int j = -1; j <= 1; j += 2) { for (int k = 0; k <= 26; k++) { float num = -6.5f + (float)k * 0.5f; float num2 = Mathf.Sin(Mathf.Repeat((float)k, 9f) / 9f * MathF.PI) * 0.35f; Part(r, "Bulb", (PrimitiveType)0, new Vector3(num, 3.9499998f - num2, (float)j * 2.2f), new Vector3(0.09f, 0.11f, 0.09f), array2[k % array2.Length]); } } Transform transform = new GameObject("ClawMachine").transform; transform.SetParent(r, false); transform.localPosition = new Vector3(3.9f, 0f, -6.35f); transform.localRotation = Quaternion.Euler(0f, 180f, 0f); Part(transform, "Base", (PrimitiveType)3, new Vector3(0f, 0.45f, 0f), new Vector3(1f, 0.9f, 1f), Lit(new Color(0.85f, 0.2f, 0.35f)), collide: true); Part(transform, "Glass", (PrimitiveType)3, new Vector3(0f, 1.35f, 0f), new Vector3(0.96f, 0.9f, 0.96f), Glow(new Color(0.12f, 0.16f, 0.25f))); Part(transform, "Roof", (PrimitiveType)3, new Vector3(0f, 1.88f, 0f), new Vector3(1.04f, 0.16f, 1.04f), pink); Label(transform, "CLAW", new Vector3(0f, 1.88f, -0.53f), 0.025f, Color.white); for (int l = 0; l < 9; l++) { Part(transform, "Plush", (PrimitiveType)0, new Vector3(-0.3f + (float)(l % 3) * 0.3f, 0.98f, -0.3f + (float)(l / 3) * 0.3f), Vector3.one * 0.22f, Glow(Color.HSVToRGB((float)l * 0.11f % 1f, 0.6f, 0.85f))); } Part(transform, "Cable", (PrimitiveType)2, new Vector3(0.1f, 1.62f, 0.05f), new Vector3(0.015f, 0.16f, 0.015f), plastic); Part(transform, "Claw", (PrimitiveType)0, new Vector3(0.1f, 1.44f, 0.05f), new Vector3(0.12f, 0.08f, 0.12f), plastic); AddLight(transform, new Vector3(0f, 1.4f, -0.9f), new Color(1f, 0.4f, 0.6f), 0.7f, 3.5f); Transform transform2 = new GameObject("Fridge").transform; transform2.SetParent(r, false); transform2.localPosition = new Vector3(3.4f, 0f, 6.45f); transform2.localRotation = Quaternion.Euler(0f, 180f, 0f); Part(transform2, "Body", (PrimitiveType)3, new Vector3(0f, 0.45f, 0f), new Vector3(0.6f, 0.9f, 0.6f), Lit(new Color(0.85f, 0.87f, 0.9f)), collide: true); Part(transform2, "Handle", (PrimitiveType)3, new Vector3(0.22f, 0.55f, 0.31f), new Vector3(0.03f, 0.3f, 0.03f), dark); Part(transform2, "Logo", (PrimitiveType)3, new Vector3(0f, 0.75f, 0.305f), new Vector3(0.3f, 0.06f, 0.01f), cyan); for (int m = 0; m < 3; m++) { Part(transform2, "Can", (PrimitiveType)2, new Vector3(-0.16f + (float)m * 0.16f, 0.96f, 0f), new Vector3(0.07f, 0.06f, 0.07f), Lit((Color)(m switch { 1 => new Color(0.1f, 0.5f, 0.9f), 0 => new Color(0.8f, 0.1f, 0.1f), _ => new Color(0.2f, 0.8f, 0.3f), }))); } string[] array3 = new string[6] { ".XX.XX.", "XXXXXXX", "XXXXXXX", ".XXXXX.", "..XXX..", "...X..." }; string[] array4 = new string[6] { "..XXXX..", ".XXOOXX.", "XXOOOOXX", "XXXXXXXX", "..OXXO..", "..OOOO.." }; Material m2 = Glow(new Color(1f, 0.25f, 0.3f)); Material val = Glow(new Color(1f, 0.95f, 0.9f)); Material val2 = Glow(new Color(1f, 0.55f, 0.15f)); for (int n = 0; n < array3.Length; n++) { for (int num3 = 0; num3 < array3[n].Length; num3++) { if (array3[n][num3] == 'X') { Part(r, "Pixel", (PrimitiveType)3, new Vector3(-6.95f, 3.75f - (float)n * 0.1f, -4.6f + (float)num3 * 0.1f), new Vector3(0.03f, 0.095f, 0.095f), m2); } } } for (int num4 = 0; num4 < array4.Length; num4++) { for (int num5 = 0; num5 < array4[num4].Length; num5++) { if (array4[num4][num5] != '.') { Part(r, "Pixel", (PrimitiveType)3, new Vector3(-6.95f, 3.75f - (float)num4 * 0.1f, 4f + (float)num5 * 0.1f), new Vector3(0.03f, 0.095f, 0.095f), (array4[num4][num5] == 'X') ? val2 : val); } } } for (int num6 = 0; num6 < 24; num6++) { float num7 = (float)num6 / 24f * MathF.PI * 2f; Part(r, "Ring", (PrimitiveType)3, new Vector3(6.94f, 3.45f + Mathf.Sin(num7) * 0.4f, 5.6f + Mathf.Cos(num7) * 0.4f), new Vector3(0.03f, 0.1f, 0.1f), (num6 % 2 == 0) ? pink : cyan); } Label(r, "HIGH SCORE", new Vector3(6.92f, 3.45f, 3.4f), 0.04f, new Color(0.5f, 1f, 0.6f), 90f); for (int num8 = -1; num8 <= 1; num8 += 2) { Part(r, "SideTable", (PrimitiveType)2, new Vector3((float)num8 * 4.3f, 0.25f, 1.9f), new Vector3(0.5f, 0.25f, 0.5f), wood, collide: true); Part(r, "LampPole", (PrimitiveType)2, new Vector3((float)num8 * 4.3f, 0.7f, 1.9f), new Vector3(0.03f, 0.2f, 0.03f), dark); Part(r, "LampShade", (PrimitiveType)2, new Vector3((float)num8 * 4.3f, 0.95f, 1.9f), new Vector3(0.3f, 0.1f, 0.3f), Glow(new Color(1f, 0.8f, 0.55f))); AddLight(r, new Vector3((float)num8 * 4.3f, 1.1f, 1.9f), new Color(1f, 0.8f, 0.55f), 0.6f, 3f); } } private static float RowY(int row) { return 0.35f + (float)row * 0.45f; } private static Color SystemColor(string system) { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_005d: 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) switch ((system ?? "").ToUpperInvariant()) { case "PS1": case "PSX": return new Color(0.32f, 0.55f, 0.95f); case "PS2": return new Color(0.62f, 0.42f, 0.95f); default: { int num = 0; string text = system ?? ""; foreach (char c in text) { num = num * 31 + c; } return Color.HSVToRGB(Mathf.Repeat((float)(num & 0xFFFF) / 65535f, 1f), 0.5f, 0.85f); } } } private void BuildConsole(Transform r, Vector3 pos, Material plastic, Material dark) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0049: 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) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_0115: 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_0155: 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_018d: Unknown result type (might be due to invalid IL or missing references) //IL_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01c5: Unknown result type (might be due to invalid IL or missing references) //IL_01d9: Unknown result type (might be due to invalid IL or missing references) //IL_01fd: Unknown result type (might be due to invalid IL or missing references) //IL_0211: Unknown result type (might be due to invalid IL or missing references) //IL_0225: Unknown result type (might be due to invalid IL or missing references) //IL_024c: Unknown result type (might be due to invalid IL or missing references) //IL_0260: Unknown result type (might be due to invalid IL or missing references) //IL_0284: Unknown result type (might be due to invalid IL or missing references) //IL_0298: Unknown result type (might be due to invalid IL or missing references) Transform transform = new GameObject("Console").transform; transform.SetParent(r, false); transform.localPosition = pos; Part(transform, "Body", (PrimitiveType)3, new Vector3(0f, 0.05f, 0f), new Vector3(0.72f, 0.12f, 0.52f), plastic, collide: true); Part(transform, "Front", (PrimitiveType)3, new Vector3(0f, 0.03f, -0.262f), new Vector3(0.7f, 0.07f, 0.01f), Lit(new Color(0.42f, 0.42f, 0.45f))); _lid = new GameObject("Lid").transform; _lid.SetParent(transform, false); _lid.localPosition = new Vector3(-0.06f, 0.112f, 0.17f); Part(_lid, "LidDisc", (PrimitiveType)2, new Vector3(0f, 0f, -0.17f), new Vector3(0.36f, 0.008f, 0.36f), Lit(new Color(0.5f, 0.5f, 0.53f))); Part(_lid, "LidRing", (PrimitiveType)2, new Vector3(0f, 0.002f, -0.17f), new Vector3(0.1f, 0.008f, 0.1f), dark); Part(transform, "Power", (PrimitiveType)2, new Vector3(0.25f, 0.115f, -0.12f), new Vector3(0.06f, 0.012f, 0.06f), dark); Part(transform, "Open", (PrimitiveType)2, new Vector3(0.25f, 0.115f, 0.05f), new Vector3(0.06f, 0.012f, 0.06f), dark); Part(transform, "Led", (PrimitiveType)3, new Vector3(0.25f, 0.06f, -0.265f), new Vector3(0.03f, 0.02f, 0.01f), Glow(new Color(0.2f, 1f, 0.3f))); Part(transform, "Port1", (PrimitiveType)3, new Vector3(-0.2f, 0.03f, -0.266f), new Vector3(0.1f, 0.025f, 0.01f), dark); Part(transform, "Port2", (PrimitiveType)3, new Vector3(0f, 0.03f, -0.266f), new Vector3(0.1f, 0.025f, 0.01f), dark); _consoleT = transform; } private void RebuildShelfBoxes() { //IL_01ff: Unknown result type (might be due to invalid IL or missing references) //IL_0209: Expected O, but got Unknown //IL_027b: Unknown result type (might be due to invalid IL or missing references) //IL_028f: Unknown result type (might be due to invalid IL or missing references) //IL_0294: Unknown result type (might be due to invalid IL or missing references) //IL_02b9: Unknown result type (might be due to invalid IL or missing references) //IL_02cd: Unknown result type (might be due to invalid IL or missing references) //IL_02d2: Unknown result type (might be due to invalid IL or missing references) //IL_02ee: Expected O, but got Unknown //IL_0425: Unknown result type (might be due to invalid IL or missing references) //IL_0437: Unknown result type (might be due to invalid IL or missing references) //IL_0441: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_room == (Object)null || (Object)(object)EmuSession.Instance == (Object)null || _held != null) { return; } List list = EmuSession.Instance.ShelfItems(); List list2 = new List(); string[] array = (REPOPS1Plugin.ShelfSystems.Value ?? "").Split(','); foreach (string s in array) { if (s.Trim().Length > 0 && !list2.Exists((string x) => x.Equals(s.Trim(), StringComparison.OrdinalIgnoreCase))) { list2.Add(s.Trim()); } } foreach (MenuItem item in list) { string sys = (string.IsNullOrEmpty(item.Folder) ? "Games" : item.Folder); if (!list2.Exists((string x) => x.Equals(sys, StringComparison.OrdinalIgnoreCase))) { list2.Add(sys); } } if (list2.Count > 4) { list2.RemoveRange(4, list2.Count - 4); } string text = list.Count + "|" + GameShelf.CoverVersion + "|" + string.Join(",", list2); foreach (MenuItem item2 in list) { text = text + "|" + item2.Title; } if (text == _shelfSig && (Object)(object)_shelfRoot != (Object)null) { return; } ClearShelfBoxes(); _shelfSig = text; _shelfRoot = new GameObject("Shelves"); _shelfRoot.transform.SetParent(_room.transform, false); List list3 = new List(list); list3.Sort((MenuItem a, MenuItem b) => ((b.Local != null) ? PlayStats.Get(b.Local.Path).LastPlayed : 0).CompareTo((a.Local != null) ? PlayStats.Get(a.Local.Path).LastPlayed : 0)); for (int num = 0; num < 5 && num < list3.Count; num++) { GameObject obj = Part(_shelfRoot.transform, "Poster", (PrimitiveType)5, new Vector3(6.92f, 2.1f, PosterZ(num)), new Vector3(0.94f, 1.04f, 1f), Lit(Color.white)); obj.transform.localRotation = Quaternion.Euler(0f, 90f, 0f); bool real; Material val = new Material(Shader.Find("Standard")) { mainTexture = (Texture)(object)EmuSession.Instance.CoverFor(list3[num], out real) }; _boxMats.Add(val); obj.GetComponent().sharedMaterial = val; } float num2 = (float)list2.Count * 2.3f + (float)(list2.Count - 1) * 0.4f; for (int num3 = 0; num3 < list2.Count; num3++) { Transform val2 = BuildUnit(list2[num3], (0f - num2) / 2f + 1.15f + (float)num3 * 2.7f + 0.5f); int num4 = 0; foreach (MenuItem item3 in list) { if ((string.IsNullOrEmpty(item3.Folder) ? "Games" : item3.Folder).Equals(list2[num3], StringComparison.OrdinalIgnoreCase)) { if (num4 >= 50) { break; } AddBox(val2, item3, num4 / 10, num4 % 10); num4++; } } if (num4 == 0) { Label(val2, "add " + list2[num3] + " games", new Vector3(0.2f, RowY(2) + 0.12f, 0f), 0.018f, SystemColor(list2[num3]) * 0.9f, -90f); } } } private Transform BuildUnit(string system, float z) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_006e: 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_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: 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) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0148: Unknown result type (might be due to invalid IL or missing references) //IL_0182: Unknown result type (might be due to invalid IL or missing references) //IL_0196: Unknown result type (might be due to invalid IL or missing references) //IL_01d7: Unknown result type (might be due to invalid IL or missing references) //IL_01eb: Unknown result type (might be due to invalid IL or missing references) //IL_0219: 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_024c: Unknown result type (might be due to invalid IL or missing references) //IL_0256: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Unknown result type (might be due to invalid IL or missing references) //IL_0261: Unknown result type (might be due to invalid IL or missing references) //IL_0281: Unknown result type (might be due to invalid IL or missing references) //IL_0286: Unknown result type (might be due to invalid IL or missing references) Color val = SystemColor(system); Transform transform = new GameObject("Shelf " + system).transform; transform.SetParent(_shelfRoot.transform, false); transform.localPosition = new Vector3(-7f, 0f, z); Material m = Glow(val * 0.75f); Material m2 = Lit(new Color(val.r * 0.12f, val.g * 0.12f, val.b * 0.14f)); Material m3 = Lit(new Color(0.16f, 0.12f, 0.1f)); Part(transform, "Back", (PrimitiveType)3, new Vector3(0.03f, 1.25f, 0f), new Vector3(0.03f, 2.4f, 2.3f), m2, collide: true); for (int i = 0; i < 5; i++) { Part(transform, "Board", (PrimitiveType)3, new Vector3(0.16f, RowY(i), 0f), new Vector3(0.28f, 0.025f, 2.3f), m3, collide: true); Part(transform, "Edge", (PrimitiveType)3, new Vector3(0.302f, RowY(i) + 0.002f, 0f), new Vector3(0.008f, 0.012f, 2.28f), m); } for (int j = -1; j <= 1; j += 2) { ((Object)Part(transform, "Side", (PrimitiveType)3, new Vector3(0.16f, 1.25f, (float)j * 1.165f), new Vector3(0.3f, 2.4f, 0.03f), m3, collide: true)).name = "Side"; } for (int k = -1; k <= 1; k += 2) { Part(transform, "SideGlow", (PrimitiveType)3, new Vector3(0.31f, 1.25f, (float)k * 1.165f), new Vector3(0.008f, 2.36f, 0.012f), m); } Part(transform, "Top", (PrimitiveType)3, new Vector3(0.16f, 2.47f, 0f), new Vector3(0.3f, 0.03f, 2.36f), m3, collide: true); Label(transform, system, new Vector3(0.12f, 2.68f, 0f), 0.05f, Color.Lerp(val, Color.white, 0.35f), -90f); AddLight(transform, new Vector3(1.1f, 1.4f, 0f), val, 0.55f, 3.4f); return transform; } private void AddBox(Transform unit, MenuItem item, int row, int col) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_001f: 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_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00af: 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_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Expected O, but got Unknown //IL_0146: 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_0152: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Unknown result type (might be due to invalid IL or missing references) Material m = Lit(new Color(0.06f, 0.06f, 0.08f)); Transform transform = new GameObject("GameBox").transform; transform.SetParent(unit, false); transform.localPosition = new Vector3(0.15f, RowY(row) + 0.115f, -0.99f + (float)col * 0.22f); Part(transform, "Case", (PrimitiveType)3, Vector3.zero, new Vector3(0.025f, 0.2f, 0.185f), m, collide: true); GameObject obj = Part(transform, "Cover", (PrimitiveType)5, new Vector3(0.0135f, 0f, 0f), new Vector3(0.18f, 0.195f, 1f), m); obj.transform.localRotation = Quaternion.Euler(0f, -90f, 0f); bool real; Material val = new Material(Shader.Find("Standard")) { mainTexture = (Texture)(object)EmuSession.Instance.CoverFor(item, out real) }; val.SetFloat("_Glossiness", 0.55f); _boxMats.Add(val); obj.GetComponent().sharedMaterial = val; _boxes.Add(new GameBox { Item = item, T = transform, Home = unit, HomePos = transform.localPosition, HomeRot = transform.localRotation }); } private void ClearShelfBoxes() { ReturnHeld(sound: false); if ((Object)(object)_shelfRoot != (Object)null) { Object.Destroy((Object)(object)_shelfRoot); } _shelfRoot = null; foreach (Material boxMat in _boxMats) { if ((Object)(object)boxMat != (Object)null) { Object.Destroy((Object)(object)boxMat); } } _boxMats.Clear(); _boxes.Clear(); _shelfSig = null; } private bool ShelfTick() { _shelfHint = null; if (_inserting) { return true; } if (_held != null && (Object)(object)_held.T == (Object)null) { _held = null; _shelfSig = null; } if (_held != null && WalkedInto(_exit)) { ReturnHeld(sound: false); return false; } if (Time.unscaledTime >= _shelfCheckAt) { _shelfCheckAt = Time.unscaledTime + 2f; RebuildShelfBoxes(); } if (_held == null) { GameBox gameBox = LookedAtBox(); if (gameBox == null) { return false; } _shelfHint = "Take " + Short(gameBox.Item.Title); if (!Interact()) { return false; } Hold(gameBox); return true; } if (LookingAt(_consoleT, 28f)) { _shelfHint = "Put " + Short(_held.Item.Title) + " in the console"; if (Interact()) { ((MonoBehaviour)this).StartCoroutine(Insert(_held)); } return true; } _shelfHint = "Put it back on the shelf"; if (Interact()) { ReturnHeld(sound: true); } return true; } private GameBox LookedAtBox() { //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0056: 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_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) Camera main = Camera.main; if ((Object)(object)main == (Object)null) { return null; } GameBox result = null; float num = 9f; foreach (GameBox box in _boxes) { if ((Object)(object)box.T == (Object)null) { continue; } Vector3 val = box.T.position - ((Component)main).transform.position; if (!(((Vector3)(ref val)).magnitude > 2.4f)) { float num2 = Vector3.Angle(((Component)main).transform.forward, val); if (num2 < num) { num = num2; result = box; } } } return result; } private void Hold(GameBox box) { //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) Camera main = Camera.main; if (!((Object)(object)main == (Object)null)) { _held = box; box.T.SetParent(((Component)main).transform, false); box.T.localPosition = new Vector3(0.26f, -0.2f, 0.55f); box.T.localRotation = Quaternion.Euler(-8f, 70f, 0f); SetLayerColliders(box.T, on: false); } } private void ReturnHeld(bool sound) { //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) GameBox held = _held; _held = null; if (held != null && !((Object)(object)held.T == (Object)null) && !((Object)(object)_shelfRoot == (Object)null) && !((Object)(object)held.Home == (Object)null)) { held.T.SetParent(((Object)(object)held.Home != (Object)null) ? held.Home : _shelfRoot.transform, false); held.T.localPosition = held.HomePos; held.T.localRotation = held.HomeRot; SetLayerColliders(held.T, on: true); } } private static void SetLayerColliders(Transform t, bool on) { Collider[] componentsInChildren = ((Component)t).GetComponentsInChildren(); for (int i = 0; i < componentsInChildren.Length; i++) { componentsInChildren[i].enabled = on; } } private IEnumerator Insert(GameBox box) { _inserting = true; EmuSession emu = EmuSession.Instance; MenuItem item = box.Item; if (emu.Choose(item) == EmuSession.ChooseResult.NeedsConfirm) { Note("This closes " + Short(emu.RunningTitle) + " (unsaved progress is lost). Put the box in again to start it."); _inserting = false; yield break; } box.T.SetParent(_room.transform, true); Vector3 from = box.T.position; Quaternion fromRot = box.T.rotation; Vector3 to = _consoleT.position + _consoleT.up * 0.35f; for (float t = 0f; t < 0.35f; t += Time.unscaledDeltaTime) { box.T.position = Vector3.Lerp(from, to, t / 0.35f); box.T.rotation = Quaternion.Slerp(fromRot, _consoleT.rotation * Quaternion.Euler(0f, 0f, 90f), t / 0.35f); if ((Object)(object)_lid != (Object)null) { _lid.localRotation = Quaternion.Euler(-60f * t / 0.35f, 0f, 0f); } yield return null; } GameObject disc = Part(_consoleT, "Disc", (PrimitiveType)2, new Vector3(-0.06f, 0.3f, 0f), new Vector3(0.24f, 0.004f, 0.24f), Glow(new Color(0.85f, 0.85f, 0.95f))); for (float t = 0f; t < 0.3f; t += Time.unscaledDeltaTime) { disc.transform.localPosition = new Vector3(-0.06f, Mathf.Lerp(0.3f, 0.12f, t / 0.3f), 0f); yield return null; } for (float t = 0f; t < 0.25f; t += Time.unscaledDeltaTime) { if ((Object)(object)_lid != (Object)null) { _lid.localRotation = Quaternion.Euler(-60f * (1f - t / 0.25f), 0f, 0f); } yield return null; } if ((Object)(object)_lid != (Object)null) { _lid.localRotation = Quaternion.identity; } Object.Destroy((Object)(object)disc); _held = box; ReturnHeld(sound: false); _inserting = false; if (Inside) { emu.OpenScreen(); } } private static string Short(string title) { string text = title ?? ""; int num = text.IndexOf(" (", StringComparison.Ordinal); if (num <= 0) { return text; } return text.Substring(0, num); } private static float PosterZ(int i) { return -4f + (float)i * 2f; } private bool LookingAtPad() { return PadLookedAt() >= 0; } private int PadLookedAt() { for (int i = 0; i < _pads.Count; i++) { if (LookingAt(_pads[i].pad, 14f)) { return i; } } return -1; } private void AnimatePads() { //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_008f: 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_0094: 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_00a9: 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_00f2: 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_00fc: Unknown result type (might be due to invalid IL or missing references) Camera main = Camera.main; for (int i = 0; i < _pads.Count; i++) { var (val, val2, val3) = _pads[i]; if (!((Object)(object)val == (Object)null)) { string text = PS1Presence.PadHolder(i); Color val4 = (Color)((text == null) ? (new Color(0.3f, 0.8f, 1f) * (0.75f + 0.25f * Mathf.Sin(Time.time * 3f + (float)i))) : new Color(0.15f, 0.35f, 0.2f)); if (val2.IsKeywordEnabled("_EMISSION")) { val2.SetColor("_EmissionColor", val4); } else { val2.color = val4; } val3.text = text ?? ""; if ((Object)(object)main != (Object)null && text != null) { ((Component)val3).transform.rotation = Quaternion.LookRotation(((Component)val3).transform.position - ((Component)main).transform.position); } } } } private static Light AddLight(Transform parent, Vector3 pos, Color color, float intensity, float range) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) Light obj = new GameObject("Light").AddComponent(); ((Component)obj).transform.SetParent(parent, false); ((Component)obj).transform.localPosition = pos; obj.type = (LightType)2; obj.color = color; obj.intensity = intensity; obj.range = range; return obj; } private void AnimateScreens() { //IL_00b8: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_010d: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_014c: Unknown result type (might be due to invalid IL or missing references) PS1Stream instance = PS1Stream.Instance; EmuSession instance2 = EmuSession.Instance; Texture val = (Texture)(object)(((Object)(object)instance2 != (Object)null && instance2.Running) ? instance2.ScreenTexture : (((Object)(object)instance != (Object)null && instance.HasViewFrame) ? instance.ViewTexture : (((Object)(object)instance2 != (Object)null) ? instance2.ScreenTexture : null))); if ((Object)(object)_portalScreen != (Object)null) { if ((Object)(object)val != (Object)null) { SetScreen(_portalScreen, val, Color.white); } else { SetScreen(_portalScreen, null, Color.HSVToRGB(Mathf.Repeat(Time.time * 0.08f, 1f), 0.6f, 0.5f + 0.15f * Mathf.Sin(Time.time * 3f))); } } if ((Object)(object)_portalList != (Object)null) { _portalList.text = PS1Presence.InsideList(); } if ((Object)(object)_tvScreen != (Object)null) { SetScreen(_tvScreen, val, (Color)(((Object)(object)val != (Object)null) ? Color.white : new Color(0.04f, 0.05f, 0.08f))); } foreach (Material extraScreen in _extraScreens) { SetScreen(extraScreen, val, (Color)(((Object)(object)val != (Object)null) ? Color.white : new Color(0.08f, 0.02f, 0.12f))); } AnimatePads(); if ((Object)(object)_tvLight != (Object)null) { _tvLight.intensity = (((Object)(object)val != (Object)null) ? (1.5f + 0.25f * Mathf.PerlinNoise(Time.time * 6f, 0f)) : 0.5f); } } private static void SetScreen(Material m, Texture tex, Color tint) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)m.mainTexture != (Object)(object)tex) { m.mainTexture = tex; m.mainTextureScale = new Vector2(1f, -1f); m.mainTextureOffset = new Vector2(0f, 1f); if (m.IsKeywordEnabled("_EMISSION")) { m.SetTexture("_EmissionMap", tex); } } if (m.IsKeywordEnabled("_EMISSION")) { m.SetColor("_EmissionColor", tint); } else { m.color = tint; } } private static GameObject Part(Transform parent, string name, PrimitiveType type, Vector3 pos, Vector3 size, Material m, bool collide = false) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0030: 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) GameObject val = GameObject.CreatePrimitive(type); ((Object)val).name = name; if (!collide) { Object.Destroy((Object)(object)val.GetComponent()); } val.transform.SetParent(parent, false); val.transform.localPosition = pos; val.transform.localScale = size; val.GetComponent().sharedMaterial = m; return val; } private static TextMesh Label(Transform parent, string text, Vector3 pos, float size, Color c, float turn = 0f) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0017: 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_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject("Label"); val.transform.SetParent(parent, false); val.transform.localPosition = pos; val.transform.localRotation = Quaternion.Euler(0f, turn, 0f); TextMesh val2 = val.AddComponent(); val2.font = TextFont; ((Renderer)val.GetComponent()).sharedMaterial = TextFont.material; val2.text = text; val2.characterSize = size; val2.fontSize = 64; val2.color = c; val2.anchor = (TextAnchor)4; val2.alignment = (TextAlignment)1; return val2; } private static Material Lit(Color c) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Expected O, but got Unknown //IL_0046: Unknown result type (might be due to invalid IL or missing references) if (LitCache.TryGetValue(c, out var value) && (Object)(object)value != (Object)null) { return value; } Material val = new Material(Shader.Find("Standard")) { color = c }; val.SetFloat("_Glossiness", 0.2f); return LitCache[c] = val; } private static Material Glow(Color c) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_001f: 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) if (GlowCache.TryGetValue(c, out var value) && (Object)(object)value != (Object)null) { return value; } return GlowCache[c] = NewGlow(c); } private static Material NewGlow(Color c) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_005d: 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_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Expected O, but got Unknown //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: 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_0043: Expected O, but got Unknown string[] array = new string[3] { "Unlit/Texture", "UI/Default", "Sprites/Default" }; for (int i = 0; i < array.Length; i++) { Shader val = Shader.Find(array[i]); if ((Object)(object)val != (Object)null) { return new Material(val) { color = c }; } } Material val2 = new Material(Shader.Find("Standard")) { color = Color.black }; val2.EnableKeyword("_EMISSION"); val2.SetColor("_EmissionColor", c); return val2; } private static bool ParseFloats(string s, int count, out float[] v) { v = new float[count]; string[] array = (s ?? "").Split(','); if (array.Length != count) { return false; } for (int i = 0; i < count; i++) { if (!float.TryParse(array[i], NumberStyles.Float, CultureInfo.InvariantCulture, out v[i])) { return false; } } return true; } private void OnGUI() { //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_0062: 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_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Expected O, but got Unknown //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: 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_00da: Expected O, but got Unknown //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_0214: Unknown result type (might be due to invalid IL or missing references) if (_fade > 0.001f) { if ((Object)(object)_black == (Object)null) { _black = new Texture2D(1, 1); _black.SetPixel(0, 0, Color.black); _black.Apply(); } Color color = GUI.color; GUI.color = new Color(1f, 1f, 1f, _fade); GUI.DrawTexture(new Rect(0f, 0f, (float)Screen.width, (float)Screen.height), (Texture)(object)_black); GUI.color = color; } if (_moving || EmuSession.Open) { return; } if (_hint == null) { _hint = new GUIStyle(GUI.skin.label) { fontSize = 22, alignment = (TextAnchor)4, richText = true }; _hint.normal.textColor = Color.white; } if (Time.unscaledTime < _noteUntil) { GUI.Label(new Rect(0f, (float)Screen.height * 0.25f, (float)Screen.width, 40f), _note, _hint); } if (_placing) { GUI.Label(new Rect(0f, (float)Screen.height * 0.68f, (float)Screen.width, 40f), "Walk and look to aim [E]: place hereScroll / [R]: turn [Esc]: cancel", _hint); return; } string text = null; if (!Inside && (Object)(object)_portal != (Object)null && _portal.activeInHierarchy && LookingAt(_portalCenter)) { text = "Enter the game room"; } else if (Inside && _shelfHint != null) { text = _shelfHint; } else if (Inside && LookingAtPad()) { text = "Play"; } else if (Inside && LookingAt(_exit)) { text = "Back to the truck"; } if (text != null) { GUI.Label(new Rect(0f, (float)Screen.height * 0.6f, (float)Screen.width, 40f), "[E] " + text, _hint); } } } internal struct RemoteGame { public string Title; public string System; public string Folder; } internal sealed class PS1Stream : MonoBehaviour { private class HostSocket : SocketManager { private readonly Dictionary _actors = new Dictionary(); public bool NewViewers; public int ActorOf(Connection c) { if (!_actors.TryGetValue(((Connection)(ref c)).Id, out var value)) { return -1; } return value; } public bool HasActor(int actor) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) foreach (Connection item in base.Connected) { if (ActorOf(item) == actor) { return true; } } return false; } public override void OnConnecting(Connection connection, ConnectionInfo info) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: Unknown result type (might be due to invalid IL or missing references) NetIdentity identity = ((ConnectionInfo)(ref info)).Identity; string text = ((NetIdentity)(ref identity)).SteamId.Value.ToString(); PlayerAvatar val = SemiFunc.PlayerGetFromSteamID(text); int num = (((Object)(object)val != (Object)null && (Object)(object)val.photonView != (Object)null) ? val.photonView.OwnerActorNr : (-1)); REPOPS1Plugin.Log.LogInfo((object)("Game room: connection from " + text + " " + ((num >= 0) ? "accepted" : "rejected (not in this game)") + ".")); if (num < 0) { ((Connection)(ref connection)).Close(false, 0, "Closing Connection"); return; } _actors[((Connection)(ref connection)).Id] = num; ((Connection)(ref connection)).Accept(); } public override void OnConnected(Connection connection, ConnectionInfo info) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) ((SocketManager)this).OnConnected(connection, info); NewViewers = true; } public override void OnDisconnected(Connection connection, ConnectionInfo info) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_001c: 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) int num = ActorOf(connection); _actors.Remove(((Connection)(ref connection)).Id); ((SocketManager)this).OnDisconnected(connection, info); if (num >= 0) { EmuSession.Instance?.ReleasePort(num); } } public override void OnMessage(Connection connection, NetIdentity identity, IntPtr data, int size, long messageNum, long recvTime, int channel) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) if (size >= 1 && size <= 64) { byte[] array = new byte[size]; Marshal.Copy(data, array, 0, size); OnGuestMessage(ActorOf(connection), array); } } } private class ViewerConnection : ConnectionManager { public readonly Queue Frames = new Queue(); public PS1Stream Owner; public bool Failed; public bool IsConnected; public bool EverConnected; private byte[] _pcm = new byte[0]; public override void OnConnected(ConnectionInfo info) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) ((ConnectionManager)this).OnConnected(info); IsConnected = (EverConnected = true); REPOPS1Plugin.Log.LogInfo((object)"Game room: connected to the console."); } public override void OnMessage(IntPtr data, int size, long messageNum, long recvTime, int channel) { if (size < 2) { return; } byte b = Marshal.ReadByte(data); switch (b) { case 1: { byte[] array = new byte[size - 1]; Marshal.Copy(data + 1, array, 0, array.Length); Frames.Enqueue(array); while (Frames.Count > 4) { Frames.Dequeue(); } return; } case 2: if (size > 5 && (Object)(object)Owner?._viewAudio != (Object)null) { Owner._viewAudio.SetSourceRate(Marshal.ReadInt32(data + 1)); int num = size - 5; if (_pcm.Length < num) { _pcm = new byte[num]; } Marshal.Copy(data + 5, _pcm, 0, num); Owner._viewAudio.Push(_pcm, 0, num); return; } break; } if (((b == 3 && size >= 5) || (b == 4 && size >= 7)) && (Object)(object)Owner != (Object)null) { byte[] array2 = new byte[size]; Marshal.Copy(data, array2, 0, size); if (b == 3) { Owner.OnList(array2); } else { Owner.OnStatus(array2); } } } public override void OnDisconnected(ConnectionInfo info) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) ((ConnectionManager)this).OnDisconnected(info); Failed = true; IsConnected = false; REPOPS1Plugin.Log.LogInfo((object)$"Game room: console connection ended ({((ConnectionInfo)(ref info)).EndReason})."); } } public const int VirtualPort = 7791; private const byte MsgFrame = 1; private const byte MsgAudio = 2; private const byte MsgList = 3; private const byte MsgStatus = 4; private const byte MsgPad = 10; private const byte MsgStart = 11; private const byte MsgStop = 12; private const byte MsgTake = 13; private const byte MsgRelease = 14; private const int MaxBacklogFrames = 2; private HostSocket _socket; private ViewerConnection _conn; private int _viewingActor = -1; private int _failures; private float _retryAt; private float _lastStatusAt; private float _lastListCheckAt; private float _lastPadSentAt; private int _lastSentFrame; private int _listHash; private float _lastSentAt; private PadState _lastPad; private EmuAudio _viewAudio; private static bool _relayInit; private static readonly object PcmLock = new object(); private static byte[] _pcm = new byte[65536]; private static int _pcmLen; private static volatile bool _collect; private RenderTexture _readbackRt; private volatile bool _readbackBusy; private byte[] _readyJpg; private const int StreamMaxHeight = 480; public static PS1Stream Instance { get; private set; } public Texture2D ViewTexture { get; private set; } public bool HasViewFrame { get; private set; } public bool Connected { get { if (_conn != null) { return _conn.IsConnected; } return false; } } public bool RemoteHasGame { get; private set; } public string RemoteTitle { get; private set; } = ""; public float RemoteAspect { get; private set; } = 1.3333334f; public int MyPad { get; private set; } = -1; public List RemoteLibrary { get; } = new List(); public int RemoteVersion { get; private set; } public string RemoteOwnerName { get { if (_viewingActor < 0) { return ""; } Room currentRoom = PhotonNetwork.CurrentRoom; object s; if (currentRoom == null) { s = null; } else { Player player = currentRoom.GetPlayer(_viewingActor, false); s = ((player != null) ? player.NickName : null); } return Clean((string)s); } } private void Awake() { Instance = this; } public static void HostAudio(IntPtr data, int frames) { if (!_collect || frames <= 0) { return; } int num = frames * 4; lock (PcmLock) { if (_pcmLen + num > _pcm.Length) { if (_pcmLen + num > 1048576) { return; } Array.Resize(ref _pcm, Math.Max(_pcm.Length * 2, _pcmLen + num)); } Marshal.Copy(data, _pcm, _pcmLen, num); _pcmLen += num; } } public static void HostAudio(short left, short right) { if (!_collect) { return; } lock (PcmLock) { if (_pcmLen + 4 <= _pcm.Length) { _pcm[_pcmLen++] = (byte)left; _pcm[_pcmLen++] = (byte)(left >> 8); _pcm[_pcmLen++] = (byte)right; _pcm[_pcmLen++] = (byte)(right >> 8); } } } private void Update() { try { bool num = PhotonNetwork.InRoom && !PhotonNetwork.OfflineMode; EmuSession instance = EmuSession.Instance; if (num) { _ = (Object)(object)instance != (Object)null; } bool flag = false; if (flag && _socket == null) { StartHost(); } else if (!flag && _socket != null) { StopHost(); } _collect = _socket != null && ((SocketManager)_socket).Connected.Count > 0 && instance.HasGame; if (_socket != null) { HostTick(); } int num2 = ((num && PS1Room.Inside) ? PickConsole() : (-1)); if (num2 != _viewingActor) { StopViewer(); } if (num2 >= 0 && _conn == null && Time.unscaledTime >= _retryAt) { StartViewer(num2); } if (_conn != null) { ViewerTick(); } } catch (Exception ex) { REPOPS1Plugin.Log.LogError((object)("Game room stream: " + ex)); StopHost(); StopViewer(); _retryAt = Time.unscaledTime + 5f; } } private int PickConsole() { Room currentRoom = PhotonNetwork.CurrentRoom; if (EmuSession.RemoteMode && _viewingActor >= 0 && currentRoom.GetPlayer(_viewingActor, false) != null) { return _viewingActor; } Player[] playerListOthers = PhotonNetwork.PlayerListOthers; foreach (Player val in playerListOthers) { if (PS1Presence.StateOf(val) == 2) { return val.ActorNumber; } } Player masterClient = PhotonNetwork.MasterClient; if (masterClient == null || masterClient.IsLocal) { return -1; } return masterClient.ActorNumber; } private void OnDestroy() { StopHost(); StopViewer(); } private static void InitRelay() { if (!_relayInit) { SteamNetworkingUtils.InitRelayNetworkAccess(); _relayInit = true; } } private static string Clean(string s) { return (s ?? "").Replace("<", "").Replace(">", "").Trim(); } public bool IsWatching(int actor) { if (_socket != null) { return _socket.HasActor(actor); } return false; } private void StartHost() { InitRelay(); _socket = SteamNetworkingSockets.CreateRelaySocket(7791); _listHash = 0; REPOPS1Plugin.Log.LogInfo((object)$"Game room: console open to the room on relay port {7791}."); } private void StopHost() { _collect = false; lock (PcmLock) { _pcmLen = 0; } if (_socket != null) { try { ((SocketManager)_socket).Close(); } catch (Exception) { } _socket = null; REPOPS1Plugin.Log.LogInfo((object)"Game room: console closed to the room."); } } private void HostTick() { //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00db: 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_0145: Unknown result type (might be due to invalid IL or missing references) //IL_014a: Unknown result type (might be due to invalid IL or missing references) //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_01d3: Unknown result type (might be due to invalid IL or missing references) //IL_029b: Unknown result type (might be due to invalid IL or missing references) //IL_02a0: Unknown result type (might be due to invalid IL or missing references) //IL_02a8: 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_0394: Unknown result type (might be due to invalid IL or missing references) //IL_0399: Unknown result type (might be due to invalid IL or missing references) //IL_03dd: Unknown result type (might be due to invalid IL or missing references) ((SocketManager)_socket).Receive(32, true); HashSet connected = ((SocketManager)_socket).Connected; if (connected.Count == 0) { lock (PcmLock) { _pcmLen = 0; return; } } EmuSession instance = EmuSession.Instance; float unscaledTime = Time.unscaledTime; if (unscaledTime - _lastListCheckAt > 1f || _socket.NewViewers) { _lastListCheckAt = unscaledTime; instance.EnsureLibrary(); int num = ListHash(instance.Library); if (num != _listHash || _socket.NewViewers) { _listHash = num; _socket.NewViewers = false; byte[] array = ListMessage(instance.Library, num); foreach (Connection item in connected) { Connection current = item; ((Connection)(ref current)).SendMessage(array, (SendType)8, (ushort)0); } } } if (unscaledTime - _lastStatusAt > 0.25f) { _lastStatusAt = unscaledTime; byte[] bytes = Encoding.UTF8.GetBytes(instance.GameTitle ?? ""); foreach (Connection item2 in connected) { Connection current2 = item2; int num2 = _socket.ActorOf(current2); int num3 = -1; for (int i = 0; i < 4; i++) { if (num2 >= 0 && instance.PortOwner(i) == num2) { num3 = i; } } byte[] array2 = new byte[7 + bytes.Length]; array2[0] = 4; array2[1] = (instance.HasGame ? ((byte)1) : ((byte)0)); BitConverter.GetBytes(instance.Aspect).CopyTo(array2, 2); array2[6] = (byte)(sbyte)num3; Buffer.BlockCopy(bytes, 0, array2, 7, bytes.Length); ((Connection)(ref current2)).SendMessage(array2, (SendType)8, (ushort)0); } } if (!instance.HasGame) { lock (PcmLock) { _pcmLen = 0; return; } } byte[] array3 = null; lock (PcmLock) { if (_pcmLen > 0) { array3 = new byte[5 + _pcmLen]; array3[0] = 2; BitConverter.GetBytes((int)instance.SampleRate).CopyTo(array3, 1); Buffer.BlockCopy(_pcm, 0, array3, 5, _pcmLen); _pcmLen = 0; } } if (array3 != null) { foreach (Connection item3 in connected) { Connection current3 = item3; ((Connection)(ref current3)).SendMessage(array3, (SendType)9, (ushort)0); } } Texture2D screenTexture = instance.ScreenTexture; int value = REPOPS1Plugin.StreamFps.Value; if ((Object)(object)screenTexture == (Object)null || instance.FrameCount == _lastSentFrame || unscaledTime - _lastSentAt < 1f / (float)value) { return; } byte[] array4; if (((Texture)screenTexture).isReadable) { array4 = ImageConversion.EncodeToJPG(screenTexture, REPOPS1Plugin.StreamQuality.Value); } else { array4 = _readyJpg; _readyJpg = null; if (!_readbackBusy) { RequestReadback((Texture)(object)screenTexture); } if (array4 == null) { return; } } _lastSentFrame = instance.FrameCount; _lastSentAt = unscaledTime; byte[] array5 = new byte[1 + array4.Length]; array5[0] = 1; Buffer.BlockCopy(array4, 0, array5, 1, array4.Length); foreach (Connection item4 in connected) { Connection current4 = item4; ConnectionStatus val = ((Connection)(ref current4)).QuickStatus(); int num4 = 2 + (int)Math.Ceiling((float)Math.Max(0, ((ConnectionStatus)(ref val)).Ping) / 1000f * (float)value); if (((ConnectionStatus)(ref val)).PendingReliable + ((ConnectionStatus)(ref val)).SentUnackedReliable <= num4 * array5.Length) { ((Connection)(ref current4)).SendMessage(array5, (SendType)9, (ushort)0); } } } private void RequestReadback(Texture tex) { //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Expected O, but got Unknown //IL_00df: Unknown result type (might be due to invalid IL or missing references) int num = Math.Min(480, tex.height); int num2 = Math.Max(2, tex.width * num / Math.Max(1, tex.height) / 2 * 2); if ((Object)(object)_readbackRt == (Object)null || ((Texture)_readbackRt).width != num2 || ((Texture)_readbackRt).height != num) { if ((Object)(object)_readbackRt != (Object)null) { _readbackRt.Release(); Object.Destroy((Object)(object)_readbackRt); } _readbackRt = new RenderTexture(num2, num, 0, (RenderTextureFormat)0) { name = "REPOPS1 Stream Readback" }; } Graphics.Blit(tex, _readbackRt); _readbackBusy = true; int quality = REPOPS1Plugin.StreamQuality.Value; AsyncGPUReadback.Request((Texture)(object)_readbackRt, 0, (TextureFormat)4, (Action)delegate(AsyncGPUReadbackRequest req) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) _readbackBusy = false; if (!((AsyncGPUReadbackRequest)(ref req)).hasError) { NativeArray val = ImageConversion.EncodeNativeArrayToJPG(((AsyncGPUReadbackRequest)(ref req)).GetData(0), (GraphicsFormat)8, (uint)((AsyncGPUReadbackRequest)(ref req)).width, (uint)((AsyncGPUReadbackRequest)(ref req)).height, 0u, quality); _readyJpg = val.ToArray(); val.Dispose(); } }); } private static int ListHash(List games) { int num = 17 + games.Count; foreach (GameEntry game in games) { num = num * 31 + (game.Title + "\t" + game.System).GetHashCode(); } if (num != 0) { return num; } return 1; } private static byte[] ListMessage(List games, int version) { StringBuilder stringBuilder = new StringBuilder(); foreach (GameEntry game in games) { stringBuilder.Append(Tidy(game.Title)).Append('\t').Append(Tidy(game.System)) .Append('\t') .Append(Tidy(GameLibrary.SystemFolder(game))) .Append('\n'); } byte[] bytes = Encoding.UTF8.GetBytes(stringBuilder.ToString()); byte[] array = new byte[5 + bytes.Length]; array[0] = 3; BitConverter.GetBytes(version).CopyTo(array, 1); Buffer.BlockCopy(bytes, 0, array, 5, bytes.Length); return array; } private static string Tidy(string s) { return (s ?? "").Replace('\t', ' ').Replace('\n', ' ').Replace('\r', ' '); } private static void OnGuestMessage(int actor, byte[] msg) { EmuSession instance = EmuSession.Instance; if ((Object)(object)instance == (Object)null || actor < 0 || msg.Length == 0) { return; } switch (msg[0]) { case 10: if (msg.Length >= 11) { instance.RemotePad(actor, PadState.From(msg, 1)); } break; case 11: if (msg.Length >= 5) { instance.RemoteStart(actor, BitConverter.ToInt32(msg, 1)); } break; case 12: instance.RemoteStop(actor); break; case 13: if (instance.HasGame) { instance.TakePort(actor); } break; case 14: instance.ReleasePort(actor); break; } } public void SendPad(PadState pad) { //IL_00b0: Unknown result type (might be due to invalid IL or missing references) if (Connected) { float unscaledTime = Time.unscaledTime; if (pad.Buttons != _lastPad.Buttons || pad.Lx != _lastPad.Lx || pad.Ly != _lastPad.Ly || pad.Rx != _lastPad.Rx || pad.Ry != _lastPad.Ry || !(unscaledTime - _lastPadSentAt < 0.1f)) { _lastPad = pad; _lastPadSentAt = unscaledTime; byte[] array = new byte[11] { 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; pad.Write(array, 1); ((Connection)(ref ((ConnectionManager)_conn).Connection)).SendMessage(array, (SendType)1, (ushort)0); } } } public void SendStart(int index) { byte[] array = new byte[5] { 11, 0, 0, 0, 0 }; BitConverter.GetBytes(index).CopyTo(array, 1); SendControl(array); } public void SendStop() { SendControl(new byte[1] { 12 }); } public void SendTakePad() { SendControl(new byte[1] { 13 }); } public void SendReleasePad() { SendControl(new byte[1] { 14 }); _lastPad = default(PadState); } private void SendControl(byte[] msg) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) if (Connected) { ((Connection)(ref ((ConnectionManager)_conn).Connection)).SendMessage(msg, (SendType)8, (ushort)0); } } private void StartViewer(int actor) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_003e: 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) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Expected O, but got Unknown //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Expected O, but got Unknown if (!ulong.TryParse(PS1Identity.SteamIdOfActor(actor), out var result)) { _retryAt = Time.unscaledTime + 2f; return; } InitRelay(); _viewingActor = actor; _conn = SteamNetworkingSockets.ConnectRelay(new SteamId { Value = result }, 7791); _conn.Owner = this; if ((Object)(object)ViewTexture == (Object)null) { ViewTexture = new Texture2D(2, 2, (TextureFormat)4, false) { name = "REPOPS1 Stream", wrapMode = (TextureWrapMode)1 }; } if ((Object)(object)_viewAudio == (Object)null) { GameObject val = new GameObject("REPOPS1_StreamAudio"); Object.DontDestroyOnLoad((Object)(object)val); ((Object)val).hideFlags = (HideFlags)61; _viewAudio = val.AddComponent(); } _viewAudio.Clear(); REPOPS1Plugin.Log.LogInfo((object)$"Game room: connecting to player {actor}'s console."); } private void StopViewer() { HasViewFrame = false; RemoteHasGame = false; RemoteTitle = ""; MyPad = -1; if (RemoteLibrary.Count > 0) { RemoteLibrary.Clear(); RemoteVersion++; } _viewingActor = -1; if ((Object)(object)_viewAudio != (Object)null) { _viewAudio.Clear(); } if (_conn != null) { try { ((ConnectionManager)_conn).Close(false, 0, "Closing Connection"); } catch (Exception) { } _conn = null; REPOPS1Plugin.Log.LogInfo((object)"Game room: disconnected from the console."); } } private void ViewerTick() { //IL_010b: Unknown result type (might be due to invalid IL or missing references) ((ConnectionManager)_conn).Receive(32, true); if (_conn.Failed) { bool everConnected = _conn.EverConnected; StopViewer(); _failures = ((!everConnected) ? (_failures + 1) : 0); _retryAt = Time.unscaledTime + ((_failures < 3) ? 3f : 30f); return; } byte[] array = null; while (_conn.Frames.Count > 0) { array = _conn.Frames.Dequeue(); } if (array != null && ImageConversion.LoadImage(ViewTexture, array, false)) { ((Texture)ViewTexture).filterMode = (FilterMode)(REPOPS1Plugin.Smooth.Value ? 1 : 0); HasViewFrame = true; } if (!RemoteHasGame) { HasViewFrame = false; } bool flag = EmuSession.Open && EmuSession.RemoteMode; _viewAudio.SetSpatial(!flag); if ((Object)(object)PS1Room.Tv != (Object)null) { ((Component)_viewAudio).transform.position = PS1Room.Tv.position; } _viewAudio.Volume = ((flag || PS1Room.Inside) ? REPOPS1Plugin.Volume.Value : 0f); } private void OnList(byte[] msg) { RemoteLibrary.Clear(); string[] array = Encoding.UTF8.GetString(msg, 5, msg.Length - 5).Split('\n'); foreach (string text in array) { if (text.Length != 0) { string[] array2 = text.Split('\t'); RemoteLibrary.Add(new RemoteGame { Title = array2[0], System = ((array2.Length > 1) ? array2[1] : ""), Folder = ((array2.Length > 2) ? array2[2] : "") }); } } RemoteVersion++; } private void OnStatus(byte[] msg) { bool remoteHasGame = RemoteHasGame; RemoteHasGame = msg[1] != 0; float num = BitConverter.ToSingle(msg, 2); RemoteAspect = ((num > 0.2f && num < 5f) ? num : 1.3333334f); MyPad = (sbyte)msg[6]; string text = Encoding.UTF8.GetString(msg, 7, msg.Length - 7); if (remoteHasGame != RemoteHasGame || text != RemoteTitle) { RemoteVersion++; } RemoteTitle = text; } } internal sealed class QuickMenu { private sealed class Item { public string Label; public Func Value; public Action Change; public Action Press; } private static readonly int[] Scales = new int[10] { 1, 2, 3, 4, 5, 6, 8, 10, 12, 16 }; private readonly EmuSession _emu; private readonly List _items = new List(); private int _sel; private int _slot = 1; private int _top; private bool _optionsPage; private GUIStyle _title; private GUIStyle _row; private GUIStyle _value; private GUIStyle _hint; private static readonly string[] PadNames = new string[16] { "Cross", "Square", "Select", "Start", "Up", "Down", "Left", "Right", "Circle", "Triangle", "L1", "R1", "L2", "R2", "L3", "R3" }; public bool IsOpen { get; private set; } private static string ScaleName(int s) { return s switch { 16 => "16x (maximum)", 6 => "6x (about 4K)", 4 => "4x (about 1440p)", 3 => "3x (about 1080p)", 1 => "Original PS1 (1x)", _ => s + "x", }; } public QuickMenu(EmuSession emu) { _emu = emu; } public void Open() { IsOpen = true; _optionsPage = false; Build(); _sel = 0; } public void Close() { IsOpen = false; } private void Build() { _items.Clear(); _top = 0; if (_optionsPage) { BuildOptions(); return; } bool remoteMode = EmuSession.RemoteMode; Add("Resume", null, null, Close); if (!remoteMode && _emu.HasGame) { Add("State slot", () => $"< {_slot} > {_emu.SlotInfo(_slot)}", delegate(int d) { _slot = Mathf.Clamp(_slot + d, 1, 9); }, null); Add("Save state", () => "slot " + _slot, null, delegate { _emu.SaveSlot(_slot); Close(); }); Add("Load state", () => "slot " + _slot, null, delegate { if (_emu.LoadSlot(_slot)) { Close(); } }); if (_emu.DiscCount > 1) { Add("Change disc", () => $"{_emu.DiscCount} discs: puts the next one in", null, delegate { _emu.NextDisc(); Close(); }); } Add("Reset game", null, null, delegate { _emu.ResetGame(); Close(); }); Add("Turn the game off", null, null, delegate { Close(); _emu.PowerOff(); }); Add("Picture quality", () => (!_emu.HwActive) ? "Original (GPU renderer needed for more)" : ("< " + ScaleName(REPOPS1Plugin.ResolutionScale.Value) + " > emulator: " + (_emu.CoreScaleValue() ?? "?")), delegate(int d) { if (_emu.HwActive) { int num = Array.IndexOf(Scales, REPOPS1Plugin.ResolutionScale.Value); num = Mathf.Clamp(((num < 0) ? 2 : num) + d, 0, Scales.Length - 1); REPOPS1Plugin.ResolutionScale.Value = Scales[num]; if (Scales[num] == 1) { REPOPS1Plugin.Enhancements.Value = false; } _emu.ApplyVideoSettings(); } }, null); Add("Widescreen 16:9", () => OnOff(REPOPS1Plugin.Widescreen.Value), delegate { REPOPS1Plugin.Widescreen.Value = !REPOPS1Plugin.Widescreen.Value; _emu.ApplyVideoSettings(); }, null); Add("Enhancements (steady 3D, true colour)", () => (!_emu.HwActive) ? "GPU renderer only" : OnOff(REPOPS1Plugin.Enhancements.Value), delegate { if (_emu.HwActive) { REPOPS1Plugin.Enhancements.Value = !REPOPS1Plugin.Enhancements.Value; _emu.ApplyVideoSettings(); } }, null); Add("Renderer", () => "running now: " + (_emu.HwActive ? "GPU" : "Software") + " next game: < " + REPOPS1Plugin.Renderer.Value + " >", delegate { REPOPS1Plugin.Renderer.Value = ((REPOPS1Plugin.Renderer.Value == "GPU") ? "Software" : "GPU"); _emu.Note("Renderer: " + REPOPS1Plugin.Renderer.Value + " from the next game you start. This one keeps running."); }, null); Add("Emulator settings...", () => _emu.CoreOptionKeys().Count + " settings", null, delegate { _optionsPage = true; Build(); _sel = 0; }); } Add("Smooth picture", () => OnOff(REPOPS1Plugin.Smooth.Value), delegate { REPOPS1Plugin.Smooth.Value = !REPOPS1Plugin.Smooth.Value; }, null); Add("Fill the screen", () => OnOff(REPOPS1Plugin.Stretch.Value), delegate { REPOPS1Plugin.Stretch.Value = !REPOPS1Plugin.Stretch.Value; }, null); Add("Volume", () => $"< {Mathf.RoundToInt(REPOPS1Plugin.Volume.Value * 100f)}% >", delegate(int d) { REPOPS1Plugin.Volume.Value = Mathf.Clamp(Mathf.Round(REPOPS1Plugin.Volume.Value * 10f + (float)d) / 10f, 0f, 2f); }, null); if (remoteMode) { Add("Leave the game", null, null, delegate { Close(); _emu.PowerOff(); }); } Add("Controller test", PressedNow, null, null); Add("Game list", null, null, delegate { Close(); _emu.ShowGameList(); }); Add("Back to the room", null, null, delegate { Close(); _emu.Close(); }); } private void BuildOptions() { Add("< Back", null, null, delegate { _optionsPage = false; Build(); _sel = 0; }); foreach (string item in _emu.CoreOptionKeys()) { string text = item.ToLowerInvariant(); if (LibretroCore.IsPolicyKey(item) || text.Contains("renderer") || (text.Contains("gpu") && text.Contains("usethread"))) { continue; } string k = item; Add(Pretty(k), () => "< " + (_emu.CoreOptionValue(k) ?? "?") + " >", delegate(int d) { string[] array = _emu.CoreOptionChoices(k); if (array.Length != 0) { int num = Array.IndexOf(array, _emu.CoreOptionValue(k)); _emu.SetCoreOption(k, array[(((num >= 0) ? num : 0) + d + array.Length) % array.Length]); } }, null); } } private static string Pretty(string key) { string text = key; int num = text.IndexOf('_'); if (num > 0) { text = text.Substring(num + 1); } StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < text.Length; i++) { char c = text[i]; if (c == '_') { stringBuilder.Append(' '); continue; } if (i > 0 && char.IsUpper(c) && char.IsLower(text[i - 1])) { stringBuilder.Append(' '); } stringBuilder.Append(c); } return stringBuilder.ToString(); } private void Add(string label, Func value, Action change, Action press) { _items.Add(new Item { Label = label, Value = value, Change = change, Press = (press ?? ((change != null) ? ((Action)delegate { change(1); }) : null)) }); } private static string OnOff(bool v) { if (!v) { return "Off"; } return "On"; } private string PressedNow() { PadState padState = EmuInput.Sample(active: true); StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < 16; i++) { if ((padState.Buttons & (1 << i)) != 0) { stringBuilder.Append(PadNames[i]).Append(" "); } } if (Math.Abs((int)padState.Lx) > 8000 || Math.Abs((int)padState.Ly) > 8000) { stringBuilder.Append("Left stick "); } if (Math.Abs((int)padState.Rx) > 8000 || Math.Abs((int)padState.Ry) > 8000) { stringBuilder.Append("Right stick "); } int localPad = _emu.LocalPad; return ((stringBuilder.Length > 0) ? stringBuilder.ToString().Trim() : "press any button") + ((localPad >= 0) ? $" (you: Pad {localPad + 1})" : " (no pad)"); } public void Tick() { if (!IsOpen) { return; } int num = EmuInput.StickStep(); if (Input.GetKeyDown((KeyCode)274) || Input.GetKeyDown((KeyCode)115) || EmuInput.PadPressed((Gamepad g) => g.dpad.down)) { num = 1; } if (Input.GetKeyDown((KeyCode)273) || Input.GetKeyDown((KeyCode)119) || EmuInput.PadPressed((Gamepad g) => g.dpad.up)) { num = -1; } if (Input.GetKeyDown((KeyCode)281) || EmuInput.PadPressed((Gamepad g) => g.rightShoulder)) { num = 10; } if (Input.GetKeyDown((KeyCode)280) || EmuInput.PadPressed((Gamepad g) => g.leftShoulder)) { num = -10; } _sel = ((Math.Abs(num) > 1) ? Mathf.Clamp(_sel + num, 0, _items.Count - 1) : ((_sel + num + _items.Count) % _items.Count)); Item item = _items[_sel]; int num2 = 0; if (Input.GetKeyDown((KeyCode)275) || Input.GetKeyDown((KeyCode)100) || EmuInput.PadPressed((Gamepad g) => g.dpad.right)) { num2 = 1; } if (Input.GetKeyDown((KeyCode)276) || Input.GetKeyDown((KeyCode)97) || EmuInput.PadPressed((Gamepad g) => g.dpad.left)) { num2 = -1; } if (num2 != 0) { item.Change?.Invoke(num2); } if (EmuInput.PadPressed((Gamepad g) => g.buttonEast) || Input.GetKeyDown((KeyCode)8)) { if (_optionsPage) { _optionsPage = false; Build(); _sel = 0; } else { Close(); } } else if (Input.GetKeyDown((KeyCode)13) || Input.GetKeyDown((KeyCode)271) || EmuInput.PadPressed((Gamepad g) => g.buttonSouth)) { item.Press?.Invoke(); } } public void Draw() { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: 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_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003f: 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_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005e: 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_0071: Expected O, but got Unknown //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0089: 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_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: 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_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: 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_00f7: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_01b7: Unknown result type (might be due to invalid IL or missing references) //IL_01bc: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01f2: Unknown result type (might be due to invalid IL or missing references) //IL_0215: Unknown result type (might be due to invalid IL or missing references) //IL_0224: Unknown result type (might be due to invalid IL or missing references) //IL_0247: Unknown result type (might be due to invalid IL or missing references) //IL_025a: Unknown result type (might be due to invalid IL or missing references) //IL_0269: Unknown result type (might be due to invalid IL or missing references) //IL_029b: Unknown result type (might be due to invalid IL or missing references) //IL_04a7: Unknown result type (might be due to invalid IL or missing references) //IL_03aa: Unknown result type (might be due to invalid IL or missing references) //IL_0340: Unknown result type (might be due to invalid IL or missing references) //IL_0372: Unknown result type (might be due to invalid IL or missing references) //IL_0381: Unknown result type (might be due to invalid IL or missing references) //IL_0451: Unknown result type (might be due to invalid IL or missing references) if (!IsOpen) { return; } if (_title == null) { _title = new GUIStyle(GUI.skin.label) { fontSize = 30, alignment = (TextAnchor)4, richText = true }; _row = new GUIStyle(GUI.skin.label) { fontSize = 21, alignment = (TextAnchor)3, richText = true, clipping = (TextClipping)1 }; _value = new GUIStyle(_row) { alignment = (TextAnchor)5 }; _hint = new GUIStyle(GUI.skin.label) { fontSize = 16, alignment = (TextAnchor)4, richText = true }; GUIStyleState normal = _title.normal; GUIStyleState normal2 = _row.normal; GUIStyleState normal3 = _value.normal; Color val = (_hint.normal.textColor = Color.white); Color val2 = (normal3.textColor = val); Color textColor = (normal2.textColor = val2); normal.textColor = textColor; } int num = Mathf.Min(_items.Count, Mathf.Max(5, (int)(((float)Screen.height * 0.8f - 130f) / 38f))); if (_sel < _top) { _top = _sel; } if (_sel >= _top + num) { _top = _sel - num + 1; } float num2 = Mathf.Min(900f, (float)Screen.width * 0.85f); float num3 = 124f + (float)num * 38f; float num4 = ((float)Screen.width - num2) / 2f; float num5 = ((float)Screen.height - num3) / 2f; Color color = GUI.color; GUI.color = new Color(0f, 0f, 0f, 0.6f); GUI.DrawTexture(new Rect(0f, 0f, (float)Screen.width, (float)Screen.height), (Texture)(object)Texture2D.whiteTexture); GUI.color = new Color(0.08f, 0.05f, 0.16f, 0.95f); GUI.DrawTexture(new Rect(num4, num5, num2, num3), (Texture)(object)Texture2D.whiteTexture); GUI.color = new Color(0.85f, 0.25f, 0.85f, 1f); GUI.DrawTexture(new Rect(num4, num5, num2, 3f), (Texture)(object)Texture2D.whiteTexture); GUI.color = color; string text = (_optionsPage ? "Emulator settings" : _emu.GameTitleForMenu); GUI.Label(new Rect(num4, num5 + 10f, num2, 44f), "" + (text ?? "").Replace("<", "‹").Replace(">", "›") + "", _title); Rect val5 = default(Rect); for (int i = 0; i < num && _top + i < _items.Count; i++) { int num6 = _top + i; ((Rect)(ref val5))..ctor(num4 + 30f, num5 + 62f + (float)i * 38f, num2 - 60f, 34f); if (num6 == _sel) { GUI.color = new Color(0.55f, 0.2f, 0.9f, 0.9f); GUI.DrawTexture(new Rect(((Rect)(ref val5)).x - 12f, ((Rect)(ref val5)).y, ((Rect)(ref val5)).width + 24f, ((Rect)(ref val5)).height), (Texture)(object)Texture2D.whiteTexture); GUI.color = color; } GUI.Label(new Rect(((Rect)(ref val5)).x, ((Rect)(ref val5)).y, ((Rect)(ref val5)).width * 0.55f, ((Rect)(ref val5)).height), ((num6 == _sel) ? "" : "") + _items[num6].Label + ((num6 == _sel) ? "" : ""), _row); string text2 = _items[num6].Value?.Invoke(); if (text2 != null) { GUI.Label(new Rect(((Rect)(ref val5)).x + ((Rect)(ref val5)).width * 0.4f, ((Rect)(ref val5)).y, ((Rect)(ref val5)).width * 0.6f, ((Rect)(ref val5)).height), "" + text2 + "", _value); } } GUI.Label(new Rect(num4, num5 + num3 - 44f, num2, 36f), "Up / Down: choose Left / Right: change Enter / A: select B / Circle: back L3 + R3: close", _hint); } } [BepInPlugin("repops1.platform", "REPO Game Room", "0.1.0")] public class REPOPS1Plugin : BaseUnityPlugin { public const string Guid = "repops1.platform"; public const string Name = "REPO Game Room"; public const string Version = "0.1.0"; public const bool GuestOnly = true; internal static REPOPS1Plugin Instance; internal static ManualLogSource Log; internal static ConfigEntry CorePath; internal static ConfigEntry GamePath; internal static ConfigEntry SystemDirectory; internal static ConfigEntry CoreOptions; internal static ConfigEntry GamesFolder; internal static ConfigEntry CoresFolder; internal static ConfigEntry CoreForExtension; internal static ConfigEntry SystemFolders; internal static ConfigEntry ExternalEmulators; internal static ConfigEntry ToggleKey; internal static ConfigEntry ChangeGameKey; internal static ConfigEntry Volume; internal static ConfigEntry Smooth; internal static ConfigEntry Stretch; internal static ConfigEntry PlayAnywhere; internal static ConfigEntry PortalSpot; internal static ConfigEntry PortalOffset; internal static ConfigEntry PlacePortalKey; internal static ConfigEntry StreamFps; internal static ConfigEntry StreamQuality; internal static ConfigEntry Renderer; internal static ConfigEntry ResolutionScale; internal static ConfigEntry Widescreen; internal static ConfigEntry Enhancements; internal static ConfigEntry QuickMenuKey; internal static ConfigEntry DownloadCovers; internal static ConfigEntry CoreDebugLog; internal static ConfigEntry EmulationThread; internal static ConfigEntry D3D11Level110; internal static ConfigEntry CoverSystems; internal static ConfigEntry ShelfSystems; private static ConfigEntry[] _padKeys; private static readonly string[] PadNames = new string[16] { "B", "Y", "Select", "Start", "Up", "Down", "Left", "Right", "A", "X", "L", "R", "L2", "R2", "L3", "R3" }; private static readonly string[] PadHints = new string[16] { "PS1 Cross, SNES B", "PS1 Square, SNES Y", "", "", "", "", "", "", "PS1 Circle, SNES A", "PS1 Triangle, SNES X", "PS1 L1", "PS1 R1", "", "", "", "" }; private static readonly KeyCode[] PadDefaults; internal static KeyCode PadKey(uint id) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) if (_padKeys == null || id >= _padKeys.Length) { return (KeyCode)0; } return _padKeys[id].Value; } private void Awake() { //IL_0257: Unknown result type (might be due to invalid IL or missing references) //IL_0261: Expected O, but got Unknown //IL_02e0: Unknown result type (might be due to invalid IL or missing references) //IL_02ea: Expected O, but got Unknown //IL_0312: Unknown result type (might be due to invalid IL or missing references) //IL_031c: Expected O, but got Unknown //IL_0472: Unknown result type (might be due to invalid IL or missing references) //IL_047c: Expected O, but got Unknown //IL_04a6: Unknown result type (might be due to invalid IL or missing references) //IL_04b0: Expected O, but got Unknown //IL_0564: Unknown result type (might be due to invalid IL or missing references) //IL_0569: Unknown result type (might be due to invalid IL or missing references) //IL_056f: Expected O, but got Unknown //IL_056f: Unknown result type (might be due to invalid IL or missing references) //IL_0577: Unknown result type (might be due to invalid IL or missing references) //IL_057e: Unknown result type (might be due to invalid IL or missing references) //IL_0585: Unknown result type (might be due to invalid IL or missing references) Instance = this; Log = ((BaseUnityPlugin)this).Logger; GamesFolder = ((BaseUnityPlugin)this).Config.Bind("Paths", "GamesFolder", "", "Folders with your own games, separated by ; (e.g. one per system). Subfolders too. Every file a core in CoresFolder can play is listed and put on that core's shelf."); CoresFolder = ((BaseUnityPlugin)this).Config.Bind("Paths", "CoresFolder", "", "Folder with libretro cores (*_libretro.dll), one per system: e.g. swanstation (PS1), snes9x (SNES), mgba (GBA), genesis_plus_gx (Mega Drive). Download them yourself; the mod ships none."); CoreForExtension = ((BaseUnityPlugin)this).Config.Bind("Paths", "CoreForExtension", "", "When several cores play the same file type: extension=part of the core's file name; ... (e.g. bin=swanstation; iso=swanstation)."); SystemFolders = ((BaseUnityPlugin)this).Config.Bind("Paths", "SystemFolders", "", "A system folder per system, when a core wants its own layout: PS2=E:\\Emu\\PS2 (the PS2 core reads pcsx2\\bios inside it); ..."); CorePath = ((BaseUnityPlugin)this).Config.Bind("Paths", "CorePath", "", "Optional single core DLL, in addition to CoresFolder."); ExternalEmulators = ((BaseUnityPlugin)this).Config.Bind("Paths", "ExternalEmulators", "", "Systems played with a real emulator program instead of a core: PS2=E:\\pcsx2\\pcsx2-qt.exe; ... It runs with its own settings behind R.E.P.O and its window is shown on the screen."); GamePath = ((BaseUnityPlugin)this).Config.Bind("Paths", "GamePath", "", "Optional single game file, in addition to GamesFolder."); SystemDirectory = ((BaseUnityPlugin)this).Config.Bind("Paths", "SystemDirectory", "", "Folder the cores look in for BIOS files. Empty = BepInEx/config/REPOPS1/system."); CoreOptions = ((BaseUnityPlugin)this).Config.Bind("Core", "Options", "", "Overrides for the core's own options: key=value; key=value. The available keys and values are written to the BepInEx log when the game starts."); ToggleKey = ((BaseUnityPlugin)this).Config.Bind("Controls", "ToggleKey", (KeyCode)289, "Open/close the game screen (Esc also closes it)."); ChangeGameKey = ((BaseUnityPlugin)this).Config.Bind("Controls", "ChangeGameKey", (KeyCode)288, "While playing: close the game and go back to the game list."); PlayAnywhere = ((BaseUnityPlugin)this).Config.Bind("Controls", "PlayAnywhere", false, "Let the toggle key open the game screen outside the game room too (for testing: monsters can still reach you)."); PlacePortalKey = ((BaseUnityPlugin)this).Config.Bind("Room", "PlacePortalKey", (KeyCode)290, "Host: place the game room portal anywhere (preview, then E to place)."); PortalSpot = ((BaseUnityPlugin)this).Config.Bind("Room", "PortalSpot", "", "Host: where the portal stands in the truck, relative to the truck's screen: x, y, z, turn (set it with PlacePortalKey)."); PortalOffset = ((BaseUnityPlugin)this).Config.Bind("Room", "PortalOffset", "1.3, 1.8, 90", "Fallback before PortalSpot is set: metres right of your truck spawn, metres forward, turn in degrees."); Volume = ((BaseUnityPlugin)this).Config.Bind("Audio", "Volume", 1f, new ConfigDescription("Emulator volume.", (AcceptableValueBase)(object)new AcceptableValueRange(0f, 2f), Array.Empty())); Smooth = ((BaseUnityPlugin)this).Config.Bind("Video", "Smooth", false, "Smooth the picture when scaling (off = sharp pixels)."); Stretch = ((BaseUnityPlugin)this).Config.Bind("Video", "Stretch", false, "Stretch the picture to the whole screen instead of keeping the game's aspect ratio."); Renderer = ((BaseUnityPlugin)this).Config.Bind("Video", "Renderer", "GPU", new ConfigDescription("GPU = cores that can draw with Direct3D 11 do (SwanStation: sharp upscaling). Software = always on the CPU (native resolution; use it if GPU mode misbehaves).", (AcceptableValueBase)(object)new AcceptableValueList(new string[2] { "GPU", "Software" }), Array.Empty())); ResolutionScale = ((BaseUnityPlugin)this).Config.Bind("Video", "ResolutionScale", 3, new ConfigDescription("GPU mode: internal resolution, times the console's own (PS1: 1 = original, 3 = about 1080p, 6 = about 4K, 16 = the emulator's maximum).", (AcceptableValueBase)(object)new AcceptableValueRange(1, 16), Array.Empty())); Widescreen = ((BaseUnityPlugin)this).Config.Bind("Video", "Widescreen", false, "16:9 widescreen hack where the core has one (works in most 3D games; some HUDs stretch)."); Enhancements = ((BaseUnityPlugin)this).Config.Bind("Video", "Enhancements", true, "GPU mode, PS1: steadier 3D (PGXP) and full colour (true colour)."); EmulationThread = ((BaseUnityPlugin)this).Config.Bind("Video", "EmulationThread", true, "Software rendering: run the emulator on its own thread at the console's own speed (smooth PS2 next to R.E.P.O). Off = inside R.E.P.O's frames, as before."); D3D11Level110 = ((BaseUnityPlugin)this).Config.Bind("Video", "D3D11FeatureLevel110", true, "GPU mode: tell a running GPU core the device is Direct3D 11.0 (as RetroArch's is). PS2 (PCSX2) cores need it to draw at all."); CoreDebugLog = ((BaseUnityPlugin)this).Config.Bind("Core", "DebugLog", true, "Write the cores' debug messages to the BepInEx log too (for finding problems; turn off when all works)."); QuickMenuKey = ((BaseUnityPlugin)this).Config.Bind("Controls", "QuickMenuKey", (KeyCode)287, "While playing: the quick menu (also L3 + R3 on a gamepad): save/load state, picture settings, reset."); DownloadCovers = ((BaseUnityPlugin)this).Config.Bind("Covers", "Download", true, "Fetch a missing box picture from the libretro thumbnail library by the game file's exact name, into GamesFolder\\Covers (on this PC only)."); CoverSystems = ((BaseUnityPlugin)this).Config.Bind("Covers", "Systems", "PS1=Sony - PlayStation; PSX=Sony - PlayStation; PS2=Sony - PlayStation 2; PSP=Sony - PlayStation Portable; SNES=Nintendo - Super Nintendo Entertainment System; NES=Nintendo - Nintendo Entertainment System; N64=Nintendo - Nintendo 64; GBA=Nintendo - Game Boy Advance; GBC=Nintendo - Game Boy Color; GB=Nintendo - Game Boy; Genesis=Sega - Mega Drive - Genesis; MegaDrive=Sega - Mega Drive - Genesis", "Core folder name = libretro thumbnail system name, for downloading covers."); ShelfSystems = ((BaseUnityPlugin)this).Config.Bind("Room", "Shelves", "PS1, PS2", "Shelf units in the game room, left to right, named like the core folders (Cores\\PS1 -> PS1). Systems with games get a unit anyway (max 4)."); StreamFps = ((BaseUnityPlugin)this).Config.Bind("Stream", "FramesPerSecond", 30, new ConfigDescription("While you play: frames per second sent to the others in the room.", (AcceptableValueBase)(object)new AcceptableValueRange(10, 60), Array.Empty())); StreamQuality = ((BaseUnityPlugin)this).Config.Bind("Stream", "JpegQuality", 80, new ConfigDescription("While you play: picture quality sent to the others (higher = sharper, more upload).", (AcceptableValueBase)(object)new AcceptableValueRange(30, 95), Array.Empty())); _padKeys = new ConfigEntry[PadNames.Length]; for (int i = 0; i < PadNames.Length; i++) { _padKeys[i] = ((BaseUnityPlugin)this).Config.Bind("Keyboard", PadNames[i], PadDefaults[i], "Keyboard key for the pad's " + PadNames[i] + " button" + ((PadHints[i].Length > 0) ? (" (" + PadHints[i] + ")") : "") + ". A gamepad works too."); } GameObject val = new GameObject("REPOPS1"); Object.DontDestroyOnLoad((Object)val); ((Object)val).hideFlags = (HideFlags)61; val.AddComponent(); val.AddComponent(); val.AddComponent(); val.AddComponent(); RoomShield.Apply(); } static REPOPS1Plugin() { KeyCode[] array = new KeyCode[16]; RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); PadDefaults = (KeyCode[])(object)array; } } internal static class RoomShield { private static readonly Type[] Targets = new Type[3] { typeof(PlayerHealth), typeof(PlayerAvatar), typeof(PlayerTumble) }; private static int _hostDepth; public static void Apply() { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Expected O, but got Unknown //IL_015b: Unknown result type (might be due to invalid IL or missing references) //IL_0169: Expected O, but got Unknown Harmony val = new Harmony("repops1.platform.shield"); HarmonyMethod val2 = new HarmonyMethod(typeof(RoomShield), "RpcPrefix", (Type[])null); HarmonyMethod val3 = new HarmonyMethod(typeof(RoomShield), "RpcFinalizer", (Type[])null); int num = 0; Type[] targets = Targets; foreach (Type type in targets) { MethodInfo[] methods = type.GetMethods(BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (MethodInfo methodInfo in methods) { if (!methodInfo.IsAbstract && !methodInfo.ContainsGenericParameters && methodInfo.GetParameters().Any((ParameterInfo p) => p.ParameterType == typeof(PhotonMessageInfo))) { try { val.Patch((MethodBase)methodInfo, val2, (HarmonyMethod)null, (HarmonyMethod)null, val3, (HarmonyMethod)null); num++; } catch (Exception ex) { REPOPS1Plugin.Log.LogWarning((object)("Shield: can't guard " + type.Name + "." + methodInfo.Name + ": " + ex.Message)); } } } } val.Patch((MethodBase)AccessTools.Method(typeof(PlayerHealth), "Hurt", (Type[])null, (Type[])null), new HarmonyMethod(typeof(RoomShield), "HurtPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); REPOPS1Plugin.Log.LogInfo((object)$"Shield: guarding {num} network calls in the game room."); } private static bool Shielded(Component target) { if (!PS1Room.Inside || (Object)(object)target == (Object)null || !PhotonNetwork.InRoom) { return false; } PhotonView componentInParent = target.GetComponentInParent(); if ((Object)(object)componentInParent != (Object)null) { return componentInParent.IsMine; } return false; } private static bool RpcPrefix(Component __instance, object[] __args, MethodBase __originalMethod) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) if (!Shielded(__instance)) { return true; } for (int i = 0; i < __args.Length; i++) { if (__args[i] is PhotonMessageInfo val) { Player sender = val.Sender; if (sender == null || sender.IsLocal) { return true; } if (sender.IsMasterClient) { _hostDepth++; return true; } REPOPS1Plugin.Log.LogWarning((object)$"Shield: blocked {__originalMethod.Name} from {sender.NickName} (#{sender.ActorNumber})."); return false; } } return true; } private static Exception RpcFinalizer(Component __instance, object[] __args, Exception __exception) { if (_hostDepth > 0 && Shielded(__instance) && __args.Any((object a) => a is PhotonMessageInfo val && val.Sender != null && val.Sender.IsMasterClient && !val.Sender.IsLocal)) { _hostDepth--; } return __exception; } private static bool HurtPrefix(PlayerHealth __instance) { if (_hostDepth <= 0) { return !Shielded((Component)(object)__instance); } return true; } } internal sealed class VirtualPad : IDisposable { private struct XInputState { public uint Packet; public ushort Buttons; public byte Lt; public byte Rt; public short Lx; public short Ly; public short Rx; public short Ry; } private static readonly Guid BusInterface = new Guid("96E42B22-F5E9-42F8-B043-ED0F932F014F"); private const uint IoPlugin = 2793476u; private const uint IoUnplug = 2793480u; private const uint IoCheckVersion = 2793484u; private const uint IoWaitReady = 2793488u; private const uint IoXusbReport = 2795528u; private readonly SafeFileHandle _bus; private readonly uint _serial; private readonly byte[] _report = new byte[20]; private PadState _last; private bool _sent; public static readonly List Slots = new List(); public static float PluggedAt = -100f; public int XInputSlot { get; private set; } = -1; [DllImport("cfgmgr32.dll", CharSet = CharSet.Unicode)] private static extern int CM_Get_Device_Interface_List_SizeW(out uint len, ref Guid cls, IntPtr device, uint flags); [DllImport("cfgmgr32.dll", CharSet = CharSet.Unicode)] private static extern int CM_Get_Device_Interface_ListW(ref Guid cls, IntPtr device, char[] buffer, uint len, uint flags); [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)] private static extern SafeFileHandle CreateFileW(string name, uint access, uint share, IntPtr sec, uint disposition, uint flags, IntPtr template); [DllImport("kernel32.dll", SetLastError = true)] private static extern bool DeviceIoControl(SafeFileHandle dev, uint code, byte[] inBuf, int inLen, byte[] outBuf, int outLen, out int returned, IntPtr overlapped); [DllImport("xinput1_4.dll")] private static extern int XInputGetState(int user, out XInputState state); public static bool IsVirtual(InputDevice d) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: 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) if (Slots.Count != 0 && d != null) { InputDeviceDescription description = d.description; if (!(((InputDeviceDescription)(ref description)).interfaceName != "XInput")) { description = d.description; string text = (((InputDeviceDescription)(ref description)).capabilities ?? "").Replace(" ", ""); foreach (int slot in Slots) { if (text.Contains("\"userIndex\":" + slot)) { return true; } } return false; } } return false; } private VirtualPad(SafeFileHandle bus, uint serial) { _bus = bus; _serial = serial; } public static VirtualPad Create() { string text = BusPath(); if (text == null) { REPOPS1Plugin.Log.LogWarning((object)"Virtual pad: the ViGEmBus driver is not installed, so guests can't play the emulator program."); return null; } SafeFileHandle safeFileHandle = CreateFileW(text, 3221225472u, 3u, IntPtr.Zero, 3u, 128u, IntPtr.Zero); if (safeFileHandle.IsInvalid) { REPOPS1Plugin.Log.LogWarning((object)$"Virtual pad: can't open the ViGEmBus driver ({Marshal.GetLastWin32Error()})."); return null; } Io(safeFileHandle, 2793484u, Pack(8, 1u)); int num = ConnectedSlots(); for (uint num2 = 1u; num2 <= 16; num2++) { byte[] array = new byte[16]; BitConverter.GetBytes(16).CopyTo(array, 0); BitConverter.GetBytes(num2).CopyTo(array, 4); BitConverter.GetBytes((ushort)1118).CopyTo(array, 12); BitConverter.GetBytes((ushort)654).CopyTo(array, 14); if (!Io(safeFileHandle, 2793476u, array)) { continue; } Io(safeFileHandle, 2793488u, Pack(8, num2)); VirtualPad virtualPad = new VirtualPad(safeFileHandle, num2); virtualPad.Send(default(PadState)); for (int i = 0; i < 40; i++) { if (virtualPad.XInputSlot >= 0) { break; } Thread.Sleep(25); int num3 = ConnectedSlots(); for (int j = 0; j < 4; j++) { if ((num3 & ~num & (1 << j)) != 0) { virtualPad.XInputSlot = j; break; } } } if (virtualPad.XInputSlot >= 0) { Slots.Add(virtualPad.XInputSlot); } PluggedAt = Time.unscaledTime; REPOPS1Plugin.Log.LogInfo((object)$"Virtual pad plugged in (bus serial {num2}, XInput slot {virtualPad.XInputSlot})."); return virtualPad; } REPOPS1Plugin.Log.LogWarning((object)$"Virtual pad: the ViGEmBus driver refused a new pad ({Marshal.GetLastWin32Error()})."); safeFileHandle.Dispose(); return null; } public void Send(PadState s) { int b; if (!_sent || s.Buttons != _last.Buttons || s.Lx != _last.Lx || s.Ly != _last.Ly || s.Rx != _last.Rx || s.Ry != _last.Ry) { _sent = true; _last = s; b = s.Buttons; ushort num = 0; if (On(4u)) { num |= 1; } if (On(5u)) { num |= 2; } if (On(6u)) { num |= 4; } if (On(7u)) { num |= 8; } if (On(3u)) { num |= 0x10; } if (On(2u)) { num |= 0x20; } if (On(14u)) { num |= 0x40; } if (On(15u)) { num |= 0x80; } if (On(10u)) { num |= 0x100; } if (On(11u)) { num |= 0x200; } if (On(0u)) { num |= 0x1000; } if (On(8u)) { num |= 0x2000; } if (On(1u)) { num |= 0x4000; } if (On(9u)) { num |= 0x8000; } BitConverter.GetBytes(20).CopyTo(_report, 0); BitConverter.GetBytes(_serial).CopyTo(_report, 4); BitConverter.GetBytes(num).CopyTo(_report, 8); _report[10] = (byte)(On(12u) ? byte.MaxValue : 0); _report[11] = (byte)(On(13u) ? byte.MaxValue : 0); BitConverter.GetBytes(s.Lx).CopyTo(_report, 12); BitConverter.GetBytes(Flip(s.Ly)).CopyTo(_report, 14); BitConverter.GetBytes(s.Rx).CopyTo(_report, 16); BitConverter.GetBytes(Flip(s.Ry)).CopyTo(_report, 18); Io(_bus, 2795528u, _report); } bool On(uint id) { return (b & (1 << (int)id)) != 0; } } public void Dispose() { if (!_bus.IsClosed) { Io(_bus, 2793480u, Pack(8, _serial)); _bus.Dispose(); REPOPS1Plugin.Log.LogInfo((object)"Virtual pad unplugged."); } } private static short Flip(short v) { if (v != short.MinValue) { return (short)(-v); } return short.MaxValue; } private static byte[] Pack(int size, uint serial) { byte[] array = new byte[size]; BitConverter.GetBytes(size).CopyTo(array, 0); BitConverter.GetBytes(serial).CopyTo(array, 4); return array; } private static bool Io(SafeFileHandle bus, uint code, byte[] data) { int returned; return DeviceIoControl(bus, code, data, data.Length, null, 0, out returned, IntPtr.Zero); } private static int ConnectedSlots() { int num = 0; for (int i = 0; i < 4; i++) { if (XInputGetState(i, out var _) == 0) { num |= 1 << i; } } return num; } private static string BusPath() { Guid cls = BusInterface; if (CM_Get_Device_Interface_List_SizeW(out var len, ref cls, IntPtr.Zero, 0u) != 0 || len <= 1) { return null; } char[] array = new char[len]; if (CM_Get_Device_Interface_ListW(ref cls, IntPtr.Zero, array, len, 0u) != 0) { return null; } string text = new string(array).Split('\0')[0]; if (text.Length <= 0) { return null; } return text; } } internal static class WindowCapture { [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int QueryInterfaceFn(IntPtr self, ref Guid iid, out IntPtr obj); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate uint ReleaseFn(IntPtr self); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int CreateForWindowFn(IntPtr self, IntPtr hwnd, ref Guid iid, out IntPtr item); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int CreatePoolFn(IntPtr self, IntPtr device, int format, int buffers, long size, out IntPtr pool); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int RecreateFn(IntPtr self, IntPtr device, int format, int buffers, long size); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int OutPtrFn(IntPtr self, out IntPtr result); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int OutSizeFn(IntPtr self, out long size); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int CreateSessionFn(IntPtr self, IntPtr item, out IntPtr session); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int NoArgFn(IntPtr self); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int PutBoolFn(IntPtr self, byte value); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int GetInterfaceFn(IntPtr self, ref Guid iid, out IntPtr obj); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int CreateTexture2DFn(IntPtr dev, ref TexDesc desc, IntPtr init, out IntPtr tex); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int OpenSharedFn(IntPtr dev, IntPtr handle, ref Guid iid, out IntPtr res); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void GetDescFn(IntPtr tex, out TexDesc desc); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void CopyResourceFn(IntPtr ctx, IntPtr dst, IntPtr src); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate void FlushFn(IntPtr ctx); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int SharedHandleFn(IntPtr res, out IntPtr handle); private struct TexDesc { public uint Width; public uint Height; public uint MipLevels; public uint ArraySize; public uint Format; public uint SampleCount; public uint SampleQuality; public uint Usage; public uint BindFlags; public uint CpuAccess; public uint Misc; } [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate int GetIidsFn(IntPtr self, out uint count, out IntPtr iids); [UnmanagedFunctionPointer(CallingConvention.StdCall)] private delegate uint ThreadProc(IntPtr arg); public static volatile IntPtr Window; public static volatile int CropX; public static volatile int CropY; public static volatile int CropW; public static volatile int CropH; public static volatile bool Failed; public static volatile int Frames; private static readonly Guid IidItemInterop = new Guid("3628E81B-3CAC-4C60-B7F4-23CE0E0C3356"); private static readonly Guid IidItem = new Guid("79C3F95B-31F7-4EC2-A464-632EF5D30760"); private static readonly Guid IidPoolStatics2 = new Guid("589B103F-6BBC-5DF5-A991-02E28B3B66D5"); private static readonly Guid IidSession2 = new Guid("2C39AE40-7D2E-5044-804E-8B6799D4CF9E"); private static readonly Guid IidSession3 = new Guid("F2CDD966-22AE-5EA1-9596-3A289344C3BE"); private static readonly Guid IidClosable = new Guid("30D5A829-7FA4-4026-83BB-D75BAE4EA99E"); private static readonly Guid IidDxgiAccess = new Guid("A9B3D012-3DF2-4EE3-B8D1-8695F457D3C1"); private static readonly Guid IidTexture2D = new Guid("6f15aaf2-d208-4e89-9ab4-489535d34f9c"); private static readonly Guid IidDxgiDevice = new Guid("54EC77FA-1377-44E6-8C32-88FD5F44C84C"); private static readonly Guid IidWinRtDevice = new Guid("A37624AB-8D5F-4650-9D3E-9EAE3D9BC670"); private const int PixelBgra8 = 87; private static readonly Guid IidDxgiResource = new Guid("035f3ab4-482e-4e50-b41f-8a7f8bd8960b"); private static IntPtr _current; private static IntPtr _item; private static IntPtr _pool; private static IntPtr _session; private static IntPtr _device; private static IntPtr _capDevice; private static IntPtr _capContext; private static IntPtr _shared; private static uint _sharedW; private static uint _sharedH; private static long _size; private static bool _roInit; private static bool _warnedNoFrame; private static int _got; private static ThreadProc _threadProc; private static volatile IntPtr _pubHandle; private static volatile int _pubX; private static volatile int _pubY; private static volatile int _pubW; private static volatile int _pubH; private static volatile int _published; private static IntPtr _openedHandle; private static IntPtr _onUnity; private static int _consumed; private static int _startTick; private static int _statTick; private static int _ticks; [DllImport("combase.dll")] private static extern int RoInitialize(int type); [DllImport("combase.dll", CharSet = CharSet.Unicode)] private static extern int WindowsCreateString(string s, int length, out IntPtr hstring); [DllImport("combase.dll")] private static extern int WindowsDeleteString(IntPtr hstring); [DllImport("combase.dll")] private static extern int RoGetActivationFactory(IntPtr classId, ref Guid iid, out IntPtr factory); [DllImport("d3d11.dll")] private static extern int CreateDirect3D11DeviceFromDXGIDevice(IntPtr dxgiDevice, out IntPtr inspectable); [DllImport("d3d11.dll")] private static extern int D3D11CreateDevice(IntPtr adapter, int driverType, IntPtr software, uint flags, IntPtr levels, uint count, uint sdk, out IntPtr device, out int level, out IntPtr context); private static T Call(IntPtr com, int slot) where T : Delegate { return Marshal.GetDelegateForFunctionPointer(Marshal.ReadIntPtr(Marshal.ReadIntPtr(com), slot * IntPtr.Size)); } private static void Release(ref IntPtr com) { if (com != IntPtr.Zero) { Call(com, 2)(com); } com = IntPtr.Zero; } private static IntPtr Query(IntPtr com, Guid iid) { Call(com, 0)(com, ref iid, out var obj); return obj; } [DllImport("combase.dll", CharSet = CharSet.Unicode)] private static extern IntPtr WindowsGetStringRawBuffer(IntPtr hstring, out uint length); [DllImport("ole32.dll")] private static extern void CoTaskMemFree(IntPtr p); private static void Describe(string what, IntPtr com) { try { string arg = "?"; if (Call(com, 4)(com, out var result) >= 0 && result != IntPtr.Zero) { arg = Marshal.PtrToStringUni(WindowsGetStringRawBuffer(result, out var length), (int)length); WindowsDeleteString(result); } StringBuilder stringBuilder = new StringBuilder(); if (Call(com, 3)(com, out var count, out var iids) >= 0 && iids != IntPtr.Zero) { byte[] array = new byte[16]; for (int i = 0; i < count; i++) { Marshal.Copy(iids + i * 16, array, 0, 16); stringBuilder.Append(' ').Append(new Guid(array)); } CoTaskMemFree(iids); } REPOPS1Plugin.Log.LogInfo((object)$"Window capture: {what} is {arg}, interfaces:{stringBuilder}"); } catch (Exception ex) { REPOPS1Plugin.Log.LogInfo((object)("Window capture: can't describe the " + what + ": " + ex.Message)); } } private static void Close(IntPtr com) { if (!(com == IntPtr.Zero)) { IntPtr com2 = Query(com, IidClosable); if (!(com2 == IntPtr.Zero)) { Call(com2, 6)(com2); Release(ref com2); } } } private static IntPtr Factory(string className, Guid iid) { WindowsCreateString(className, className.Length, out var hstring); try { IntPtr factory; return (RoGetActivationFactory(hstring, ref iid, out factory) >= 0) ? factory : IntPtr.Zero; } finally { WindowsDeleteString(hstring); } } [DllImport("kernel32.dll")] private static extern IntPtr CreateThread(IntPtr attr, UIntPtr stack, ThreadProc proc, IntPtr arg, uint flags, out uint id); [DllImport("ole32.dll")] private static extern int CoInitializeEx(IntPtr reserved, uint flags); [DllImport("ole32.dll")] private static extern int CoGetApartmentType(out int type, out int qualifier); internal static void RenderTick() { if (_threadProc == null) { _threadProc = delegate { int num2 = CoInitializeEx(IntPtr.Zero, 0u); CoGetApartmentType(out var type, out var _); REPOPS1Plugin.Log.LogInfo((object)$"Window capture thread: COM 0x{num2:X8}, apartment {type} (1 = MTA)."); while (true) { try { CaptureStep(); } catch (Exception ex) { REPOPS1Plugin.Log.LogError((object)("Window capture failed: " + ex.Message)); Thread.Sleep(500); } Thread.Sleep((Window == IntPtr.Zero) ? 50 : 3); } }; CreateThread(IntPtr.Zero, UIntPtr.Zero, _threadProc, IntPtr.Zero, 0u, out var _); } IntPtr pubHandle = _pubHandle; if (pubHandle != _openedHandle) { if (_onUnity != IntPtr.Zero) { Release(ref _onUnity); } _openedHandle = pubHandle; if (pubHandle != IntPtr.Zero) { Guid iid = IidTexture2D; int num = Call(D3D11Host.Device, 28)(D3D11Host.Device, pubHandle, ref iid, out _onUnity); if (num < 0) { REPOPS1Plugin.Log.LogError((object)$"Window capture: Unity's device can't open the shared texture (0x{num:X8})."); _onUnity = IntPtr.Zero; } } } int published = _published; if (published != _consumed && !(_onUnity == IntPtr.Zero)) { _consumed = published; D3D11Host.CopyIn(_onUnity, _pubX, _pubY, _pubW, _pubH); Frames++; } } private static void CaptureStep() { IntPtr window = Window; if (window != _current) { Teardown(); _current = window; if (window == IntPtr.Zero) { return; } Failed = !Start(window); } if (_pool == IntPtr.Zero) { return; } _ticks++; if (Environment.TickCount - _statTick > 10000) { _statTick = Environment.TickCount; REPOPS1Plugin.Log.LogInfo((object)$"Window capture: {_ticks} checks, {_got} pictures so far, {Frames} shown."); _ticks = 0; } IntPtr com = IntPtr.Zero; while (true) { Call(_pool, 7)(_pool, out var result); if (result == IntPtr.Zero) { break; } if (com != IntPtr.Zero) { Close(com); Release(ref com); } com = result; } if (com == IntPtr.Zero) { if (_got == 0 && !_warnedNoFrame && Environment.TickCount - _startTick > 5000) { _warnedNoFrame = true; REPOPS1Plugin.Log.LogWarning((object)"Window capture: no picture from the window after 5 s (is it minimised?)."); } return; } _got++; try { Call(com, 8)(com, out var size); IntPtr result2; int num = Call(com, 6)(com, out result2); if (_got == 1) { REPOPS1Plugin.Log.LogInfo((object)string.Format("Window capture: first picture {0}x{1}, surface 0x{2:X8} {3}.", size & 0xFFFFFFFFu, size >> 32, num, (result2 != IntPtr.Zero) ? "ok" : "missing")); } if (result2 != IntPtr.Zero) { Guid iid = IidDxgiAccess; IntPtr obj; int num2 = Call(result2, 0)(result2, ref iid, out obj); if (obj == IntPtr.Zero && _got == 1) { REPOPS1Plugin.Log.LogWarning((object)$"Window capture: the picture has no DXGI access (0x{num2:X8})."); Describe("surface", result2); Describe("frame", com); } if (obj != IntPtr.Zero) { Guid iid2 = IidTexture2D; Call(obj, 3)(obj, ref iid2, out var obj2); if (obj2 != IntPtr.Zero) { int num3 = (int)(size & 0xFFFFFFFFu); int num4 = (int)(size >> 32); int num5 = CropX; int num6 = CropY; int num7 = CropW; int num8 = CropH; if (num7 <= 0 || num8 <= 0 || num5 + num7 > num3 || num6 + num8 > num4) { num5 = (num6 = 0); num7 = num3; num8 = num4; } if (Share(obj2)) { _pubX = num5; _pubY = num6; _pubW = num7; _pubH = num8; _published++; } Release(ref obj2); } else { REPOPS1Plugin.Log.LogWarning((object)"Window capture: a picture without a texture."); } Release(ref obj); } Release(ref result2); } if (size != _size && size != 0L) { _size = size; Call(_pool, 6)(_pool, _device, 87, 2, size); } } finally { Close(com); Release(ref com); } } private static bool Start(IntPtr hwnd) { if (!_roInit) { _roInit = true; RoInitialize(1); } IntPtr com = Factory("Windows.Graphics.Capture.GraphicsCaptureItem", IidItemInterop); if (com == IntPtr.Zero) { REPOPS1Plugin.Log.LogError((object)"Window capture: Windows Graphics Capture is not available (Windows 10 1903 or newer)."); return false; } Guid iid = IidItem; int num = Call(com, 3)(com, hwnd, ref iid, out _item); Release(ref com); if (num < 0 || _item == IntPtr.Zero) { REPOPS1Plugin.Log.LogError((object)$"Window capture: can't capture that window (0x{num:X8})."); return false; } _startTick = Environment.TickCount; _got = 0; _warnedNoFrame = false; if (_capDevice == IntPtr.Zero) { num = D3D11CreateDevice(IntPtr.Zero, 1, IntPtr.Zero, 32u, IntPtr.Zero, 0u, 7u, out _capDevice, out var _, out _capContext); if (num < 0 || _capDevice == IntPtr.Zero) { REPOPS1Plugin.Log.LogError((object)$"Window capture: no D3D11 device of its own (0x{num:X8})."); return false; } } IntPtr com2 = Query(_capDevice, IidDxgiDevice); if (com2 == IntPtr.Zero) { REPOPS1Plugin.Log.LogError((object)"Window capture: no DXGI device."); return false; } CreateDirect3D11DeviceFromDXGIDevice(com2, out var inspectable); Release(ref com2); if (inspectable == IntPtr.Zero) { REPOPS1Plugin.Log.LogError((object)"Window capture: no WinRT device."); return false; } _device = Query(inspectable, IidWinRtDevice); Release(ref inspectable); Call(_item, 7)(_item, out _size); IntPtr com3 = Factory("Windows.Graphics.Capture.Direct3D11CaptureFramePool", IidPoolStatics2); if (com3 == IntPtr.Zero) { REPOPS1Plugin.Log.LogError((object)"Window capture: no free-threaded frame pool."); return false; } num = Call(com3, 6)(com3, _device, 87, 2, _size, out _pool); Release(ref com3); if (num < 0 || _pool == IntPtr.Zero) { REPOPS1Plugin.Log.LogError((object)$"Window capture: frame pool failed (0x{num:X8})."); return false; } num = Call(_pool, 10)(_pool, _item, out _session); if (num < 0 || _session == IntPtr.Zero) { REPOPS1Plugin.Log.LogError((object)$"Window capture: session failed (0x{num:X8})."); return false; } IntPtr com4 = Query(_session, IidSession2); if (com4 != IntPtr.Zero) { Call(com4, 7)(com4, 0); Release(ref com4); } IntPtr com5 = Query(_session, IidSession3); if (com5 != IntPtr.Zero) { Call(com5, 7)(com5, 0); Release(ref com5); } num = Call(_session, 6)(_session); if (num < 0) { REPOPS1Plugin.Log.LogError((object)$"Window capture: start failed (0x{num:X8})."); return false; } D3D11Host.ResetFrameLog(); REPOPS1Plugin.Log.LogInfo((object)$"Window capture started ({_size & 0xFFFFFFFFu}x{_size >> 32})."); return true; } private static bool Share(IntPtr tex) { Call(tex, 10)(tex, out var desc); if (_shared == IntPtr.Zero || desc.Width != _sharedW || desc.Height != _sharedH) { _pubHandle = IntPtr.Zero; Release(ref _shared); TexDesc desc2 = new TexDesc { Width = desc.Width, Height = desc.Height, MipLevels = 1u, ArraySize = 1u, Format = desc.Format, SampleCount = 1u, Usage = 0u, BindFlags = 8u, Misc = 2u }; int num = Call(_capDevice, 5)(_capDevice, ref desc2, IntPtr.Zero, out _shared); if (num < 0) { REPOPS1Plugin.Log.LogError((object)$"Window capture: shared texture failed (0x{num:X8})."); _shared = IntPtr.Zero; return false; } IntPtr com = Query(_shared, IidDxgiResource); Call(com, 8)(com, out var handle); Release(ref com); _sharedW = desc.Width; _sharedH = desc.Height; _pubHandle = handle; } Call(_capContext, 47)(_capContext, _shared, tex); Call(_capContext, 111)(_capContext); return true; } private static void Teardown() { _pubHandle = IntPtr.Zero; Release(ref _shared); _sharedW = (_sharedH = 0u); Close(_session); Release(ref _session); Close(_pool); Release(ref _pool); Release(ref _item); Release(ref _device); _size = 0L; _current = IntPtr.Zero; } }