using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Loader; using System.Runtime.Versioning; using BoneLib; using MelonLoader; using MelonLoader.Utils; using Microsoft.CodeAnalysis; using WristHub.Universal; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: MelonInfo(typeof(WristHubUniversalMod), "WristHub", "4.4.5", "WristHub contributors", null)] [assembly: MelonGame("Stress Level Zero", "BONELAB")] [assembly: AssemblyMetadata("WristHubPlatform", "Universal")] [assembly: TargetFramework(".NETCoreApp,Version=v6.0", FrameworkDisplayName = ".NET 6.0")] [assembly: AssemblyCompany("WristHub")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("4.4.5.0")] [assembly: AssemblyInformationalVersion("4.4.5")] [assembly: AssemblyProduct("WristHub")] [assembly: AssemblyTitle("WristHub")] [assembly: AssemblyVersion("4.4.5.0")] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [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 WristHub.Universal { public sealed class WristHubUniversalMod : MelonMod { private sealed class WristHubPayloadLoadContext : AssemblyLoadContext { public WristHubPayloadLoadContext() : base("WristHub embedded runtime") { } protected override Assembly? Load(AssemblyName assemblyName) { Assembly assembly = base.Assemblies.FirstOrDefault((Assembly candidate) => AssemblyName.ReferenceMatchesDefinition(candidate.GetName(), assemblyName)); if (assembly != null) { return assembly; } return AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly candidate) => AssemblyName.ReferenceMatchesDefinition(candidate.GetName(), assemblyName)); } } private static readonly object PayloadResolverGate = new object(); private static readonly Dictionary ResolvablePlatformPayloads = new Dictionary(StringComparer.OrdinalIgnoreCase); private static bool _payloadResolverInstalled; private WristHubPayloadLoadContext _payloadLoadContext = new WristHubPayloadLoadContext(); private readonly List _platformDependencies = new List(); private object? _runtime; private Action? _update; private Action? _lateUpdate; private Action? _sceneLoaded; private Action? _deinitialize; private Type? _extensionRuntimeType; private Action? _extensionUpdate; private Action? _extensionSceneChanged; private Action? _extensionShutdown; private bool _runtimeFailed; private long _nextFrameFailureLogAt; private int _suppressedFrameFailures; private bool _isAndroid; private int? _pendingSceneBuildIndex; private string? _pendingSceneName; private static readonly string[] PackagedCommonDependencies = new string[17] { "NLayer.dll", "NVorbis.dll", "System.Runtime.CompilerServices.Unsafe.dll", "System.Diagnostics.DiagnosticSource.dll", "Microsoft.Extensions.DependencyInjection.Abstractions.dll", "Microsoft.Extensions.Logging.Abstractions.dll", "Common.Logging.Core.dll", "Common.Logging.dll", "SimpleBase.dll", "System.Net.IPNetwork.dll", "Makaretu.Dns.dll", "Makaretu.Dns.Multicast.dll", "DnsClient.dll", "Concentus.dll", "BouncyCastle.Cryptography.dll", "websocket-sharp.dll", "SIPSorceryMedia.Abstractions.dll" }; public override void OnInitializeMelon() { try { InstallPlatformPayloadResolver(); _isAndroid = HelperMethods.IsAndroid(); StartBundledRuntime(); } catch (Exception ex) { _runtimeFailed = true; ((MelonBase)this).LoggerInstance.Error("WristHub universal loader stopped safely: " + (ex.GetBaseException().Message ?? ex.Message)); } } public override void OnUpdate() { InvokeFrame(_update, "update"); InvokeExtension(_extensionUpdate, "update"); } public override void OnLateUpdate() { InvokeFrame(_lateUpdate, "late update"); } public override void OnSceneWasLoaded(int buildIndex, string sceneName) { if (!_runtimeFailed) { if (_sceneLoaded == null) { _pendingSceneBuildIndex = buildIndex; _pendingSceneName = sceneName; } else { InvokeSceneChanged(buildIndex, sceneName, "scene load"); } } } public override void OnDeinitializeMelon() { ShutdownExtension(); if (_deinitialize != null) { try { _deinitialize(); } catch (Exception ex) { ((MelonBase)this).LoggerInstance.Warning("WristHub universal runtime cleanup recovered: " + ex.GetBaseException().Message); } } _runtime = null; _update = null; _lateUpdate = null; _sceneLoaded = null; _deinitialize = null; _extensionRuntimeType = null; _pendingSceneBuildIndex = null; _pendingSceneName = null; _platformDependencies.Clear(); } private void StartBundledRuntime() { Type type = LoadPackagedRuntime(); _runtime = Activator.CreateInstance(type) ?? throw new InvalidOperationException("The bundled WristHub runtime could not be created."); (type.GetMethod("InitializeFromUniversalHost", BindingFlags.Instance | BindingFlags.Public) ?? throw new MissingMethodException(type.FullName, "InitializeFromUniversalHost")).Invoke(_runtime, new object[1] { ((MelonBase)this).LoggerInstance }); _update = Bind(type, "OnUpdate"); _lateUpdate = Bind(type, "OnLateUpdate"); _sceneLoaded = Bind>(type, "OnSceneWasLoaded"); _deinitialize = Bind(type, "OnDeinitializeMelon"); TryInitializeExtension(); ((MelonBase)this).LoggerInstance.Msg("WristHub selected the " + (_isAndroid ? "Quest" : "PCVR") + " runtime."); int? pendingSceneBuildIndex = _pendingSceneBuildIndex; if (pendingSceneBuildIndex.HasValue) { int valueOrDefault = pendingSceneBuildIndex.GetValueOrDefault(); string pendingSceneName = _pendingSceneName; if (pendingSceneName != null) { _pendingSceneBuildIndex = null; _pendingSceneName = null; InvokeSceneChanged(valueOrDefault, pendingSceneName, "deferred scene load"); } } } private static void InstallPlatformPayloadResolver() { lock (PayloadResolverGate) { if (!_payloadResolverInstalled) { AssemblyLoadContext.Default.Resolving += ResolvePlatformPayloadFromDefaultContext; AppDomain.CurrentDomain.AssemblyResolve += ResolvePlatformPayloadFromAppDomain; _payloadResolverInstalled = true; } } } private static void RetainPlatformPayload(Assembly assembly) { string name = assembly.GetName().Name; if (string.IsNullOrWhiteSpace(name) || !name.StartsWith("WristHub.Platform.", StringComparison.OrdinalIgnoreCase)) { throw new InvalidDataException("The embedded WristHub runtime has an invalid assembly identity."); } lock (PayloadResolverGate) { ResolvablePlatformPayloads[name] = assembly; } } private static void RetainExtensionPayload(Assembly assembly) { string name = assembly.GetName().Name; if (name == null || !name.Equals("WristHub.Build49.Extension", StringComparison.OrdinalIgnoreCase)) { throw new InvalidDataException("The embedded WristHub extension has an invalid assembly identity."); } lock (PayloadResolverGate) { ResolvablePlatformPayloads[name] = assembly; } } private static Assembly? ResolvePlatformPayloadFromDefaultContext(AssemblyLoadContext context, AssemblyName requested) { return ResolveRetainedPlatformPayload(requested); } private static Assembly? ResolvePlatformPayloadFromAppDomain(object? sender, ResolveEventArgs args) { try { return ResolveRetainedPlatformPayload(new AssemblyName(args.Name)); } catch { return null; } } private static Assembly? ResolveRetainedPlatformPayload(AssemblyName requested) { string name = requested.Name; if (string.IsNullOrWhiteSpace(name) || (!name.StartsWith("WristHub.Platform.", StringComparison.OrdinalIgnoreCase) && !name.Equals("WristHub.Build49.Extension", StringComparison.OrdinalIgnoreCase))) { return null; } lock (PayloadResolverGate) { if (!ResolvablePlatformPayloads.TryGetValue(name, out Assembly value)) { return null; } return AssemblyName.ReferenceMatchesDefinition(value.GetName(), requested) ? value : null; } } private Type LoadPackagedRuntime() { string path = ResolvePackagedRuntimeDirectory(); string path2 = Path.Combine(path, "common"); string text = Path.Combine(path, _isAndroid ? "quest" : "pcvr"); _platformDependencies.Add(LoadPackagedAssembly(Path.Combine(MelonEnvironment.ModsDirectory, "WristHub.Core.dll"), "WristHub.Core", 8)); string[] packagedCommonDependencies = PackagedCommonDependencies; foreach (string text2 in packagedCommonDependencies) { int maximumMegabytes = ((text2 == "BouncyCastle.Cryptography.dll") ? 8 : 4); _platformDependencies.Add(LoadPackagedAssembly(Path.Combine(path2, text2), Path.GetFileNameWithoutExtension(text2), maximumMegabytes)); } _platformDependencies.Add(LoadPackagedAssembly(Path.Combine(text, "SIPSorcery.dll"), "SIPSorcery", 8)); string text3 = (_isAndroid ? "WristHub.Platform.Quest.dll" : "WristHub.Platform.PCVR.dll"); string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(text3); Assembly assembly = LoadPackagedAssembly(Path.Combine(text, text3), fileNameWithoutExtension, 64); RetainPlatformPayload(assembly); _platformDependencies.Add(assembly); TryLoadPackagedExtension(text); return assembly.GetType("BoneHub.Mod.BoneHubMod", throwOnError: true); } private static string ResolvePackagedRuntimeDirectory() { string[] array = new string[3] { Path.Combine(MelonEnvironment.UserDataDirectory, "MrAssBurgers-WristHub", "WristHubRuntime"), Path.Combine(MelonEnvironment.UserDataDirectory, "WristHubRuntime"), Path.Combine(MelonEnvironment.GameRootDirectory, "UserData", "WristHubRuntime") }; foreach (string text in array) { if (Directory.Exists(Path.Combine(text, "common")) && Directory.Exists(Path.Combine(text, "pcvr")) && Directory.Exists(Path.Combine(text, "quest"))) { return text; } } throw new DirectoryNotFoundException("WristHub's packaged runtime folder is missing. Reinstall the complete Thunderstore package."); } private Assembly LoadPackagedAssembly(string path, string expectedName, int maximumMegabytes) { Assembly assembly = LoadAssemblyFile(path, maximumMegabytes); if (!string.Equals(assembly.GetName().Name, expectedName, StringComparison.OrdinalIgnoreCase)) { throw new InvalidDataException("The packaged WristHub component " + Path.GetFileName(path) + " has an invalid identity."); } return assembly; } private void TryLoadPackagedExtension(string platformDirectory) { _extensionRuntimeType = null; string path = Path.Combine(platformDirectory, "WristHub.Build49.Extension.dll"); if (!File.Exists(path)) { return; } try { Assembly assembly = LoadPackagedAssembly(path, "WristHub.Build49.Extension", 4); Type type = assembly.GetType("WristHub.Build49Extension.ExtensionRuntime", throwOnError: true); RetainExtensionPayload(assembly); _platformDependencies.Add(assembly); _extensionRuntimeType = type; } catch (Exception ex) { _extensionRuntimeType = null; ((MelonBase)this).LoggerInstance.Warning("WristHub skipped its optional Build 49 extension; the base runtime will continue: " + ex.GetBaseException().Message); } } private Assembly LoadAssemblyFile(string path, int maximumMegabytes) { FileInfo fileInfo = new FileInfo(path); if (!fileInfo.Exists || fileInfo.Length <= 0 || fileInfo.Length > (long)maximumMegabytes * 1024L * 1024) { throw new InvalidDataException("A staged WristHub runtime component has invalid bounds."); } using FileStream assembly = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read, 131072, FileOptions.SequentialScan); return _payloadLoadContext.LoadFromStream(assembly); } private T Bind(Type runtimeType, string methodName) where T : Delegate { if (_runtime == null) { throw new InvalidOperationException("The WristHub runtime is unavailable."); } return (T)(runtimeType.GetMethod(methodName, BindingFlags.Instance | BindingFlags.Public) ?? throw new MissingMethodException(runtimeType.FullName, methodName)).CreateDelegate(typeof(T), _runtime); } private static T BindStatic(Type runtimeType, string methodName) where T : Delegate { return (T)(runtimeType.GetMethod(methodName, BindingFlags.Static | BindingFlags.Public) ?? throw new MissingMethodException(runtimeType.FullName, methodName)).CreateDelegate(typeof(T)); } private void TryInitializeExtension() { Type extensionRuntimeType = _extensionRuntimeType; _extensionRuntimeType = null; if (extensionRuntimeType == null) { return; } try { Action action = BindStatic>(extensionRuntimeType, "Initialize"); _extensionUpdate = BindStatic(extensionRuntimeType, "OnUpdate"); _extensionSceneChanged = BindStatic>(extensionRuntimeType, "OnSceneChanged"); _extensionShutdown = BindStatic(extensionRuntimeType, "Shutdown"); action(((MelonBase)this).LoggerInstance); } catch (Exception exception) { StopExtension("initialization", exception); } } private void InvokeSceneChanged(int buildIndex, string sceneName, string stage) { try { _sceneLoaded(buildIndex, sceneName); } catch (Exception exception) { StopRuntime(stage, exception); return; } Action extensionSceneChanged = _extensionSceneChanged; if (extensionSceneChanged == null) { return; } try { extensionSceneChanged(buildIndex, sceneName); } catch (Exception exception2) { StopExtension(stage, exception2); } } private void InvokeExtension(Action? action, string stage) { if (_runtimeFailed || action == null) { return; } try { action(); } catch (Exception exception) { StopExtension(stage, exception); } } private void StopExtension(string stage, Exception exception) { Action extensionShutdown = _extensionShutdown; _extensionUpdate = null; _extensionSceneChanged = null; _extensionShutdown = null; try { extensionShutdown?.Invoke(); } catch { } ((MelonBase)this).LoggerInstance.Warning("WristHub stopped its optional Build 49 extension after a " + stage + " failure; the base runtime will continue: " + exception.GetBaseException().Message); } private void ShutdownExtension() { Action extensionShutdown = _extensionShutdown; _extensionUpdate = null; _extensionSceneChanged = null; _extensionShutdown = null; if (extensionShutdown == null) { return; } try { extensionShutdown(); } catch (Exception ex) { ((MelonBase)this).LoggerInstance.Warning("WristHub optional extension cleanup recovered; the base runtime will continue shutting down: " + ex.GetBaseException().Message); } } private void InvokeFrame(Action? action, string stage) { if (_runtimeFailed || action == null) { return; } try { action(); } catch (Exception exception) { ReportFrameFailure(stage, exception); } } private void ReportFrameFailure(string stage, Exception exception) { long tickCount = Environment.TickCount64; if (tickCount < _nextFrameFailureLogAt) { _suppressedFrameFailures++; return; } int suppressedFrameFailures = _suppressedFrameFailures; _suppressedFrameFailures = 0; _nextFrameFailureLogAt = tickCount + 5000; ((MelonBase)this).LoggerInstance.Error("WristHub universal runtime recovered after a " + stage + " failure; the watch will continue: " + exception.GetBaseException().Message + ((suppressedFrameFailures > 0) ? $" ({suppressedFrameFailures} repeated failures suppressed)" : string.Empty)); } private void StopRuntime(string stage, Exception exception) { if (!_runtimeFailed) { _runtimeFailed = true; ((MelonBase)this).LoggerInstance.Error("WristHub universal runtime stopped after a " + stage + " failure: " + exception.GetBaseException().Message); } } } }