// Consolidated decompiled source — Wubarrk-TortalPortal v1.0.0 // Generated by Hexium's decompiled-source browser. Best-effort concatenation of every type in this // version's manifest — decompiler output isn't guaranteed to compile as-is. using System; using System.Runtime.CompilerServices; using BepInEx.Configuration; using JetBrains.Annotations; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using HarmonyLib; using UnityEngine; using BepInEx; using TMPro; using ServerSync; using BepInEx.Logging; using System.Text; using UnityEngine.Rendering; // ---- plugins/TortalPortal.dll :: Microsoft.CodeAnalysis.EmbeddedAttribute ---- namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } // ---- plugins/TortalPortal.dll :: ServerSync.OwnConfigEntryBase ---- namespace ServerSync { [PublicAPI] public abstract class OwnConfigEntryBase { public object? LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } } // ---- plugins/TortalPortal.dll :: ServerSync.SyncedConfigEntry`1 ---- namespace ServerSync { [PublicAPI] public class SyncedConfigEntry(ConfigEntry sourceConfig) : OwnConfigEntryBase { public readonly ConfigEntry SourceConfig = sourceConfig; public override ConfigEntryBase BaseConfig => SourceConfig; public T Value { get { return SourceConfig.Value; } set { SourceConfig.Value = value; } } public void AssignLocalValue(T value) { if (LocalBaseValue == null) { Value = value; } else { LocalBaseValue = value; } } } } // ---- plugins/TortalPortal.dll :: ServerSync.CustomSyncedValueBase ---- namespace ServerSync { public abstract class CustomSyncedValueBase { public object? LocalBaseValue; public readonly string Identifier; public readonly Type Type; private object? boxedValue; protected bool localIsOwner; public readonly int Priority; public object? BoxedValue { get { return boxedValue; } set { boxedValue = value; this.ValueChanged?.Invoke(); } } public event Action? ValueChanged; protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority) { Priority = priority; Identifier = identifier; Type = type; configSync.AddCustomValue(this); localIsOwner = configSync.IsSourceOfTruth; configSync.SourceOfTruthChanged += delegate(bool truth) { localIsOwner = truth; }; } } } // ---- plugins/TortalPortal.dll :: ServerSync.CustomSyncedValue`1 ---- namespace ServerSync { [PublicAPI] public sealed class CustomSyncedValue : CustomSyncedValueBase { public T Value { get { return (T)base.BoxedValue; } set { base.BoxedValue = value; } } public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0) : base(configSync, identifier, typeof(T), priority) { Value = value; } public void AssignLocalValue(T value) { if (localIsOwner) { Value = value; } else { LocalBaseValue = value; } } } } // ---- plugins/TortalPortal.dll :: ServerSync.ConfigurationManagerAttributes ---- namespace ServerSync { internal class ConfigurationManagerAttributes { [UsedImplicitly] public bool? ReadOnly = false; } } // ---- plugins/TortalPortal.dll :: ServerSync.ConfigSync ---- namespace ServerSync { [PublicAPI] public class ConfigSync { [HarmonyPatch(typeof(ZRpc), "HandlePackage")] private static class SnatchCurrentlyHandlingRPC { public static ZRpc? currentRpc; [HarmonyPrefix] private static void Prefix(ZRpc __instance) { currentRpc = __instance; } } [HarmonyPatch(typeof(ZNet), "Awake")] internal static class RegisterRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance) { isServer = __instance.IsServer(); foreach (ConfigSync configSync2 in configSyncs) { ZRoutedRpc.instance.Register(configSync2.Name + " ConfigSync", configSync2.RPC_FromOtherClientConfigSync); if (isServer) { configSync2.InitialSyncDone = true; Debug.Log("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"); } } if (isServer) { __instance.StartCoroutine(WatchAdminListChanges()); } static void SendAdmin(List peers, bool isAdmin) { ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1] { new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = isAdmin } }); ConfigSync configSync = configSyncs.First(); if (configSync != null) { ZNet.instance.StartCoroutine(configSync.sendZPackage(peers, package)); } } static IEnumerator WatchAdminListChanges() { MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId"); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); List CurrentList = new List(adminList.GetList()); while (true) { yield return new WaitForSeconds(30f); if (!adminList.GetList().SequenceEqual(CurrentList)) { CurrentList = new List(adminList.GetList()); List list = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); return ((object)listContainsId != null) ? ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })) : adminList.Contains(hostName); }).ToList(); SendAdmin(ZNet.instance.GetPeers().Except(list).ToList(), isAdmin: false); SendAdmin(list, isAdmin: true); } } } } } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] private static class RegisterClientRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance, ZNetPeer peer) { if (__instance.IsServer()) { return; } foreach (ConfigSync configSync in configSyncs) { peer.m_rpc.Register(configSync.Name + " ConfigSync", configSync.RPC_FromServerConfigSync); } } } private class ParsedConfigs { public readonly Dictionary configValues = new Dictionary(); public readonly Dictionary customValues = new Dictionary(); } [HarmonyPatch(typeof(ZNet), "Shutdown")] private class ResetConfigsOnShutdown { [HarmonyPostfix] private static void Postfix() { ProcessingServerUpdate = true; foreach (ConfigSync configSync in configSyncs) { configSync.resetConfigsFromServer(); configSync.IsSourceOfTruth = true; configSync.InitialSyncDone = false; } ProcessingServerUpdate = false; } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] private class SendConfigsAfterLogin { private class BufferingSocket(ISocket original) : ZPlayFabSocket, ISocket { public volatile bool finished; public volatile int versionMatchQueued = -1; public readonly List Package = new List(); public readonly ISocket Original = original; public new bool IsConnected() { return Original.IsConnected(); } public new ZPackage Recv() { return Original.Recv(); } public new int GetSendQueueSize() { return Original.GetSendQueueSize(); } public new int GetCurrentSendRate() { return Original.GetCurrentSendRate(); } public new bool IsHost() { return Original.IsHost(); } public new void Dispose() { Original.Dispose(); } public new bool GotNewData() { return Original.GotNewData(); } public new void Close() { Original.Close(); } public new string GetEndPointString() { return Original.GetEndPointString(); } public new void GetAndResetStats(out int totalSent, out int totalRecv) { Original.GetAndResetStats(out totalSent, out totalRecv); } public new void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec) { Original.GetConnectionQuality(out localQuality, out remoteQuality, out ping, out outByteSec, out inByteSec); } public new ISocket Accept() { return Original.Accept(); } public new int GetHostPort() { return Original.GetHostPort(); } public new bool Flush() { return Original.Flush(); } public new string GetHostName() { return Original.GetHostName(); } public new void VersionMatch() { if (finished) { Original.VersionMatch(); } else { versionMatchQueued = Package.Count; } } public new void Send(ZPackage pkg) { int pos = pkg.GetPos(); pkg.SetPos(0); int num = pkg.ReadInt(); if ((num == "PeerInfo".GetStableHashCode() || num == "RoutedRPC".GetStableHashCode() || num == "ZDOData".GetStableHashCode()) && !finished) { ZPackage zPackage = new ZPackage(pkg.GetArray()); zPackage.SetPos(pos); Package.Add(zPackage); } else { pkg.SetPos(pos); Original.Send(pkg); } } } [HarmonyPriority(800)] [HarmonyPrefix] private static void Prefix(ref Dictionary? __state, ZNet __instance, ZRpc rpc) { if (!__instance.IsServer()) { return; } BufferingSocket bufferingSocket = new BufferingSocket(rpc.GetSocket()); AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket); if (AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }).Invoke(__instance, new object[1] { rpc }) is ZNetPeer obj && ZNet.m_onlineBackend != OnlineBackendType.Steamworks) { FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket"); if (fieldInfo.GetValue(obj) is ZPlayFabSocket zPlayFabSocket) { typeof(ZPlayFabSocket).GetField("m_remotePlayerId").SetValue(bufferingSocket, zPlayFabSocket.m_remotePlayerId); } fieldInfo.SetValue(obj, bufferingSocket); } if (__state == null) { __state = new Dictionary(); } __state[Assembly.GetExecutingAssembly()] = bufferingSocket; } [HarmonyPostfix] private static void Postfix(Dictionary __state, ZNet __instance, ZRpc rpc) { ZNetPeer peer; if (__instance.IsServer()) { object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }).Invoke(__instance, new object[1] { rpc }); peer = obj as ZNetPeer; if (peer == null) { SendBufferedData(); } else { __instance.StartCoroutine(sendAsync()); } } IEnumerator sendAsync() { foreach (ConfigSync configSync in configSyncs) { List list = new List(); if (configSync.CurrentVersion != null) { list.Add(new PackageEntry { section = "Internal", key = "serverversion", type = typeof(string), value = configSync.CurrentVersion }); } MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId"); SyncedList syncedList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); list.Add(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = (((object)methodInfo == null) ? ((object)syncedList.Contains(rpc.GetSocket().GetHostName())) : methodInfo.Invoke(ZNet.instance, new object[2] { syncedList, rpc.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, list, partial: false); yield return __instance.StartCoroutine(configSync.sendZPackage(new List { peer }, package)); } SendBufferedData(); } void SendBufferedData() { if (rpc.GetSocket() is BufferingSocket bufferingSocket) { AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original); if (AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }).Invoke(__instance, new object[1] { rpc }) is ZNetPeer obj2) { AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(obj2, bufferingSocket.Original); } } BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()]; bufferingSocket2.finished = true; for (int i = 0; i < bufferingSocket2.Package.Count; i++) { if (i == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } bufferingSocket2.Original.Send(bufferingSocket2.Package[i]); } if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } } } } private class PackageEntry { public string section; public string key; public Type type; public object? value; } [HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")] private static class PreventSavingServerInfo { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, ref string __result) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase)) { return true; } __result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType); return false; } } [HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")] private static class PreventConfigRereadChangingValues { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, string value) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null) { return true; } try { ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType); } catch (Exception ex) { Debug.LogWarning($"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}"); } return false; } } private class InvalidDeserializationTypeException : Exception { public string expected; public string received; public string field = ""; } public static bool ProcessingServerUpdate; public readonly string Name; public string? DisplayName; public string? CurrentVersion; public string? MinimumRequiredVersion; public bool ModRequired; private bool? forceConfigLocking; private bool isSourceOfTruth = true; private static readonly HashSet configSyncs; private readonly HashSet allConfigs = new HashSet(); private HashSet allCustomValues = new HashSet(); private static bool isServer; private static bool lockExempt; private OwnConfigEntryBase? lockedConfig; private const byte PARTIAL_CONFIGS = 1; private const byte FRAGMENTED_CONFIG = 2; private const byte COMPRESSED_CONFIG = 4; private readonly Dictionary> configValueCache = new Dictionary>(); private readonly List> cacheExpirations = new List>(); private static long packageCounter; public bool IsLocked { get { bool? flag = forceConfigLocking; bool num; if (!flag.HasValue) { if (lockedConfig == null) { goto IL_0051; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag == true; } if (num) { return !lockExempt; } goto IL_0051; IL_0051: return false; } set { forceConfigLocking = value; } } public bool IsAdmin { get { if (!lockExempt) { return isSourceOfTruth; } return true; } } public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } public event Action? SourceOfTruthChanged; private event Action? lockedConfigChanged; static ConfigSync() { ProcessingServerUpdate = false; configSyncs = new HashSet(); lockExempt = false; packageCounter = 0L; RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle); } public ConfigSync(string name) { Name = name; configSyncs.Add(this); new VersionCheck(this); } public SyncedConfigEntry AddConfigEntry(ConfigEntry configEntry) { OwnConfigEntryBase ownConfigEntryBase = configData(configEntry); SyncedConfigEntry syncedEntry = ownConfigEntryBase as SyncedConfigEntry; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry(configEntry); AccessTools.DeclaredField(typeof(ConfigDescription), "k__BackingField").SetValue(configEntry.Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(configEntry.Description.Tags ?? Array.Empty()).Concat(new SyncedConfigEntry[1] { syncedEntry }).ToArray()); configEntry.SettingChanged += delegate { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(ZRoutedRpc.Everybody, configEntry); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry AddLockingConfigEntry(ConfigEntry lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry(lockingConfig); lockingConfig.SettingChanged += delegate { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry)lockedConfig; } internal void AddCustomValue(CustomSyncedValueBase customValue) { if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier)) { throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)"); } allCustomValues.Add(customValue); allCustomValues = new HashSet(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority)); customValue.ValueChanged += delegate { if (!ProcessingServerUpdate) { Broadcast(ZRoutedRpc.Everybody, customValue); } }; } private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package) { lockedConfigChanged += serverLockedSettingChanged; IsSourceOfTruth = false; if (HandleConfigSyncRPC(0L, package, clientUpdate: false)) { InitialSyncDone = true; } } private void RPC_FromOtherClientConfigSync(long sender, ZPackage package) { HandleConfigSyncRPC(sender, package, clientUpdate: true); } private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate) { try { if (isServer && IsLocked) { string text = SnatchCurrentlyHandlingRPC.currentRpc?.GetSocket()?.GetHostName(); if (text != null) { MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId"); SyncedList syncedList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); if (!(((object)methodInfo == null) ? syncedList.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { syncedList, text })))) { return false; } } } cacheExpirations.RemoveAll(delegate(KeyValuePair kv) { if (kv.Key < DateTimeOffset.Now.Ticks) { configValueCache.Remove(kv.Value); return true; } return false; }); byte b = package.ReadByte(); if ((b & 2) != 0) { long num = package.ReadLong(); string text2 = sender.ToString() + num; if (!configValueCache.TryGetValue(text2, out var value)) { value = new SortedDictionary(); configValueCache[text2] = value; cacheExpirations.Add(new KeyValuePair(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2)); } int key = package.ReadInt(); int num2 = package.ReadInt(); value.Add(key, package.ReadByteArray()); if (value.Count < num2) { return false; } configValueCache.Remove(text2); package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray()); b = package.ReadByte(); } ProcessingServerUpdate = true; if ((b & 4) != 0) { MemoryStream stream = new MemoryStream(package.ReadByteArray()); MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress)) { deflateStream.CopyTo(memoryStream); } package = new ZPackage(memoryStream.ToArray()); b = package.ReadByte(); } if ((b & 1) == 0) { resetConfigsFromServer(); } ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package); ConfigFile configFile = null; bool saveOnConfigSet = false; foreach (KeyValuePair configValue in parsedConfigs.configValues) { if (!isServer && configValue.Key.LocalBaseValue == null) { configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue; } if (configFile == null) { configFile = configValue.Key.BaseConfig.ConfigFile; saveOnConfigSet = configFile.SaveOnConfigSet; configFile.SaveOnConfigSet = false; } configValue.Key.BaseConfig.BoxedValue = configValue.Value; } if (configFile != null) { configFile.SaveOnConfigSet = saveOnConfigSet; configFile.Save(); } foreach (KeyValuePair customValue in parsedConfigs.customValues) { if (!isServer) { CustomSyncedValueBase key2 = customValue.Key; if (key2.LocalBaseValue == null) { key2.LocalBaseValue = customValue.Key.BoxedValue; } } customValue.Key.BoxedValue = customValue.Value; } Debug.Log(string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name)); if (!isServer) { serverLockedSettingChanged(); } return true; } finally { ProcessingServerUpdate = false; } } private ParsedConfigs ReadConfigsFromPackage(ZPackage package) { ParsedConfigs parsedConfigs = new ParsedConfigs(); Dictionary dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c); Dictionary dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c); int num = package.ReadInt(); for (int num2 = 0; num2 < num; num2++) { string text = package.ReadString(); string text2 = package.ReadString(); string text3 = package.ReadString(); Type type = Type.GetType(text3); if (text3 == "" || type != null) { object obj; try { obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type)); } catch (InvalidDeserializationTypeException ex) { Debug.LogWarning("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected); continue; } OwnConfigEntryBase value2; if (text == "Internal") { CustomSyncedValueBase value; if (text2 == "serverversion") { if (obj?.ToString() != CurrentVersion) { Debug.LogWarning("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")); } } else if (text2 == "lockexempt") { if (obj is bool flag) { lockExempt = flag; } } else if (dictionary2.TryGetValue(text2, out value)) { if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3) { parsedConfigs.customValues[value] = obj; continue; } Debug.LogWarning("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName); } } else if (dictionary.TryGetValue(text + "_" + text2, out value2)) { Type type2 = configType(value2.BaseConfig); if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3) { parsedConfigs.configValues[value2] = obj; continue; } Debug.LogWarning("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName); } else { Debug.LogWarning("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."); } continue; } Debug.LogWarning("Got invalid type " + text3 + ", abort reading of received configs"); return new ParsedConfigs(); } return parsedConfigs; } private static bool isWritableConfig(OwnConfigEntryBase config) { ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config)); if (configSync == null) { return true; } if (!configSync.IsSourceOfTruth && config.SynchronizedConfig && config.LocalBaseValue != null) { if (!configSync.IsLocked) { if (config == configSync.lockedConfig) { return lockExempt; } return true; } return false; } return true; } private void serverLockedSettingChanged() { foreach (OwnConfigEntryBase allConfig in allConfigs) { configAttribute(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig); } } private void resetConfigsFromServer() { ConfigFile configFile = null; bool saveOnConfigSet = false; foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null)) { if (configFile == null) { configFile = item.BaseConfig.ConfigFile; saveOnConfigSet = configFile.SaveOnConfigSet; configFile.SaveOnConfigSet = false; } item.BaseConfig.BoxedValue = item.LocalBaseValue; item.LocalBaseValue = null; } if (configFile != null) { configFile.SaveOnConfigSet = saveOnConfigSet; } foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null)) { item2.BoxedValue = item2.LocalBaseValue; item2.LocalBaseValue = null; } lockedConfigChanged -= serverLockedSettingChanged; serverLockedSettingChanged(); } private IEnumerator distributeConfigToPeers(ZNetPeer peer, ZPackage package) { ZRoutedRpc rpc = ZRoutedRpc.instance; if (rpc == null) { yield break; } byte[] data = package.GetArray(); if (data != null && data.LongLength > 250000) { int fragments = (int)(1 + (data.LongLength - 1) / 250000); long packageIdentifier = ++packageCounter; int fragment = 0; while (fragment < fragments) { foreach (bool item in waitForQueue()) { yield return item; } if (peer.m_socket.IsConnected()) { ZPackage zPackage = new ZPackage(); zPackage.Write((byte)2); zPackage.Write(packageIdentifier); zPackage.Write(fragment); zPackage.Write(fragments); zPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray()); SendPackage(zPackage); if (fragment != fragments - 1) { yield return true; } int num = fragment + 1; fragment = num; continue; } break; } yield break; } foreach (bool item2 in waitForQueue()) { yield return item2; } SendPackage(package); void SendPackage(ZPackage pkg) { string text = Name + " ConfigSync"; if (isServer) { peer.m_rpc.Invoke(text, pkg); } else { rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, pkg); } } IEnumerable waitForQueue() { float timeout = Time.time + 30f; while (peer.m_socket.GetSendQueueSize() > 20000) { if (Time.time > timeout) { Debug.Log($"Disconnecting {peer.m_uid} after 30 seconds config sending timeout"); peer.m_rpc.Invoke("Error", ZNet.ConnectionStatus.ErrorConnectFailed); ZNet.instance.Disconnect(peer); break; } yield return false; } } } private IEnumerator sendZPackage(long target, ZPackage package) { if (!ZNet.instance) { return Enumerable.Empty().GetEnumerator(); } List list = (List)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance); if (target != ZRoutedRpc.Everybody) { list = list.Where((ZNetPeer p) => p.m_uid == target).ToList(); } return sendZPackage(list, package); } private IEnumerator sendZPackage(List peers, ZPackage package) { if (!ZNet.instance) { yield break; } byte[] array = package.GetArray(); if (array != null && array.LongLength > 10000) { ZPackage zPackage = new ZPackage(); zPackage.Write((byte)4); MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(memoryStream, System.IO.Compression.CompressionLevel.Optimal)) { deflateStream.Write(array, 0, array.Length); } zPackage.Write(memoryStream.ToArray()); package = zPackage; } List> writers = (from p in peers where p.IsReady() select distributeConfigToPeers(p, package)).ToList(); writers.RemoveAll((IEnumerator writer) => !writer.MoveNext()); while (writers.Count > 0) { yield return null; writers.RemoveAll((IEnumerator writer) => !writer.MoveNext()); } } private void Broadcast(long target, params ConfigEntryBase[] configs) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(configs); ZNet.instance?.StartCoroutine(sendZPackage(target, package)); } } private void Broadcast(long target, params CustomSyncedValueBase[] customValues) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(null, customValues); ZNet.instance?.StartCoroutine(sendZPackage(target, package)); } } private static OwnConfigEntryBase? configData(ConfigEntryBase config) { return config.Description.Tags?.OfType().SingleOrDefault(); } public static SyncedConfigEntry? ConfigData(ConfigEntry config) { return config.Description.Tags?.OfType>().SingleOrDefault(); } private static T configAttribute(ConfigEntryBase config) { return config.Description.Tags.OfType().First(); } private static Type configType(ConfigEntryBase config) { return configType(config.SettingType); } private static Type configType(Type type) { if (!type.IsEnum) { return type; } return Enum.GetUnderlyingType(type); } private static ZPackage ConfigsToPackage(IEnumerable? configs = null, IEnumerable? customValues = null, IEnumerable? packageEntries = null, bool partial = true) { List list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List(); List list2 = customValues?.ToList() ?? new List(); ZPackage zPackage = new ZPackage(); zPackage.Write(partial ? ((byte)1) : ((byte)0)); zPackage.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0)); foreach (PackageEntry item in packageEntries ?? Array.Empty()) { AddEntryToPackage(zPackage, item); } foreach (CustomSyncedValueBase item2 in list2) { AddEntryToPackage(zPackage, new PackageEntry { section = "Internal", key = item2.Identifier, type = item2.Type, value = item2.BoxedValue }); } foreach (ConfigEntryBase item3 in list) { AddEntryToPackage(zPackage, new PackageEntry { section = item3.Definition.Section, key = item3.Definition.Key, type = configType(item3), value = item3.BoxedValue }); } return zPackage; } private static void AddEntryToPackage(ZPackage package, PackageEntry entry) { package.Write(entry.section); package.Write(entry.key); package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type)); AddValueToZPackage(package, entry.value); } private static string GetZPackageTypeString(Type type) { return type.AssemblyQualifiedName; } private static void AddValueToZPackage(ZPackage package, object? value) { Type type = value?.GetType(); if (value is Enum) { value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture); } else { if (value is ICollection collection) { package.Write(collection.Count); { foreach (object item in collection) { AddValueToZPackage(package, item); } return; } } if ((object)type != null && type.IsValueType && !type.IsPrimitive) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); package.Write(fields.Length); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { package.Write(GetZPackageTypeString(fieldInfo.FieldType)); AddValueToZPackage(package, fieldInfo.GetValue(value)); } return; } } ZRpc.Serialize(new object[1] { value }, ref package); } private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type) { if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); int num = package.ReadInt(); if (num != fields.Length) { throw new InvalidDeserializationTypeException { received = $"(field count: {num})", expected = $"(field count: {fields.Length})" }; } object uninitializedObject = FormatterServices.GetUninitializedObject(type); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { string text = package.ReadString(); if (text != GetZPackageTypeString(fieldInfo.FieldType)) { throw new InvalidDeserializationTypeException { received = text, expected = GetZPackageTypeString(fieldInfo.FieldType), field = fieldInfo.Name }; } fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType)); } return uninitializedObject; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >)) { int num2 = package.ReadInt(); IDictionary dictionary = (IDictionary)Activator.CreateInstance(type); Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments); FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic); for (int j = 0; j < num2; j++) { object obj = ReadValueWithTypeFromZPackage(package, type2); dictionary.Add(field.GetValue(obj), field2.GetValue(obj)); } return dictionary; } if (type != typeof(List) && type.IsGenericType) { Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]); if ((object)type3 != null && type3.IsAssignableFrom(type)) { int num3 = package.ReadInt(); object obj2 = Activator.CreateInstance(type); MethodInfo method = type3.GetMethod("Add"); for (int k = 0; k < num3; k++) { method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) }); } return obj2; } } ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo)); AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type); List parameters = new List(); ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref parameters); return parameters.First(); } } } // ---- plugins/TortalPortal.dll :: ServerSync.VersionCheck ---- namespace ServerSync { [PublicAPI] [HarmonyPatch] public class VersionCheck { private static readonly HashSet versionChecks; private static readonly Dictionary notProcessedNames; public string Name; private string? displayName; private string? currentVersion; private string? minimumRequiredVersion; public bool ModRequired = true; private string? ReceivedCurrentVersion; private string? ReceivedMinimumRequiredVersion; private readonly List ValidatedClients = new List(); private ConfigSync? ConfigSync; public string DisplayName { get { return displayName ?? Name; } set { displayName = value; } } public string CurrentVersion { get { return currentVersion ?? "0.0.0"; } set { currentVersion = value; } } public string MinimumRequiredVersion { get { string text = minimumRequiredVersion; if (text == null) { if (!ModRequired) { return "0.0.0"; } text = CurrentVersion; } return text; } set { minimumRequiredVersion = value; } } private static void PatchServerSync() { Patches patchInfo = PatchProcessor.GetPatchInfo(AccessTools.DeclaredMethod(typeof(ZNet), "Awake")); if (patchInfo != null && patchInfo.Postfixes.Count((Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0) { return; } Harmony harmony = new Harmony("org.bepinex.helpers.ServerSync"); foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) }) where t.IsClass select t) { harmony.PatchAll(item); } } static VersionCheck() { versionChecks = new HashSet(); notProcessedNames = new Dictionary(); typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1] { new Action(PatchServerSync) }); } public VersionCheck(string name) { Name = name; ModRequired = true; versionChecks.Add(this); } public VersionCheck(ConfigSync configSync) { ConfigSync = configSync; Name = ConfigSync.Name; versionChecks.Add(this); } public void Initialize() { ReceivedCurrentVersion = null; ReceivedMinimumRequiredVersion = null; if (ConfigSync != null) { Name = ConfigSync.Name; DisplayName = ConfigSync.DisplayName; CurrentVersion = ConfigSync.CurrentVersion; MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion; ModRequired = ConfigSync.ModRequired; } } private bool IsVersionOk() { if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null) { return !ModRequired; } bool num = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion); bool flag = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion); return num && flag; } private string ErrorClient() { if (ReceivedMinimumRequiredVersion == null) { return DisplayName + " is not installed on the server."; } if (!(new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion))) { return DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". You have version " + CurrentVersion + "."; } return DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + "."; } private string ErrorServer(ZRpc rpc) { return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion; } private string Error(ZRpc? rpc = null) { if (rpc != null) { return ErrorServer(rpc); } return ErrorClient(); } private static VersionCheck[] GetFailedClient() { return versionChecks.Where((VersionCheck check) => !check.IsVersionOk()).ToArray(); } private static VersionCheck[] GetFailedServer(ZRpc rpc) { return versionChecks.Where((VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc)).ToArray(); } private static void Logout() { Game.instance.Logout(); AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, ZNet.ConnectionStatus.ErrorVersion); } private static void DisconnectClient(ZRpc rpc) { rpc.Invoke("Error", 3); } private static void CheckVersion(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, null); } private static void CheckVersion(ZRpc rpc, ZPackage pkg, Action? original) { string text = pkg.ReadString(); string text2 = pkg.ReadString(); string text3 = pkg.ReadString(); bool flag = false; foreach (VersionCheck versionCheck in versionChecks) { if (!(text != versionCheck.Name)) { Debug.Log("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + "."); versionCheck.ReceivedMinimumRequiredVersion = text2; versionCheck.ReceivedCurrentVersion = text3; if (ZNet.instance.IsServer() && versionCheck.IsVersionOk()) { versionCheck.ValidatedClients.Add(rpc); } flag = true; } } if (flag) { return; } pkg.SetPos(0); if (original != null) { original(rpc, pkg); if (pkg.GetPos() == 0) { notProcessedNames.Add(text, text3); } } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] [HarmonyPrefix] private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance) { VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient()); if (array.Length == 0) { return true; } VersionCheck[] array2 = array; for (int i = 0; i < array2.Length; i++) { Debug.LogWarning(array2[i].Error(rpc)); } if (__instance.IsServer()) { DisconnectClient(rpc); } else { Logout(); } return false; } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] [HarmonyPrefix] private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance) { notProcessedNames.Clear(); IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc); if (dictionary.Contains("ServerSync VersionCheck".GetStableHashCode())) { object obj = dictionary["ServerSync VersionCheck".GetStableHashCode()]; Action action = (Action)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj); peer.m_rpc.Register("ServerSync VersionCheck", delegate(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, action); }); } else { peer.m_rpc.Register("ServerSync VersionCheck", CheckVersion); } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.Initialize(); if (versionCheck.ModRequired || __instance.IsServer()) { Debug.Log("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + "."); ZPackage zPackage = new ZPackage(); zPackage.Write(versionCheck.Name); zPackage.Write(versionCheck.MinimumRequiredVersion); zPackage.Write(versionCheck.CurrentVersion); peer.m_rpc.Invoke("ServerSync VersionCheck", zPackage); } } } [HarmonyPatch(typeof(ZNet), "Disconnect")] [HarmonyPrefix] private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance) { if (!__instance.IsServer()) { return; } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.ValidatedClients.Remove(peer.m_rpc); } } [HarmonyPatch(typeof(FejdStartup), "ShowConnectError")] [HarmonyPostfix] private static void ShowConnectionError(FejdStartup __instance) { if (!__instance.m_connectionFailedPanel.activeSelf || ZNet.GetConnectionStatus() != ZNet.ConnectionStatus.ErrorVersion) { return; } bool flag = false; VersionCheck[] failedClient = GetFailedClient(); if (failedClient.Length != 0) { string text = string.Join("\n", failedClient.Select((VersionCheck check) => check.Error())); TMP_Text connectionFailedError = __instance.m_connectionFailedError; connectionFailedError.text = connectionFailedError.text + "\n" + text; flag = true; } foreach (KeyValuePair item in notProcessedNames.OrderBy((KeyValuePair kv) => kv.Key)) { if (!__instance.m_connectionFailedError.text.Contains(item.Key)) { TMP_Text connectionFailedError2 = __instance.m_connectionFailedError; connectionFailedError2.text = connectionFailedError2.text + "\nServer expects you to have " + item.Key + " (Version: " + item.Value + ") installed."; flag = true; } } if (flag) { RectTransform component = __instance.m_connectionFailedPanel.transform.Find("Image").GetComponent(); Vector2 sizeDelta = component.sizeDelta; sizeDelta.x = 675f; component.sizeDelta = sizeDelta; __instance.m_connectionFailedError.ForceMeshUpdate(); float num = __instance.m_connectionFailedError.renderedHeight + 105f; RectTransform component2 = component.transform.Find("ButtonOk").GetComponent(); component2.anchoredPosition = new Vector2(component2.anchoredPosition.x, component2.anchoredPosition.y - (num - component.sizeDelta.y) / 2f); sizeDelta = component.sizeDelta; sizeDelta.y = num; component.sizeDelta = sizeDelta; } } } } // ---- plugins/TortalPortal.dll :: TortalPortal.FilterMode ---- namespace TortalPortal { public enum FilterMode { Vanilla, WhitelistBlacklist, BypassAll } } // ---- plugins/TortalPortal.dll :: TortalPortal.Configuration ---- namespace TortalPortal { public static class Configuration { public static ConfigSync configSync = new ConfigSync("wubarrk.TortalPortal") { DisplayName = "Total Portal Control System", CurrentVersion = "1.0.0", MinimumRequiredVersion = "1.0.0" }; public static ConfigEntry filterMode; public static ConfigEntry whitelistItems; public static ConfigEntry blacklistItems; public static ConfigEntry maxPortalsPerPlayer; public static ConfigEntry adminBypass; public static ConfigEntry allowTames; public static ConfigEntry enableCustomVFX; public static ConfigEntry vfxOrbHeightOffset; public static ConfigEntry enablePortalCameraShot; public static ConfigEntry snapshotRefreshIntervalMinutes; public static ConfigEntry uiTextScale; public static ConfigEntry enableDebugMode; public static void Init(ConfigFile config) { filterMode = config.Bind("1 - General", "FilterMode", FilterMode.Vanilla, "Determines how portal item filters behave: Vanilla, WhitelistBlacklist, BypassAll (everything allowed)."); whitelistItems = config.Bind("1 - General", "WhitelistItems", "", "Comma-separated list of prefab names. If populated, ONLY these items can be teleported."); blacklistItems = config.Bind("1 - General", "BlacklistItems", "", "Comma-separated list of prefab names. Any item here CANNOT be teleported."); maxPortalsPerPlayer = config.Bind("2 - Limits", "MaxPortalsPerPlayer", 0, "Maximum portals a single player can place. 0 means unlimited."); adminBypass = config.Bind("2 - Limits", "AdminBypass", defaultValue: true, "Allows admins to bypass max portal limits, PIN locks, and item filters."); allowTames = config.Bind("3 - Features", "AllowTames", defaultValue: true, "If true, tameable creatures near the player will teleport with them."); enableCustomVFX = config.Bind("3 - Features", "EnableCustomVFX", defaultValue: true, "Replaces vanilla portal VFX with a custom procedural green runic gateway."); vfxOrbHeightOffset = config.Bind("3 - Features", "VFXOrbHeightOffset", 0f, "Vertical nudge in metres for the rune orb inside the gate. The orb is auto-centred on each portal's own arch, so this is only for fine-tuning."); enablePortalCameraShot = config.Bind("3 - Features", "EnablePortalCameraShot", defaultValue: true, "If true, takes a camera snapshot when a portal is placed for the UI preview."); snapshotRefreshIntervalMinutes = config.Bind("3 - Features", "SnapshotRefreshIntervalMinutes", 30, "Interval in minutes for the background coroutine to refresh active portal snapshots. Set to 0 to disable."); uiTextScale = config.Bind("3 - Features", "UITextScale", 1f, new ConfigDescription("Scales all text in the portal windows. 1 is the designed size.", new AcceptableValueRange(0.6f, 2f))); enableDebugMode = config.Bind("4 - Debug", "EnableDebugLogging", defaultValue: false, "Enable verbose logging to the console for debugging UI and teleportation events."); configSync.AddConfigEntry(filterMode); configSync.AddConfigEntry(whitelistItems); configSync.AddConfigEntry(blacklistItems); configSync.AddConfigEntry(maxPortalsPerPlayer); configSync.AddConfigEntry(adminBypass); configSync.AddConfigEntry(allowTames); configSync.AddConfigEntry(enableCustomVFX); configSync.AddConfigEntry(enablePortalCameraShot); configSync.AddConfigEntry(snapshotRefreshIntervalMinutes); } public static bool IsAdmin() { if (adminBypass.Value) { return configSync.IsAdmin; } return false; } public static void LogDebug(string msg) { if (enableDebugMode != null && enableDebugMode.Value) { Plugin.Log.LogInfo("[TortalPortal Debug] " + msg); } } } } // ---- plugins/TortalPortal.dll :: TortalPortal.FilterPatch ---- namespace TortalPortal { [HarmonyPatch] public static class FilterPatch { [HarmonyPatch(typeof(Humanoid), "IsTeleportable")] [HarmonyPrefix] public static bool HumanoidIsTeleportable_Prefix(Humanoid __instance, ref bool __result) { try { if (Configuration.IsAdmin() || Configuration.filterMode.Value == FilterMode.BypassAll) { __result = true; return false; } if (Configuration.filterMode.Value == FilterMode.Vanilla) { return true; } List allItems = __instance.GetInventory().GetAllItems(); string[] array = (from s in Configuration.whitelistItems.Value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries) select s.Trim()).ToArray(); string[] array2 = (from s in Configuration.blacklistItems.Value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries) select s.Trim()).ToArray(); if (Configuration.filterMode.Value == FilterMode.WhitelistBlacklist) { bool flag = array.Length != 0; bool flag2 = array2.Length != 0; foreach (ItemDrop.ItemData item in allItems) { string value = item.m_dropPrefab?.name; bool teleportable = item.m_shared.m_teleportable; if (flag2 && !string.IsNullOrEmpty(value) && array2.Contains(value)) { __result = false; return false; } if ((!flag || string.IsNullOrEmpty(value) || !array.Contains(value)) && !teleportable) { __result = false; return false; } } __result = true; return false; } return true; } catch (Exception arg) { Plugin.Log.LogError(string.Format("TortalPortal: {0} failed, falling back to vanilla behavior. Reason: {1}", "HumanoidIsTeleportable_Prefix", arg)); return true; } } [HarmonyPatch(typeof(Inventory), "IsTeleportable")] [HarmonyPrefix] public static bool InventoryIsTeleportable_Prefix(Inventory __instance, ref bool __result) { try { if (Configuration.IsAdmin() || Configuration.filterMode.Value == FilterMode.BypassAll) { __result = true; return false; } if (Configuration.filterMode.Value == FilterMode.Vanilla) { return true; } List allItems = __instance.GetAllItems(); string[] array = (from s in Configuration.whitelistItems.Value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries) select s.Trim()).ToArray(); string[] array2 = (from s in Configuration.blacklistItems.Value.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries) select s.Trim()).ToArray(); if (Configuration.filterMode.Value == FilterMode.WhitelistBlacklist) { bool flag = array.Length != 0; bool flag2 = array2.Length != 0; foreach (ItemDrop.ItemData item in allItems) { string value = item.m_dropPrefab?.name; bool teleportable = item.m_shared.m_teleportable; if (flag2 && !string.IsNullOrEmpty(value) && array2.Contains(value)) { __result = false; return false; } if ((!flag || string.IsNullOrEmpty(value) || !array.Contains(value)) && !teleportable) { __result = false; return false; } } __result = true; return false; } return true; } catch (Exception arg) { Plugin.Log.LogError(string.Format("TortalPortal: {0} failed, falling back to vanilla behavior. Reason: {1}", "InventoryIsTeleportable_Prefix", arg)); return true; } } } } // ---- plugins/TortalPortal.dll :: TortalPortal.PlacementPatch ---- namespace TortalPortal { [HarmonyPatch] [HarmonyPatch] public static class PlacementPatch { private const float CameraForwardOffset = 2f; private const float CameraHeight = 1.7f; private const float CameraPitch = 8f; private const float CameraFieldOfView = 78f; [HarmonyPatch(typeof(ZNet), "Start")] [HarmonyPostfix] public static void ZNet_Start_Postfix() { InitializeBackgroundSnapshot(); } [HarmonyPatch(typeof(Player), "UpdatePlacement")] [HarmonyPrefix] public static void Player_UpdatePlacement_Prefix(Player __instance, ref bool __state) { try { if ((bool)__instance.m_placementMarkerInstance) { Piece component = __instance.m_placementMarkerInstance.GetComponent(); if (component != null && component.GetComponent() != null) { __state = true; } } } catch (Exception arg) { Plugin.Log.LogError(string.Format("TortalPortal: {0} failed (non-fatal). Reason: {1}", "Player_UpdatePlacement_Prefix", arg)); } } [HarmonyPatch(typeof(Player), "PlacePiece")] [HarmonyPrefix] public static bool Player_PlacePiece_Prefix(Player __instance, Piece piece, out bool __state) { __state = false; try { if (piece == null || piece.GetComponent() == null) { return true; } int value = Configuration.maxPortalsPerPlayer.Value; if (value > 0 && !Configuration.IsAdmin() && CountPlayerPortals(Game.instance.GetPlayerProfile().GetPlayerID()) >= value) { __instance.Message(MessageHud.MessageType.Center, $"Maximum portals reached ({value})."); return false; } __state = true; return true; } catch (Exception arg) { Plugin.Log.LogError(string.Format("TortalPortal: {0} failed, falling back to vanilla placement. Reason: {1}", "Player_PlacePiece_Prefix", arg)); return true; } } [HarmonyPatch(typeof(Player), "PlacePiece")] [HarmonyPostfix] public static void Player_PlacePiece_Postfix(Player __instance, Piece piece, Vector3 pos, Quaternion rot, bool __state) { try { if (__state && !(piece == null) && piece.GetComponent() != null && Configuration.enablePortalCameraShot.Value) { Plugin.Instance.StartCoroutine(FindAndSnapshotRoutine(pos)); } } catch (Exception arg) { Plugin.Log.LogError(string.Format("TortalPortal: {0} failed (non-fatal). Reason: {1}", "Player_PlacePiece_Postfix", arg)); } } private static IEnumerator FindAndSnapshotRoutine(Vector3 pos) { yield return new WaitForSeconds(0.5f); Collider[] array = Physics.OverlapSphere(pos, 2f); TeleportWorld teleportWorld = null; Collider[] array2 = array; for (int i = 0; i < array2.Length; i++) { TeleportWorld componentInParent = array2[i].GetComponentInParent(); if (componentInParent != null) { teleportWorld = componentInParent; break; } } if (teleportWorld != null) { yield return Plugin.Instance.StartCoroutine(TakeSnapshotRoutine(teleportWorld.transform)); } } public static List GetAllPortals() { List list = new List(); if (ZDOMan.instance == null) { return list; } int index = 0; while (!ZDOMan.instance.GetAllZDOsWithPrefabIterative("portal_wood", list, ref index)) { } index = 0; while (!ZDOMan.instance.GetAllZDOsWithPrefabIterative("portal_stone", list, ref index)) { } index = 0; while (!ZDOMan.instance.GetAllZDOsWithPrefabIterative("portal_blackmarble", list, ref index)) { } return list; } private static int CountPlayerPortals(long playerID) { int num = 0; foreach (ZDO allPortal in GetAllPortals()) { if (allPortal.GetLong(ZDOVars.s_creator, 0L) == playerID) { num++; } } return num; } private static IEnumerator TakeSnapshotRoutine(Transform portalTransform) { yield return new WaitForEndOfFrame(); TakeSnapshotCore(portalTransform); } public static void InitializeBackgroundSnapshot() { if (ZNet.instance != null && ZNet.instance.IsServer()) { Plugin.Instance.StartCoroutine(BackgroundSnapshotRoutine()); } } private static IEnumerator BackgroundSnapshotRoutine() { while (true) { int value = Configuration.snapshotRefreshIntervalMinutes.Value; if (value <= 0) { yield return new WaitForSeconds(60f); continue; } yield return new WaitForSeconds((float)value * 60f); if (ZNetScene.instance == null || ZDOMan.instance == null) { continue; } List allPortals = GetAllPortals(); int num = 0; foreach (ZDO item in allPortals) { ZNetView zNetView = ZNetScene.instance.FindInstance(item); if (!(zNetView != null)) { continue; } TeleportWorld component = zNetView.GetComponent(); if (component != null) { Plugin.Instance.StartCoroutine(TakeSnapshotRoutine(component.transform)); num++; if (num >= 3) { break; } } } } } private static void TakeSnapshotCore(Transform portalTransform) { GameObject gameObject = null; RenderTexture renderTexture = null; Texture2D texture2D = null; TortalPortalRuneVFX tortalPortalRuneVFX = null; try { gameObject = new GameObject("PortalSnapshotCam"); Camera camera = gameObject.AddComponent(); camera.enabled = false; Camera main = Camera.main; if (main != null) { camera.CopyFrom(main); } gameObject.transform.position = portalTransform.position + portalTransform.forward * 2f + Vector3.up * 1.7f; gameObject.transform.rotation = portalTransform.rotation * Quaternion.Euler(8f, 0f, 0f); camera.fieldOfView = 78f; camera.nearClipPlane = 0.15f; if (main == null) { camera.farClipPlane = 300f; } renderTexture = (camera.targetTexture = new RenderTexture(1280, 720, 24)); camera.ResetAspect(); tortalPortalRuneVFX = portalTransform.GetComponent(); if (tortalPortalRuneVFX != null) { tortalPortalRuneVFX.SetVisible(visible: false); } camera.Render(); if (tortalPortalRuneVFX != null) { tortalPortalRuneVFX.SetVisible(visible: true); tortalPortalRuneVFX = null; } RenderTexture.active = renderTexture; texture2D = new Texture2D(1280, 720, TextureFormat.RGB24, mipChain: false); texture2D.ReadPixels(new Rect(0f, 0f, 1280f, 720f), 0, 0); texture2D.Apply(); camera.targetTexture = null; RenderTexture.active = null; byte[] bytes = texture2D.EncodeToJPG(75); ZNetView component = portalTransform.GetComponent(); if ((bool)component && component.IsValid()) { component.GetZDO().Set("PortalSnapshot", bytes); } } catch (Exception arg) { Plugin.Log.LogError($"TortalPortal: Portal snapshot capture failed (non-fatal, portal placement unaffected). Reason: {arg}"); } finally { if (tortalPortalRuneVFX != null) { tortalPortalRuneVFX.SetVisible(visible: true); } RenderTexture.active = null; if (renderTexture != null) { UnityEngine.Object.Destroy(renderTexture); } if (gameObject != null) { UnityEngine.Object.Destroy(gameObject); } if (texture2D != null) { UnityEngine.Object.Destroy(texture2D); } } } } } // ---- plugins/TortalPortal.dll :: TortalPortal.Plugin ---- namespace TortalPortal { [BepInPlugin("wubarrk.TortalPortal", "TortalPortal", "1.0.0")] public class Plugin : BaseUnityPlugin { public const string PluginGUID = "wubarrk.TortalPortal"; public const string PluginName = "TortalPortal"; public const string PluginVersion = "1.0.0"; private readonly Harmony _harmony = new Harmony("wubarrk.TortalPortal"); private static readonly Type[] PatchTypes = new Type[6] { typeof(PlacementPatch), typeof(FilterPatch), typeof(PortalBehaviorPatch), typeof(SecurityPatch), typeof(TamesPatch), typeof(VFXPatch) }; public static Plugin Instance; public static ManualLogSource Log; private void Awake() { Instance = this; Log = base.Logger; Configuration.Init(base.Config); ApplyPatches(); try { VFXPatch.InitBundle(); } catch (Exception arg) { Log.LogError($"TortalPortal: VFX bundle failed to load, custom VFX will be disabled. Reason: {arg}"); } Log.LogInfo("TortalPortal v1.0.0 loaded successfully."); } private void ApplyPatches() { Type[] patchTypes = PatchTypes; foreach (Type type in patchTypes) { try { _harmony.PatchAll(type); Log.LogInfo("TortalPortal: Patched " + type.Name + " successfully."); } catch (Exception arg) { Log.LogError($"TortalPortal: Failed to patch {type.Name} - related feature(s) will be disabled. Reason: {arg}"); } } } } } // ---- plugins/TortalPortal.dll :: TortalPortal.PortalBehaviorPatch ---- namespace TortalPortal { [HarmonyPatch] public static class PortalBehaviorPatch { private static TeleportWorld _autoOpenedFor; private static ZDOID _arrivedThrough = ZDOID.None; public static void SuppressAutoOpenFor(ZDOID portalId) { _arrivedThrough = portalId; } [HarmonyPatch(typeof(TeleportWorld), "Awake")] [HarmonyPostfix] public static void TeleportWorld_Awake_Postfix(TeleportWorld __instance) { try { if (Configuration.enableCustomVFX.Value) { StripVanillaPortalVFX(__instance); if (__instance.gameObject.GetComponent() == null) { __instance.gameObject.AddComponent(); } } } catch (Exception arg) { Plugin.Log.LogError(string.Format("TortalPortal: {0} failed. Reason: {1}", "TeleportWorld_Awake_Postfix", arg)); } } private static void StripVanillaPortalVFX(TeleportWorld portal) { GameObject gameObject = ((portal.m_target_found != null) ? portal.m_target_found.gameObject : null); ParticleSystem[] componentsInChildren = portal.GetComponentsInChildren(includeInactive: true); foreach (ParticleSystem particleSystem in componentsInChildren) { if (!(particleSystem == null)) { particleSystem.Clear(withChildren: true); ParticleSystem.EmissionModule emission = particleSystem.emission; emission.enabled = false; if (particleSystem.gameObject != portal.gameObject && particleSystem.gameObject != gameObject) { particleSystem.gameObject.SetActive(value: false); } } } if (portal.m_connected != null) { portal.m_connected.m_effectPrefabs = new EffectList.EffectData[0]; } } [HarmonyPatch(typeof(TeleportWorld), "UpdatePortal")] [HarmonyPrefix] public static bool TeleportWorld_UpdatePortal_Prefix(TeleportWorld __instance, ref float ___m_colorAlpha, ref bool ___m_hadTarget) { try { ZNetView component = __instance.GetComponent(); if (component == null || !component.IsValid() || __instance.m_proximityRoot == null) { return true; } Player closestPlayer = Player.GetClosestPlayer(__instance.m_proximityRoot.position, __instance.m_activationRange); bool flag = closestPlayer != null && !closestPlayer.IsTeleporting(); bool flag2 = flag && closestPlayer == Player.m_localPlayer; bool flag3 = false; if (flag2) { flag3 = closestPlayer.IsTeleportable() || __instance.m_allowAllItems || Configuration.IsAdmin() || Configuration.filterMode.Value == FilterMode.BypassAll; if (!flag3) { Configuration.LogDebug("Local player is in range but cannot teleport (likely carrying restricted items)."); } } UpdatePortalVisuals(__instance, flag, flag3 && flag2, ref ___m_hadTarget); ZDOID uid = component.GetZDO().m_uid; if (flag2 && flag3) { if (_arrivedThrough == uid) { Configuration.LogDebug($"Arrived through portal ZDO {uid}. Holding its menu closed until the player leaves and returns."); _autoOpenedFor = __instance; _arrivedThrough = ZDOID.None; } else if (_autoOpenedFor != __instance && !PortalUIManager.IsUIVisible()) { Configuration.LogDebug($"Local player in range and can teleport. Showing UI for portal ZDO {uid}."); _autoOpenedFor = __instance; PortalUIManager.ShowUI(__instance); } } else if (!flag2) { if (_autoOpenedFor == __instance) { Configuration.LogDebug("Local player left range. Clearing auto-open state for this portal."); _autoOpenedFor = null; } if (PortalUIManager.IsUIVisible() && PortalUIManager.CurrentSourcePortal == __instance) { Configuration.LogDebug("Local player left range while UI was open. Hiding UI."); PortalUIManager.HideUI(); } } return false; } catch (Exception arg) { if (_autoOpenedFor == __instance) { _autoOpenedFor = null; } Plugin.Log.LogError(string.Format("TortalPortal: {0} failed, falling back to vanilla portal update. Reason: {1}", "TeleportWorld_UpdatePortal_Prefix", arg)); return true; } } private static void UpdatePortalVisuals(TeleportWorld portal, bool anyPlayerInRange, bool localCanTeleport, ref bool hadTarget) { try { if (anyPlayerInRange && !hadTarget && portal.m_connected != null) { portal.m_connected.Create(portal.transform.position, portal.transform.rotation); } if (portal.m_target_found != null) { portal.m_target_found.SetActive(localCanTeleport); } } catch (Exception arg) { Plugin.Log.LogError($"TortalPortal: portal visuals update failed (non-fatal, teleport menu unaffected). Reason: {arg}"); } finally { hadTarget = anyPlayerInRange; } } [HarmonyPatch(typeof(TeleportWorld), "Update")] [HarmonyPrefix] public static bool TeleportWorld_Update_Prefix(TeleportWorld __instance, ref float ___m_colorAlpha, ref bool ___m_hadTarget) { try { ___m_colorAlpha = Mathf.MoveTowards(___m_colorAlpha, ___m_hadTarget ? 1f : 0f, Time.deltaTime); __instance.m_model.material.SetColor("_EmissionColor", Color.Lerp(__instance.m_colorUnconnected, __instance.m_colorTargetfound, ___m_colorAlpha)); TortalPortalRuneVFX component = __instance.GetComponent(); if (component != null) { component.Charge = (___m_hadTarget ? 1f : 0.2f); } return false; } catch (Exception arg) { Plugin.Log.LogError(string.Format("TortalPortal: {0} failed, falling back to vanilla update. Reason: {1}", "TeleportWorld_Update_Prefix", arg)); return true; } } [HarmonyPatch(typeof(TeleportWorld), "Teleport")] [HarmonyPrefix] public static bool TeleportWorld_Teleport_Prefix() { try { return false; } catch (Exception arg) { Plugin.Log.LogError(string.Format("TortalPortal: {0} failed, falling back to vanilla teleport. Reason: {1}", "TeleportWorld_Teleport_Prefix", arg)); return true; } } } } // ---- plugins/TortalPortal.dll :: TortalPortal.PortalUIManager ---- namespace TortalPortal { public class PortalUIManager : MonoBehaviour { private sealed class PortalEntry { public ZDO Zdo; public string Tag; public string Pin; public string Creator; public Vector3 Pos; public Heightmap.Biome Biome; public float Distance; public string Label; public string SearchKey; public bool Locked; } private static PortalUIManager _instance; private bool _isVisible; private bool _isConfigMode; private readonly List _entries = new List(); private PortalEntry _selected; private string _searchFilter = ""; private Vector2 _scrollPos; private string _pinInput = ""; private bool _showPinPrompt; private Texture2D _previewTex; private bool _previewExpanded; private string _configName = ""; private string _configPin = ""; private bool _configHasPin; private static MethodInfo _loadImageMethod; public static TeleportWorld CurrentSourcePortal { get; private set; } public static void Init() { if (_instance == null) { GameObject obj = new GameObject("PortalUIManager"); _instance = obj.AddComponent(); UnityEngine.Object.DontDestroyOnLoad(obj); } } public static bool IsUIVisible() { if (_instance != null) { return _instance._isVisible; } return false; } public static void ShowUI(TeleportWorld sourcePortal) { Configuration.LogDebug("PortalUIManager.ShowUI called."); if (_instance == null) { Init(); } CurrentSourcePortal = sourcePortal; _instance._isConfigMode = false; _instance._isVisible = true; _instance.BuildEntries(); Configuration.LogDebug($"Found {_instance._entries.Count} destination portals."); if (Minimap.instance != null) { Configuration.LogDebug("Opening Large Minimap."); Minimap.instance.SetMapMode(Minimap.MapMode.Large); } } public static void ShowConfigUI(TeleportWorld targetPortal) { Configuration.LogDebug("PortalUIManager.ShowConfigUI called."); if (_instance == null) { Init(); } CurrentSourcePortal = targetPortal; _instance._isConfigMode = true; _instance._isVisible = true; ZDO zDO = targetPortal.GetComponent().GetZDO(); _instance._configName = zDO.GetString(ZDOVars.s_tag); _instance._configPin = zDO.GetString("PortalPIN"); _instance._configHasPin = !string.IsNullOrEmpty(_instance._configPin); if (Minimap.instance != null) { Minimap.instance.SetMapMode(Minimap.MapMode.None); } } public static void HideUI() { Configuration.LogDebug("PortalUIManager.HideUI called."); if (_instance != null) { _instance._isVisible = false; _instance._isConfigMode = false; _instance._selected = null; _instance._showPinPrompt = false; _instance._pinInput = ""; _instance._previewExpanded = false; _instance.ClearPreview(); } CurrentSourcePortal = null; if (Minimap.instance != null && Minimap.instance.m_mode == Minimap.MapMode.Large) { Configuration.LogDebug("Closing Large Minimap."); Minimap.instance.SetMapMode(Minimap.MapMode.None); } } private void BuildEntries() { _entries.Clear(); _selected = null; _showPinPrompt = false; _pinInput = ""; _previewExpanded = false; ClearPreview(); ZDOID zDOID = ZDOID.None; if (CurrentSourcePortal != null) { ZNetView component = CurrentSourcePortal.GetComponent(); if (component != null && component.IsValid()) { zDOID = component.GetZDO().m_uid; } } Vector3 a = ((Player.m_localPlayer != null) ? Player.m_localPlayer.transform.position : Vector3.zero); foreach (ZDO allPortal in PlacementPatch.GetAllPortals()) { if (allPortal != null && !(allPortal.m_uid == zDOID)) { string text = Sanitise(allPortal.GetString(ZDOVars.s_tag)); if (string.IsNullOrEmpty(text)) { text = "Unnamed portal"; } string text2 = Sanitise(allPortal.GetString(ZDOVars.s_creatorName)); if (string.IsNullOrEmpty(text2)) { text2 = "Unknown"; } Vector3 position = allPortal.GetPosition(); string text3 = allPortal.GetString("PortalPIN"); PortalEntry portalEntry = new PortalEntry { Zdo = allPortal, Tag = text, Pin = text3, Creator = text2, Pos = position, Biome = ((WorldGenerator.instance != null) ? WorldGenerator.instance.GetBiome(position) : Heightmap.Biome.None), Distance = Vector3.Distance(a, position), Locked = !string.IsNullOrEmpty(text3) }; portalEntry.SearchKey = text.ToLowerInvariant(); portalEntry.Label = "" + text + "" + (portalEntry.Locked ? " [LOCKED]" : "") + "\n" + PrettyBiome(portalEntry.Biome) + " · " + $"{Mathf.RoundToInt(portalEntry.Distance)}m · {text2}"; _entries.Add(portalEntry); } } _entries.Sort((PortalEntry portalEntry2, PortalEntry b) => string.Compare(portalEntry2.Tag, b.Tag, StringComparison.OrdinalIgnoreCase)); } private static string Sanitise(string s) { if (string.IsNullOrEmpty(s)) { return s; } return s.Replace('<', '(').Replace('>', ')'); } private static string PrettyBiome(Heightmap.Biome biome) { string text = biome.ToString(); StringBuilder stringBuilder = new StringBuilder(text.Length + 4); for (int i = 0; i < text.Length; i++) { if (i > 0 && char.IsUpper(text[i])) { stringBuilder.Append(' '); } stringBuilder.Append(text[i]); } return stringBuilder.ToString(); } private void OnGUI() { if (_isVisible) { TortalUITheme.EnsureBuilt(); if (!_isConfigMode && Minimap.instance != null && Minimap.instance.m_mode != Minimap.MapMode.Large) { HideUI(); } else if (_isConfigMode) { DrawConfigUI(); } else if (_previewExpanded && _previewTex != null && _selected != null) { DrawExpandedPreview(); } else { DrawSelectUI(); } } } private void DrawSelectUI() { float num = Mathf.Min((float)Screen.width - 120f, TortalUITheme.S(860f)); float num2 = Mathf.Min((float)Screen.height - 80f, TortalUITheme.S(660f)); float x = Mathf.Max(20f, Mathf.Min(52f, (float)Screen.width - num - 20f)); Rect win = new Rect(x, Mathf.Round(((float)Screen.height - num2) * 0.5f), num, num2); TortalUITheme.DrawWindow(win, "Total Portal Control"); Rect rect = TortalUITheme.Body(win); float num3 = Mathf.Round(rect.width * 0.54f); Rect rect2 = new Rect(rect.x, rect.y, num3, rect.height); Rect rect3 = new Rect(rect2.xMax + 20f, rect.y, rect.width - num3 - 20f, rect.height); float height = TortalUITheme.S(26f); float num4 = TortalUITheme.S(54f); Rect rect4 = new Rect(rect2.x, rect2.y, rect2.width, height); GUI.Label(new Rect(rect4.x, rect4.y, num4, rect4.height), "Search", TortalUITheme.Header); _searchFilter = GUI.TextField(new Rect(rect4.x + num4 + 4f, rect4.y, rect4.width - num4 - 4f, rect4.height), _searchFilter, 32, TortalUITheme.Field); float num5 = TortalUITheme.S(92f); if (GUI.Button(new Rect(rect3.xMax - num5, rect4.y, num5, height), "Close", TortalUITheme.Button)) { HideUI(); return; } Rect rect5 = new Rect(rect2.x, rect4.yMax + 12f, rect2.width, rect2.height - rect4.height - 12f); TortalUITheme.DrawInset(rect5); DrawPortalList(rect5); Rect area = new Rect(rect3.x, rect4.yMax + 12f, rect3.width, rect3.height - rect4.height - 12f); DrawDetails(area); GUI.Label(TortalUITheme.FooterLine(win), "Pick a destination to preview it · the map marks the selection · close the map to cancel", TortalUITheme.Footer); } private void DrawPortalList(Rect area) { GUILayout.BeginArea(new Rect(area.x + 4f, area.y + 4f, area.width - 8f, area.height - 8f)); _scrollPos = GUILayout.BeginScrollView(_scrollPos); string text = ((_searchFilter == null) ? "" : _searchFilter.ToLowerInvariant()); int num = 0; foreach (PortalEntry entry in _entries) { if (text.Length <= 0 || entry.SearchKey.IndexOf(text, StringComparison.Ordinal) >= 0) { num++; Rect rect = GUILayoutUtility.GetRect(GUIContent.none, TortalUITheme.Row, GUILayout.ExpandWidth(expand: true), GUILayout.Height(TortalUITheme.S(44f))); if (_selected == entry) { TortalUITheme.DrawSelection(rect); } if (GUI.Button(rect, entry.Label, TortalUITheme.Row)) { Select(entry); } } } if (num == 0) { GUILayout.Space(24f); GUILayout.Label((_entries.Count == 0) ? "No other portals discovered yet." : "Nothing matches that search.", TortalUITheme.Note); } GUILayout.EndScrollView(); GUILayout.EndArea(); } private void Select(PortalEntry e) { _selected = e; _showPinPrompt = e.Locked && !Configuration.IsAdmin(); _pinInput = ""; _previewExpanded = false; LoadPreview(e.Zdo); if (Minimap.instance != null) { Minimap.instance.ShowPointOnMap(e.Pos); } } private void DrawDetails(Rect area) { if (_selected == null) { GUI.Label(new Rect(area.x, area.y + area.height * 0.4f, area.width, TortalUITheme.S(40f)), "Select a portal from the list.", TortalUITheme.Note); return; } PortalEntry selected = _selected; float y = area.y; Rect rect = new Rect(area.x, y, area.width, Mathf.Round(area.width * 9f / 16f)); TortalUITheme.DrawInset(rect); if (_previewTex != null) { GUI.DrawTexture(new Rect(rect.x + 1f, rect.y + 1f, rect.width - 2f, rect.height - 2f), _previewTex, ScaleMode.ScaleAndCrop); } else { GUI.Label(rect, "No snapshot captured yet.", TortalUITheme.Note); } TortalUITheme.DrawOutline(rect, new Color(TortalUITheme.Gold.r, TortalUITheme.Gold.g, TortalUITheme.Gold.b, 0.8f), 1f); if (_previewTex != null && GUI.Button(rect, GUIContent.none, TortalUITheme.ImageButton)) { _previewExpanded = true; return; } y = rect.yMax + 4f; if (_previewTex != null) { GUI.Label(new Rect(area.x, y, area.width, TortalUITheme.S(16f)), "click the image to view it full size", TortalUITheme.Footer); } y += TortalUITheme.S(20f); GUI.Label(new Rect(area.x, y, area.width, TortalUITheme.S(24f)), selected.Tag, TortalUITheme.SubTitle); y += TortalUITheme.S(28f); TortalUITheme.DrawRule(new Rect(area.x, y, area.width, 1f)); y += TortalUITheme.S(14f); y = StatRow(area, y, "Owner", selected.Creator); y = StatRow(area, y, "Biome", PrettyBiome(selected.Biome)); y = StatRow(area, y, "Distance", $"{Mathf.RoundToInt(selected.Distance)} m"); y = StatRow(area, y, "Position", $"{(int)selected.Pos.x}, {(int)selected.Pos.y}, {(int)selected.Pos.z}"); StatRow(area, y, "Status", selected.Locked ? "Locked" : "Open"); float num = TortalUITheme.S(44f); Rect position = new Rect(area.x, area.yMax - num, area.width, num); if (_showPinPrompt) { float num2 = TortalUITheme.S(26f); float num3 = TortalUITheme.S(40f); Rect rect2 = new Rect(area.x, position.y - num2 - 8f, area.width, num2); GUI.Label(new Rect(rect2.x, rect2.y, num3, rect2.height), "PIN", TortalUITheme.Header); _pinInput = GUI.PasswordField(new Rect(rect2.x + num3 + 4f, rect2.y, rect2.width - num3 - 4f, rect2.height), _pinInput, '*', 10, TortalUITheme.Field); if (GUI.Button(position, "Unlock & Teleport", TortalUITheme.Primary)) { if (_pinInput == selected.Pin) { ExecuteTeleport(selected.Zdo); } else { Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Incorrect PIN!"); } } } else if (GUI.Button(position, "Teleport", TortalUITheme.Primary)) { ExecuteTeleport(selected.Zdo); } } private static float StatRow(Rect area, float y, string key, string value) { float num = TortalUITheme.S(84f); float num2 = TortalUITheme.S(20f); GUI.Label(new Rect(area.x, y, num, num2), key, TortalUITheme.Key); GUI.Label(new Rect(area.x + num + 4f, y, area.width - num - 4f, num2), value, TortalUITheme.Value); return y + num2 + 2f; } private void DrawExpandedPreview() { TortalUITheme.DrawFill(new Rect(0f, 0f, Screen.width, Screen.height), new Color(0f, 0f, 0f, 0.86f)); float num = ((_previewTex.height > 0) ? ((float)_previewTex.width / (float)_previewTex.height) : 1.7777778f); float num2 = 80f; float num3 = 36f + TortalUITheme.TitleHeight + TortalUITheme.FooterHeight; float num4 = Mathf.Max(240f, (float)Screen.width - 48f - num2); float num5 = Mathf.Max(160f, (float)Screen.height - 48f - num3); float num6 = num4; float num7 = num4 / num; if (num7 > num5) { num7 = num5; num6 = num5 * num; } Rect win = new Rect(Mathf.Round(((float)Screen.width - num6 - num2) * 0.5f), Mathf.Round(((float)Screen.height - num7 - num3) * 0.5f), Mathf.Round(num6 + num2), Mathf.Round(num7 + num3)); TortalUITheme.DrawWindow(win, _selected.Tag); Rect rect = TortalUITheme.Body(win); GUI.DrawTexture(rect, _previewTex, ScaleMode.ScaleToFit); TortalUITheme.DrawOutline(rect, new Color(TortalUITheme.Gold.r, TortalUITheme.Gold.g, TortalUITheme.Gold.b, 0.8f), 1f); GUI.Label(TortalUITheme.FooterLine(win), $"{PrettyBiome(_selected.Biome)} · {(int)_selected.Pos.x}, {(int)_selected.Pos.y}, {(int)_selected.Pos.z}" + " · click anywhere to close", TortalUITheme.Footer); if (GUI.Button(new Rect(0f, 0f, Screen.width, Screen.height), GUIContent.none, GUIStyle.none)) { _previewExpanded = false; } } private void DrawConfigUI() { float num = Mathf.Min((float)Screen.width - 80f, TortalUITheme.S(540f)); float num2 = Mathf.Min((float)Screen.height - 80f, TortalUITheme.S(440f)); Rect win = new Rect(Mathf.Round(((float)Screen.width - num) * 0.5f), Mathf.Round(((float)Screen.height - num2) * 0.5f), num, num2); TortalUITheme.DrawWindow(win, "Portal Configuration"); Rect rect = TortalUITheme.Body(win); float y = rect.y; float num3 = TortalUITheme.S(20f); float num4 = TortalUITheme.S(28f); float width = TortalUITheme.S(200f); GUI.Label(new Rect(rect.x, y, rect.width, num3), "Portal name", TortalUITheme.Header); y += num3 + 4f; _configName = GUI.TextField(new Rect(rect.x, y, rect.width, num4), _configName, 20, TortalUITheme.Field); y += num4 + 16f; if (GUI.Button(new Rect(rect.x, y, width, num4), _configHasPin ? "PIN lock: ON" : "PIN lock: OFF", TortalUITheme.Button)) { _configHasPin = !_configHasPin; } y += num4 + 12f; if (_configHasPin) { GUI.Label(new Rect(rect.x, y, rect.width, num3), "PIN", TortalUITheme.Header); y += num3 + 4f; _configPin = GUI.TextField(new Rect(rect.x, y, width, num4), _configPin, 10, TortalUITheme.Field); } float num5 = TortalUITheme.S(40f); Rect position = new Rect(rect.x, rect.yMax - num5, rect.width * 0.5f - 8f, num5); Rect position2 = new Rect(position.xMax + 16f, position.y, position.width, position.height); if (GUI.Button(position, "Save", TortalUITheme.Primary)) { string value = (_configHasPin ? _configPin : ""); ZDO zDO = CurrentSourcePortal.GetComponent().GetZDO(); zDO.Set(ZDOVars.s_tag, _configName); zDO.Set("PortalPIN", value); Player.m_localPlayer.Message(MessageHud.MessageType.Center, "Portal configuration saved."); HideUI(); } else if (GUI.Button(position2, "Cancel", TortalUITheme.Primary)) { HideUI(); } else { GUI.Label(TortalUITheme.FooterLine(win), "A PIN is required from anyone but you and the server admins.", TortalUITheme.Footer); } } private static void LoadImageViaReflection(Texture2D tex, byte[] data) { if (_loadImageMethod == null) { _loadImageMethod = typeof(ImageConversion).GetMethod("LoadImage", new Type[2] { typeof(Texture2D), typeof(byte[]) }); } _loadImageMethod.Invoke(null, new object[2] { tex, data }); } private void ClearPreview() { if (!(_previewTex == null)) { UnityEngine.Object.Destroy(_previewTex); _previewTex = null; } } private void LoadPreview(ZDO zdo) { ClearPreview(); byte[] byteArray = zdo.GetByteArray("PortalSnapshot"); if (byteArray != null && byteArray.Length != 0) { _previewTex = new Texture2D(2, 2); LoadImageViaReflection(_previewTex, byteArray); } } private void ExecuteTeleport(ZDO targetZdo) { Configuration.LogDebug($"ExecuteTeleport called for ZDO {targetZdo.m_uid}"); if (CurrentSourcePortal == null) { Configuration.LogDebug("CurrentSourcePortal is null! Cannot teleport."); return; } Vector3 position = targetZdo.GetPosition(); Quaternion rotation = targetZdo.GetRotation(); Vector3 vector = position + rotation * Vector3.forward * CurrentSourcePortal.m_exitDistance + Vector3.up; Configuration.LogDebug($"Teleporting player to {vector}."); PortalBehaviorPatch.SuppressAutoOpenFor(targetZdo.m_uid); HideUI(); Player.m_localPlayer.TeleportTo(vector, rotation, distantTeleport: true); Game.instance.IncrementPlayerStat(PlayerStatType.PortalsUsed); if (Configuration.allowTames.Value) { Configuration.LogDebug("Tame teleporting is enabled but not yet implemented."); } } } } // ---- plugins/TortalPortal.dll :: TortalPortal.SecurityPatch ---- namespace TortalPortal { [HarmonyPatch] public static class SecurityPatch { [HarmonyPatch(typeof(TeleportWorld), "Interact")] [HarmonyPrefix] public static bool TeleportWorld_Interact_Prefix(TeleportWorld __instance, Humanoid human, bool hold, bool alt, ref bool __result) { try { if (hold) { __result = false; return false; } Configuration.LogDebug("TeleportWorld_Interact_Prefix called."); ZNetView component = __instance.GetComponent(); if (component == null || !component.IsValid()) { return true; } long num = component.GetZDO().GetLong(ZDOVars.s_creator, 0L); long playerID = Game.instance.GetPlayerProfile().GetPlayerID(); if (num == playerID || Configuration.IsAdmin()) { Configuration.LogDebug("Access granted for portal configuration. Showing Config UI."); PortalUIManager.ShowConfigUI(__instance); __result = true; return false; } Configuration.LogDebug($"Access denied. CreatorID: {num}, PlayerID: {playerID}, IsAdmin: {Configuration.IsAdmin()}"); __result = true; return false; } catch (Exception arg) { Plugin.Log.LogError(string.Format("TortalPortal: {0} failed, falling back to vanilla interact. Reason: {1}", "TeleportWorld_Interact_Prefix", arg)); return true; } } [HarmonyPatch(typeof(TeleportWorld), "SetText")] [HarmonyPrefix] public static bool TeleportWorld_SetText_Prefix(TeleportWorld __instance, string text) { try { ZNetView component = __instance.GetComponent(); if (component != null && component.IsValid() && component.IsOwner()) { component.GetZDO().Set("PortalPIN", text); Player.m_localPlayer.Message(MessageHud.MessageType.Center, string.IsNullOrEmpty(text) ? "Portal lock removed." : "Portal PIN set."); } return false; } catch (Exception arg) { Plugin.Log.LogError(string.Format("TortalPortal: {0} failed, falling back to vanilla SetText. Reason: {1}", "TeleportWorld_SetText_Prefix", arg)); return true; } } } } // ---- plugins/TortalPortal.dll :: TortalPortal.TamesPatch ---- namespace TortalPortal { [HarmonyPatch] public static class TamesPatch { [HarmonyPatch(typeof(Player), "TeleportTo")] [HarmonyPrefix] public static void Player_TeleportTo_Prefix(Player __instance, Vector3 pos, Quaternion rot, bool distantTeleport) { try { if (!Configuration.allowTames.Value) { return; } float num = 10f; foreach (Character allCharacter in Character.GetAllCharacters()) { if (allCharacter == __instance || !(Vector3.Distance(__instance.transform.position, allCharacter.transform.position) <= num) || !(allCharacter.GetComponent() != null) || !allCharacter.IsTamed()) { continue; } MonsterAI component = allCharacter.GetComponent(); if (component != null && component.GetFollowTarget() == __instance.gameObject) { Vector3 vector = UnityEngine.Random.insideUnitSphere * 2f; vector.y = 0f; allCharacter.transform.position = pos + vector; allCharacter.transform.rotation = rot; Rigidbody component2 = allCharacter.GetComponent(); if ((bool)component2) { component2.linearVelocity = Vector3.zero; } } } } catch (Exception arg) { Plugin.Log.LogError(string.Format("TortalPortal: {0} failed (non-fatal). Reason: {1}", "Player_TeleportTo_Prefix", arg)); } } } } // ---- plugins/TortalPortal.dll :: TortalPortal.TortalUITheme ---- namespace TortalPortal { internal static class TortalUITheme { private enum Edge { Top, Bottom, Left, Right } private sealed class Painter { public bool MirrorX; public bool MirrorY; public bool Transpose; private readonly int _w; private readonly int _h; private readonly float[] _a; private readonly float[] _z; public Painter(int w, int h) { _w = w; _h = h; _a = new float[w * h]; _z = new float[w * h]; } private void Put(float fx, float fy, float a, float z) { if (a <= 0f) { return; } if (Transpose) { float num = fx; fx = fy; fy = num; } int num2 = Mathf.RoundToInt(fx); int num3 = Mathf.RoundToInt(fy); if (MirrorX) { num2 = _w - 1 - num2; } if (MirrorY) { num3 = _h - 1 - num3; } if (num2 >= 0 && num3 >= 0 && num2 < _w && num3 < _h) { int num4 = num3 * _w + num2; if (a > _a[num4]) { _a[num4] = a; } if (z > _z[num4]) { _z[num4] = z; } } } public void Disc(float cx, float cy, float r) { if (r <= 0f) { return; } int num = Mathf.FloorToInt(cx - r - 1f); int num2 = Mathf.CeilToInt(cx + r + 1f); int num3 = Mathf.FloorToInt(cy - r - 1f); int num4 = Mathf.CeilToInt(cy + r + 1f); for (int i = num3; i <= num4; i++) { for (int j = num; j <= num2; j++) { float num5 = (float)j - cx; float num6 = (float)i - cy; float num7 = Mathf.Sqrt(num5 * num5 + num6 * num6); float num8 = Mathf.Clamp01(r + 0.5f - num7); if (!(num8 <= 0f)) { Put(j, i, num8, Mathf.Sqrt(Mathf.Max(0f, 1f - num7 / r * (num7 / r)))); } } } } public void Lozenge(float cx, float cy, float r) { int num = Mathf.FloorToInt(cx - r - 1f); int num2 = Mathf.CeilToInt(cx + r + 1f); int num3 = Mathf.FloorToInt(cy - r - 1f); int num4 = Mathf.CeilToInt(cy + r + 1f); for (int i = num3; i <= num4; i++) { for (int j = num; j <= num2; j++) { float num5 = Mathf.Abs((float)j - cx) + Mathf.Abs((float)i - cy); float num6 = Mathf.Clamp01(r + 0.5f - num5); if (!(num6 <= 0f)) { Put(j, i, num6, Mathf.Sqrt(Mathf.Max(0f, 1f - num5 / r * (num5 / r)))); } } } } public void Taper(Vector2 a, Vector2 b, float w0, float w1) { int num = Mathf.Max(8, Mathf.CeilToInt(Vector2.Distance(a, b) * 3f)); for (int i = 0; i <= num; i++) { float t = (float)i / (float)num; Vector2 vector = Vector2.Lerp(a, b, t); Disc(vector.x, vector.y, Mathf.Lerp(w0, w1, t)); } } public void Bezier(Vector2 a, Vector2 b, Vector2 c, float w0, float w1) { int num = Mathf.Max(16, Mathf.CeilToInt((Vector2.Distance(a, b) + Vector2.Distance(b, c)) * 3f)); for (int i = 0; i <= num; i++) { float num2 = (float)i / (float)num; float num3 = 1f - num2; Vector2 vector = num3 * num3 * a + 2f * num3 * num2 * b + num2 * num2 * c; Disc(vector.x, vector.y, Mathf.Lerp(w0, w1, num2)); } } public void Spiral(Vector2 eye, float r0, float growth, float t0, float t1, float phase, float w0, float w1, bool mirror = false) { int num = Mathf.Max(48, Mathf.CeilToInt((t1 - t0) * 40f)); for (int i = 0; i <= num; i++) { float t2 = (float)i / (float)num; float num2 = Mathf.Lerp(t0, t1, t2); float num3 = r0 * Mathf.Exp(growth * num2); float f = num2 + phase; float num4 = Mathf.Cos(f) * num3; float num5 = Mathf.Sin(f) * num3; if (mirror) { num4 = 0f - num4; } Disc(eye.x + num4, eye.y + num5, Mathf.Lerp(w0, w1, t2)); } } public void RailPixel(int x, int y, float d, float half) { float num = Mathf.Clamp01(half + 0.5f - d); if (!(num <= 0f)) { Put(x, y, num, Mathf.Sqrt(Mathf.Max(0f, 1f - d / half * (d / half)))); } } public void RailElbow(float mid, float half, float centre) { float num = centre - mid; for (int i = 0; i < _h; i++) { for (int j = 0; j < _w; j++) { float d; if (!((float)j <= centre) || !((float)i <= centre)) { d = ((!((float)i <= centre)) ? ((!((float)j <= centre)) ? Mathf.Min(Mathf.Abs((float)i - mid), Mathf.Abs((float)j - mid)) : Mathf.Abs((float)j - mid)) : Mathf.Abs((float)i - mid)); } else { float num2 = (float)j - centre; float num3 = (float)i - centre; d = Mathf.Abs(Mathf.Sqrt(num2 * num2 + num3 * num3) - num); } RailPixel(j, i, d, half); } } } public Texture2D Bake() { Texture2D texture2D = New(_w, _h, TextureWrapMode.Clamp, UnityEngine.FilterMode.Bilinear); Color[] array = new Color[_w * _h]; for (int i = 0; i < _h; i++) { for (int j = 0; j < _w; j++) { int num = i * _w + j; float num2 = _a[num]; int num3 = (_h - 1 - i) * _w + j; if (num2 <= 0f) { array[num3] = Color.clear; continue; } float num4 = Z(j - 1, i) - Z(j + 1, i) + (Z(j, i - 1) - Z(j, i + 1)); float num5 = Mathf.Clamp01(0.42f + 0.5f * num4 + 0.18f * _z[num]); Color color = ((num5 < 0.5f) ? Color.Lerp(GoldDeep, Gold, num5 * 2f) : Color.Lerp(Gold, GoldBright, (num5 - 0.5f) * 2f)); array[num3] = new Color(color.r, color.g, color.b, num2); } } texture2D.SetPixels(array); texture2D.Apply(updateMipmaps: false); return texture2D; } private float Z(int x, int y) { return _z[Mathf.Clamp(y, 0, _h - 1) * _w + Mathf.Clamp(x, 0, _w - 1)]; } } public static readonly Color GoldDeep = new Color(0.26f, 0.17f, 0.05f, 1f); public static readonly Color Gold = new Color(0.8f, 0.62f, 0.26f, 1f); public static readonly Color GoldBright = new Color(1f, 0.94f, 0.72f, 1f); public static readonly Color Parchment = new Color(0.9f, 0.86f, 0.75f, 1f); public static readonly Color Muted = new Color(0.6f, 0.56f, 0.48f, 1f); public const string HexMuted = "#9A9182"; public const string HexLocked = "#E0736B"; public const string HexOpen = "#87D278"; public const float Band = 18f; public const float Pad = 22f; public static float TitleHeight = 54f; public static float FooterHeight = 30f; private const int CornerTile = 84; private const float Overhang = 10f; private const float CornerExtent = 74f; private const int CrestW = 56; private const int CrestH = 34; private const float CrestOverhang = 8f; private const float OuterMid = 4.4f; private const float OuterHalf = 2.7f; private const float InnerMid = 12.4f; private const float InnerHalf = 1.6f; private const float BendCentre = 32f; public static GUIStyle Title; public static GUIStyle SubTitle; public static GUIStyle Header; public static GUIStyle Key; public static GUIStyle Value; public static GUIStyle Note; public static GUIStyle Footer; public static GUIStyle Button; public static GUIStyle Primary; public static GUIStyle Row; public static GUIStyle Field; public static GUIStyle ImageButton; private static Texture2D _railTop; private static Texture2D _railBottom; private static Texture2D _railLeft; private static Texture2D _railRight; private static Texture2D _cornerTL; private static Texture2D _cornerTR; private static Texture2D _cornerBL; private static Texture2D _cornerBR; private static Texture2D _crestTop; private static Texture2D _crestBottom; private static Texture2D _diamond; private static Texture2D _panel; private static Texture2D _white; private static Texture2D _btnNormal; private static Texture2D _btnHover; private static Texture2D _btnActive; private static Texture2D _rowNormal; private static Texture2D _rowHover; private static Texture2D _rowActive; private static Texture2D _selection; private static Texture2D _fieldTex; public static float TextScale { get; private set; } = 1f; public static float S(float v) { return Mathf.Round(v * TextScale); } public static void EnsureBuilt() { if (_railTop != null) { float num = ((Configuration.uiTextScale != null) ? Configuration.uiTextScale.Value : 1f); if (Title == null || !Mathf.Approximately(num, TextScale)) { BuildStyles(num); } return; } _railTop = BuildRail(Edge.Top); _railBottom = BuildRail(Edge.Bottom); _railLeft = BuildRail(Edge.Left); _railRight = BuildRail(Edge.Right); _cornerTL = BuildCorner(mirrorX: false, mirrorY: false); _cornerTR = BuildCorner(mirrorX: true, mirrorY: false); _cornerBL = BuildCorner(mirrorX: false, mirrorY: true); _cornerBR = BuildCorner(mirrorX: true, mirrorY: true); _crestTop = BuildCrest(flip: false); _crestBottom = BuildCrest(flip: true); _diamond = BuildDiamond(14); _panel = BuildPanel(64); _white = BuildSolid(Color.white); _btnNormal = BuildPatch(new Color(0.1f, 0.085f, 0.065f, 0.95f), GoldDeep); _btnHover = BuildPatch(new Color(0.19f, 0.15f, 0.09f, 0.97f), Gold); _btnActive = BuildPatch(new Color(0.3f, 0.23f, 0.11f, 0.98f), GoldBright); _rowNormal = BuildPatch(Color.clear, Color.clear); _rowHover = BuildPatch(new Color(0.8f, 0.62f, 0.26f, 0.1f), new Color(0.8f, 0.62f, 0.26f, 0.45f)); _rowActive = BuildPatch(new Color(0.8f, 0.62f, 0.26f, 0.2f), Gold); _selection = BuildSolid(new Color(0.8f, 0.62f, 0.26f, 0.15f)); _fieldTex = BuildPatch(new Color(0.03f, 0.03f, 0.025f, 0.95f), GoldDeep); BuildStyles((Configuration.uiTextScale != null) ? Configuration.uiTextScale.Value : 1f); } public static void DrawWindow(Rect win, string title) { EnsureBuilt(); GUI.DrawTexture(new Rect(win.x + 1f, win.y + 1f, win.width - 2f, win.height - 2f), _panel, ScaleMode.StretchToFill); DrawFrame(win); DrawShadowed(new Rect(win.x + 74f, win.y + 18f + 8f, win.width - 148f, TitleHeight - 20f), title.ToUpperInvariant(), Title); DrawRule(new Rect(win.x + 18f + 22f, win.y + 18f + TitleHeight - 12f, win.width - 80f, 1f)); } public static Rect Body(Rect win) { return new Rect(win.x + 18f + 22f, win.y + 18f + TitleHeight, win.width - 80f, win.height - 36f - TitleHeight - FooterHeight); } public static Rect FooterLine(Rect win) { return new Rect(win.x + 18f + 22f, win.yMax - 18f - FooterHeight, win.width - 80f, S(18f)); } private static void DrawFrame(Rect r) { float width = r.width - 148f; float height = r.height - 148f; GUI.DrawTexture(new Rect(r.x + 74f, r.y, width, 18f), _railTop); GUI.DrawTexture(new Rect(r.x + 74f, r.yMax - 18f, width, 18f), _railBottom); GUI.DrawTexture(new Rect(r.x, r.y + 74f, 18f, height), _railLeft); GUI.DrawTexture(new Rect(r.xMax - 18f, r.y + 74f, 18f, height), _railRight); float num = 74f; GUI.DrawTexture(new Rect(r.x - 10f, r.y - 10f, 84f, 84f), _cornerTL); GUI.DrawTexture(new Rect(r.xMax - num, r.y - 10f, 84f, 84f), _cornerTR); GUI.DrawTexture(new Rect(r.x - 10f, r.yMax - num, 84f, 84f), _cornerBL); GUI.DrawTexture(new Rect(r.xMax - num, r.yMax - num, 84f, 84f), _cornerBR); float x = r.center.x - 28f; GUI.DrawTexture(new Rect(x, r.y - 8f, 56f, 34f), _crestTop); GUI.DrawTexture(new Rect(x, r.yMax + 8f - 34f, 56f, 34f), _crestBottom); DrawOutline(new Rect(r.x + 18f, r.y + 18f, r.width - 36f, r.height - 36f), new Color(Gold.r, Gold.g, Gold.b, 0.45f), 1f); } public static void DrawOutline(Rect r, Color c, float t) { Color color = GUI.color; GUI.color = c; GUI.DrawTexture(new Rect(r.x, r.y, r.width, t), _white); GUI.DrawTexture(new Rect(r.x, r.yMax - t, r.width, t), _white); GUI.DrawTexture(new Rect(r.x, r.y, t, r.height), _white); GUI.DrawTexture(new Rect(r.xMax - t, r.y, t, r.height), _white); GUI.color = color; } public static void DrawFill(Rect r, Color c) { Color color = GUI.color; GUI.color = c; GUI.DrawTexture(r, _white); GUI.color = color; } public static void DrawInset(Rect r) { DrawFill(r, new Color(0f, 0f, 0f, 0.45f)); DrawOutline(r, new Color(Gold.r, Gold.g, Gold.b, 0.32f), 1f); } public static void DrawSelection(Rect r) { GUI.DrawTexture(r, _selection); } public static void DrawRule(Rect r) { DrawFill(r, new Color(Gold.r, Gold.g, Gold.b, 0.4f)); GUI.DrawTexture(new Rect(r.center.x - 7f, r.y - 7f + 0.5f, 14f, 14f), _diamond); } public static void DrawShadowed(Rect r, string text, GUIStyle style) { Color textColor = style.normal.textColor; style.normal.textColor = new Color(0f, 0f, 0f, 0.7f); GUI.Label(new Rect(r.x + 1.5f, r.y + 1.5f, r.width, r.height), text, style); style.normal.textColor = textColor; GUI.Label(r, text, style); } private static void BuildStyles(float scale) { TextScale = Mathf.Clamp(scale, 0.6f, 2f); TitleHeight = 26f + Mathf.Round(28f * TextScale); FooterHeight = Mathf.Max(30f, Mathf.Round(30f * TextScale)); Font font = FindFont(); Title = Text(font, Pt(25), FontStyle.Bold, GoldBright, TextAnchor.MiddleCenter); SubTitle = Text(font, Pt(18), FontStyle.Bold, Gold, TextAnchor.MiddleLeft); Header = Text(font, Pt(13), FontStyle.Bold, Gold, TextAnchor.MiddleLeft); Key = Text(font, Pt(13), FontStyle.Normal, Muted, TextAnchor.MiddleLeft); Value = Text(font, Pt(13), FontStyle.Bold, Parchment, TextAnchor.MiddleLeft); Note = Text(font, Pt(13), FontStyle.Italic, Muted, TextAnchor.MiddleCenter); Note.wordWrap = true; Footer = Text(font, Pt(11), FontStyle.Normal, Muted, TextAnchor.MiddleCenter); Button = Patch(font, Pt(13), FontStyle.Bold, TextAnchor.MiddleCenter, _btnNormal, _btnHover, _btnActive); Button.padding = new RectOffset(12, 12, 6, 6); Primary = Patch(font, Pt(16), FontStyle.Bold, TextAnchor.MiddleCenter, _btnNormal, _btnHover, _btnActive); Primary.padding = new RectOffset(12, 12, 8, 8); Primary.normal.textColor = Gold; Row = Patch(font, Pt(14), FontStyle.Normal, TextAnchor.MiddleLeft, _rowNormal, _rowHover, _rowActive); Row.padding = new RectOffset(12, 12, 4, 4); Row.normal.textColor = Parchment; ImageButton = Patch(font, Pt(11), FontStyle.Normal, TextAnchor.LowerCenter, _rowNormal, _rowHover, _rowActive); Field = new GUIStyle { font = font, fontSize = Pt(13), alignment = TextAnchor.MiddleLeft, padding = new RectOffset(8, 8, 4, 4), border = new RectOffset(3, 3, 3, 3), clipping = TextClipping.Clip }; Field.normal.background = _fieldTex; Field.focused.background = _fieldTex; Field.hover.background = _fieldTex; Field.active.background = _fieldTex; Field.normal.textColor = Parchment; Field.focused.textColor = GoldBright; Field.hover.textColor = Parchment; Field.active.textColor = Parchment; } private static int Pt(int designSize) { return Mathf.Max(8, Mathf.RoundToInt((float)designSize * TextScale)); } private static GUIStyle Text(Font font, int size, FontStyle fs, Color colour, TextAnchor anchor) { return new GUIStyle { font = font, fontSize = size, fontStyle = fs, alignment = anchor, richText = true, wordWrap = false, clipping = TextClipping.Clip, normal = { textColor = colour } }; } private static GUIStyle Patch(Font font, int size, FontStyle fs, TextAnchor anchor, Texture2D normal, Texture2D hover, Texture2D active) { GUIStyle gUIStyle = new GUIStyle(); gUIStyle.font = font; gUIStyle.fontSize = size; gUIStyle.fontStyle = fs; gUIStyle.alignment = anchor; gUIStyle.richText = true; gUIStyle.wordWrap = false; gUIStyle.border = new RectOffset(3, 3, 3, 3); gUIStyle.clipping = TextClipping.Clip; gUIStyle.normal.background = normal; gUIStyle.hover.background = hover; gUIStyle.active.background = active; gUIStyle.focused.background = normal; gUIStyle.normal.textColor = Parchment; gUIStyle.hover.textColor = GoldBright; gUIStyle.active.textColor = GoldBright; gUIStyle.focused.textColor = Parchment; return gUIStyle; } private static Font FindFont() { Font[] array = Resources.FindObjectsOfTypeAll(); string[] array2 = new string[3] { "AveriaSerifLibre", "Norsebold", "Norse" }; foreach (string value in array2) { Font[] array3 = array; foreach (Font font in array3) { if (font != null && font.name.IndexOf(value, StringComparison.OrdinalIgnoreCase) >= 0) { return font; } } } return null; } private static Texture2D BuildRail(Edge edge) { int num; int num2; if (edge != Edge.Top) { num = ((edge == Edge.Bottom) ? 1 : 0); if (num == 0) { num2 = 18; goto IL_0012; } } else { num = 1; } num2 = 4; goto IL_0012; IL_0012: int num3 = num2; int num4 = ((num != 0) ? 18 : 4); Painter painter = new Painter(num3, num4); for (int i = 0; i < num4; i++) { for (int j = 0; j < num3; j++) { float num5 = edge switch { Edge.Top => i, Edge.Bottom => num4 - 1 - i, Edge.Left => j, _ => num3 - 1 - j, }; painter.RailPixel(j, i, Mathf.Abs(num5 - 4.4f), 2.7f); painter.RailPixel(j, i, Mathf.Abs(num5 - 12.4f), 1.6f); } } return painter.Bake(); } private static Texture2D BuildCorner(bool mirrorX, bool mirrorY) { Painter painter = new Painter(84, 84) { MirrorX = mirrorX, MirrorY = mirrorY }; painter.RailElbow(14.4f, 2.7f, 32f); painter.RailElbow(22.4f, 1.6f, 32f); painter.Lozenge(11f, 11f, 4.5f); painter.Taper(new Vector2(13.5f, 13.5f), new Vector2(19.3f, 19.3f), 1.2f, 2.2f); painter.Lozenge(36f, 36f, 3.4f); for (int i = 0; i < 2; i++) { painter.Transpose = i == 1; painter.Taper(new Vector2(38.5f, 35f), new Vector2(47f, 32f), 1.4f, 0.45f); painter.Spiral(new Vector2(50f, 31f), 1.3f, 0.33f, 0f, 6.8f, 5.371f, 0.55f, 2.4f); painter.Bezier(new Vector2(56f, 36f), new Vector2(68f, 41f), new Vector2(78f, 30f), 2.2f, 0.35f); painter.Spiral(new Vector2(76f, 32f), 0.9f, 0.32f, 0f, 4.6f, 1f, 1.1f, 0.3f); painter.Disc(58f, 34f, 1.8f); } painter.Transpose = false; return painter.Bake(); } private static Texture2D BuildCrest(bool flip) { Painter painter = new Painter(56, 34); painter.MirrorY = flip; painter.Disc(28f, 2.5f, 1.8f); painter.Lozenge(28f, 9f, 6.5f); painter.Taper(new Vector2(28f, 14f), new Vector2(28f, 24f), 2.2f, 1.2f); painter.Spiral(new Vector2(17f, 25f), 1.2f, 0.33f, 0f, 5.4f, 2.6f, 2f, 0.35f); painter.Spiral(new Vector2(39f, 25f), 1.2f, 0.33f, 0f, 5.4f, 2.6f, 2f, 0.35f, mirror: true); painter.Bezier(new Vector2(23f, 19f), new Vector2(13f, 24f), new Vector2(4f, 16f), 1.6f, 0.3f); painter.Bezier(new Vector2(33f, 19f), new Vector2(43f, 24f), new Vector2(52f, 16f), 1.6f, 0.3f); painter.Disc(3f, 14f, 1.5f); painter.Disc(53f, 14f, 1.5f); return painter.Bake(); } private static Texture2D BuildDiamond(int size) { Painter painter = new Painter(size, size); float num = (float)(size - 1) * 0.5f; painter.Lozenge(num, num, (float)size * 0.36f); return painter.Bake(); } private static Texture2D BuildPanel(int size) { Texture2D texture2D = New(size, size, TextureWrapMode.Clamp, UnityEngine.FilterMode.Bilinear); Color[] array = new Color[size * size]; float num = (float)(size - 1) * 0.5f; for (int i = 0; i < size; i++) { for (int j = 0; j < size; j++) { float num2 = ((float)j - num) / num; float num3 = ((float)i - num) / num; float num4 = Mathf.Clamp01(1f - 0.55f * Mathf.Sqrt(0.6f * (num2 * num2 + num3 * num3))); array[i * size + j] = new Color(0.055f * num4 + 0.02f, 0.048f * num4 + 0.017f, 0.038f * num4 + 0.013f, 0.955f); } } texture2D.SetPixels(array); texture2D.Apply(updateMipmaps: false); return texture2D; } private static Texture2D BuildPatch(Color fill, Color border) { Texture2D texture2D = New(12, 12, TextureWrapMode.Clamp, UnityEngine.FilterMode.Point); Color[] array = new Color[144]; for (int i = 0; i < 12; i++) { for (int j = 0; j < 12; j++) { int num = Mathf.Min(Mathf.Min(j, i), Mathf.Min(11 - j, 11 - i)); array[i * 12 + j] = ((num == 0) ? border : fill); } } texture2D.SetPixels(array); texture2D.Apply(updateMipmaps: false); return texture2D; } private static Texture2D BuildSolid(Color c) { Texture2D texture2D = New(1, 1, TextureWrapMode.Clamp, UnityEngine.FilterMode.Point); texture2D.SetPixel(0, 0, c); texture2D.Apply(updateMipmaps: false); return texture2D; } private static Texture2D New(int w, int h, TextureWrapMode wrap, UnityEngine.FilterMode filter) { return new Texture2D(w, h, TextureFormat.RGBA32, mipChain: false) { wrapMode = wrap, filterMode = filter, hideFlags = HideFlags.HideAndDontSave }; } } } // ---- plugins/TortalPortal.dll :: TortalPortal.VFXPatch ---- namespace TortalPortal { [HarmonyPatch] public static class VFXPatch { private static GameObject MistsOfAvalorVFXPrefab; public static void InitBundle() { if (!Configuration.enableCustomVFX.Value) { return; } string path = Path.Combine(Path.GetDirectoryName(Plugin.Instance.Info.Location), "MistsOfAvalorBundle"); if (File.Exists(path)) { AssetBundle assetBundle = AssetBundle.LoadFromFile(path); if (assetBundle != null) { MistsOfAvalorVFXPrefab = assetBundle.LoadAsset("GreenRunicPortalVFX"); assetBundle.Unload(unloadAllLoadedObjects: false); } return; } string path2 = "C:\\WubarrkCODING\\MistsofAvalor\\HexiumDist\\plugins\\MistsOfAvalorBundle"; if (File.Exists(path2)) { AssetBundle assetBundle2 = AssetBundle.LoadFromFile(path2); if (assetBundle2 != null) { MistsOfAvalorVFXPrefab = assetBundle2.LoadAsset("GreenRunicPortalVFX"); assetBundle2.Unload(unloadAllLoadedObjects: false); } } } [HarmonyPatch(typeof(TeleportWorld), "Awake")] [HarmonyPostfix] public static void TeleportWorld_Awake_Postfix(TeleportWorld __instance) { try { if (Configuration.enableCustomVFX.Value && !(MistsOfAvalorVFXPrefab == null)) { ParticleSystem[] componentsInChildren = __instance.GetComponentsInChildren(includeInactive: true); for (int i = 0; i < componentsInChildren.Length; i++) { componentsInChildren[i].gameObject.SetActive(value: false); } GameObject gameObject = UnityEngine.Object.Instantiate(MistsOfAvalorVFXPrefab, __instance.transform); gameObject.transform.localPosition = Vector3.zero; gameObject.transform.localRotation = Quaternion.identity; } } catch (Exception arg) { Plugin.Log.LogError(string.Format("TortalPortal: {0} failed (non-fatal). Reason: {1}", "TeleportWorld_Awake_Postfix", arg)); } } } } // ---- plugins/TortalPortal.dll :: TortalPortal.TortalPortalRuneVFX ---- namespace TortalPortal { public class TortalPortalRuneVFX : MonoBehaviour { public Color Colour = new Color(0.3f, 1f, 0.55f); public float GateWidth = 2.4f; public float GateHeight = 2.8f; [NonSerialized] public float Charge; private ParticleSystem _veil; private ParticleSystem _motes; private LineRenderer _ringA; private LineRenderer _ringB; private LineRenderer _sigil; private LineRenderer _sigilInner; private LineRenderer[] _spokes; private ParticleSystem _sigilRunes; private float _spin; private float _orbHeight; private readonly List _parts = new List(); private const int RingSegments = 64; private static Texture2D _atlasTex; private static Texture2D _softTex; private void Start() { if (_atlasTex == null) { _atlasTex = TortalRuneTexture.GenerateRuneAtlas(Color.white); } if (_softTex == null) { _softTex = TortalRuneTexture.GenerateSoftTrail(Color.white); } Texture2D atlasTex = _atlasTex; Texture2D softTex = _softTex; Material orCreateRuneMaterial = TortalRuneMaterial.GetOrCreateRuneMaterial(atlasTex, Colour); Material orCreateRuneMaterial2 = TortalRuneMaterial.GetOrCreateRuneMaterial(softTex, Colour); if (orCreateRuneMaterial == null || orCreateRuneMaterial2 == null) { Debug.LogWarning("[Tortal] rune VFX: no usable particle shader - portal keeps vanilla effects only."); base.enabled = false; return; } _orbHeight = MeasureGateCentre(); BuildVeil(orCreateRuneMaterial); BuildRings(orCreateRuneMaterial2); BuildSigil(orCreateRuneMaterial2, orCreateRuneMaterial); BuildMotes(orCreateRuneMaterial); } private float MeasureGateCentre() { float num = GateHeight * 0.45f; Bounds bounds = default(Bounds); bool flag = false; MeshRenderer[] componentsInChildren = GetComponentsInChildren(); foreach (MeshRenderer meshRenderer in componentsInChildren) { if (!(meshRenderer == null)) { if (!flag) { bounds = meshRenderer.bounds; flag = true; } else { bounds.Encapsulate(meshRenderer.bounds); } } } float num2 = (flag ? base.transform.InverseTransformPoint(bounds.center).y : num); if (num2 < 0.5f || num2 > 6f) { Configuration.LogDebug($"Rune VFX: measured gate centre {num2:0.00}m is implausible, using {num:0.00}m."); num2 = num; } float num3 = num2 + Configuration.vfxOrbHeightOffset.Value; Configuration.LogDebug($"Rune VFX: gate centre {num2:0.00}m, orb placed at {num3:0.00}m."); return num3; } public void SetVisible(bool visible) { foreach (GameObject part in _parts) { if (!(part == null)) { Renderer component = part.GetComponent(); if (component != null) { component.enabled = visible; } } } } private void BuildVeil(Material mat) { GameObject gameObject = Child("RuneVeil", new Vector3(0f, _orbHeight - 0.08f, 0f)); _veil = gameObject.AddComponent(); ParticleSystem.MainModule main = _veil.main; main.loop = true; main.playOnAwake = true; main.startSpeed = new ParticleSystem.MinMaxCurve(0.15f, 0.5f); main.startLifetime = new ParticleSystem.MinMaxCurve(1.6f, 3.2f); main.startSize = new ParticleSystem.MinMaxCurve(0.22f, 0.55f); main.startColor = Colour; main.maxParticles = 220; main.simulationSpace = ParticleSystemSimulationSpace.Local; main.startRotation = new ParticleSystem.MinMaxCurve(0f, MathF.PI * 2f); ParticleSystem.EmissionModule emission = _veil.emission; emission.rateOverTime = 26f; ParticleSystem.ShapeModule shape = _veil.shape; shape.enabled = true; shape.shapeType = ParticleSystemShapeType.Box; shape.scale = new Vector3(GateWidth * 0.82f, GateHeight * 0.72f, 0.12f); ParticleSystem.VelocityOverLifetimeModule velocityOverLifetime = _veil.velocityOverLifetime; velocityOverLifetime.enabled = true; velocityOverLifetime.space = ParticleSystemSimulationSpace.Local; velocityOverLifetime.x = new ParticleSystem.MinMaxCurve(-0.06f, 0.06f); velocityOverLifetime.y = new ParticleSystem.MinMaxCurve(0.25f, 0.75f); velocityOverLifetime.z = new ParticleSystem.MinMaxCurve(-0.06f, 0.06f); FadeInOut(_veil); Atlas(_veil); ParticleSystemRenderer component = gameObject.GetComponent(); component.renderMode = ParticleSystemRenderMode.Billboard; component.material = mat; component.shadowCastingMode = ShadowCastingMode.Off; component.receiveShadows = false; } private void BuildRings(Material glow) { float num = GateWidth * 0.44f; _ringA = BuildCircle("RuneRingA", new Vector3(0f, _orbHeight, 0f), num, glow, 0.055f, vertical: true); _ringB = BuildCircle("RuneRingB", new Vector3(0f, _orbHeight, 0f), num * 0.68f, glow, 0.04f, vertical: true); _spokes = new LineRenderer[4]; for (int i = 0; i < _spokes.Length; i++) { LineRenderer lineRenderer = Child("RuneSpoke" + i, new Vector3(0f, _orbHeight, 0f)).AddComponent(); float f = MathF.PI / (float)_spokes.Length * (float)i; Vector3 vector = new Vector3(Mathf.Cos(f), Mathf.Sin(f), 0f) * (num * 0.68f); Line(lineRenderer, glow, 0.03f, new Vector3[2] { -vector, vector }); _spokes[i] = lineRenderer; } } private void BuildSigil(Material glow, Material runeMat) { float num = GateWidth * 0.85f; _sigil = BuildCircle("SigilOuter", new Vector3(0f, 0.06f, 0f), num, glow, 0.07f, vertical: false); _sigilInner = BuildCircle("SigilInner", new Vector3(0f, 0.06f, 0f), num * 0.62f, glow, 0.05f, vertical: false); GameObject gameObject = Child("SigilRunes", new Vector3(0f, 0.35f, 0f)); _sigilRunes = gameObject.AddComponent(); ParticleSystem.MainModule main = _sigilRunes.main; main.loop = true; main.playOnAwake = true; main.startSpeed = 0f; main.startLifetime = new ParticleSystem.MinMaxCurve(1.4f, 2.6f); main.startSize = new ParticleSystem.MinMaxCurve(0.3f, 0.5f); main.startColor = Colour; main.maxParticles = 90; main.simulationSpace = ParticleSystemSimulationSpace.Local; ParticleSystem.EmissionModule emission = _sigilRunes.emission; emission.rateOverTime = 14f; ParticleSystem.ShapeModule shape = _sigilRunes.shape; shape.enabled = true; shape.shapeType = ParticleSystemShapeType.Circle; shape.radius = num * 0.9f; shape.radiusThickness = 0f; shape.rotation = new Vector3(90f, 0f, 0f); FadeInOut(_sigilRunes); Atlas(_sigilRunes); ParticleSystemRenderer component = gameObject.GetComponent(); component.renderMode = ParticleSystemRenderMode.Billboard; component.material = runeMat; component.shadowCastingMode = ShadowCastingMode.Off; component.receiveShadows = false; } private void BuildMotes(Material mat) { GameObject gameObject = Child("RuneMotes", new Vector3(0f, 0.2f, 0f)); _motes = gameObject.AddComponent(); ParticleSystem.MainModule main = _motes.main; main.loop = true; main.playOnAwake = true; main.startSpeed = new ParticleSystem.MinMaxCurve(0.3f, 0.9f); main.startLifetime = new ParticleSystem.MinMaxCurve(3f, 6f); main.startSize = new ParticleSystem.MinMaxCurve(0.1f, 0.26f); main.startColor = Colour; main.maxParticles = 120; main.simulationSpace = ParticleSystemSimulationSpace.World; main.gravityModifier = -0.02f; ParticleSystem.EmissionModule emission = _motes.emission; emission.rateOverTime = 10f; ParticleSystem.ShapeModule shape = _motes.shape; shape.enabled = true; shape.shapeType = ParticleSystemShapeType.Circle; shape.radius = GateWidth * 0.9f; shape.rotation = new Vector3(90f, 0f, 0f); FadeInOut(_motes); Atlas(_motes); ParticleSystemRenderer component = gameObject.GetComponent(); component.renderMode = ParticleSystemRenderMode.Billboard; component.material = mat; component.shadowCastingMode = ShadowCastingMode.Off; component.receiveShadows = false; } private void Update() { Charge = Mathf.Max(0f, Charge - Time.deltaTime * 1.4f); float num = Mathf.Clamp01(Charge); _spin += Time.deltaTime * (18f + 150f * num); if (_ringA != null) { _ringA.transform.localRotation = Quaternion.Euler(0f, 0f, _spin); } if (_ringB != null) { _ringB.transform.localRotation = Quaternion.Euler(0f, 0f, (0f - _spin) * 1.6f); } if (_spokes != null) { LineRenderer[] spokes = _spokes; foreach (LineRenderer lineRenderer in spokes) { if (lineRenderer != null) { lineRenderer.transform.localRotation = Quaternion.Euler(0f, 0f, (0f - _spin) * 1.6f); } } } if (_sigil != null) { _sigil.transform.localRotation = Quaternion.Euler(0f, (0f - _spin) * 0.5f, 0f); } if (_sigilInner != null) { _sigilInner.transform.localRotation = Quaternion.Euler(0f, _spin * 0.8f, 0f); } if (_sigilRunes != null) { _sigilRunes.transform.localRotation = Quaternion.Euler(0f, (0f - _spin) * 0.5f, 0f); } if (_veil != null) { ParticleSystem.EmissionModule emission = _veil.emission; emission.rateOverTime = 26f + 120f * num; ParticleSystem.MainModule main = _veil.main; main.startColor = Colour * (1f + 1.6f * num); } if (_sigilRunes != null) { ParticleSystem.EmissionModule emission2 = _sigilRunes.emission; emission2.rateOverTime = 14f + 50f * num; } float num2 = 1f + 1.8f * num; Width(_ringA, 0.055f * num2); Width(_ringB, 0.04f * num2); Width(_sigil, 0.07f * num2); Width(_sigilInner, 0.05f * num2); if (_spokes != null) { LineRenderer[] spokes = _spokes; for (int i = 0; i < spokes.Length; i++) { Width(spokes[i], 0.03f * num2); } } } public void Discharge() { if (_veil != null) { _veil.Emit(70); } if (_motes != null) { _motes.Emit(45); } if (_sigilRunes != null) { _sigilRunes.Emit(40); } Charge = 1f; } private GameObject Child(string name, Vector3 localPos) { GameObject gameObject = new GameObject(name); gameObject.layer = base.gameObject.layer; gameObject.transform.SetParent(base.transform, worldPositionStays: false); gameObject.transform.localPosition = localPos; _parts.Add(gameObject); return gameObject; } private LineRenderer BuildCircle(string name, Vector3 pos, float radius, Material mat, float width, bool vertical) { LineRenderer lineRenderer = Child(name, pos).AddComponent(); Vector3[] array = new Vector3[65]; for (int i = 0; i <= 64; i++) { float f = MathF.PI / 32f * (float)i; float x = Mathf.Cos(f) * radius; float num = Mathf.Sin(f) * radius; array[i] = (vertical ? new Vector3(x, num, 0f) : new Vector3(x, 0f, num)); } Line(lineRenderer, mat, width, array); return lineRenderer; } private void Line(LineRenderer lr, Material mat, float width, Vector3[] pts) { lr.useWorldSpace = false; lr.loop = false; lr.material = mat; lr.positionCount = pts.Length; lr.SetPositions(pts); float startWidth = (lr.endWidth = width); lr.startWidth = startWidth; lr.startColor = Colour; lr.endColor = Colour; lr.shadowCastingMode = ShadowCastingMode.Off; lr.receiveShadows = false; lr.alignment = LineAlignment.View; } private static void Width(LineRenderer lr, float w) { if (!(lr == null)) { float startWidth = (lr.endWidth = w); lr.startWidth = startWidth; } } private static void FadeInOut(ParticleSystem ps) { ParticleSystem.ColorOverLifetimeModule colorOverLifetime = ps.colorOverLifetime; colorOverLifetime.enabled = true; Gradient gradient = new Gradient(); gradient.SetKeys(new GradientColorKey[2] { new GradientColorKey(Color.white, 0f), new GradientColorKey(Color.white, 1f) }, new GradientAlphaKey[4] { new GradientAlphaKey(0f, 0f), new GradientAlphaKey(1f, 0.25f), new GradientAlphaKey(1f, 0.65f), new GradientAlphaKey(0f, 1f) }); colorOverLifetime.color = new ParticleSystem.MinMaxGradient(gradient); } private static void Atlas(ParticleSystem ps) { ParticleSystem.TextureSheetAnimationModule textureSheetAnimation = ps.textureSheetAnimation; textureSheetAnimation.enabled = true; textureSheetAnimation.numTilesX = 4; textureSheetAnimation.numTilesY = 4; textureSheetAnimation.animation = ParticleSystemAnimationType.WholeSheet; textureSheetAnimation.timeMode = ParticleSystemAnimationTimeMode.Lifetime; textureSheetAnimation.startFrame = new ParticleSystem.MinMaxCurve(0f, 16f); textureSheetAnimation.frameOverTime = new ParticleSystem.MinMaxCurve(0f); } } } // ---- plugins/TortalPortal.dll :: TortalPortal.TortalRuneMaterial ---- namespace TortalPortal { public static class TortalRuneMaterial { private static readonly Dictionary _materialCache = new Dictionary(); private static bool _initialized = false; private static void Init() { if (!_initialized) { _initialized = true; Debug.Log("[Tortal] rune VFX: Seeking glowing, additive, unlit shaders worthy of Tortal."); } } private static long MakeCacheKey(Shader shader, Texture2D tex, Color color) { int num = ((shader != null) ? shader.GetInstanceID() : 0); int num2 = ((tex != null) ? tex.GetInstanceID() : 0); int hashCode = color.GetHashCode(); return (long)((ulong)((long)num << 32) ^ ((ulong)(uint)num2 << 16) ^ (uint)hashCode); } public static Material GetOrCreateRuneMaterial(Texture2D runeTex, Color color) { Init(); Shader shader = Shader.Find("Particles/Standard Unlit") ?? Shader.Find("Legacy Shaders/Particles/Alpha Blended") ?? Shader.Find("Particles/Alpha Blended") ?? Shader.Find("Particles/Additive"); if (shader == null) { float num = float.MinValue; Material[] array = Resources.FindObjectsOfTypeAll(); foreach (Material material in array) { if (!(material == null) && !(material.shader == null)) { Shader shader2 = material.shader; string text = shader2.name.ToLower(); float num2 = 0f; if (text.Contains("particle")) { num2 += 3f; } if (text.Contains("add")) { num2 += 3f; } if (text.Contains("unlit")) { num2 += 2f; } if (text.Contains("transparent")) { num2 += 1.5f; } if ((material.HasProperty("_Color") || material.HasProperty("_TintColor")) && num2 > num) { num = num2; shader = shader2; } } } } if (shader == null) { Debug.LogError("[Tortal] rune VFX: No glowing shader found. The runes refuse to shine."); return null; } long key = MakeCacheKey(shader, runeTex, color); if (_materialCache.TryGetValue(key, out var value) && value != null) { return value; } Material material2 = new Material(shader); if (runeTex != null) { if (material2.HasProperty("_MainTex")) { material2.SetTexture("_MainTex", runeTex); } if (material2.HasProperty("_BaseMap")) { material2.SetTexture("_BaseMap", runeTex); } try { material2.mainTexture = runeTex; } catch { } } if (material2.HasProperty("_Color")) { material2.SetColor("_Color", color); } if (material2.HasProperty("_TintColor")) { material2.SetColor("_TintColor", color); } if (material2.HasProperty("_EmissionColor")) { material2.SetColor("_EmissionColor", color * 3f); } material2.SetInt("_SrcBlend", 1); material2.SetInt("_DstBlend", 1); material2.SetInt("_ZWrite", 0); material2.DisableKeyword("_ALPHATEST_ON"); material2.EnableKeyword("_ALPHABLEND_ON"); material2.DisableKeyword("_ALPHAPREMULTIPLY_ON"); material2.renderQueue = 3000; _materialCache[key] = material2; Debug.Log("[Tortal] rune VFX: Forged glowing additive rune material from '" + shader.name + "'."); return material2; } public static void ClearCache() { _materialCache.Clear(); _initialized = false; } } } // ---- plugins/TortalPortal.dll :: TortalPortal.TortalRuneTexture ---- namespace TortalPortal { public static class TortalRuneTexture { private const int Size = 128; public static Texture2D GenerateRune(Color color) { int runeIndex = Mathf.Abs(color.GetHashCode()) % 16; return GenerateRune(color, runeIndex); } public static Texture2D GenerateRuneAtlas(Color color) { int num = 128; Texture2D texture2D = new Texture2D(512, 512, TextureFormat.RGBA32, mipChain: true) { filterMode = UnityEngine.FilterMode.Bilinear, wrapMode = TextureWrapMode.Clamp }; Color color2 = new Color(0f, 0f, 0f, 0f); Color[] array = new Color[512 * 512]; for (int i = 0; i < array.Length; i++) { array[i] = color2; } texture2D.SetPixels(array); for (int j = 0; j < 16; j++) { int num2 = j % 4; int num3 = 3 - j / 4; DrawRuneOntoAtlas(texture2D, color, j, num2 * num, num3 * num, num); } texture2D.Apply(updateMipmaps: true); return texture2D; } public static Texture2D GenerateSoftTrail(Color color) { Texture2D texture2D = new Texture2D(128, 128, TextureFormat.RGBA32, mipChain: false); texture2D.filterMode = UnityEngine.FilterMode.Bilinear; Vector2 b = new Vector2(64f, 64f); float num = 64f; for (int i = 0; i < 128; i++) { for (int j = 0; j < 128; j++) { float num2 = Vector2.Distance(new Vector2((float)j + 0.5f, (float)i + 0.5f), b) / num; float t = Mathf.Clamp01(1f - num2); t = Mathf.SmoothStep(0f, 1f, t); t = Mathf.Pow(t, 1.6f); Color color2 = new Color(color.r, color.g, color.b, color.a * t); texture2D.SetPixel(j, i, color2); } } texture2D.Apply(updateMipmaps: true); return texture2D; } public static Texture2D GenerateStreak(Color color) { Texture2D texture2D = new Texture2D(128, 128, TextureFormat.RGBA32, mipChain: false); texture2D.filterMode = UnityEngine.FilterMode.Bilinear; Vector2 vector = new Vector2(64f, 64f); float num = 64f; for (int i = 0; i < 128; i++) { for (int j = 0; j < 128; j++) { float t = Mathf.Abs((float)i + 0.5f - vector.y) / num; float num2 = Mathf.Abs((float)j + 0.5f - vector.x) / (num * 0.6f); float num3 = Mathf.Clamp01(1f - num2); float f = Mathf.SmoothStep(1f, 0f, t); num3 *= Mathf.Pow(f, 0.9f); Color color2 = new Color(color.r, color.g, color.b, color.a * num3); texture2D.SetPixel(j, i, color2); } } texture2D.Apply(updateMipmaps: true); return texture2D; } public static Texture2D GenerateBlend(Color color) { Texture2D texture2D = GenerateSoftTrail(color); Texture2D texture2D2 = GenerateRune(color); Texture2D texture2D3 = new Texture2D(128, 128, TextureFormat.RGBA32, mipChain: false); texture2D3.filterMode = UnityEngine.FilterMode.Bilinear; for (int i = 0; i < 128; i++) { for (int j = 0; j < 128; j++) { Color pixel = texture2D.GetPixel(j, i); Color pixel2 = texture2D2.GetPixel(j, i); float num = Mathf.Clamp01(pixel.a + pixel2.a * 0.65f); Color color2 = new Color(color.r, color.g, color.b, color.a * num); texture2D3.SetPixel(j, i, color2); } } texture2D3.Apply(updateMipmaps: true); return texture2D3; } private static void DrawRuneOntoAtlas(Texture2D tex, Color color, int runeIndex, int offsetX, int offsetY, int size) { Color c = new Color(color.r * 0.6f, color.g * 0.6f, color.b * 0.6f, 0.6f); Color c2 = new Color(color.r, color.g, color.b, 1f); float scale = (float)size / 128f; switch (runeIndex) { case 0: DrawLineLocal(20, 20, 108, 108, c, 6); DrawLineLocal(108, 20, 20, 108, c, 6); DrawLineLocal(20, 20, 108, 108, c2, 3); DrawLineLocal(108, 20, 20, 108, c2, 3); break; case 1: DrawLineLocal(64, 16, 64, 112, c, 6); DrawLineLocal(64, 64, 32, 96, c, 5); DrawLineLocal(64, 64, 96, 96, c, 5); DrawLineLocal(64, 16, 64, 112, c2, 3); DrawLineLocal(64, 64, 32, 96, c2, 2); DrawLineLocal(64, 64, 96, 96, c2, 2); break; case 2: DrawLineLocal(40, 20, 40, 108, c, 6); DrawLineLocal(40, 96, 96, 112, c, 5); DrawLineLocal(40, 72, 96, 88, c, 5); DrawLineLocal(40, 20, 40, 108, c2, 3); DrawLineLocal(40, 96, 96, 112, c2, 2); DrawLineLocal(40, 72, 96, 88, c2, 2); break; case 3: DrawLineLocal(40, 20, 40, 112, c, 6); DrawLineLocal(40, 96, 88, 112, c, 5); DrawLineLocal(88, 112, 88, 80, c, 5); DrawLineLocal(88, 80, 40, 96, c, 5); DrawLineLocal(40, 20, 40, 112, c2, 3); DrawLineLocal(40, 96, 88, 112, c2, 2); DrawLineLocal(88, 112, 88, 80, c2, 2); DrawLineLocal(88, 80, 40, 96, c2, 2); break; case 4: DrawLineLocal(64, 16, 64, 112, c, 8); DrawLineLocal(64, 16, 64, 112, c2, 4); break; case 5: DrawLineLocal(64, 16, 64, 112, c, 6); DrawLineLocal(64, 40, 32, 72, c, 5); DrawLineLocal(64, 40, 96, 72, c, 5); DrawLineLocal(64, 16, 64, 112, c2, 3); DrawLineLocal(64, 40, 32, 72, c2, 2); DrawLineLocal(64, 40, 96, 72, c2, 2); break; case 6: DrawLineLocal(36, 16, 36, 112, c, 6); DrawLineLocal(92, 16, 92, 112, c, 6); DrawLineLocal(36, 36, 92, 92, c, 5); DrawLineLocal(36, 16, 36, 112, c2, 3); DrawLineLocal(92, 16, 92, 112, c2, 3); DrawLineLocal(36, 36, 92, 92, c2, 2); break; case 7: DrawLineLocal(80, 20, 40, 20, c, 5); DrawLineLocal(80, 20, 40, 64, c, 5); DrawLineLocal(40, 64, 80, 108, c, 5); DrawLineLocal(80, 108, 40, 108, c, 5); DrawLineLocal(80, 20, 40, 20, c2, 2); DrawLineLocal(80, 20, 40, 64, c2, 2); DrawLineLocal(40, 64, 80, 108, c2, 2); DrawLineLocal(80, 108, 40, 108, c2, 2); break; case 8: DrawLineLocal(64, 16, 64, 112, c, 6); DrawLineLocal(96, 96, 32, 32, c, 5); DrawLineLocal(64, 16, 64, 112, c2, 3); DrawLineLocal(96, 96, 32, 32, c2, 2); break; case 9: DrawLineLocal(32, 48, 32, 112, c, 6); DrawLineLocal(96, 48, 96, 112, c, 6); DrawLineLocal(32, 48, 64, 16, c, 5); DrawLineLocal(64, 16, 96, 48, c, 5); DrawLineLocal(32, 48, 32, 112, c2, 3); DrawLineLocal(96, 48, 96, 112, c2, 3); DrawLineLocal(32, 48, 64, 16, c2, 2); DrawLineLocal(64, 16, 96, 48, c2, 2); break; case 10: DrawLineLocal(48, 16, 48, 112, c, 6); DrawLineLocal(48, 80, 96, 48, c, 5); DrawLineLocal(48, 16, 48, 112, c2, 3); DrawLineLocal(48, 80, 96, 48, c2, 2); break; case 11: DrawLineLocal(64, 112, 96, 72, c, 5); DrawLineLocal(96, 72, 64, 32, c, 5); DrawLineLocal(64, 32, 32, 72, c, 5); DrawLineLocal(32, 72, 64, 112, c, 5); DrawLineLocal(32, 72, 16, 16, c, 5); DrawLineLocal(96, 72, 112, 16, c, 5); DrawLineLocal(64, 112, 96, 72, c2, 2); DrawLineLocal(96, 72, 64, 32, c2, 2); DrawLineLocal(64, 32, 32, 72, c2, 2); DrawLineLocal(32, 72, 64, 112, c2, 2); DrawLineLocal(32, 72, 16, 16, c2, 2); DrawLineLocal(96, 72, 112, 16, c2, 2); break; case 12: DrawLineLocal(20, 20, 64, 64, c, 5); DrawLineLocal(20, 108, 64, 64, c, 5); DrawLineLocal(108, 20, 64, 64, c, 5); DrawLineLocal(108, 108, 64, 64, c, 5); DrawLineLocal(20, 20, 64, 64, c2, 2); DrawLineLocal(20, 108, 64, 64, c2, 2); DrawLineLocal(108, 20, 64, 64, c2, 2); DrawLineLocal(108, 108, 64, 64, c2, 2); break; case 13: DrawLineLocal(36, 16, 36, 112, c, 6); DrawLineLocal(36, 96, 80, 80, c, 5); DrawLineLocal(80, 80, 36, 64, c, 5); DrawLineLocal(36, 64, 80, 48, c, 5); DrawLineLocal(80, 48, 36, 32, c, 5); DrawLineLocal(36, 16, 36, 112, c2, 3); DrawLineLocal(36, 96, 80, 80, c2, 2); DrawLineLocal(80, 80, 36, 64, c2, 2); DrawLineLocal(36, 64, 80, 48, c2, 2); DrawLineLocal(80, 48, 36, 32, c2, 2); break; case 14: DrawLineLocal(32, 16, 32, 112, c, 6); DrawLineLocal(96, 16, 96, 112, c, 6); DrawLineLocal(32, 112, 96, 64, c, 5); DrawLineLocal(96, 112, 32, 64, c, 5); DrawLineLocal(32, 16, 32, 112, c2, 3); DrawLineLocal(96, 16, 96, 112, c2, 3); DrawLineLocal(32, 112, 96, 64, c2, 2); DrawLineLocal(96, 112, 32, 64, c2, 2); break; case 15: DrawLineLocal(64, 16, 108, 64, c, 6); DrawLineLocal(108, 64, 64, 112, c, 6); DrawLineLocal(64, 112, 20, 64, c, 6); DrawLineLocal(20, 64, 64, 16, c, 6); DrawLineLocal(64, 16, 108, 64, c2, 3); DrawLineLocal(108, 64, 64, 112, c2, 3); DrawLineLocal(64, 112, 20, 64, c2, 3); DrawLineLocal(20, 64, 64, 16, c2, 3); break; } void DrawLineLocal(int x0, int y0, int x1, int y1, Color c3, int thickness) { DrawLineAtlas(tex, offsetX + (int)((float)x0 * scale), offsetY + (int)((float)y0 * scale), offsetX + (int)((float)x1 * scale), offsetY + (int)((float)y1 * scale), c3, thickness, 512); } } public static Texture2D GenerateRune(Color color, int runeIndex) { Texture2D texture2D = new Texture2D(128, 128, TextureFormat.RGBA32, mipChain: true); texture2D.filterMode = UnityEngine.FilterMode.Bilinear; texture2D.wrapMode = TextureWrapMode.Clamp; Color color2 = new Color(0f, 0f, 0f, 0f); Color c = new Color(color.r * 0.6f, color.g * 0.6f, color.b * 0.6f, 0.6f); Color c2 = new Color(color.r, color.g, color.b, 1f); Color[] array = new Color[16384]; for (int i = 0; i < array.Length; i++) { array[i] = color2; } texture2D.SetPixels(array); switch (runeIndex) { case 0: DrawLine(texture2D, 20, 20, 108, 108, c, 6); DrawLine(texture2D, 108, 20, 20, 108, c, 6); DrawLine(texture2D, 20, 20, 108, 108, c2, 3); DrawLine(texture2D, 108, 20, 20, 108, c2, 3); break; case 1: DrawLine(texture2D, 64, 16, 64, 112, c, 6); DrawLine(texture2D, 64, 64, 32, 96, c, 5); DrawLine(texture2D, 64, 64, 96, 96, c, 5); DrawLine(texture2D, 64, 16, 64, 112, c2, 3); DrawLine(texture2D, 64, 64, 32, 96, c2, 2); DrawLine(texture2D, 64, 64, 96, 96, c2, 2); break; case 2: DrawLine(texture2D, 40, 20, 40, 108, c, 6); DrawLine(texture2D, 40, 96, 96, 112, c, 5); DrawLine(texture2D, 40, 72, 96, 88, c, 5); DrawLine(texture2D, 40, 20, 40, 108, c2, 3); DrawLine(texture2D, 40, 96, 96, 112, c2, 2); DrawLine(texture2D, 40, 72, 96, 88, c2, 2); break; case 3: DrawLine(texture2D, 40, 20, 40, 112, c, 6); DrawLine(texture2D, 40, 96, 88, 112, c, 5); DrawLine(texture2D, 88, 112, 88, 80, c, 5); DrawLine(texture2D, 88, 80, 40, 96, c, 5); DrawLine(texture2D, 40, 20, 40, 112, c2, 3); DrawLine(texture2D, 40, 96, 88, 112, c2, 2); DrawLine(texture2D, 88, 112, 88, 80, c2, 2); DrawLine(texture2D, 88, 80, 40, 96, c2, 2); break; case 4: DrawLine(texture2D, 64, 16, 64, 112, c, 8); DrawLine(texture2D, 64, 16, 64, 112, c2, 4); break; case 5: DrawLine(texture2D, 64, 16, 64, 112, c, 6); DrawLine(texture2D, 64, 40, 32, 72, c, 5); DrawLine(texture2D, 64, 40, 96, 72, c, 5); DrawLine(texture2D, 64, 16, 64, 112, c2, 3); DrawLine(texture2D, 64, 40, 32, 72, c2, 2); DrawLine(texture2D, 64, 40, 96, 72, c2, 2); break; case 6: DrawLine(texture2D, 36, 16, 36, 112, c, 6); DrawLine(texture2D, 92, 16, 92, 112, c, 6); DrawLine(texture2D, 36, 36, 92, 92, c, 5); DrawLine(texture2D, 36, 16, 36, 112, c2, 3); DrawLine(texture2D, 92, 16, 92, 112, c2, 3); DrawLine(texture2D, 36, 36, 92, 92, c2, 2); break; default: DrawLine(texture2D, 80, 20, 40, 20, c, 5); DrawLine(texture2D, 80, 20, 40, 64, c, 5); DrawLine(texture2D, 40, 64, 80, 108, c, 5); DrawLine(texture2D, 80, 108, 40, 108, c, 5); DrawLine(texture2D, 80, 20, 40, 20, c2, 2); DrawLine(texture2D, 80, 20, 40, 64, c2, 2); DrawLine(texture2D, 40, 64, 80, 108, c2, 2); DrawLine(texture2D, 80, 108, 40, 108, c2, 2); break; case 8: DrawLine(texture2D, 64, 16, 64, 112, c, 6); DrawLine(texture2D, 96, 96, 32, 32, c, 5); DrawLine(texture2D, 64, 16, 64, 112, c2, 3); DrawLine(texture2D, 96, 96, 32, 32, c2, 2); break; case 9: DrawLine(texture2D, 32, 48, 32, 112, c, 6); DrawLine(texture2D, 96, 48, 96, 112, c, 6); DrawLine(texture2D, 32, 48, 64, 16, c, 5); DrawLine(texture2D, 64, 16, 96, 48, c, 5); DrawLine(texture2D, 32, 48, 32, 112, c2, 3); DrawLine(texture2D, 96, 48, 96, 112, c2, 3); DrawLine(texture2D, 32, 48, 64, 16, c2, 2); DrawLine(texture2D, 64, 16, 96, 48, c2, 2); break; case 10: DrawLine(texture2D, 48, 16, 48, 112, c, 6); DrawLine(texture2D, 48, 80, 96, 48, c, 5); DrawLine(texture2D, 48, 16, 48, 112, c2, 3); DrawLine(texture2D, 48, 80, 96, 48, c2, 2); break; case 11: DrawLine(texture2D, 64, 112, 96, 72, c, 5); DrawLine(texture2D, 96, 72, 64, 32, c, 5); DrawLine(texture2D, 64, 32, 32, 72, c, 5); DrawLine(texture2D, 32, 72, 64, 112, c, 5); DrawLine(texture2D, 32, 72, 16, 16, c, 5); DrawLine(texture2D, 96, 72, 112, 16, c, 5); DrawLine(texture2D, 64, 112, 96, 72, c2, 2); DrawLine(texture2D, 96, 72, 64, 32, c2, 2); DrawLine(texture2D, 64, 32, 32, 72, c2, 2); DrawLine(texture2D, 32, 72, 64, 112, c2, 2); DrawLine(texture2D, 32, 72, 16, 16, c2, 2); DrawLine(texture2D, 96, 72, 112, 16, c2, 2); break; case 12: DrawLine(texture2D, 20, 20, 64, 64, c, 5); DrawLine(texture2D, 20, 108, 64, 64, c, 5); DrawLine(texture2D, 108, 20, 64, 64, c, 5); DrawLine(texture2D, 108, 108, 64, 64, c, 5); DrawLine(texture2D, 20, 20, 64, 64, c2, 2); DrawLine(texture2D, 20, 108, 64, 64, c2, 2); DrawLine(texture2D, 108, 20, 64, 64, c2, 2); DrawLine(texture2D, 108, 108, 64, 64, c2, 2); break; case 13: DrawLine(texture2D, 36, 16, 36, 112, c, 6); DrawLine(texture2D, 36, 96, 80, 80, c, 5); DrawLine(texture2D, 80, 80, 36, 64, c, 5); DrawLine(texture2D, 36, 64, 80, 48, c, 5); DrawLine(texture2D, 80, 48, 36, 32, c, 5); DrawLine(texture2D, 36, 16, 36, 112, c2, 3); DrawLine(texture2D, 36, 96, 80, 80, c2, 2); DrawLine(texture2D, 80, 80, 36, 64, c2, 2); DrawLine(texture2D, 36, 64, 80, 48, c2, 2); DrawLine(texture2D, 80, 48, 36, 32, c2, 2); break; case 14: DrawLine(texture2D, 32, 16, 32, 112, c, 6); DrawLine(texture2D, 96, 16, 96, 112, c, 6); DrawLine(texture2D, 32, 112, 96, 64, c, 5); DrawLine(texture2D, 96, 112, 32, 64, c, 5); DrawLine(texture2D, 32, 16, 32, 112, c2, 3); DrawLine(texture2D, 96, 16, 96, 112, c2, 3); DrawLine(texture2D, 32, 112, 96, 64, c2, 2); DrawLine(texture2D, 96, 112, 32, 64, c2, 2); break; case 15: DrawLine(texture2D, 64, 16, 108, 64, c, 6); DrawLine(texture2D, 108, 64, 64, 112, c, 6); DrawLine(texture2D, 64, 112, 20, 64, c, 6); DrawLine(texture2D, 20, 64, 64, 16, c, 6); DrawLine(texture2D, 64, 16, 108, 64, c2, 3); DrawLine(texture2D, 108, 64, 64, 112, c2, 3); DrawLine(texture2D, 64, 112, 20, 64, c2, 3); DrawLine(texture2D, 20, 64, 64, 16, c2, 3); break; } texture2D.Apply(updateMipmaps: true); return texture2D; } private static void DrawLineAtlas(Texture2D tex, int x0, int y0, int x1, int y1, Color c, int thickness, int atlasSize) { int num = Mathf.Abs(x1 - x0); int num2 = Mathf.Abs(y1 - y0); int num3 = ((x0 < x1) ? 1 : (-1)); int num4 = ((y0 < y1) ? 1 : (-1)); int num5 = num - num2; while (true) { DrawCircleAtlas(tex, x0, y0, thickness, c, atlasSize); if (x0 != x1 || y0 != y1) { int num6 = 2 * num5; if (num6 > -num2) { num5 -= num2; x0 += num3; } if (num6 < num) { num5 += num; y0 += num4; } continue; } break; } } private static void DrawCircleAtlas(Texture2D tex, int cx, int cy, int r, Color c, int atlasSize) { for (int i = -r; i <= r; i++) { for (int j = -r; j <= r; j++) { if (j * j + i * i <= r * r) { int num = cx + j; int num2 = cy + i; if (num >= 0 && num < atlasSize && num2 >= 0 && num2 < atlasSize) { tex.SetPixel(num, num2, c); } } } } } private static void DrawLine(Texture2D tex, int x0, int y0, int x1, int y1, Color c, int thickness) { int num = Mathf.Abs(x1 - x0); int num2 = Mathf.Abs(y1 - y0); int num3 = ((x0 < x1) ? 1 : (-1)); int num4 = ((y0 < y1) ? 1 : (-1)); int num5 = num - num2; while (true) { DrawCircle(tex, x0, y0, thickness, c); if (x0 != x1 || y0 != y1) { int num6 = 2 * num5; if (num6 > -num2) { num5 -= num2; x0 += num3; } if (num6 < num) { num5 += num; y0 += num4; } continue; } break; } } private static void DrawCircle(Texture2D tex, int cx, int cy, int r, Color c) { for (int i = -r; i <= r; i++) { for (int j = -r; j <= r; j++) { if (j * j + i * i <= r * r) { int num = cx + j; int num2 = cy + i; if (num >= 0 && num < 128 && num2 >= 0 && num2 < 128) { tex.SetPixel(num, num2, c); } } } } } } }