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 MovePosters v1.0.9
plugins/bobabulkerENTERPRISE.MovePosters.dll
Decompiled 3 hours 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.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security.Cryptography; using System.Text; using System.Threading.Tasks; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using GameNetcodeStuff; using HarmonyLib; using Microsoft.CodeAnalysis; using Unity.Collections; using Unity.Netcode; using UnityEngine; using UnityEngine.InputSystem; using UnityEngine.Rendering; using UnityEngine.UI; using UnityEngine.Video; using moveposters.Patches; [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("bobabulkerENTERPRISE.MovePosters")] [assembly: AssemblyConfiguration("Thunderstore")] [assembly: AssemblyFileVersion("1.0.9.0")] [assembly: AssemblyInformationalVersion("1.0.9+3dce0938201db6bdbb2739cc7c79cdee268a2dcf")] [assembly: AssemblyProduct("moveposters")] [assembly: AssemblyTitle("bobabulkerENTERPRISE.MovePosters")] [assembly: AssemblyVersion("1.0.9.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 moveposters { internal static class PosterConfig { private const float PixelsPerUnityUnit = 1000f; private const float MinimumScale = 0.01f; private static ConfigEntry<string>[] _transform = null; private static float[] _scaleValue = null; private static Vector3[] _rotationValue = null; private static bool _suppressTransformEvents; private const float MaximumRequestedScale = 100f; private static bool _initialized; private static readonly Vector3[] _layoutRotation = (Vector3[])(object)new Vector3[4]; private static readonly bool[] _hasLayoutRotation = new bool[4]; private static readonly float[] DefaultScale = new float[4] { 1f, 1f, 1f, 1f }; private static readonly Vector3[] DefaultRotation = (Vector3[])(object)new Vector3[4] { new Vector3(0f, 118.23f, 0f), new Vector3(0f, 0f, 0f), new Vector3(0f, 180f, -3.67f), new Vector3(0f, 62.03f, 2.68f) }; internal static ConfigEntry<bool> ClientReceiveTransfer { get; private set; } = null; internal static ConfigEntry<int> TransferKBPerSecond { get; private set; } = null; internal static ConfigEntry<string> PosterBodyColor { get; private set; } = null; internal static ConfigEntry<bool> AllowPlayerChanges { get; private set; } = null; public static void Initialize(ConfigFile config) { //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Expected O, but got Unknown //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_01c7: Unknown result type (might be due to invalid IL or missing references) //IL_01fa: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Unknown result type (might be due to invalid IL or missing references) if (_initialized) { return; } _transform = new ConfigEntry<string>[4]; _scaleValue = new float[4]; _rotationValue = (Vector3[])(object)new Vector3[4]; ClientReceiveTransfer = config.Bind<bool>("Content Transfer", "ClientReceiveTransfer", true, "Not the host: receive the host's poster images and videos so everyone sees the same posters. Rejoin after changing it."); TransferKBPerSecond = config.Bind<int>("Content Transfer", "TransferKBPerSecond", 10240, new ConfigDescription("Host only: the speed in KB/s that poster files are sent at, shared by all downloaders (lower it if the game lags during a download).", (AcceptableValueBase)(object)new AcceptableValueRange<int>(32, 32768), Array.Empty<object>())); PosterBodyColor = config.Bind<string>("Poster Body", "Color", "#FF1494", "The colour (a hex code such as #FF1494) of the poster's back and edges."); PosterBodyColor.SettingChanged += delegate { PosterBody.ApplyColor(); }; AllowPlayerChanges = config.Bind<bool>("Poster Transform", "AllowPlayerChanges", false, "Host only: let other players change a poster's scale and rotation (a change is saved in your config). Off keeps the posters yours alone."); for (int num = 0; num < 4; num++) { int num2 = num + 1; int capturedIndex = num; string text = "Poster Transform"; string text2 = $"Poster{num2} Transform"; string text3 = ((ReadSettingFromFile(config, text, text2) != null) ? null : MigrateOldTransform(config, num2, num)); _transform[num] = config.Bind<string>(text, text2, FormatTransform(DefaultScale[num], DefaultRotation[num]), $"Poster {num2}'s scale and rotation as \"s, x, y, z\" (the scale, then the x, y and z rotation in degrees), applied immediately for everyone in the lobby."); if (text3 != null) { _transform[num].Value = text3; } if (!TryParseTransform(_transform[num].Value, out _scaleValue[num], out _rotationValue[num])) { Plugin.LogWarning($"Poster {num2} transform \"{_transform[num].Value}\" is not \"s, x, y, z\"; " + "using " + FormatTransform(DefaultScale[num], DefaultRotation[num]) + "."); _scaleValue[num] = DefaultScale[num]; _rotationValue[num] = DefaultRotation[num]; } _transform[num].SettingChanged += delegate { OnTransformChanged(capturedIndex); }; } _initialized = true; for (int num3 = 0; num3 < 4; num3++) { } } private static void OnTransformChanged(int index) { //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: 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_0056: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) if (!_initialized || _suppressTransformEvents) { return; } if (!TryParseTransform(_transform[index].Value, out var scale, out var rotation)) { Plugin.LogWarning($"Poster {index + 1} transform \"{_transform[index].Value}\" is not \"s, x, y, z\" " + "(four numbers: the scale, then the rotation in degrees); keeping " + FormatTransform(_scaleValue[index], _rotationValue[index]) + "."); return; } bool flag = !Mathf.Approximately(scale, _scaleValue[index]); Vector3 val = rotation - _rotationValue[index]; bool flag2 = ((Vector3)(ref val)).sqrMagnitude > 1E-06f; _scaleValue[index] = scale; _rotationValue[index] = rotation; if (PosterNet.IsRemoteClient) { PosterNet.ClientSendTransform(index, scale, rotation); return; } if (flag) { PosterFeature.ApplyConfigToShell(index); } if (flag2) { PosterFeature.ApplyRotationToShell(index); } } internal static void ApplyTransformFromPlayer(int index, float scale, Vector3 rotation) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004d: 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_0067: 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_009b: 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_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) if (!_initialized || index < 0 || index >= 4) { return; } if (!AllowPlayerChanges.Value) { PosterFeature.PublishSlotState(index); } else if (!float.IsNaN(scale) && !float.IsInfinity(scale) && !float.IsNaN(rotation.x) && !float.IsNaN(rotation.y) && !float.IsNaN(rotation.z) && !float.IsInfinity(rotation.x) && !float.IsInfinity(rotation.y) && !float.IsInfinity(rotation.z)) { scale = Mathf.Clamp(scale, 0.01f, 100f); Vector3 val = default(Vector3); ((Vector3)(ref val))..ctor(Mathf.DeltaAngle(0f, rotation.x), Mathf.DeltaAngle(0f, rotation.y), Mathf.DeltaAngle(0f, rotation.z)); bool flag = !Mathf.Approximately(scale, _scaleValue[index]); Vector3 val2 = val - _rotationValue[index]; bool num = ((Vector3)(ref val2)).sqrMagnitude > 1E-06f; SetTransformSilently(index, scale, val); if (flag) { PosterFeature.ApplyConfigToShell(index); } if (num) { PosterFeature.ApplyRotationToShell(index); } } } internal static void UseLayoutRotationIfDefault(int index, Vector3 layoutEuler) { //IL_001b: 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_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) if (!_initialized || index < 0 || index >= 4) { return; } _layoutRotation[index] = new Vector3(Mathf.DeltaAngle(0f, layoutEuler.x), Mathf.DeltaAngle(0f, layoutEuler.y), Mathf.DeltaAngle(0f, layoutEuler.z)); _hasLayoutRotation[index] = true; if (!(_transform[index].Value != FormatTransform(DefaultScale[index], DefaultRotation[index]))) { Vector3 val = _layoutRotation[index] - _rotationValue[index]; if (!(((Vector3)(ref val)).sqrMagnitude <= 0.0001f)) { _rotationValue[index] = _layoutRotation[index]; } } } internal static void RestoreTransformsFromConfig() { //IL_004d: 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_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) if (!_initialized) { return; } for (int i = 0; i < 4; i++) { _hasLayoutRotation[i] = false; if (!TryParseTransform(_transform[i].Value, out var scale, out var rotation)) { scale = DefaultScale[i]; rotation = DefaultRotation[i]; } _scaleValue[i] = scale; _rotationValue[i] = rotation; } } internal static void SetRotationSilently(int index, Vector3 eulerAngles) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (_initialized && index >= 0 && index < 4) { SetTransformSilently(index, _scaleValue[index], eulerAngles); } } internal static void SetTransformSilently(int index, float scale, Vector3 eulerAngles) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) if (!_initialized || index < 0 || index >= 4) { return; } Vector3 val = default(Vector3); ((Vector3)(ref val))..ctor(Mathf.DeltaAngle(0f, eulerAngles.x), Mathf.DeltaAngle(0f, eulerAngles.y), Mathf.DeltaAngle(0f, eulerAngles.z)); if (PosterNet.IsRemoteClient) { _scaleValue[index] = scale; _rotationValue[index] = val; return; } string text = FormatTransform(scale, val); if (_transform[index].Value == text) { _scaleValue[index] = scale; _rotationValue[index] = val; return; } _suppressTransformEvents = true; try { _transform[index].Value = text; _scaleValue[index] = scale; _rotationValue[index] = val; } finally { _suppressTransformEvents = false; } } internal static string FormatRotation(Vector3 rotation) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) return FormatAngle(rotation.x) + ", " + FormatAngle(rotation.y) + ", " + FormatAngle(rotation.z); } private static string FormatAngle(float degrees) { float num = Mathf.Round(Mathf.DeltaAngle(0f, degrees) * 100f) / 100f; if (num == 0f) { num = 0f; } return num.ToString("0.##", CultureInfo.InvariantCulture); } internal static string FormatTransform(float scale, Vector3 rotation) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) return scale.ToString("0.###", CultureInfo.InvariantCulture) + ", " + FormatRotation(rotation); } internal static bool TryParseTransform(string? text, out float scale, out Vector3 rotation) { //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) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) scale = 1f; rotation = Vector3.zero; if (string.IsNullOrWhiteSpace(text)) { return false; } string[] array = text.Trim().Trim('(', ')', '[', ']').Split(new char[4] { ',', ';', ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); if (array.Length != 4) { return false; } float[] array2 = new float[4]; for (int i = 0; i < 4; i++) { if (!float.TryParse(array[i], NumberStyles.Float, CultureInfo.InvariantCulture, out array2[i]) || float.IsNaN(array2[i]) || float.IsInfinity(array2[i])) { return false; } } if (array2[0] <= 0f) { return false; } scale = array2[0]; rotation = new Vector3(array2[1], array2[2], array2[3]); return true; } private static string? ReadSettingFromFile(ConfigFile config, string section, string key) { try { string configFilePath = config.ConfigFilePath; if (!File.Exists(configFilePath)) { return null; } string text = string.Empty; foreach (string item in File.ReadLines(configFilePath)) { string text2 = item.Trim(); if (text2.Length == 0 || text2.StartsWith("#")) { continue; } if (text2.StartsWith("[") && text2.EndsWith("]")) { text = text2.Substring(1, text2.Length - 2).Trim(); } else if (!(text != section)) { int num = text2.IndexOf('='); if (num > 0 && text2.Substring(0, num).Trim() == key) { return text2.Substring(num + 1).Trim(); } } } } catch (Exception) { } return null; } private static string? MigrateOldTransform(ConfigFile config, int posterNumber, int index) { //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_010d: Unknown result type (might be due to invalid IL or missing references) float scale = DefaultScale[index]; Vector3 rotation = DefaultRotation[index]; bool flag = false; string text = ReadSettingFromFile(config, "Poster Scaling", $"Poster{posterNumber} Scale"); if (text != null && float.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out var result) && result > 0f) { scale = result; flag = true; } string text2 = ReadSettingFromFile(config, "Poster Rotation", $"Poster{posterNumber} Rotation"); if (text2 != null) { string[] array = text2.Trim('(', ')', '[', ']', ' ').Split(new char[4] { ',', ';', ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries); if (array.Length == 3 && float.TryParse(array[0], NumberStyles.Float, CultureInfo.InvariantCulture, out var result2) && float.TryParse(array[1], NumberStyles.Float, CultureInfo.InvariantCulture, out var result3) && float.TryParse(array[2], NumberStyles.Float, CultureInfo.InvariantCulture, out var result4)) { ((Vector3)(ref rotation))..ctor(result2, result3, result4); flag = true; } } if (!flag) { return null; } return FormatTransform(scale, rotation); } public static float GetScale(int index) { if (index < 0 || index >= 4) { return 1f; } if (PosterFeature.TryGetHostScale(index, out var scale)) { return Mathf.Max(0.01f, scale); } return Mathf.Max(0.01f, _scaleValue[index]); } public static float PixelsToUnity(int pixels) { return (float)pixels / 1000f; } public static Vector2 PixelsToUnity(int widthPixels, int heightPixels) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) return new Vector2(PixelsToUnity(widthPixels), PixelsToUnity(heightPixels)); } public static Vector2 GetPhysicalSize(int index, int sourceWidthPixels, int sourceHeightPixels, Vector2 fallback) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0016: 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) if (index < 0 || index >= 4) { return fallback; } if (sourceWidthPixels <= 0 || sourceHeightPixels <= 0) { return fallback; } return PixelsToUnity(sourceWidthPixels, sourceHeightPixels) * GetScale(index); } public static Vector3 GetShellSize(int index, int sourceWidthPixels, int sourceHeightPixels, Vector3 fallback) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: 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_0043: Unknown result type (might be due to invalid IL or missing references) Vector2 fallback2 = default(Vector2); ((Vector2)(ref fallback2))..ctor(fallback.x, fallback.y); Vector2 physicalSize = GetPhysicalSize(index, sourceWidthPixels, sourceHeightPixels, fallback2); return new Vector3(physicalSize.x, physicalSize.y, (fallback.z > 0f) ? fallback.z : 0.01f); } public static Vector3 GetShellVisualScale(int index, int sourceWidthPixels, int sourceHeightPixels, Vector3 meshBoundsSize) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0020: 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_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_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0060: 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_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || index >= 4) { return Vector3.one; } Vector2 fallback = default(Vector2); ((Vector2)(ref fallback))..ctor(Mathf.Max(meshBoundsSize.x, 0.0001f), Mathf.Max(meshBoundsSize.y, 0.0001f)); Vector2 physicalSize = GetPhysicalSize(index, sourceWidthPixels, sourceHeightPixels, fallback); float num = ((meshBoundsSize.x > 0.0001f) ? (physicalSize.x / meshBoundsSize.x) : 1f); float num2 = ((meshBoundsSize.y > 0.0001f) ? (physicalSize.y / meshBoundsSize.y) : 1f); return new Vector3(num, num2, 1f); } public static float GetTiltX(int index) { if (index < 0 || index >= 4) { return 0f; } if (PosterFeature.TryGetHostTilt(index, out var tiltX, out var _)) { return tiltX; } return _rotationValue[index].x; } public static float GetTiltZ(int index) { if (index < 0 || index >= 4) { return 0f; } if (PosterFeature.TryGetHostTilt(index, out var _, out var tiltZ)) { return tiltZ; } return _rotationValue[index].z; } public static float GetRotationY(int index) { if (index < 0 || index >= 4) { return 0f; } return _rotationValue[index].y; } } internal static class PosterContent { private sealed class CachedHash { public long Length; public long Ticks; public byte[] Hash = Array.Empty<byte>(); } private sealed class Job { public Task Task; public Action OnDone; } private sealed class HostItem { public ulong Key; public string Name = ""; public GameObject? Poster; public string Path = ""; public long Size; public byte Ext; public int Width; public int Height; public byte[]? Hash; public bool Failed; } private sealed class Target { public string Name = ""; public ulong Key; public GameObject? Poster; public string? Path; public bool IsVideo; public byte[]? Hash; public bool IsPlaceholder; public bool VideoOff; public float PlaceholderSince; public bool Busy; public bool Dirty; public PosterProgressCanvas? Canvas; public string? RestorePath; public bool RestoreIsVideo; } private const float PlaceholderTimeoutSeconds = 20f; private const string BaseColorMapProperty = "_BaseColorMap"; private const float VideoReadyTimeoutSeconds = 15f; private const float FailedRetrySeconds = 60f; private static Type? _rendererType; private static MethodInfo? _rendererInit; private static FieldInfo? _createdPostersField; private const long FreeSpaceHeadroomBytes = 268435456L; private static readonly Dictionary<string, PosterProgressCanvas> VideoOffCanvases = new Dictionary<string, PosterProgressCanvas>(); private static readonly HashSet<string> LoggedVideoOff = new HashSet<string>(); private static bool _loggedOptOut; private static readonly ConcurrentDictionary<string, CachedHash> HashCache = new ConcurrentDictionary<string, CachedHash>(StringComparer.OrdinalIgnoreCase); private static readonly List<Job> Jobs = new List<Job>(); private static readonly HashSet<string> LocalFiles = new HashSet<string>(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary<ulong, HostItem> HostItems = new Dictionary<ulong, HostItem>(); private static readonly Dictionary<string, (string path, long size, byte ext)> HostFiles = new Dictionary<string, (string, long, byte)>(); private static bool _hostDirty; private static readonly Dictionary<ulong, Target> Targets = new Dictionary<ulong, Target>(); private static readonly HashSet<int> VideoOffPosters = new HashSet<int>(); private static readonly Dictionary<ulong, PosterContentEntry> Manifest = new Dictionary<ulong, PosterContentEntry>(); private static bool _manifestReceived; private static bool _manifestComplete; private static readonly List<PosterContentEntry> DownloadQueue = new List<PosterContentEntry>(); private static readonly Dictionary<string, float> FailedUntil = new Dictionary<string, float>(); private static bool _downloading; private static string _activeHex = ""; private static readonly Color32 PlaceholderColor = new Color32(byte.MaxValue, (byte)0, (byte)144, byte.MaxValue); private static Texture2D? _placeholder; private const int CacheKeepDays = 30; private static int _lastPercent = -1; private static bool CanSwapContent { get { if (_rendererType != null) { return _rendererInit != null; } return false; } } internal static string CacheDir { get; } = ResolveCacheDir(); private static string LegacyCacheDir => Path.Combine(Paths.CachePath, "MovePosters"); internal static void Initialize(Type? posterManagerType, Type? rendererType) { _rendererType = rendererType; _rendererInit = ((rendererType != null) ? AccessTools.Method(rendererType, "Initialize", (Type[])null, (Type[])null) : null); _createdPostersField = ((posterManagerType != null) ? AccessTools.Field(posterManagerType, "CreatedPosters") : null); Task.Run((Action)MaintainCache); } private static string ResolveCacheDir() { string text = null; try { text = Path.GetDirectoryName(typeof(PosterContent).Assembly.Location); } catch (Exception) { } if (string.IsNullOrEmpty(text)) { text = Paths.PluginPath; } return Path.Combine(text, "transferred"); } private static void MaintainCache() { try { string cacheDir = CacheDir; string[] files; if (Directory.Exists(cacheDir)) { files = Directory.GetFiles(cacheDir, "*.part"); foreach (string path in files) { if (DateTime.UtcNow - File.GetLastWriteTimeUtc(path) > TimeSpan.FromDays(7.0)) { TryDelete(path); } } files = Directory.GetFiles(cacheDir); foreach (string text in files) { if (!text.EndsWith(".part", StringComparison.OrdinalIgnoreCase) && IsDownloadName(Path.GetFileNameWithoutExtension(text)) && DateTime.UtcNow - File.GetLastWriteTimeUtc(text) > TimeSpan.FromDays(30.0)) { TryDelete(text); } } } string legacyCacheDir = LegacyCacheDir; if (!Directory.Exists(legacyCacheDir)) { return; } Directory.CreateDirectory(cacheDir); int num = 0; files = Directory.GetFiles(legacyCacheDir); foreach (string text2 in files) { if (text2.EndsWith(".part", StringComparison.OrdinalIgnoreCase)) { TryDelete(text2); continue; } string text3 = Path.Combine(cacheDir, Path.GetFileName(text2)); if (File.Exists(text3)) { TryDelete(text2); continue; } try { File.Move(text2, text3); } catch (IOException) { File.Copy(text2, text3); TryDelete(text2); } num++; } try { Directory.Delete(legacyCacheDir, recursive: false); } catch (Exception) { } _ = 0; } catch (Exception ex3) { Plugin.LogWarning("Poster cache maintenance failed: " + ex3.Message); } } private static void TryDelete(string path) { try { File.Delete(path); } catch (Exception) { } } internal static bool HasRoomFor(long size, out string message) { message = ""; string cacheDir = CacheDir; long free; try { Directory.CreateDirectory(cacheDir); if (!TryGetFreeSpace(cacheDir, out free)) { message = "cannot read the free disk space for " + cacheDir; return false; } } catch (Exception ex) { message = "cannot use the cache folder " + cacheDir + ": " + ex.Message; return false; } if (free < size + 268435456) { message = $"not enough free disk space for a {size / 1048576} MB file " + $"(keeping {256L} MB spare): {free / 1048576} MB free for {cacheDir}"; return false; } return true; } private static bool TryGetFreeSpace(string folder, out long free) { free = 0L; try { string pathRoot = Path.GetPathRoot(Path.GetFullPath(folder)); if (!string.IsNullOrEmpty(pathRoot)) { free = new DriveInfo(pathRoot).AvailableFreeSpace; return true; } } catch (Exception) { } try { if (GetDiskFreeSpaceEx(folder, out var lpFreeBytesAvailable, out var _, out var _)) { free = (long)Math.Min(lpFreeBytesAvailable, 9223372036854775807uL); return true; } } catch (Exception) { } return false; } [DllImport("kernel32.dll", CharSet = CharSet.Unicode, EntryPoint = "GetDiskFreeSpaceExW", SetLastError = true)] private static extern bool GetDiskFreeSpaceEx(string lpDirectoryName, out ulong lpFreeBytesAvailable, out ulong lpTotalNumberOfBytes, out ulong lpTotalNumberOfFreeBytes); internal static ulong NameKey(string name) { ulong num = 14695981039346656037uL; string text = name.ToLowerInvariant(); foreach (char c in text) { num ^= c; num *= 1099511628211L; } return num; } internal static byte ExtToByte(string ext) { return ext.ToLowerInvariant() switch { ".png" => 1, ".jpg" => 2, ".jpeg" => 3, ".bmp" => 4, ".mp4" => 5, _ => 0, }; } internal static string ByteToExt(byte b) { return b switch { 1 => ".png", 2 => ".jpg", 3 => ".jpeg", 4 => ".bmp", 5 => ".mp4", _ => ".bin", }; } private static bool IsVideoExt(byte b) { return b == 5; } internal static bool IsSizeAllowed(byte ext, long size) { if (ext != 0) { return size > 0; } return false; } private static byte[] HashFile(string path) { FileInfo fileInfo = new FileInfo(path); long length = fileInfo.Length; long ticks = fileInfo.LastWriteTimeUtc.Ticks; if (HashCache.TryGetValue(path, out CachedHash value) && value.Length == length && value.Ticks == ticks) { return value.Hash; } using FileStream inputStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); using SHA256 sHA = SHA256.Create(); byte[] array = sHA.ComputeHash(inputStream); HashCache[path] = new CachedHash { Length = length, Ticks = ticks, Hash = array }; return array; } private static bool TryGetContent(Dictionary<string, (Texture2D? texture, string filePath, bool isVideo)> content, string posterName, out (Texture2D? texture, string filePath, bool isVideo) value) { if (content.TryGetValue(posterName.ToLower(), out value)) { return true; } foreach (KeyValuePair<string, (Texture2D, string, bool)> item in content) { if (string.Equals(item.Key, posterName, StringComparison.OrdinalIgnoreCase)) { value = item.Value; return true; } } value = default((Texture2D, string, bool)); return false; } private static void Enqueue<T>(Task<T> task, Action<Task<T>> done) { Jobs.Add(new Job { Task = task, OnDone = delegate { done(task); } }); } internal static void AfterGather(List<string> __result) { if (__result == null) { return; } foreach (string item in __result) { LocalFiles.Add(item); } } internal static bool HostTryGetFile(string hex, out string path, out long size, out byte ext) { if (HostFiles.TryGetValue(hex, out (string, long, byte) value) && File.Exists(value.Item1)) { (path, size, ext) = value; return true; } path = ""; size = 0L; ext = 0; return false; } private static void HostRegister(string posterName, GameObject poster, string path, Texture2D? texture) { byte b = ExtToByte(Path.GetExtension(path)); if (b == 0 || !File.Exists(path)) { HostItems.Remove(NameKey(posterName)); _hostDirty = true; return; } int width = (((Object)(object)texture != (Object)null) ? ((Texture)texture).width : 0); int height = (((Object)(object)texture != (Object)null) ? ((Texture)texture).height : 0); if (IsVideoExt(b) && PosterVideoHeader.TryReadSize(path, out var width2, out var height2)) { width = width2; height = height2; } HostItem item = new HostItem { Key = NameKey(posterName), Name = posterName, Poster = poster, Path = path, Size = new FileInfo(path).Length, Ext = b, Width = width, Height = height }; HostItems[item.Key] = item; _hostDirty = true; Enqueue(Task.Run(() => HashFile(path)), delegate(Task<byte[]> task) { if (task.IsFaulted) { item.Failed = true; Plugin.LogWarning("Could not hash " + posterName + "'s file: " + task.Exception?.GetBaseException().Message); } else { item.Hash = task.Result; } _hostDirty = true; }); } private static void TickHost() { if (!_hostDirty) { return; } List<ulong> list = null; foreach (KeyValuePair<ulong, HostItem> hostItem in HostItems) { if ((Object)(object)hostItem.Value.Poster == (Object)null) { (list ?? (list = new List<ulong>())).Add(hostItem.Key); } } if (list != null) { foreach (ulong item in list) { HostItems.Remove(item); } } foreach (HostItem value in HostItems.Values) { if (value.Hash == null && !value.Failed) { return; } } List<PosterContentEntry> list2 = new List<PosterContentEntry>(); HostFiles.Clear(); foreach (HostItem value2 in HostItems.Values) { if (value2.Hash != null) { list2.Add(new PosterContentEntry { NameKey = value2.Key, Hash = value2.Hash, Size = value2.Size, Ext = value2.Ext, Width = value2.Width, Height = value2.Height }); HostFiles[PosterNet.ToHex(value2.Hash)] = (value2.Path, value2.Size, value2.Ext); } } _hostDirty = false; PosterNet.HostSetManifest(list2, complete: true); } internal static void SetLocalVideoOff(GameObject poster, bool off) { if (!((Object)(object)poster == (Object)null)) { if (off) { VideoOffPosters.Add(((Object)poster).GetInstanceID()); } else { VideoOffPosters.Remove(((Object)poster).GetInstanceID()); } } } internal static StandinKind GetLocalStandin(int index, out byte percent) { percent = 0; GameObject poster = PosterFeature.GetPoster(index); if ((Object)(object)poster == (Object)null) { return StandinKind.Ready; } if (VideoOffPosters.Contains(((Object)poster).GetInstanceID())) { return StandinKind.VideoOff; } if (!Targets.TryGetValue(NameKey("Poster" + (index + 1)), out Target value)) { return StandinKind.Ready; } if (value.VideoOff) { return StandinKind.VideoOff; } if (!value.IsPlaceholder) { return StandinKind.Ready; } PosterProgressCanvas canvas = value.Canvas; if (canvas == null) { return StandinKind.Waiting; } if (canvas.Kind == StandinKind.Downloading) { percent = (byte)Mathf.Clamp(canvas.Percent, 0, 100); } return canvas.Kind; } internal static void ResetSession() { foreach (Target value in Targets.Values) { value.Canvas?.Dispose(); value.Canvas = null; } _lastPercent = -1; PosterProgressCanvas.ClearCache(); Manifest.Clear(); DownloadQueue.Clear(); FailedUntil.Clear(); _manifestReceived = false; _manifestComplete = false; _downloading = false; _activeHex = ""; if (HostItems.Count > 0) { _hostDirty = true; } } private static Texture2D GetPlaceholder() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_placeholder != (Object)null) { return _placeholder; } Texture2D val = new Texture2D(64, 64, (TextureFormat)4, false); Color32[] array = (Color32[])(object)new Color32[4096]; for (int i = 0; i < array.Length; i++) { array[i] = PlaceholderColor; } val.SetPixels32(array); val.Apply(); ((Texture)val).filterMode = (FilterMode)0; ((Object)val).name = "MovePosters.ProgressPlaceholder"; _placeholder = val; return val; } private static bool IsDownloadName(string name) { if (name.Length != 64) { return false; } foreach (char c in name) { if ((c < '0' || c > '9') && (c < 'a' || c > 'f') && (c < 'A' || c > 'F')) { return false; } } return true; } private static string CachePathFor(PosterContentEntry e) { return Path.Combine(CacheDir, e.HashHex + ByteToExt(e.Ext)); } private static bool CachedFileValid(PosterContentEntry e, out string path) { path = CachePathFor(e); try { if (!File.Exists(path) || new FileInfo(path).Length != e.Size) { return false; } TouchCachedFile(path); return true; } catch { return false; } } private static void TouchCachedFile(string path) { try { if (DateTime.UtcNow - File.GetLastWriteTimeUtc(path) > TimeSpan.FromDays(1.0)) { File.SetLastWriteTimeUtc(path, DateTime.UtcNow); } } catch (Exception) { } } internal static bool BeforeAssign(GameObject poster, string posterName, Dictionary<string, (Texture2D? texture, string filePath, bool isVideo)> prioritizedContent, ref bool __result) { try { if ((Object)(object)poster == (Object)null || !CanSwapContent) { return true; } ulong key = NameKey(posterName); if (!PosterNet.IsRemoteClient) { return true; } if (!PosterConfig.ClientReceiveTransfer.Value) { return true; } (Texture2D, string, bool) value; bool flag = TryGetContent(prioritizedContent, posterName, out value); if (Manifest.TryGetValue(key, out PosterContentEntry value2)) { if (IsVideoBlocked(value2)) { if (TryOverrideAssign(poster, posterName, key, null, value2, placeholder: true)) { MarkVideoOff(key); __result = true; return false; } return true; } if (CachedFileValid(value2, out string path) && TryOverrideAssign(poster, posterName, key, path, value2, placeholder: false)) { __result = true; return false; } (Texture2D, string, bool) value3; if (!flag) { if (TryOverrideAssign(poster, posterName, key, null, value2, placeholder: true)) { __result = true; return false; } } else if (CanDownload(value2) && TryGetContent(prioritizedContent, posterName, out value3) && LocalDiffersFromHost(value3.Item2, value2) && TryOverrideAssign(poster, posterName, key, null, value2, placeholder: true, value3.Item2, value3.Item3)) { __result = true; return false; } return true; } if (!flag && !_manifestReceived && TryOverrideAssign(poster, posterName, key, null, null, placeholder: true)) { __result = true; return false; } } catch (Exception ex) { Plugin.LogWarning("PosterContent.BeforeAssign failed for '" + posterName + "': " + ex.Message); } return true; } internal static bool IsVideoOverMyLimit(int width, int height, bool sizeKnown) { int maxVideoResolution = PosterEffects.MaxVideoResolution; if (maxVideoResolution <= 0) { return true; } if (sizeKnown && width > 0 && height > 0) { return Math.Min(width, height) > maxVideoResolution; } return false; } private static bool IsVideoBlocked(PosterContentEntry entry) { if (IsVideoExt(entry.Ext)) { return IsVideoOverMyLimit(entry.Width, entry.Height, entry.Width > 0 && entry.Height > 0); } return false; } internal static bool TryBlockVideo(GameObject poster, string videoPath, out Texture2D? standIn) { standIn = null; int width; int height; bool flag = PosterVideoHeader.TryReadSize(videoPath, out width, out height); if (!IsVideoOverMyLimit(width, height, flag)) { return false; } if (!flag) { width = 1920; height = 1080; } int maxVideoResolution = PosterEffects.MaxVideoResolution; string text = videoPath + "|" + width + "x" + height; if (!VideoOffCanvases.TryGetValue(text, out PosterProgressCanvas value) || value == null) { value = new PosterProgressCanvas(width, height); value.SetVideoOff(); VideoOffCanvases[text] = value; } PosterFeature.SetSourceDimensions(poster, width, height); LoggedVideoOff.Add(text + "|" + maxVideoResolution); standIn = value.Texture; return true; } private static void MarkVideoOff(ulong key) { if (Targets.TryGetValue(key, out Target value)) { value.VideoOff = true; value.Canvas?.SetVideoOff(); } } private static void ShowVideoOff(Target t, PosterContentEntry entry) { if (!((Object)(object)t.Poster == (Object)null) && !t.VideoOff && t.IsPlaceholder && t.Canvas != null) { t.VideoOff = true; t.RestorePath = null; if (entry.Width > 0 && entry.Height > 0) { t.Canvas.SetPosterSize(entry.Width, entry.Height); } t.Canvas.SetVideoOff(); } } private static bool TryOverrideAssign(GameObject poster, string posterName, ulong key, string? path, PosterContentEntry? entry, bool placeholder, string? restorePath = null, bool restoreIsVideo = false) { Texture2D val = null; string text = null; bool flag = false; PosterProgressCanvas posterProgressCanvas = null; int width = 0; int height = 0; if (placeholder) { ResolvePlaceholderSize(poster, entry, out width, out height); posterProgressCanvas = new PosterProgressCanvas(width, height); val = posterProgressCanvas.Texture; if (entry != null && _downloading && _activeHex == entry.HashHex && _lastPercent >= 0) { posterProgressCanvas.SetPercent(_lastPercent); } } else { flag = IsVideoExt(ExtToByte(Path.GetExtension(path))); if (flag) { text = path; } else { val = LoadTextureBlocking(path); if ((Object)(object)val == (Object)null) { return false; } } } MeshRenderer component = poster.GetComponent<MeshRenderer>(); Material val2 = (((Object)(object)component != (Object)null) ? ((Renderer)component).material : null); Component val3 = null; try { val3 = poster.AddComponent(_rendererType); _rendererInit.Invoke(val3, new object[3] { val, text, val2 }); } catch (Exception ex) { Plugin.LogWarning("'" + posterName + "': could not apply override content (" + ex.GetBaseException().Message + "); falling back to CustomPosters' own behaviour."); posterProgressCanvas?.Dispose(); if ((Object)(object)val3 != (Object)null) { Object.DestroyImmediate((Object)(object)val3); } VideoPlayer[] components = poster.GetComponents<VideoPlayer>(); for (int i = 0; i < components.Length; i++) { Object.DestroyImmediate((Object)(object)components[i]); } AudioSource[] components2 = poster.GetComponents<AudioSource>(); for (int i = 0; i < components2.Length; i++) { Object.DestroyImmediate((Object)(object)components2[i]); } return false; } (_createdPostersField?.GetValue(null) as List<GameObject>)?.Add(poster); Target value = new Target { Name = posterName, Key = key, Poster = poster, Path = (placeholder ? null : path), IsVideo = flag, Hash = (placeholder ? null : entry?.Hash), IsPlaceholder = placeholder, PlaceholderSince = Time.unscaledTime, Canvas = posterProgressCanvas, RestorePath = (placeholder ? restorePath : null), RestoreIsVideo = restoreIsVideo }; if (Targets.TryGetValue(key, out Target value2) && value2.Canvas != null) { value2.Canvas.Dispose(); } Targets[key] = value; if (placeholder) { PosterFeature.SetSourceDimensions(poster, (width > 0) ? width : 512, (height > 0) ? height : 512); } RefreshShellVisual(poster); if (placeholder && entry != null) { Reconcile(key); } return true; } private static bool LocalDiffersFromHost(string? path, PosterContentEntry host) { try { return !string.IsNullOrEmpty(path) && File.Exists(path) && new FileInfo(path).Length != host.Size; } catch (Exception) { return false; } } private static void RefreshShellVisual(GameObject poster) { int posterIndex = PosterFeature.GetPosterIndex(poster); if (posterIndex >= 0) { PosterFeature.RefreshShellVisualMaterial(posterIndex); } } private static Texture2D? LoadTextureBlocking(string path) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected O, but got Unknown try { Texture2D val = new Texture2D(2, 2); if (!ImageConversion.LoadImage(val, File.ReadAllBytes(path))) { Object.Destroy((Object)(object)val); return null; } ((Texture)val).filterMode = (FilterMode)0; return val; } catch (Exception ex) { Plugin.LogWarning("Could not load cached image " + path + ": " + ex.Message); return null; } } internal static void AfterAssign(GameObject poster, string posterName, Dictionary<string, (Texture2D? texture, string filePath, bool isVideo)> prioritizedContent, bool __result) { try { ulong key = NameKey(posterName); if (!__result) { if (Targets.TryGetValue(key, out Target value)) { value.Canvas?.Dispose(); } Targets.Remove(key); HostItems.Remove(key); _hostDirty = true; } else { if (!TryGetContent(prioritizedContent, posterName, out (Texture2D, string, bool) value2)) { return; } Target value3; if (PosterNet.IsHost) { HostRegister(posterName, poster, value2.Item2, value2.Item1); RefreshShellVisual(poster); } else if (!Targets.TryGetValue(key, out value3) || !((Object)(object)value3.Poster == (Object)(object)poster)) { Targets[key] = new Target { Name = posterName, Key = key, Poster = poster, Path = value2.Item2, IsVideo = value2.Item3 }; RefreshShellVisual(poster); if (Manifest.ContainsKey(key)) { Reconcile(key); } } } } catch (Exception ex) { Plugin.LogWarning("PosterContent.AfterAssign failed for '" + posterName + "': " + ex.Message); } } internal static void ClientOnManifest(List<PosterContentEntry> entries, bool complete) { Manifest.Clear(); foreach (PosterContentEntry entry in entries) { Manifest[entry.NameKey] = entry; } _manifestReceived = true; _manifestComplete = complete; if (!PosterConfig.ClientReceiveTransfer.Value && entries.Count > 0 && !_loggedOptOut) { _loggedOptOut = true; } foreach (ulong item in new List<ulong>(Targets.Keys)) { if (Targets.TryGetValue(item, out Target value)) { if (Manifest.ContainsKey(item)) { Reconcile(item); } else if (value.IsPlaceholder && complete) { DestroyPlaceholder(value, "the host has no content for this poster"); } } } } private static void DestroyPlaceholder(Target t, string why) { if (t.RestorePath != null && (Object)(object)t.Poster != (Object)null && File.Exists(t.RestorePath)) { t.Canvas?.Dispose(); t.Canvas = null; t.Path = t.RestorePath; t.IsVideo = t.RestoreIsVideo; t.RestorePath = null; t.Hash = null; t.IsPlaceholder = false; RestorePrevious(t); } else { t.Canvas?.Dispose(); t.Canvas = null; if ((Object)(object)t.Poster != (Object)null) { Object.Destroy((Object)(object)t.Poster); } Targets.Remove(t.Key); } } private static void Reconcile(ulong key) { if (!Manifest.TryGetValue(key, out PosterContentEntry wanted) || !Targets.TryGetValue(key, out Target t) || (Object)(object)t.Poster == (Object)null || !PosterConfig.ClientReceiveTransfer.Value) { return; } if (IsVideoBlocked(wanted)) { ShowVideoOff(t, wanted); } else { if (t.Hash != null && PosterNet.BytesEqual(t.Hash, wanted.Hash)) { return; } if (t.Busy) { t.Dirty = true; return; } t.Busy = true; List<string> candidates = new List<string>(LocalFiles); if (t.Path != null) { candidates.Add(t.Path); } string cacheDir = CacheDir; Enqueue<string>(Task.Run(() => ResolveLocal(wanted, candidates, cacheDir)), delegate(Task<string> task) { t.Busy = false; string found = (task.IsFaulted ? null : task.Result); if (task.IsFaulted) { Plugin.LogWarning("'" + t.Name + "': checking local files failed: " + task.Exception?.GetBaseException().Message); } OnResolved(t, wanted, found); }); } } private static string? ResolveLocal(PosterContentEntry wanted, List<string> candidates, string cacheDir) { string text = Path.Combine(cacheDir, wanted.HashHex + ByteToExt(wanted.Ext)); if (File.Exists(text) && new FileInfo(text).Length == wanted.Size) { return text; } HashSet<string> hashSet = new HashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (string candidate in candidates) { if (hashSet.Add(candidate) && File.Exists(candidate) && new FileInfo(candidate).Length == wanted.Size && PosterNet.BytesEqual(HashFile(candidate), wanted.Hash)) { return candidate; } } return null; } private static void OnResolved(Target t, PosterContentEntry wanted, string? found) { if ((Object)(object)t.Poster == (Object)null) { return; } if (!Manifest.TryGetValue(t.Key, out PosterContentEntry value) || !PosterNet.BytesEqual(value.Hash, wanted.Hash)) { Reconcile(t.Key); } else if (found != null) { if (!t.IsPlaceholder && string.Equals(found, t.Path, StringComparison.OrdinalIgnoreCase)) { t.Hash = wanted.Hash; } else { PosterNet.Run(ApplyRoutine(t, found, wanted)); } } else if (CanDownload(wanted)) { if (!t.IsPlaceholder) { PosterNet.Run(StandinRoutine(t, wanted)); } EnqueueDownload(wanted); } } private static bool CanDownload(PosterContentEntry e) { string hashHex = e.HashHex; if (!PosterConfig.ClientReceiveTransfer.Value || !IsSizeAllowed(e.Ext, e.Size)) { return false; } if (FailedUntil.TryGetValue(hashHex, out var value) && Time.unscaledTime < value) { return false; } return true; } private static void EnqueueDownload(PosterContentEntry e) { string hashHex = e.HashHex; if (_downloading && _activeHex == hashHex) { return; } foreach (PosterContentEntry item in DownloadQueue) { if (item.HashHex == hashHex) { return; } } DownloadQueue.Add(e); } private static void TickDownloads() { if (!_downloading && DownloadQueue.Count != 0 && PosterNet.IsRemoteClient) { PosterContentEntry posterContentEntry = DownloadQueue[0]; DownloadQueue.RemoveAt(0); _activeHex = posterContentEntry.HashHex; if (PosterNet.ClientBeginDownload(posterContentEntry, OnDownloadDone)) { _downloading = true; _lastPercent = 0; SetCanvasesPercent(posterContentEntry.Hash, 0); } } } private static void OnDownloadDone(PosterContentEntry entry, bool ok, string? info) { _downloading = false; string hashHex = entry.HashHex; if (!ok) { FailedUntil[hashHex] = Time.unscaledTime + 60f; SetCanvasesFailed(entry.Hash); if (!(info == "disconnected")) { Plugin.LogWarning("Download of host poster " + hashHex.Substring(0, 8) + " failed: " + info + ". " + $"Will not retry for {60f:0}s."); } return; } foreach (ulong item in new List<ulong>(Targets.Keys)) { if (Manifest.TryGetValue(item, out PosterContentEntry value) && PosterNet.BytesEqual(value.Hash, entry.Hash)) { Reconcile(item); } } } internal static void ClientOnProgress(PosterContentEntry entry, long received) { if (entry.Size > 0) { int num = (int)Math.Min(100L, received * 100 / entry.Size); if (num != _lastPercent) { _lastPercent = num; SetCanvasesPercent(entry.Hash, num); } } } internal static void ClientOnHostDimensions(int index) { if (!PosterFeature.TryGetHostSourceSize(index, out var width, out var height)) { return; } foreach (Target value in Targets.Values) { if (value.Canvas != null && (Object)(object)value.Poster != (Object)null && PosterFeature.GetPosterIndex(value.Poster) == index) { value.Canvas.SetPosterSize(width, height); } } } internal static void ClientOnSpeed(PosterContentEntry entry, float bytesPerSecond) { foreach (Target value in Targets.Values) { if (value.Canvas != null && WantsFile(value, entry.Hash)) { value.Canvas.SetSpeed(bytesPerSecond); } } } private static void SetCanvasesPercent(byte[] hash, int percent) { foreach (Target value in Targets.Values) { if (value.Canvas != null && WantsFile(value, hash)) { value.Canvas.SetPercent(percent); } } } private static void SetCanvasesFailed(byte[] hash) { foreach (Target value in Targets.Values) { if (value.Canvas != null && WantsFile(value, hash)) { value.Canvas.SetFailed(); } } } private static bool WantsFile(Target t, byte[] hash) { if (Manifest.TryGetValue(t.Key, out PosterContentEntry value)) { return PosterNet.BytesEqual(value.Hash, hash); } return false; } private static void ResolvePlaceholderSize(GameObject poster, PosterContentEntry? entry, out int width, out int height) { int posterIndex = PosterFeature.GetPosterIndex(poster); if (posterIndex < 0 || !PosterFeature.TryGetHostSourceSize(posterIndex, out width, out height)) { if (entry != null && entry.Width > 0 && entry.Height > 0) { width = entry.Width; height = entry.Height; } else { width = 0; height = 0; } } } private static IEnumerator HoldPlaceholderUntilVideoReady(GameObject? poster, PosterProgressCanvas canvas) { VideoPlayer video = (((Object)(object)poster != (Object)null) ? poster.GetComponent<VideoPlayer>() : null); MeshRenderer val = (((Object)(object)poster != (Object)null) ? poster.GetComponent<MeshRenderer>() : null); Material material = (((Object)(object)val != (Object)null) ? ((Renderer)val).sharedMaterial : null); RenderTexture videoTexture = (((Object)(object)video != (Object)null) ? video.targetTexture : null); if ((Object)(object)video == (Object)null || (Object)(object)material == (Object)null || (Object)(object)videoTexture == (Object)null) { canvas.Dispose(); yield break; } material.SetTexture("_BaseColorMap", (Texture)(object)canvas.Texture); bool gotFrame = false; FrameReadyEventHandler onFrame = (FrameReadyEventHandler)delegate { gotFrame = true; }; video.sendFrameReadyEvents = true; video.frameReady += onFrame; float started = Time.unscaledTime; while (!gotFrame && (Object)(object)video != (Object)null && (Object)(object)material != (Object)null && Time.unscaledTime - started < 15f) { yield return null; } if ((Object)(object)video != (Object)null) { video.frameReady -= onFrame; video.sendFrameReadyEvents = false; } yield return null; if ((Object)(object)material != (Object)null && (Object)(object)videoTexture != (Object)null) { material.SetTexture("_BaseColorMap", (Texture)(object)videoTexture); } canvas.Dispose(); } private static IEnumerator StandinRoutine(Target t, PosterContentEntry wanted) { t.Busy = true; GameObject poster = t.Poster; if ((Object)(object)poster == (Object)null || !CanSwapContent) { t.Busy = false; yield break; } string localPath = t.Path; bool localIsVideo = t.IsVideo; ResolvePlaceholderSize(poster, wanted, out var width, out var height); PosterProgressCanvas canvas = new PosterProgressCanvas(width, height); if (_downloading && _activeHex == wanted.HashHex && _lastPercent >= 0) { canvas.SetPercent(_lastPercent); } Component component = poster.GetComponent(_rendererType); if ((Object)(object)component != (Object)null) { Object.Destroy((Object)(object)component); } VideoPlayer[] components = poster.GetComponents<VideoPlayer>(); for (int i = 0; i < components.Length; i++) { Object.Destroy((Object)(object)components[i]); } AudioSource[] components2 = poster.GetComponents<AudioSource>(); for (int i = 0; i < components2.Length; i++) { Object.Destroy((Object)(object)components2[i]); } yield return null; if ((Object)(object)poster == (Object)null) { canvas.Dispose(); t.Busy = false; yield break; } if (InvokeInitialize(poster, canvas.Texture, null)) { t.RestorePath = localPath; t.RestoreIsVideo = localIsVideo; t.Path = null; t.IsVideo = false; t.Hash = null; t.IsPlaceholder = true; t.PlaceholderSince = Time.unscaledTime; t.Canvas?.Dispose(); t.Canvas = canvas; PosterFeature.SetSourceDimensions(poster, (width > 0) ? width : 512, (height > 0) ? height : 512); RefreshShellVisual(poster); } else { canvas.Dispose(); Plugin.LogWarning("'" + t.Name + "': could not show the progress image; restoring previous content."); yield return null; RestorePrevious(t); } t.Busy = false; if (t.Dirty) { t.Dirty = false; Reconcile(t.Key); } } private static IEnumerator ApplyRoutine(Target t, string path, PosterContentEntry entry) { t.Busy = true; GameObject poster = t.Poster; bool isVideo = IsVideoExt(ExtToByte(Path.GetExtension(path))); Texture2D tex = null; if (!isVideo) { Task<byte[]> read = Task.Run(() => File.ReadAllBytes(path)); while (!read.IsCompleted) { yield return null; } if (!read.IsFaulted) { Texture2D val = new Texture2D(2, 2); if (ImageConversion.LoadImage(val, read.Result)) { ((Texture)val).filterMode = (FilterMode)0; tex = val; } else { Object.Destroy((Object)(object)val); } } if ((Object)(object)tex == (Object)null) { Plugin.LogWarning("'" + t.Name + "': could not decode " + Path.GetFileName(path) + "; keeping current content."); t.Canvas?.SetFailed(); t.Busy = false; yield break; } } if ((Object)(object)poster == (Object)null || !CanSwapContent) { t.Busy = false; yield break; } Component component = poster.GetComponent(_rendererType); if ((Object)(object)component != (Object)null) { Object.Destroy((Object)(object)component); } VideoPlayer[] components = poster.GetComponents<VideoPlayer>(); for (int num = 0; num < components.Length; num++) { Object.Destroy((Object)(object)components[num]); } AudioSource[] components2 = poster.GetComponents<AudioSource>(); for (int num = 0; num < components2.Length; num++) { Object.Destroy((Object)(object)components2[num]); } yield return null; if ((Object)(object)poster == (Object)null) { t.Busy = false; yield break; } if (InvokeInitialize(poster, tex, isVideo ? path : null)) { t.Path = path; t.IsVideo = isVideo; t.Hash = entry.Hash; t.IsPlaceholder = false; t.RestorePath = null; RefreshShellVisual(poster); if (t.Canvas != null) { PosterProgressCanvas canvas = t.Canvas; t.Canvas = null; if (isVideo) { PosterNet.Run(HoldPlaceholderUntilVideoReady(poster, canvas)); } else { canvas.Dispose(); } } } else { Plugin.LogWarning("'" + t.Name + "': failed to apply host content; restoring previous content."); yield return null; RestorePrevious(t); } t.Busy = false; if (t.Dirty) { t.Dirty = false; Reconcile(t.Key); } } private static bool InvokeInitialize(GameObject poster, Texture2D? tex, string? videoPath) { try { MeshRenderer component = poster.GetComponent<MeshRenderer>(); Material val = (((Object)(object)component != (Object)null) ? ((Renderer)component).material : null); Component obj = poster.AddComponent(_rendererType); _rendererInit.Invoke(obj, new object[3] { tex, videoPath, val }); return (Object)(object)poster != (Object)null; } catch (Exception ex) { Plugin.LogError("PosterRenderer.Initialize failed: " + ex.GetBaseException().Message); return false; } } private static void RestorePrevious(Target t) { GameObject poster = t.Poster; if ((Object)(object)poster == (Object)null) { return; } Component component = poster.GetComponent(_rendererType); if ((Object)(object)component != (Object)null) { Object.DestroyImmediate((Object)(object)component); } Texture2D val = null; string text = null; if (t.Path != null && File.Exists(t.Path)) { if (t.IsVideo) { text = t.Path; } else { val = LoadTextureBlocking(t.Path); } } if (val == null) { val = ((text != null) ? null : (t.Canvas?.Texture ?? GetPlaceholder())); } if (!InvokeInitialize(poster, val, text)) { Plugin.LogError("'" + t.Name + "': could not restore previous content either."); } else { RefreshShellVisual(poster); } } internal static void Tick(float dt) { for (int num = Jobs.Count - 1; num >= 0; num--) { Job job = Jobs[num]; if (job.Task.IsCompleted) { Jobs.RemoveAt(num); try { job.OnDone(); } catch (Exception ex) { Plugin.LogWarning("PosterContent background job failed: " + ex.Message); } } } if (PosterNet.IsHost) { TickHost(); } else { if (!PosterNet.IsRemoteClient) { return; } TickDownloads(); List<Target> list = null; foreach (Target value in Targets.Values) { if (value.IsPlaceholder && !_manifestReceived && Time.unscaledTime - value.PlaceholderSince > 20f) { (list ?? (list = new List<Target>())).Add(value); } } if (list == null) { return; } foreach (Target item in list) { DestroyPlaceholder(item, "the host never sent a content manifest"); } } } } internal sealed class PosterStareAudio : MonoBehaviour { private const string OwnSourceName = "MovePosters_StareAudio"; private static readonly List<PosterStareAudio> Live = new List<PosterStareAudio>(); private int _index = -1; private VideoPlayer? _video; private AudioSource? _source; private StareGain? _gain; private GameObject? _ownObject; private float _baseVolume = 1f; private float _baseBlend = 1f; private bool _changed; private float _stare; private float _stareVolume = -1f; private bool OwnsSource => (Object)(object)_ownObject != (Object)null; internal static void Attach(GameObject poster, int index) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Invalid comparison between Unknown and I4 if ((Object)(object)poster == (Object)null) { return; } VideoPlayer component = poster.GetComponent<VideoPlayer>(); if ((Object)(object)component == (Object)null) { Plugin.LogWarning($"Poster {index + 1}: no VideoPlayer found; stare sound unavailable."); return; } AudioSource val = null; try { if ((int)component.audioOutputMode == 1) { val = component.GetTargetAudioSource((ushort)0); } } catch (Exception) { val = null; } PosterStareAudio posterStareAudio = poster.GetComponent<PosterStareAudio>(); if ((Object)(object)posterStareAudio != (Object)null && (Object)(object)val != (Object)null && (Object)(object)posterStareAudio._source == (Object)(object)val && !posterStareAudio.OwnsSource) { posterStareAudio._index = index; return; } if ((Object)(object)posterStareAudio == (Object)null) { posterStareAudio = poster.AddComponent<PosterStareAudio>(); } posterStareAudio.Release(); posterStareAudio._index = index; posterStareAudio._video = component; if ((Object)(object)val != (Object)null) { posterStareAudio._source = val; posterStareAudio._gain = StareGain.On(((Component)val).gameObject); } else { posterStareAudio.CreateOwnSource(poster, component); } posterStareAudio._changed = false; posterStareAudio._stareVolume = -1f; posterStareAudio.Recompute(); } private void CreateOwnSource(GameObject poster, VideoPlayer video) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Expected O, but got Unknown GameObject val = new GameObject("MovePosters_StareAudio"); val.transform.SetParent(poster.transform, false); AudioSource val2 = val.AddComponent<AudioSource>(); val2.playOnAwake = false; val2.spatialBlend = 0f; val2.spatialize = false; val2.dopplerLevel = 0f; val2.volume = 0f; _ownObject = val; _source = val2; _gain = StareGain.On(val); video.Stop(); video.audioOutputMode = (VideoAudioOutputMode)1; video.SetTargetAudioSource((ushort)0, val2); video.Prepare(); } private void Release() { RestoreSource(); if ((Object)(object)_gain != (Object)null) { _gain.Target = 1f; } if ((Object)(object)_ownObject != (Object)null) { Object.Destroy((Object)(object)_ownObject); } _ownObject = null; _source = null; _gain = null; _video = null; } private void OnEnable() { Live.Add(this); } private void OnDisable() { Live.Remove(this); RestoreSource(); _stare = 0f; _stareVolume = -1f; if ((Object)(object)_gain != (Object)null) { _gain.Target = 1f; } } internal static void SetStare(int index, float amount) { for (int i = 0; i < Live.Count; i++) { if (Live[i]._index == index) { Live[i].ApplyStare(amount); } } } internal static void ClearStare() { for (int i = 0; i < Live.Count; i++) { Live[i].ApplyStare(0f); } } internal static bool HasAudio(int index) { for (int i = 0; i < Live.Count; i++) { if (Live[i]._index == index && Live[i].CanControl()) { return true; } } return false; } private void ApplyStare(float amount) { float num = PosterControlsSettings.StareVolumePercent; if (!Mathf.Approximately(amount, _stare) || !Mathf.Approximately(num, _stareVolume)) { _stare = amount; _stareVolume = num; Recompute(); } } private bool CanControl() { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Invalid comparison between Unknown and I4 if ((Object)(object)_source == (Object)null) { return false; } if (OwnsSource) { return true; } if (!_source.mute) { if (!((Object)(object)_video == (Object)null)) { return (int)_video.audioOutputMode == 1; } return true; } return false; } private void Recompute() { if ((Object)(object)_source == (Object)null || !CanControl()) { SetGain(1f); return; } float num = Mathf.Max(0f, _stareVolume) / 100f; if (OwnsSource) { float num2 = Mathf.Lerp(0f, num, _stare); _source.volume = Mathf.Min(num2, 1f); SetGain(Mathf.Max(num2, 1f)); return; } if (_stare <= 0f) { RestoreSource(); SetGain(1f); return; } if (!_changed) { _baseVolume = _source.volume; _baseBlend = _source.spatialBlend; _changed = true; } float num3 = Mathf.Lerp(_baseVolume, num, _stare); _source.volume = Mathf.Min(num3, 1f); SetGain(Mathf.Max(num3, 1f)); _source.spatialBlend = Mathf.Lerp(_baseBlend, 0f, _stare); } private void SetGain(float gain) { if ((Object)(object)_gain != (Object)null) { _gain.Target = gain; } } private void RestoreSource() { if (_changed) { _changed = false; if ((Object)(object)_source != (Object)null && !OwnsSource) { _source.volume = _baseVolume; _source.spatialBlend = _baseBlend; } } } } internal sealed class StareGain : MonoBehaviour { private const float LimiterKnee = 0.8f; private volatile float _target = 1f; private float _applied = 1f; internal float Target { get { return _target; } set { _target = value; } } internal static StareGain On(GameObject host) { StareGain component = host.GetComponent<StareGain>(); if (!((Object)(object)component != (Object)null)) { return host.AddComponent<StareGain>(); } return component; } private void OnAudioFilterRead(float[] data, int channels) { float target = _target; float num = _applied; if (num <= 1f && target <= 1f) { _applied = 1f; return; } int num2 = ((channels > 0) ? (data.Length / channels) : data.Length); if (num2 <= 0) { return; } float num3 = (target - num) / (float)num2; int num4 = 0; for (int i = 0; i < num2; i++) { num += num3; int num5 = 0; while (num5 < channels) { data[num4] = SoftLimit(data[num4] * num); num5++; num4++; } } _applied = target; } private static float SoftLimit(float x) { float num = Math.Abs(x); if (num <= 0.8f) { return x; } float num2 = 0.19999999f; float num3 = 0.8f + num2 * (float)Math.Tanh((num - 0.8f) / num2); if (!(x < 0f)) { return num3; } return 0f - num3; } } internal static class PosterVideoHeader { private const long MaxHeaderBytes = 67108864L; internal static bool TryReadSize(string path, out int width, out int height) { width = 0; height = 0; try { using FileStream fileStream = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); long length = fileStream.Length; long num = 0L; byte[] array = new byte[16]; long num2; for (; num + 8 <= length; num += num2) { fileStream.Position = num; if (fileStream.Read(array, 0, 8) < 8) { return false; } num2 = ReadUInt32(array, 0); string text = Encoding.ASCII.GetString(array, 4, 4); int num3 = 8; switch (num2) { case 1L: if (fileStream.Read(array, 8, 8) < 8) { return false; } num2 = (long)ReadUInt64(array, 8); num3 = 16; break; case 0L: num2 = length - num; break; } if (num2 < num3) { return false; } if (!(text == "moov")) { continue; } long num4 = num2 - num3; if (num4 <= 0 || num4 > 67108864 || num + num2 > length) { return false; } byte[] array2 = new byte[num4]; fileStream.Position = num + num3; int num5; for (int i = 0; i < num4; i += num5) { num5 = fileStream.Read(array2, i, (int)num4 - i); if (num5 <= 0) { return false; } } return ParseMovie(array2, out width, out height); } } catch (Exception) { } return false; } private static bool ParseMovie(byte[] data, out int width, out int height) { width = 0; height = 0; int position = 0; string type; int payloadStart; int payloadEnd; while (NextBox(data, ref position, data.Length, out type, out payloadStart, out payloadEnd)) { if (!(type != "trak") && IsVideoTrack(data, payloadStart, payloadEnd) && FindChild(data, payloadStart, payloadEnd, "tkhd", out var childStart, out var childEnd) && childEnd - childStart >= 84) { int num = (int)(ReadUInt32(data, childEnd - 8) >> 16); int num2 = (int)(ReadUInt32(data, childEnd - 4) >> 16); if (num > 0 && num2 > 0) { width = num; height = num2; return true; } } } return false; } private static bool IsVideoTrack(byte[] data, int start, int end) { if (!FindChild(data, start, end, "mdia", out var childStart, out var childEnd) || !FindChild(data, childStart, childEnd, "hdlr", out var childStart2, out var childEnd2) || childEnd2 - childStart2 < 12) { return false; } return Encoding.ASCII.GetString(data, childStart2 + 8, 4) == "vide"; } private static bool FindChild(byte[] data, int start, int end, string wanted, out int childStart, out int childEnd) { int position = start; string type; while (NextBox(data, ref position, end, out type, out childStart, out childEnd)) { if (type == wanted) { return true; } } childStart = 0; childEnd = 0; return false; } private static bool NextBox(byte[] data, ref int position, int end, out string type, out int payloadStart, out int payloadEnd) { type = ""; payloadStart = 0; payloadEnd = 0; if (position + 8 > end) { return false; } long num = ReadUInt32(data, position); type = Encoding.ASCII.GetString(data, position + 4, 4); int num2 = 8; switch (num) { case 1L: if (position + 16 > end) { return false; } num = (long)ReadUInt64(data, position + 8); num2 = 16; break; case 0L: num = end - position; break; } if (num < num2 || position + num > end) { return false; } payloadStart = position + num2; payloadEnd = (int)(position + num); position = payloadEnd; return true; } private static uint ReadUInt32(byte[] data, int offset) { return (uint)((data[offset] << 24) | (data[offset + 1] << 16) | (data[offset + 2] << 8) | data[offset + 3]); } private static ulong ReadUInt64(byte[] data, int offset) { return ((ulong)ReadUInt32(data, offset) << 32) | ReadUInt32(data, offset + 4); } } internal static class PosterFeature { private sealed class PosterEntry { public GameObject Poster { get; set; } public string PosterName { get; set; } public int Index { get; } public int UnlockableId { get; set; } = -1; public GameObject? Shell { get; set; } public GameObject? PosterVisual { get; set; } public int SourceWidthPixels { get; set; } public int SourceHeightPixels { get; set; } public Vector3 OriginalLocalScale { get; } public Vector3 OriginalEuler { get; } public float HostScale { get; set; } public int HostSourceWidth { get; set; } public int HostSourceHeight { get; set; } public bool HasHostTilt { get; set; } public float HostTiltX { get; set; } public float HostTiltZ { get; set; } public PosterEntry(GameObject poster, int index) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) Poster = poster; PosterName = ((Object)poster).name; Index = index; OriginalLocalScale = poster.transform.localScale; OriginalEuler = poster.transform.eulerAngles; } } private const int MovablePosterCount = 4; private static readonly List<PosterEntry> Entries = new List<PosterEntry>(); private static readonly Dictionary<int, GameObject> PendingShellBinds = new Dictionary<int, GameObject>(); private static readonly Dictionary<int, PosterSlotState> PendingShellStates = new Dictionary<int, PosterSlotState>(); private static bool _loggedClientShellSkip; public static IReadOnlyList<GameObject> AllPosters { get { List<GameObject> list = new List<GameObject>(Entries.Count); foreach (PosterEntry entry in Entries) { if ((Object)(object)entry.Poster != (Object)null) { list.Add(entry.Poster); } } return list; } } public static int LivePosterCount { get { int num = 0; foreach (PosterEntry entry in Entries) { if ((Object)(object)entry.Poster != (Object)null) { num++; } } return num; } } public static void CopyPostersTo(List<GameObject> into) { into.Clear(); foreach (PosterEntry entry in Entries) { if ((Object)(object)entry.Poster != (Object)null) { into.Add(entry.Poster); } } } public static void RegisterPoster(GameObject poster) { //IL_011e: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)poster == (Object)null) { return; } foreach (PosterEntry entry in Entries) { if ((Object)(object)entry.Poster == (Object)(object)poster) { return; } } string name = ((Object)poster).name; foreach (PosterEntry entry2 in Entries) { if (string.Equals(entry2.PosterName, name, StringComparison.OrdinalIgnoreCase)) { RebindPoster(entry2, poster); FlushPendingShellBind(entry2.Index); return; } } if (!IsExtraPoster(name) && Entries.Count < 4) { int count = Entries.Count; if (!string.Equals(name, $"Poster{count + 1}", StringComparison.OrdinalIgnoreCase)) { Plugin.LogWarning($"CustomPosters created \"{name}\" where MovePosters expected \"Poster{count + 1}\". " + "This ship layout creates its posters in a different order, so a poster may not line up with the same one on another player's ship."); } PosterEntry posterEntry = new PosterEntry(poster, count); Entries.Add(posterEntry); PosterConfig.UseLayoutRotationIfDefault(count, posterEntry.OriginalEuler); PosterUnlockables.EnsureInitialized(4); int id = PosterUnlockables.GetId(count); posterEntry.UnlockableId = id; PosterBody.Ensure(poster); FlushPendingShellBind(count); } } private static bool IsExtraPoster(string name) { if (!string.Equals(name, "Poster5", StringComparison.OrdinalIgnoreCase)) { return string.Equals(name, "CustomTips", StringComparison.OrdinalIgnoreCase); } return true; } private static void RebindPoster(PosterEntry entry, GameObject poster) { entry.Poster = poster; PosterBody.Ensure(poster); if ((Object)(object)entry.Shell == (Object)null) { entry.Shell = null; entry.PosterVisual = null; } if ((Object)(object)entry.Shell != (Object)null) { SyncPosterToShell(entry.Index); ApplyDimensionsToShell(entry.Index); } PosterStorage.Refresh(); } public static void SetSourceDimensions(GameObject poster, int widthPixels, int heightPixels) { if (!((Object)(object)poster == (Object)null)) { int posterIndex = GetPosterIndex(poster); if (posterIndex >= 0) { SetSourceDimensions(posterIndex, widthPixels, heightPixels); } } } public static void SetSourceDimensions(int index, int widthPixels, int heightPixels) { if (index >= 0 && index < Entries.Count && widthPixels > 0 && heightPixels > 0) { PosterEntry posterEntry = Entries[index]; bool num = posterEntry.SourceWidthPixels != widthPixels || posterEntry.SourceHeightPixels != heightPixels; posterEntry.SourceWidthPixels = widthPixels; posterEntry.SourceHeightPixels = heightPixels; if (num || (Object)(object)posterEntry.Shell != (Object)null) { ApplyDimensionsToShell(index); } if (num) { PublishSlotState(index); } } } public static void RefreshShellVisualMaterial(int index) { if (index < 0 || index >= Entries.Count) { return; } PosterEntry posterEntry = Entries[index]; GameObject poster = posterEntry.Poster; GameObject posterVisual = posterEntry.PosterVisual; if (!((Object)(object)poster == (Object)null) && !((Object)(object)posterVisual == (Object)null)) { MeshRenderer component = poster.GetComponent<MeshRenderer>(); MeshRenderer component2 = posterVisual.GetComponent<MeshRenderer>(); if (!((Object)(object)component == (Object)null) && !((Object)(object)component2 == (Object)null)) { ((Renderer)component2).sharedMaterials = ((Renderer)component).sharedMaterials; } } } public static int GetPosterIndex(GameObject poster) { if ((Object)(object)poster == (Object)null) { return -1; } foreach (PosterEntry entry in Entries) { if ((Object)(object)entry.Poster == (Object)(object)poster) { return entry.Index; } } return -1; } public static GameObject? GetPoster(int index) { if (index < 0 || index >= Entries.Count) { return null; } return Entries[index].Poster; } public static GameObject? GetShell(int index) { if (index < 0 || index >= Entries.Count) { return null; } return Entries[index].Shell; } public static int GetPosterIndexByUnlockableId(int unlockableId) { foreach (PosterEntry entry in Entries) { if (entry.UnlockableId == unlockableId) { return entry.Index; } } return -1; } public static void SyncPosterToTransform(int index, Vector3 position, Quaternion rotation) { //IL_0033: 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 (index >= 0 && index < Entries.Count) { GameObject poster = Entries[index].Poster; if (!((Object)(object)poster == (Object)null)) { poster.transform.SetPositionAndRotation(position, rotation); } } } public static void SyncPosterToShell(int index) { //IL_0051: 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) if (index >= 0 && index < Entries.Count) { PosterEntry posterEntry = Entries[index]; if (!((Object)(object)posterEntry.Poster == (Object)null) && !((Object)(object)posterEntry.Shell == (Object)null)) { posterEntry.Poster.transform.SetPositionAndRotation(posterEntry.Shell.transform.position, posterEntry.Shell.transform.rotation); } } } public static void PublishSlotState(int index) { //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)NetworkManager.Singleton == (Object)null || !NetworkManager.Singleton.IsServer || index < 0 || index >= Entries.Count) { return; } PosterEntry posterEntry = Entries[index]; if (!((Object)(object)posterEntry.Shell == (Object)null)) { NetworkObject component = posterEntry.Shell.GetComponent<NetworkObject>(); if (!((Object)(object)component == (Object)null) && component.IsSpawned) { PosterNet.HostPublishSlot(index, new PosterSlotState { ShellNetworkObjectId = component.NetworkObjectId, IsPublished = true, Position = posterEntry.Shell.transform.position, Rotation = posterEntry.Shell.transform.rotation, Scale = PosterConfig.GetScale(index), SourceWidth = posterEntry.SourceWidthPixels, SourceHeight = posterEntry.SourceHeightPixels, TiltX = PosterConfig.GetTiltX(index), TiltZ = PosterConfig.GetTiltZ(index), IsStored = PosterStorage.IsStored(index) }); } } } public static void OnSlotStateChanged(int index, PosterSlotState state, int attempts = 0) { if ((!((Object)(object)NetworkManager.Singleton != (Object)null) || !NetworkManager.Singleton.IsServer) && state.IsPublished && state.ShellNetworkObjectId != 0L) { if ((Object)(object)NetworkManager.Singleton == (Object)null || NetworkManager.Singleton.SpawnManager == null || !NetworkManager.Singleton.SpawnManager.SpawnedObjects.TryGetValue(state.ShellNetworkObjectId, out var value) || (Object)(object)value == (Object)null) { PosterNet.QueueSlotRetry(index, state, attempts); } else { BindClientShell(index, ((Component)value).gameObject, state); } } } public static void BindClientShell(int index, GameObject shell, PosterSlotState state) { //IL_007e: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)shell == (Object)null || index < 0) { return; } PosterUnlockables.EnsureInitialized(4); if (index >= Entries.Count || (Object)(object)Entries[index].Poster == (Object)null) { PendingShellBinds[index] = shell; PendingShellStates[index] = state; HideUnboundShell(shell); return; } PosterEntry posterEntry = Entries[index]; posterEntry.HostScale = state.Scale; PosterConfig.SetTransformSilently(index, state.Scale, ((Quaternion)(ref state.Rotation)).eulerAngles); posterEntry.HostSourceWidth = state.SourceWidth; posterEntry.HostSourceHeight = state.SourceHeight; posterEntry.HasHostTilt = true; posterEntry.HostTiltX = state.TiltX; posterEntry.HostTiltZ = state.TiltZ; PosterContent.ClientOnHostDimensions(index); PosterStorage.OnHostSlotState(index, state.IsStored); if (!((Object)(object)posterEntry.Shell == (Object)(object)shell)) { GameObject poster = posterEntry.Poster; if ((Object)(object)poster == (Object)null) { return; } _ = (Object)(object)posterEntry.Shell != (Object)null; if (!ConfigureShell(index, shell, poster)) { Plugin.LogError("Failed to configure received network shell for " + $"Poster {index + 1}."); return; } posterEntry.Shell = shell; } if (state.IsPublished) { ApplyPublishedTransform(index, state); } else { SyncPosterToShell(index); } ApplyDimensionsToShell(index); } private static void ApplyPublishedTransform(int index, PosterSlotState state) { //IL_0057: 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) if (index < 0 || index >= Entries.Count) { return; } PosterEntry posterEntry = Entries[index]; if (!((Object)(object)posterEntry.Shell == (Object)null)) { PlaceableShipObject componentInChildren = posterEntry.Shell.GetComponentInChildren<PlaceableShipObject>(); if (!((Object)(object)componentInChildren == (Object)null) && !((Object)(object)ShipBuildModeManager.Instance == (Object)null)) { ShipBuildModeManager.Instance.PlaceShipObject(state.Position, ((Quaternion)(ref state.Rotation)).eulerAngles, componentInChildren, false); SyncPosterToShell(index); } } } private static void HideUnboundShell(GameObject shell) { if (!((Object)(object)shell == (Object)null)) { Renderer[] componentsInChildren = shell.GetComponentsInChildren<Renderer>(true); for (int i = 0; i < componentsInChildren.Length; i++) { componentsInChildren[i].enabled = false; } Collider[] componentsInChildren2 = shell.GetComponentsInChildren<Collider>(true); for (int i = 0; i < componentsInChildren2.Length; i++) { componentsInChildren2[i].enabled = false; } } } public static void ResetSession() { PosterStorage.ResetSession(); PosterConfig.RestoreTransformsFromConfig(); Entries.Clear(); PendingShellBinds.Clear(); PendingShellStates.Clear(); _loggedClientShellSkip = false; } internal static bool TryGetHostScale(int index, out float scale) { scale = 0f; if (!PosterNet.IsRemoteClient || index < 0 || index >= Entries.Count) { return false; } scale = Entries[index].HostScale; return scale > 0f; } internal static bool TryGetPosterForPreview(int index, out GameObject poster, out int width, out int height) { poster = null; width = 0; height = 0; if (index < 0 || index >= Entries.Count || (Object)(object)Entries[index].Poster == (Object)null) { return false; } poster = Entries[index].Poster; width = EffectiveSourceWidth(Entries[index]); height = EffectiveSourceHeight(Entries[index]); return true; } internal static bool TryGetHostTilt(int index, out float tiltX, out float tiltZ) { tiltX = 0f; tiltZ = 0f; if (!PosterNet.IsRemoteClient || index < 0 || index >= Entries.Count || !Entries[index].HasHostTilt) { return false; } tiltX = Entries[index].HostTiltX; tiltZ = Entries[index].HostTiltZ; return true; } internal static bool TryGetHostSourceSize(int index, out int width, out int height) { width = 0; height = 0; if (index < 0) { return false; } if (index < Entries.Count && Entries[index].HostSourceWidth > 0 && Entries[index].HostSourceHeight > 0) { width = Entries[index].HostSourceWidth; height = Entries[index].HostSourceHeight; return true; } if (PendingShellStates.TryGetValue(index, out var value) && value.SourceWidth > 0 && value.SourceHeight > 0) { width = value.SourceWidth; height = value.SourceHeight; return true; } return false; } private static int EffectiveSourceWidth(PosterEntry entry) { if (!PosterNet.IsRemoteClient || entry.HostSourceWidth <= 0 || entry.HostSourceHeight <= 0) { return entry.SourceWidthPixels; } return entry.HostSourceWidth; } private static int EffectiveSourceHeight(PosterEntry entry) { if (!PosterNet.IsRemoteClient || entry.HostSourceWidth <= 0 || entry.HostSourceHeight <= 0) { return entry.SourceHeightPixels; } return entry.HostSourceHeight; } private static Quaternion GetBaseRotation(PosterEntry entry) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) return Quaternion.Euler(PosterConfig.GetTiltX(entry.Index), PosterConfig.GetRotationY(entry.Index), PosterConfig.GetTiltZ(entry.Index)); } private static Quaternion KeepOnlyYaw(Quaternion placed, Quaternion baseRotation) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: 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_000d: 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_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_003d: 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_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) Quaternion val = placed * Quaternion.Inverse(baseRotation); float num = Mathf.Sqrt(val.y * val.y + val.w * val.w); if (num < 1E-05f) { return baseRotation; } return new Quaternion(0f, val.y / num, 0f, val.w / num) * baseRotation; } internal static bool TryGetHealedPlacement(int index, out Vector3 position, out Vector3 healedRotation) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0094: 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_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) position = Vector3.zero; healedRotation = Vector3.zero; if (index < 0 || index >= Entries.Count) { return false; } PosterEntry posterEntry = Entries[index]; List<UnlockableItem> list = StartOfRound.Instance?.unlockablesList?.unlockables; if (list == null || posterEntry.UnlockableId < 0 || posterEntry.UnlockableId >= list.Count) { return false; } UnlockableItem val = list[posterEntry.UnlockableId]; if (val == null || !val.hasBeenMoved) { return false; } Quaternion val2 = Quaternion.Euler(val.placedRotation); Quaternion val3 = KeepOnlyYaw(val2, GetBaseRotation(posterEntry)); if (Quaternion.Angle(val2, val3) <= 1f) { return false; } position = val.placedPosition; healedRotation = ((Quaternion)(ref val3)).eulerAngles; return true; } private static void FlushPendingShellBind(int index) { if (PendingShellBinds.TryGetValue(index, out GameObject value)) { PendingShellBinds.Remove(index); PendingShellStates.TryGetValue(index, out var value2); PendingShellStates.Remove(index); if (!((Object)(object)value == (Object)null)) { BindClientShell(index, value, value2); } } } public static void CreateShells() { if (Entries.Count == 0) { return; } if ((Object)(object)NetworkManager.Singleton == (Object)null || !NetworkManager.Singleton.IsServer) { if (!_loggedClientShellSkip) { _loggedClientShellSkip = true; } return; } GameObject val = FindClassicPaintingPrefab(); if ((Object)(object)val == (Object)null) { Plugin.LogError("Could not find ClassicPaintingContainer prefab."); return; } int num = Mathf.Min(4, Entries.Count); for (int i = 0; i < num; i++) { CreateShell(i, val); } } private static void CreateShell(int index, GameObject classicPaintingPrefab) { if (index < 0 || index >= Entries.Count) { return; } PosterEntry posterEntry = Entries[index]; GameObject poster = posterEntry.Poster; if ((Object)(object)poster == (Object)null || (Object)(object)posterEntry.Shell != (Object)null || posterEntry.UnlockableId < 0) { return; } GameObject val = Object.Instantiate<GameObject>(classicPaintingPrefab); ((Object)val).name = $"MovePosters_Poster{index + 1}_Shell"; if (!ConfigureShell(index, val, poster)) { Object.Destroy((Object)(object)val); return; } posterEntry.Shell = val; NetworkObject component = val.GetComponent<NetworkObject>(); if ((Object)(object)component == (Object)null) { Plugin.LogError($"Poster {index + 1} shell has no NetworkObject."); Object.Destroy((Object)(object)val); posterEntry.Shell = null; posterEntry.PosterVisual = null; return; } if (!component.IsSpawned) { component.Spawn(false); } RestoreSavedTransform(index); PosterStorage.OnHostShellReady(index); ApplyDimensionsToShell(index); PublishSlotState(index); } public static void RestoreSavedTransform(int index) { //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Unknown result type (might be due to invalid IL or missing references) if (index < 0 || index >= Entries.Count) { return; } PosterEntry posterEntry = Entries[index]; if ((Object)(object)posterEntry.Shell == (Object)null || posterEntry.UnlockableId < 0) { return; } StartOfRound instance = StartOfRound.Instance; if ((Object)(object)instance == (Object)null || (Object)(object)instance.unlockablesList == (Object)null) { return; } List<UnlockableItem> unlockables = instance.unlockablesList.unlockables; if (posterEntry.UnlockableId >= unlockables.Count) { return; } UnlockableItem val = unlockables[posterEntry.UnlockableId]; if (val == null || !val.hasBeenMoved) { return; } PlaceableShipObject componentInChildren = posterEntry.Shell.GetComponentInChildren<PlaceableShipObject>(); if (!((Object)(object)componentInChildren == (Object)null) && !((Object)(object)ShipBuildModeManager.Instance == (Object)null)) { Vector3 val2 = val.placedRotation; Quaternion val3 = Quaternion.Euler(val2); Quaternion val4 = KeepOnlyYaw(val3, GetBaseRotation(posterEntry)); if (Quaternion.Angle(val3, val4) > 1f) { val2 = ((Quaternion)(ref val4)).eulerAngles; } ShipBuildModeManager.Instance.PlaceShipObject(val.placedPosition, val2, componentInChildren, false); SyncPosterToShell(index); } } private static bool ConfigureShell(int index, GameObject shell, GameObject poster) { //IL_0062: Unknown result type