Please disclose if your mod was created primarily using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of ValhallaEvolvedWard v1.0.1
ValhallaWard.dll
Decompiled 2 years ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Diagnostics; using System.Dynamic; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Xml.Serialization; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using ServerSync; using TMPro; using UnityEngine; using UnityEngine.Audio; using UnityEngine.Events; using UnityEngine.UI; using fastJSON; [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: Guid("3AEF396B-2C4A-4EE1-94F3-204AA9A949C2")] [assembly: ComVisible(false)] [assembly: AssemblyTrademark("")] [assembly: AssemblyCopyright("Copyright © 2023")] [assembly: AssemblyProduct("PyroWard")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyDescription("")] [assembly: AssemblyTitle("PyroWard")] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: CompilationRelaxations(8)] [assembly: TargetFramework(".NETFramework,Version=v4.6.2", FrameworkDisplayName = ".NET Framework 4.6.2")] [assembly: AssemblyCompany("")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [Microsoft.CodeAnalysis.Embedded] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] [Microsoft.CodeAnalysis.Embedded] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ServerSync { [PublicAPI] public abstract class OwnConfigEntryBase { public object? LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [PublicAPI] public class SyncedConfigEntry<T> : OwnConfigEntryBase { public readonly ConfigEntry<T> SourceConfig; public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig; public T Value { get { return SourceConfig.Value; } set { SourceConfig.Value = value; } } public SyncedConfigEntry(ConfigEntry<T> sourceConfig) { SourceConfig = sourceConfig; } public void AssignLocalValue(T value) { if (LocalBaseValue == null) { Value = value; } else { LocalBaseValue = value; } } } public abstract class CustomSyncedValueBase { public object? LocalBaseValue; public readonly string Identifier; public readonly Type Type; private object? boxedValue; protected bool localIsOwner; public object? BoxedValue { get { return boxedValue; } set { boxedValue = value; this.ValueChanged?.Invoke(); } } public event Action? ValueChanged; protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type) { Identifier = identifier; Type = type; configSync.AddCustomValue(this); localIsOwner = configSync.IsSourceOfTruth; configSync.SourceOfTruthChanged += delegate(bool truth) { localIsOwner = truth; }; } } [PublicAPI] public sealed class CustomSyncedValue<T> : CustomSyncedValueBase { public T Value { get { return (T)base.BoxedValue; } set { base.BoxedValue = value; } } public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T)) : base(configSync, identifier, typeof(T)) { Value = value; } public void AssignLocalValue(T value) { if (localIsOwner) { Value = value; } else { LocalBaseValue = value; } } } internal class ConfigurationManagerAttributes { [UsedImplicitly] public bool? ReadOnly = false; } [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<ZPackage>(configSync2.Name + " ConfigSync", (Action<long, ZPackage>)configSync2.RPC_FromOtherClientConfigSync); if (isServer) { configSync2.InitialSyncDone = true; Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections")); } } if (isServer) { ((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges()); } static void SendAdmin(List<ZNetPeer> 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) { ((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package)); } } static IEnumerator WatchAdminListChanges() { SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); List<string> CurrentList = new List<string>(adminList.GetList()); while (true) { yield return (object)new WaitForSeconds(30f); if (!adminList.GetList().SequenceEqual(CurrentList)) { CurrentList = new List<string>(adminList.GetList()); List<ZNetPeer> list = (from p in ZNet.instance.GetPeers() where adminList.Contains(p.m_rpc.GetSocket().GetHostName()) select p).ToList(); List<ZNetPeer> peers2 = ZNet.instance.GetPeers().Except(list).ToList(); SendAdmin(peers2, 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<ZPackage>(configSync.Name + " ConfigSync", (Action<ZRpc, ZPackage>)configSync.RPC_FromServerConfigSync); } } } private class ParsedConfigs { public readonly Dictionary<OwnConfigEntryBase, object?> configValues = new Dictionary<OwnConfigEntryBase, object>(); public readonly Dictionary<CustomSyncedValueBase, object?> customValues = new Dictionary<CustomSyncedValueBase, object>(); } [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 { public volatile bool finished; public volatile int versionMatchQueued = -1; public readonly List<ZPackage> Package = new List<ZPackage>(); public readonly ISocket Original; public BufferingSocket(ISocket original) { Original = original; } public bool IsConnected() { return Original.IsConnected(); } public ZPackage Recv() { return Original.Recv(); } public int GetSendQueueSize() { return Original.GetSendQueueSize(); } public int GetCurrentSendRate() { return Original.GetCurrentSendRate(); } public bool IsHost() { return Original.IsHost(); } public void Dispose() { Original.Dispose(); } public bool GotNewData() { return Original.GotNewData(); } public void Close() { Original.Close(); } public string GetEndPointString() { return Original.GetEndPointString(); } public void GetAndResetStats(out int totalSent, out int totalRecv) { Original.GetAndResetStats(ref totalSent, ref totalRecv); } public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec) { Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec); } public ISocket Accept() { return Original.Accept(); } public int GetHostPort() { return Original.GetHostPort(); } public bool Flush() { return Original.Flush(); } public string GetHostName() { return Original.GetHostName(); } public void VersionMatch() { if (finished) { Original.VersionMatch(); } else { versionMatchQueued = Package.Count; } } public void Send(ZPackage pkg) { //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Expected O, but got Unknown int pos = pkg.GetPos(); pkg.SetPos(0); int num = pkg.ReadInt(); if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished) { ZPackage val = new ZPackage(pkg.GetArray()); val.SetPos(pos); Package.Add(val); } else { pkg.SetPos(pos); Original.Send(pkg); } } } [HarmonyPriority(800)] [HarmonyPrefix] private static void Prefix(ref Dictionary<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc) { //IL_0073: Unknown result type (might be due to invalid IL or missing references) if (__instance.IsServer()) { BufferingSocket value = new BufferingSocket(rpc.GetSocket()); AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, value); object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (val != null && (int)ZNet.m_onlineBackend != 0) { AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, value); } if (__state == null) { __state = new Dictionary<Assembly, BufferingSocket>(); } __state[Assembly.GetExecutingAssembly()] = value; } } [HarmonyPostfix] private static void Postfix(Dictionary<Assembly, BufferingSocket> __state, ZNet __instance, ZRpc rpc) { ZNetPeer peer; if (__instance.IsServer()) { object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (peer == null) { SendBufferedData(); } else { ((MonoBehaviour)__instance).StartCoroutine(sendAsync()); } } void SendBufferedData() { if (rpc.GetSocket() is BufferingSocket bufferingSocket) { AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original); object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val2 = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null); if (val2 != null) { AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val2, 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(); } } IEnumerator sendAsync() { foreach (ConfigSync configSync in configSyncs) { List<PackageEntry> list = new List<PackageEntry>(); 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", (Type[])null, (Type[])null); SyncedList val = (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)val.Contains(rpc.GetSocket().GetHostName())) : methodInfo.Invoke(ZNet.instance, new object[2] { val, rpc.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, list, partial: false); yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package)); } SendBufferedData(); } } } 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((object)$"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<ConfigSync> configSyncs; private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>(); private readonly HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>(); 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<string, SortedDictionary<int, byte[]>> configValueCache = new Dictionary<string, SortedDictionary<int, byte[]>>(); private readonly List<KeyValuePair<long, string>> cacheExpirations = new List<KeyValuePair<long, string>>(); 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.GetValueOrDefault(); } 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<bool>? SourceOfTruthChanged; private event Action? lockedConfigChanged; static ConfigSync() { ProcessingServerUpdate = false; configSyncs = new HashSet<ConfigSync>(); lockExempt = false; packageCounter = 0L; RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle); } public ConfigSync(string name) { Name = name; configSyncs.Add(this); new VersionCheck(this); } public SyncedConfigEntry<T> AddConfigEntry<T>(ConfigEntry<T> configEntry) { OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry); SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry<T>(configEntry); AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray()); configEntry.SettingChanged += delegate { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry<T> AddLockingConfigEntry<T>(ConfigEntry<T> lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry<T>(lockingConfig); lockingConfig.SettingChanged += delegate { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry<T>)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); 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) { //IL_0212: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Expected O, but got Unknown //IL_01b9: Unknown result type (might be due to invalid IL or missing references) //IL_01c0: Expected O, but got Unknown //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Expected O, but got Unknown try { if (isServer && IsLocked) { ZRpc? currentRpc = SnatchCurrentlyHandlingRPC.currentRpc; object obj; if (currentRpc == null) { obj = null; } else { ISocket socket = currentRpc.GetSocket(); obj = ((socket != null) ? socket.GetHostName() : null); } string text = (string)obj; if (text != null) { MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text })))) { return false; } } } cacheExpirations.RemoveAll(delegate(KeyValuePair<long, string> kv) { if (kv.Key < DateTimeOffset.Now.Ticks) { configValueCache.Remove(kv.Value); return true; } return false; }); byte b = package.ReadByte(); if ((b & 2u) != 0) { long num = package.ReadLong(); string text2 = sender.ToString() + num; if (!configValueCache.TryGetValue(text2, out var value)) { value = new SortedDictionary<int, byte[]>(); configValueCache[text2] = value; cacheExpirations.Add(new KeyValuePair<long, string>(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 & 4u) != 0) { byte[] buffer = package.ReadByteArray(); MemoryStream stream = new MemoryStream(buffer); 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); foreach (KeyValuePair<OwnConfigEntryBase, object> configValue in parsedConfigs.configValues) { if (!isServer && configValue.Key.LocalBaseValue == null) { configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue; } configValue.Key.BaseConfig.BoxedValue = configValue.Value; } foreach (KeyValuePair<CustomSyncedValueBase, object> 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((object)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<string, OwnConfigEntryBase> dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c); Dictionary<string, CustomSyncedValueBase> dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c); int num = package.ReadInt(); for (int i = 0; i < num; i++) { 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((object)("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((object)("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((object)("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((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName)); } else { Debug.LogWarning((object)("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((object)("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<ConfigurationManagerAttributes>(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig); } } private void resetConfigsFromServer() { foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null)) { item.BaseConfig.BoxedValue = item.LocalBaseValue; item.LocalBaseValue = null; } foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null)) { item2.BoxedValue = item2.LocalBaseValue; item2.LocalBaseValue = null; } lockedConfigChanged -= serverLockedSettingChanged; serverLockedSettingChanged(); } private IEnumerator<bool> 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 val = new ZPackage(); val.Write((byte)2); val.Write(packageIdentifier); val.Write(fragment); val.Write(fragments); val.Write(data.Skip(250000 * fragment).Take(250000).ToArray()); SendPackage(val); 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, new object[1] { pkg }); } else { rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg }); } } IEnumerable<bool> waitForQueue() { float timeout = Time.time + 30f; while (peer.m_socket.GetSendQueueSize() > 20000) { if (Time.time > timeout) { Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout"); peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 }); ZNet.instance.Disconnect(peer); break; } yield return false; } } } private IEnumerator sendZPackage(long target, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { return Enumerable.Empty<object>().GetEnumerator(); } List<ZNetPeer> list = (List<ZNetPeer>)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<ZNetPeer> peers, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { yield break; } byte[] array = package.GetArray(); if (array != null && array.LongLength > 10000) { ZPackage val = new ZPackage(); val.Write((byte)4); MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionLevel.Optimal)) { deflateStream.Write(array, 0, array.Length); } val.Write(memoryStream.ToArray()); package = val; } List<IEnumerator<bool>> writers = (from peer in peers where peer.IsReady() select peer into p select distributeConfigToPeers(p, package)).ToList(); writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext()); while (writers.Count > 0) { yield return null; writers.RemoveAll((IEnumerator<bool> writer) => !writer.MoveNext()); } } private void Broadcast(long target, params ConfigEntryBase[] configs) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(configs); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } private void Broadcast(long target, params CustomSyncedValueBase[] customValues) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(null, customValues); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } private static OwnConfigEntryBase? configData(ConfigEntryBase config) { return config.Description.Tags?.OfType<OwnConfigEntryBase>().SingleOrDefault(); } public static SyncedConfigEntry<T>? ConfigData<T>(ConfigEntry<T> config) { return ((ConfigEntryBase)config).Description.Tags?.OfType<SyncedConfigEntry<T>>().SingleOrDefault(); } private static T configAttribute<T>(ConfigEntryBase config) { return config.Description.Tags.OfType<T>().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<ConfigEntryBase>? configs = null, IEnumerable<CustomSyncedValueBase>? customValues = null, IEnumerable<PackageEntry>? packageEntries = null, bool partial = true) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Expected O, but got Unknown List<ConfigEntryBase> list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List<ConfigEntryBase>(); List<CustomSyncedValueBase> list2 = customValues?.ToList() ?? new List<CustomSyncedValueBase>(); ZPackage val = new ZPackage(); val.Write((byte)(partial ? 1 : 0)); val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0)); foreach (PackageEntry item in packageEntries ?? Array.Empty<PackageEntry>()) { AddEntryToPackage(val, item); } foreach (CustomSyncedValueBase item2 in list2) { AddEntryToPackage(val, new PackageEntry { section = "Internal", key = item2.Identifier, type = item2.Type, value = item2.BoxedValue }); } foreach (ConfigEntryBase item3 in list) { AddEntryToPackage(val, new PackageEntry { section = item3.Definition.Section, key = item3.Definition.Key, type = configType(item3), value = item3.BoxedValue }); } return val; } 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<string>) && type.IsGenericType) { Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]); if ((object)type3 != null && type3.IsAssignableFrom(type.GetGenericTypeDefinition())) { 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<object> source = new List<object>(); ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source); return source.First(); } } [HarmonyPatch] [PublicAPI] public class VersionCheck { private static readonly HashSet<VersionCheck> versionChecks; private static readonly Dictionary<string, string> 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<ZRpc> ValidatedClients = new List<ZRpc>(); 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() { //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Expected O, but got Unknown Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null)); if (patchInfo != null && patchInfo.Postfixes.Count((Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0) { return; } Harmony val = 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) { val.PatchAll(item); } } static VersionCheck() { versionChecks = new HashSet<VersionCheck>(); notProcessedNames = new Dictionary<string, string>(); 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 flag = new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion); bool flag2 = new Version(ReceivedCurrentVersion) >= new Version(MinimumRequiredVersion); return flag && flag2; } private string ErrorClient() { if (ReceivedMinimumRequiredVersion == null) { return "Mod " + DisplayName + " must not be installed."; } if (!(new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion))) { return "Mod " + DisplayName + " requires minimum " + ReceivedMinimumRequiredVersion + ". Installed is version " + CurrentVersion + "."; } return "Mod " + DisplayName + " requires maximum " + ReceivedCurrentVersion + ". Installed is 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(true, true); AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3); } private static void DisconnectClient(ZRpc rpc) { rpc.Invoke("Error", new object[1] { 3 }); } private static void CheckVersion(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, null); } private static void CheckVersion(ZRpc rpc, ZPackage pkg, Action<ZRpc, ZPackage>? 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((object)("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; foreach (VersionCheck versionCheck in array2) { Debug.LogWarning((object)versionCheck.Error(rpc)); } if (__instance.IsServer()) { DisconnectClient(rpc); } else { Logout(); } return false; } [HarmonyPrefix] [HarmonyPatch(typeof(ZNet), "OnNewConnection")] private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance) { //IL_0172: Unknown result type (might be due to invalid IL or missing references) //IL_0179: Expected O, but got Unknown notProcessedNames.Clear(); IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc); if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck"))) { object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")]; Action<ZRpc, ZPackage> action = (Action<ZRpc, ZPackage>)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj); peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)delegate(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, action); }); } else { peer.m_rpc.Register<ZPackage>("ServerSync VersionCheck", (Action<ZRpc, ZPackage>)CheckVersion); } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.Initialize(); if (versionCheck.ModRequired || __instance.IsServer()) { Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + ".")); ZPackage val = new ZPackage(); val.Write(versionCheck.Name); val.Write(versionCheck.MinimumRequiredVersion); val.Write(versionCheck.CurrentVersion); peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val }); } } } [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); } } [HarmonyPostfix] [HarmonyPatch(typeof(FejdStartup), "ShowConnectError")] private static void ShowConnectionError(FejdStartup __instance) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Invalid comparison between Unknown and I4 if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3) { return; } 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; } foreach (KeyValuePair<string, string> item in notProcessedNames.OrderBy((KeyValuePair<string, string> kv) => kv.Key)) { if (!__instance.m_connectionFailedError.text.Contains(item.Key)) { TMP_Text connectionFailedError2 = __instance.m_connectionFailedError; connectionFailedError2.text = connectionFailedError2.text + "\n" + item.Key + " (Version: " + item.Value + ")"; } } } } } namespace PyroWard { [BepInPlugin("kg.PyroWard", "kg.PyroWard", "1.0.0")] public class PyroWard : BaseUnityPlugin { [HarmonyPatch(typeof(Terminal), "Awake")] private static class Terminal_Awake_Patch { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static ConsoleEvent <>9__0_0; internal void <Postfix>b__0_0(ConsoleEventArgs context) { EnableWardSounds.Value = !EnableWardSounds.Value; context.Context.AddString("Ward Sounds " + (EnableWardSounds.Value ? "<color=green>Enabled</color>" : "<color=red>Disabled</color>")); ((ConfigEntryBase)EnableWardSounds).ConfigFile.Save(); } } [UsedImplicitly] private static void Postfix(Terminal __instance) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Expected O, but got Unknown object obj = <>c.<>9__0_0; if (obj == null) { ConsoleEvent val = delegate(ConsoleEventArgs context) { EnableWardSounds.Value = !EnableWardSounds.Value; context.Context.AddString("Ward Sounds " + (EnableWardSounds.Value ? "<color=green>Enabled</color>" : "<color=red>Disabled</color>")); ((ConfigEntryBase)EnableWardSounds).ConfigFile.Save(); }; <>c.<>9__0_0 = val; obj = (object)val; } new ConsoleCommand("muteward", "Mute Ward Sounds", (ConsoleEvent)obj, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); } } [HarmonyPatch] private static class Game_Awake_Patch { public static IEnumerable<MethodInfo> TargetMethods() { yield return AccessTools.Method(typeof(ZNet), "Start", (Type[])null, (Type[])null); yield return AccessTools.Method(typeof(FejdStartup), "Awake", (Type[])null, (Type[])null); } private static void Postfix() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) _localUserID = (((int)ZNet.m_onlineBackend == 0) ? PrivilegeManager.GetNetworkUserId().Split(new char[1] { '_' })[1] : PrivilegeManager.GetNetworkUserId()); if (string.IsNullOrWhiteSpace(_localUserID)) { _localUserID = "ERROR"; } } } [HarmonyPatch(typeof(Player), "PlacePiece", new Type[] { typeof(Piece) })] private static class PlacePiece_Patch { private static bool Prefix(Piece piece) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)((Component)piece).GetComponent<PyroWard_Component>())) { return true; } if (!PyroWard_Component.CanBuild(Player.m_localPlayer.m_placementGhost.transform.position)) { ((Character)Player.m_localPlayer).Message((MessageType)2, "Other ward near", 0, (Sprite)null); return false; } if (!_canPlaceWard && !Player.m_debugMode) { MessageHud.instance.ShowMessage((MessageType)2, "<color=red>Ward Limit</color>", 0, (Sprite)null); return false; } return true; } } [HarmonyPatch(typeof(ZNetScene), "Awake")] private static class ZNetScene_Awake_Patch { private static void Postfix(ZNetScene __instance) { if (isServer) { ZRoutedRpc.instance.Register("PyroWard wardplaced", (Action<long>)WardPlaced); return; } ZRoutedRpc.instance.Register<bool>("PyroWard Data", (Action<long, bool>)ReceiveData_PyroWard); List<GameObject> pieces = __instance.GetPrefab("Hammer").GetComponent<ItemDrop>().m_itemData.m_shared.m_buildPieces.m_pieces; if (!pieces.Contains(Ward_Prefab)) { pieces.Add(Ward_Prefab); } __instance.m_prefabs.Add(FlashShield); __instance.m_namedPrefabs.Add(StringExtensionMethods.GetStableHashCode(((Object)FlashShield).name), FlashShield); __instance.m_prefabs.Add(FlashShield_Permit); __instance.m_namedPrefabs.Add(StringExtensionMethods.GetStableHashCode(((Object)FlashShield_Permit).name), FlashShield_Permit); __instance.m_prefabs.Add(FlashShield_Fuel); __instance.m_namedPrefabs.Add(StringExtensionMethods.GetStableHashCode(((Object)FlashShield_Fuel).name), FlashShield_Fuel); __instance.m_prefabs.Add(FlashShield_Activate); __instance.m_namedPrefabs.Add(StringExtensionMethods.GetStableHashCode(((Object)FlashShield_Activate).name), FlashShield_Activate); __instance.m_prefabs.Add(FlashShield_Deactivate); __instance.m_namedPrefabs.Add(StringExtensionMethods.GetStableHashCode(((Object)FlashShield_Deactivate).name), FlashShield_Deactivate); __instance.m_prefabs.Add(Ward_Prefab); __instance.m_namedPrefabs.Add(StringExtensionMethods.GetStableHashCode(((Object)Ward_Prefab).name), Ward_Prefab); } private static void WardPlaced(long sender) { ZNetPeer peer = ZNet.instance.GetPeer(sender); if (peer != null) { string hostName = peer.m_socket.GetHostName(); if (_wardManager.PlayersWardData.ContainsKey(hostName)) { _wardManager.PlayersWardData[hostName]++; } else { _wardManager.PlayersWardData[hostName] = 1; } _wardManager.Save(); ZRoutedRpc.instance.InvokeRoutedRPC(peer.m_uid, "PyroWard Data", new object[1] { _wardManager.CanBuildWard(hostName) }); } } private static void ReceiveData_PyroWard(long sender, bool data) { _canPlaceWard = data; } } [HarmonyPatch(typeof(AudioMan), "Awake")] private static class AudioMan_Awake_Patch { [UsedImplicitly] private static void Postfix(AudioMan __instance) { AudioMixerGroup outputAudioMixerGroup = __instance.m_masterMixer.FindMatchingGroups("SFX")[0]; GameObject[] array = asset.LoadAllAssets<GameObject>(); foreach (GameObject val in array) { AudioSource[] componentsInChildren = val.GetComponentsInChildren<AudioSource>(true); foreach (AudioSource val2 in componentsInChildren) { val2.outputAudioMixerGroup = outputAudioMixerGroup; } } GameObject[] array2 = asset_vfx.LoadAllAssets<GameObject>(); foreach (GameObject val3 in array2) { AudioSource[] componentsInChildren2 = val3.GetComponentsInChildren<AudioSource>(true); foreach (AudioSource val4 in componentsInChildren2) { val4.outputAudioMixerGroup = outputAudioMixerGroup; } } } } public class PyroWard_Component : MonoBehaviour, Interactable, Hoverable { private static readonly List<PyroWard_Component> _instances = new List<PyroWard_Component>(); private ZNetView _znet; public Piece _piece; private CircleProjector _areaMarker_main; private List<Material> _wardMaterials; private Transform _playerBase; private Transform SFX; private int LastFlashTime; private int _areaMarkerTimer; public bool ForceButtonEnabled { get { if (_znet.IsValid()) { return _znet.m_zdo.GetBool("ForceButtonEnabled", false); } return false; } set { _znet.m_zdo.Set("ForceButtonEnabled", value); } } private float Fuel { get { if (!_znet.IsValid()) { return 0f; } return _znet.m_zdo.GetFloat("Fuel", 0f); } set { _znet.m_zdo.Set("Fuel", value); } } private int LastUpdateTime { get { if (!_znet.IsValid()) { return 0; } return _znet.m_zdo.GetInt("LastUpdateTime", 0); } set { _znet.m_zdo.Set("LastUpdateTime", value); } } public int Radius { get { if (!_znet.IsValid()) { return 0; } return _znet.m_zdo.GetInt("Radius", 0); } set { _znet.m_zdo.Set("Radius", value); } } public static bool CanBuild(Vector3 pos) { //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) foreach (PyroWard_Component instance in _instances) { if (!instance.IsPermitted(Player.m_localPlayer.GetPlayerID()) && Vector3.Distance(((Component)instance._piece).transform.position, pos) <= 100f) { return false; } } return true; } private void OnDestroy() { _instances.Remove(this); } public bool IsEnabled() { if (ForceButtonEnabled) { return Fuel > 0f; } return false; } public static PyroWard_Component TryFindWard(Vector3 objectPos, bool enabledOnly = true) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) foreach (PyroWard_Component instance in _instances) { if ((instance.IsEnabled() || !enabledOnly) && instance.IsInside_Main(objectPos)) { return instance; } } return null; } private void Awake() { //IL_00f7: Unknown result type (might be due to invalid IL or missing references) _znet = ((Component)this).GetComponent<ZNetView>(); _areaMarker_main = ((Component)((Component)this).transform.Find("AreaMarket_Main")).GetComponent<CircleProjector>(); _playerBase = ((Component)this).transform.Find("PlayerBase"); SFX = ((Component)this).transform.Find("VFX/sfx"); if (_znet.IsValid()) { _instances.Add(this); _piece = ((Component)this).GetComponent<Piece>(); _wardMaterials = (from x in ((Component)((Component)this).transform).GetComponentsInChildren<MeshRenderer>(true) select ((Renderer)x).material).ToList(); ((MonoBehaviour)this).InvokeRepeating("UpdateStatus", 1f, 1f); if (_znet.IsOwner() && GetCreatorName() == "") { Setup(Game.instance.GetPlayerProfile().GetName(), ((int)ZNet.m_onlineBackend == 0) ? PrivilegeManager.GetNetworkUserId().Split(new char[1] { '_' })[1] : PrivilegeManager.GetNetworkUserId()); } ((Component)_areaMarker_main).gameObject.SetActive(false); _znet.Register("RPC_Interact", (Action<long>)IteractWithWardSwitch); _znet.Register<int>("RPC_AddFuel", (Action<long, int>)RPC_AddFuel); } } private void RPC_AddFuel(long arg1, int amount) { if (_znet.IsOwner()) { Fuel = Mathf.Min(Fuel + (float)amount, (float)WardMaxFuel.Value); } } private void IteractWithWardSwitch(long obj) { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) if (_znet.IsOwner()) { ForceButtonEnabled = !ForceButtonEnabled; Object.Instantiate<GameObject>(ForceButtonEnabled ? FlashShield_Activate : FlashShield_Deactivate, ((Component)this).transform.position, Quaternion.identity); } } public void Flash() { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) if (!(EnvMan.instance.m_totalSeconds - (double)LastFlashTime <= 2.0)) { LastFlashTime = (int)EnvMan.instance.m_totalSeconds; GameObject val = Object.Instantiate<GameObject>(FlashShield, ((Component)this).transform.position, Quaternion.identity); int radius = Radius; val.transform.Find("Dome").localScale = new Vector3((float)radius, (float)radius, (float)radius); } } private void UpdateAreaMarker() { //IL_004b: Unknown result type (might be due to invalid IL or missing references) _areaMarkerTimer++; if (_areaMarkerTimer >= 3) { _areaMarkerTimer = 0; _areaMarker_main.m_radius = Radius; _playerBase.localScale = new Vector3((float)Radius, (float)Radius, (float)Radius); } } private void UpdateStatus() { //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Unknown result type (might be due to invalid IL or missing references) UpdateAreaMarker(); bool flag = IsEnabled(); if (flag) { _wardMaterials.ForEach(delegate(Material m) { m.EnableKeyword("_EMISSION"); }); ((Component)((Component)this).transform.Find("VFX")).gameObject.SetActive(EnableWardSounds.Value); ((Component)SFX).gameObject.SetActive(EnableWardSounds.Value); } else { _wardMaterials.ForEach(delegate(Material m) { m.DisableKeyword("_EMISSION"); }); ((Component)((Component)this).transform.Find("VFX")).gameObject.SetActive(false); ((Component)SFX).gameObject.SetActive(EnableWardSounds.Value); } if (Object.op_Implicit((Object)(object)Player.m_localPlayer) && IsInside_Main(((Component)Player.m_localPlayer).transform.position)) { ((Component)_areaMarker_main).gameObject.SetActive(true); } else { ((Component)_areaMarker_main).gameObject.SetActive(false); } if (!_znet.HasOwner() || !_znet.IsOwner()) { return; } int num = (int)EnvMan.instance.m_totalSeconds; int num2 = num - LastUpdateTime; if (ForceButtonEnabled) { Fuel -= num2; if (Fuel < 0f) { Fuel = 0f; } if (flag != IsEnabled()) { Object.Instantiate<GameObject>(flag ? FlashShield_Deactivate : FlashShield_Activate, ((Component)this).transform.position, Quaternion.identity); } } LastUpdateTime = (int)EnvMan.instance.m_totalSeconds; } private bool IsInside_Main(Vector3 point) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) return Utils.DistanceXZ(((Component)this).transform.position, point) < (float)Radius; } public bool IsPermitted(long playerID) { if (!_piece.IsCreator()) { return CheckPermitList(playerID); } return true; } private bool CheckPermitList(long playerID) { return GetPermittedPlayers().Any((KeyValuePair<long, string> player) => player.Key == playerID); } public List<KeyValuePair<long, string>> GetPermittedPlayers() { List<KeyValuePair<long, string>> list = new List<KeyValuePair<long, string>>(); int @int = _znet.m_zdo.GetInt("permitted", 0); for (int i = 0; i < @int; i++) { long @long = _znet.m_zdo.GetLong("pu_id" + i, 0L); string @string = _znet.m_zdo.GetString("pu_name" + i, ""); if (@long != 0L) { list.Add(new KeyValuePair<long, string>(@long, @string)); } } return list; } private void SetPermittedPlayers(IReadOnlyList<KeyValuePair<long, string>> users) { _znet.m_zdo.Set("permitted", users.Count); for (int i = 0; i < users.Count; i++) { KeyValuePair<long, string> keyValuePair = users[i]; _znet.m_zdo.Set("pu_id" + i, keyValuePair.Key); _znet.m_zdo.Set("pu_name" + i, keyValuePair.Value); } } public void AddPermitted(long playerID, string playerName) { List<KeyValuePair<long, string>> permittedPlayers = GetPermittedPlayers(); if (!permittedPlayers.Any((KeyValuePair<long, string> keyValuePair) => keyValuePair.Key == playerID)) { permittedPlayers.Add(new KeyValuePair<long, string>(playerID, playerName)); SetPermittedPlayers(permittedPlayers); } } public void RemovePermitted(long playerID) { List<KeyValuePair<long, string>> permittedPlayers = GetPermittedPlayers(); if (permittedPlayers.RemoveAll((KeyValuePair<long, string> x) => x.Key == playerID) > 0) { SetPermittedPlayers(permittedPlayers); } } private void AddUserList(StringBuilder text) { List<KeyValuePair<long, string>> permittedPlayers = GetPermittedPlayers(); text.Append("\n$piece_guardstone_additional: "); for (int i = 0; i < permittedPlayers.Count; i++) { text.Append(permittedPlayers[i].Value); if (i != permittedPlayers.Count - 1) { text.Append(", "); } } } public static bool AllowAction(Vector3 point, bool flash = true) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)Player.m_localPlayer)) { return false; } if (Player.m_debugMode) { return true; } long playerID = Player.m_localPlayer.GetPlayerID(); IEnumerable<PyroWard_Component> enumerable = _instances.Where((PyroWard_Component x) => x.IsEnabled() && x.IsInside_Main(point)); foreach (PyroWard_Component item in enumerable) { if (!item.IsPermitted(playerID)) { if (flash) { item.Flash(); } return false; } } return true; } public bool Interact(Humanoid user, bool hold, bool alt) { Player val = (Player)(object)((user is Player) ? user : null); if (Input.GetKey((KeyCode)304) && (_piece.IsCreator() || Player.m_debugMode)) { _znet.ClaimOwnership(); PyroWardUI.Show(this); return true; } if (IsPermitted(Player.m_localPlayer.GetPlayerID())) { _znet.InvokeRPC("RPC_Interact", new object[1]); return true; } return false; } public bool UseItem(Humanoid user, ItemData item) { //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) if (!UseFuel.Value) { return false; } string[] array = (from i in WardFuelPrefabs.Value.Split(new char[1] { ',' }) select i.Trim()).ToArray(); for (int j = 0; j < array.Length; j += 2) { string text = array[j]; int num = int.Parse(array[j + 1]); if (((Object)item.m_dropPrefab).name == text) { item.m_stack--; if (item.m_stack <= 0) { user.GetInventory().RemoveItem(item); } _znet.InvokeRPC("RPC_AddFuel", new object[1] { num }); Object.Instantiate<GameObject>(FlashShield_Fuel, ((Component)this).transform.position, Quaternion.identity); return true; } } return false; } private string GetCreatorName() { return _znet.m_zdo.GetString("creatorName", ""); } private void Setup(string name, string id) { LastUpdateTime = (int)EnvMan.instance.m_totalSeconds; _canPlaceWard = false; _znet.m_zdo.Set("creatorName", name); _znet.m_zdo.Set("PyroWard_id", id); Fuel = (float)WardMaxFuel.Value / 2f; ForceButtonEnabled = true; if (ZNet.instance.GetServerPeer() != null) { ZRoutedRpc.instance.InvokeRoutedRPC(ZNet.instance.GetServerPeer().m_uid, "PyroWard wardplaced", new object[1]); } } public string GetHoverText() { if (!_znet.IsValid() || !Object.op_Implicit((Object)(object)Player.m_localPlayer)) { return ""; } StringBuilder stringBuilder = new StringBuilder(256); if (UseFuel.Value) { stringBuilder.Append("Charge: <color=green>" + ((int)Fuel).ToTime() + "</color> | <color=yellow>" + WardMaxFuel.Value.ToTimeNoS() + "</color>\n"); } stringBuilder.Append(string.Concat(str2: (!ForceButtonEnabled) ? "<color=#AF0000>Deactivated</color>" : ((!(Fuel <= 0f)) ? "<color=green>Activated</color>" : "<color=#AF0000>No Fuel</color>"), str0: _piece.m_name, str1: " ( ", str3: " )")); stringBuilder.Append("\n$piece_guardstone_owner " + GetCreatorName() + "\n"); AddUserList(stringBuilder); if (_piece.IsCreator()) { stringBuilder.Append("\n [<color=yellow><b>L.Shift + $KEY_Use </b></color>] Open UI"); } if (IsPermitted(Player.m_localPlayer.GetPlayerID())) { if (ForceButtonEnabled) { stringBuilder.Append("\n [<color=yellow><b>$KEY_Use</b></color>] <color=red>Deactivate</color>"); } else { stringBuilder.Append("\n [<color=yellow><b>$KEY_Use</b></color>] <color=green>Activate</color>"); } } return Localization.instance.Localize(stringBuilder.ToString()); } public string GetHoverName() { return "Ward"; } } private enum PlayerStatus { VIP, User } private class WardManager { private readonly string _path; public readonly Dictionary<string, int> PlayersWardData = new Dictionary<string, int>(); public WardManager(string path) { _path = path; if (!File.Exists(_path)) { File.Create(_path).Dispose(); return; } string text = File.ReadAllText(_path); if (!string.IsNullOrEmpty(text)) { PlayersWardData = JSON.ToObject<Dictionary<string, int>>(text); } } public bool CanBuildWard(string id) { if (!PlayersWardData.ContainsKey(id)) { return true; } return GetPlayerStatus(id) switch { PlayerStatus.VIP => PlayersWardData[id] < MaxAmountOfWards_VIP.Value, PlayerStatus.User => PlayersWardData[id] < MaxAmountOfWards.Value, _ => false, }; } public void Save() { File.WriteAllText(_path, JSON.ToNiceJSON(PlayersWardData)); } } [HarmonyPatch(typeof(Piece), "CanBeRemoved")] private static class Piece_CanBeRemoved_Patch { private static void Postfix(Piece __instance, bool __result) { if (Object.op_Implicit((Object)(object)((Component)__instance).GetComponent<PyroWard_Component>()) && !__instance.IsCreator() && !Player.m_debugMode) { __result = false; } } } [HarmonyPatch(typeof(ZDOMan), "HandleDestroyedZDO")] private static class ZDOMan_Patch { private static readonly int PyroWard_id = StringExtensionMethods.GetStableHashCode("PyroWard_id"); private static void Prefix(ZDOMan __instance, ZDOID uid) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) if (!isServer) { return; } ZDO zDO = __instance.GetZDO(uid); if (zDO == null || string.IsNullOrEmpty(zDO.GetString(PyroWard_id, ""))) { return; } string @string = zDO.GetString(PyroWard_id, ""); if (_wardManager.PlayersWardData.ContainsKey(@string)) { _wardManager.PlayersWardData[@string]--; if (_wardManager.PlayersWardData[@string] < 0) { _wardManager.PlayersWardData[@string] = 0; } ZNetPeer peerByHostName = ZNet.instance.GetPeerByHostName(@string); if (peerByHostName != null) { ZRoutedRpc.instance.InvokeRoutedRPC(peerByHostName.m_uid, "PyroWard Data", new object[1] { _wardManager.CanBuildWard(@string) }); } } _wardManager.Save(); } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] private static class ZnetSync { private static void Postfix(ZRpc rpc) { if (ZNet.instance.IsServer() && ZNet.instance.IsDedicated()) { ZNetPeer peer = ZNet.instance.GetPeer(rpc); string hostName = peer.m_socket.GetHostName(); ZRoutedRpc.instance.InvokeRoutedRPC(peer.m_uid, "PyroWard Data", new object[1] { _wardManager.CanBuildWard(hostName) }); } } } [HarmonyPatch(typeof(Game), "Start")] private static class Game_Start_Patch { private static void Postfix() { _canPlaceWard = false; } } [HarmonyPatch(typeof(PrivateArea), "CheckAccess")] private static class PrivateArea_CheckAccess_Patch { private static void Postfix(Vector3 point, bool flash, ref bool __result) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) __result &= PyroWard_Component.AllowAction(point, flash); } } [HarmonyPatch(typeof(ItemDrop), "Interact")] private static class ItemDrop_Interact_Patch { private static bool Prefix(ItemDrop __instance) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return PyroWard_Component.AllowAction(((Component)__instance).transform.position); } } [HarmonyPatch(typeof(CraftingStation), "Interact")] private static class CraftingStation_Interact_Patch { private static bool Prefix(ItemDrop __instance) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return PyroWard_Component.AllowAction(((Component)__instance).transform.position); } } [HarmonyPatch(typeof(Player), "AutoPickup")] private static class Player_AutoPickup_Patch { private static bool Prefix(Player __instance) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return PyroWard_Component.AllowAction(((Component)__instance).transform.position, flash: false); } } [HarmonyPatch(typeof(WearNTear), "Damage")] private static class WearNTear_Damage_Patch { private static bool Prefix(WearNTear __instance) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) PyroWard_Component component = ((Component)__instance).GetComponent<PyroWard_Component>(); if (component != null && component.IsEnabled()) { return false; } return PyroWard_Component.AllowAction(((Component)__instance).transform.position, flash: false); } } [HarmonyPatch(typeof(WearNTear), "ApplyDamage")] private static class WearNTear_Damage_Patch2 { private static bool Prefix(WearNTear __instance) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return !Object.op_Implicit((Object)(object)PyroWard_Component.TryFindWard(((Component)__instance).transform.position)); } } [HarmonyPatch(typeof(TeleportWorld), "Teleport")] private static class TeleportWorld_Teleport_Patch { private static bool Prefix(ItemDrop __instance) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return PyroWard_Component.AllowAction(((Component)__instance).transform.position); } } [HarmonyPatch(typeof(ZNetScene), "Awake")] private static class ZNetScene_Awake_Patch_Recipe { private static void Postfix(ZNetScene __instance) { ResetRecipe(null, null); } } private const string GUID = "kg.PyroWard"; private const string NAME = "kg.PyroWard"; private const string VERSION = "1.0.0"; public static AssetBundle asset; private static AssetBundle asset_vfx; private static GameObject Ward_Prefab; private static GameObject FlashShield; private static GameObject FlashShield_Permit; private static GameObject FlashShield_Fuel; private static GameObject FlashShield_Activate; private static GameObject FlashShield_Deactivate; private static ConfigEntry<string> WardRecipe; private static ConfigEntry<bool> UseFuel; public static ConfigEntry<int> WardMaxRadius; public static ConfigEntry<int> WardMaxRadius_VIP; private static ConfigEntry<string> WardFuelPrefabs; private static ConfigEntry<int> WardMaxFuel; private static ConfigEntry<string> VIPLIST; private static ConfigEntry<int> MaxPlayerWardSpace; private static ConfigEntry<int> MaxPlayerWardSpace_VIP; private readonly ConfigSync configSync = new ConfigSync("kg.PyroWard") { DisplayName = "kg.PyroWard" }; private static bool _canPlaceWard; private static ConfigEntry<bool> EnableWardSounds; public static string _localUserID = "NONE"; private static WardManager _wardManager; private static ConfigEntry<int> MaxAmountOfWards; private static ConfigEntry<int> MaxAmountOfWards_VIP; private static PyroWard _thistype; private static FileSystemWatcher fsw; private static readonly List<ZDO> TempWardList = new List<ZDO>(); private static bool isServer => (int)SystemInfo.graphicsDeviceType == 4; private ConfigEntry<T> config<T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true) { ConfigEntry<T> val = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, description); SyncedConfigEntry<T> syncedConfigEntry = configSync.AddConfigEntry<T>(val); syncedConfigEntry.SynchronizedConfig = synchronizedSetting; return val; } private ConfigEntry<T> config<T>(string group, string name, T value, string description, bool synchronizedSetting = true) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting); } private void Awake() { //IL_0285: Unknown result type (might be due to invalid IL or missing references) _thistype = this; asset = GetAssetBundle("pyroward"); asset_vfx = GetAssetBundle("pyrowardvfx"); WardMaxFuel = config("Ward", "WardMaxFuel", 604800, "Ward Max Fuel"); WardMaxRadius = config("Ward", "WardMaxRadius", 50, "Ward Max Radius"); WardMaxRadius_VIP = config("Ward", "WardMaxRadius_VIP", 100, "Ward Max Radius (VIP)"); UseFuel = config("Ward", "UseFuel", value: true, "Use Fuel"); WardFuelPrefabs = config("Ward", "WardFuelPrefabs", "Stone, 100", "Ward Fuel Prefabs"); WardRecipe = config("Ward", "WardRecipe", "SwordCheat,1", "Ward Recipe"); MaxPlayerWardSpace = config("Ward", "MaxPlayerWardSpace", 500, "Max Player Ward Space"); MaxPlayerWardSpace_VIP = config("Ward", "MaxPlayerWardSpace_VIP", 1000, "Max Player Ward Space (VIP)"); WardRecipe.SettingChanged += ResetRecipe; VIPLIST = config("Ward", "VIPLIST", "SteamIDShere", "VIP List"); MaxAmountOfWards = config("WardOne", "MaxAmountOfWards", 3, "Max amount of wards"); MaxAmountOfWards_VIP = config("WardOne", "MaxAmountOfWards_VIP", 5, "Max amount of wards for VIP"); EnableWardSounds = ((BaseUnityPlugin)this).Config.Bind<bool>("SFX", "EnableWardSounds", true, "Enable Ward Sounds"); PyroWardUI.Init(); JSON.Parameters = new JSONParameters { UseExtensions = false, SerializeNullValues = false, DateTimeMilliseconds = false, UseUTCDateTime = true, UseOptimizedDatasetSchema = true, UseValuesOfEnums = true }; Ward_Prefab = asset.LoadAsset<GameObject>("PyroWard"); Ward_Prefab.AddComponent<PyroWard_Component>(); FlashShield = asset_vfx.LoadAsset<GameObject>("PyroWard_Explosion"); FlashShield_Permit = asset_vfx.LoadAsset<GameObject>("PyroWard_Permit"); FlashShield_Fuel = asset_vfx.LoadAsset<GameObject>("PyroWard_Fuel"); FlashShield_Activate = asset_vfx.LoadAsset<GameObject>("PyroWard_Activate"); FlashShield_Deactivate = asset_vfx.LoadAsset<GameObject>("PyroWard_Deactivate"); if (isServer) { ServerSideInit(); } new Harmony("kg.PyroWard").PatchAll(); } public static bool IsVIP(string steam) { return VIPLIST.Value.Replace(" ", "").Split(new char[1] { ',' }).Any((string x) => x.Trim() == steam); } private static PlayerStatus GetPlayerStatus(string id) { if (!IsVIP(id)) { return PlayerStatus.User; } return PlayerStatus.VIP; } private void ServerSideInit() { string text = Path.Combine(Paths.ConfigPath, "PyroWard"); if (!Directory.Exists(text)) { Directory.CreateDirectory(text); } _wardManager = new WardManager(Path.Combine(text, "WardData.json")); fsw = new FileSystemWatcher(Paths.ConfigPath) { Filter = Path.GetFileName(((BaseUnityPlugin)this).Config.ConfigFilePath), EnableRaisingEvents = true, IncludeSubdirectories = true, SynchronizingObject = ThreadingHelper.SynchronizingObject }; fsw.Changed += ConfigChanged; ((MonoBehaviour)_thistype).StartCoroutine(SendWardsToClients()); } private static IEnumerator SendWardsToClients() { while (true) { if (Object.op_Implicit((Object)(object)Game.instance) && ZDOMan.instance != null && Object.op_Implicit((Object)(object)ZNet.instance) && ZNet.instance.IsServer()) { TempWardList.Clear(); int index = 0; while (!ZDOMan.instance.GetAllZDOsWithPrefabIterative(((Object)Ward_Prefab).name, TempWardList, ref index)) { yield return null; } foreach (ZDO tempWard in TempWardList) { ZDOMan.instance.ForceSendZDO(tempWard.m_uid); } } yield return (object)new WaitForSeconds(10f); } } private void ConfigChanged(object sender, FileSystemEventArgs e) { MonoBehaviour.print((object)"[Pyro Ward] Config changed..."); ((MonoBehaviour)_thistype).StartCoroutine(DelayReloadConfigFile(((BaseUnityPlugin)this).Config)); } private static IEnumerator DelayReloadConfigFile(ConfigFile file) { yield return (object)new WaitForSecondsRealtime(2.5f); file.Reload(); } private static AssetBundle GetAssetBundle(string filename) { Assembly executingAssembly = Assembly.GetExecutingAssembly(); string name = executingAssembly.GetManifestResourceNames().Single((string str) => str.EndsWith(filename)); using Stream stream = executingAssembly.GetManifestResourceStream(name); return AssetBundle.LoadFromStream(stream); } private void Update() { if (Input.GetKeyDown((KeyCode)27) && PyroWardUI.IsVisible()) { PyroWardUI.Hide(); } } private static void ResetRecipe(object sender, EventArgs eventArgs) { //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Expected O, but got Unknown //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Expected O, but got Unknown if (!Object.op_Implicit((Object)(object)ZNetScene.instance)) { return; } try { List<Requirement> list = new List<Requirement>(); string[] array = WardRecipe.Value.Split(new char[1] { ',' }); for (int i = 0; i < array.Length; i += 2) { string text = array[i]; int amount = int.Parse(array[i + 1]); list.Add(new Requirement { m_amount = amount, m_resItem = ObjectDB.instance.GetItemPrefab(StringExtensionMethods.GetStableHashCode(text)).GetComponent<ItemDrop>(), m_recover = (text != "SwordCheat") }); } Ward_Prefab.GetComponent<Piece>().m_resources = list.ToArray(); Ward_Prefab.GetComponent<Piece>().m_craftingStation = ZNetScene.instance.GetPrefab("piece_workbench").GetComponent<CraftingStation>(); } catch { Ward_Prefab.GetComponent<Piece>().m_resources = (Requirement[])(object)new Requirement[1] { new Requirement { m_amount = 1, m_resItem = ObjectDB.instance.GetItemPrefab("SwordCheat").GetComponent<ItemDrop>(), m_recover = false } }; } } public static int GetPlayerSpaceLeft() { List<ZDO> list = new List<ZDO>(); int num = 0; while (!ZDOMan.instance.GetAllZDOsWithPrefabIterative(((Object)Ward_Prefab).name, list, ref num)) { } int num2 = (IsVIP(_localUserID) ? MaxPlayerWardSpace_VIP.Value : MaxPlayerWardSpace.Value); foreach (ZDO item in list.Where((ZDO w) => w.GetLong(ZDOVars.s_creator, 0L) == Player.m_localPlayer.GetPlayerID())) { int @int = item.GetInt("Radius", 0); num2 -= @int; } return Mathf.Max(num2, 0); } } public static class EXTENTIONS { public static string ToTime(this int seconds) { TimeSpan timeSpan = TimeSpan.FromSeconds(seconds); string text = ""; if (timeSpan.Days > 0) { text += $"{timeSpan.Days:D2}d "; } if (timeSpan.Hours > 0) { text += $"{timeSpan.Hours:D2}h "; } if (timeSpan.Minutes > 0) { text += $"{timeSpan.Minutes:D2}m "; } return text + $"{timeSpan.Seconds:D2}s"; } public static string ToTimeNoS(this int seconds) { TimeSpan timeSpan = TimeSpan.FromSeconds(seconds); string text = ""; if (timeSpan.Days > 0) { text += $"{timeSpan.Days:D2}d "; } if (timeSpan.Hours > 0) { text += $"{timeSpan.Hours:D2}h "; } if (timeSpan.Minutes > 0) { text += $"{timeSpan.Minutes:D2}m "; } return text; } } public static class PyroWardUI { [HarmonyPatch(typeof(TextInput), "IsVisible")] private static class TextInput_IsVisible_Patch { [UsedImplicitly] private static void Postfix(ref bool __result) { __result |= IsVisible(); } } [HarmonyPatch(typeof(StoreGui), "IsVisible")] private static class TextInput_IsVisible_Patch2 { [UsedImplicitly] private static void Postfix(ref bool __result) { __result |= IsVisible(); } } [CompilerGenerated] private static class <>O { public static UnityAction <0>__Click_Apply; } private static GameObject UI; private static GameObject Element; private static PyroWard.PyroWard_Component _currentWard; private static TMP_Text _radiusText; private static Slider _slider; private static Button _applyButton; private static Transform _permitted_Content; private static Transform _allplayers_Content; private static int _currentMaxRadius; public static bool IsVisible() { if (Object.op_Implicit((Object)(object)UI)) { return UI.activeSelf; } return false; } public static void Init() { //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Expected O, but got Unknown UI = Object.Instantiate<GameObject>(PyroWard.asset.LoadAsset<GameObject>("PyroWardUI")); Element = PyroWard.asset.LoadAsset<GameObject>("PyroWardUI_Player"); Object.DontDestroyOnLoad((Object)(object)UI); UI.SetActive(false); _slider = ((Component)UI.transform.Find("Canvas/Background/Radius_Slider")).GetComponent<Slider>(); _radiusText = ((Component)UI.transform.Find("Canvas/Background/Radius_Text")).GetComponent<TMP_Text>(); _applyButton = ((Component)UI.transform.Find("Canvas/Background/Apply")).GetComponent<Button>(); _permitted_Content = UI.transform.Find("Canvas/Background/Permitted_SV/Viewport/Content"); _allplayers_Content = UI.transform.Find("Canvas/Background/Players_SV/Viewport/Content"); ButtonClickedEvent onClick = _applyButton.onClick; object obj = <>O.<0>__Click_Apply; if (obj == null) { UnityAction val = Click_Apply; <>O.<0>__Click_Apply = val; obj = (object)val; } ((UnityEvent)onClick).AddListener((UnityAction)obj); ((UnityEvent<float>)(object)_slider.onValueChanged).AddListener((UnityAction<float>)delegate { if (Object.op_Implicit((Object)(object)_currentWard)) { int playerSpaceLeft = PyroWard.GetPlayerSpaceLeft(); int radius = _currentWard.Radius; int num = (int)_slider.value; int num2 = playerSpaceLeft + radius - num; _radiusText.text = $"Radius:\n{_slider.value} / {_currentMaxRadius} (space left: {num2})"; } }); } private static void Click_Apply() { if (!Object.op_Implicit((Object)(object)_currentWard)) { Hide(); return; } int num = PyroWard.GetPlayerSpaceLeft() + _currentWard.Radius; _currentWard.Radius = Mathf.Min((int)_slider.value, num); Hide(); } private static void LoadData() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Expected O, but got Unknown //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown //IL_0114: Unknown result type (might be due to invalid IL or missing references) //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_0166: Unknown result type (might be due to invalid IL or missing references) //IL_0170: Expected O, but got Unknown //IL_01c0: Unknown result type (might be due to invalid IL or missing references) //IL_01c5: Unknown result type (might be due to invalid IL or missing references) //IL_01d1: Unknown result type (might be due to invalid IL or missing references) //IL_01db: Unknown result type (might be due to invalid IL or missing references) //IL_0237: Unknown result type (might be due to invalid IL or missing references) //IL_023c: Unknown result type (might be due to invalid IL or missing references) //IL_0289: Unknown result type (might be due to invalid IL or missing references) //IL_0293: Expected O, but got Unknown foreach (Transform item in _permitted_Content) { Transform val = item; Object.Destroy((Object)(object)((Component)val).gameObject); } foreach (Transform item2 in _allplayers_Content) { Transform val2 = item2; Object.Destroy((Object)(object)((Component)val2).gameObject); } List<KeyValuePair<long, string>> permittedUsers = _currentWard.GetPermittedPlayers(); foreach (KeyValuePair<long, string> permittedUser in permittedUsers) { GameObject val3 = Object.Instantiate<GameObject>(Element, _permitted_Content); val3.GetComponent<TMP_Text>().text = permittedUser.Value; ((Graphic)((Component)val3.transform.Find("Button/Foreground")).GetComponent<Image>()).color = Color32.op_Implicit(new Color32((byte)239, (byte)87, (byte)76, byte.MaxValue)); ((Component)val3.transform.Find("Button/Text")).GetComponent<TMP_Text>().text = "Remove"; ((UnityEvent)((Component)val3.transform.Find("Button")).GetComponent<Button>().onClick).AddListener((UnityAction)delegate { long key = permittedUser.Key; _currentWard.RemovePermitted(key); LoadData(); }); } IEnumerable<PlayerInfo> enumerable = from x in ZNet.instance.GetPlayerList() where ZDOMan.instance.GetZDO(x.m_characterID) != null && !permittedUsers.Any((KeyValuePair<long, string> y) => y.Key == ZDOMan.instance.GetZDO(x.m_characterID).GetLong(ZDOVars.s_playerID, 0L)) select x; foreach (PlayerInfo player in enumerable) { if (!(player.m_characterID == ((Character)Player.m_localPlayer).GetZDOID())) { GameObject val4 = Object.Instantiate<GameObject>(Element, _allplayers_Content); val4.GetComponent<TMP_Text>().text = player.m_name; ((Graphic)((Component)val4.transform.Find("Button/Foreground")).GetComponent<Image>()).color = Color32.op_Implicit(new Color32((byte)76, (byte)239, (byte)87, byte.MaxValue)); ((Component)val4.transform.Find("Button/Text")).GetComponent<TMP_Text>().text = "Add"; ((UnityEvent)((Component)val4.transform.Find("Button")).GetComponent<Button>().onClick).AddListener((UnityAction)delegate { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) ZDOID characterID = player.m_characterID; string name = player.m_name; _currentWard.AddPermitted(ZDOMan.instance.GetZDO(characterID).GetLong(ZDOVars.s_playerID, 0L), name); LoadData(); }); } } } public static void Hide() { _currentWard = null; UI.SetActive(false); } public static void Show(PyroWard.PyroWard_Component ward) { if (!((Object)(object)ward == (Object)null)) { _currentWard = ward; UI.SetActive(true); _currentMaxRadius = (PyroWard.IsVIP(PyroWard._localUserID) ? PyroWard.WardMaxRadius_VIP.Value : PyroWard.WardMaxRadius.Value); _slider.minValue = 0f; _slider.maxValue = _currentMaxRadius; _slider.value = _currentWard.Radius; int playerSpaceLeft = PyroWard.GetPlayerSpaceLeft(); int radius = _currentWard.Radius; int num = (int)_slider.value; int num2 = playerSpaceLeft + radius - num; _radiusText.text = $"Radius:\n{_slider.value} / {_currentMaxRadius} (space left: {num2})"; LoadData(); } } } } namespace fastJSON { internal class DynamicJson : DynamicObject, IEnumerable { private IDictionary<string, object> _dictionary { get; set; } private List<object> _list { get; set; } public DynamicJson(string json) { object obj = JSON.Parse(json); if (obj is IDictionary<string, object>) { _dictionary = (IDictionary<string, object>)obj; } else { _list = (List<object>)obj; } } private DynamicJson(object dictionary) { if (dictionary is IDictionary<string, object>) { _dictionary = (IDictionary<string, object>)dictionary; } } public override IEnumerable<string> GetDynamicMemberNames() { return _dictionary.Keys.ToList(); } public override bool TryGetIndex(GetIndexBinder binder, object[] indexes, out object result) { object obj = indexes[0]; if (obj is int) { result = _list[(int)obj]; } else { result = _dictionary[(string)obj]; } if (result is IDictionary<string, object>) { result = new DynamicJson(result as IDictionary<string, object>); } return true; } public override bool TryGetMember(GetMemberBinder binder, out object result) { if (!_dictionary.TryGetValue(binder.Name, out result) && !_dictionary.TryGetValue(binder.Name.ToLowerInvariant(), out result)) { return false; } if (result is IDictionary<string, object>) { result = new DynamicJson(result as IDictionary<string, object>); } else if (result is List<object>) { List<object> list = new List<object>(); foreach (object item in (List<object>)result) { if (item is IDictionary<string, object>) { list.Add(new DynamicJson(item as IDictionary<string, object>)); } else { list.Add(item); } } result = list; } return _dictionary.ContainsKey(binder.Name); } IEnumerator IEnumerable.GetEnumerator() { foreach (object item in _list) { yield return new DynamicJson(item as IDictionary<string, object>); } } } public sealed class DatasetSchema { public List<string> Info; public string Name; } public class DataMemberAttribute : Attribute { public string Name { get; set; } } internal static class Formatter { private static void AppendIndent(StringBuilder sb, int count, string indent) { while (count > 0) { sb.Append(indent); count--; } } public static string PrettyPrint(string input) { return PrettyPrint(input, new string(' ', JSON.Parameters.FormatterIndentSpaces)); } public static string PrettyPrint(string input, string spaces) { StringBuilder stringBuilder = new StringBuilder(); int num = 0; int length = input.Length; char[] array = input.ToCharArray(); for (int i = 0; i < length; i++) { char c = array[i]; if (c == '"') { bool flag = true; while (flag) { stringBuilder.Append(c); c = array[++i]; switch (c) { case '\\': stringBuilder.Append(c); c = array[++i]; break; case '"': flag = false; break; } } } switch (c) { case '[': case '{': stringBuilder.Append(c); stringBuilder.AppendLine(); AppendIndent(stringBuilder, ++num, spaces); break; case ']': case '}': stringBuilder.AppendLine(); AppendIndent(stringBuilder, --num, spaces); stringBuilder.Append(c); break; case ',': stringBuilder.Append(c); stringBuilder.AppendLine(); AppendIndent(stringBuilder, num, spaces); break; case ':': stringBuilder.Append(" : "); break; default: if (!char.IsWhiteSpace(c)) { stringBuilder.Append(c); } break; } } return stringBuilder.ToString(); } } public class Helper { public static bool IsNullable(Type t) { if (!t.IsGenericType) { return false; } Type genericTypeDefinition = t.GetGenericTypeDefinition(); return genericTypeDefinition.Equals(typeof(Nullable<>)); } public static Type UnderlyingTypeOf(Type t) { return Reflection.Instance.GetGenericArguments(t)[0]; } public static DateTimeOffset CreateDateTimeOffset(int year, int month, int day, int hour, int min, int sec, int milli, int extraTicks, TimeSpan offset) { DateTimeOffset dateTimeOffset = new DateTimeOffset(year, month, day, hour, min, sec, milli, offset); if (extraTicks > 0) { return dateTimeOffset + TimeSpan.FromTicks(extraTicks); } return dateTimeOffset; } public static bool BoolConv(object v) { bool result = false; if (v is bool) { result = (bool)v; } else if (v is long) { result = (((long)v > 0) ? true : false); } else if (v is string) { string text = (string)v; switch (text.ToLowerInvariant()) { case "1": case "true": case "yes": case "on": result = true; break; } } return result; } public static long AutoConv(object value, JSONParameters param) { if (value is string) { if (param.AutoConvertStringToNumbers) { string text = (string)value; return CreateLong(text, 0, text.Length); } throw new Exception("AutoConvertStringToNumbers is disabled for converting string : " + value); } if (value is long) { return (long)value; } return Convert.ToInt64(value); } public unsafe static long CreateLong(string s, int index, int count) { long num = 0L; int num2 = 1; fixed (char* ptr = s) { char* ptr2 = ptr; ptr2 += index; if (*ptr2 == '-') { num2 = -1; ptr2++; count--; } if (*ptr2 == '+') { ptr2++; count--; } while (count > 0) { num = num * 10 + (*ptr2 - 48); ptr2++; count--; } } return num * num2; } public unsafe static long CreateLong(char[] s, int index, int count) { long num = 0L; int num2 = 1; fixed (char* ptr = s) { char* ptr2 = ptr; ptr2 += index; if (*ptr2 == '-') { num2 = -1; ptr2++; count--; } if (*ptr2 == '+') { ptr2++; count--; } while (count > 0) { num = num * 10 + (*ptr2 - 48); ptr2++; count--; } } return num * num2; } public unsafe static int CreateInteger(string s, int index, int count) { int num = 0; int num2 = 1; fixed (char* ptr = s) { char* ptr2 = ptr; ptr2 += index; if (*ptr2 == '-') { num2 = -1; ptr2++; count--; } if (*ptr2 == '+') { ptr2++; count--; } while (count > 0) { num = num * 10 + (*ptr2 - 48); ptr2++; count--; } } return num * num2; } public static object CreateEnum(Type pt, object v) { return Enum.Parse(pt, v.ToString(), ignoreCase: true); } public static Guid CreateGuid(string s) { if (s.Length > 30) { return new Guid(s); } return new Guid(Convert.FromBase64String(s)); } public static StringDictionary CreateSD(Dictionary<string, object> d) { StringDictionary stringDictionary = new StringDictionary(); foreach (KeyValuePair<string, object> item in d) { stringDictionary.Add(item.Key, (string)item.Value); } return stringDictionary; } public static NameValueCollection CreateNV(Dictionary<string, object> d) { NameValueCollection nameValueCollection = new NameValueCollection(); foreach (KeyValuePair<string, object> item in d) { nameValueCollection.Add(item.Key, (string)item.Value); } return nameValueCollection; } public static object CreateDateTimeOffset(string value) { int milli = 0; int extraTicks = 0; int num = 0; int num2 = 0; int year = CreateInteger(value, 0, 4); int month = CreateInteger(value, 5, 2); int day = CreateInteger(value, 8, 2); int hour = CreateInteger(value, 11, 2); int min = CreateInteger(value, 14, 2); int sec = CreateInteger(value, 17, 2); int num3 = 20; if (value.Length > 21 && value[19] == '.') { milli = CreateInteger(value, num3, 3); num3 = 23; if (value.Length > 25 && char.IsDigit(value[num3])) { extraTicks = CreateInteger(value, num3, 4); num3 = 27;