Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of Farlocks Replay v0.3.5
BepInEx/plugins/FarlocksReplay/FarlocksReplay.dll
Decompiled an hour ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Threading; using System.Threading.Tasks; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using Microsoft.CodeAnalysis; using Unity.Collections; using UnityEngine; using UnityEngine.Rendering; using UnityEngine.SceneManagement; [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("FarlocksReplay")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.3.5.0")] [assembly: AssemblyInformationalVersion("0.3.5+d9b87c6e8b5f8cedc4483d305eb6f65d02388e56")] [assembly: AssemblyProduct("FarlocksReplay")] [assembly: AssemblyTitle("FarlocksReplay")] [assembly: AssemblyVersion("0.3.5.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace RepoReplay { internal static class AudioSelfTest { private sealed class Context { internal string Path; internal string Report; internal GameObject Source; internal AudioClip Tone; internal AudioListener[] Listeners; internal bool[] Enabled; } internal static IEnumerator Run(Plugin owner) { Context context = new Context { Path = Path.Combine(owner.ReplayDirectory, "audiotest_" + DateTime.UtcNow.ToString("yyyyMMdd_HHmmss_fff") + ".repo_rep"), Report = Path.Combine(Paths.PluginPath, "audio-selftest.txt") }; File.WriteAllText(context.Report, "RUNNING: actual Unity DSP game-mix recording and procedural replay.\n"); IEnumerator steps = Steps(owner, context); while (true) { bool flag = false; object obj = null; Exception ex = null; try { flag = steps.MoveNext(); if (flag) { obj = steps.Current; } } catch (Exception ex2) { ex = ex2; } if (ex != null) { Cleanup(owner, context); File.AppendAllText(context.Report, "FAIL: " + ex?.ToString() + "\n"); owner.LogFailure(ex); yield break; } if (!flag) { break; } yield return obj; } Cleanup(owner, context); } private static IEnumerator Steps(Plugin owner, Context context) { yield return (object)new WaitForSecondsRealtime(2f); Require(GameIntegration.IsMainMenu() && !owner.Player.IsActive && !owner.Recorder.IsRecording, "Audio fixture requires idle main menu"); Require((Object)(object)owner.Audio != (Object)null, "ReplayAudio helper is missing"); context.Listeners = Object.FindObjectsByType<AudioListener>((FindObjectsSortMode)0); context.Enabled = new bool[context.Listeners.Length]; int num = 0; for (int i = 0; i < context.Listeners.Length; i++) { context.Enabled[i] = ((Behaviour)context.Listeners[i]).enabled; if (context.Enabled[i] && ((Component)context.Listeners[i]).gameObject.activeInHierarchy) { num++; } } Require(num > 0, "Main menu has no active audio listener; cannot validate the real mixer tap"); int rate = AudioSettings.outputSampleRate; Require(rate >= 8000 && rate <= 192000, "Invalid Unity output rate"); context.Tone = AudioClip.Create("RepoReplay diagnostic sine", rate * 2, 1, rate, false); float[] array = new float[rate * 2]; for (int j = 0; j < array.Length; j++) { array[j] = 0.18f * Mathf.Sin(MathF.PI * 880f * (float)j / (float)rate); } Require(context.Tone.SetData(array, 0), "Could not populate the diagnostic Unity AudioClip"); context.Source = new GameObject("RepoReplay diagnostic tone", new Type[1] { typeof(AudioSource) }); AudioSource source = context.Source.GetComponent<AudioSource>(); source.playOnAwake = false; source.spatialBlend = 0f; source.volume = 0.3f; source.loop = true; source.clip = context.Tone; source.ignoreListenerPause = true; owner.Audio.StartRecording(context.Path); source.Play(); long began = Stopwatch.GetTimestamp(); int voiceBlocks = 0; float[] voice = new float[960]; object processor = new object(); double num2; while ((num2 = (double)(Stopwatch.GetTimestamp() - began) / (double)Stopwatch.Frequency) < 1.65) { owner.Audio.TickRecording(); if (num2 >= 0.3 + (double)voiceBlocks * 0.02 && voiceBlocks < 35) { for (int k = 0; k < voice.Length; k++) { voice[k] = 0.12f * Mathf.Sin(MathF.PI * 440f * (float)(voiceBlocks * voice.Length + k) / 48000f); } InjectSyntheticVoice(owner.Audio, processor, voice); voiceBlocks++; } yield return null; } source.Stop(); owner.Audio.StopRecording(); Require(File.Exists(context.Path + ".audio.wav"), "Unity listener DSP callback did not publish a game-mix WAV"); Require(owner.Audio.CapturedGameSamples > rate / 2, "Unity listener DSP captured too few samples"); Require(owner.Audio.CapturedGamePeak > 0.005f && owner.Audio.CapturedGameRms > 0.001, "Recorded game-mix WAV is silent"); Require(File.Exists(context.Path + ".voice.wav") && owner.Audio.CapturedVoiceSamples > 12000, "Synthetic voice did not pass through the microphone hook/queue/WAV path"); Require(owner.Audio.CapturedVoicePeak > 0.05f && owner.Audio.CapturedVoiceRms > 0.01, "Synthetic voice WAV is silent"); File.AppendAllText(context.Report, "Capture PASS: actualUnityGameFrames=" + owner.Audio.CapturedGameSamples + " gameRMS=" + owner.Audio.CapturedGameRms.ToString("R", CultureInfo.InvariantCulture) + " syntheticVoiceFrames=" + owner.Audio.CapturedVoiceSamples + " voiceRMS=" + owner.Audio.CapturedVoiceRms.ToString("R", CultureInfo.InvariantCulture) + "\n"); owner.Audio.StartPlayback(context.Path, 0f, 1f); Require(owner.Audio.HasGameAudio && owner.Audio.HasMicrophoneAudio, "Recorded WAV tracks could not be reopened"); bool condition = false; AudioOutput[] array2 = Object.FindObjectsByType<AudioOutput>((FindObjectsSortMode)0); foreach (AudioOutput audioOutput in array2) { if (audioOutput.Owner == owner.Audio) { condition = true; Require((Object)(object)((Component)audioOutput).GetComponent<AudioSource>() != (Object)null && (Object)(object)((Component)audioOutput).GetComponent<AudioListener>() == (Object)null, "Playback filter must belong only to its source DSP stage"); AudioListener componentInChildren = ((Component)audioOutput).GetComponentInChildren<AudioListener>(); Require((Object)(object)componentInChildren != (Object)null && (Object)(object)((Component)componentInChildren).gameObject != (Object)(object)((Component)audioOutput).gameObject && (Object)(object)((Component)componentInChildren).GetComponent<AudioSource>() == (Object)null, "Playback listener must be a separate object without a source/filter"); } } Require(condition, "Unity procedural playback filter was not created"); began = Stopwatch.GetTimestamp(); while ((num2 = (double)(Stopwatch.GetTimestamp() - began) / (double)Stopwatch.Frequency) < 0.55) { owner.Audio.TickPlayback((float)num2, shouldPlay: true, 1f); yield return null; } Require(owner.Audio.RenderedPlaybackFrames > rate / 5 && owner.Audio.RenderedPlaybackPeak > 0.005f && owner.Audio.RenderedPlaybackRms > 0.001, "Unity procedural playback DSP did not render recorded sound"); int playbackSeekVersion = owner.Audio.PlaybackSeekVersion; float time = (float)Math.Max(0.0, owner.Audio.PlaybackClock - 0.05); owner.Audio.SeekPlayback(time); Require(owner.Audio.PlaybackSeekVersion == playbackSeekVersion + 1, "Small explicit seek did not publish a DSP seek command"); owner.Audio.TickPlayback(time, shouldPlay: false, 1f); owner.Audio.SeekPlayback(0.6f); yield return (object)new WaitForSecondsRealtime(0.12f); Require(Math.Abs(owner.Audio.PlaybackClock - 0.6) < 0.06, "Paused seek advanced or was ignored"); began = Stopwatch.GetTimestamp(); while ((num2 = (double)(Stopwatch.GetTimestamp() - began) / (double)Stopwatch.Frequency) < 0.12) { owner.Audio.TickPlayback(0.2f + (float)num2 * 4f, shouldPlay: true, 4f); yield return null; } Require(owner.Audio.PlaybackClock > 0.4, "4x procedural playback clock did not advance"); double outputRms = owner.Audio.RenderedPlaybackRms; owner.Audio.StopPlayback(); yield return null; for (int m = 0; m < context.Listeners.Length; m++) { if ((Object)(object)context.Listeners[m] != (Object)null) { Require(((Behaviour)context.Listeners[m]).enabled == context.Enabled[m], "Original listener state was not restored"); } } File.AppendAllText(context.Report, "PASS: actual Unity listener-mix capture, non-silent game WAV, synthetic transmitted-voice hook/queue/WAV, reloaded tracks, actual Unity procedural playback output, <=180ms explicit seek, paused seek, 4x clock, listener restoration.\nPlaybackRMS=" + outputRms.ToString("R", CultureInfo.InvariantCulture) + "\nPath=" + context.Path + "\nNot covered: a human speaking into the physical microphone, remote-player voice/network, device switching.\n"); owner.LogInfo("AUDIO SELFTEST PASS " + context.Report); } private static void InjectSyntheticVoice(ReplayAudio audio, object token, float[] samples) { FieldInfo field = typeof(ReplayAudio).GetField("microphoneProcessor", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo field2 = typeof(ReplayAudio).GetField("micInMix", BindingFlags.Instance | BindingFlags.NonPublic); object value = field.GetValue(audio); object value2 = field2.GetValue(audio); try { field.SetValue(audio, token); field2.SetValue(audio, false); typeof(ReplayAudio).GetMethod("MicrophoneFloat", BindingFlags.Static | BindingFlags.NonPublic).Invoke(null, new object[7] { token, samples, true, 48000, 1, true, false }); } finally { field.SetValue(audio, value); field2.SetValue(audio, value2); } } private static void Cleanup(Plugin owner, Context context) { try { owner.Audio?.StopRecording(); owner.Audio?.StopPlayback(); } catch (Exception error) { owner.LogFailure(error); } if ((Object)(object)context.Source != (Object)null) { Object.Destroy((Object)(object)context.Source); } if ((Object)(object)context.Tone != (Object)null) { Object.Destroy((Object)(object)context.Tone); } } private static void Require(bool condition, string message) { if (!condition) { throw new InvalidOperationException(message); } } } internal static class BindingsSelfTest { private sealed class TestCase { internal Plugin Owner; internal ReplayUI Ui; internal bool Visible; internal bool Settings; internal string Report; internal string Config; internal string Path; internal string Other; internal string PrivateRoot; internal string SettingsScreenshot; internal string DeleteScreenshot; internal ReplayTrashEntry Trashed; internal ReplayTrashEntry PrivateTrash; } private const BindingFlags Flags = BindingFlags.Instance | BindingFlags.NonPublic; internal static IEnumerator Run(Plugin owner) { string text = Guid.NewGuid().ToString("N"); TestCase test = new TestCase { Owner = owner, Report = Path.Combine(Paths.PluginPath, "controls-selftest.txt"), Config = Path.Combine(Paths.PluginPath, "controls-fixture-" + text + ".cfg"), Path = Path.Combine(owner.ReplayDirectory, "controlsfixture_" + text + ".repo_rep"), PrivateRoot = Path.Combine(owner.ReplayDirectory, ".ControlsFixture_" + text), SettingsScreenshot = Path.Combine(Paths.PluginPath, "controls-settings-selftest.png"), DeleteScreenshot = Path.Combine(Paths.PluginPath, "controls-delete-selftest.png") }; test.Other = test.Path + "2.effects"; File.WriteAllText(test.Report, "RUNNING: owned config, shortcut capture, replay-trash bundle and real modal panels; no OS input.\n"); IEnumerator run = Execute(test); Exception failure = null; while (true) { bool flag; try { flag = run.MoveNext(); } catch (Exception ex) { failure = ex; break; } if (!flag) { break; } yield return run.Current; } (run as IDisposable)?.Dispose(); try { if (test.Ui != null) { Set(test.Ui, "showBindings", test.Settings); Set(test.Ui, "pendingDelete", null); Set(test.Ui, "pendingEmpty", null); test.Ui.Visible = test.Visible; owner.Bindings.Modal = test.Settings; typeof(ReplayUI).GetMethod("RefreshFiles", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(test.Ui, null); } if (test.Trashed != null && Directory.Exists(test.Trashed.DirectoryPath) && !File.Exists(test.Path)) { ReplayLibrary.Restore(owner.ReplayDirectory, test.Trashed); } string[] array = new string[5] { test.Path, test.Path + ".effects", test.Path + ".v000.wav", test.Other, test.Config }; foreach (string path in array) { if (File.Exists(path)) { File.Delete(path); } } CleanupPrivateFixture(test); } catch (Exception ex2) { if (failure == null) { failure = ex2; } } if (failure != null) { File.AppendAllText(test.Report, "FAIL: " + failure?.ToString() + "\n"); owner.LogFailure(failure); } else { File.AppendAllText(test.Report, "PASS: config persistence; duplicate rejection; Event-based rebind/cancel and frame fence; exact replay bundle trash/restore/permanent empty; unrelated prefix retained; SETTINGS and DELETE panels captured.\n"); owner.LogInfo("CONTROLS SELFTEST PASS " + test.Report); } } private static IEnumerator Execute(TestCase test) { Plugin owner = test.Owner; Require(GameIntegration.IsMainMenu() && !owner.Player.IsActive && !owner.Recorder.IsRecording && !owner.Recorder.IsFinalizing, "Idle main menu required"); ReplayBindings replayBindings = new ReplayBindings(new ConfigFile(test.Config, false)); Require(replayBindings.TryAssign(ReplayAction.Record, new ReplayShortcut((KeyCode)291, ReplayModifiers.Control), out var _), "Direct assignment failed"); Require(new ReplayBindings(new ConfigFile(test.Config, false)).Label(ReplayAction.Record) == "Ctrl+F10", "Shortcut config did not persist"); Require(!replayBindings.TryAssign(ReplayAction.Record, new ReplayShortcut((KeyCode)289), out var error2) && error2.Length > 0, "Duplicate shortcut was accepted"); replayBindings.BeginCapture(ReplayAction.Keyframe); Require(replayBindings.InputBlocked && !replayBindings.IsDown(ReplayAction.Record), "Rebind did not suppress global actions"); Event input = new Event { type = (EventType)4, keyCode = (KeyCode)292, modifiers = (EventModifiers)1 }; replayBindings.HandleCapture(input); Require(!replayBindings.IsCapturing && replayBindings.Label(ReplayAction.Keyframe) == "Shift+F11" && replayBindings.InputBlocked, "Event chord capture/frame fence failed"); replayBindings.BeginCapture(ReplayAction.Library); Event input2 = new Event { type = (EventType)4, keyCode = (KeyCode)27 }; replayBindings.HandleCapture(input2); Require(!replayBindings.IsCapturing && replayBindings.Label(ReplayAction.Library) == "F8", "Capture cancel changed its shortcut"); replayBindings.BeginCapture(ReplayAction.Fast); replayBindings.HandleModifierRelease(new Event { type = (EventType)5, keyCode = (KeyCode)303 }); Require(!replayBindings.IsCapturing && replayBindings.Label(ReplayAction.Fast) == "RightShift", "Modifier-only binding failed"); File.AppendAllText(test.Report, "Shortcuts: config reload, conflicting F8 rejection, Shift+F11 Event capture, Escape cancel, RightShift modifier-only, global-input frame fence PASS.\n"); File.WriteAllText(test.Path, "owned fixture, never opened as a replay"); File.WriteAllText(test.Path + ".effects", "owned effects"); File.WriteAllText(test.Path + ".v000.wav", "owned audio"); File.WriteAllText(test.Other, "unrelated exact-prefix collision"); ReplayBundle bundle = ReplayLibrary.Inspect(owner.ReplayDirectory, test.Path); Require(bundle.FileCount == 3, "Bundle whitelist selected wrong files"); test.Ui = typeof(Plugin).GetField("ui", BindingFlags.Instance | BindingFlags.NonPublic)?.GetValue(owner) as ReplayUI; Require(test.Ui != null, "Existing replay UI unavailable"); test.Visible = test.Ui.Visible; test.Settings = (bool)typeof(ReplayUI).GetField("showBindings", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(test.Ui); test.Ui.Visible = true; Set(test.Ui, "showBindings", true); owner.Bindings.Modal = true; yield return null; yield return (object)new WaitForEndOfFrame(); ScreenCapture.CaptureScreenshot(test.SettingsScreenshot); yield return null; yield return (object)new WaitForEndOfFrame(); Set(test.Ui, "showBindings", false); Set(test.Ui, "pendingDelete", bundle); yield return null; yield return (object)new WaitForEndOfFrame(); ScreenCapture.CaptureScreenshot(test.DeleteScreenshot); yield return null; yield return (object)new WaitForEndOfFrame(); Set(test.Ui, "pendingDelete", null); owner.Bindings.Modal = false; test.Trashed = ReplayLibrary.MoveToTrash(owner.ReplayDirectory, bundle); Require(!File.Exists(test.Path) && File.Exists(test.Other) && test.Trashed.FileCount == 3, "Trash move escaped exact bundle"); ReplayLibrary.Restore(owner.ReplayDirectory, test.Trashed); test.Trashed = null; Require(File.Exists(test.Path) && File.Exists(test.Path + ".effects") && File.Exists(test.Path + ".v000.wav"), "Restore missed a sidecar"); Directory.CreateDirectory(test.PrivateRoot); string text = Path.Combine(test.PrivateRoot, "owned.repo_rep"); File.WriteAllText(text, "owned private trash test"); test.PrivateTrash = ReplayLibrary.MoveToTrash(test.PrivateRoot, ReplayLibrary.Inspect(test.PrivateRoot, text)); ReplayLibrary.EmptyTrash(test.PrivateRoot, ReplayLibrary.Trash(test.PrivateRoot)); Require(!File.Exists(text) && ReplayLibrary.Trash(test.PrivateRoot).Length == 0 && File.Exists(test.Other), "Private permanent trash empty failed"); File.AppendAllText(test.Report, "Library: 3-file owned bundle moved/restored; unrelated prefix untouched; permanent empty confined to owned private fixture directory. Screenshots: " + test.SettingsScreenshot + " / " + test.DeleteScreenshot + "\n"); } private static void CleanupPrivateFixture(TestCase test) { try { if (test.PrivateTrash != null && Directory.Exists(test.PrivateTrash.DirectoryPath)) { ReplayBundleFile[] files = test.PrivateTrash.Files; foreach (ReplayBundleFile replayBundleFile in files) { if (File.Exists(replayBundleFile.FullPath)) { File.Delete(replayBundleFile.FullPath); } } string path = Path.Combine(test.PrivateTrash.DirectoryPath, "bundle.info"); if (File.Exists(path)) { File.Delete(path); } RemoveEmptyDirectory(test.PrivateTrash.DirectoryPath); } string path2 = Path.Combine(test.PrivateRoot, "owned.repo_rep"); if (File.Exists(path2)) { File.Delete(path2); } RemoveEmptyDirectory(Path.Combine(test.PrivateRoot, ".ReplayTrash")); RemoveEmptyDirectory(test.PrivateRoot); if (Directory.Exists(test.PrivateRoot)) { File.AppendAllText(test.Report, "Cleanup retained fixture evidence directory: " + test.PrivateRoot + "\n"); } } catch (Exception ex) { File.AppendAllText(test.Report, "Cleanup retained fixture evidence directory: " + test.PrivateRoot + " / " + ex.Message + "\n"); } } private static void RemoveEmptyDirectory(string path) { if (!Directory.Exists(path)) { return; } using (IEnumerator<string> enumerator = Directory.EnumerateFileSystemEntries(path).GetEnumerator()) { if (enumerator.MoveNext()) { return; } } Directory.Delete(path, recursive: false); } private static void Set(object target, string field, object value) { target.GetType().GetField(field, BindingFlags.Instance | BindingFlags.NonPublic).SetValue(target, value); } private static void Require(bool condition, string message) { if (!condition) { throw new InvalidOperationException(message); } } } internal static class EffectsSelfTest { internal static IEnumerator Run(Plugin owner) { string text = Path.Combine(Paths.PluginPath, "effects-selftest.txt"); string text2 = Path.Combine(owner.ReplayDirectory, "effectsfixture_" + Guid.NewGuid().ToString("N")); File.WriteAllText(text, "RUNNING: native beam/particle/generated counter mesh recording.\n"); Scene sourceScene = default(Scene); Scene targetScene = default(Scene); ReplayVisualArchive archive = null; ReplayVisualArchive loaded = null; ReplayEffects capture = null; ReplayEffects playback = null; Material ownedMaterial = null; Mesh ownedMesh = null; Texture2D ownedTexture = null; bool failed = false; try { Require(GameIntegration.IsMainMenu() && !owner.Player.IsActive && !owner.Recorder.IsRecording, "Idle main menu required"); sourceScene = SceneManager.CreateScene("EffectsFixtureSource_" + Guid.NewGuid().ToString("N")); GameObject val = new GameObject("FX_BEAM"); SceneManager.MoveGameObjectToScene(val, sourceScene); LineRenderer val2 = val.AddComponent<LineRenderer>(); val2.useWorldSpace = true; val2.positionCount = 2; val2.SetPositions((Vector3[])(object)new Vector3[2] { new Vector3(0f, 1f, 0f), new Vector3(2f, 1f, 0f) }); val2.startWidth = 0.12f; val2.endWidth = 0.08f; Shader val3 = Shader.Find("Sprites/Default") ?? Shader.Find("Particles/Standard Unlit") ?? Shader.Find("Unlit/Color"); Require((Object)(object)val3 != (Object)null, "No supported fixture shader"); ownedMaterial = (((Renderer)val2).sharedMaterial = new Material(val3)); ownedTexture = new Texture2D(2, 2, (TextureFormat)4, false); ownedTexture.SetPixels((Color[])(object)new Color[4] { Color.red, Color.green, Color.blue, Color.white }); ownedTexture.Apply(); ownedMaterial.mainTexture = (Texture)(object)ownedTexture; ownedMaterial.color = new Color(0.2f, 0.7f, 0.9f, 1f); GameObject val5 = new GameObject("FX_PARTICLES"); SceneManager.MoveGameObjectToScene(val5, sourceScene); ParticleSystem val6 = val5.AddComponent<ParticleSystem>(); MainModule main = val6.main; ((MainModule)(ref main)).playOnAwake = false; ((MainModule)(ref main)).maxParticles = 16; ((MainModule)(ref main)).simulationSpace = (ParticleSystemSimulationSpace)1; EmissionModule emission = val6.emission; ((EmissionModule)(ref emission)).enabled = false; ParticleSystemRenderer component = val5.GetComponent<ParticleSystemRenderer>(); ((Renderer)component).sharedMaterial = ownedMaterial; ownedMesh = new Mesh { name = "EffectsFixtureParticleMesh" }; ownedMesh.vertices = (Vector3[])(object)new Vector3[4] { new Vector3(-0.5f, -0.5f, 0f), new Vector3(0.5f, -0.5f, 0f), new Vector3(0.5f, 0.5f, 0f), new Vector3(-0.5f, 0.5f, 0f) }; ownedMesh.uv = (Vector2[])(object)new Vector2[4] { Vector2.zero, Vector2.right, Vector2.one, Vector2.up }; ownedMesh.triangles = new int[6] { 0, 1, 2, 0, 2, 3 }; ownedMesh.RecalculateBounds(); component.renderMode = (ParticleSystemRenderMode)4; component.mesh = ownedMesh; val6.Stop(false, (ParticleSystemStopBehavior)0); EmitParams val7 = default(EmitParams); ((EmitParams)(ref val7)).position = new Vector3(0f, 1f, 0f); ((EmitParams)(ref val7)).startLifetime = 10f; ((EmitParams)(ref val7)).startSize = 0.2f; ((EmitParams)(ref val7)).startColor = Color32.op_Implicit(Color.red); ((EmitParams)(ref val7)).randomSeed = 777u; val6.Emit(val7, 1); val6.Pause(false); GameObject val8 = new GameObject("FX_NONRENDERING_PARTICLES"); SceneManager.MoveGameObjectToScene(val8, sourceScene); ParticleSystem obj = val8.AddComponent<ParticleSystem>(); MainModule main2 = obj.main; ((MainModule)(ref main2)).playOnAwake = false; EmissionModule emission2 = obj.emission; ((EmissionModule)(ref emission2)).enabled = false; obj.Stop(false, (ParticleSystemStopBehavior)0); ParticleSystemRenderer component2 = val8.GetComponent<ParticleSystemRenderer>(); component2.renderMode = (ParticleSystemRenderMode)5; ((Renderer)component2).sharedMaterial = null; Type type = FindType("TMPro.TextMeshPro"); Type type2 = FindType("TMPro.TMP_FontAsset"); Require(type != null && type2 != null, "Game TMP types unavailable"); GameObject val9 = new GameObject("FX_COUNTER"); SceneManager.MoveGameObjectToScene(val9, sourceScene); val9.transform.position = new Vector3(3f, 1f, 0f); Component val10 = val9.AddComponent(type); Object[] array = Resources.FindObjectsOfTypeAll(type2); Require(array.Length != 0, "No loaded game font"); type.GetProperty("font").SetValue(val10, array[0], null); SetText(val10, "000"); ForceText(val10); MeshRenderer component3 = val9.GetComponent<MeshRenderer>(); MeshFilter component4 = val9.GetComponent<MeshFilter>(); Require((Object)(object)component3 != (Object)null && (Object)(object)component4 != (Object)null && (Object)(object)component4.sharedMesh != (Object)null, "Counter mesh was not generated"); Vector4[] array2 = Uvs(component4.sharedMesh); archive = ReplayVisualArchive.BeginCapture(text2, new List<Transform> { val.transform, val5.transform, val8.transform, val9.transform }, (Scene[])(object)new Scene[1] { sourceScene }); capture = new ReplayEffects(); capture.StartRecording(text2, archive, (Scene[])(object)new Scene[1] { sourceScene }, null); capture.TickRecording(0f); val2.SetPositions((Vector3[])(object)new Vector3[2] { new Vector3(0f, 3f, 0f), new Vector3(2f, 3f, 0f) }); Particle[] array3 = (Particle[])(object)new Particle[4]; int particles = val6.GetParticles(array3); Require(particles == 1, "Fixture emission failed"); ((Particle)(ref array3[0])).position = new Vector3(0f, 3f, 0f); val6.SetParticles(array3, particles); SetText(val10, "888"); ForceText(val10); Vector4[] b = Uvs(component4.sharedMesh); Require(Different(array2, b), "Fixture did not change glyph UVs"); capture.TickRecording(1f); capture.StopRecording(); archive.Complete(); archive.Dispose(); archive = null; GameObject[] rootGameObjects = ((Scene)(ref sourceScene)).GetRootGameObjects(); for (int i = 0; i < rootGameObjects.Length; i++) { Object.Destroy((Object)(object)rootGameObjects[i]); } Object.Destroy((Object)(object)ownedMaterial); ownedMaterial = null; File.AppendAllText(text, "Capture completed: same-width counter digits changed UVs; line and particle moved.\n"); targetScene = SceneManager.CreateScene("EffectsFixtureTarget_" + Guid.NewGuid().ToString("N")); loaded = ReplayVisualArchive.Load(text2); playback = new ReplayEffects(); playback.StartPlayback(text2, targetScene, loaded, null); playback.Seek(0.5f); rootGameObjects = ((Scene)(ref targetScene)).GetRootGameObjects(); for (int i = 0; i < rootGameObjects.Length; i++) { Require(((Object)rootGameObjects[i]).name != "Replay effect: FX_NONRENDERING_PARTICLES", "RenderMode.None particle unexpectedly created a replay visual root"); } Require(loaded.MissingAssets == 0, "Intentionally non-rendering particle created a missing-material fallback"); LineRenderer val11 = Find<LineRenderer>(targetScene, "Replay effect: FX_BEAM"); Require((Object)(object)val11 != (Object)null && val11.positionCount == 2 && Mathf.Abs(val11.GetPosition(0).y - 2f) < 0.001f, "Beam interpolation failed"); Require((Object)(object)((Renderer)val11).sharedMaterial != (Object)null && ((Object)((Renderer)val11).sharedMaterial.shader).name == ((Object)val3).name, "Beam material/shader archive was lost"); Texture mainTexture = ((Renderer)val11).sharedMaterial.mainTexture; Texture2D val12 = (Texture2D)(object)((mainTexture is Texture2D) ? mainTexture : null); Require((Object)(object)val12 != (Object)null && (Object)(object)val12 != (Object)(object)ownedTexture && ((Texture)val12).width == 2 && ((Texture)val12).height == 2, "Material texture was not independently archived"); Color[] array4 = (Color[])(object)new Color[4] { Color.red, Color.green, Color.blue, Color.white }; for (int j = 0; j < 2; j++) { for (int k = 0; k < 2; k++) { Color val13 = array4[j * 2 + k]; Color pixel = val12.GetPixel(k, j); Require(Mathf.Abs(val13.r - pixel.r) < 0.01f && Mathf.Abs(val13.g - pixel.g) < 0.01f && Mathf.Abs(val13.b - pixel.b) < 0.01f && Mathf.Abs(val13.a - pixel.a) < 0.01f, "PNG texture texel/orientation mismatch at " + k + "," + j); } } Require(Mathf.Abs(((Renderer)val11).sharedMaterial.color.g - 0.7f) < 0.001f, "Material color was lost"); ParticleSystem val14 = Find<ParticleSystem>(targetScene, "Replay effect: FX_PARTICLES"); Require((Object)(object)val14 != (Object)null && val14.particleCount == 1, "Particle snapshot was lost"); ParticleSystemRenderer component5 = ((Component)val14).GetComponent<ParticleSystemRenderer>(); Require((int)component5.renderMode == 4 && (Object)(object)component5.mesh != (Object)null && (Object)(object)component5.mesh != (Object)(object)ownedMesh && component5.mesh.vertexCount == 4 && component5.mesh.triangles.Length == 6, "Particle mesh archive was lost"); Particle[] array5 = (Particle[])(object)new Particle[4]; val14.GetParticles(array5); Require(Mathf.Abs(((Particle)(ref array5[0])).position.y - 2f) < 0.001f, "Particle interpolation failed"); MeshFilter val15 = Find<MeshFilter>(targetScene, "Replay effect: FX_COUNTER"); Require((Object)(object)val15 != (Object)null && (Object)(object)val15.sharedMesh != (Object)null, "Counter geometry missing"); Vector4[] a = Uvs(val15.sharedMesh); playback.Seek(1f); Vector4[] array6 = Uvs(val15.sharedMesh); Require(!Different(a, array2) && !Different(array6, b), "Counter UV components were not restored exactly"); MeshRenderer component6 = ((Component)val15).GetComponent<MeshRenderer>(); Require((Object)(object)((Renderer)component6).sharedMaterial != (Object)null && (Object)(object)((Renderer)component6).sharedMaterial.mainTexture != (Object)null, "Counter font material/atlas archive was lost"); Require(Different(a, array6), "Changing same-width counter digits were not replayed"); playback.Seek(0f); val14.GetParticles(array5); Require(Mathf.Abs(((Particle)(ref array5[0])).position.y - 1f) < 0.001f, "Backward particle seek failed"); File.AppendAllText(text, "PASS: native LineRenderer recording/interpolation; independently archived textured materials and particle mesh; RenderMode.None/null-material emitter creates no replay root and no missing asset; particle snapshot/interpolation/backward seek; changing TMP-generated counter glyphs, exact UV4 and font atlas; reload from bounded compressed sidecar.\n"); owner.LogInfo("EFFECTS SELFTEST PASS " + text); } catch (Exception ex) { failed = true; File.AppendAllText(text, "FAIL: " + ex); owner.LogFailure(ex); } yield return null; capture?.Dispose(); playback?.Dispose(); archive?.Dispose(); loaded?.Dispose(); if ((Object)(object)ownedMaterial != (Object)null) { Object.Destroy((Object)(object)ownedMaterial); } if ((Object)(object)ownedMesh != (Object)null) { Object.Destroy((Object)(object)ownedMesh); } if ((Object)(object)ownedTexture != (Object)null) { Object.Destroy((Object)(object)ownedTexture); } if (((Scene)(ref sourceScene)).IsValid() && ((Scene)(ref sourceScene)).isLoaded) { SceneManager.UnloadSceneAsync(sourceScene); } if (((Scene)(ref targetScene)).IsValid() && ((Scene)(ref targetScene)).isLoaded) { SceneManager.UnloadSceneAsync(targetScene); } _ = failed; } private static Type FindType(string name) { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { Type type = assemblies[i].GetType(name, throwOnError: false); if (type != null) { return type; } } return null; } private static void SetText(Component target, string value) { ((object)target).GetType().GetProperty("text").SetValue(target, value, null); } private static void ForceText(Component target) { MethodInfo? method = ((object)target).GetType().GetMethod("ForceMeshUpdate", BindingFlags.Instance | BindingFlags.Public, null, new Type[2] { typeof(bool), typeof(bool) }, null); Require(method != null, "TMP mesh update API unavailable"); method.Invoke(target, new object[2] { true, true }); } private static Vector4[] Uvs(Mesh mesh) { List<Vector4> list = new List<Vector4>(); mesh.GetUVs(0, list); return list.ToArray(); } private static bool Different(Vector4[] a, Vector4[] b) { //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) if (a.Length != b.Length) { return true; } for (int i = 0; i < a.Length; i++) { if (a[i] != b[i]) { return true; } } return false; } private static T Find<T>(Scene scene, string name) where T : Component { GameObject[] rootGameObjects = ((Scene)(ref scene)).GetRootGameObjects(); foreach (GameObject val in rootGameObjects) { if (((Object)val).name == name) { return val.GetComponent<T>(); } } return default(T); } private static void Require(bool condition, string message) { if (!condition) { throw new InvalidOperationException(message); } } } internal struct TrackedCandidate { public Transform Root; public EntityKind Kind; public TrackedCandidate(Transform root, EntityKind kind) { Root = root; Kind = kind; } } internal static class GameIntegration { private const BindingFlags Fields = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; private static readonly Dictionary<string, Type> Types = new Dictionary<string, Type>(); private static readonly Dictionary<string, GameObject> Templates = new Dictionary<string, GameObject>(StringComparer.Ordinal); private static readonly Dictionary<string, string> ResourcePaths = new Dictionary<string, string>(StringComparer.Ordinal); private static float lastAssetScan = -100f; private static readonly List<Transform> candidateNodes = new List<Transform>(); internal static bool IsMainMenu() { object obj = Singleton("RunManager", "instance"); if (obj == null) { return false; } object obj2 = Read(obj, "levelCurrent"); Object val = (Object)((obj2 is Object) ? obj2 : null); object obj3 = Read(obj, "levelMainMenu"); Object val2 = (Object)((obj3 is Object) ? obj3 : null); if (Object.op_Implicit(val) && Object.op_Implicit(val2)) { return val == val2; } return false; } internal static bool IsMatchReady() { object obj = Singleton("RunManager", "instance"); object obj2 = Singleton("LevelGenerator", "Instance"); if (obj != null && obj2 != null) { object obj3 = Read(obj2, "Generated"); if (obj3 is bool && (bool)obj3) { object obj4 = Read(obj, "levelCurrent"); Object val = (Object)((obj4 is Object) ? obj4 : null); if (!Object.op_Implicit(val)) { return false; } Type type = GameType("SemiFunc"); MethodInfo methodInfo = ((type == null) ? null : type.GetMethod("RunIsLevel", BindingFlags.Static | BindingFlags.Public, null, Type.EmptyTypes, null)); try { if (methodInfo != null) { return (bool)methodInfo.Invoke(null, null); } } catch (TargetInvocationException) { return false; } string[] array = new string[6] { "levelMainMenu", "levelLobby", "levelLobbyMenu", "levelTutorial", "levelRecording", "levelSplashScreen" }; foreach (string name in array) { object obj5 = Read(obj, name); if (val == (Object)((obj5 is Object) ? obj5 : null)) { return false; } } array = new string[2] { "levelShop", "levelArena" }; foreach (string name2 in array) { if (!(Read(obj, name2) is IEnumerable enumerable)) { continue; } foreach (object item in enumerable) { if (val == (Object)((item is Object) ? item : null)) { return false; } } } return true; } } return false; } internal static ReplayHeader CaptureHeader(int tickRate) { //IL_001c: 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_00f3: 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_0117: Unknown result type (might be due to invalid IL or missing references) RefreshAssets(force: true); object target = Singleton("GameDirector", "instance"); ReplayHeader replayHeader = new ReplayHeader(); Scene activeScene = SceneManager.GetActiveScene(); replayHeader.SceneName = ((Scene)(ref activeScene)).name; replayHeader.GameVersion = Application.version; replayHeader.GameBuild = "26407089"; replayHeader.Seed = ((Read(target, "Seed") is int num) ? num : 0); replayHeader.TickRate = tickRate; ReplayHeader replayHeader2 = replayHeader; Type type = GameType("Module"); if (type == null) { return replayHeader2; } Object[] array = Resources.FindObjectsOfTypeAll(type); foreach (Object obj in array) { Component val = (Component)(object)((obj is Component) ? obj : null); if (IsRuntime(val)) { Transform transform = val.transform; replayHeader2.Rooms.Add(new RoomRecord { Name = CleanName(((Object)val.gameObject).name), ResourcePath = GetResourcePath(val.gameObject), Position = ToVec(transform.position), Rotation = ToQuat(transform.rotation), Scale = ToVec(transform.lossyScale) }); } } replayHeader2.Rooms.Sort((RoomRecord a, RoomRecord b) => string.CompareOrdinal(a.Name + ":" + a.Position.X + ":" + a.Position.Z, b.Name + ":" + b.Position.X + ":" + b.Position.Z)); return replayHeader2; } internal static List<TrackedCandidate> FindCandidates(bool resolveTemplates = true) { //IL_01a0: 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) if (resolveTemplates) { RefreshAssets(force: false); } List<TrackedCandidate> list = new List<TrackedCandidate>(); HashSet<int> seen = new HashSet<int>(); AddType(list, seen, "PlayerAvatar", EntityKind.Player); AddType(list, seen, "EnemyParent", EntityKind.Enemy); AddType(list, seen, "Enemy", EntityKind.Enemy); AddType(list, seen, "PhysGrabHinge", EntityKind.Door); string[] array = new string[4] { "TruckDoor", "ShopKeycardDoor", "TutorialDoor", "DoorTrap" }; foreach (string typeName in array) { AddType(list, seen, typeName, EntityKind.Door); } AddType(list, seen, "ValuableObject", EntityKind.Physics); AddType(list, seen, "PhysGrabObject", EntityKind.Physics); Rigidbody[] array2 = Object.FindObjectsByType<Rigidbody>((FindObjectsInactive)1, (FindObjectsSortMode)0); foreach (Rigidbody val in array2) { if (IsRuntime((Component)(object)val)) { AddCandidate(list, seen, ((Component)val).transform, EntityKind.Physics); } } array = new string[2] { "Interaction", "ExtractionPoint" }; foreach (string typeName2 in array) { AddType(list, seen, typeName2, EntityKind.Interactive); } if (!resolveTemplates) { return list; } HashSet<string> hashSet = new HashSet<string>(StringComparer.Ordinal); foreach (TrackedCandidate item in list) { if (Object.op_Implicit((Object)(object)item.Root)) { hashSet.Add(CleanName(((Object)item.Root).name)); } } GameObject[] array3 = Resources.FindObjectsOfTypeAll<GameObject>(); foreach (GameObject val2 in array3) { if (Object.op_Implicit((Object)(object)val2)) { Scene scene = val2.scene; if (!((Scene)(ref scene)).IsValid() && hashSet.Contains(CleanName(((Object)val2).name))) { Remember(CleanName(((Object)val2).name), string.Empty, val2); } } } return list; } private static void AddType(List<TrackedCandidate> selected, HashSet<int> seen, string typeName, EntityKind kind) { Type type = GameType(typeName); if (type == null || !typeof(Component).IsAssignableFrom(type)) { return; } Object[] array = Object.FindObjectsByType(type, (FindObjectsInactive)1, (FindObjectsSortMode)0); foreach (Object obj in array) { Component val = (Component)(object)((obj is Component) ? obj : null); if (IsRuntime(val)) { Transform root = ((typeName == "PlayerAvatar") ? PlayerRecordingRoot(val) : val.transform); AddCandidate(selected, seen, root, kind); } } } private static Transform PlayerRecordingRoot(Component avatar) { //IL_0026: 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) Transform transform = avatar.transform; object obj = Read(avatar, "playerAvatarVisuals"); Component val = (Component)((obj is Component) ? obj : null); if (!IsRuntime(val) || val.gameObject.scene != avatar.gameObject.scene) { return transform; } Transform transform2 = val.transform; if (transform2.IsChildOf(transform)) { return transform; } Type type = GameType("PlayerAvatar"); if (type == null) { return transform; } Transform parent = transform.parent; int num = 1; while ((Object)(object)parent != (Object)null && num <= 3) { int num2 = 0; Transform val2 = transform2; while ((Object)(object)val2 != (Object)null && (Object)(object)val2 != (Object)(object)parent && num2 <= 3) { val2 = val2.parent; num2++; } if ((Object)(object)val2 == (Object)(object)parent && num2 <= 3) { Component[] componentsInChildren = ((Component)parent).GetComponentsInChildren(type, true); Type type2 = GameType("Module"); bool flag = type2 != null && (Object)(object)((Component)parent).GetComponentInChildren(type2, true) != (Object)null; if (componentsInChildren.Length == 1 && (Object)(object)componentsInChildren[0] == (Object)(object)avatar && !flag && ((Component)parent).GetComponentsInChildren<Transform>(true).Length <= 8192) { return parent; } return transform; } num++; parent = parent.parent; } return transform; } private static void AddCandidate(List<TrackedCandidate> selected, HashSet<int> seen, Transform root, EntityKind kind) { if (!Object.op_Implicit((Object)(object)root) || ((Object)root).name.IndexOf("Menu", StringComparison.OrdinalIgnoreCase) >= 0 || !seen.Add(((Object)root).GetInstanceID())) { return; } foreach (TrackedCandidate item in selected) { if (Object.op_Implicit((Object)(object)item.Root) && root.IsChildOf(item.Root)) { return; } } candidateNodes.Clear(); ((Component)root).GetComponentsInChildren<Transform>(true, candidateNodes); if (candidateNodes.Count <= 8192) { selected.RemoveAll((TrackedCandidate candidate) => Object.op_Implicit((Object)(object)candidate.Root) && candidate.Root.IsChildOf(root)); selected.Add(new TrackedCandidate(root, kind)); } } private static bool IsRuntime(Component component) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0013: 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_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003d: 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_0054: Unknown result type (might be due to invalid IL or missing references) if (Object.op_Implicit((Object)(object)component)) { Scene scene = component.gameObject.scene; if (((Scene)(ref scene)).IsValid()) { scene = component.gameObject.scene; if (((Scene)(ref scene)).isLoaded && component.gameObject.scene == SceneManager.GetActiveScene()) { scene = component.gameObject.scene; return !((Scene)(ref scene)).name.StartsWith("RepoReplay", StringComparison.Ordinal); } } } return false; } internal static Scene[] MissionScenes() { //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) return (Scene[])(object)new Scene[1] { SceneManager.GetActiveScene() }; } internal static string GetResourcePath(GameObject instance, bool resolveTemplate = true) { if (!Object.op_Implicit((Object)(object)instance)) { return string.Empty; } if (resolveTemplate) { RefreshAssets(force: false); } string text = CleanName(((Object)instance).name); if (!ResourcePaths.TryGetValue(text, out var value)) { value = string.Empty; } if (resolveTemplate && !string.IsNullOrEmpty(value)) { ResolveTemplate(text, value); } return value; } internal static GameObject ResolveTemplate(string name, string resourcePath) { //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Unknown result type (might be due to invalid IL or missing references) name = CleanName(name); if (!string.IsNullOrEmpty(resourcePath) && Templates.TryGetValue(resourcePath, out var value) && Object.op_Implicit((Object)(object)value)) { return value; } if (!string.IsNullOrEmpty(resourcePath)) { GameObject val = LoadAssetPath(resourcePath); if (Object.op_Implicit((Object)(object)val)) { Remember(name, resourcePath, val); return val; } } if (Templates.TryGetValue(name, out var value2) && Object.op_Implicit((Object)(object)value2)) { return value2; } RefreshAssets(force: true); if (Templates.TryGetValue(name, out value2) && Object.op_Implicit((Object)(object)value2)) { return value2; } GameObject[] array = Resources.FindObjectsOfTypeAll<GameObject>(); foreach (GameObject val2 in array) { if (Object.op_Implicit((Object)(object)val2)) { Scene scene = val2.scene; if (!((Scene)(ref scene)).IsValid() && !(CleanName(((Object)val2).name) != name)) { Remember(name, string.Empty, val2); return val2; } } } return null; } private static void RefreshAssets(bool force) { if (!force && Time.realtimeSinceStartup - lastAssetScan < 3f) { return; } lastAssetScan = Time.realtimeSinceStartup; object obj = Singleton("RunManager", "instance"); if (obj == null) { return; } RememberPool(Read(obj, "singleplayerPool") as IDictionary); RememberPool(Read(Read(obj, "multiplayerPool"), "ResourceCache") as IDictionary); List<object> list = new List<object>(); FieldInfo[] fields = obj.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); foreach (FieldInfo fieldInfo in fields) { if (fieldInfo.FieldType.Name == "Level") { list.Add(fieldInfo.GetValue(obj)); } else { if (!fieldInfo.FieldType.IsGenericType || !fieldInfo.FieldType.GetGenericArguments().Any((Type t) => t.Name == "Level") || !(fieldInfo.GetValue(obj) is IEnumerable enumerable)) { continue; } foreach (object item in enumerable) { list.Add(item); } } } foreach (object item2 in list) { if (item2 == null) { continue; } Object val = (Object)((item2 is Object) ? item2 : null); if (val != null && !Object.op_Implicit(val)) { continue; } fields = item2.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); for (int i = 0; i < fields.Length; i++) { object value = fields[i].GetValue(item2); if (value == null) { continue; } if (IsPrefabRef(value.GetType())) { RememberPrefabRef(value); } else { if (!(value is IEnumerable enumerable2) || value is string) { continue; } foreach (object item3 in enumerable2) { if (item3 != null && IsPrefabRef(item3.GetType())) { RememberPrefabRef(item3); } } } } } } private static void RememberPool(IDictionary pool) { //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) if (pool == null) { return; } foreach (DictionaryEntry item in pool) { object? value = item.Value; GameObject val = (GameObject)((value is GameObject) ? value : null); if (Object.op_Implicit((Object)(object)val)) { Scene scene = val.scene; if (!((Scene)(ref scene)).IsValid()) { Remember(CleanName(((Object)val).name), (item.Key as string) ?? string.Empty, val); } } } } private static bool IsPrefabRef(Type type) { Type type2 = type; while (type2 != null) { if (type2.Name == "PrefabRef" || type2.Name == "PrefabRef`1") { return true; } type2 = type2.BaseType; } return false; } private static void RememberPrefabRef(object reference) { string text = Read(reference, "PrefabName") as string; string text2 = Read(reference, "ResourcePath") as string; object obj = Read(reference, "Bundle"); AssetBundle val = (AssetBundle)((obj is AssetBundle) ? obj : null); if (!string.IsNullOrEmpty(text2)) { if (Object.op_Implicit((Object)(object)val)) { string text3 = Read(reference, "resourcePath") as string; text2 = "bundle:" + ((Object)val).name + "|" + (text3 ?? text2); } if (!string.IsNullOrEmpty(text)) { ResourcePaths[CleanName(text)] = text2; } } } private static GameObject LoadAssetPath(string path) { if (path.StartsWith("bundle:", StringComparison.Ordinal)) { int num = path.IndexOf('|', 7); if (num < 0) { return null; } string text = path.Substring(7, num - 7); string text2 = path.Substring(num + 1); foreach (AssetBundle allLoadedAssetBundle in AssetBundle.GetAllLoadedAssetBundles()) { if (Object.op_Implicit((Object)(object)allLoadedAssetBundle) && ((Object)allLoadedAssetBundle).name == text) { return allLoadedAssetBundle.LoadAsset<GameObject>(text2); } } return null; } return Resources.Load<GameObject>(path); } private static void Remember(string name, string path, GameObject prefab) { if (Object.op_Implicit((Object)(object)prefab)) { if (!string.IsNullOrEmpty(name)) { Templates[name] = prefab; } if (!string.IsNullOrEmpty(path)) { Templates[path] = prefab; ResourcePaths[name] = path; } } } private static Type GameType(string name) { if (Types.TryGetValue(name, out var value)) { return value; } Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { Type type = assemblies[i].GetType(name, throwOnError: false); if (type != null) { Types[name] = type; return type; } } return null; } private static object Singleton(string typeName, string fieldName) { Type type = GameType(typeName); if (!(type == null)) { return type.GetField(fieldName, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(null); } return null; } private static object Read(object target, string name) { if (target != null) { Object val = (Object)((target is Object) ? target : null); if (val == null || Object.op_Implicit(val)) { Type type = target.GetType(); while (type != null) { FieldInfo field = type.GetField(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (field != null) { return field.GetValue(target); } PropertyInfo property = type.GetProperty(name, BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); if (property != null && property.GetIndexParameters().Length == 0) { return property.GetValue(target, null); } type = type.BaseType; } return null; } } return null; } private static string CleanName(string name) { return (name ?? string.Empty).Replace("(Clone)", string.Empty).Trim(); } private static Vec3 ToVec(Vector3 value) { //IL_0000: 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: Unknown result type (might be due to invalid IL or missing references) return new Vec3(value.x, value.y, value.z); } private static Quat ToQuat(Quaternion value) { //IL_0000: 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: 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) return new Quat(value.x, value.y, value.z, value.w); } } internal sealed class HudTheme { internal static readonly Color Text = Color32.op_Implicit(new Color32((byte)226, (byte)234, (byte)218, byte.MaxValue)); internal static readonly Color Muted = Color32.op_Implicit(new Color32((byte)135, (byte)154, (byte)133, byte.MaxValue)); internal static readonly Color Green = Color32.op_Implicit(new Color32((byte)158, (byte)244, (byte)76, byte.MaxValue)); internal static readonly Color Amber = new Color(1f, 0.55f, 0f, 1f); internal static readonly Color Red = Color32.op_Implicit(new Color32(byte.MaxValue, (byte)89, (byte)74, byte.MaxValue)); internal static readonly Color Panel = Color32.op_Implicit(new Color32((byte)6, (byte)13, (byte)9, (byte)238)); internal static readonly Color Edge = Color32.op_Implicit(new Color32((byte)53, (byte)76, (byte)46, byte.MaxValue)); private readonly Dictionary<int, GUIStyle> styles = new Dictionary<int, GUIStyle>(); private Font font; private bool nativeFont; private float nextFontSearch; internal void Prepare() { if (nativeFont || Time.realtimeSinceStartup < nextFontSearch) { return; } nextFontSearch = Time.realtimeSinceStartup + 5f; Font val = null; Font val2 = null; Font val3 = null; Font[] array = Resources.FindObjectsOfTypeAll<Font>(); foreach (Font val4 in array) { if (!((Object)(object)val4 == (Object)null)) { if (((Object)val4).name.StartsWith("Teko", StringComparison.Ordinal)) { val2 = val4; break; } if (((Object)val4).name.StartsWith("RobotoMono", StringComparison.Ordinal)) { val3 = val4; } if (((Object)val4).name == "PerfectDOSVGA437") { val = val4; } } } if ((Object)(object)val2 == (Object)null) { val2 = val; } if ((Object)(object)val2 == (Object)null) { val2 = val3; } if (!((Object)(object)val2 == (Object)null)) { font = val2; nativeFont = true; styles.Clear(); } } private GUIStyle Style(int size) { //IL_001c: 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_0047: 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_0055: 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_0063: 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_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Expected O, but got Unknown //IL_0075: 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_0080: Expected O, but got Unknown //IL_0081: Expected O, but got Unknown if (styles.TryGetValue(size, out var value)) { return value; } value = new GUIStyle(GUI.skin.label) { font = (((Object)(object)font != (Object)null) ? font : GUI.skin.font), fontSize = size, fontStyle = (FontStyle)1, richText = false, alignment = (TextAnchor)3, clipping = (TextClipping)1, padding = new RectOffset(), margin = new RectOffset() }; styles[size] = value; return value; } internal static void Fill(Rect rect, Color color) { //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_000b: Unknown result type (might be due to invalid IL or missing references) Color color2 = GUI.color; GUI.color = color; GUI.DrawTexture(rect, (Texture)(object)Texture2D.whiteTexture); GUI.color = color2; } internal static void Outline(Rect rect, Color color, float thickness = 1f) { //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_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_005a: 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_007d: 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) Fill(new Rect(((Rect)(ref rect)).x, ((Rect)(ref rect)).y, ((Rect)(ref rect)).width, thickness), color); Fill(new Rect(((Rect)(ref rect)).x, ((Rect)(ref rect)).yMax - thickness, ((Rect)(ref rect)).width, thickness), color); Fill(new Rect(((Rect)(ref rect)).x, ((Rect)(ref rect)).y, thickness, ((Rect)(ref rect)).height), color); Fill(new Rect(((Rect)(ref rect)).xMax - thickness, ((Rect)(ref rect)).y, thickness, ((Rect)(ref rect)).height), color); } internal void Label(Rect rect, string text, int size, Color color, TextAnchor align = (TextAnchor)3) { //IL_0009: 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_005c: 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_007e: Unknown result type (might be due to invalid IL or missing references) GUIStyle val = Style(size); val.alignment = align; val.normal.textColor = new Color(0f, 0f, 0f, 0.85f); GUI.Label(new Rect(((Rect)(ref rect)).x + 1f, ((Rect)(ref rect)).y + 1f, ((Rect)(ref rect)).width, ((Rect)(ref rect)).height), text ?? "", val); val.normal.textColor = color; GUI.Label(rect, text ?? "", val); } internal bool Button(Rect rect, string text, int size, bool selected = false, bool danger = false) { //IL_000e: 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_0038: 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_0024: 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_0074: 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_005d: 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_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_00b2: 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_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: 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: 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_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) bool flag = GUI.enabled && ((Rect)(ref rect)).Contains(Event.current.mousePosition); Color val = (danger ? Red : (selected ? Green : Text)); Fill(rect, Color32.op_Implicit(selected ? new Color32((byte)38, (byte)62, (byte)25, (byte)245) : (flag ? new Color32((byte)31, (byte)44, (byte)24, byte.MaxValue) : new Color32((byte)11, (byte)21, (byte)13, (byte)240)))); Outline(rect, (!GUI.enabled) ? Color32.op_Implicit(new Color32((byte)30, (byte)38, (byte)29, byte.MaxValue)) : (flag ? Amber : (selected ? Green : Edge))); Label(rect, text, size, (!GUI.enabled) ? (Muted * 0.6f) : (flag ? Amber : val), (TextAnchor)4); return GUI.Button(rect, GUIContent.none, GUIStyle.none); } internal float Slider(Rect hit, float value, float min, float max, Color accent) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Invalid comparison between Unknown and I4 //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Invalid comparison between Unknown and I4 //IL_0069: 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) //IL_0028: 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_003c: 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_00e6: 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_011f: 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_0144: 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_0163: Unknown result type (might be due to invalid IL or missing references) int controlID = GUIUtility.GetControlID((FocusType)2, hit); Event current = Event.current; if (GUI.enabled && current.button == 0 && (int)current.type == 0 && ((Rect)(ref hit)).Contains(current.mousePosition)) { GUIUtility.hotControl = controlID; value = FromMouse(hit, current.mousePosition.x, min, max); current.Use(); } else if (GUIUtility.hotControl == controlID && (int)current.type == 3) { value = FromMouse(hit, current.mousePosition.x, min, max); current.Use(); } else if (GUIUtility.hotControl == controlID && (int)current.type == 1) { GUIUtility.hotControl = 0; current.Use(); } float num = ((max > min) ? Mathf.InverseLerp(min, max, value) : 0f); Rect rect = default(Rect); ((Rect)(ref rect))..ctor(((Rect)(ref hit)).x, ((Rect)(ref hit)).center.y - 2f, ((Rect)(ref hit)).width, 4f); Fill(rect, Color32.op_Implicit(new Color32((byte)42, (byte)58, (byte)39, byte.MaxValue))); Fill(new Rect(((Rect)(ref rect)).x, ((Rect)(ref rect)).y, ((Rect)(ref rect)).width * num, ((Rect)(ref rect)).height), accent); Fill(new Rect(((Rect)(ref hit)).x + ((Rect)(ref hit)).width * num - 3f, ((Rect)(ref hit)).center.y - 8f, 6f, 16f), accent); return Mathf.Clamp(value, min, max); } private static float FromMouse(Rect rect, float x, float min, float max) { return Mathf.Lerp(min, max, Mathf.Clamp01((x - ((Rect)(ref rect)).x) / Mathf.Max(1f, ((Rect)(ref rect)).width))); } } internal static class InputGateSelfTest { private sealed class TestCase { internal Plugin Owner; internal ReplayUI Ui; internal ReplayInputGate Gate; internal Harmony Harmony; internal bool PreviousVisible; internal bool WatchRelease; internal bool CursorVisible; internal CursorLockMode CursorLock; internal readonly Dictionary<Renderer, bool> Renderers = new Dictionary<Renderer, bool>(); internal readonly Dictionary<Behaviour, bool> Graphics = new Dictionary<Behaviour, bool>(); internal Component Menu; internal MethodInfo MenuUpdate; internal int OriginalUpdates; internal int SkippedUpdates; internal int ReleaseObserved; internal string ReleaseError; internal string Report; internal string Screenshot; } private static TestCase current; internal static IEnumerator Run(Plugin owner) { TestCase test = new TestCase { Owner = owner, Report = Path.Combine(Paths.PluginPath, "inputgate-selftest.txt"), Screenshot = Path.Combine(Paths.PluginPath, "inputgate-selftest.png") }; File.WriteAllText(test.Report, "RUNNING: native menu/cursor exclusivity; no synthesized OS input.\n"); IEnumerator run = Execute(test); Exception failure = null; while (true) { bool flag; try { flag = run.MoveNext(); } catch (Exception ex) { failure = ex; break; } if (!flag) { break; } yield return run.Current; } (run as IDisposable)?.Dispose(); try { test.WatchRelease = false; if (test.Ui != null) { test.Ui.Visible = test.PreviousVisible; test.Gate?.Tick(test.PreviousVisible, isReplay: false); } } catch (Exception ex2) { if (failure == null) { failure = ex2; } } for (int i = 0; i < 3; i++) { yield return null; } if (failure != null) { File.AppendAllText(test.Report, "FAIL: " + failure?.ToString() + "\n"); owner.LogFailure(failure); } else { File.AppendAllText(test.Report, "PASS: real native menu/click suppression; hidden native pointer; exact release restoration and resumed native Update; software cursor and screenshot observations above. Held-click OS input was not synthesized.\n"); owner.LogInfo("INPUT GATE SELFTEST PASS " + test.Report); } } private static IEnumerator Execute(TestCase test) { Require((Object)(object)test.Owner != (Object)null && GameIntegration.IsMainMenu() && !test.Owner.Player.IsActive && !test.Owner.Recorder.IsRecording, "Idle main menu required"); BindingFlags flags = BindingFlags.Instance | BindingFlags.NonPublic; test.Ui = typeof(Plugin).GetField("ui", flags)?.GetValue(test.Owner) as ReplayUI; test.Gate = typeof(Plugin).GetField("inputGate", flags)?.GetValue(test.Owner) as ReplayInputGate; Require(test.Ui != null && test.Gate != null, "Existing replay UI/input gate unavailable"); test.PreviousVisible = test.Ui.Visible; test.Ui.Visible = false; for (int i = 0; i < 6; i++) { if (!test.Gate.Capturing) { break; } test.Gate.Tick(uiVisible: false, isReplay: false); yield return null; } Require(!test.Gate.Capturing, "Release physical mouse buttons before running the fixture"); Require(NoButtonsHeld() && !Input.anyKeyDown, "Fixture requires an idle pointer/keyboard"); Type type = AccessTools.TypeByName("MenuManager"); Require(type != null, "Native MenuManager type unavailable"); Object[] array = Object.FindObjectsByType(type, (FindObjectsInactive)0, (FindObjectsSortMode)0); foreach (Object obj in array) { Component val = (Component)(object)((obj is Component) ? obj : null); if (val == null) { continue; } Scene scene = val.gameObject.scene; if (((Scene)(ref scene)).IsValid()) { Behaviour val2 = (Behaviour)(object)((val is Behaviour) ? val : null); if (val2 == null || val2.enabled) { test.Menu = val; break; } } } test.MenuUpdate = AccessTools.Method(type, "Update", Type.EmptyTypes, (Type[])null); Require((Object)(object)test.Menu != (Object)null && test.MenuUpdate != null, "Active native MenuManager.Update unavailable"); current = test; test.Harmony = new Harmony("RepoReplay.InputGateSelfTest." + Guid.NewGuid().ToString("N")); try { test.Harmony.Patch((MethodBase)test.MenuUpdate, (HarmonyMethod)null, new HarmonyMethod(typeof(InputGateSelfTest), "ObserveNativeUpdate", (Type[])null) { priority = 0 }, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); test.Harmony.Patch((MethodBase)AccessTools.Method(typeof(ReplayInputGate), "Release", (Type[])null, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(InputGateSelfTest), "ObserveRelease", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); test.MenuUpdate.Invoke(test.Menu, null); Require(test.OriginalUpdates > 0, "Native Update probe could not observe the unblocked baseline"); CaptureCursorBaseline(test); test.CursorVisible = Cursor.visible; test.CursorLock = Cursor.lockState; Require(test.Renderers.Count + test.Graphics.Count > 0, "No native MenuCursor visual found"); File.AppendAllText(test.Report, "Baseline: native cursor renderers=" + test.Renderers.Count + ", graphics/canvas=" + test.Graphics.Count + ", Cursor.visible=" + test.CursorVisible + ", lock=" + ((object)Unsafe.As<CursorLockMode, CursorLockMode>(ref test.CursorLock)/*cast due to .constrained prefix*/).ToString() + "; native Update probe active.\n"); int i = test.OriginalUpdates; int skippedUpdates = test.SkippedUpdates; int suppressedCallbackCount = test.Gate.SuppressedCallbackCount; test.Ui.Visible = true; test.Gate.Tick(uiVisible: true, isReplay: false); Require(test.Gate.Capturing && ReplayInputGate.BlocksNativeMenu, "Overlay did not capture native menu input"); AssertHidden(test); Require(!Cursor.visible && (int)Cursor.lockState == 0, "OS cursor not hidden/unlocked while overlay is visible"); test.MenuUpdate.Invoke(test.Menu, null); Require(test.OriginalUpdates == i && test.SkippedUpdates == skippedUpdates + 1 && test.Gate.SuppressedCallbackCount > suppressedCallbackCount, "MenuManager.Update was not suppressed by the real gate prefix (__runOriginal=" + (test.OriginalUpdates != i) + ", skipped=" + (test.SkippedUpdates - skippedUpdates) + ", suppressed=" + (test.Gate.SuppressedCallbackCount - suppressedCallbackCount) + ")"); int num = AssertNativeClickQueriesFalse(test); Require(num > 0, "No native click query could be verified"); File.AppendAllText(test.Report, "Captured: MenuManager.Update postfix observed __runOriginal=false (" + test.SkippedUpdates + " skipped); " + num + " native bool hover/click query paths returned false; all native cursor visuals disabled.\n"); yield return null; yield return null; yield return (object)new WaitForEndOfFrame(); Require(test.OriginalUpdates == i, "Native menu Update escaped while the overlay was visible"); AssertHidden(test); object? obj2 = typeof(ReplayInputGate).GetField("cursorTexture", flags)?.GetValue(test.Gate); Texture2D val3 = (Texture2D)((obj2 is Texture2D) ? obj2 : null); if (Application.isFocused) { Require((Object)(object)val3 != (Object)null, "Software pointer was not drawn by the real OnGUI repaint path"); } File.AppendAllText(test.Report, "Software cursor: texture-created=" + ((Object)(object)val3 != (Object)null) + ", focused=" + Application.isFocused + ", mouse=" + ((object)Input.mousePosition/*cast due to .constrained prefix*/).ToString() + ", screen=" + Screen.width + "x" + Screen.height + ", GUI depths=" + -20000 + " / " + -10000 + ".\n"); ScreenCapture.CaptureScreenshot(test.Screenshot); for (int k = 0; k < 4; k++) { yield return null; yield return (object)new WaitForEndOfFrame(); } File.AppendAllText(test.Report, File.Exists(test.Screenshot) ? ("Overlay screenshot: " + test.Screenshot + "\n") : "Overlay screenshot requested; native write was still pending.\n"); Require(NoButtonsHeld(), "Release physical mouse buttons before the restoration check"); test.WatchRelease = true; test.Ui.Visible = false; test.Gate.Tick(uiVisible: false, isReplay: false); Require(test.Gate.Capturing && ReplayInputGate.BlocksNativeMenu, "Overlay close skipped the released-frame input barrier"); suppressedCallbackCount = test.Gate.SuppressedCallbackCount; skippedUpdates = test.SkippedUpdates; test.MenuUpdate.Invoke(test.Menu, null); Require(test.OriginalUpdates == i && test.SkippedUpdates == skippedUpdates + 1 && test.Gate.SuppressedCallbackCount > suppressedCallbackCount, "Native menu received the overlay-closing frame"); Require(AssertNativeClickQueriesFalse(test) > 0, "Closing-frame native click guard missing"); for (int k = 0; k < 8; k++) { if (!test.Gate.Capturing) { break; } yield return null; test.Gate.Tick(uiVisible: false, isReplay: false); } Require(!test.Gate.Capturing && !ReplayInputGate.BlocksNativeMenu, "Native input did not resume after the released-frame barrier"); Require(test.ReleaseObserved == 1 && test.ReleaseError == null, test.ReleaseError ?? "Exact Release state was not observed"); int originalUpdates = test.OriginalUpdates; test.MenuUpdate.Invoke(test.Menu, null); Require(test.OriginalUpdates == originalUpdates + 1, "Native MenuManager.Update did not resume after gate release"); File.AppendAllText(test.Report, "Released: closing-frame Update/click queries blocked; Release postfix observed exact renderer/Graphic enabled and Cursor visible/lock baseline; native Update resumed. Suppressed callbacks=" + test.Gate.SuppressedCallbackCount + ".\n"); } finally { test.WatchRelease = false; Harmony harmony = test.Harmony; if (harmony != null) { harmony.UnpatchSelf(); } if (current == test) { current = null; } } } private static void ObserveNativeUpdate(bool __runOriginal) { if (current != null) { if (__runOriginal) { current.OriginalUpdates++; } else { current.SkippedUpdates++; } } } private static void ObserveRelease() { //IL_010c: 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) TestCase testCase = current; if (testCase == null || !testCase.WatchRelease) { return; } testCase.ReleaseObserved++; foreach (KeyValuePair<Renderer, bool> renderer in testCase.Renderers) { if ((Object)(object)renderer.Key != (Object)null && renderer.Key.enabled != renderer.Value) { testCase.ReleaseError = "Native cursor renderer baseline mismatch: " + ((Object)renderer.Key).name; } } foreach (KeyValuePair<Behaviour, bool> graphic in testCase.Graphics) { if ((Object)(object)graphic.Key != (Object)null && graphic.Key.enabled != graphic.Value) { testCase.ReleaseError = "Native cursor Graphic/Canvas baseline mismatch: " + ((Object)graphic.Key).name; } } if (Cursor.visible != testCase.CursorVisible || Cursor.lockState != testCase.CursorLock) { testCase.ReleaseError = "Cursor.visible/lock baseline was not restored exactly"; } } private static void CaptureCursorBaseline(TestCase test) { //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) //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) Type type = AccessTools.TypeByName("MenuCursor"); Require(type != null, "Native MenuCursor type unavailable"); Object[] array = Object.FindObjectsByType(type, (FindObjectsInactive)1, (FindObjectsSortMode)0); foreach (Object obj in array) { Component val = (Component)(object)((obj is Component) ? obj : null); if ((Object)(object)val == (Object)null) { continue; } Scene scene = val.gameObject.scene; if (!((Scene)(ref scene)).IsValid()) { continue; } scene = val.gameObject.scene; if (!((Scene)(ref scene)).isLoaded) { continue; } Behaviour val2 = (Behaviour)(object)((val is Behaviour) ? val : null); if (val2 != null && !val2.enabled) { continue; } Renderer[] componentsInChildren = val.GetComponentsInChildren<Renderer>(true); foreach (Renderer val3 in componentsInChildren) { if ((Object)(object)val3 != (Object)null) { test.Renderers[val3] = val3.enabled; } } Behaviour[] componentsInChildren2 = val.GetComponentsInChildren<Behaviour>(true); foreach (Behaviour val4 in componentsInChildren2) { if ((Object)(object)val4 != (Object)null && (val4 is Canvas || IsGraphic(((object)val4).GetType()))) { test.Graphics[val4] = val4.enabled; } } } } private static void AssertHidden(TestCase test) { foreach (KeyValuePair<Renderer, bool> renderer in test.Renderers) { bool condition = (Object)(object)renderer.Key == (Object)null || !renderer.Key.enabled; Renderer key = renderer.Key; Require(condition, "Native cursor renderer remained visible: " + ((key != null) ? ((Object)key).name : null)); } foreach (KeyValuePair<Behaviour, bool> graphic in test.Graphics) { bool condition2 = (Object)(object)graphic.Key == (Object)null || !graphic.Key.enabled; Behaviour key2 = graphic.Key; Require(condition2, "Native cursor Graphic/Canvas remained visible: " + ((key2 != null) ? ((Object)key2).name : null)); } Require(test.Gate.HiddenNativeCursorRendererCount >= test.Renderers.Count + test.Graphics.Count, "Gate did not register every native cursor visual"); } private static int AssertNativeClickQueriesFalse(TestCase test) { //IL_0100: 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) int num = 0; string[][] array = new string[4][] { new string[2] { "SemiFunc", "InputUIClick" }, new string[2] { "SemiFunc", "UIMouseHover" }, new string[2] { "InputManager", "IsUIClickFromMouseThisFrame" }, new string[2] { "InputManager", "IsUIClickFromKeyboardThisFrame" } }; foreach (string[] array2 in array) { Type type = AccessTools.TypeByName(array2[0]); if (type == null) { continue; } MethodInfo methodInfo = AccessTools.Method(type, array2[1], Type.EmptyTypes, (Type[])null); if (methodInfo == null || methodInfo.ReturnType != typeof(bool)) { continue; } object obj = null; if (!methodInfo.IsStatic) { Object[] array3 = Object.FindObjectsByType(type, (FindObjectsInactive)1, (FindObjectsSortMode)0); foreach (Object val in array3) { Component val2 = (Component)(object)((val is Component) ? val : null); if (val2 != null) { Scene scene = val2.gameObject.scene; if (((Scene)(ref scene)).IsValid()) { obj = val; break; } } } if (obj == null) { continue; } } int suppressedCallbackCount = test.Gate.SuppressedCallbackCount; Require(!(bool)methodInfo.Invoke(obj, null) && test.Gate.SuppressedCallbackCount > suppressedCallbackCount, "Native click query escaped input gate: " + array2[0] + "." + array2[1]); num++; } return num; } private static bool NoButtonsHeld() { if (!Input.GetMouseButton(0) && !Input.GetMouseButton(1)) { return !Input.GetMouseButton(2); } return false; } private static bool IsGraphic(Type type) { while (type != null) { if (type.FullName == "UnityEngine.UI.Graphic") { return true; } type = type.BaseType; } return false; } private static void Require(bool condition, string message) { if (!condition) { throw new InvalidOperationException(message); } } } internal static class IntegrationSelfTest { private sealed class Context { internal string SaveName; internal string ReplayFile; internal string Report; internal string Screenshot; internal string Stage = "initializing"; internal int Rooms; internal int Entities; internal int Frames; internal float Duration; } internal static IEnumerator Run(Plugin owner) { Context context = new Context { SaveName = "REPLAY_TEST_" + DateTime.UtcNow.ToString("yyyyMMdd_HHmmss") + "_" + Guid.NewGuid().ToString("N").Substring(0, 8), Report = Path.Combine(Paths.PluginPath, "integration-selftest.txt"), Screenshot = Path.Combine(Paths.PluginPath, "integration-selftest.png") }; File.WriteAllText(context.Report, "RUNNING: opt-in native mission integration test.\nSave=" + context.SaveName + "\n"); IEnumerator steps = Steps(owner, context); while (true) { object obj = null; bool flag = false; Exception ex = null; try { flag = steps.MoveNext(); if (flag) { obj = steps.Current; } } catch (Exception error) { ex = Unwrap(error); } if (ex != null) { try { owner.Recorder.Stop(); if (owner.Player.IsActive) { owner.StopReplay(); } } catch (Exception error2) { owner.LogFailure(error2); } File.AppendAllText(context.Report, "FAIL at " + context.Stage + ": " + ex?.ToString() + "\n"); owner.LogFailure(ex); owner.LogInfo("INTEGRATION SELFTEST FAIL stage=" + context.Stage + " report=" + context.Report); break; } if (flag) { yield return obj; continue; } break; } } private static IEnumerator Steps(Plugin owner, Context context) { Stage(owner, context, "waiting for initialized main menu"); yield return (object)new WaitForSecondsRealtime(3f); Require(GameIntegration.IsMainMenu() && !owner.Player.IsActive && !owner.Recorder.IsRecording, "Integration test requires an idle main menu."); Require(!PhotonFlag("InRoom") && !PhotonFlag("IsConnected"), "Photon must be disconnected before the offline test."); string text = Path.Combine(Application.persistentDataPath, "saves", context.SaveName); Require(!Directory.Exists(text) && !File.Exists(text), "Throwaway save name unexpectedly exists."); Stage(owner, context, "initializing unique throwaway single-player run"); object obj = Singleton("GameManager", "instance"); object obj2 = Singleton("RunManager", "instance"); object obj3 = Singleton("StatsManager", "instance"); Require(obj != null && obj2 != null && obj3 != null, "Game manager singletons are unavailable."); Invoke(obj, "SetGameMode", 0); Invoke(obj2, "ResetProgress"); Invoke(obj, "SetConnectRandom", false); Invoke(obj, "SetLobbyType", EnumValue("GameManager+LobbyTypes", "Private")); Invoke(obj3, "SaveFileCreate", context.SaveName, false); Require(SelectedSave() == context.SaveName, "Native save selection is not the unique test run."); File.AppendAllText(context.Report, "SaveFolder=" + text + "\n"); Stage(owner, context, "entering native mission"); object menuGenerator = Singleton("LevelGenerator", "Instance"); Invoke(obj2, "ChangeLevel", true, false, EnumValue("RunManager+ChangeLevelType", "RunLevel")); float deadline = Time.realtimeSinceStartup + 120f; while (Singleton("LevelGenerator", "Instance") == menuGenerator || !GameIntegration.IsMatchReady()) { Require(Time.realtimeSinceStartup < deadline, "Native level generation timed out after 120 seconds."); Require(SelectedSave() == context.SaveName, "Save selection changed during level generation."); yield return null; } Require(SelectedSave() == context.SaveName && !PhotonFlag("InRoom"), "Mission is not owned by the offline test save."); Stage(owner, context, "sampling real generated mission for 12 seconds"); if (!owner.Recorder.IsRecording) { owner.Recorder.Start(owner.TickRate); } Require(owner.Recorder.IsRecording, "Recorder did not start in the generated mission."); context.ReplayFile = owner.Recorder.CurrentFile; float until = Time.realtimeSinceStartup + 12f; while (Time.realtimeSinceStartup < until) { Require(SelectedSave() == context.SaveName, "Save selection changed while recording."); Require(owner.Recorder.IsRecording, "Recorder stopped before the 12-second sample completed."); yield return null; } owner.Recorder.Stop(); while (owner.Recorder.IsFinalizing) { owner.Recorder.PollFinalizations(); yield return null; } Require(File.Exists(context.ReplayFile), "Recorder did not publish a completed binary replay."); ReplayRecording recording = ReplayFile.Read(context.ReplayFile); context.Rooms = recording.Header.Rooms.Count; context.Entities = recording.Entities.Count; context.Frames = recording.Frames.Count; context.Duration = recording.Duration; Require(context.Rooms > 0 && context.Entities > 0 && context.Frames > 20 && context.Duration >= 10f, "Real recording is missing rooms, entities, duration, or frames."); Require(recording.Entities.Values.Any((EntityDefinition entity) => entity.Kind == EntityKind.Player), "Real player avatar was not tracked."); Require(recording.Entities.Values.Any((EntityDefinition entity) => entity.Kind == EntityKind.Player && entity.Nodes.Count > 20), "Player body/head/arm hierarchy was not tracked."); Stage(owner, context, "validated real binary: rooms=" + context.Rooms + " entities=" + context.Entities + " frames=" + context.Frames); Require(SelectedSave() == context.SaveName, "Refusing to return with a different save selected."); object missionGenerator = Singleton("LevelGenerator", "Instance"); Invoke(Singleton("RunManager", "instance"), "ChangeLevel", true, false, EnumValue("RunManager+ChangeLevelType", "MainMenu")); Stage(owner, context, "returning through native main-menu transition"); deadline = Time.realtimeSinceStartup + 90f; while (true) { if (Singleton("LevelGenerator", "Instance") != missionGenerator && GameIntegration.IsMainMenu() && Singleton("LevelGenerator", "Instance") != null) { object obj4 = Read(Singleton("LevelGenerator", "Instance"), "Generated"); if (obj4 is bool && (bool)obj4) { break; } } Require(Time.realtimeSinceStartup < deadline, "Native return to main menu timed out after 90 seconds."); yield return null; } yield return (object)new WaitForSecondsRealtime(3f); Require(!owner.Recorder.IsRecording && GameIntegration.IsMainMenu(), "Main menu did not settle after returning."); Stage(owner, context, "loading recorded mission in isolated replay scene"); owner.LoadReplay(context.ReplayFile); Require(owner.Player.IsActive && (Object)(object)owner.Player.Camera != (Object)null, "Actual recorded replay failed to open."); Scene activeScene = SceneManager.GetActiveScene(); Require(((Scene)(ref activeScene)).name.StartsWith("RepoReplay_", StringComparison.Ordinal), "Playback did not create its isolated visual scene."); GameObject[] rootGameObjects = ((Scene)(ref activeScene)).GetRootGameObjects(); Require(rootGameObjects.Length >= context.Entities + 2, "Reconstructed environment or entity roots are missing."); GameObject[] array = rootGameObjects; foreach (GameObject val in array) { Require(val.GetComponentsInChildren<Rigidbody>(true).Length == 0 && val.GetComponentsInChildren<Collider>(true).Length == 0, "Replay scene contains physics or trigger components."); MonoBehaviour[] componentsInChildren = val.GetComponentsInChildren<MonoBehaviour>(true); foreach (MonoBehaviour val2 in componentsInChildren) { Require(val2 is ReplayCamera || ((object)val2).GetType().FullName == "UnityEngine.Rendering.PostProcessing.PostProcessLayer" || ((object)val2).GetType().FullName == "UnityEngine.Rendering.PostProcessing.PostProcessVolume", "Replay scene contains gameplay MonoBehaviour: " + ((object)val2).GetType().FullName); } } Require(rootGameObjects.Any((GameObject root) => root.activeInHierarchy && root.GetComponentsInChildren<Renderer>(true).Length != 0), "No reconstructed visuals are active."); Require(!owner.Player.IsLegacy && owner.Player.VisualMissingAssets == 0, "Some real recorded visuals are missing or archive was not used: " + owner.Status); array = rootGameObjects; for (int num = 0; num < array.Length; num++) { Renderer[] componentsInChildren2 = array[num].GetComponentsInChildren<Renderer>(true); foreach (Renderer val3 in componentsInChildren2) { Material[] sharedMaterials = val3.sharedMaterials; foreach (Material val4 in sharedMaterials) { Require((Object)(object)val4 != (Object)null && (Object)(object)val4.shader != (Object)null && val4.shader.isSupported, "Destroyed or unsupported material after original level unload: " + ((Object)val3).name); } } } float[] array2 = new float[6] { 0f, 0.17f, 0.83f, 0.4f, 1f, 0.5f }; foreach (float num4 in array2) { float num5 = recording.Duration * num4; owner.Player.Seek(num5); Require(Mathf.Abs(owner.Player.Time - num5) < 0.002f, "Recorded mission seek assertion failed."); } EntityDefinition player = recording.Entities.Values.First((EntityDefinition entity) => entity.Kind == EntityKind.Player); EntityState entityState = recording.Frames.First((ReplayFrame frame) => frame.States.Any((EntityState state) => state.Id == player.Id && state.Nodes.Count > 0)).States.First((EntityState state) => state.Id == player.Id && state.Nodes.Count > 0); Transform val5 = owner.Player.PlayerAnchor(); Vector3 val6 = (((Object)(object)val5 != (Object)null) ? val5.position : VisualFactory.V(entityState.Nodes[0].Position)) + Vector3.up; ReplayCamera camera = owner.Player.Camera; ((Component)camera).transform.position = val6 + new Vector3(0f, 2f, -5f); ((Component)camera).transform.LookAt(val6); camera.AddKeyframe(0f); ((Component)camera).transform.position = val6 + new Vector3(3f, 2f, -4f); ((Component)camera).transform.LookAt(val6); camera.AddKeyframe(recording.Duration); owner.Player.SaveCameraPath(); camera.Keyframes.Clear(); owner.Player.LoadCameraPath(); Require(camera.Keyframes.Count == 2, "Real replay camera-path roundtrip failed."); camera.PathEnabled = true; owner.Player.Seek(recording.Duration * 0.5f); Require(Vector3.Distance(((Component)camera).transform.position, val6) < 10f, "Camera path interpolation produced an implausible position."); Stage(owner, context, "capturing actual replay screenshot"); yield return (object)new WaitForEndOfFrame(); ScreenCapture.CaptureScreenshot(context.Screenshot); yield return (object)new WaitForSecondsRealtime(3f); Require(File.Exists(context.Screenshot) && new FileInfo(context.Screenshot).Length > 1000, "Screenshot was not written."); owner.StopReplay(); yield return null; Require(!owner.Player.IsActive && GameIntegration.IsMainMenu(), "Replay exit did not restore the main menu."); File.AppendAllText(context.Report, "PASS: native offline mission generation, 12s real recording, compressed replay read, recorded rooms and player entities, isolated geometry/proxies, no gameplay scripts or physics, timeline seek, camera path roundtrip, screenshot, replay exit.\nReplay=" + context.ReplayFile + "\nRooms=" + context.Rooms + "\nEntities=" + context.Entities + "\nFrames=" + context.Frames + "\nDuration=" + context.Duration + "\nScreenshot=" + context.Screenshot + "\nLimit: no multiplayer or six-client test.\n"); owner.LogInfo("INTEGRATION SELFTEST PASS report=" + context.Report + " replay=" + context.ReplayFile); } private static void Stage(Plugin owner, Context context, string stage) { context.Stage = stage; owner.LogInfo("INTEGRATION SELFTEST " + stage); File.AppendAllText(context.Report, DateTime.UtcNow.ToString("O") + " " + stage + "\n"); } private static void Require(bool condition, string message) { if (!condition) { throw new InvalidOperationException(message); } } private static Type TypeNamed(string name) { Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); for (int i = 0; i < assemblies.Length; i++) { Type type = assemblies[i].GetType(name, throwOnError: false); if (type != null) { return type; } } throw new MissingMemberException("Game type not found: " + name); } private static object Singleton(string name, string field) { return TypeNamed(name).GetField(field, BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(null); } private static object Read(object target, string field) { return target?.GetType().GetField(field, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)?.GetValue(target); } private static object EnumValue(string typeName, string name) { return Enum.Parse(TypeNamed(typeName), name); } private static string SelectedSave() { return Read(Singleton("StatsManager", "instance"), "saveFileCurrent") as string; } private static bool PhotonFlag(string property) { return (bool)TypeNamed("Photon.Pun.PhotonNetwork").GetProperty(property, BindingFlags.Static | BindingFlags.Public).GetValue(null, null); } private static object Invoke(object target, string methodName, params object[] args) { if (target == null) { throw new NullReferenceException("Missing target for " + methodName); } MethodInfo? methodInfo = target.GetType().GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault((MethodInfo candidate) => candidate.Name == methodName && candidate.GetParameters().Length == args.Length && candidate.GetParameters().Select((ParameterInfo parameter, int index) => args[index] == null || parameter.ParameterType.IsInstanceOfType(args[index])).All((bool match) => match)); if (methodInfo == null) { throw new MissingMethodException(target.GetType().FullName, methodName); } return methodInfo.Invoke(target, args); } private static Exception Unwrap(Exception error) { while (error is TargetInvocationException && error.InnerException != null) { error = error.InnerException; } return error; } } internal static class LightingSelfTest { private sealed class Context { internal string Folder; internal string Report; internal readonly StringBuilder Log = new StringBuilder(); internal readonly List<Object> Owned = new List<Object>(); internal Scene Source; internal Scene Replay; internal Scene Previous; internal ReplayVisualArchive Capture; internal ReplayVisualArchive Loaded; internal ReplayVisualArchive Legacy; internal ReplayPostProcessing Post; } internal static IEnumerator Run(Plugin owner) { Context c = new Context(); IEnumerator steps = Steps(owner, c); while (true) { object obj = null; bool flag = false; Exception ex = null; try { flag = steps.MoveNext(); if (flag) { obj = steps.Current; } } catch (Exception ex2) { ex = ex2; } if (ex != null) { c.Log.AppendLine("FAIL: " + ex); Cleanup(c); if (c.Report != null) { File.WriteAllText(c.Report, c.Log.ToString()); } owner.LogFailure(ex); owner.LogInfo("LIGHTING SELFTEST FAIL report=" + c.Report); yield break; } if (!flag) { break; } yield return obj; } Cleanup(c); File.WriteAllText(c.Report, c.Log.ToString()); owner.LogInfo("LIGHTING SELFTEST PASS report=" + c.Report); } private unsafe static IEnumerator Steps(Plugin owner, Context c) { Require(Array.IndexOf(Environment.GetCommandLineArgs(), "--repo-replay-isolated") >= 0, "Lighting fixture requires isolated runtime."); Require(owner.ReplayDirectory.Replace('\\', '/').Contains("/work/test-runtime-"), "Lighting fixture refuses installed replay data."); c.Folder = Path.Combine(owner.ReplayDirectory, "lighting-" + Guid.NewGuid().ToString("N")); Directory.CreateDirectory(c.Folder); c.Report = Path.Combine(c.Folder, "lighting-selftest.txt"); Camera main = Camera.main; c.Log.AppendLine("Unity=" + Application.unityVersion + " colorSpace=" + ((object)QualitySettings.activeColorSpace/*cast due to .constrained prefix*/).ToString() + " pixelLightCount=" + QualitySettings.pixelLightCount + " nativeLightmaps=" + LightmapSettings.lightmaps.Length); Light[] componentsInChildren; if ((Object)(object)main != (Object)null) { c.Log.AppendLine("NativeCamera=" + PathOf(((Component)main).transform) + " renderingPath=" + ((object)main.renderingPath/*cast due to .constrained prefix*/).ToString() + " actual=" + ((object)main.actualRenderingPath/*cast due to .constrained prefix*/).ToString() + " HDR=" + main.allowHDR); c.Log.AppendLine("NativeCameraComponents=" + string.Join(",", from x in ((Component)main).GetComponents<Component>() where (Object)(object)x != (Object)null select ((object)x).GetType().FullName)); componentsInChildren = ((Component)main).GetComponentsInChildren<Light>(true); foreach (Light val in componentsInChildren) { c.Log.AppendLine("NativeCameraLight=" + PathOf(((Component)val).transform) + " intensity=" + val.intensity + " range=" + val.range + " renderMode=" + ((object)val.renderMode/*cast due to .constrained prefix*/).ToString() + " mask=" + val.cullingMask + " layer=" + ((Component)val).gameObject.layer); } } Camera[] array = Object.FindObjectsByType<Camera>((FindObjectsInactive)1, (FindObjectsSortMode)0); foreach (Camera val2 in array) { c.Log.AppendLine("ALL CAMERA=" + PathOf(((Component)val2).transform) + " enabled=" + ((Behaviour)val2).enabled + " active=" + ((Component)val2).gameObject.activeInHierarchy + " tag=" + ((Component)val2).tag + " mask=" + val2.cullingMask + " target=" + (((Object)(object)val2.targetTexture == (Object)null) ? "screen" : ((Object)val2.targetTexture).name) + " lights=" + ((Component)val2).GetComponentsInChildren<Light>(true).Length); foreach (Light item in from x in ((Component)val2).GetComponentsInChildren<Light>(true) where ((Object)x).name == "Main Light" || ((Object)x).name == "Bottom Light" || ((Object)x).name == "Rim Light" || ((Object)x).name == "Side Light" select x) { c.Log.AppendLine("CANDIDATE HEADLIGHT=" + PathOf(((Component)item).transform) + " enabled=" + ((Behaviour)item).enabled + " active=" + ((Component)item).gameObject.activeInHierarchy + " mode=" + ((object)item.renderMode/*cast due to .constrained prefix*/).ToString() + " ma