Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of Deadheim v15.0.5
Combat.dll
Decompiled 2 weeks agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using ServerSync; using TMPro; using UnityEngine; [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: CompilationRelaxations(8)] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] namespace Combat { public class Patches { [HarmonyPatch(typeof(Character), "ApplyDamage")] public static class ApplyDamage { public static int combatHashCode = StringExtensionMethods.GetStableHashCode("Combat"); public static void Postfix(Character __instance, HitData hit) { //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Expected O, but got Unknown //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Expected O, but got Unknown if (!Object.op_Implicit((Object)(object)hit.GetAttacker())) { return; } StatusEffect statusEffect = ObjectDB.m_instance.GetStatusEffect(combatHashCode); statusEffect.m_ttl = Combat.BuffSeconds.Value; if (Combat.ActivateOnlyForPVP.Value && (!hit.GetAttacker().IsPlayer() || !__instance.IsPlayer())) { return; } if (hit.GetAttacker().IsPlayer()) { Player val = (Player)hit.GetAttacker(); if (((Character)val).GetSEMan().HaveStatusEffect("Combat")) { ((Character)val).GetSEMan().RemoveStatusEffect(combatHashCode, false); } ((Character)val).GetSEMan().AddStatusEffect(statusEffect, false, 0, 0f); } if (__instance.IsPlayer()) { Player val2 = (Player)__instance; if (((Character)val2).GetSEMan().HaveStatusEffect("Combat")) { ((Character)val2).GetSEMan().RemoveStatusEffect(combatHashCode, false); } ((Character)val2).GetSEMan().AddStatusEffect(statusEffect, false, 0, 0f); } } } [HarmonyPatch(typeof(ObjectDB), "Awake")] public static class ConsumeItem { private static void Postfix(ObjectDB __instance) { __instance.m_StatusEffects.Add((StatusEffect)(object)StatusEffects.CreateStatusEffect("Combat", "Combat", ((IEnumerable<Sprite>)Resources.FindObjectsOfTypeAll<Sprite>()).FirstOrDefault((Func<Sprite, bool>)((Sprite x) => ((Object)x).name == "mapicon_player_32")))); } } [HarmonyPatch(typeof(Humanoid), "IsTeleportable")] public static class IsTeleportable { private static bool Prefix(Humanoid __instance) { if (!Combat.PreventTeleport.Value) { return true; } if (!((Character)__instance).GetSEMan().HaveStatusEffect("Combat")) { return true; } ((Character)__instance).Message((MessageType)2, "You can't teleport in Combat", 0, (Sprite)null); return false; } } } [BepInPlugin("Detalhes.Combat", "Detalhes.Combat", "1.0.0")] public class Combat : BaseUnityPlugin { public const string PluginGUID = "Detalhes.Combat"; public const string Name = "Combat"; public const string Version = "1.0.0"; private ConfigSync configSync = new ConfigSync("Detalhes.Combat") { DisplayName = "Combat", CurrentVersion = "1.0.0", MinimumRequiredVersion = "1.0.0" }; private Harmony _harmony = new Harmony("Detalhes.Combat"); public static ConfigEntry<int> BuffSeconds; public static ConfigEntry<bool> ActivateOnlyForPVP; public static ConfigEntry<bool> PreventTeleport; public void Awake() { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Expected O, but got Unknown //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Expected O, but got Unknown BuffSeconds = config("Server config", "BuffSeconds", 30, new ConfigDescription("BuffSeconds", (AcceptableValueBase)null, Array.Empty<object>())); ActivateOnlyForPVP = config("Server config", "ActivateOnlyForPVP", value: false, new ConfigDescription("ActivateOnlyForPVP", (AcceptableValueBase)null, Array.Empty<object>())); PreventTeleport = config("Server config", "PreventTeleport", value: true, new ConfigDescription("PreventTeleport", (AcceptableValueBase)null, Array.Empty<object>())); _harmony.PatchAll(); } 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); } } public class StatusEffects { public static SE_Stats CreateStatusEffect(string effectName, string m_name, Sprite icon) { SE_Stats val = ScriptableObject.CreateInstance<SE_Stats>(); ((Object)val).name = effectName; ((StatusEffect)val).m_name = m_name; ((StatusEffect)val).m_tooltip = m_name; ((StatusEffect)val).m_icon = icon; return val; } } } namespace Microsoft.CodeAnalysis { [Microsoft.CodeAnalysis.Embedded] [CompilerGenerated] 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] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ServerSync { [PublicAPI] internal abstract class OwnConfigEntryBase { public object? LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [PublicAPI] internal 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; } } } internal 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; }; } } [PublicAPI] internal 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), int priority = 0) : base(configSync, identifier, typeof(T), priority) { Value = value; } public void AssignLocalValue(T value) { if (localIsOwner) { Value = value; } else { LocalBaseValue = value; } } } internal class ConfigurationManagerAttributes { [UsedImplicitly] public bool? ReadOnly = false; } [PublicAPI] internal 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> adminPeer = (from p in ZNet.instance.GetPeers() where adminList.Contains(p.m_rpc.GetSocket().GetHostName()) select p).ToList(); List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList(); SendAdmin(nonAdminPeer, isAdmin: false); SendAdmin(adminPeer, 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 = false; 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_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: 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); } } } [HarmonyPrefix] [HarmonyPriority(800)] private static void Prefix(ref Dictionary<Assembly, BufferingSocket>? __state, ZNet __instance, ZRpc rpc) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 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) { ZRpc rpc2 = rpc; ZNet __instance2 = __instance; Dictionary<Assembly, BufferingSocket> __state2 = __state; ZNetPeer peer; if (__instance2.IsServer()) { object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 }); peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (peer == null) { SendBufferedData(); } else { ((MonoBehaviour)__instance2).StartCoroutine(sendAsync()); } } void SendBufferedData() { if (rpc2.GetSocket() is BufferingSocket bufferingSocket) { AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc2, bufferingSocket.Original); object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 }); ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null); if (val != null) { AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original); } } BufferingSocket bufferingSocket2 = __state2[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> entries = new List<PackageEntry>(); if (configSync.CurrentVersion != null) { entries.Add(new PackageEntry { section = "Internal", key = "serverversion", type = typeof(string), value = configSync.CurrentVersion }); } MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); entries.Add(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc2.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2] { adminList, rpc2.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false); yield return ((MonoBehaviour)__instance2).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package)); } SendBufferedData(); } } } private class PackageEntry { public string section = null; public string key = null; public Type type = null; 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 = null; public string received = null; public string field = ""; } public static bool ProcessingServerUpdate; public readonly string Name; public string? DisplayName; public string? CurrentVersion; public string? MinimumRequiredVersion; public bool ModRequired = false; private bool? forceConfigLocking; private bool isSourceOfTruth = true; private static readonly HashSet<ConfigSync> configSyncs; private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>(); private HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>(); private static bool isServer; private static bool lockExempt; private OwnConfigEntryBase? lockedConfig = null; 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_0052; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag.GetValueOrDefault(); } if (!num) { goto IL_0052; } int result = ((!lockExempt) ? 1 : 0); goto IL_0053; IL_0053: return (byte)result != 0; IL_0052: result = 0; goto IL_0053; } set { forceConfigLocking = value; } } public bool IsAdmin => lockExempt || isSourceOfTruth; public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } = false; 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) { ConfigEntry<T> configEntry2 = configEntry; OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry2); SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry<T>(configEntry2); AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry2).Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(((ConfigEntryBase)configEntry2).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray()); configEntry2.SettingChanged += delegate { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry2); } }; 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) { CustomSyncedValueBase customValue2 = customValue; if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue2.Identifier)) { throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)"); } allCustomValues.Add(customValue2); allCustomValues = new HashSet<CustomSyncedValueBase>(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority)); customValue2.ValueChanged += delegate { if (!ProcessingServerUpdate) { Broadcast(ZRoutedRpc.Everybody, customValue2); } }; } 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_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Expected O, but got Unknown //IL_024e: Unknown result type (might be due to invalid IL or missing references) //IL_0255: Expected O, but got Unknown //IL_01e8: Unknown result type (might be due to invalid IL or missing references) //IL_01ef: 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 SortedDictionary<int, byte[]> 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) { OwnConfigEntryBase config2 = config; ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config2)); if (configSync == null) { return true; } return configSync.IsSourceOfTruth || !config2.SynchronizedConfig || config2.LocalBaseValue == null || (!configSync.IsLocked && (config2 != configSync.lockedConfig || lockExempt)); } 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) { ZNetPeer peer2 = peer; 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 (peer2.m_socket.IsConnected()) { ZPackage fragmentedPackage = new ZPackage(); fragmentedPackage.Write((byte)2); fragmentedPackage.Write(packageIdentifier); fragmentedPackage.Write(fragment); fragmentedPackage.Write(fragments); fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray()); SendPackage(fragmentedPackage); 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) { peer2.m_rpc.Invoke(text, new object[1] { pkg }); } else { rpc.InvokeRoutedRPC(peer2.m_server ? 0 : peer2.m_uid, text, new object[1] { pkg }); } } IEnumerable<bool> waitForQueue() { float timeout = Time.time + 30f; while (peer2.m_socket.GetSendQueueSize() > 20000) { if (Time.time > timeout) { Debug.Log((object)$"Disconnecting {peer2.m_uid} after 30 seconds config sending timeout"); peer2.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 }); ZNet.instance.Disconnect(peer2); 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) { ZPackage package2 = package; if (!Object.op_Implicit((Object)(object)ZNet.instance)) { yield break; } byte[] rawData = package2.GetArray(); if (rawData != null && rawData.LongLength > 10000) { ZPackage compressedPackage = new ZPackage(); compressedPackage.Write((byte)4); MemoryStream output = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal)) { deflateStream.Write(rawData, 0, rawData.Length); } compressedPackage.Write(output.ToArray()); package2 = compressedPackage; } List<IEnumerator<bool>> writers = (from peer in peers where peer.IsReady() select peer into p select distributeConfigToPeers(p, package2)).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) { return type.IsEnum ? Enum.GetUnderlyingType(type) : type; } private static ZPackage ConfigsToPackage(IEnumerable<ConfigEntryBase>? configs = null, IEnumerable<CustomSyncedValueBase>? customValues = null, IEnumerable<PackageEntry>? packageEntries = null, bool partial = true) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: 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)) { 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] internal 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 { return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0"); } set { minimumRequiredVersion = value; } } private static void PatchServerSync() { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: 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."; } return (new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)) ? ("Mod " + DisplayName + " requires maximum " + ReceivedCurrentVersion + ". Installed is version " + CurrentVersion + ".") : ("Mod " + DisplayName + " requires minimum " + ReceivedMinimumRequiredVersion + ". 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) { return (rpc == null) ? ErrorClient() : ErrorServer(rpc); } private static VersionCheck[] GetFailedClient() { return versionChecks.Where((VersionCheck check) => !check.IsVersionOk()).ToArray(); } private static VersionCheck[] GetFailedServer(ZRpc rpc) { ZRpc rpc2 = rpc; return versionChecks.Where((VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc2)).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); } } } [HarmonyPrefix] [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] 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_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0195: 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_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: 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>, string>((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 + ")"; } } } } }
Deadheim.dll
Decompiled 2 weeks agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using Jotunn; using Jotunn.Configs; using Jotunn.Entities; using Jotunn.Managers; using Jotunn.Utils; using Splatform; using UnityEngine; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: AssemblyTitle("Deadheim")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Deadheimxx")] [assembly: AssemblyCopyright("Copyright © 2026")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("d361daa4-9ce5-430e-a275-944805ecb71e")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] namespace MassFarming { [HarmonyPatch] public static class MassPickup { private static FieldInfo m_interactMaskField = AccessTools.Field(typeof(Player), "m_interactMask"); private static MethodInfo _ExtractMethod = AccessTools.Method(typeof(Beehive), "Extract", (Type[])null, (Type[])null); [HarmonyPatch(typeof(Player), "Interact")] public static void Prefix(Player __instance, GameObject go, bool hold, bool alt) { //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_019e: Unknown result type (might be due to invalid IL or missing references) if (((Character)__instance).InAttack() || ((Character)__instance).InDodge() || hold || !Input.GetKey((KeyCode)304)) { return; } Interactable componentInParent = go.GetComponentInParent<Interactable>(); Pickable val = (Pickable)(object)((componentInParent is Pickable) ? componentInParent : null); if (val != null) { int num = (int)m_interactMaskField.GetValue(__instance); Collider[] array = Physics.OverlapSphere(go.transform.position, 10f, num); Collider[] array2 = array; foreach (Collider val2 in array2) { object obj; if (val2 == null) { obj = null; } else { GameObject gameObject = ((Component)val2).gameObject; obj = ((gameObject != null) ? gameObject.GetComponentInParent<Pickable>() : null); } Pickable val3 = (Pickable)obj; if (val3 != null && (Object)(object)val3 != (Object)(object)val && ((Object)val3.m_itemPrefab).name == ((Object)val.m_itemPrefab).name) { val3.Interact((Humanoid)(object)__instance, false, alt); } } return; } Beehive val4 = (Beehive)(object)((componentInParent is Beehive) ? componentInParent : null); if (val4 == null) { return; } int num2 = (int)m_interactMaskField.GetValue(__instance); Collider[] array3 = Physics.OverlapSphere(go.transform.position, 10f, num2); Collider[] array4 = array3; foreach (Collider val5 in array4) { object obj2; if (val5 == null) { obj2 = null; } else { GameObject gameObject2 = ((Component)val5).gameObject; obj2 = ((gameObject2 != null) ? gameObject2.GetComponentInParent<Beehive>() : null); } Beehive val6 = (Beehive)obj2; if (val6 != null && (Object)(object)val6 != (Object)(object)val4 && PrivateArea.CheckAccess(((Component)val6).transform.position, 0f, true, false)) { _ExtractMethod.Invoke(val6, null); } } } } } namespace Deadheim { [HarmonyPatch] public class FasterBoats { [HarmonyPatch(typeof(Ship), "GetSailForce")] private class ChangeShipBaseSpeed { private static void Postfix(ref Vector3 __result) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) __result *= Plugin.BoatWindSpeedmultiplier.Value; } } } [HarmonyPatch] public class ClonedItems { [HarmonyPatch(typeof(ItemDrop), "DropItem")] public static class DropItem { [HarmonyPriority(800)] private static void Prefix(ItemDrop __instance, ItemData item) { if (!((Object)(object)item.m_dropPrefab != (Object)null)) { if (item != null && item.m_shared != null && item.m_shared.m_name.Equals(" Basic Armor Kit I", StringComparison.CurrentCultureIgnoreCase)) { item.m_dropPrefab = PrefabManager.Instance.GetPrefab("ArmorKit1"); } if (item != null && item.m_shared != null && item.m_shared.m_name.Equals("Good Armor Kit II", StringComparison.CurrentCultureIgnoreCase)) { item.m_dropPrefab = PrefabManager.Instance.GetPrefab("ArmorKit2"); } if (item != null && item.m_shared != null && item.m_shared.m_name.Equals("Great Armor Kit III", StringComparison.CurrentCultureIgnoreCase)) { item.m_dropPrefab = PrefabManager.Instance.GetPrefab("ArmorKit3"); } if (item != null && item.m_shared != null && item.m_shared.m_name.Equals("Superior Armor Kit IV", StringComparison.CurrentCultureIgnoreCase)) { item.m_dropPrefab = PrefabManager.Instance.GetPrefab("ArmorKit4"); } if (item != null && item.m_shared != null && item.m_shared.m_name.Equals("Basic Weapon Kit I", StringComparison.CurrentCultureIgnoreCase)) { item.m_dropPrefab = PrefabManager.Instance.GetPrefab("WeaponKit1"); } if (item != null && item.m_shared != null && item.m_shared.m_name.Equals("Good Weapon Kit II", StringComparison.CurrentCultureIgnoreCase)) { item.m_dropPrefab = PrefabManager.Instance.GetPrefab("WeaponKit2"); } if (item != null && item.m_shared != null && item.m_shared.m_name.Equals("Great Weapon Kit III", StringComparison.CurrentCultureIgnoreCase)) { item.m_dropPrefab = PrefabManager.Instance.GetPrefab("WeaponKit3"); } if (item != null && item.m_shared != null && item.m_shared.m_name.Equals("Superior Weapon Kit IV", StringComparison.CurrentCultureIgnoreCase)) { item.m_dropPrefab = PrefabManager.Instance.GetPrefab("WeaponKit4"); } } } } public static void LoadAssets() { PrefabManager.OnPrefabsRegistered += AddClonedItems; PieceManager.OnPiecesRegistered += AddClonedPieces; CreatureManager.OnVanillaCreaturesAvailable += AddVanillaClonedCreatures; } private static void AddClonedItems() { AddPortalToken(); AddSpawnerToken(); AddItemKits(); PrefabManager.OnPrefabsRegistered -= AddClonedItems; } private static void AddClonedPieces() { AddAesirChest(); AddAdminWards(); AddBuildableSpawners(); PieceManager.OnPiecesRegistered -= AddClonedPieces; } private static void AddVanillaClonedCreatures() { AddBatzao(); AddNomTameableWolf(); AddPorcoLox(); AddSkeletao(); CreatureManager.OnVanillaCreaturesAvailable -= AddVanillaClonedCreatures; } private static void AddAdminWards() { AddBigdminWard(); AddSmallAdminWard(); } private static void AddItemKits() { AddArmorKit("ArmorKit1", "piece_chest_wood", "Basic Armor Kit I", "Kit de itens utilizados para fabricar armaduras de menor qualidade pertencente a era do bronze.", "Wood", "Guck", "armorkit1.png"); AddArmorKit("ArmorKit2", "piece_chest_wood", "Good Armor Kit II", "Kit de itens utilizados para fabricar armaduras de refinadas de qualidade pertencente a era do ferro.", "Wood", "Blueberries", "armorkit2.png"); AddArmorKit("ArmorKit3", "piece_chest_wood", "Great Armor Kit III", "Kit de itens utilizados para fabricar armaduras reluzentes beirando a perfeição, sua qualidade pertence a era da prata.", "Wood", "Amber", "armorkit3.png"); AddArmorKit("ArmorKit4", "piece_chest_wood", "Superior Armor Kit IV", "Kit de itens utilizados para fabricar armaduras de maior qualidade dentro os mortais beirando o divino pertencentes a era do linho.", "Wood", "Ruby", "armorkit4.png"); AddArmorKit("WeaponKit1", "piece_chest_wood", "Basic Weapon Kit I", "Kit de itens utilizados para fabricar armas mais simples de qualidade duvidosa, muito utilizada na era do bronze.", "FineWood", "Guck", "weaponkit1.png"); AddArmorKit("WeaponKit2", "piece_chest_wood", "Good Weapon Kit II", "Kit de itens utilizados para fabricar armas maior refinaria, muito utilizada na era do ferro.", "FineWood", "Blueberries", "weaponkit2.png"); AddArmorKit("WeaponKit3", "piece_chest_wood", "Great Weapon Kit III", "Kit de itens utilizados para fabricar armas prateadas com brilhos que afligem os olhos, muito utilizada na era da prata.", "FineWood", "Amber", "weaponkit3.png"); AddArmorKit("WeaponKit4", "piece_chest_wood", "Superior Weapon Kit IV", "Kit de itens utilizados para fabricar armas negras, extremamente laminadas capazes de perfurar a grossa pele de um Lox utilizada por aqueles que chegaram na era do metal negro.", "FineWood", "Ruby", "weaponkit4.png"); } private static T CopyComponent<T>(T original, GameObject destination) where T : Component { Type type = ((object)original).GetType(); Component val = destination.AddComponent(type); FieldInfo[] fields = type.GetFields(); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { fieldInfo.SetValue(val, fieldInfo.GetValue(original)); } return (T)(object)((val is T) ? val : null); } private static void AddArmorKit(string prefabName, string prefabToCopy, string name, string description, string firstShaderPrefabName, string secondShaderPrefabName, string icon) { //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Expected O, but got Unknown //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_0123: Unknown result type (might be due to invalid IL or missing references) ItemDrop component = PrefabManager.Instance.GetPrefab("Resin").GetComponent<ItemDrop>(); GameObject val = PrefabManager.Instance.CreateClonedPrefab(prefabName, prefabToCopy); Object.Destroy((Object)(object)val.GetComponent<Piece>()); Object.Destroy((Object)(object)val.GetComponent<Container>()); Object.Destroy((Object)(object)val.GetComponent<WearNTear>()); Object.Destroy((Object)(object)val.GetComponent<ZNetView>()); val.AddComponent<ZNetView>(); ItemDrop val2 = val.AddComponent<ItemDrop>(); val2.m_floating = val.AddComponent<Floating>(); val2.m_body = val.AddComponent<Rigidbody>(); val2.m_itemData.m_shared = new SharedData(); val2.m_itemData.m_shared.m_icons = (Sprite[])(object)new Sprite[1] { Util.LoadSprite(icon, 64, 64) }; val2.m_itemData.m_shared.m_name = name; val2.m_itemData.m_shared.m_description = description; val2.m_itemData.m_shared.m_maxStackSize = 25; Vector3 localScale = val.transform.localScale; localScale.x *= 0.3f; localScale.y *= 0.3f; localScale.z *= 0.3f; val.transform.localScale = localScale; MeshRenderer[] componentsInChildren = val.GetComponentsInChildren<MeshRenderer>(); MeshRenderer[] array = componentsInChildren; foreach (MeshRenderer val3 in array) { List<Material> list = new List<Material>(); if ((Object)(object)val3 == (Object)(object)componentsInChildren[0]) { list.Add(((Renderer)PrefabManager.Instance.GetPrefab(firstShaderPrefabName).GetComponentInChildren<MeshRenderer>()).materials[0]); } else { list.Add(((Renderer)PrefabManager.Instance.GetPrefab(secondShaderPrefabName).GetComponentInChildren<MeshRenderer>()).materials[0]); } ((Renderer)val3).materials = list.ToArray(); } val.GetComponent<ItemDrop>().m_itemData.m_dropPrefab = val; ItemManager.Instance.RegisterItemInObjectDB(val); } private static void AddSmallAdminWard() { GameObject val = PrefabManager.Instance.CreateClonedPrefab("AdminWardSmall", "guard_stone"); Piece component = val.GetComponent<Piece>(); component.m_resources[0].m_resItem = PrefabManager.Instance.GetPrefab("SwordCheat").GetComponent<ItemDrop>(); component.m_resources[0].m_recover = false; component.m_description = "Admin Ward small"; component.m_name = "Admin Ward small"; PrivateArea component2 = ((Component)component).GetComponent<PrivateArea>(); component2.m_radius = 40f; component2.m_name = "AdminWardSmall"; MeshRenderer componentInChildren = val.GetComponentInChildren<MeshRenderer>(); List<Material> list = new List<Material>(); list.Add(((Renderer)PrefabManager.Instance.GetPrefab("FreezeGland").GetComponentInChildren<MeshRenderer>()).materials[0]); list.Add(((Renderer)PrefabManager.Instance.GetPrefab("FreezeGland").GetComponentInChildren<MeshRenderer>()).materials[0]); ((Renderer)componentInChildren).materials = list.ToArray(); PieceManager.Instance.RegisterPieceInPieceTable(val, "Hammer", "Misc"); } private static void AddBigdminWard() { GameObject val = PrefabManager.Instance.CreateClonedPrefab("AdminWard", "guard_stone"); Piece component = val.GetComponent<Piece>(); component.m_resources[0].m_resItem = PrefabManager.Instance.GetPrefab("SwordCheat").GetComponent<ItemDrop>(); component.m_resources[0].m_recover = false; component.m_description = "Admin Ward"; component.m_name = "Admin Ward"; PrivateArea component2 = ((Component)component).GetComponent<PrivateArea>(); component2.m_radius = 150f; component2.m_name = "AdminWard"; MeshRenderer componentInChildren = val.GetComponentInChildren<MeshRenderer>(); List<Material> list = new List<Material>(); list.Add(((Renderer)PrefabManager.Instance.GetPrefab("Tar").GetComponentInChildren<MeshRenderer>()).materials[0]); list.Add(((Renderer)PrefabManager.Instance.GetPrefab("SurtlingCore").GetComponentInChildren<MeshRenderer>()).materials[0]); ((Renderer)componentInChildren).materials = list.ToArray(); PieceManager.Instance.RegisterPieceInPieceTable(val, "Hammer", "Misc"); } private static void AddAesirChest() { GameObject val = PrefabManager.Instance.CreateClonedPrefab("AesirChest", "piece_chest_private"); Piece component = val.GetComponent<Piece>(); component.m_resources[0].m_resItem = PrefabManager.Instance.GetPrefab("Bronze").GetComponent<ItemDrop>(); component.m_resources[1].m_resItem = PrefabManager.Instance.GetPrefab("Wood").GetComponent<ItemDrop>(); component.m_description = "Aesir Chest"; component.m_name = "Aesir Chest"; PieceManager.Instance.RegisterPieceInPieceTable(val, "Hammer", "Furniture"); } private static void AddPortalToken() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown CustomItem val = new CustomItem("PortalToken", "Thunderstone"); ItemDrop itemDrop = val.ItemDrop; itemDrop.m_itemData.m_shared.m_name = "Portal Token"; itemDrop.m_itemData.m_shared.m_description = "Me compre para o Detalhes poder manter seu vício."; itemDrop.m_itemData.m_shared.m_maxStackSize = 10; ItemManager.Instance.AddItem(val); } private static void AddSpawnerToken() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown CustomItem val = new CustomItem("SpawnerToken", "Thunderstone"); ItemDrop itemDrop = val.ItemDrop; itemDrop.m_itemData.m_shared.m_name = "Spawner Token"; itemDrop.m_itemData.m_shared.m_description = "Token used to build protected vanilla spawners."; itemDrop.m_itemData.m_shared.m_maxStackSize = 10; ItemManager.Instance.AddItem(val); } private static void AddBuildableSpawners() { AddBuildableSpawner("BuildableGreydwarfNestSpawner", "Spawner_GreydwarfNest", "Black Forest Spawner", "Indestructible Black Forest monster spawner."); AddBuildableSpawner("BuildableDraugrPileSpawner", "Spawner_DraugrPile", "Swamp Spawner", "Indestructible Swamp monster spawner."); } private static void AddBuildableSpawner(string prefabName, string sourcePrefabName, string name, string description) { //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Expected O, but got Unknown GameObject prefab = PrefabManager.Instance.GetPrefab(sourcePrefabName); if ((Object)(object)prefab == (Object)null) { Logger.LogWarning((object)("Could not create " + name + ". Missing vanilla prefab: " + sourcePrefabName)); return; } GameObject val = PrefabManager.Instance.CreateClonedPrefab(prefabName, sourcePrefabName); Piece val2 = val.GetComponent<Piece>() ?? val.AddComponent<Piece>(); val2.m_name = name; val2.m_description = description; val2.m_enabled = true; val2.m_icon = GetSpawnerIcon(sourcePrefabName) ?? val2.m_icon; val2.m_category = (PieceCategory)0; val2.m_groundPiece = true; val2.m_groundOnly = true; val2.m_clipGround = true; val2.m_noInWater = true; val2.m_canRotate = true; val2.m_canBeRemoved = true; val2.m_repairPiece = false; val2.m_resources = (Requirement[])(object)new Requirement[1] { new Requirement { m_resItem = PrefabManager.Instance.GetPrefab("SpawnerToken").GetComponent<ItemDrop>(), m_amount = 1, m_recover = true } }; WearNTear component = val.GetComponent<WearNTear>(); if ((Object)(object)component != (Object)null) { component.m_health = 999999f; component.m_noRoofWear = true; component.m_noSupportWear = true; } Destructible component2 = val.GetComponent<Destructible>(); if ((Object)(object)component2 != (Object)null) { component2.m_health = 999999f; } PieceManager.Instance.RegisterPieceInPieceTable(val, "Hammer", "Misc"); } private static Sprite GetSpawnerIcon(string sourcePrefabName) { string text = ((sourcePrefabName == "Spawner_GreydwarfNest") ? "GreydwarfEye" : "WitheredBone"); GameObject prefab = PrefabManager.Instance.GetPrefab(text); Sprite val = ((prefab == null) ? null : prefab.GetComponent<ItemDrop>()?.m_itemData?.m_shared?.m_icons?.FirstOrDefault()); if ((Object)(object)val != (Object)null) { return val; } GameObject prefab2 = PrefabManager.Instance.GetPrefab("SpawnerToken"); return (prefab2 == null) ? null : prefab2.GetComponent<ItemDrop>()?.m_itemData?.m_shared?.m_icons?.FirstOrDefault(); } private static void AddNomTameableWolf() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected O, but got Unknown //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Expected O, but got Unknown CustomCreature val = new CustomCreature("LoboNaoDomavel", "Wolf", new CreatureConfig()); Humanoid component = val.Prefab.GetComponent<Humanoid>(); ((Character)component).m_name = "Lobo nao domavel"; CreatureManager.Instance.AddCreature(val); Object.Destroy((Object)(object)val.Prefab.GetComponent<Tameable>()); Object.Destroy((Object)(object)val.Prefab.GetComponent<Procreation>()); } private static void AddSkeletao() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected O, but got Unknown //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) CustomCreature val = new CustomCreature("Skeletao", "Skeleton", new CreatureConfig { Faction = (Faction)3 }); Humanoid component = val.Prefab.GetComponent<Humanoid>(); ((Character)component).m_name = "Esqueletão"; ((Character)component).m_boss = true; ((Character)component).m_health = 500f; SkinnedMeshRenderer[] componentsInChildren = val.Prefab.GetComponentsInChildren<SkinnedMeshRenderer>(); SkinnedMeshRenderer[] array = componentsInChildren; foreach (SkinnedMeshRenderer val2 in array) { ((Renderer)val2).material.color = Color.black; ((Renderer)val2).sharedMaterial.color = Color.black; } Vector3 localScale = val.Prefab.transform.localScale; localScale.x *= 1.3f; localScale.y *= 1.3f; localScale.z *= 1.3f; val.Prefab.transform.localScale = localScale; CreatureManager.Instance.AddCreature(val); Object.Destroy((Object)(object)val.Prefab.GetComponent<Tameable>()); Object.Destroy((Object)(object)val.Prefab.GetComponent<Procreation>()); } private static void AddPorcoLox() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0023: Expected O, but got Unknown //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) CustomCreature val = new CustomCreature("PorcoLox", "Lox", new CreatureConfig { Faction = (Faction)2 }); Humanoid component = val.Prefab.GetComponent<Humanoid>(); GameObject val2 = PrefabManager.Instance.CreateClonedPrefab("PorcoLoxRagDoll", "lox_ragdoll"); ((Character)component).m_name = "PorcoLox"; ((Character)component).m_boss = true; ((Character)component).m_health = 300f; ColorRenderers(val.Prefab, Color.black); Vector3 localScale = val.Prefab.transform.localScale; localScale.x *= 0.5f; localScale.y *= 0.5f; localScale.z *= 0.5f; val2.transform.localScale = localScale; int index = ((Character)component).m_deathEffects.m_effectPrefabs.ToList().FindIndex((EffectData x) => ((Object)x.m_prefab).name == "lox_ragdoll"); ((Character)val.Prefab.GetComponent<Humanoid>()).m_deathEffects.m_effectPrefabs.ToList()[index].m_prefab = val2; ColorRenderers(val2, Color.black); val.Prefab.transform.localScale = localScale; CreatureManager.Instance.AddCreature(val); Object.Destroy((Object)(object)val.Prefab.GetComponent<Tameable>()); Object.Destroy((Object)(object)val.Prefab.GetComponent<Procreation>()); } public static void ColorRenderers(GameObject gameObject, Color color) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) SkinnedMeshRenderer[] componentsInChildren = gameObject.GetComponentsInChildren<SkinnedMeshRenderer>(); SkinnedMeshRenderer[] array = componentsInChildren; foreach (SkinnedMeshRenderer val in array) { ((Renderer)val).material.color = color; ((Renderer)val).sharedMaterial.color = color; } } private static void AddBatzao() { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_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_005a: Expected O, but got Unknown //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Expected O, but got Unknown //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) CreatureConfig val = new CreatureConfig(); val.DropConfigs = (DropConfig[])(object)new DropConfig[1] { new DropConfig { Item = "Coins", Chance = 100f, MinAmount = 50, MaxAmount = 100, OnePerPlayer = false, LevelMultiplier = false } }; val.Faction = (Faction)3; CustomCreature val2 = new CustomCreature("Morcegao", "Bat", val); Vector3 localScale = val2.Prefab.transform.localScale; localScale.x *= 3f; localScale.y *= 3f; localScale.z *= 3f; val2.Prefab.transform.localScale = localScale; Humanoid component = val2.Prefab.GetComponent<Humanoid>(); ((Character)component).m_name = "Morcegão"; ((Character)component).m_health = 500f; ((Character)component).m_boss = true; CreatureManager.Instance.AddCreature(val2); } } [HarmonyPatch(typeof(Container), "Awake")] public static class Container_Awake_Patch { private const int woodChestRows = 4; private const int woodChestColumns = 5; private const int personalChestRows = 6; private const int personalChestColumns = 6; private const int ironChestRows = 8; private const int ironChestColumns = 6; private const int karveInventoryRows = 4; private const int karveInventoryColumns = 2; private const int longboatInventoryRows = 6; private const int longboatInventoryColumns = 6; private const int cartInventoryRows = 5; private const int cartInventoryColumns = 6; private const int aesirRows = 8; private static void Postfix(Container __instance, ref Inventory ___m_inventory) { if (((Object)(object)__instance == (Object)null || ___m_inventory == null || !Object.op_Implicit((Object)(object)((Component)__instance).transform.parent)) && ___m_inventory != null && ((Object)((Component)__instance).gameObject).name.Contains("AesirChest")) { ___m_inventory.m_width = 6; ___m_inventory.m_height = 6; } } } internal class CraftingStations { [HarmonyPatch(typeof(CraftingStation), "CheckUsable")] public static class WorkbenchRemoveRestrictions { private static bool Prefix(ref CraftingStation __instance) { __instance.m_craftRequireRoof = false; return true; } } [HarmonyPatch(typeof(PrivateArea), "Awake")] public static class PrivateAreaAwake { public static void Postfix(ref PrivateArea __instance) { int num = Plugin.WardRadius.Value; if (__instance.m_name.Contains("AdminWard")) { num = 50; } if (__instance.m_name.Contains("RaidWard")) { num = 50; } __instance.m_areaMarker.m_radius = num; __instance.m_radius = num; } } } public static class EpicMMOApi { private enum API_State { NotReady, NotInstalled, Ready } private static string pluginKey = "EpicMMOSystem"; private static API_State state = API_State.NotReady; private static MethodInfo eGetLevel; private static MethodInfo eAddExp; private static MethodInfo eGetAttribute; public static int GetLevel() { int result = 0; Init(); if (eGetLevel != null) { result = (int)eGetLevel.Invoke(null, null); } return result; } public static int GetAttribute(string attribute) { string value = 0.ToString(); Player.m_localPlayer.m_knownTexts.TryGetValue(pluginKey + "_LevelSystem_" + attribute, out value); return Convert.ToInt32(value); } public static void AddExp(int value) { Init(); eAddExp?.Invoke(null, new object[1] { value }); } private static void Init() { API_State aPI_State = state; if (aPI_State != API_State.Ready && aPI_State != API_State.NotInstalled) { if (Type.GetType("EpicMMOSystem.EpicMMOSystem, EpicMMOSystem") == null) { state = API_State.NotInstalled; return; } state = API_State.Ready; Type type = Type.GetType("API.EMMOS_API, EpicMMOSystem"); eGetLevel = type.GetMethod("GetLevel", BindingFlags.Static | BindingFlags.Public); eAddExp = type.GetMethod("AddExp", BindingFlags.Static | BindingFlags.Public); eGetAttribute = type.GetMethod("GetAttribute", BindingFlags.Static | BindingFlags.Public); } } } internal class ItemService { public static void ModifyItemsCost() { //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c3: Expected O, but got Unknown //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Expected O, but got Unknown //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_011d: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Expected O, but got Unknown //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_014e: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Expected O, but got Unknown GameObject prefab = PrefabManager.Instance.GetPrefab("piece_cartographytable"); prefab.GetComponent<Piece>().m_resources[0].m_amount = 100; prefab.GetComponent<Piece>().m_resources[1].m_amount = 100; prefab.GetComponent<Piece>().m_resources[2].m_amount = 100; prefab.GetComponent<Piece>().m_resources[3].m_amount = 100; prefab.GetComponent<Piece>().m_resources[4].m_amount = 100; GameObject prefab2 = PrefabManager.Instance.GetPrefab("portal_wood"); Piece component = prefab2.GetComponent<Piece>(); component.m_resources = (Requirement[])(object)new Requirement[4] { new Requirement { m_resItem = PrefabManager.Instance.GetPrefab("PortalToken").GetComponent<ItemDrop>(), m_amount = 1, m_recover = true }, new Requirement { m_resItem = PrefabManager.Instance.GetPrefab("FineWood").GetComponent<ItemDrop>(), m_amount = 100, m_recover = true }, new Requirement { m_resItem = PrefabManager.Instance.GetPrefab("GreydwarfEye").GetComponent<ItemDrop>(), m_amount = 30, m_recover = true }, new Requirement { m_resItem = PrefabManager.Instance.GetPrefab("SurtlingCore").GetComponent<ItemDrop>(), m_amount = 10, m_recover = true } }; } public static void OnlyAdminPieces() { GameObject val = ((IEnumerable<GameObject>)ObjectDB.instance.m_items).FirstOrDefault((Func<GameObject, bool>)((GameObject x) => ((Object)x).name == "Hammer")); PieceTable buildPieces = val.GetComponent<ItemDrop>().m_itemData.m_shared.m_buildPieces; string[] array = Plugin.OnlyAdminPieces.Value.Split(new char[1] { ',' }); foreach (string text in array) { GameObject prefab = PrefabManager.Instance.GetPrefab(text); if (prefab != null) { Piece component = prefab.GetComponent<Piece>(); Requirement[] resources = component.m_resources; foreach (Requirement val2 in resources) { val2.m_resItem = PrefabManager.Instance.GetPrefab("SwordCheat").GetComponent<ItemDrop>(); val2.m_recover = false; } if (!SynchronizationManager.Instance.PlayerIsAdmin) { buildPieces.m_pieces.Remove(prefab); } } } } public static void SetWardFirePlace() { GameObject prefab = PrefabManager.Instance.GetPrefab("guard_stone"); Fireplace val = prefab.AddComponent<Fireplace>(); val.m_fuelItem = PrefabManager.Instance.GetPrefab("GreydwarfEye").GetComponent<ItemDrop>(); } public static void NerfRunicCape() { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Expected O, but got Unknown GameObject itemPrefab = ObjectDB.instance.GetItemPrefab("rae_CapeHorseHide"); if (Object.op_Implicit((Object)(object)itemPrefab)) { ItemDrop component = itemPrefab.GetComponent<ItemDrop>(); SE_Stats val = (SE_Stats)component.m_itemData.m_shared.m_equipStatusEffect; val.m_mods = new List<DamageModPair>(); } } public static void WolvesTameable() { if (!Plugin.WolvesAreTameable.Value) { GameObject prefab = PrefabManager.Instance.GetPrefab("Wolf"); if (Object.op_Implicit((Object)(object)prefab)) { Tameable component = prefab.GetComponent<Tameable>(); Procreation component2 = prefab.GetComponent<Procreation>(); Object.Destroy((Object)(object)component); Object.Destroy((Object)(object)component2); } } } public static void LoxTameable() { if (!Plugin.LoxTameable.Value) { GameObject prefab = PrefabManager.Instance.GetPrefab("Lox"); if (Object.op_Implicit((Object)(object)prefab)) { Tameable component = prefab.GetComponent<Tameable>(); Procreation component2 = prefab.GetComponent<Procreation>(); Object.Destroy((Object)(object)component); Object.Destroy((Object)(object)component2); } } } public static void StubNoLife() { List<GameObject> list = new List<GameObject>(); list.Add(PrefabManager.Instance.GetPrefab("Pinetree_01_Stub")); list.Add(PrefabManager.Instance.GetPrefab("SwampTree1_Stub")); list.Add(PrefabManager.Instance.GetPrefab("BirchStub")); list.Add(PrefabManager.Instance.GetPrefab("FirTree_Stub")); list.Add(PrefabManager.Instance.GetPrefab("OakStub")); list.Add(PrefabManager.Instance.GetPrefab("Beech_Stub")); foreach (GameObject item in list) { Destructible component = item.GetComponent<Destructible>(); component.m_health = 1f; } } } public static class MarketplaceTeleporterCosts { private static readonly Regex RichTextRegex = new Regex("</?(?!color\\b)\\w+[^>]*>", RegexOptions.Compiled); private static string _currentTeleporterNpcName = ""; private static Harmony _harmony; private static bool _npcPatchApplied; private static bool _clickPatchApplied; private static bool _waitingLogged; private static string _lastPatchError = ""; public static void StartPatchRetry(MonoBehaviour host, Harmony harmony) { if (!((Object)(object)host == (Object)null) && harmony != null) { _harmony = harmony; host.StartCoroutine(PatchWhenMarketplaceReady()); } } private static IEnumerator PatchWhenMarketplaceReady() { while (!_npcPatchApplied || !_clickPatchApplied) { TryPatchMarketplace(); if (_npcPatchApplied && _clickPatchApplied) { Debug.Log((object)"[Deadheim] Marketplace teleporter cost patches applied."); break; } if (!_waitingLogged) { Debug.Log((object)"[Deadheim] Waiting for Marketplace to load before applying teleporter cost patches."); _waitingLogged = true; } yield return (object)new WaitForSeconds(2f); } } private static void TryPatchMarketplace() { //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Expected O, but got Unknown if (_harmony == null) { return; } try { if (!_npcPatchApplied) { MethodBase methodBase = FindRememberTeleporterNpcTarget(); if (methodBase != null) { _harmony.Patch(methodBase, new HarmonyMethod(typeof(MarketplaceTeleporterCosts), "RememberTeleporterNpcPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); _npcPatchApplied = true; } } if (!_clickPatchApplied) { MethodBase methodBase2 = FindTeleporterPinClickTarget(); if (methodBase2 != null) { _harmony.Patch(methodBase2, new HarmonyMethod(typeof(MarketplaceTeleporterCosts), "ChargeOnTeleporterPinClickPrefix", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); _clickPatchApplied = true; } } } catch (Exception ex) { if (_lastPatchError != ex.Message) { _lastPatchError = ex.Message; Debug.LogWarning((object)("[Deadheim] Marketplace teleporter patch retry failed: " + ex.Message)); } } } private static MethodBase FindRememberTeleporterNpcTarget() { Type type = AccessTools.TypeByName("Marketplace.Modules.NPC.Market_NPC+NPCcomponent"); if (type != null) { MethodBase methodBase = FindOpenUIForType(type); if (methodBase != null) { return methodBase; } } Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { Type[] array; try { array = assembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { array = Array.FindAll(ex.Types, (Type t) => t != null); } catch { continue; } Type[] array2 = array; foreach (Type type2 in array2) { if (type2.FullName.IndexOf("Marketplace", StringComparison.OrdinalIgnoreCase) >= 0) { MethodBase methodBase2 = FindOpenUIForType(type2); if (methodBase2 != null) { return methodBase2; } } } } return null; } private static MethodBase FindOpenUIForType(Type type) { foreach (MethodInfo declaredMethod in AccessTools.GetDeclaredMethods(type)) { ParameterInfo[] parameters = declaredMethod.GetParameters(); if (declaredMethod.Name != "OpenUIForType" || parameters.Length < 3 || parameters[1].ParameterType != typeof(string) || parameters[2].ParameterType != typeof(string)) { continue; } return declaredMethod; } return null; } private static void RememberTeleporterNpcPrefix(object[] __args) { if (__args != null && __args.Length >= 3 && __args[0] != null) { string text = __args[0].ToString(); if (text.Equals("Teleporter", StringComparison.OrdinalIgnoreCase)) { _currentTeleporterNpcName = CleanName(__args[2] as string); } } } private static MethodBase FindTeleporterPinClickTarget() { Type type = AccessTools.TypeByName("Marketplace.Modules.Teleporter.Teleporter_Main_Client+PatchClickIconMinimap"); MethodBase methodBase = ((type == null) ? null : AccessTools.Method(type, "Prefix", new Type[1] { typeof(Minimap) }, (Type[])null)); if (methodBase != null) { return methodBase; } Assembly[] assemblies = AppDomain.CurrentDomain.GetAssemblies(); foreach (Assembly assembly in assemblies) { Type[] array; try { array = assembly.GetTypes(); } catch (ReflectionTypeLoadException ex) { array = Array.FindAll(ex.Types, (Type t) => t != null); } catch { continue; } Type[] array2 = array; foreach (Type type2 in array2) { if (type2.FullName.IndexOf("Marketplace", StringComparison.OrdinalIgnoreCase) >= 0 && type2.FullName.IndexOf("Teleporter", StringComparison.OrdinalIgnoreCase) >= 0) { MethodInfo methodInfo = AccessTools.Method(type2, "Prefix", new Type[1] { typeof(Minimap) }, (Type[])null); if (methodInfo != null) { return methodInfo; } } } } return null; } private static bool ChargeOnTeleporterPinClickPrefix(Minimap __0) { try { if ((Object)(object)__0 == (Object)null || (Object)(object)Player.m_localPlayer == (Object)null) { return true; } if (!TryGetClickedTeleporterPin(__0, out var _)) { return true; } int costForNpc = GetCostForNpc(_currentTeleporterNpcName); if (costForNpc <= 0) { return true; } if (!CanUseMarketplaceTeleporterWithCurrentInventory()) { return true; } Inventory inventory = ((Humanoid)Player.m_localPlayer).GetInventory(); string value = Plugin.MarketplaceTeleporterCostItem.Value; int num = inventory.CountItems(value, -1, true); if (num < costForNpc) { ((Character)Player.m_localPlayer).Message((MessageType)2, $"Voce precisa de {costForNpc} moedas para teleportar com {_currentTeleporterNpcName}.", 0, (Sprite)null); __0.SetMapMode((MapMode)1); return false; } inventory.RemoveItem(value, costForNpc, -1, true); ((Character)Player.m_localPlayer).Message((MessageType)2, $"Teleporte pago: {costForNpc} moedas.", 0, (Sprite)null); return true; } catch (Exception ex) { Debug.LogWarning((object)("[Deadheim] Marketplace teleporter cost check failed: " + ex)); return true; } } private static int GetCostForNpc(string npcName) { if (string.IsNullOrWhiteSpace(npcName) || Plugin.MarketplaceTeleporterCosts == null) { return 0; } Dictionary<string, int> dictionary = ParseCosts(Plugin.MarketplaceTeleporterCosts.Value); int value; return dictionary.TryGetValue(NormalizeName(npcName), out value) ? value : 0; } private static Dictionary<string, int> ParseCosts(string raw) { Dictionary<string, int> dictionary = new Dictionary<string, int>(StringComparer.OrdinalIgnoreCase); if (string.IsNullOrWhiteSpace(raw)) { return dictionary; } string[] array = raw.Split(new char[2] { ',', ';' }, StringSplitOptions.RemoveEmptyEntries); string[] array2 = array; foreach (string text in array2) { string[] array3 = text.Split(new char[1] { ':' }, 2); if (array3.Length == 2) { string text2 = NormalizeName(array3[0]); if (!string.IsNullOrWhiteSpace(text2) && int.TryParse(array3[1].Trim(), out var result) && result > 0) { dictionary[text2] = result; } } } return dictionary; } private static bool TryGetClickedTeleporterPin(Minimap minimap, out PinData clickedPin) { //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) clickedPin = null; Type type = AccessTools.TypeByName("Marketplace.Modules.Teleporter.Teleporter_Main_Client"); if (!(((type == null) ? null : AccessTools.Field(type, "CurrentTeleporterObjects"))?.GetValue(null) is IEnumerable enumerable)) { return false; } Vector3 val = minimap.ScreenToWorldPoint(Input.mousePosition); float num = minimap.m_removeRadius * minimap.m_largeZoom * 2f; foreach (object item in enumerable) { PinData val2 = (PinData)((item is PinData) ? item : null); if (val2 == null || Vector3.Distance(val2.m_pos, val) > num) { continue; } clickedPin = val2; return true; } return false; } private static bool CanUseMarketplaceTeleporterWithCurrentInventory() { if (((Humanoid)Player.m_localPlayer).IsTeleportable()) { return true; } return MarketplaceAllowsTeleportWithOre(); } private static bool MarketplaceAllowsTeleportWithOre() { try { Type type = AccessTools.TypeByName("Marketplace.Modules.Global_Options.Global_Configs"); object obj = ((type == null) ? null : AccessTools.Field(type, "SyncedGlobalOptions"))?.GetValue(null); object obj2 = obj?.GetType().GetProperty("Value")?.GetValue(obj, null); FieldInfo fieldInfo = ((obj2 == null) ? null : AccessTools.Field(obj2.GetType(), "_canTeleportWithOre")); return fieldInfo != null && (bool)fieldInfo.GetValue(obj2); } catch { return false; } } private static string CleanName(string name) { if (string.IsNullOrWhiteSpace(name)) { return ""; } return RichTextRegex.Replace(name, "").Trim(); } private static string NormalizeName(string name) { return CleanName(name).ToLowerInvariant(); } } [HarmonyPatch] public class Patches : MonoBehaviour { [HarmonyPatch(typeof(Player), "SetPlayerID")] internal class SetPlayerID { private static void Postfix(long playerID, string name) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) try { if (Object.op_Implicit((Object)(object)Player.m_localPlayer)) { Plugin.steamId = ((IUser)PlatformManager.DistributionPlatform.LocalUser).PlatformUserID.m_userID; Plugin.PlayerName = ((Character)Player.m_localPlayer).m_nview.GetZDO().GetString("playerName", ""); Debug.Log((object)("steamId: " + Plugin.steamId)); } } catch { } } } [HarmonyPatch(typeof(Chat), "OnNewChatMessage")] internal class OnNewChatMessage { private static bool Prefix(string text) { if (text.ToLower().Contains("i have arrived")) { return false; } if (text.ToLower().Contains("i have arrived")) { return false; } return true; } } [HarmonyPatch(typeof(Player), "HaveSeenTutorial")] public class Player_HaveSeenTutorial_Patch { [HarmonyPrefix] private static void Prefix(Player __instance, ref string name) { if (!__instance.m_shownTutorials.Contains(name)) { __instance.m_shownTutorials.Add(name); } } } [HarmonyPatch(typeof(SE_Stats), "Setup")] public static class SE_Stats_Setup_Patch { private static void Postfix(ref SE_Stats __instance) { int num = 200; if (__instance.m_addMaxCarryWeight > 0f) { __instance.m_addMaxCarryWeight = __instance.m_addMaxCarryWeight - 150f + (float)num; } } } [HarmonyPatch(typeof(Player), "Update")] public static class PlayerUpdate { [HarmonyPriority(0)] private static void Postfix(Player __instance) { if (Plugin.StaffMessage.Value != "") { ((Character)Player.m_localPlayer).Message((MessageType)2, Plugin.StaffMessage.Value, 0, (Sprite)null); } } } [HarmonyPatch(typeof(ZNet), "GetOtherPublicPlayers")] private class AdminGetOtherPublicPlayers { [HarmonyPriority(0)] private static void Postfix(List<PlayerInfo> playerList) { //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) if (!SynchronizationManager.Instance.PlayerIsAdmin || (Object)(object)ZNet.instance == (Object)null || playerList == null) { return; } Player localPlayer = Player.m_localPlayer; object obj; if (localPlayer == null) { obj = null; } else { ZNetView nview = ((Character)localPlayer).m_nview; if (nview == null) { obj = null; } else { ZDO zDO = nview.GetZDO(); obj = ((zDO != null) ? zDO.GetString("playerName", "") : null); } } if (obj == null) { obj = ""; } string text = (string)obj; foreach (PlayerInfo player in ZNet.instance.GetPlayerList()) { if (!string.IsNullOrWhiteSpace(player.m_name) && !(player.m_name == text) && !playerList.Exists((PlayerInfo existing) => existing.m_name == player.m_name)) { playerList.Add(player); } } } } [HarmonyPatch(typeof(CraftingStation), "Start")] public static class WorkbenchRangeIncrease { public static void Prefix(ref CraftingStation __instance, ref float ___m_rangeBuild, GameObject ___m_areaMarker) { try { ___m_rangeBuild = 30f; ___m_areaMarker.GetComponent<CircleProjector>().m_radius = ___m_rangeBuild; } catch { } } } [HarmonyPatch(typeof(Skills), "RaiseSkill")] public static class RaiseSkill { private static bool Prefix(ref Skills __instance, ref SkillType skillType, ref float factor) { Skill skill = __instance.GetSkill(skillType); if (skill.m_level >= (float)Plugin.SkillCap.Value) { return false; } factor *= Plugin.SkillMultiplier.Value; return true; } } [HarmonyPatch(typeof(TeleportWorld), "Teleport")] public static class TeleportWorldAesir { private static bool Prefix(TeleportWorld __instance, Player player) { if ((Object)(object)player != (Object)(object)Player.m_localPlayer) { return true; } if (Plugin.Vip.Value.Contains(Plugin.steamId)) { return true; } string text = __instance.GetText(); if (!Plugin.VipPortalNames.Value.Contains(text)) { return true; } ((Character)player).Message((MessageType)2, "Only Aesir can access this portal.", 0, (Sprite)null); return false; } } [HarmonyPatch(typeof(Player), "PlacePiece")] public static class NoBuild_Patch { [HarmonyPriority(0)] private static bool Prefix(Piece piece, Player __instance) { if (Plugin.Vip.Value.Contains(Plugin.steamId)) { return true; } if (((Object)((Component)piece).gameObject).name == "AesirChest") { ((Character)__instance).Message((MessageType)2, "Esse báu é apenas para Aesir's", 0, (Sprite)null); return false; } return true; } } [HarmonyPatch(typeof(ZNetScene), "RemoveObjects")] public static class ZNetScene_RemoveObjects_NullGuard { private static readonly FieldInfo s_instances = typeof(ZNetScene).GetField("m_instances", BindingFlags.Instance | BindingFlags.NonPublic); private static bool _dirty = true; [HarmonyPrefix] private static void Prefix(ZNetScene __instance) { if (!_dirty || !(s_instances?.GetValue(__instance) is Dictionary<ZDO, ZNetView> dictionary)) { return; } List<ZDO> list = null; foreach (KeyValuePair<ZDO, ZNetView> item in dictionary) { if ((Object)(object)item.Value == (Object)null) { if (list == null) { list = new List<ZDO>(); } list.Add(item.Key); } } if (list != null) { foreach (ZDO item2 in list) { dictionary.Remove(item2); } Debug.LogWarning((object)$"[Deadheim] Removed {list.Count} null ZNetView entries from ZNetScene.m_instances to stop NullReferenceException spam."); } else { _dirty = false; } } [HarmonyPatch(typeof(Game), "Logout")] [HarmonyPostfix] private static void OnLogout() { _dirty = true; } } [HarmonyPostfix] [HarmonyPatch(typeof(Game), "Update")] private static void GameUpdate() { if (Object.op_Implicit((Object)(object)Player.m_localPlayer)) { ((Selectable)InventoryGui.instance.m_pvp).interactable = false; } } [HarmonyPatch(typeof(Player), "OnSpawned")] [HarmonyPostfix] public static void Awake_Postfix(ref Player __instance) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Expected O, but got Unknown if (ZRoutedRpc.instance != null) { ItemService.SetWardFirePlace(); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "Sync", new object[1] { (object)new ZPackage() }); } } [HarmonyPatch(typeof(Player), "EdgeOfWorldKill")] [HarmonyPrefix] public static bool EdgeOfWorldKill() { return false; } public static void setDeathStat(HitData ___m_lastHit) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Expected I4, but got Unknown HitType hitType = ___m_lastHit.m_hitType; HitType val = hitType; switch ((int)val) { case 0: Game.instance.IncrementPlayerStat((PlayerStatType)55, 1f); break; case 1: Game.instance.IncrementPlayerStat((PlayerStatType)56, 1f); break; case 2: Game.instance.IncrementPlayerStat((PlayerStatType)57, 1f); break; case 3: Game.instance.IncrementPlayerStat((PlayerStatType)58, 1f); break; case 4: Game.instance.IncrementPlayerStat((PlayerStatType)59, 1f); break; case 5: Game.instance.IncrementPlayerStat((PlayerStatType)60, 1f); break; case 6: Game.instance.IncrementPlayerStat((PlayerStatType)61, 1f); break; case 7: Game.instance.IncrementPlayerStat((PlayerStatType)62, 1f); break; case 8: Game.instance.IncrementPlayerStat((PlayerStatType)64, 1f); break; case 9: Game.instance.IncrementPlayerStat((PlayerStatType)63, 1f); break; case 10: Game.instance.IncrementPlayerStat((PlayerStatType)65, 1f); break; case 11: Game.instance.IncrementPlayerStat((PlayerStatType)66, 1f); break; case 12: Game.instance.IncrementPlayerStat((PlayerStatType)67, 1f); break; case 13: Game.instance.IncrementPlayerStat((PlayerStatType)68, 1f); break; case 14: Game.instance.IncrementPlayerStat((PlayerStatType)69, 1f); break; case 15: Game.instance.IncrementPlayerStat((PlayerStatType)70, 1f); break; case 16: Game.instance.IncrementPlayerStat((PlayerStatType)71, 1f); break; case 17: Game.instance.IncrementPlayerStat((PlayerStatType)72, 1f); break; case 18: Game.instance.IncrementPlayerStat((PlayerStatType)73, 1f); break; default: ZLog.LogWarning((object)("Not implemented death type " + ((object)(HitType)(ref ___m_lastHit.m_hitType)).ToString())); break; } } } [BepInPlugin("Detalhes.Deadheim", "Detalhes.Deadheim", "6.0.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] [NetworkCompatibility(/*Could not decode attribute arguments.*/)] public class Plugin : BaseUnityPlugin { public const string Version = "6.0.0"; public const string PluginGUID = "Detalhes.Deadheim"; public static string steamId = ""; public static ConfigEntry<string> Vip; public static ConfigEntry<string> AdminList; public static ConfigEntry<string> OnlyAdminPieces; public static ConfigEntry<string> VipPortalNames; public static ConfigEntry<int> WardRadius; public static ConfigEntry<string> StaffMessage; public static ConfigEntry<string> DungeonPrefabs; public static ConfigEntry<float> SkillMultiplier; public static ConfigEntry<float> BoatWindSpeedmultiplier; public static ConfigEntry<int> SafeArea; public static ConfigEntry<int> WardLimit; public static ConfigEntry<int> WardLimitVip; public static ConfigEntry<string> MarketplaceTeleporterCosts; public static ConfigEntry<string> MarketplaceTeleporterCostItem; public static ConfigEntry<int> WardChargeDurationInSec; public static ConfigEntry<bool> ResetWorldDay; public static ConfigEntry<bool> WolvesAreTameable; public static ConfigEntry<bool> LoxTameable; public static ConfigEntry<int> SkillCap; public static ConfigEntry<string> PortalMaterials; public static string PlayerName = ""; public static bool IsAdmin = false; public static int PlayerWardCount = 999; public static int PlayerPortalCount = 999; public static int maxPlayers = 50; public static List<ZRpc> validatedUsers = new List<ZRpc>(); public static bool hasSpawned = false; private Harmony _harmony = new Harmony("Detalhes.deadheim"); private void Update() { //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Expected O, but got Unknown Player localPlayer = Player.m_localPlayer; if ((Object)(object)Player.m_localPlayer == (Object)null || !Object.op_Implicit((Object)(object)localPlayer.m_hovering)) { return; } Interactable componentInParent = localPlayer.m_hovering.GetComponentInParent<Interactable>(); if (componentInParent != null && componentInParent is Bed) { Bed val = (Bed)componentInParent; if (val.IsMine() && Input.GetKeyDown((KeyCode)112)) { Retreat.SetHearthStonePosition(); ((Character)Player.m_localPlayer).Message((MessageType)2, "Seu novo ponto de Retreat", 0, (Sprite)null); } } } private void Awake() { //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Expected O, but got Unknown //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Expected O, but got Unknown //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Expected O, but got Unknown //IL_00d3: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Expected O, but got Unknown //IL_00e1: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Expected O, but got Unknown //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_0121: Expected O, but got Unknown //IL_0121: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Expected O, but got Unknown //IL_0153: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Unknown result type (might be due to invalid IL or missing references) //IL_0161: Expected O, but got Unknown //IL_0161: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Expected O, but got Unknown //IL_0193: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_01a1: Expected O, but got Unknown //IL_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: Expected O, but got Unknown //IL_01d3: Unknown result type (might be due to invalid IL or missing references) //IL_01d8: Unknown result type (might be due to invalid IL or missing references) //IL_01e1: Expected O, but got Unknown //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_01eb: Expected O, but got Unknown //IL_020f: Unknown result type (might be due to invalid IL or missing references) //IL_0214: Unknown result type (might be due to invalid IL or missing references) //IL_021d: Expected O, but got Unknown //IL_021d: Unknown result type (might be due to invalid IL or missing references) //IL_0227: Expected O, but got Unknown //IL_024b: Unknown result type (might be due to invalid IL or missing references) //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0259: Expected O, but got Unknown //IL_0259: Unknown result type (might be due to invalid IL or missing references) //IL_0263: Expected O, but got Unknown //IL_028b: Unknown result type (might be due to invalid IL or missing references) //IL_0290: Unknown result type (might be due to invalid IL or missing references) //IL_0299: Expected O, but got Unknown //IL_0299: Unknown result type (might be due to invalid IL or missing references) //IL_02a3: Expected O, but got Unknown //IL_02cb: Unknown result type (might be due to invalid IL or missing references) //IL_02d0: Unknown result type (might be due to invalid IL or missing references) //IL_02d9: Expected O, but got Unknown //IL_02d9: Unknown result type (might be due to invalid IL or missing references) //IL_02e3: Expected O, but got Unknown //IL_030b: Unknown result type (might be due to invalid IL or missing references) //IL_0310: Unknown result type (might be due to invalid IL or missing references) //IL_0319: Expected O, but got Unknown //IL_0319: Unknown result type (might be due to invalid IL or missing references) //IL_0323: Expected O, but got Unknown //IL_034b: Unknown result type (might be due to invalid IL or missing references) //IL_0350: Unknown result type (might be due to invalid IL or missing references) //IL_0359: Expected O, but got Unknown //IL_0359: Unknown result type (might be due to invalid IL or missing references) //IL_0363: Expected O, but got Unknown //IL_0387: Unknown result type (might be due to invalid IL or missing references) //IL_038c: Unknown result type (might be due to invalid IL or missing references) //IL_0395: Expected O, but got Unknown //IL_0395: Unknown result type (might be due to invalid IL or missing references) //IL_039f: Expected O, but got Unknown //IL_03c3: Unknown result type (might be due to invalid IL or missing references) //IL_03c8: Unknown result type (might be due to invalid IL or missing references) //IL_03d1: Expected O, but got Unknown //IL_03d1: Unknown result type (might be due to invalid IL or missing references) //IL_03db: Expected O, but got Unknown //IL_0403: Unknown result type (might be due to invalid IL or missing references) //IL_0408: Unknown result type (might be due to invalid IL or missing references) //IL_0411: Expected O, but got Unknown //IL_0411: Unknown result type (might be due to invalid IL or missing references) //IL_041b: Expected O, but got Unknown //IL_0443: Unknown result type (might be due to invalid IL or missing references) //IL_0448: Unknown result type (might be due to invalid IL or missing references) //IL_0451: Expected O, but got Unknown //IL_0451: Unknown result type (might be due to invalid IL or missing references) //IL_045b: Expected O, but got Unknown //IL_0483: Unknown result type (might be due to invalid IL or missing references) //IL_0488: Unknown result type (might be due to invalid IL or missing references) //IL_0491: Expected O, but got Unknown //IL_0491: Unknown result type (might be due to invalid IL or missing references) //IL_049b: Expected O, but got Unknown //IL_04bf: Unknown result type (might be due to invalid IL or missing references) //IL_04c4: Unknown result type (might be due to invalid IL or missing references) //IL_04cd: Expected O, but got Unknown //IL_04cd: Unknown result type (might be due to invalid IL or missing references) //IL_04d7: Expected O, but got Unknown //IL_04ff: Unknown result type (might be due to invalid IL or missing references) //IL_0504: Unknown result type (might be due to invalid IL or missing references) //IL_050d: Expected O, but got Unknown //IL_050d: Unknown result type (might be due to invalid IL or missing references) //IL_0517: Expected O, but got Unknown SynchronizationManager.OnConfigurationSynchronized += delegate(object obj, ConfigurationSynchronizationEventArgs attr) { if (attr.InitialSynchronization) { ItemService.SetWardFirePlace(); ItemService.ModifyItemsCost(); ItemService.LoxTameable(); ItemService.WolvesTameable(); ItemService.StubNoLife(); ItemService.OnlyAdminPieces(); IsAdmin = AdminList.Value.Contains(steamId); } else { Logger.LogMessage((object)"Config sync event received"); } }; ((BaseUnityPlugin)this).Config.SaveOnConfigSet = true; OnlyAdminPieces = ((BaseUnityPlugin)this).Config.Bind<string>("Server config", "OnlyAdminPieces", "SHGateHouse,SHWallMusteringHall,SHTowerSquareTwoFloorCenter,SHTowerSquareTwoFloorCorner,SHTowerSquareTwoFloorJunction,SHWallOpenTwoFloorCapped,SHWallOpenTwoFloorWithNest,SHWallOpenTwoFloorWithNestCapped,SHWallOpenTwoFloor,SHEnclosedTower,SHBunkhouse,SHWell,SHOuterWallCovered,SHOuterWallOpenCapped,SHOuterWallOpen,SHOuterWallTowerSquareCenter,SHOuterWallTowerTransition,SHOuterWallTowerRound,SHOuterWallGate,SHWatchtower,SHTowerRoundWallEnd,SHOuterWallCoverdCapped,SHWallInnerArch,SHWallInnerPillar,SHWallInnerPlain,SHWallInnerPosh,SHHouseSmall,SHHouseMedium,SHHouseLarge,SHHayBarn,SHOldBarn,SHStorageBarn,SHMainHall", new ConfigDescription("OnlyAdminPieces", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); VipPortalNames = ((BaseUnityPlugin)this).Config.Bind<string>("Server config", "VipPortalNames", "cavalinho,eguinha", new ConfigDescription("VipPortalNames", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); SkillCap = ((BaseUnityPlugin)this).Config.Bind<int>("Server config", "SkillCap", 100, new ConfigDescription("SkillCap", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); AdminList = ((BaseUnityPlugin)this).Config.Bind<string>("Server config", "AdminList", "76561198053330247 76561197961128381 76561198111650012 76561197993642177 76561198993982965", new ConfigDescription("AdminList", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); Vip = ((BaseUnityPlugin)this).Config.Bind<string>("Server config", "Vip", "76561198053330247", new ConfigDescription("VipList", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); StaffMessage = ((BaseUnityPlugin)this).Config.Bind<string>("Server config", "StaffMessage", "", new ConfigDescription("StaffMessage", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); DungeonPrefabs = ((BaseUnityPlugin)this).Config.Bind<string>("Server config", "DungeonPrefabs", "dungeon_forestcrypt_door,dungeon_sunkencrypt_irongate", new ConfigDescription("DungeonPrefabs", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); WolvesAreTameable = ((BaseUnityPlugin)this).Config.Bind<bool>("Server config", "WolvesAreTameable", false, new ConfigDescription("WolvesAreTameable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); LoxTameable = ((BaseUnityPlugin)this).Config.Bind<bool>("Server config", "LoxTameable", false, new ConfigDescription("LoxTameable", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); SafeArea = ((BaseUnityPlugin)this).Config.Bind<int>("Server config", "SafeArea", 1500, new ConfigDescription("SafeArea", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); WardChargeDurationInSec = ((BaseUnityPlugin)this).Config.Bind<int>("Server config", "WardChargeDurationInSec", 86400, new ConfigDescription("WardChargeDurationInSec", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); MarketplaceTeleporterCosts = ((BaseUnityPlugin)this).Config.Bind<string>("Server config", "MarketplaceTeleporterCosts", "agostinho:100,barqueiro:50", new ConfigDescription("Gold cost for Marketplace teleporter NPCs. Format: NPCName:Cost,NPCName:Cost", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); MarketplaceTeleporterCostItem = ((BaseUnityPlugin)this).Config.Bind<string>("Server config", "MarketplaceTeleporterCostItem", "Coins", new ConfigDescription("Item prefab consumed when using Marketplace teleporter NPCs.", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); WardLimit = ((BaseUnityPlugin)this).Config.Bind<int>("Server config", "WardLimit", 3, new ConfigDescription("WardLimit", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); WardLimitVip = ((BaseUnityPlugin)this).Config.Bind<int>("Server config", "WardLimitVip", 5, new ConfigDescription("WardLimitVip", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); WardRadius = ((BaseUnityPlugin)this).Config.Bind<int>("Server config", "WardRadius", 150, new ConfigDescription("WardRadius", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); BoatWindSpeedmultiplier = ((BaseUnityPlugin)this).Config.Bind<float>("Server config", "boatWindSpeedmultiplier", 1f, new ConfigDescription("boatWindSpeedmultiplier", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); SkillMultiplier = ((BaseUnityPlugin)this).Config.Bind<float>("Server config", "SkillMultiplier", 0.5f, new ConfigDescription("SkillMultiplier", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); ResetWorldDay = ((BaseUnityPlugin)this).Config.Bind<bool>("Server config", "ResetWorldDay", false, new ConfigDescription("ResetWorldDay", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); PortalMaterials = ((BaseUnityPlugin)this).Config.Bind<string>("Portal Mats", "PortalMaterials", "PortalToken:1,FineWood:100,GreydwarfEye:30,SurtlingCore:10", new ConfigDescription("Dynamic materials for the portal. Format: PrefabName:Amount,PrefabName:Amount", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); _harmony.PatchAll(); Deadheim.MarketplaceTeleporterCosts.StartPatchRetry((MonoBehaviour)(object)this, _harmony); ClonedItems.LoadAssets(); } } [HarmonyPatch] internal class Portal { [HarmonyPatch(typeof(Player), "PlacePiece")] public static class NoBuild_Patch { public static void UpdatePortalMaterials() { //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Unknown result type (might be due to invalid IL or missing references) //IL_00f6: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Unknown result type (might be due to invalid IL or missing references) //IL_010a: Expected O, but got Unknown GameObject prefab = PrefabManager.Instance.GetPrefab("portal_wood"); if ((Object)(object)prefab == (Object)null) { return; } Piece component = prefab.GetComponent<Piece>(); List<Requirement> list = new List<Requirement>(); string[] array = Plugin.PortalMaterials.Value.Split(new char[1] { ',' }); string[] array2 = array; foreach (string text in array2) { string[] array3 = text.Split(new char[1] { ':' }); if (array3.Length != 2) { continue; } string text2 = array3[0].Trim(); if (!int.TryParse(array3[1].Trim(), out var result) || result <= 0) { continue; } GameObject prefab2 = PrefabManager.Instance.GetPrefab(text2); if ((Object)(object)prefab2 != (Object)null) { ItemDrop component2 = prefab2.GetComponent<ItemDrop>(); if ((Object)(object)component2 != (Object)null) { list.Add(new Requirement { m_resItem = component2, m_amount = result, m_recover = true }); } else { Logger.LogWarning((object)("[Deadheim] O prefab '" + text2 + "' não é um item válido.")); } } else { Logger.LogWarning((object)("[Deadheim] Prefab '" + text2 + "' não encontrado no jogo.")); } } if (list.Count > 0) { component.m_resources = list.ToArray(); Logger.LogInfo((object)"[Deadheim] Materiais do portal atualizados dinamicamente!"); } else { Logger.LogWarning((object)"[Deadheim] Nenhum material válido na config. Mantendo os materiais originais."); } } private static int GetPortalCount() { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected O, but got Unknown if (SynchronizationManager.Instance.PlayerIsAdmin) { return 0; } ZPackage val = new ZPackage(); val.Write(Player.m_localPlayer.GetPlayerID()); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "DeadheimPortalAndTotemCountServer", new object[1] { val }); return Plugin.PlayerPortalCount; } } } [HarmonyPatch] public class Retreat { [HarmonyPatch(typeof(Terminal), "InitTerminal")] public class AddChatCommands { [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 args) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) if (!Plugin.Vip.Value.Contains(Plugin.steamId)) { args.Context.AddString("Only Aesir can use this command"); return; } if (!((Humanoid)Player.m_localPlayer).IsTeleportable()) { args.Context.AddString("Can't teleport"); return; } Vector3 hearthStonePosition = GetHearthStonePosition(); if (hearthStonePosition == Vector3.zero) { args.Context.AddString("You need to set hearthstone spawn point"); } else { ((Character)Player.m_localPlayer).TeleportTo(hearthStonePosition, ((Component)Player.m_localPlayer).transform.rotation, true); } } } private static void Postfix() { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Expected O, but got Unknown object obj = <>c.<>9__0_0; if (obj == null) { ConsoleEvent val = delegate(ConsoleEventArgs args) { //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) if (!Plugin.Vip.Value.Contains(Plugin.steamId)) { args.Context.AddString("Only Aesir can use this command"); } else if (!((Humanoid)Player.m_localPlayer).IsTeleportable()) { args.Context.AddString("Can't teleport"); } else { Vector3 hearthStonePosition = GetHearthStonePosition(); if (hearthStonePosition == Vector3.zero) { args.Context.AddString("You need to set hearthstone spawn point"); } else { ((Character)Player.m_localPlayer).TeleportTo(hearthStonePosition, ((Component)Player.m_localPlayer).transform.rotation, true); } } }; <>c.<>9__0_0 = val; obj = (object)val; } new ConsoleCommand("retreat", "go back home", (ConsoleEvent)obj, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); } } [HarmonyPatch(typeof(Chat), "Awake")] public class AddGroupChat { private static void Postfix(Chat __instance) { int index = Math.Max(0, ((Terminal)__instance).m_chatBuffer.Count - 5); ((Terminal)__instance).m_chatBuffer.Insert(index, "/retreat go back home"); ((Terminal)__instance).UpdateChat(); } } [HarmonyPatch(typeof(Bed), "GetHoverText")] private static class Bed_GetHoverText_Patch { private static void Postfix(Bed __instance, ref string __result, ZNetView ___m_nview) { if ((__instance.IsMine() && ___m_nview.GetZDO().GetLong("owner", 0L) != 0L) || Traverse.Create((object)__instance).Method("IsCurrent", Array.Empty<object>()).GetValue<bool>()) { __result += Localization.instance.Localize("\n[<color=yellow><b>P</b></color>] Definir ponto de retreat"); } } } public static Vector3 GetHearthStonePosition() { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)Player.m_localPlayer == (Object)null || !Player.m_localPlayer.m_customData.ContainsKey("positionX")) { return Vector3.zero; } Vector3 result = default(Vector3); result.x = float.Parse(Player.m_localPlayer.m_customData["positionX"]); result.y = float.Parse(Player.m_localPlayer.m_customData["positionY"]); result.z = float.Parse(Player.m_localPlayer.m_customData["positionZ"]); return result; } public static void SetHearthStonePosition() { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)Player.m_localPlayer == (Object)null)) { Vector3 position = ((Component)Player.m_localPlayer).transform.position; Player.m_localPlayer.m_customData["positionX"] = position.x.ToString(); Player.m_localPlayer.m_customData["positionY"] = position.y.ToString(); Player.m_localPlayer.m_customData["positionZ"] = position.z.ToString(); } } } [HarmonyPatch] internal class RPC { [HarmonyPatch(typeof(Player), "OnSpawned")] public static class OnSpawned { public static void Postfix() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown ZPackage val = new ZPackage(); val.Write(Player.m_localPlayer.GetPlayerID()); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "DeadheimPortalAndTotemCountServer", new object[1] { val }); } } [HarmonyPatch(typeof(Game), "Start")] public static class GameStart { public static void Postfix() { if (ZRoutedRpc.instance != null) { ZRoutedRpc.instance.Register<ZPackage>("DeadheimPortalAndTotemCountServer", (Action<long, ZPackage>)RPC_PortalAndTotemCountServer); ZRoutedRpc.instance.Register<ZPackage>("DeadheimPortalAndTotemCountClient", (Action<long, ZPackage>)RPC_PortalAndTotemCountClient); } } } public static void RPC_PortalAndTotemCountServer(long sender, ZPackage pkg) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected O, but got Unknown if (ZNet.instance.IsServer()) { long creatorId = pkg.ReadLong(); string creatorWardAndPortalCount = Util.GetCreatorWardAndPortalCount(creatorId); ZPackage val = new ZPackage(); val.Write(creatorWardAndPortalCount); ZRoutedRpc.instance.InvokeRoutedRPC(sender, "DeadheimPortalAndTotemCountClient", new object[1] { val }); } } public static void RPC_PortalAndTotemCountClient(long sender, ZPackage pkg) { string text = pkg.ReadString(); Plugin.PlayerPortalCount = Convert.ToInt32(text.Split(new char[1] { ',' })[0]); Plugin.PlayerWardCount = Convert.ToInt32(text.Split(new char[1] { ',' })[1]); } } [HarmonyPatch] internal class Smelters { [HarmonyPatch(typeof(Smelter), "Awake")] public static class Smelter_Awake_Patch { private static void Prefix(ref Smelter __instance) { string value = "$piece_charcoalkiln"; string value2 = "$piece_smelter"; string value3 = "$piece_blastfurnace"; if (__instance.m_name.Equals(value)) { __instance.m_maxOre = 100; __instance.m_secPerProduct = 20f; } else if (__instance.m_name.Equals(value2)) { __instance.m_maxOre = 50; __instance.m_maxFuel = 100; __instance.m_secPerProduct = 20f; __instance.m_fuelPerProduct = 2; } else if (__instance.m_name.Equals(value3)) { __instance.m_maxOre = 50; __instance.m_maxFuel = 100; __instance.m_secPerProduct = 20f; __instance.m_fuelPerProduct = 2; } } } } public static class Util { public static int CREATORHASH = StringExtensionMethods.GetStableHashCode("creator"); public static string GetCreatorWardAndPortalCount(long creatorId) { int creatorPrefabCount = GetCreatorPrefabCount(StringExtensionMethods.GetStableHashCode("portal_wood"), creatorId); int creatorPrefabCount2 = GetCreatorPrefabCount(StringExtensionMethods.GetStableHashCode("guard_stone"), creatorId); return $"{creatorPrefabCount},{creatorPrefabCount2}"; } private static int GetCreatorPrefabCount(int prefabHash, long creatorId) { int num = 0; List<ZDO>[] objectsBySector = ZDOMan.instance.m_objectsBySector; foreach (List<ZDO> list in objectsBySector) { if (list == null) { continue; } for (int j = 0; j < list.Count; j++) { ZDO val = list[j]; if (val.GetPrefab() == prefabHash) { long @long = val.GetLong(CREATORHASH, 0L); if (@long != 0 && @long == creatorId) { num++; } } } } return num; } private static byte[] ReadEmbeddedFileBytes(string name) { using MemoryStream memoryStream = new MemoryStream(); Assembly.GetExecutingAssembly().GetManifestResourceStream(Assembly.GetExecutingAssembly().GetName().Name + "." + name).CopyTo(memoryStream); return memoryStream.ToArray(); } private static Texture2D LoadTexture(string name) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Expected O, but got Unknown Texture2D val = new Texture2D(2, 2); byte[] array = ReadEmbeddedFileBytes("assets." + name); if (array == null || array.Length == 0) { return val; } MethodInfo method = typeof(ImageConversion).GetMethod("LoadImage", new Type[2] { typeof(Texture2D), typeof(byte[]) }); if (method != null) { method.Invoke(null, new object[2] { val, array }); } else { Debug.LogError((object)"[LoadTexture] Could not find LoadImage method via Reflection."); } return val; } public static Sprite LoadSprite(string name, int width, int height) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) return Sprite.Create(LoadTexture(name), new Rect(0f, 0f, (float)width, (float)height), Vector2.zero); } } } namespace Deadheim.world { internal class World { [HarmonyPatch(typeof(ZNet), "SaveWorldThread")] internal class SaveWorldThread { private static void Prefix(ref ZNet __instance) { if (Plugin.ResetWorldDay.Value) { __instance.m_netTime = 2040.0; } } } } } namespace Deadheim.EnhancedWards { [HarmonyPatch] public class Ward { [HarmonyPatch(typeof(WearNTear), "RPC_Damage")] public static class RPC_Damage { [HarmonyPriority(800)] private static bool Prefix(WearNTear __instance, ref HitData hit, ZNetView ___m_nview) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) try { if (___m_nview == null) { return false; } if (!CheckInPrivateArea(((Component)__instance).transform.position)) { return true; } if (((Object)((Component)__instance).gameObject).name.Contains("guard_stone")) { return false; } if (((Object)((Component)__instance).gameObject).name.Contains("AdminWard")) { return false; } if (Vector3.Distance(new Vector3(0f, 0f), ((Component)Player.m_localPlayer).transform.position) <= (float)Plugin.SafeArea.Value) { return false; } return true; } catch (Exception ex) { Debug.LogError((object)(ex.Message + " - " + ex.StackTrace)); return false; } } } [HarmonyPatch(typeof(Door), "CanInteract")] public static class DoorCanInteract { private static void Postfix(Door __instance, ref bool __result) { string name = ((Object)((Component)__instance).gameObject).name; name = name.Replace("(Clone)", ""); if (Plugin.DungeonPrefabs.Value.Split(new char[1] { ',' }).Contains(((Object)((Component)__instance).gameObject).name.Replace("(Clone)", ""))) { __result = true; } } } [HarmonyPatch(typeof(PrivateArea), "IsEnabled")] public static class PrivateAreaCheckAccess { private static void Postfix(PrivateArea __instance, ref bool __result) { //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_0075: Expected O, but got Unknown //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Expected O, but got Unknown Player localPlayer = Player.m_localPlayer; if (!Object.op_Implicit((Object)(object)localPlayer) || !Object.op_Implicit((Object)(object)localPlayer.m_hovering)) { return; } Interactable componentInParent = localPlayer.m_hovering.GetComponentInParent<Interactable>(); if (componentInParent == null) { return; } Door val = null; Container val2 = null; if (((object)componentInParent).GetType().Name == "Door") { val = (Door)componentInParent; } if (((object)componentInParent).GetType().Name == "Container") { val2 = (Container)componentInParent; } if (val == null && val2 == null) { return; } string text = ""; if (val != null) { text = ((Object)((Component)val).gameObject).name; } if (Object.op_Implicit((Object)(object)val2)) { text = ((Object)((Component)val2).gameObject).name; } if (!(text == "")) { text = text.Replace("(Clone)", ""); if (Plugin.DungeonPrefabs.Value.Split(new char[1] { ',' }).Contains(text)) { __result = false; } } } } [HarmonyPatch(typeof(Fireplace), "UpdateState")] public static class FireplaceUpdateState { private static bool Prefix(Fireplace __instance) { if (!((Object)((Component)__instance).gameObject).name.Contains("guard_stone")) { return true; } return false; } } [HarmonyPatch(typeof(Fireplace), "Awake")] public static class FireplaceAwake { private static bool Prefix(Fireplace __instance) { try { if (!((Object)((Component)__instance).gameObject).name.Contains("guard_stone")) { return true; } __instance.m_nview = ((Component)__instance).gameObject.GetComponent<ZNetView>(); __instance.m_piece = ((Component)__instance).gameObject.GetComponent<Piece>(); if (__instance.m_nview.GetZDO() == null) { return false; } if (__instance.m_nview.IsOwner() && (double)__instance.m_nview.GetZDO().GetFloat("fuel", -1f) == -1.0) { __instance.m_nview.GetZDO().Set("fuel", __instance.m_startFuel); } __instance.m_nview.Register("AddFuel", (Action<long>)__instance.RPC_AddFuel); ((MonoBehaviour)__instance).InvokeRepeating("UpdateFireplace", 0f, 10f); return false; } catch { return false; } } } [HarmonyPatch(typeof(Fireplace), "UpdateFireplace")] public static class UpdateFireplace { private static bool Prefix(Fireplace __instance) { if (!((Object)((Component)__instance).gameObject).name.Contains("guard_stone")) { return true; } if (!__instance.m_nview.IsValid()) { return false; } Piece component = ((Component)__instance).gameObject.GetComponent<Piece>(); if (__instance.m_nview.IsOwner()) { if (__instance.m_fuelItem == null) { __instance.m_fuelItem = PrefabManager.Instance.GetPrefab("GreydwarfEye").GetComponent<ItemDrop>(); } __instance.m_secPerFuel = Plugin.WardChargeDurationInSec.Value; __instance.m_maxFuel = 10f; PrivateArea component2 = ((Component)__instance).gameObject.GetComponent<PrivateArea>(); float @float = __instance.m_nview.GetZDO().GetFloat("fuel", 0f); double timeSinceLastUpdate = __instance.GetTimeSinceLastUpdate(); float num = (float)timeSinceLastUpdate / __instance.m_secPerFuel; float num2 = @float - num; if ((double)num2 <= 0.0) { num2 = 0f; if (component2.IsEnabled()) { component2.SetEnabled(false); } } if (num2 > 10f) { num2 = 10f; } __instance.m_nview.GetZDO().Set("fuel", num2); } return false; } } [HarmonyPatch(typeof(Player), "PlacePiece")] public static class NoBuild_Patch { [HarmonyPriority(800)] private static bool Prefix(Piece piece, Player __instance) { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_01d0: Unknown result type (might be due to invalid IL or missing references) //IL_01e2: Unknown result type (might be due to invalid IL or missing references) //IL_01e8: Unknown result type (might be due to invalid IL or missing references) //IL_01f0: Unknown result type (might be due to invalid IL or missing references) //IL_01f7: Expected O, but got Unknown //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) if (SynchronizationManager.Instance.PlayerIsAdmin) { return true; } bool flag = ((Object)((Component)piece).gameObject).name.Contains("guard_stone"); bool flag2 = false; Vector3 position = __instance.m_placementGhost.transform.position; if (flag) { List<ZDO> zDOList = GetZDOList(StringExtensionMethods.GetStableHashCode(((Object)((Component)piece).gameObject).name)); foreach (ZDO item in zDOList) { if (Vector3.Distance(new Vector3(position.x, 0f, position.z), new Vector3(item.m_position.x, 0f, item.m_position.z)) <= ((Component)piece).GetComponent<PrivateArea>().m_radius * 3f && !IsBuilderPermitted(item, __instance)) { ((Character)Player.m_localPlayer).Message((MessageType)2, "Não é possível construir wards próximo da área de outros wards.", 0, (Sprite)null); return false; } } } if (!flag) { return true; } int wardCount = GetWardCount(); if (Plugin.Vip.Value.Contains(Plugin.steamId)) { if (wardCount >= Plugin.WardLimitVip.Value) { ((Character)Player.m_localPlayer).Message((MessageType)2, "Você não pode mais colocar wards.", 0, (Sprite)null); return false; } } else if (wardCount >= Plugin.WardLimit.Value) { ((Character)Player.m_localPlayer).Message((MessageType)2, "Você não pode mais colocar wards.", 0, (Sprite)null); return false; } Minimap.instance.AddPin(((Component)__instance).transform.position, (PinType)9, "WARD", true, false, 0L, default(PlatformUserID)); ZPackage val = new ZPackage(); val.Write(Player.m_localPlayer.GetPlayerID()); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "DeadheimPortalAndTotemCountServer", new object[1] { val }); return true; } } [HarmonyPatch(typeof(Player), "Update")] public static class Update { private static void Postfix(ref Player __instance) { //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_016f: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)__instance.m_hovering)) { return; } Interactable componentInParent = __instance.m_hovering.GetComponentInParent<Interactable>(); if (componentInParent == null) { return; } PrivateArea val = (PrivateArea)(object)((componentInParent is PrivateArea) ? componentInParent : null); if (val == null) { return; } Fireplace componentInParent2 = ((Component)val).GetComponentInParent<Fireplace>(); StringBuilder stringBuilder = new StringBuilder(256); KeyCode val2 = (KeyCode)107; KeyCode val3 = (KeyCode)121; if (val.IsPermitted(__instance.GetPlayerID()) || val.m_piece.m_creator == __instance.GetPlayerID()) { if (Object.op_Implicit((Object)(object)componentInParent2)) { stringBuilder.Append("\n[<color=yellow><b>" + ((object)(KeyCode)(ref val3)).ToString() + "</b></color>] Fuel: " + Math.Round(componentInParent2.m_nview.GetZDO().GetFloat("fuel", 0f), 2) + "/" + componentInParent2.m_maxFuel); } stringBuilder.Append("\n[<color=yellow><b>" + ((object)(KeyCode)(ref val2)).ToString() + "</b></color>]"); val.m_name = stringBuilder.ToString(); val.AddUserList(stringBuilder); if (Input.GetKeyDown(val2)) { Interact(__instance, __instance.m_hovering, val); } if (Input.GetKeyDown(val3)) { FuelWard(__instance, componentInParent2); } } } public static void FuelWard(Player player, Fireplace fireplace) { if (!((double)fireplace.m_holdRepeatInterval <= 0.0) && !(Time.time - fireplace.m_lastUseTime < fireplace.m_holdRepeatInterval)) { if (!fireplace.m_nview.HasOwner()) { fireplace.m_nview.ClaimOwnership(); } if (fireplace.m_fuelItem == null) { fireplace.m_fuelItem = PrefabManager.Instance.GetPrefab("GreydwarfEye").GetComponent<ItemDrop>(); } fireplace.Interact((Humanoid)(object)player, false, false); } } public static void Interact(Player player, GameObject go, PrivateArea privateArea) { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: 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_006d: Unknown result type (might be due to invalid IL or missing references) player.m_lastHoverInteractTime = Time.time; privateArea.m_nview.InvokeRPC("ToggleEnabled", new object[1] { privateArea.m_piece.GetCreator() }); Vector3 val = go.transform.position - ((Component)player).transform.position; val.y = 0f; ((Vector3)(ref val)).Normalize(); ((Component)player).transform.rotation = Quaternion.LookRotation(val); ((Character)player).m_zanim.SetTrigger("interact"); } } public static bool CheckInPrivateArea(Vector3 point, bool flash = false) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) foreach (PrivateArea allArea in PrivateArea.m_allAreas) { if (allArea.IsEnabled() && allArea.IsInside(point, 0f)) { if (flash) { allArea.FlashShield(false); } return true; } } return false; } private static int GetWardCount() { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected O, but got Unknown if (SynchronizationManager.Instance.PlayerIsAdmin) { return 0; } ZPackage val = new ZPackage(); val.Write(Player.m_localPlayer.GetPlayerID()); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "DeadheimPortalAndTotemCountServer", new object[1] { val }); return Plugin.PlayerWardCount; } private static List<ZDO> GetZDOList(int prefabHash) { List<ZDO> list = new List<ZDO>(); List<ZDO>[] objectsBySector = ZDOMan.instance.m_objectsBySector; foreach (List<ZDO> list2 in objectsBySector) { if (list2 == null) { continue; } for (int j = 0; j < list2.Count; j++) { ZDO val = list2[j]; if (val.GetPrefab() == prefabHash) { list.Add(val); } } } return list; } private static bool IsBuilderPermitted(ZDO zdo, Player player) { List<KeyValuePair<long, string>> list = new List<KeyValuePair<long, string>>(); long @long = zdo.GetLong(Util.CREATORHASH, 0L); if (@long == player.GetPlayerID()) { return true; } int @int = zdo.GetInt("permitted", 0); for (int i = 0; i < @int; i++) { long long2 = zdo.GetLong("pu_id" + i, 0L); string @string = zdo.GetString("pu_name" + i, ""); if (long2 != 0) { list.Add(new KeyValuePair<long, string>(long2, @string)); } } foreach (KeyValuePair<long, string> item in list) { if (item.Key == player.GetPlayerID()) { return true; } } return false; } } } namespace Deadheim.Craft { public class CraftPatches { [HarmonyPatch(typeof(InventoryGui), "UpdateRecipe")] private class FasterCrafting { private static void Prefix(ref InventoryGui __instance) { __instance.m_craftDuration = 0.25f; } } } }
DeadLogger.dll
Decompiled 2 weeks agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using ServerSync; using TMPro; using UnityEngine; [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: CompilationRelaxations(8)] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] namespace DeadLogger { internal class Patches { [HarmonyPatch(typeof(Player), "PlacePiece")] public static class PlacePiece { private static void Postfix(Player __instance, Piece piece, bool __result) { if (__result) { Util.PrepareLog("Construiu: ", __instance, ((Component)piece).gameObject); } } } [HarmonyPatch(typeof(Player), "RemovePiece")] public static class RemovePiece { public static Piece pieceRemoved; public static string portalTag = ""; private static void Postfix(Player __instance, bool __result) { if (!__result) { return; } string textToAppend = "Destruiu: "; try { TeleportWorld component = ((Component)pieceRemoved).gameObject.GetComponent<TeleportWorld>(); if (Object.op_Implicit((Object)(object)component)) { textToAppend = "Destruiu Portal " + portalTag + " : "; } PrivateArea component2 = ((Component)pieceRemoved).gameObject.GetComponent<PrivateArea>(); Fireplace component3 = ((Component)pieceRemoved).gameObject.GetComponent<Fireplace>(); if (Object.op_Implicit((Object)(object)component3) && Object.op_Implicit((Object)(object)component2)) { textToAppend = "Destruiu Totem Combustivel " + component3.m_nview.GetZDO().GetFloat("fuel", -1f) + " : "; } } catch { } Util.PrepareLog(textToAppend, __instance, ((Component)pieceRemoved).gameObject); } private static void Finalizer() { pieceRemoved = null; portalTag = ""; } } [HarmonyPatch(typeof(Player), "CheckCanRemovePiece")] public static class PieceRemoved { private static void Postfix(Piece piece) { RemovePiece.pieceRemoved = piece; TeleportWorld component = ((Component)piece).gameObject.GetComponent<TeleportWorld>(); if (Object.op_Implicit((Object)(object)component)) { RemovePiece.portalTag = component.GetText() + " : "; } } } [HarmonyPatch(typeof(WearNTear), "RPC_Damage")] public static class RPC_Damage { private static void Postfix(WearNTear __instance, ref HitData hit, ZNetView ___m_nview) { //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_0104: Expected O, but got Unknown if (___m_nview != null && Object.op_Implicit((Object)(object)hit.GetAttacker()) && hit.GetAttacker().IsPlayer()) { float totalDamage = hit.GetTotalDamage(); string textToAppend = "Destruiu Hit: "; TeleportWorld component = ((Component)__instance).gameObject.GetComponent<TeleportWorld>(); if (Object.op_Implicit((Object)(object)component)) { textToAppend = "Destruiu Hit Portal " + component.GetText() + " : "; } PrivateArea component2 = ((Component)__instance).gameObject.GetComponent<PrivateArea>(); Fireplace component3 = ((Component)__instance).gameObject.GetComponent<Fireplace>(); if (Object.op_Implicit((Object)(object)component3) && Object.op_Implicit((Object)(object)component2)) { textToAppend = "Destruiu Totem Combustivel " + component3.m_nview.GetZDO().GetFloat("fuel", -1f) + " : "; } if (__instance.m_health <= totalDamage) { Util.PrepareLog(textToAppend, (Player)hit.GetAttacker(), ((Component)__instance).gameObject); } } } } [HarmonyPatch(typeof(Door), "Interact")] public static class DoorCanInteract { private static void Postfix(Door __instance, ref bool __result, Humanoid character) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Expected O, but got Unknown if (__result && ((Character)character).IsPlayer()) { Util.PrepareLog("Interagiu Porta: ", (Player)character, ((Component)__instance).gameObject); } } } [HarmonyPatch(typeof(Container), "Interact")] public static class ContainerInteract { private static void Postfix(Container __instance, ref bool __result, Humanoid character) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_0031: Expected O, but got Unknown if (__result && ((Character)character).IsPlayer()) { Util.PrepareLog("Interagiu Container: ", (Player)character, ((Component)__instance).gameObject); } } } [HarmonyPatch(typeof(PrivateArea), "Interact")] public static class PrivateAreaInteract { private static void Postfix(PrivateArea __instance, ref bool __result, Humanoid human) { //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Expected O, but got Unknown if (__result && ((Character)human).IsPlayer()) { string textToAppend = "Interagiu Totem: "; PrivateArea component = ((Component)__instance).gameObject.GetComponent<PrivateArea>(); Fireplace component2 = ((Component)__instance).gameObject.GetComponent<Fireplace>(); if (Object.op_Implicit((Object)(object)component2) && Object.op_Implicit((Object)(object)component)) { textToAppend = "Interagiu Totem Combustivel " + component2.m_nview.GetZDO().GetFloat("fuel", -1f) + " : "; } Util.PrepareLog(textToAppend, (Player)human, ((Component)__instance).gameObject); } } } [HarmonyPatch(typeof(TeleportWorld), "Interact")] public static class TeleportInteract { private static void Postfix(TeleportWorld __instance, ref bool __result, Humanoid human) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown if (__result && ((Character)human).IsPlayer()) { Util.PrepareLog("Interagiu Portal " + __instance.GetText() + " : ", (Player)human, ((Component)__instance).gameObject); } } } [HarmonyPatch(typeof(TeleportWorld), "Teleport")] public static class TeleportTeleport { private static void Postfix(TeleportWorld __instance, Player player) { if (__instance.TargetFound() && !ZoneSystem.instance.GetGlobalKey("noportals") && ((Humanoid)player).IsTeleportable() && ((Character)player).IsPlayer()) { PlayerTeleportTo.PortalName = __instance.GetText(); } } } [HarmonyPatch(typeof(Player), "TeleportTo")] public static class PlayerTeleportTo { public static string PortalName = ""; private static void Postfix(Player __instance, ref bool __result, Vector3 pos) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) if (__result) { Util.PrepareLog("Teleportou com portal" + PortalName + " para x " + (int)pos.x + "," + (int)pos.z + ": ", __instance, ((Component)__instance).gameObject); } } private static void Finalizer() { PortalName = ""; } } } [BepInPlugin("Detalhes.DeadLogger", "Detalhes.DeadLogger", "1.0.0")] public class DeadLogger : BaseUnityPlugin { public const string PluginGUID = "Detalhes.DeadLogger"; public const string Name = "DeadLogger"; public const string Version = "1.0.0"; private ConfigSync configSync = new ConfigSync("Detalhes.DeadLogger") { DisplayName = "DeadLogger", CurrentVersion = "1.0.0", MinimumRequiredVersion = "1.0.0" }; private Harmony _harmony = new Harmony("Detalhes.DeadLogger"); public static ConfigEntry<string> PrefabsToLog; public static GameObject Menu; public static string FileDirectory = Paths.ConfigPath + "/DeadLogger/"; public void Awake() { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected O, but got Unknown PrefabsToLog = config("Server config", "PrefabsToLog", "", new ConfigDescription("PrefabsToLog", (AcceptableValueBase)null, Array.Empty<object>())); _harmony.PatchAll(); } 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); } } [HarmonyPatch] internal class RPC { [HarmonyPatch(typeof(Game), "Start")] public static class GameStart { public static void Postfix() { if (ZRoutedRpc.instance != null) { ZRoutedRpc.instance.Register<ZPackage>("DeadLogger_SaveLog", (Action<long, ZPackage>)RPC_DeadLogger_SaveLog); } } } public static void RPC_DeadLogger_SaveLog(long sender, ZPackage pkg) { if (ZNet.instance.IsServer()) { string[] array = pkg.ReadString().Split(new char[1] { '|' }); string text = array[0]; string text2 = array[1]; string text3 = array[2]; string path = DeadLogger.FileDirectory + "generalLog.txt"; string text4 = text + "_" + text2 + ".txt"; string path2 = DeadLogger.FileDirectory + text4; if (!Directory.Exists(DeadLogger.FileDirectory)) { Directory.CreateDirectory(DeadLogger.FileDirectory); } DateTime dateTime = DateTime.UtcNow.AddHours(-3.0); string text5 = dateTime.Hour + ":" + dateTime.Minute + " " + dateTime.Day + "/" + dateTime.Month + "/" + dateTime.Year; text3 = text3 + " " + text5; File.AppendAllText(path2, text3 + Environment.NewLine); File.AppendAllText(path, text + " " + text2 + " " + text3 + Environment.NewLine); } } } public class Util { public static void SendLog(string description, Vector3 pos, string nick, long peerId, long creatorId) { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Expected O, but got Unknown description = description + " Posição: " + (int)pos.x + "," + (int)pos.z; description = description + " CreatorId: " + creatorId; ZPackage val = new ZPackage(); string text = nick + "|"; text = text + peerId + "|"; text = text + description + "|"; val.Write(text); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "DeadLogger_SaveLog", new object[1] { val }); } public static void PrepareLog(string textToAppend, Player __instance, GameObject gameObject) { //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_00e4: Unknown result type (might be due to invalid IL or missing references) if (!(DeadLogger.PrefabsToLog.Value != "") || DeadLogger.PrefabsToLog.Value.Contains(((Object)gameObject).name)) { List<PlayerInfo> list = new List<PlayerInfo>(); ZNet.instance.GetOtherPublicPlayers(list); long peerId = ((Character)__instance).m_nview.m_zdo.GetOwner(); PlayerInfo val = ((IEnumerable<PlayerInfo>)list).FirstOrDefault((Func<PlayerInfo, bool>)((PlayerInfo x) => ((ZDOID)(ref x.m_characterID)).UserID == peerId)); string nick = val.m_name; if (__instance.GetPlayerID() == Player.m_localPlayer.GetPlayerID()) { nick = Game.instance.GetPlayerProfile().m_playerName; } long creatorId = 0L; Piece component = gameObject.GetComponent<Piece>(); if (Object.op_Implicit((Object)(object)component)) { creatorId = component.m_creator; } SendLog(textToAppend + ((Object)gameObject).name, ((Component)__instance).transform.position, nick, __instance.GetPlayerID(), creatorId); } } } } namespace Microsoft.CodeAnalysis { [Microsoft.CodeAnalysis.Embedded] [CompilerGenerated] 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; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [Microsoft.CodeAnalysis.Embedded] [CompilerGenerated] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] [Microsoft.CodeAnalysis.Embedded] [CompilerGenerated] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ServerSync { [PublicAPI] internal abstract class OwnConfigEntryBase { public object? LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [PublicAPI] internal 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; } } } internal 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; }; } } [PublicAPI] internal 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), int priority = 0) : base(configSync, identifier, typeof(T), priority) { Value = value; } public void AssignLocalValue(T value) { if (localIsOwner) { Value = value; } else { LocalBaseValue = value; } } } internal class ConfigurationManagerAttributes { [UsedImplicitly] public bool? ReadOnly = false; } [PublicAPI] internal 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> adminPeer = (from p in ZNet.instance.GetPeers() where adminList.Contains(p.m_rpc.GetSocket().GetHostName()) select p).ToList(); List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList(); SendAdmin(nonAdminPeer, isAdmin: false); SendAdmin(adminPeer, 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 = false; 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_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: 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_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 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) { ZRpc rpc2 = rpc; ZNet __instance2 = __instance; Dictionary<Assembly, BufferingSocket> __state2 = __state; ZNetPeer peer; if (__instance2.IsServer()) { object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 }); peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (peer == null) { SendBufferedData(); } else { ((MonoBehaviour)__instance2).StartCoroutine(sendAsync()); } } void SendBufferedData() { if (rpc2.GetSocket() is BufferingSocket bufferingSocket) { AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc2, bufferingSocket.Original); object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance2, new object[1] { rpc2 }); ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null); if (val != null) { AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original); } } BufferingSocket bufferingSocket2 = __state2[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> entries = new List<PackageEntry>(); if (configSync.CurrentVersion != null) { entries.Add(new PackageEntry { section = "Internal", key = "serverversion", type = typeof(string), value = configSync.CurrentVersion }); } MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); entries.Add(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc2.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2] { adminList, rpc2.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false); yield return ((MonoBehaviour)__instance2).StartCoroutine(configSync.sendZPackage(new List<ZNetPeer> { peer }, package)); } SendBufferedData(); } } } private class PackageEntry { public string section = null; public string key = null; public Type type = null; 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 = null; public string received = null; public string field = ""; } public static bool ProcessingServerUpdate; public readonly string Name; public string? DisplayName; public string? CurrentVersion; public string? MinimumRequiredVersion; public bool ModRequired = false; private bool? forceConfigLocking; private bool isSourceOfTruth = true; private static readonly HashSet<ConfigSync> configSyncs; private readonly HashSet<OwnConfigEntryBase> allConfigs = new HashSet<OwnConfigEntryBase>(); private HashSet<CustomSyncedValueBase> allCustomValues = new HashSet<CustomSyncedValueBase>(); private static bool isServer; private static bool lockExempt; private OwnConfigEntryBase? lockedConfig = null; 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_0052; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag.GetValueOrDefault(); } if (!num) { goto IL_0052; } int result = ((!lockExempt) ? 1 : 0); goto IL_0053; IL_0053: return (byte)result != 0; IL_0052: result = 0; goto IL_0053; } set { forceConfigLocking = value; } } public bool IsAdmin => lockExempt || isSourceOfTruth; public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } = false; 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) { ConfigEntry<T> configEntry2 = configEntry; OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry2); SyncedConfigEntry<T> syncedEntry = ownConfigEntryBase as SyncedConfigEntry<T>; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry<T>(configEntry2); AccessTools.DeclaredField(typeof(ConfigDescription), "<Tags>k__BackingField").SetValue(((ConfigEntryBase)configEntry2).Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(((ConfigEntryBase)configEntry2).Description.Tags ?? Array.Empty<object>()).Concat(new SyncedConfigEntry<T>[1] { syncedEntry }).ToArray()); configEntry2.SettingChanged += delegate { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry2); } }; 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) { CustomSyncedValueBase customValue2 = customValue; if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue2.Identifier)) { throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)"); } allCustomValues.Add(customValue2); allCustomValues = new HashSet<CustomSyncedValueBase>(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority)); customValue2.ValueChanged += delegate { if (!ProcessingServerUpdate) { Broadcast(ZRoutedRpc.Everybody, customValue2); } }; } 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_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Expected O, but got Unknown //IL_024e: Unknown result type (might be due to invalid IL or missing references) //IL_0255: Expected O, but got Unknown //IL_01e8: Unknown result type (might be due to invalid IL or missing references) //IL_01ef: 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 SortedDictionary<int, byte[]> 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) { OwnConfigEntryBase config2 = config; ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config2)); if (configSync == null) { return true; } return configSync.IsSourceOfTruth || !config2.SynchronizedConfig || config2.LocalBaseValue == null || (!configSync.IsLocked && (config2 != configSync.lockedConfig || lockExempt)); } 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) { ZNetPeer peer2 = peer; 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 (peer2.m_socket.IsConnected()) { ZPackage fragmentedPackage = new ZPackage(); fragmentedPackage.Write((byte)2); fragmentedPackage.Write(packageIdentifier); fragmentedPackage.Write(fragment); fragmentedPackage.Write(fragments); fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray()); SendPackage(fragmentedPackage); 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) { peer2.m_rpc.Invoke(text, new object[1] { pkg }); } else { rpc.InvokeRoutedRPC(peer2.m_server ? 0 : peer2.m_uid, text, new object[1] { pkg }); } } IEnumerable<bool> waitForQueue() { float timeout = Time.time + 30f; while (peer2.m_socket.GetSendQueueSize() > 20000) { if (Time.time > timeout) { Debug.Log((object)$"Disconnecting {peer2.m_uid} after 30 seconds config sending timeout"); peer2.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 }); ZNet.instance.Disconnect(peer2); 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) { ZPackage package2 = package; if (!Object.op_Implicit((Object)(object)ZNet.instance)) { yield break; } byte[] rawData = package2.GetArray(); if (rawData != null && rawData.LongLength > 10000) { ZPackage compressedPackage = new ZPackage(); compressedPackage.Write((byte)4); MemoryStream output = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal)) { deflateStream.Write(rawData, 0, rawData.Length); } compressedPackage.Write(output.ToArray()); package2 = compressedPackage; } List<IEnumerator<bool>> writers = (from peer in peers where peer.IsReady() select peer into p select distributeConfigToPeers(p, package2)).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) { return type.IsEnum ? Enum.GetUnderlyingType(type) : type; } private static ZPackage ConfigsToPackage(IEnumerable<ConfigEntryBase>? configs = null, IEnumerable<CustomSyncedValueBase>? customValues = null, IEnumerable<PackageEntry>? packageEntries = null, bool partial = true) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: 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)) { 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] internal 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 { return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0"); } set { minimumRequiredVersion = value; } } private static void PatchServerSync() { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: 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."; } return (new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion)) ? ("Mod " + DisplayName + " requires maximum " + ReceivedCurrentVersion + ". Installed is version " + CurrentVersion + ".") : ("Mod " + DisplayName + " requires minimum " + ReceivedMinimumRequiredVersion + ". 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) { return (rpc == null) ? ErrorClient() : ErrorServer(rpc); } private static VersionCheck[] GetFailedClient() { return versionChecks.Where((VersionCheck check) => !check.IsVersionOk()).ToArray(); } private static VersionCheck[] GetFailedServer(ZRpc rpc) { ZRpc rpc2 = rpc; return versionChecks.Where((VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc2)).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); } } } [HarmonyPrefix] [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] 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_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0195: 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 }); } } } [HarmonyPrefix] [HarmonyPatch(typeof(ZNet), "Disconnect")] 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_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: 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>, string>((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 + ")"; } } } } }
DonationShop.dll
Decompiled 2 weeks agousing System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using HarmonyLib; using Jotunn; using Jotunn.Managers; using Jotunn.Utils; using Splatform; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] namespace DonationShop; [BepInPlugin("Detalhes.DonationShop", "Detalhes.DonationShop", "2.0.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] [NetworkCompatibility(/*Could not decode attribute arguments.*/)] public class DonationShop : BaseUnityPlugin { public const string PluginGUID = "Detalhes.DonationShop"; public const string Name = "DonationShop"; public const string Version = "2.0.0"; public static bool IsBuying = false; public static string PlayerName = ""; public static Dictionary<string, GameObject> menuItems = new Dictionary<string, GameObject>(); private Harmony harmony = new Harmony("Detalhes.DonationShop"); public static GameObject Menu; public static ConfigEntry<KeyCode> KeyboardShortcut; public static ConfigEntry<string> ShopItems; public void Awake() { InitConfigs(); SynchronizationManager.OnConfigurationSynchronized += delegate(object obj, ConfigurationSynchronizationEventArgs attr) { if (attr.InitialSynchronization) { Logger.LogMessage((object)"Initial Config sync event received"); } else { Logger.LogMessage((object)"Config sync event received"); } }; harmony.PatchAll(); } private void Update() { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown if (Input.GetKeyDown(KeyboardShortcut.Value)) { Player localPlayer = Player.m_localPlayer; if (Object.op_Implicit((Object)(object)localPlayer) && !((Character)localPlayer).IsDead() && !((Character)localPlayer).InCutscene() && !((Character)localPlayer).IsTeleporting()) { GUI.ToggleMenu(); ZPackage val = new ZPackage(); val.Write(((object)(PlatformUserID)(ref PlayFabManager.m_customId)).ToString()); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "GetGoldServer", new object[1] { val }); } } } public void InitConfigs() { //IL_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Expected O, but got Unknown //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Expected O, but got Unknown //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Expected O, but got Unknown //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Expected O, but got Unknown ((BaseUnityPlugin)this).Config.SaveOnConfigSet = true; KeyboardShortcut = ((BaseUnityPlugin)this).Config.Bind<KeyCode>("Client config", "KeyboardShortcutConfig", (KeyCode)278, new ConfigDescription("Client side KeyboardShortcut", (AcceptableValueBase)null, new object[2] { null, (object)new ConfigurationManagerAttributes { IsAdminOnly = false } })); ShopItems = ((BaseUnityPlugin)this).Config.Bind<string>("Server config", "ShopItems", "prefabs=Blueberriesamount=50;price=150|prefab=Raspberry;amount=50;price=150|prefab=Thistle;amount=50;price=200|prefab=Cloudberry;amount=50;price=100|prefab=Wood;amount=50;price=100|prefab=Stone;amount=50;price=100|prefab=RoundLog;amount=50;price=100|prefab=FineWood;amount=50;price=150|prefab=IronNails;amount=10;price=110|prefab=IronOre;amount=50;price=700|prefab=SilverOre;amount=50;price=1000|prefab=GreydwarfEye;amount=500;price=250|prefab=SurtlingCore;amount=100;price=100|prefab=PortalToken;amount=1;price=750|prefab=ResetToken;amount=1;price=250|prefab=Coins;amount=1000;price=500", new ConfigDescription("ShopItems", (AcceptableValueBase)null, new object[1] { (object)new ConfigurationManagerAttributes { IsAdminOnly = true } })); } } internal class GUI { public static void ToggleMenu() { if (!Object.op_Implicit((Object)(object)DonationShop.Menu) && Object.op_Implicit((Object)(object)Player.m_localPlayer)) { if (GUIManager.Instance == null) { Debug.LogError((object)"GUIManager instance is null"); return; } if (!Object.op_Implicit((Object)(object)GUIManager.CustomGUIFront)) { Debug.LogError((object)"GUIManager CustomGUI is null"); return; } LoadMenu(); } bool active = !DonationShop.Menu.activeSelf; DonationShop.Menu.SetActive(active); } public static void DestroyMenu() { DonationShop.Menu.SetActive(false); } public static void LoadMenu() { //IL_0030: 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_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Expected O, but got Unknown //IL_00d9: Unknown result type (might be due to invalid IL or missing references) //IL_010a: 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_0128: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Unknown result type (might be due to invalid IL or missing references) //IL_01bf: Unknown result type (might be due to invalid IL or missing references) //IL_01ce: Unknown result type (might be due to invalid IL or missing references) //IL_0209: Unknown result type (might be due to invalid IL or missing references) //IL_0218: Unknown result type (might be due to invalid IL or missing references) //IL_0227: Unknown result type (might be due to invalid IL or missing references) //IL_0238: Unknown result type (might be due to invalid IL or missing references) //IL_023e: Unknown result type (might be due to invalid IL or missing references) //IL_027d: Unknown result type (might be due to invalid IL or missing references) //IL_0287: Expected O, but got Unknown if (!((Object)(object)Player.m_localPlayer == (Object)null)) { DonationShop.Menu = GUIManager.Instance.CreateWoodpanel(GUIManager.CustomGUIFront.transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0f, 0f), 600f, 700f, true); DonationShop.Menu.SetActive(false); GameObject val = GUIManager.Instance.CreateScrollView(DonationShop.Menu.transform, false, true, 8f, 50f, GUIManager.Instance.ValheimScrollbarHandleColorBlock, new Color(0.1568628f, 0.1019608f, 0.0627451f, 1f), 500f, 450f); RectTransform val2 = (RectTransform)val.transform; val2.anchoredPosition = new Vector2(0f, 25f); val.SetActive(true); GameObject value = GUIManager.Instance.CreateText("Deadcoins : 0", DonationShop.Menu.transform, new Vector2(0.5f, 1f), new Vector2(0.5f, 1f), new Vector2(-85f, -100f), GUIManager.Instance.AveriaSerifBold, 25, GUIManager.Instance.ValheimOrange, true, Color.black, 350f, 80f, false); DonationShop.menuItems.Add("coinText", value); CreateItems(val); ((Component)val.transform.Find("Scroll View")).GetComponent<ScrollRect>().verticalNormalizedPosition = 1f; GameObject val3 = GUIManager.Instance.CreateButton("Close", DonationShop.Menu.transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0f, -300f), 170f, 45f); val3.SetActive(true); GameObject value2 = GUIManager.Instance.CreateText("", DonationShop.Menu.transform, new Vector2(0.5f, 1f), new Vector2(0.5f, 1f), new Vector2(0f, -600f), GUIManager.Instance.AveriaSerifBold, 14, Color.red, true, Color.black, 500f, 30f, false); DonationShop.menuItems.Add("errorText", value2); Button component = val3.GetComponent<Button>(); ((UnityEvent)component.onClick).AddListener(new UnityAction(DestroyMenu)); } } private static void CreateItems(GameObject scrollView) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_01ae: Unknown result type (might be due to invalid IL or missing references) //IL_01b4: Unknown result type (might be due to invalid IL or missing references) //IL_01fb: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_022f: Unknown result type (might be due to invalid IL or missing references) //IL_0235: Unknown result type (might be due to invalid IL or missing references) //IL_027c: Unknown result type (might be due to invalid IL or missing references) //IL_028b: Unknown result type (might be due to invalid IL or missing references) //IL_029a: Unknown result type (might be due to invalid IL or missing references) //IL_02b0: Unknown result type (might be due to invalid IL or missing references) //IL_02b6: Unknown result type (might be due to invalid IL or missing references) //IL_02e8: Unknown result type (might be due to invalid IL or missing references) //IL_02f7: Unknown result type (might be due to invalid IL or missing references) //IL_0306: Unknown result type (might be due to invalid IL or missing references) //IL_033d: Unknown result type (might be due to invalid IL or missing references) //IL_0347: Expected O, but got Unknown //IL_0385: Unknown result type (might be due to invalid IL or missing references) //IL_0394: Unknown result type (might be due to invalid IL or missing references) //IL_03a3: Unknown result type (might be due to invalid IL or missing references) //IL_03b9: Unknown result type (might be due to invalid IL or missing references) //IL_03bf: Unknown result type (might be due to invalid IL or missing references) GameObject val = GUIManager.Instance.CreateText("\n", scrollView.transform.Find("Scroll View/Viewport/Content"), new Vector2(0.5f, 1f), new Vector2(0.5f, 1f), new Vector2(0f, 0f), GUIManager.Instance.AveriaSerifBold, 10, GUIManager.Instance.ValheimOrange, true, Color.black, 150f, 30f, false); string[] array = DonationShop.ShopItems.Value.Trim(new char[1] { ' ' }).Split(new char[1] { '|' }); foreach (string text in array) { string[] array2 = text.Split(new char[1] { ';' }); string text2 = array2[0].Split(new char[1] { '=' })[1]; string amount = array2[1].Split(new char[1] { '=' })[1]; string price = array2[2].Split(new char[1] { '=' })[1]; GameObject originalPrefab = PrefabManager.Instance.GetPrefab(text2); if (originalPrefab == null) { Debug.LogError((object)("prefab cagado" + text2)); continue; } GameObject val2 = GUIManager.Instance.CreateText(text2.ToString(), scrollView.transform.Find("Scroll View/Viewport/Content"), new Vector2(0.5f, 1f), new Vector2(0.5f, 1f), new Vector2(0f, 0f), GUIManager.Instance.AveriaSerifBold, 14, GUIManager.Instance.ValheimOrange, true, Color.black, 150f, 18f, false); GameObject val3 = GUIManager.Instance.CreateText(amount + "x", scrollView.transform.Find("Scroll View/Viewport/Content"), new Vector2(0.5f, 1f), new Vector2(0.5f, 1f), new Vector2(0f, 0f), GUIManager.Instance.AveriaSerifBold, 14, GUIManager.Instance.ValheimOrange, true, Color.black, 60f, 18f, false); GameObject value = GUIManager.Instance.CreateText(price + " Deadcoins", scrollView.transform.Find("Scroll View/Viewport/Content"), new Vector2(0.5f, 1f), new Vector2(0.5f, 1f), new Vector2(0f, 0f), GUIManager.Instance.AveriaSerifBold, 14, GUIManager.Instance.ValheimOrange, true, Color.black, 250f, 18f, false); GameObject val4 = GUIManager.Instance.CreateButton(" Comprar ", val2.transform, new Vector2(0.5f, -0.8f), new Vector2(0.5f, -0.8f), new Vector2(220f, 0f), 80f, 50f); val4.SetActive(true); Button component = val4.GetComponent<Button>(); ((UnityEvent)component.onClick).AddListener((UnityAction)delegate { Shopper.BuyItem(originalPrefab, Convert.ToInt32(amount), Convert.ToInt32(price)); }); DonationShop.menuItems.Add(text2 + "Text", value); GameObject val5 = GUIManager.Instance.CreateText("", scrollView.transform.Find("Scroll View/Viewport/Content"), new Vector2(0.5f, -5f), new Vector2(0.5f, -5f), new Vector2(0f, -20f), GUIManager.Instance.AveriaSerifBold, 10, GUIManager.Instance.ValheimOrange, true, Color.black, 150f, 10f, false); } } } [HarmonyPatch] public class RPC { public static string Folder = "/DonationShop/"; [HarmonyPatch(typeof(Game), "Start")] [HarmonyPrefix] public static void Prefix() { ZRoutedRpc.instance.Register<ZPackage>("GetGoldServer", (Action<long, ZPackage>)RPC_GetGoldServer); ZRoutedRpc.instance.Register<ZPackage>("GetGoldClient", (Action<long, ZPackage>)RPC_GetGoldClient); ZRoutedRpc.instance.Register<ZPackage>("BuyItemServer", (Action<long, ZPackage>)RPC_BuyItemServer); ZRoutedRpc.instance.Register<ZPackage>("BuyItemClient", (Action<long, ZPackage>)RPC_BuyItemClient); ZRoutedRpc.instance.Register<ZPackage>("DontHaveGold", (Action<long, ZPackage>)RPC_DontHaveGold); } public static void RPC_GetGoldServer(long sender, ZPackage pkg) { //IL_0095: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Expected O, but got Unknown if (!ZNet.instance.IsServer()) { return; } ZNetPeer peer = ZNet.instance.GetPeer(sender); Debug.LogError((object)"RPC_GetGoldServer"); if (peer != null) { string[] array = pkg.ReadString().Split(new char[1] { ',' }); string text = array[0]; string playerName = peer.m_playerName; string path = Paths.ConfigPath + Folder + playerName + "-" + text + ".json"; ZPackage val = new ZPackage(); if (!File.Exists(path)) { Directory.CreateDirectory(Paths.ConfigPath + Folder); File.WriteAllText(path, "0"); val.Write("0"); } val.Write(File.ReadAllText(path)); ZRoutedRpc.instance.InvokeRoutedRPC(sender, "GetGoldClient", new object[1] { val }); } } public static void RPC_GetGoldClient(long sender, ZPackage pkg) { if (DonationShop.menuItems.TryGetValue("coinText", out var value)) { value.GetComponent<Text>().text = "Deadcoins: " + pkg.ReadString(); } } public static void RPC_DontHaveGold(long sender, ZPackage pkg) { if (Object.op_Implicit((Object)(object)Player.m_localPlayer)) { if (DonationShop.menuItems.TryGetValue("errorText", out var value)) { value.GetComponent<Text>().text = "Erro: você não tem deadcoins suficientes"; } DonationShop.IsBuying = false; } } public static void RPC_BuyItemServer(long sender, ZPackage pkg) { //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Expected O, but got Unknown if (ZNet.instance.IsServer()) { ZNetPeer peer = ZNet.instance.GetPeer(sender); string[] array = pkg.ReadString().Split(new char[1] { ',' }); int num = Convert.ToInt32(array[0]); int num2 = Convert.ToInt32(array[1]); string text = array[2]; string text2 = array[3]; string playerName = peer.m_playerName; string path = Paths.ConfigPath + Folder + playerName + "-" + text2 + ".json"; int num3 = Convert.ToInt32(File.ReadAllText(path)); if (num > num3) { ZRoutedRpc.instance.InvokeRoutedRPC(sender, "DontHaveGold", new object[1] { (object)new ZPackage() }); return; } File.WriteAllText(path, (num3 - num).ToString()); Directory.CreateDirectory(Paths.ConfigPath + Folder + "/log/"); File.AppendAllText(Paths.ConfigPath + Folder + "/log/log.txt", text2 + "-" + playerName + "buyed " + num2 + " " + text + "for " + num + " coins"); ZRoutedRpc.instance.InvokeRoutedRPC(sender, "BuyItemClient", new object[1] { pkg }); } } public static void RPC_BuyItemClient(long sender, ZPackage pkg) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) ZPackage val = new ZPackage(); val.Write(((object)(PlatformUserID)(ref PlayFabManager.m_customId)).ToString()); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "GetGoldServer", new object[1] { val }); string[] array = pkg.ReadString().Split(new char[1] { ',' }); int num = Convert.ToInt32(array[0]); int num2 = Convert.ToInt32(array[1]); string text = array[2]; GameObject prefab = PrefabManager.Instance.GetPrefab(text); if ((Object)(object)prefab.GetComponent<ItemDrop>() != (Object)null) { ((Humanoid)Player.m_localPlayer).m_inventory.AddItem(prefab, num2); } else { Object.Instantiate<GameObject>(prefab, ((Component)Player.m_localPlayer).transform.position, Quaternion.identity); } DonationShop.IsBuying = false; } } internal class Shopper { public static void BuyItem(GameObject prefab, int amount, int price) { //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Expected O, but got Unknown //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) if (DonationShop.menuItems.TryGetValue("errorText", out var value)) { value.GetComponent<Text>().text = ""; } if (DonationShop.IsBuying) { value.GetComponent<Text>().text = "Aguarde o processamento da última compra."; } DonationShop.IsBuying = true; ZPackage val = new ZPackage(); string[] obj = new string[7] { price.ToString(), ",", amount.ToString(), ",", ((Object)prefab).name, ",", null }; PlatformUserID customId = PlayFabManager.m_customId; obj[6] = ((object)(PlatformUserID)(ref customId)).ToString(); val.Write(string.Concat(obj)); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "BuyItemServer", new object[1] { val }); } }
Hearthstone.dll
Decompiled 2 weeks 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.ComponentModel; using System.Diagnostics; 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.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using HarmonyLib; using ItemManager; using JetBrains.Annotations; using Microsoft.CodeAnalysis; using ServerSync; using TMPro; using UnityEngine; [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: CompilationRelaxations(8)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] namespace Hearthstone { [BepInPlugin("Detalhes.Hearthstone", "Hearthstone", "2.0.5")] public class Hearthstone : BaseUnityPlugin { public const string PluginGUID = "Detalhes.Hearthstone"; public const string Version = "2.0.5"; private Harmony harmony = new Harmony("Detalhes.Hearthstone"); public static ConfigEntry<bool> allowTeleportWithoutRestriction; private ConfigSync configSync = new ConfigSync("Detalhes.Hearthstone") { DisplayName = "Hearthstone", CurrentVersion = "2.0.5", MinimumRequiredVersion = "2.0.5" }; 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_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty<object>()), synchronizedSetting); } private void Awake() { //IL_009b: Unknown result type (might be due to invalid IL or missing references) allowTeleportWithoutRestriction = config("General", "allowTeleportWithoutRestriction", value: false, "Allow teleport without restriction"); Item item = new Item("hearthstone", "Hearthstone"); item.RequiredItems.Add("Crystal", 3); item.RequiredItems.Add("Coins", 30); item.RequiredItems.Add("BoneFragments", 20); SharedData shared = item.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared; shared.m_name = "Hearthstone"; shared.m_description = "Brings you back home."; shared.m_itemType = (ItemType)2; shared.m_consumeStatusEffect = null; item.Crafting.Add(CraftingTable.Workbench, 1); harmony.PatchAll(); } private void Update() { Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null || ((Character)localPlayer).IsDead()) { return; } Chat instance = Chat.instance; if ((instance != null && instance.HasFocus()) || Console.IsVisible() || Menu.IsVisible()) { return; } GameObject hoverObject = ((Humanoid)localPlayer).GetHoverObject(); if ((Object)(object)hoverObject == (Object)null) { return; } Bed componentInParent = hoverObject.GetComponentInParent<Bed>(); if ((Object)(object)componentInParent == (Object)null) { return; } ZNetView component = ((Component)componentInParent).GetComponent<ZNetView>(); if ((Object)(object)component != (Object)null && component.IsValid()) { long @long = component.GetZDO().GetLong(ZDOVars.s_owner, 0L); if (@long == localPlayer.GetPlayerID() && Input.GetKeyDown((KeyCode)112)) { SetHearthStonePosition(); ((Character)localPlayer).Message((MessageType)2, "Here is your new Hearthstone spawn", 0, (Sprite)null); } } } public static Vector3 GetHearthStonePosition() { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)Player.m_localPlayer == (Object)null || !Player.m_localPlayer.m_customData.ContainsKey("positionX")) { return Vector3.zero; } Vector3 result = default(Vector3); result.x = float.Parse(Player.m_localPlayer.m_customData["positionX"]); result.y = float.Parse(Player.m_localPlayer.m_customData["positionY"]); result.z = float.Parse(Player.m_localPlayer.m_customData["positionZ"]); return result; } public static void SetHearthStonePosition() { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)Player.m_localPlayer == (Object)null)) { Vector3 position = ((Component)Player.m_localPlayer).transform.position; Player.m_localPlayer.m_customData["positionX"] = position.x.ToString(); Player.m_localPlayer.m_customData["positionY"] = position.y.ToString(); Player.m_localPlayer.m_customData["positionZ"] = position.z.ToString(); } } } internal class Patches { [HarmonyPatch(typeof(Player), "ConsumeItem")] public static class ConsumePatch { private static bool Prefix(Player __instance, ref bool __result, ItemData item) { //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) if (item.m_shared.m_name != null && item.m_shared.m_name.IndexOf("hearthstone", StringComparison.OrdinalIgnoreCase) >= 0) { if (!((Humanoid)__instance).IsTeleportable() && !Hearthstone.allowTeleportWithoutRestriction.Value) { ((Character)__instance).Message((MessageType)2, "You can't teleport carrying those items", 0, (Sprite)null); __result = false; return false; } Vector3 hearthStonePosition = Hearthstone.GetHearthStonePosition(); if (hearthStonePosition == Vector3.zero) { ((Character)__instance).Message((MessageType)2, "You need to set hearthstone spawn point", 0, (Sprite)null); __result = false; return false; } ((Humanoid)__instance).GetInventory().RemoveItem(item, 1); ((Character)__instance).TeleportTo(hearthStonePosition, ((Component)__instance).transform.rotation, true); __result = true; return false; } return true; } } [HarmonyPatch(typeof(Bed), "GetHoverText")] private static class Bed_GetHoverText_Patch { private static void Postfix(Bed __instance, ref string __result, ZNetView ___m_nview) { if (!((Object)(object)___m_nview == (Object)null) && ___m_nview.IsValid() && !((Object)(object)Player.m_localPlayer == (Object)null)) { long @long = ___m_nview.GetZDO().GetLong(ZDOVars.s_owner, 0L); if (@long == Player.m_localPlayer.GetPlayerID() || Traverse.Create((object)__instance).Method("IsCurrent", Array.Empty<object>()).GetValue<bool>()) { __result += Localization.instance.Localize("\n[<color=yellow><b>P</b></color>] Set hearthstone"); } } } } } } namespace Microsoft.CodeAnalysis { [<f0d71fc2-41df-48fc-8477-25274cc8a8b9>Embedded] [CompilerGenerated] internal sealed class <f0d71fc2-41df-48fc-8477-25274cc8a8b9>EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [<f0d71fc2-41df-48fc-8477-25274cc8a8b9>Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class <af88efce-352b-493a-8b7e-30b8dff1c597>NullableAttribute : Attribute { public readonly byte[] NullableFlags; public <af88efce-352b-493a-8b7e-30b8dff1c597>NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public <af88efce-352b-493a-8b7e-30b8dff1c597>NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [<f0d71fc2-41df-48fc-8477-25274cc8a8b9>Embedded] [CompilerGenerated] internal sealed class <d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContextAttribute : Attribute { public readonly byte Flag; public <d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContextAttribute(byte P_0) { Flag = P_0; } } [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] [<f0d71fc2-41df-48fc-8477-25274cc8a8b9>Embedded] [CompilerGenerated] internal sealed class <e662831b-f412-4be7-bae8-7e91d5a305f0>RefSafetyRulesAttribute : Attribute { public readonly int Version; public <e662831b-f412-4be7-bae8-7e91d5a305f0>RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ItemManager { [PublicAPI] internal enum CraftingTable { Disabled, Inventory, [InternalName("piece_workbench")] Workbench, [InternalName("piece_cauldron")] Cauldron, [InternalName("forge")] Forge, [InternalName("piece_artisanstation")] ArtisanTable, [InternalName("piece_stonecutter")] StoneCutter, [InternalName("piece_magetable")] MageTable, [InternalName("blackforge")] BlackForge, [InternalName("piece_preptable")] FoodPreparationTable, [InternalName("piece_MeadCauldron")] MeadKetill, Custom } [PublicAPI] internal enum ConversionPiece { Disabled, [InternalName("smelter")] Smelter, [InternalName("charcoal_kiln")] CharcoalKiln, [InternalName("blastfurnace")] BlastFurnace, [InternalName("windmill")] Windmill, [InternalName("piece_spinningwheel")] SpinningWheel, [InternalName("eitrrefinery")] EitrRefinery, Custom } [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(1)] [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(0)] internal class InternalName : Attribute { public readonly string internalName; public InternalName(string internalName) { this.internalName = internalName; } } [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(0)] [PublicAPI] [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(1)] internal class RequiredResourceList { public readonly List<Requirement> Requirements = new List<Requirement>(); public bool Free; public void Add(string itemName, int amount, int quality = 0) { Requirements.Add(new Requirement { itemName = itemName, amount = amount, quality = quality }); } public void Add(string itemName, ConfigEntry<int> amountConfig, int quality = 0) { Requirements.Add(new Requirement { itemName = itemName, amountConfig = amountConfig, quality = quality }); } } [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(0)] [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(1)] [PublicAPI] internal class CraftingStationList { public readonly List<CraftingStationConfig> Stations = new List<CraftingStationConfig>(); public void Add(CraftingTable table, int level) { Stations.Add(new CraftingStationConfig { Table = table, level = level }); } public void Add(string customTable, int level) { Stations.Add(new CraftingStationConfig { Table = CraftingTable.Custom, level = level, custom = customTable }); } } [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(1)] [PublicAPI] [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(0)] internal class ItemRecipe { public readonly RequiredResourceList RequiredItems = new RequiredResourceList(); public readonly RequiredResourceList RequiredUpgradeItems = new RequiredResourceList(); public readonly CraftingStationList Crafting = new CraftingStationList(); public int CraftAmount = 1; public bool RequireOnlyOneIngredient; public float QualityResultAmountMultiplier = 1f; [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(2)] public ConfigEntryBase RecipeIsActive; } [PublicAPI] internal class Trade { public Trader Trader; public uint Price; public uint Stack = 1u; [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(2)] public string RequiredGlobalKey; } [PublicAPI] [Flags] internal enum Trader { None = 0, Haldor = 1, Hildir = 2 } internal struct Requirement { [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(1)] public string itemName; public int amount; [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(2)] public ConfigEntry<int> amountConfig; [Description("Set to a non-zero value to apply the requirement only for a specific quality")] public int quality; } internal struct CraftingStationConfig { public CraftingTable Table; public int level; [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(2)] public string custom; } [Flags] internal enum Configurability { Disabled = 0, Recipe = 1, Stats = 2, Drop = 4, Trader = 8, Full = 0xF } [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(1)] [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(0)] [PublicAPI] internal class DropTargets { public readonly List<DropTarget> Drops = new List<DropTarget>(); public void Add(string creatureName, float chance, int min = 1, int? max = null, bool levelMultiplier = true) { Drops.Add(new DropTarget { creature = creatureName, chance = chance, min = min, max = max.GetValueOrDefault(min), levelMultiplier = levelMultiplier }); } } internal struct DropTarget { [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(1)] public string creature; public int min; public int max; public float chance; public bool levelMultiplier; } internal enum Toggle { On = 1, Off = 0 } [PublicAPI] [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(0)] [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(1)] internal class Item { [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(0)] private class ItemConfig { [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(new byte[] { 2, 1 })] public ConfigEntry<string> craft; [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(new byte[] { 2, 1 })] public ConfigEntry<string> upgrade; public ConfigEntry<CraftingTable> table; public ConfigEntry<int> tableLevel; public ConfigEntry<string> customTable; [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(2)] public ConfigEntry<int> maximumTableLevel; public ConfigEntry<Toggle> requireOneIngredient; public ConfigEntry<float> qualityResultAmountMultiplier; } [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(0)] private class TraderConfig { public ConfigEntry<Trader> trader; public ConfigEntry<uint> price; public ConfigEntry<uint> stack; public ConfigEntry<string> requiredGlobalKey; } [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] private class RequirementQuality { public int quality; } [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(0)] [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(2)] private class ConfigurationManagerAttributes { [UsedImplicitly] public int? Order; [UsedImplicitly] public bool? Browsable; [UsedImplicitly] public string Category; [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(new byte[] { 2, 1 })] [UsedImplicitly] public Action<ConfigEntryBase> CustomDrawer; public Func<bool> browsability; } [PublicAPI] [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] public enum DamageModifier { Normal, Resistant, Weak, Immune, Ignore, VeryResistant, VeryWeak, None } [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] private delegate void setDmgFunc(ref DamageTypes dmg, float value); [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(0)] private class SerializedRequirements { public readonly List<Requirement> Reqs; public SerializedRequirements(List<Requirement> reqs) { Reqs = reqs; } public SerializedRequirements(string reqs) : this(reqs.Split(new char[1] { ',' }).Select([<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] (string r) => { string[] array = r.Split(new char[1] { ':' }); Requirement result = default(Requirement); result.itemName = array[0]; result.amount = ((array.Length <= 1 || !int.TryParse(array[1], out var result2)) ? 1 : result2); result.quality = ((array.Length > 2 && int.TryParse(array[2], out var result3)) ? result3 : 0); return result; }).ToList()) { } public override string ToString() { return string.Join(",", Reqs.Select([<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] (Requirement r) => $"{r.itemName}:{r.amount}" + ((r.quality > 0) ? $":{r.quality}" : ""))); } [return: <af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(2)] public static ItemDrop fetchByName(ObjectDB objectDB, string name) { GameObject itemPrefab = objectDB.GetItemPrefab(name); ItemDrop obj = ((itemPrefab != null) ? itemPrefab.GetComponent<ItemDrop>() : null); if ((Object)(object)obj == (Object)null) { Debug.LogWarning((object)("The required item '" + name + "' does not exist.")); } return obj; } public static Requirement[] toPieceReqs(ObjectDB objectDB, SerializedRequirements craft, SerializedRequirements upgrade) { //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00fd: Unknown result type (might be due to invalid IL or missing references) //IL_0178: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_018f: Expected O, but got Unknown //IL_0194: Expected O, but got Unknown //IL_011c: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Expected O, but got Unknown Dictionary<string, Requirement> dictionary = craft.Reqs.Where((Requirement r) => r.itemName != "").ToDictionary((Func<Requirement, string>)([<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] (Requirement r) => r.itemName), (Func<Requirement, Requirement>)([<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] (Requirement r) => { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown ItemDrop val6 = ResItem(r); return (val6 != null) ? new Requirement { m_amount = (r.amountConfig?.Value ?? r.amount), m_resItem = val6, m_amountPerLevel = 0 } : ((Requirement)null); })); List<Requirement> list = dictionary.Values.Where([<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] (Requirement v) => v != null).ToList(); foreach (Requirement item in upgrade.Reqs.Where((Requirement r) => r.itemName != "")) { if (item.quality > 0) { ItemDrop val = ResItem(item); if (val != null) { Requirement val2 = new Requirement { m_resItem = val, m_amountPerLevel = (item.amountConfig?.Value ?? item.amount), m_amount = 0 }; list.Add(val2); requirementQuality.Add(val2, new RequirementQuality { quality = item.quality }); } continue; } if (!dictionary.TryGetValue(item.itemName, out var value) || value == null) { ItemDrop val3 = ResItem(item); if (val3 != null) { string itemName = item.itemName; Requirement val4 = new Requirement { m_resItem = val3, m_amount = 0 }; Requirement val5 = val4; dictionary[itemName] = val4; value = val5; list.Add(value); } } if (value != null) { value.m_amountPerLevel = item.amountConfig?.Value ?? item.amount; } } return list.ToArray(); [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(2)] ItemDrop ResItem(Requirement r) { return fetchByName(objectDB, r.itemName); } } } [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(0)] private class SerializedDrop { public readonly List<DropTarget> Drops; public SerializedDrop(List<DropTarget> drops) { Drops = drops; } public SerializedDrop(string drops) { Drops = ((drops == "") ? ((IEnumerable<string>)Array.Empty<string>()) : ((IEnumerable<string>)drops.Split(new char[1] { ',' }))).Select([<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] (string r) => { string[] array = r.Split(new char[1] { ':' }); if (array.Length <= 2 || !int.TryParse(array[2], out var result)) { result = 1; } if (array.Length <= 3 || !int.TryParse(array[3], out var result2)) { result2 = result; } bool levelMultiplier = array.Length <= 4 || array[4] != "0"; DropTarget result3 = default(DropTarget); result3.creature = array[0]; result3.chance = ((array.Length > 1 && float.TryParse(array[1], out var result4)) ? result4 : 1f); result3.min = result; result3.max = result2; result3.levelMultiplier = levelMultiplier; return result3; }).ToList(); } public override string ToString() { return string.Join(",", Drops.Select([<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] (DropTarget r) => $"{r.creature}:{r.chance.ToString(CultureInfo.InvariantCulture)}:{r.min}:" + ((r.min == r.max) ? "" : $"{r.max}") + (r.levelMultiplier ? "" : ":0"))); } [return: <af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(2)] private static Character fetchByName(ZNetScene netScene, string name) { GameObject prefab = netScene.GetPrefab(name); Character obj = ((prefab != null) ? prefab.GetComponent<Character>() : null); if ((Object)(object)obj == (Object)null) { Debug.LogWarning((object)("The drop target character '" + name + "' does not exist.")); } return obj; } public Dictionary<Character, Drop> toCharacterDrops(ZNetScene netScene, GameObject item) { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Expected O, but got Unknown Dictionary<Character, Drop> dictionary = new Dictionary<Character, Drop>(); foreach (DropTarget drop in Drops) { Character val = fetchByName(netScene, drop.creature); if (val != null) { dictionary[val] = new Drop { m_prefab = item, m_amountMin = drop.min, m_amountMax = drop.max, m_chance = drop.chance, m_levelMultiplier = drop.levelMultiplier }; } } return dictionary; } } private static readonly List<Item> registeredItems = new List<Item>(); private static readonly Dictionary<ItemDrop, Item> itemDropMap = new Dictionary<ItemDrop, Item>(); private static Dictionary<Item, Dictionary<string, List<Recipe>>> activeRecipes = new Dictionary<Item, Dictionary<string, List<Recipe>>>(); [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(new byte[] { 1, 1, 2 })] private static Dictionary<Recipe, ConfigEntryBase> hiddenCraftRecipes = new Dictionary<Recipe, ConfigEntryBase>(); [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(new byte[] { 1, 1, 2 })] private static Dictionary<Recipe, ConfigEntryBase> hiddenUpgradeRecipes = new Dictionary<Recipe, ConfigEntryBase>(); private static Dictionary<Item, Dictionary<string, ItemConfig>> itemCraftConfigs = new Dictionary<Item, Dictionary<string, ItemConfig>>(); private static Dictionary<Item, ConfigEntry<string>> itemDropConfigs = new Dictionary<Item, ConfigEntry<string>>(); private Dictionary<CharacterDrop, Drop> characterDrops = new Dictionary<CharacterDrop, Drop>(); private readonly Dictionary<ConfigEntryBase, Action> statsConfigs = new Dictionary<ConfigEntryBase, Action>(); private static readonly ConditionalWeakTable<Requirement, RequirementQuality> requirementQuality = new ConditionalWeakTable<Requirement, RequirementQuality>(); public static Configurability DefaultConfigurability = Configurability.Full; public Configurability? Configurable; private Configurability configurationVisible = Configurability.Full; [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(2)] private TraderConfig traderConfig; public readonly GameObject Prefab; [Description("Specifies the maximum required crafting station level to upgrade and repair the item.\nDefault is calculated from crafting station level and maximum quality.")] public int MaximumRequiredStationLevel = int.MaxValue; [Description("Assigns the item as a drop item to a creature.\nUses a creature name, a drop chance and a minimum and maximum amount.")] public readonly DropTargets DropsFrom = new DropTargets(); [Description("Configures whether the item can be bought at the trader.\nDon't forget to set cost to something above 0 or the item will be sold for free.")] public readonly Trade Trade = new Trade(); internal List<Conversion> Conversions = new List<Conversion>(); internal List<ItemConversion> conversions = new List<ItemConversion>(); public Dictionary<string, ItemRecipe> Recipes = new Dictionary<string, ItemRecipe>(); [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(2)] private static object configManager; [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(2)] private static Localization _english; [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(2)] private static BaseUnityPlugin _plugin; private static bool hasConfigSync = true; [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(2)] private static object _configSync; private Configurability configurability => Configurable ?? DefaultConfigurability; [Description("Specifies the resources needed to craft the item.\nUse .Add to add resources with their internal ID and an amount.\nUse one .Add for each resource type the item should need.")] public RequiredResourceList RequiredItems => this[""].RequiredItems; [Description("Specifies the resources needed to upgrade the item.\nUse .Add to add resources with their internal ID and an amount. This amount will be multipled by the item quality level.\nUse one .Add for each resource type the upgrade should need.")] public RequiredResourceList RequiredUpgradeItems => this[""].RequiredUpgradeItems; [Description("Specifies the crafting station needed to craft the item.\nUse .Add to add a crafting station, using the CraftingTable enum and a minimum level for the crafting station.\nUse one .Add for each crafting station.")] public CraftingStationList Crafting => this[""].Crafting; [Description("Specifies a config entry which toggles whether a recipe is active.")] [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(2)] public ConfigEntryBase RecipeIsActive { [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(2)] get { return this[""].RecipeIsActive; } [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(2)] set { this[""].RecipeIsActive = value; } } [Description("Specifies the number of items that should be given to the player with a single craft of the item.\nDefaults to 1.")] public int CraftAmount { get { return this[""].CraftAmount; } set { this[""].CraftAmount = value; } } public bool RequireOnlyOneIngredient { get { return this[""].RequireOnlyOneIngredient; } set { this[""].RequireOnlyOneIngredient = value; } } public float QualityResultAmountMultiplier { get { return this[""].QualityResultAmountMultiplier; } set { this[""].QualityResultAmountMultiplier = value; } } public ItemRecipe this[string name] { get { if (Recipes.TryGetValue(name, out var value)) { return value; } return Recipes[name] = new ItemRecipe(); } } private static Localization english => _english ?? (_english = LocalizationCache.ForLanguage("English")); private static BaseUnityPlugin plugin { get { //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Expected O, but got Unknown if (_plugin == null) { IEnumerable<TypeInfo> source; try { source = Assembly.GetExecutingAssembly().DefinedTypes.ToList(); } catch (ReflectionTypeLoadException ex) { source = from t in ex.Types where t != null select t.GetTypeInfo(); } _plugin = (BaseUnityPlugin)Chainloader.ManagerObject.GetComponent((Type)source.First([<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] (TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t))); } return _plugin; } } [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(2)] private static object configSync { [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(2)] get { if (_configSync == null && hasConfigSync) { Type type = Assembly.GetExecutingAssembly().GetType("ServerSync.ConfigSync"); if ((object)type != null) { _configSync = Activator.CreateInstance(type, plugin.Info.Metadata.GUID + " ItemManager"); type.GetField("CurrentVersion").SetValue(_configSync, plugin.Info.Metadata.Version.ToString()); type.GetProperty("IsLocked").SetValue(_configSync, true); } else { hasConfigSync = false; } } return _configSync; } } public Item(string assetBundleFileName, string prefabName, string folderName = "assets") : this(PrefabManager.RegisterAssetBundle(assetBundleFileName, folderName), prefabName) { } public Item(AssetBundle bundle, string prefabName) : this(PrefabManager.RegisterPrefab(bundle, prefabName, addToObjectDb: true), skipRegistering: true) { } public Item(GameObject prefab, bool skipRegistering = false) { if (!skipRegistering) { PrefabManager.RegisterPrefab(prefab, addToObjectDb: true); } Prefab = prefab; registeredItems.Add(this); itemDropMap[Prefab.GetComponent<ItemDrop>()] = this; Prefab.GetComponent<ItemDrop>().m_itemData.m_dropPrefab = Prefab; } public void ToggleConfigurationVisibility(Configurability visible) { configurationVisible = visible; if (itemDropConfigs.TryGetValue(this, out var value)) { Toggle((ConfigEntryBase)(object)value, Configurability.Drop); } if (itemCraftConfigs.TryGetValue(this, out var value2)) { foreach (ItemConfig value4 in value2.Values) { ToggleObj(value4, Configurability.Recipe); } } foreach (Conversion conversion in Conversions) { if (conversion.config != null) { ToggleObj(conversion.config, Configurability.Recipe); } } foreach (KeyValuePair<ConfigEntryBase, Action> statsConfig in statsConfigs) { Toggle(statsConfig.Key, Configurability.Stats); if ((visible & Configurability.Stats) != 0) { statsConfig.Value(); } } reloadConfigDisplay(); void Toggle(ConfigEntryBase cfg, Configurability check) { object[] tags = cfg.Description.Tags; for (int j = 0; j < tags.Length; j++) { if (tags[j] is ConfigurationManagerAttributes configurationManagerAttributes) { configurationManagerAttributes.Browsable = (visible & check) != 0 && (configurationManagerAttributes.browsability == null || configurationManagerAttributes.browsability()); } } } void ToggleObj(object obj, Configurability check) { FieldInfo[] fields = obj.GetType().GetFields(); for (int i = 0; i < fields.Length; i++) { object? value3 = fields[i].GetValue(obj); ConfigEntryBase val = (ConfigEntryBase)((value3 is ConfigEntryBase) ? value3 : null); if (val != null) { Toggle(val, check); } } } } internal static void reloadConfigDisplay() { object obj = configManager?.GetType().GetProperty("DisplayingWindow").GetValue(configManager); if (obj is bool && (bool)obj) { configManager.GetType().GetMethod("BuildSettingList").Invoke(configManager, Array.Empty<object>()); } } private void UpdateItemTableConfig(string recipeKey, CraftingTable table, string customTableValue) { if (activeRecipes.ContainsKey(this) && activeRecipes[this].TryGetValue(recipeKey, out var value)) { value.First().m_enabled = table != CraftingTable.Disabled; if ((uint)table <= 1u) { value.First().m_craftingStation = null; } else if (table == CraftingTable.Custom) { Recipe obj = value.First(); GameObject prefab = ZNetScene.instance.GetPrefab(customTableValue); obj.m_craftingStation = ((prefab != null) ? prefab.GetComponent<CraftingStation>() : null); } else { value.First().m_craftingStation = ZNetScene.instance.GetPrefab(getInternalName(table)).GetComponent<CraftingStation>(); } } } private void UpdateCraftConfig(string recipeKey, SerializedRequirements craftRequirements, SerializedRequirements upgradeRequirements) { if (!Object.op_Implicit((Object)(object)ObjectDB.instance) || !activeRecipes.ContainsKey(this) || !activeRecipes[this].TryGetValue(recipeKey, out var value)) { return; } foreach (Recipe item in value) { item.m_resources = SerializedRequirements.toPieceReqs(ObjectDB.instance, craftRequirements, upgradeRequirements); } } internal static void Patch_FejdStartup() { //IL_0f3d: Unknown result type (might be due to invalid IL or missing references) //IL_0f42: Unknown result type (might be due to invalid IL or missing references) //IL_2208: Unknown result type (might be due to invalid IL or missing references) //IL_2212: Expected O, but got Unknown //IL_1006: Unknown result type (might be due to invalid IL or missing references) //IL_1009: Unknown result type (might be due to invalid IL or missing references) //IL_105f: Expected I4, but got Unknown //IL_0c2c: Unknown result type (might be due to invalid IL or missing references) //IL_0c36: Expected O, but got Unknown //IL_1193: Unknown result type (might be due to invalid IL or missing references) //IL_1196: Unknown result type (might be due to invalid IL or missing references) //IL_1198: Invalid comparison between Unknown and I4 //IL_036f: Unknown result type (might be due to invalid IL or missing references) //IL_0379: Expected O, but got Unknown //IL_119a: Unknown result type (might be due to invalid IL or missing references) //IL_119e: Invalid comparison between Unknown and I4 //IL_0d4f: Unknown result type (might be due to invalid IL or missing references) //IL_0d59: Expected O, but got Unknown //IL_0dfa: Unknown result type (might be due to invalid IL or missing references) //IL_0e04: Expected O, but got Unknown //IL_11a0: Unknown result type (might be due to invalid IL or missing references) //IL_11a4: Invalid comparison between Unknown and I4 //IL_0eae: Unknown result type (might be due to invalid IL or missing references) //IL_0eb8: Expected O, but got Unknown //IL_139f: Unknown result type (might be due to invalid IL or missing references) //IL_13a2: Unknown result type (might be due to invalid IL or missing references) //IL_13a4: Invalid comparison between Unknown and I4 //IL_0462: Unknown result type (might be due to invalid IL or missing references) //IL_046c: Expected O, but got Unknown //IL_13a6: Unknown result type (might be due to invalid IL or missing references) //IL_13aa: Unknown result type (might be due to invalid IL or missing references) //IL_13ac: Invalid comparison between Unknown and I4 //IL_13ae: Unknown result type (might be due to invalid IL or missing references) //IL_13b2: Invalid comparison between Unknown and I4 //IL_059d: Unknown result type (might be due to invalid IL or missing references) //IL_05a7: Expected O, but got Unknown //IL_1487: Unknown result type (might be due to invalid IL or missing references) //IL_148c: Unknown result type (might be due to invalid IL or missing references) //IL_148e: Unknown result type (might be due to invalid IL or missing references) //IL_1491: Invalid comparison between Unknown and I4 //IL_1493: Unknown result type (might be due to invalid IL or missing references) //IL_1497: Invalid comparison between Unknown and I4 //IL_06b5: Unknown result type (might be due to invalid IL or missing references) //IL_06bf: Expected O, but got Unknown //IL_1506: Unknown result type (might be due to invalid IL or missing references) //IL_1509: Unknown result type (might be due to invalid IL or missing references) //IL_150b: Invalid comparison between Unknown and I4 //IL_150d: Unknown result type (might be due to invalid IL or missing references) //IL_1511: Unknown result type (might be due to invalid IL or missing references) //IL_1513: Invalid comparison between Unknown and I4 //IL_0794: Unknown result type (might be due to invalid IL or missing references) //IL_079e: Expected O, but got Unknown //IL_1515: Unknown result type (might be due to invalid IL or missing references) //IL_1519: Invalid comparison between Unknown and I4 //IL_1656: Unknown result type (might be due to invalid IL or missing references) //IL_1659: Invalid comparison between Unknown and I4 //IL_089e: Unknown result type (might be due to invalid IL or missing references) //IL_08a8: Expected O, but got Unknown //IL_1856: Unknown result type (might be due to invalid IL or missing references) //IL_185d: Invalid comparison between Unknown and I4 //IL_1926: Unknown result type (might be due to invalid IL or missing references) //IL_192b: Unknown result type (might be due to invalid IL or missing references) //IL_192d: Unknown result type (might be due to invalid IL or missing references) //IL_1931: Unknown result type (might be due to invalid IL or missing references) //IL_1933: Invalid comparison between Unknown and I4 //IL_19a2: Unknown result type (might be due to invalid IL or missing references) //IL_19a5: Unknown result type (might be due to invalid IL or missing references) //IL_19a7: Invalid comparison between Unknown and I4 //IL_15cc: Unknown result type (might be due to invalid IL or missing references) //IL_15d1: Unknown result type (might be due to invalid IL or missing references) //IL_19a9: Unknown result type (might be due to invalid IL or missing references) //IL_19ad: Invalid comparison between Unknown and I4 //IL_19af: Unknown result type (might be due to invalid IL or missing references) //IL_19b3: Invalid comparison between Unknown and I4 //IL_1e20: Unknown result type (might be due to invalid IL or missing references) //IL_1e23: Invalid comparison between Unknown and I4 Type type = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault([<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] (Assembly a) => a.GetName().Name == "ConfigurationManager")?.GetType("ConfigurationManager.ConfigurationManager"); if (DefaultConfigurability != 0) { bool saveOnConfigSet = plugin.Config.SaveOnConfigSet; plugin.Config.SaveOnConfigSet = false; foreach (Item item4 in registeredItems.Where([<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] (Item i) => i.configurability != Configurability.Disabled)) { Item item3 = item4; string name2 = item3.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_name; string englishName = new Regex("['\\[\"\\]]").Replace(english.Localize(name2), "").Trim(); string localizedName = Localization.instance.Localize(name2).Trim(); int order = 0; if ((item3.configurability & Configurability.Recipe) != 0) { itemCraftConfigs[item3] = new Dictionary<string, ItemConfig>(); foreach (string item5 in item3.Recipes.Keys.DefaultIfEmpty("")) { string configKey = item5; string text = ((configKey == "") ? "" : (" (" + configKey + ")")); if (configKey == "") { Configurability? configurable = item3.Configurable; if (configurable.HasValue && item3.Crafting.Stations.Count == 0) { item3.Crafting.Add(CraftingTable.Disabled, 1); } } if (!item3.Recipes.ContainsKey(configKey) || item3.Recipes[configKey].Crafting.Stations.Count <= 0) { continue; } ItemConfig itemConfig2 = (itemCraftConfigs[item3][configKey] = new ItemConfig()); ItemConfig cfg = itemConfig2; List<ConfigurationManagerAttributes> hideWhenNoneAttributes = new List<ConfigurationManagerAttributes>(); cfg.table = config(englishName, "Crafting Station" + text, item3.Recipes[configKey].Crafting.Stations.First().Table, new ConfigDescription("Crafting station where " + englishName + " is available.", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Order = (order -= 1), Browsable = ((item3.configurationVisible & Configurability.Recipe) != 0), Category = localizedName } })); ConfigurationManagerAttributes customTableAttributes = new ConfigurationManagerAttributes { Order = (order -= 1), browsability = CustomTableBrowsability, Browsable = (CustomTableBrowsability() && (item3.configurationVisible & Configurability.Recipe) != 0), Category = localizedName }; cfg.customTable = config(englishName, "Custom Crafting Station" + text, item3.Recipes[configKey].Crafting.Stations.First().custom ?? "", new ConfigDescription("", (AcceptableValueBase)null, new object[1] { customTableAttributes })); cfg.table.SettingChanged += TableConfigChanged; cfg.customTable.SettingChanged += TableConfigChanged; ConfigurationManagerAttributes configurationManagerAttributes = new ConfigurationManagerAttributes { Order = (order -= 1), browsability = TableLevelBrowsability, Browsable = (TableLevelBrowsability() && (item3.configurationVisible & Configurability.Recipe) != 0), Category = localizedName }; hideWhenNoneAttributes.Add(configurationManagerAttributes); cfg.tableLevel = config(englishName, "Crafting Station Level" + text, item3.Recipes[configKey].Crafting.Stations.First().level, new ConfigDescription("Required crafting station level to craft " + englishName + ".", (AcceptableValueBase)null, new object[1] { configurationManagerAttributes })); cfg.tableLevel.SettingChanged += [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] (object _, EventArgs _) => { if (activeRecipes.ContainsKey(item3) && activeRecipes[item3].TryGetValue(configKey, out var value6)) { value6.First().m_minStationLevel = cfg.tableLevel.Value; } }; if (item3.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_maxQuality > 1) { cfg.maximumTableLevel = config(englishName, "Maximum Crafting Station Level" + text, (item3.MaximumRequiredStationLevel == int.MaxValue) ? (item3.Recipes[configKey].Crafting.Stations.First().level + item3.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_maxQuality - 1) : item3.MaximumRequiredStationLevel, new ConfigDescription("Maximum crafting station level to upgrade and repair " + englishName + ".", (AcceptableValueBase)null, new object[1] { configurationManagerAttributes })); } cfg.requireOneIngredient = config(englishName, "Require only one resource" + text, item3.Recipes[configKey].RequireOnlyOneIngredient ? Toggle.On : Toggle.Off, new ConfigDescription("Whether only one of the ingredients is needed to craft " + englishName, (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Order = (order -= 1), browsability = TableLevelBrowsability, Browsable = (TableLevelBrowsability() && (item3.configurationVisible & Configurability.Recipe) != 0), Category = localizedName } })); ConfigurationManagerAttributes qualityResultAttributes = new ConfigurationManagerAttributes { Order = (order -= 1), browsability = QualityResultBrowsability, Browsable = (QualityResultBrowsability() && (item3.configurationVisible & Configurability.Recipe) != 0), Category = localizedName }; cfg.requireOneIngredient.SettingChanged += [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] (object _, EventArgs _) => { if (activeRecipes.ContainsKey(item3) && activeRecipes[item3].TryGetValue(configKey, out var value5)) { foreach (Recipe item6 in value5) { item6.m_requireOnlyOneIngredient = cfg.requireOneIngredient.Value == Toggle.On; } } qualityResultAttributes.Browsable = QualityResultBrowsability(); reloadConfigDisplay(); }; cfg.qualityResultAmountMultiplier = config(englishName, "Quality Multiplier" + text, item3.Recipes[configKey].QualityResultAmountMultiplier, new ConfigDescription("Multiplies the crafted amount based on the quality of the resources when crafting " + englishName + ". Only works, if Require Only One Resource is true.", (AcceptableValueBase)null, new object[1] { qualityResultAttributes })); cfg.qualityResultAmountMultiplier.SettingChanged += [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] (object _, EventArgs _) => { if (activeRecipes.ContainsKey(item3) && activeRecipes[item3].TryGetValue(configKey, out var value4)) { foreach (Recipe item7 in value4) { item7.m_qualityResultAmountMultiplier = cfg.qualityResultAmountMultiplier.Value; } } }; if ((!item3.Recipes[configKey].RequiredItems.Free || item3.Recipes[configKey].RequiredItems.Requirements.Count > 0) && item3.Recipes[configKey].RequiredItems.Requirements.All((Requirement r) => r.amountConfig == null)) { cfg.craft = itemConfig("Crafting Costs" + text, new SerializedRequirements(item3.Recipes[configKey].RequiredItems.Requirements).ToString(), "Item costs to craft " + englishName, isUpgrade: false); } if (item3.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_maxQuality > 1 && (!item3.Recipes[configKey].RequiredUpgradeItems.Free || item3.Recipes[configKey].RequiredUpgradeItems.Requirements.Count > 0) && item3.Recipes[configKey].RequiredUpgradeItems.Requirements.All((Requirement r) => r.amountConfig == null)) { cfg.upgrade = itemConfig("Upgrading Costs" + text, new SerializedRequirements(item3.Recipes[configKey].RequiredUpgradeItems.Requirements).ToString(), "Item costs per level to upgrade " + englishName, isUpgrade: true); } if (cfg.craft != null) { cfg.craft.SettingChanged += ConfigChanged; } if (cfg.upgrade != null) { cfg.upgrade.SettingChanged += ConfigChanged; } void ConfigChanged(object o, EventArgs e) { item3.UpdateCraftConfig(configKey, new SerializedRequirements(cfg.craft?.Value ?? ""), new SerializedRequirements(cfg.upgrade?.Value ?? "")); } bool CustomTableBrowsability() { return cfg.table.Value == CraftingTable.Custom; } bool ItemBrowsability() { return cfg.table.Value != CraftingTable.Disabled; } bool QualityResultBrowsability() { return cfg.requireOneIngredient.Value == Toggle.On; } void TableConfigChanged(object o, EventArgs e) { item3.UpdateItemTableConfig(configKey, cfg.table.Value, cfg.customTable.Value); customTableAttributes.Browsable = cfg.table.Value == CraftingTable.Custom; foreach (ConfigurationManagerAttributes item8 in hideWhenNoneAttributes) { item8.Browsable = cfg.table.Value != CraftingTable.Disabled; } reloadConfigDisplay(); } bool TableLevelBrowsability() { return cfg.table.Value != CraftingTable.Disabled; } ConfigEntry<string> itemConfig(string name, string value, string desc, bool isUpgrade) { //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Expected O, but got Unknown ConfigurationManagerAttributes configurationManagerAttributes3 = new ConfigurationManagerAttributes { CustomDrawer = drawRequirementsConfigTable(item3, isUpgrade), Order = (order -= 1), browsability = ItemBrowsability, Browsable = (ItemBrowsability() && (item3.configurationVisible & Configurability.Recipe) != 0), Category = localizedName }; hideWhenNoneAttributes.Add(configurationManagerAttributes3); return config(englishName, name, value, new ConfigDescription(desc, (AcceptableValueBase)null, new object[1] { configurationManagerAttributes3 })); } } if ((item3.configurability & Configurability.Drop) != 0) { ConfigEntry<string> val3 = (itemDropConfigs[item3] = config(englishName, "Drops from", new SerializedDrop(item3.DropsFrom.Drops).ToString(), new ConfigDescription(englishName + " drops from this creature.", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { CustomDrawer = drawDropsConfigTable, Category = localizedName, Browsable = ((item3.configurationVisible & Configurability.Drop) != 0) } }))); val3.SettingChanged += [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] (object _, EventArgs _) => { item3.UpdateCharacterDrop(); }; } for (int j = 0; j < item3.Conversions.Count; j++) { string text2 = ((item3.Conversions.Count > 1) ? $"{j + 1}. " : ""); Conversion conversion = item3.Conversions[j]; conversion.config = new Conversion.ConversionConfig(); int index = j; conversion.config.input = config(englishName, text2 + "Conversion Input Item", conversion.Input, new ConfigDescription("Input item to create " + englishName, (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Category = localizedName, Browsable = ((item3.configurationVisible & Configurability.Recipe) != 0) } })); conversion.config.input.SettingChanged += [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] (object _, EventArgs _) => { if (index < item3.conversions.Count) { ObjectDB instance = ObjectDB.instance; if (instance != null) { ItemDrop from = SerializedRequirements.fetchByName(instance, conversion.config.input.Value); item3.conversions[index].m_from = from; UpdatePiece(); } } }; conversion.config.piece = config(englishName, text2 + "Conversion Piece", conversion.Piece, new ConfigDescription("Conversion piece used to create " + englishName, (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Category = localizedName, Browsable = ((item3.configurationVisible & Configurability.Recipe) != 0) } })); conversion.config.piece.SettingChanged += [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] (object _, EventArgs _) => { UpdatePiece(); }; conversion.config.customPiece = config(englishName, text2 + "Conversion Custom Piece", conversion.customPiece ?? "", new ConfigDescription("Custom conversion piece to create " + englishName, (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Category = localizedName, Browsable = ((item3.configurationVisible & Configurability.Recipe) != 0) } })); conversion.config.customPiece.SettingChanged += [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] (object _, EventArgs _) => { UpdatePiece(); }; void UpdatePiece() { if (index < item3.conversions.Count && Object.op_Implicit((Object)(object)ZNetScene.instance)) { string text3 = ((conversion.config.piece.Value == ConversionPiece.Disabled) ? null : ((conversion.config.piece.Value == ConversionPiece.Custom) ? conversion.config.customPiece.Value : getInternalName(conversion.config.piece.Value))); string activePiece = conversion.config.activePiece; if (conversion.config.activePiece != null) { int num = ZNetScene.instance.GetPrefab(conversion.config.activePiece).GetComponent<Smelter>().m_conversion.IndexOf(item3.conversions[index]); if (num >= 0) { Smelter[] array3 = Resources.FindObjectsOfTypeAll<Smelter>(); foreach (Smelter val4 in array3) { if (Utils.GetPrefabName(((Component)val4).gameObject) == activePiece) { val4.m_conversion.RemoveAt(num); } } } conversion.config.activePiece = null; } if (item3.conversions[index].m_from != null && conversion.config.piece.Value != 0) { GameObject prefab = ZNetScene.instance.GetPrefab(text3); if (((prefab != null) ? prefab.GetComponent<Smelter>() : null) != null) { conversion.config.activePiece = text3; Smelter[] array3 = Resources.FindObjectsOfTypeAll<Smelter>(); foreach (Smelter val5 in array3) { if (Utils.GetPrefabName(((Component)val5).gameObject) == text3) { val5.m_conversion.Add(item3.conversions[index]); } } } } } } } } if ((item3.configurability & Configurability.Stats) != 0) { item3.statsConfigs.Clear(); SharedData shared2 = item3.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared; ItemType itemType = shared2.m_itemType; statcfg<float>("Weight", "Weight of " + englishName + ".", (SharedData shared) => shared.m_weight, delegate(SharedData shared, float value) { shared.m_weight = value; }); statcfg<int>("Trader Value", "Trader value of " + englishName + ".", (SharedData shared) => shared.m_value, delegate(SharedData shared, int value) { shared.m_value = value; }); bool flag; switch (itemType - 3) { case 0: case 1: case 2: case 3: case 4: case 8: case 9: case 11: case 14: case 16: case 19: flag = true; break; default: flag = false; break; } if (flag) { statcfg<float>("Durability", "Durability of " + englishName + ".", (SharedData shared) => shared.m_maxDurability, delegate(SharedData shared, float value) { shared.m_maxDurability = value; }); statcfg<float>("Durability per Level", "Durability gain per level of " + englishName + ".", (SharedData shared) => shared.m_durabilityPerLevel, delegate(SharedData shared, float value) { shared.m_durabilityPerLevel = value; }); statcfg<float>("Movement Speed Modifier", "Movement speed modifier of " + englishName + ".", (SharedData shared) => shared.m_movementModifier, delegate(SharedData shared, float value) { shared.m_movementModifier = value; }); } if ((itemType - 3 <= 2 || (int)itemType == 14 || (int)itemType == 22) ? true : false) { statcfg<float>("Block Armor", "Block armor of " + englishName + ".", (SharedData shared) => shared.m_blockPower, delegate(SharedData shared, float value) { shared.m_blockPower = value; }); statcfg<float>("Block Armor per Level", "Block armor per level for " + englishName + ".", (SharedData shared) => shared.m_blockPowerPerLevel, delegate(SharedData shared, float value) { shared.m_blockPowerPerLevel = value; }); statcfg<float>("Block Force", "Block force of " + englishName + ".", (SharedData shared) => shared.m_deflectionForce, delegate(SharedData shared, float value) { shared.m_deflectionForce = value; }); statcfg<float>("Block Force per Level", "Block force per level for " + englishName + ".", (SharedData shared) => shared.m_deflectionForcePerLevel, delegate(SharedData shared, float value) { shared.m_deflectionForcePerLevel = value; }); statcfg<float>("Parry Bonus", "Parry bonus of " + englishName + ".", (SharedData shared) => shared.m_timedBlockBonus, delegate(SharedData shared, float value) { shared.m_timedBlockBonus = value; }); } else if ((itemType - 6 <= 1 || itemType - 11 <= 1 || (int)itemType == 17) ? true : false) { statcfg<float>("Armor", "Armor of " + englishName + ".", (SharedData shared) => shared.m_armor, delegate(SharedData shared, float value) { shared.m_armor = value; }); statcfg<float>("Armor per Level", "Armor per level for " + englishName + ".", (SharedData shared) => shared.m_armorPerLevel, delegate(SharedData shared, float value) { shared.m_armorPerLevel = value; }); } SkillType skillType = shared2.m_skillType; if (((int)skillType == 7 || (int)skillType == 12) ? true : false) { statcfg<int>("Tool tier", "Tool tier of " + englishName + ".", (SharedData shared) => shared.m_toolTier, delegate(SharedData shared, int value) { shared.m_toolTier = value; }); } if ((itemType - 5 <= 2 || itemType - 11 <= 1 || (int)itemType == 17) ? true : false) { Dictionary<DamageType, DamageModifier> modifiers = shared2.m_damageModifiers.ToDictionary((DamageModPair d) => d.m_type, (DamageModPair d) => (DamageModifier)d.m_modifier); DamageType[] first = (DamageType[])Enum.GetValues(typeof(DamageType)); DamageType[] array = new DamageType[5]; RuntimeHelpers.InitializeArray(array, (RuntimeFieldHandle)/*OpCode not supported: LdMemberToken*/); foreach (DamageType item9 in first.Except((IEnumerable<DamageType>)(object)array)) { DamageType damageType = item9; statcfg<DamageModifier>(((object)(DamageType)(ref damageType)).ToString() + " Resistance", ((object)(DamageType)(ref damageType)).ToString() + " resistance of " + englishName + ".", (SharedData _) => (!modifiers.TryGetValue(damageType, out var value3)) ? DamageModifier.None : value3, delegate(SharedData shared, DamageModifier value) { //IL_0002: 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_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) DamageModPair val6 = default(DamageModPair); val6.m_type = damageType; val6.m_modifier = (DamageModifier)value; DamageModPair val7 = val6; for (int n = 0; n < shared.m_damageModifiers.Count; n++) { if (shared.m_damageModifiers[n].m_type == damageType) { if (value == DamageModifier.None) { shared.m_damageModifiers.RemoveAt(n); } else { shared.m_damageModifiers[n] = val7; } return; } } if (value != DamageModifier.None) { shared.m_damageModifiers.Add(val7); } }); } } if ((int)itemType == 2 && shared2.m_food > 0f) { statcfg<float>("Health", "Health value of " + englishName + ".", (SharedData shared) => shared.m_food, delegate(SharedData shared, float value) { shared.m_food = value; }); statcfg<float>("Stamina", "Stamina value of " + englishName + ".", (SharedData shared) => shared.m_foodStamina, delegate(SharedData shared, float value) { shared.m_foodStamina = value; }); statcfg<float>("Eitr", "Eitr value of " + englishName + ".", (SharedData shared) => shared.m_foodEitr, delegate(SharedData shared, float value) { shared.m_foodEitr = value; }); statcfg<float>("Duration", "Duration of " + englishName + ".", (SharedData shared) => shared.m_foodBurnTime, delegate(SharedData shared, float value) { shared.m_foodBurnTime = value; }); statcfg<float>("Health Regen", "Health regen value of " + englishName + ".", (SharedData shared) => shared.m_foodRegen, delegate(SharedData shared, float value) { shared.m_foodRegen = value; }); } if ((int)shared2.m_skillType == 10) { statcfg<float>("Health Cost", "Health cost of " + englishName + ".", (SharedData shared) => shared.m_attack.m_attackHealth, delegate(SharedData shared, float value) { shared.m_attack.m_attackHealth = value; }); statcfg<float>("Health Cost Percentage", "Health cost percentage of " + englishName + ".", (SharedData shared) => shared.m_attack.m_attackHealthPercentage, delegate(SharedData shared, float value) { shared.m_attack.m_attackHealthPercentage = value; }); } skillType = shared2.m_skillType; if (skillType - 9 <= 1) { statcfg<float>("Eitr Cost", "Eitr cost of " + englishName + ".", (SharedData shared) => shared.m_attack.m_attackEitr, delegate(SharedData shared, float value) { shared.m_attack.m_attackEitr = value; }); } if ((itemType - 3 <= 1 || (int)itemType == 14 || (int)itemType == 22) ? true : false) { statcfg<float>("Knockback", "Knockback of " + englishName + ".", (SharedData shared) => shared.m_attackForce, delegate(SharedData shared, float value) { shared.m_attackForce = value; }); statcfg<float>("Backstab Bonus", "Backstab bonus of " + englishName + ".", (SharedData shared) => shared.m_backstabBonus, delegate(SharedData shared, float value) { shared.m_backstabBonus = value; }); statcfg<float>("Attack Stamina", "Attack stamina of " + englishName + ".", (SharedData shared) => shared.m_attack.m_attackStamina, delegate(SharedData shared, float value) { shared.m_attack.m_attackStamina = value; }); SetDmg("True", (DamageTypes dmg) => dmg.m_damage, delegate(ref DamageTypes dmg, float val) { dmg.m_damage = val; }); SetDmg("Slash", (DamageTypes dmg) => dmg.m_slash, delegate(ref DamageTypes dmg, float val) { dmg.m_slash = val; }); SetDmg("Pierce", (DamageTypes dmg) => dmg.m_pierce, delegate(ref DamageTypes dmg, float val) { dmg.m_pierce = val; }); SetDmg("Blunt", (DamageTypes dmg) => dmg.m_blunt, delegate(ref DamageTypes dmg, float val) { dmg.m_blunt = val; }); SetDmg("Chop", (DamageTypes dmg) => dmg.m_chop, delegate(ref DamageTypes dmg, float val) { dmg.m_chop = val; }); SetDmg("Pickaxe", (DamageTypes dmg) => dmg.m_pickaxe, delegate(ref DamageTypes dmg, float val) { dmg.m_pickaxe = val; }); SetDmg("Fire", (DamageTypes dmg) => dmg.m_fire, delegate(ref DamageTypes dmg, float val) { dmg.m_fire = val; }); SetDmg("Poison", (DamageTypes dmg) => dmg.m_poison, delegate(ref DamageTypes dmg, float val) { dmg.m_poison = val; }); SetDmg("Frost", (DamageTypes dmg) => dmg.m_frost, delegate(ref DamageTypes dmg, float val) { dmg.m_frost = val; }); SetDmg("Lightning", (DamageTypes dmg) => dmg.m_lightning, delegate(ref DamageTypes dmg, float val) { dmg.m_lightning = val; }); SetDmg("Spirit", (DamageTypes dmg) => dmg.m_spirit, delegate(ref DamageTypes dmg, float val) { dmg.m_spirit = val; }); if ((int)itemType == 4) { statcfg<int>("Projectiles", "Number of projectiles that " + englishName + " shoots at once.", (SharedData shared) => shared.m_attack.m_projectileBursts, delegate(SharedData shared, int value) { shared.m_attack.m_projectileBursts = value; }); statcfg<float>("Burst Interval", "Time between the projectiles " + englishName + " shoots at once.", (SharedData shared) => shared.m_attack.m_burstInterval, delegate(SharedData shared, float value) { shared.m_attack.m_burstInterval = value; }); statcfg<float>("Minimum Accuracy", "Minimum accuracy for " + englishName + ".", (SharedData shared) => shared.m_attack.m_projectileAccuracyMin, delegate(SharedData shared, float value) { shared.m_attack.m_projectileAccuracyMin = value; }); statcfg<float>("Accuracy", "Accuracy for " + englishName + ".", (SharedData shared) => shared.m_attack.m_projectileAccuracy, delegate(SharedData shared, float value) { shared.m_attack.m_projectileAccuracy = value; }); statcfg<float>("Minimum Velocity", "Minimum velocity for " + englishName + ".", (SharedData shared) => shared.m_attack.m_projectileVelMin, delegate(SharedData shared, float value) { shared.m_attack.m_projectileVelMin = value; }); statcfg<float>("Velocity", "Velocity for " + englishName + ".", (SharedData shared) => shared.m_attack.m_projectileVel, delegate(SharedData shared, float value) { shared.m_attack.m_projectileVel = value; }); statcfg<float>("Maximum Draw Time", "Time until " + englishName + " is fully drawn at skill level 0.", (SharedData shared) => shared.m_attack.m_drawDurationMin, delegate(SharedData shared, float value) { shared.m_attack.m_drawDurationMin = value; }); statcfg<float>("Stamina Drain", "Stamina drain per second while drawing " + englishName + ".", (SharedData shared) => shared.m_attack.m_drawStaminaDrain, delegate(SharedData shared, float value) { shared.m_attack.m_drawStaminaDrain = value; }); } } } List<ConfigurationManagerAttributes> traderAttributes; if ((item3.configurability & Configurability.Trader) != 0) { traderAttributes = new List<ConfigurationManagerAttributes>(); item3.traderConfig = new TraderConfig { trader = config(englishName, "Trader Selling", item3.Trade.Trader, new ConfigDescription("Which traders sell " + englishName + ".", (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Order = (order -= 1), Browsable = ((item3.configurationVisible & Configurability.Trader) != 0), Category = localizedName } })) }; item3.traderConfig.trader.SettingChanged += [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] (object _, EventArgs _) => { item3.ReloadTraderConfiguration(); foreach (ConfigurationManagerAttributes item10 in traderAttributes) { item10.Browsable = TraderBrowsability(); } reloadConfigDisplay(); }; item3.traderConfig.price = traderConfig<uint>("Trader Price", item3.Trade.Price, "Price of " + englishName + " at the trader."); item3.traderConfig.stack = traderConfig<uint>("Trader Stack", item3.Trade.Stack, "Stack size of " + englishName + " in the trader. Also known as the number of items sold by a trader in one transaction."); item3.traderConfig.requiredGlobalKey = traderConfig<string>("Trader Required Global Key", item3.Trade.RequiredGlobalKey ?? "", "Required global key to unlock " + englishName + " at the trader."); if (item3.traderConfig.trader.Value != 0) { PrefabManager.AddItemToTrader(item3.Prefab, item3.traderConfig.trader.Value, item3.traderConfig.price.Value, item3.traderConfig.stack.Value, item3.traderConfig.requiredGlobalKey.Value); } } else if (item3.Trade.Trader != 0) { PrefabManager.AddItemToTrader(item3.Prefab, item3.Trade.Trader, item3.Trade.Price, item3.Trade.Stack, item3.Trade.RequiredGlobalKey); } void SetDmg(string dmgType, Func<DamageTypes, float> readDmg, setDmgFunc setDmg) { statcfg<float>(dmgType + " Damage", dmgType + " damage dealt by " + englishName + ".", (SharedData shared) => readDmg(shared.m_damages), delegate(SharedData shared, float val) { setDmg(ref shared.m_damages, val); }); statcfg<float>(dmgType + " Damage Per Level", dmgType + " damage dealt increase per level for " + englishName + ".", (SharedData shared) => readDmg(shared.m_damagesPerLevel), delegate(SharedData shared, float val) { setDmg(ref shared.m_damagesPerLevel, val); }); } bool TraderBrowsability() { return item3.traderConfig.trader.Value != Trader.None; } void statcfg<T>(string configName, string description, [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(new byte[] { 1, 1, 0 })] Func<SharedData, T> readDefault, [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(new byte[] { 1, 1, 0 })] Action<SharedData, T> setValue) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Expected O, but got Unknown SharedData shared3 = item3.Prefab.GetComponent<ItemDrop>().m_itemData.m_shared; ConfigEntry<T> cfg2 = config(englishName, configName, readDefault(shared3), new ConfigDescription(description, (AcceptableValueBase)null, new object[1] { new ConfigurationManagerAttributes { Category = localizedName, Browsable = ((item3.configurationVisible & Configurability.Stats) != 0) } })); if ((item3.configurationVisible & Configurability.Stats) != 0) { setValue(shared3, cfg2.Value); } item3.statsConfigs.Add((ConfigEntryBase)(object)cfg2, ApplyConfig); cfg2.SettingChanged += [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] (object _, EventArgs _) => { if ((item3.configurationVisible & Configurability.Stats) != 0) { ApplyConfig(); } }; void ApplyConfig() { item3.ApplyToAllInstances(delegate(ItemData item) { setValue(item.m_shared, cfg2.Value); }); } } [return: <af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(new byte[] { 1, 0 })] ConfigEntry<T> traderConfig<T>(string name, [<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(0)] T value, string desc) { //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Expected O, but got Unknown ConfigurationManagerAttributes configurationManagerAttributes2 = new ConfigurationManagerAttributes { Order = (order -= 1), browsability = TraderBrowsability, Browsable = (TraderBrowsability() && (item3.configurationVisible & Configurability.Trader) != 0), Category = localizedName }; traderAttributes.Add(configurationManagerAttributes2); ConfigEntry<T> obj = config(englishName, name, value, new ConfigDescription(desc, (AcceptableValueBase)null, new object[1] { configurationManagerAttributes2 })); obj.SettingChanged += [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] (object _, EventArgs _) => { item3.ReloadTraderConfiguration(); }; return obj; } } if (saveOnConfigSet) { plugin.Config.SaveOnConfigSet = true; plugin.Config.Save(); } } configManager = ((type == null) ? null : Chainloader.ManagerObject.GetComponent(type)); foreach (Item registeredItem in registeredItems) { Item item2 = registeredItem; foreach (KeyValuePair<string, ItemRecipe> recipe in item2.Recipes) { KeyValuePair<string, ItemRecipe> kv = recipe; RequiredResourceList[] array2 = new RequiredResourceList[2] { kv.Value.RequiredItems, kv.Value.RequiredUpgradeItems }; foreach (RequiredResourceList requiredResourceList in array2) { for (int l = 0; l < requiredResourceList.Requirements.Count; l++) { ConfigEntry<int> amountCfg; int resourceIndex; if ((item2.configurability & Configurability.Recipe) != 0) { amountCfg = requiredResourceList.Requirements[l].amountConfig; if (amountCfg != null) { resourceIndex = l; amountCfg.SettingChanged += ConfigChanged; } } void ConfigChanged(object o, EventArgs e) { if (Object.op_Implicit((Object)(object)ObjectDB.instance) && activeRecipes.ContainsKey(item2) && activeRecipes[item2].TryGetValue(kv.Key, out var value2)) { foreach (Recipe item11 in value2) { item11.m_resources[resourceIndex].m_amount = amountCfg.Value; } } } } } } item2.InitializeNewRegisteredItem(); } } private void InitializeNewRegisteredItem() { foreach (KeyValuePair<string, ItemRecipe> recipe in Recipes) { KeyValuePair<string, ItemRecipe> kv = recipe; ConfigEntryBase enabledCfg = kv.Value.RecipeIsActive; if (enabledCfg != null) { ((object)enabledCfg).GetType().GetEvent("SettingChanged").AddEventHandler(enabledCfg, new EventHandler(ConfigChanged)); } void ConfigChanged(object o, EventArgs e) { if (Object.op_Implicit((Object)(object)ObjectDB.instance) && activeRecipes.ContainsKey(this) && activeRecipes[this].TryGetValue(kv.Key, out var value)) { foreach (Recipe item in value) { item.m_enabled = (int)enabledCfg.BoxedValue != 0; } } } } } public void ReloadCraftingConfiguration() { if (Object.op_Implicit((Object)(object)ObjectDB.instance) && ObjectDB.instance.GetItemPrefab(StringExtensionMethods.GetStableHashCode(((Object)Prefab).name)) == null) { registerRecipesInObjectDB(ObjectDB.instance); ObjectDB.instance.m_items.Add(Prefab); ObjectDB.instance.m_itemByHash.Add(StringExtensionMethods.GetStableHashCode(((Object)Prefab).name), Prefab); ZNetScene.instance.m_prefabs.Add(Prefab); ZNetScene.instance.m_namedPrefabs.Add(StringExtensionMethods.GetStableHashCode(((Object)Prefab).name), Prefab); } foreach (string item in Recipes.Keys.DefaultIfEmpty("")) { if (Recipes.TryGetValue(item, out var value) && value.Crafting.Stations.Count > 0) { UpdateItemTableConfig(item, value.Crafting.Stations.First().Table, value.Crafting.Stations.First().custom ?? ""); UpdateCraftConfig(item, new SerializedRequirements(value.RequiredItems.Requirements), new SerializedRequirements(value.RequiredUpgradeItems.Requirements)); } } } private void ReloadTraderConfiguration() { if (traderConfig.trader.Value == Trader.None) { PrefabManager.RemoveItemFromTrader(Prefab); } else { PrefabManager.AddItemToTrader(Prefab, traderConfig.trader.Value, traderConfig.price.Value, traderConfig.stack.Value, traderConfig.requiredGlobalKey.Value); } } public static void ApplyToAllInstances(GameObject prefab, Action<ItemData> callback) { callback(prefab.GetComponent<ItemDrop>().m_itemData); string name = prefab.GetComponent<ItemDrop>().m_itemData.m_shared.m_name; Inventory[] source = (from c in Player.s_players.Select([<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] (Player p) => ((Humanoid)p).GetInventory()).Concat(from c in Object.FindObjectsOfType<Container>() select c.GetInventory()) where c != null select c).ToArray(); foreach (ItemData item in (from i in (from p in ObjectDB.instance.m_items select p.GetComponent<ItemDrop>() into c where Object.op_Implicit((Object)(object)c) && Object.op_Implicit((Object)(object)((Component)c).GetComponent<ZNetView>()) select c).Concat(ItemDrop.s_instances) select i.m_itemData).Concat(source.SelectMany([<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] (Inventory i) => i.GetAllItems()))) { if (item.m_shared.m_name == name) { callback(item); } } } public void ApplyToAllInstances(Action<ItemData> callback) { ApplyToAllInstances(Prefab, callback); } [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] [return: <af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(1)] private static string getInternalName<T>(T value) where T : struct { return ((InternalName)typeof(T).GetMember(value.ToString())[0].GetCustomAttributes(typeof(InternalName)).First()).internalName; } private void registerRecipesInObjectDB(ObjectDB objectDB) { //IL_045a: Unknown result type (might be due to invalid IL or missing references) //IL_045f: Unknown result type (might be due to invalid IL or missing references) //IL_0492: Unknown result type (might be due to invalid IL or missing references) //IL_04a8: Expected O, but got Unknown activeRecipes[this] = new Dictionary<string, List<Recipe>>(); itemCraftConfigs.TryGetValue(this, out var value); foreach (KeyValuePair<string, ItemRecipe> recipe in Recipes) { List<Recipe> list = new List<Recipe>(); foreach (CraftingStationConfig station in recipe.Value.Crafting.Stations) { ItemConfig itemConfig = value?[recipe.Key]; Recipe val = ScriptableObject.CreateInstance<Recipe>(); string name = ((Object)Prefab).name; CraftingTable table = station.Table; ((Object)val).name = name + "_Recipe_" + table; val.m_amount = recipe.Value.CraftAmount; ConfigEntryBase recipeIsActive = recipe.Value.RecipeIsActive; val.m_enabled = (int)(((recipeIsActive != null) ? recipeIsActive.BoxedValue : null) ?? ((object)1)) != 0 && (itemConfig == null || itemConfig.table.Value != CraftingTable.Disabled); val.m_item = Prefab.GetComponent<ItemDrop>(); val.m_resources = SerializedRequirements.toPieceReqs(objectDB, (itemConfig?.craft == null) ? new SerializedRequirements(recipe.Value.RequiredItems.Requirements) : new SerializedRequirements(itemConfig.craft.Value), (itemConfig?.upgrade == null) ? new SerializedRequirements(recipe.Value.RequiredUpgradeItems.Requirements) : new SerializedRequirements(itemConfig.upgrade.Value)); table = ((itemConfig == null || list.Count > 0) ? station.Table : itemConfig.table.Value); if ((uint)table <= 1u) { val.m_craftingStation = null; } else if (((itemConfig == null || list.Count > 0) ? station.Table : itemConfig.table.Value) == CraftingTable.Custom) { GameObject prefab = ZNetScene.instance.GetPrefab((itemConfig == null || list.Count > 0) ? station.custom : itemConfig.customTable.Value); if (prefab != null) { val.m_craftingStation = prefab.GetComponent<CraftingStation>(); } else { Debug.LogWarning((object)("Custom crafting station '" + ((itemConfig == null || list.Count > 0) ? station.custom : itemConfig.customTable.Value) + "' does not exist")); } } else { val.m_craftingStation = ZNetScene.instance.GetPrefab(getInternalName((itemConfig == null || list.Count > 0) ? station.Table : itemConfig.table.Value)).GetComponent<CraftingStation>(); } val.m_minStationLevel = ((itemConfig == null || list.Count > 0) ? station.level : itemConfig.tableLevel.Value); val.m_requireOnlyOneIngredient = ((itemConfig == null) ? recipe.Value.RequireOnlyOneIngredient : (itemConfig.requireOneIngredient.Value == Toggle.On)); val.m_qualityResultAmountMultiplier = itemConfig?.qualityResultAmountMultiplier.Value ?? recipe.Value.QualityResultAmountMultiplier; list.Add(val); RequiredResourceList requiredItems; if (station.Table != 0) { requiredItems = recipe.Value.RequiredItems; if (requiredItems != null && !requiredItems.Free) { List<Requirement> requirements = requiredItems.Requirements; if (requirements != null && requirements.Count == 0) { hiddenCraftRecipes.Add(val, recipe.Value.RecipeIsActive); } } } requiredItems = recipe.Value.RequiredUpgradeItems; if (requiredItems != null && !requiredItems.Free) { List<Requirement> requirements = requiredItems.Requirements; if (requirements != null && requirements.Count == 0) { hiddenUpgradeRecipes.Add(val, recipe.Value.RecipeIsActive); } } } activeRecipes[this].Add(recipe.Key, list); objectDB.m_recipes.AddRange(list); } conversions = new List<ItemConversion>(); for (int i = 0; i < Conversions.Count; i++) { Conversion conversion = Conversions[i]; conversions.Add(new ItemConversion { m_from = SerializedRequirements.fetchByName(ObjectDB.instance, conversion.config?.input.Value ?? conversion.Input), m_to = Prefab.GetComponent<ItemDrop>() }); ConversionPiece conversionPiece = conversion.config?.piece.Value ?? conversion.Piece; string text = null; if (conversionPiece != 0 && conversions[i].m_from != null) { text = ((conversionPiece != ConversionPiece.Custom) ? getInternalName(conversionPiece) : (conversion.config?.customPiece.Value ?? conversion.customPiece)); GameObject prefab2 = ZNetScene.instance.GetPrefab(text); Smelter val2 = ((prefab2 != null) ? prefab2.GetComponent<Smelter>() : null); if (val2 != null) { val2.m_conversion.Add(conversions[i]); } else { text = null; } } if (conversion.config != null) { conversion.config.activePiece = text; } } } [HarmonyPriority(0)] internal static void Patch_ObjectDBInit(ObjectDB __instance) { if ((Object)(object)__instance.GetItemPrefab("Wood") == (Object)null) { return; } hiddenCraftRecipes.Clear(); hiddenUpgradeRecipes.Clear(); foreach (Item registeredItem in registeredItems) { registeredItem.registerRecipesInObjectDB(__instance); } } internal static void Patch_TraderGetAvailableItems(Trader __instance, ref List<TradeItem> __result) { string prefabName = Utils.GetPrefabName(((Component)__instance).gameObject); Trader trader2 = ((prefabName == "Haldor") ? Trader.Haldor : ((prefabName == "Hildir") ? Trader.Hildir : Trader.None)); Trader trader = trader2; __result.AddRange(from tuple in PrefabManager.CustomTradeItems.Values where (tuple.Item1 & trader) != 0 select tuple.Item2 into tradeItem where string.IsNullOrEmpty(tradeItem.m_requiredGlobalKey) || ZoneSystem.instance.GetGlobalKey(tradeItem.m_requiredGlobalKey) select tradeItem); } internal static void Patch_OnAddSmelterInput(ItemData item, bool __result) { if (__result) { ((Humanoid)Player.m_localPlayer).UnequipItem(item, true); } } internal static void Patch_MaximumRequiredStationLevel(Recipe __instance, ref int __result, int quality) { if (!itemDropMap.TryGetValue(__instance.m_item, out var value)) { return; } IEnumerable<ItemConfig> source; if (!itemCraftConfigs.TryGetValue(value, out var value2)) { source = Enumerable.Empty<ItemConfig>(); } else { CraftingStation currentCraftingStation = Player.m_localPlayer.GetCurrentCraftingStation(); if (currentCraftingStation != null) { string stationName = Utils.GetPrefabName(((Component)currentCraftingStation).gameObject); source = from c in value2.Where([<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] (KeyValuePair<string, ItemConfig> c) => { switch (c.Value.table.Value) { case CraftingTable.Disabled: case CraftingTable.Inventory: return false; case CraftingTable.Custom: return c.Value.customTable.Value == stationName; default: return getInternalName(c.Value.table.Value) == stationName; } }) select c.Value; } else { source = value2.Values; } } __result = Mathf.Min(Mathf.Max(1, __instance.m_minStationLevel) + (quality - 1), (from cfg in source where cfg.maximumTableLevel != null select cfg.maximumTableLevel.Value).DefaultIfEmpty(value.MaximumRequiredStationLevel).Max()); } internal static void Patch_GetAvailableRecipesPrefix([<af88efce-352b-493a-8b7e-30b8dff1c597>Nullable(new byte[] { 2, 1, 1, 1 })] ref Dictionary<Assembly, List<Recipe>> __state) { if (__state == null) { __state = new Dictionary<Assembly, List<Recipe>>(); } Dictionary<Recipe, ConfigEntryBase> source; if (InventoryGui.instance.InCraftTab()) { source = hiddenCraftRecipes; } else { if (!InventoryGui.instance.InUpradeTab()) { return; } source = hiddenUpgradeRecipes; } List<Recipe> list = (from kv in source select kv.Key into r where r.m_enabled select r).ToList(); __state[Assembly.GetExecutingAssembly()] = list; foreach (Recipe item in list) { item.m_enabled = false; } } internal static void Patch_GetAvailableRecipesFinalizer(Dictionary<Assembly, List<Recipe>> __state) { if (!__state.TryGetValue(Assembly.GetExecutingAssembly(), out var value)) { return; } foreach (Recipe item in value) { item.m_enabled = true; } } internal static IEnumerable<CodeInstruction> Transpile_SetupRequirementList(IEnumerable<CodeInstruction> instructionsEnumerable, ILGenerator ilg) { //IL_0150: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Expected O, but got Unknown //IL_0164: Unknown result type (might be due to invalid IL or missing references) //IL_016a: Expected O, but got Unknown //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_0181: Expected O, but got Unknown //IL_019c: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Expected O, but got Unknown //IL_01aa: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Expected O, but got Unknown //IL_01be: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Expected O, but got Unknown //IL_01cc: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Expected O, but got Unknown //IL_01e4: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Expected O, but got Unknown //IL_01f9: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Expected O, but got Unknown //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_021c: Unknown result type (might be due to invalid IL or missing references) //IL_0230: Expected O, but got Unknown //IL_0239: Unknown result type (might be due to invalid IL or missing references) //IL_023f: Expected O, but got Unknown List<CodeInstruction> list = instructionsEnumerable.ToList(); MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(InventoryGui), "SetupRequirement", (Type[])null, (Type[])null); CodeInstruction val = null; CodeInstruction val2 = null; LocalBuilder localBuilder = ilg.DeclareLocal(typeof(int)); Dictionary<Label, int> dictionary = new Dictionary<Label, int>(); bool flag = false; int num = 0; int value = 0; Label? label = default(Label?); for (int i = 0; i < list.Count; i++) { if (CodeInstructionExtensions.Calls(list[i], methodInfo)) { val = list[i + 2]; val2 = list[i + 5]; flag = true; } if (flag) { if (CodeInstructionExtensions.Branches(list[i], ref label) && dictionary.TryGetValue(label.Value, out value)) { num = i; break; } continue; } foreach (Label label4 in list[i].labels) { dictionary[label4] = i; } } if (list[value - 3].opcode == OpCodes.Dup) { return list; } Label label2 = ilg.DefineLabel(); Label label3 = ilg.DefineLabel(); list[num + 1].labels.Add(label2); list.InsertRange(num + 1, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[11] { new CodeInstruction(OpCodes.Ldloc, (object)localBuilder), new CodeInstruction(OpCodes.Brfalse, (object)label2), val.Clone(), new CodeInstruction(OpCodes.Ldarg_0, (object)null), new CodeInstruction(OpCodes.Ldfld, (object)AccessTools.DeclaredField(typeof(InventoryGui), "m_recipeRequirementList")), new CodeInstruction(OpCodes.Ldlen, (object)null), new CodeInstruction(OpCodes.Bgt, (object)label2), new CodeInstruction(OpCodes.Ldc_I4_0, (object)null), val2.Clone(), new CodeInstruction(OpCodes.Ldc_I4_0, (object)null), new CodeInstruction(OpCodes.Br, (object)label3) }); list.InsertRange(value - 2, (IEnumerable<CodeInstruction>)(object)new CodeInstruction[2] { new CodeInstruction(OpCodes.Dup, (object)null) { labels = new List<Label> { label3 } }, new CodeInstruction(OpCodes.Stloc, (object)localBuilder) }); return list; } internal static bool Patch_RequirementGetAmount(Requirement __instance, int qualityLevel, ref int __result) { if (requirementQuality.TryGetValue(__instance, out var value)) { __result = ((value.quality == qualityLevel) ? __instance.m_amountPerLevel : 0); return false; } return true; } internal static void Patch_ZNetSceneAwake(ZNetScene __instance) { foreach (Item registeredItem in registeredItems) { registeredItem.AssignDropToCreature(); } } public void AssignDropToCreature() { foreach (KeyValuePair<CharacterDrop, Drop> characterDrop in characterDrops) { if (Object.op_Implicit((Object)(object)characterDrop.Key)) { characterDrop.Key.m_drops.Remove(characterDrop.Value); } } characterDrops.Clear(); SerializedDrop serializedDrop = new SerializedDrop(DropsFrom.Drops); if (itemDropConfigs.TryGetValue(this, out var value)) { serializedDrop = new SerializedDrop(value.Value); } foreach (KeyValuePair<Character, Drop> item in serializedDrop.toCharacterDrops(ZNetScene.s_instance, Prefab)) { CharacterDrop val = ((Component)item.Key).GetComponent<CharacterDrop>(); if (val == null) { val = ((Component)item.Key).gameObject.AddComponent<CharacterDrop>(); } val.m_drops.Add(item.Value); characterDrops.Add(val, item.Value); } } public void UpdateCharacterDrop() { if (Object.op_Implicit((Object)(object)ZNetScene.instance)) { AssignDropToCreature(); } } public void Snapshot(float lightIntensity = 1.3f, Quaternion? cameraRotation = null, Quaternion? itemRotation = null) { SnapshotItem(Prefab.GetComponent<ItemDrop>(), lightIntensity, cameraRotation, itemRotation); } public static void SnapshotItem(ItemDrop item, float lightIntensity = 1.3f, Quaternion? cameraRotation = null, Quaternion? itemRotation = null) { if (Object.op_Implicit((Object)(object)ObjectDB.instance)) { Do(); } else { ((MonoBehaviour)plugin).StartCoroutine(Delay()); } IEnumerator Delay() { yield return null; Do(); } void Do() { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_016a: Unknown result type (might be due to invalid IL or missing references) //IL_01a7: Unknown result type (might be due to invalid IL or missing references) //IL_01cb: Unknown result type (might be due to invalid IL or missing references) //IL_01d0: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: Unknown result type (might be due to invalid IL or missing references) //IL_01fb: Unknown result type (might be due to invalid IL or missing references) //IL_01fd: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Unknown result type (might be due to invalid IL or missing references) //IL_0201: Unknown result type (might be due to invalid IL or missing references) //IL_0206: Unknown result type (might be due to invalid IL or missing references) //IL_0223: Unknown result type (might be due to invalid IL or missing references) //IL_022a: Unknown result type (might be due to invalid IL or missing references) //IL_0236: Unknown result type (might be due to invalid IL or missing references) //IL_023d: Unknown result type (might be due to invalid IL or missing references) //IL_0277: Unknown result type (might be due to invalid IL or missing references) //IL_0279: Unknown result type (might be due to invalid IL or missing references) //IL_027b: Unknown result type (might be due to invalid IL or missing references) //IL_0285: Unknown result type (might be due to invalid IL or missing references) //IL_028a: Unknown result type (might be due to invalid IL or missing references) //IL_028e: Unknown result type (might be due to invalid IL or missing references) //IL_029a: Unknown result type (might be due to invalid IL or missing references) //IL_02a8: Unknown result type (might be due to invalid IL or missing references) //IL_02ad: Unknown result type (might be due to invalid IL or missing references) //IL_02bf: Unknown result type (might be due to invalid IL or missing references) //IL_02d3: Unknown result type (might be due to invalid IL or missing references) //IL_02dd: Unknown result type (might be due to invalid IL or missing references) //IL_02e5: Unknown result type (might be due to invalid IL or missing references) //IL_02ea: Unknown result type (might be due to invalid IL or missing references) //IL_031c: Unknown result type (might be due to invalid IL or missing references) //IL_0323: Expected O, but got Unknown //IL_0325: Unknown result type (might be due to invalid IL or missing references) //IL_0353: Unknown result type (might be due to invalid IL or missing references) //IL_035e: Unknown result type (might be due to invalid IL or missing references) Camera component = new GameObject("Camera", new Type[1] { typeof(Camera) }).GetComponent<Camera>(); component.backgroundColor = Color.clear; component.clearFlags = (CameraClearFlags)2; component.fieldOfView = 0.5f; component.farClipPlane = 10000000f; component.cullingMask = 1073741824; ((Component)component).transform.rotation = (Quaternion)(((??)cameraRotation) ?? Quaternion.Euler(90f, 0f, 45f)); Light component2 = new GameObject("Light", new Type[1] { typeof(Light) }).GetComponent<Light>(); ((Component)component2).transform.rotation = Quaternion.Euler(150f, 0f, -5f); component2.type = (LightType)1; component2.cullingMask = 1073741824; component2.intensity = lightIntensity; Rect val = default(Rect); ((Rect)(ref val))..ctor(0f, 0f, 64f, 64f); Transform val2 = ((Component)item).transform.Find("attach"); GameObject val3; if (val2 != null) { val3 = Object.Instantiate<GameObject>(((Component)val2).gameObject); } else { ZNetView.m_forceDisableInit = true; val3 = Object.Instantiate<GameObject>(((Component)item).gameObject); ZNetView.m_forceDisableInit = false; } if (itemRotation.HasValue) { val3.transform.rotation = itemRotation.Value; } Transform[] componentsInChildren = val3.GetComponentsInChildren<Transform>(); for (int i = 0; i < componentsInChildren.Length; i++) { ((Component)componentsInChildren[i]).gameObject.layer = 30; } Renderer[] componentsInChildren2 = val3.GetComponentsInChildren<Renderer>(); Vector3 val4 = componentsInChildren2.Aggregate<Renderer, Vector3>(Vector3.positiveInfinity, [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] (Vector3 cur, Renderer renderer) => { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (!(renderer is ParticleSystemRenderer)) { Bounds bounds2 = renderer.bounds; return Vector3.Min(cur, ((Bounds)(ref bounds2)).min); } return cur; }); Vector3 val5 = componentsInChildren2.Aggregate<Renderer, Vector3>(Vector3.negativeInfinity, [<d2d3e167-740b-48fe-92ed-7bf9e2b4e8f8>NullableContext(0)] (Vector3 cur, Renderer renderer) => { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) if (!(renderer is ParticleSystemRenderer)) { Bounds bounds = renderer.bounds; return Vector3.Max(cur, ((Bounds)(ref bounds)).max); } return cur; }); Vector3 val6 = val5 - val4; component.targetTexture = RenderTexture.GetTemporary((int)((Rect)(ref val)).width, (int)((Rect)(ref val)).height); float num = Mathf.Max(val6.x, val6.z); float num2 = Mathf.Min(val6.x, val6.z); float num3 = (num + num2) / Mathf.Sqrt(2f) / Mathf.Tan(component.fieldOfView * ((float)Math.PI / 180f)); Transform transform = ((Component)component).transform; Vector3 val7 = (val4 + val5) / 2f; val7.y = val5.y; transform.position = val7 + new Vector3(0f, num3, 0f); ((Component)component2).transform.position = transform.position + new Vector3(-2f, 0f, 0.2f) / 3f * (0f - num3); component.Render(); RenderTexture active = RenderTexture.active; RenderTexture.active = component.targetTexture; Texture2D val8 = new Texture2D((int)((Rect)(ref val)).width, (int)((Rect)(ref val)).height, (TextureFormat)4, false); val8.ReadPixels(val, 0, 0); val8.Apply(); RenderTexture.active = active; item.m_itemData.m_shared.m_icons = (Sprite[
RaidSystem.dll
Decompiled 2 weeks ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Data.SqlTypes; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Dynamic; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Linq.Expressions; using System.Net; using System.Numerics; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Serialization; using System.Runtime.Serialization.Formatters; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using System.Xml; using System.Xml.Linq; using BepInEx; using BepInEx.Configuration; using Guilds; using HarmonyLib; using JetBrains.Annotations; using Jotunn.Managers; using Microsoft.CodeAnalysis; using Newtonsoft.Json; using Newtonsoft.Json.Bson; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using Newtonsoft.Json.Linq.JsonPath; using Newtonsoft.Json.Schema; using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Utilities; using ServerSync; using TMPro; using UnityEngine; using UnityEngine.Events; using UnityEngine.UI; [assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: CompilationRelaxations(8)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.0.0.0")] [module: UnverifiableCode] namespace RaidSystem { public class dWebHook { public string WebHookUrl { get; set; } public static void SendRaidMessage(string message) { string text = RaidSystemPlugin.WebhookUrl?.Value; if (string.IsNullOrWhiteSpace(text)) { text = ""; } dWebHook obj = new dWebHook(); obj.WebHookUrl = text; obj.SendMessage(message); } public void SendMessage(string message) { if (string.IsNullOrWhiteSpace(WebHookUrl) || string.IsNullOrWhiteSpace(message)) { return; } ThreadPool.QueueUserWorkItem(delegate { try { HttpWebRequest httpWebRequest = (HttpWebRequest)WebRequest.Create(WebHookUrl); httpWebRequest.ContentType = "application/json"; httpWebRequest.Method = "POST"; httpWebRequest.Timeout = 10000; string text = message.Replace("\\", "\\\\").Replace("\"", "\\\"").Replace("\n", "\\n") .Replace("\r", ""); byte[] bytes = Encoding.UTF8.GetBytes("{\"content\":\"" + text + "\"}"); httpWebRequest.ContentLength = bytes.Length; using (Stream stream = httpWebRequest.GetRequestStream()) { stream.Write(bytes, 0, bytes.Length); } using ((HttpWebResponse)httpWebRequest.GetResponse()) { } } catch (Exception ex) { Debug.LogWarning((object)("[RaidSystem] Webhook: " + ex.Message)); } }); } } internal class GUI { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static UnityAction <>9__8_0; internal void <LoadScoreboard>b__8_0() { _scoreboard.SetActive(false); } } private static GameObject _menu; private static readonly Dictionary<string, GameObject> _menuItems = new Dictionary<string, GameObject>(); private static GameObject _scoreboard; public static void ToggleMenu() { if ((Object)(object)_menu == (Object)null || ((Object)(object)_menu != (Object)null && !_menu.activeSelf)) { if (GUIManager.Instance == null) { Debug.LogError((object)"[RaidSystem] GUIManager null"); return; } if (!Object.op_Implicit((Object)(object)GUIManager.CustomGUIFront)) { Debug.LogError((object)"[RaidSystem] CustomGUI null"); return; } if (string.IsNullOrEmpty(GuildsIntegration.GetOwnGuildName())) { Player localPlayer = Player.m_localPlayer; if (localPlayer != null) { ((Character)localPlayer).Message((MessageType)2, "Entre em uma guild para usar o RaidSystem.", 0, (Sprite)null); } return; } LoadMenu(); } if ((Object)(object)_menu != (Object)null) { _menu.SetActive(!_menu.activeSelf); } } public static void ToggleScoreboard() { if ((Object)(object)_scoreboard != (Object)null) { _scoreboard.SetActive(!_scoreboard.activeSelf); return; } LoadScoreboard(); if ((Object)(object)_scoreboard != (Object)null) { _scoreboard.SetActive(true); } } public static void DestroyMenu() { if ((Object)(object)_menu != (Object)null) { _menu.SetActive(false); } } public static void LoadMenu() { //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_0180: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_01aa: Unknown result type (might be due to invalid IL or missing references) //IL_01ed: Unknown result type (might be due to invalid IL or missing references) //IL_0223: Unknown result type (might be due to invalid IL or missing references) //IL_0296: Unknown result type (might be due to invalid IL or missing references) //IL_02e2: Unknown result type (might be due to invalid IL or missing references) //IL_02f1: Unknown result type (might be due to invalid IL or missing references) //IL_0300: Unknown result type (might be due to invalid IL or missing references) //IL_034b: Unknown result type (might be due to invalid IL or missing references) //IL_035a: Unknown result type (might be due to invalid IL or missing references) //IL_0369: Unknown result type (might be due to invalid IL or missing references) //IL_03db: Unknown result type (might be due to invalid IL or missing references) //IL_03e5: Expected O, but got Unknown //IL_0404: Unknown result type (might be due to invalid IL or missing references) //IL_0484: Unknown result type (might be due to invalid IL or missing references) //IL_0493: Unknown result type (might be due to invalid IL or missing references) //IL_04a2: Unknown result type (might be due to invalid IL or missing references) //IL_04e6: Unknown result type (might be due to invalid IL or missing references) //IL_04f0: Expected O, but got Unknown if ((Object)(object)Player.m_localPlayer == (Object)null || GUIManager.Instance == null || !Object.op_Implicit((Object)(object)GUIManager.CustomGUIFront)) { return; } Object.Destroy((Object)(object)_menu); foreach (GameObject value in _menuItems.Values) { Object.Destroy((Object)(object)value); } _menuItems.Clear(); _menu = GUIManager.Instance.CreateWoodpanel(GUIManager.CustomGUIFront.transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0f, 0f), 500f, 700f, true); _menu.SetActive(false); PlayerInfo localPlayerInfo = RaidSystemPlugin.LocalPlayerInfo; string teamName = GuildsIntegration.GetOwnGuildName(); if (!string.IsNullOrEmpty(teamName)) { string text = localPlayerInfo?.Nick ?? ((Character)Player.m_localPlayer).m_nview.GetZDO().GetString("playerName", ""); GameObject val = GUIManager.Instance.CreateScrollView(_menu.transform, false, true, 8f, 50f, GUIManager.Instance.ValheimScrollbarHandleColorBlock, new Color(0.157f, 0.102f, 0.063f, 1f), 400f, 380f); ((RectTransform)val.transform).anchoredPosition = new Vector2(-20f, -50f); val.SetActive(true); _menuItems["scrollView"] = val; _menuItems["teamText"] = MakeText(teamName, _menu, new Vector2(200f, 650f), 30, 350f, 40f); _menuItems["playerNameText"] = MakeText(text, _menu, new Vector2(200f, 590f), 22, 350f, 50f); List<TerritoryInfo> territories = DataStore.Load().Territories; int num = territories.Count((TerritoryInfo t) => string.Equals(t.OwnerTeamId, teamName, StringComparison.OrdinalIgnoreCase)); _menuItems["territoriesText"] = MakeText($"Territories: {num}/{territories.Count}", _menu, new Vector2(370f, 617f), 18, 350f, 40f); GUIManager instance = GUIManager.Instance; string text2 = localPlayerInfo?.Description ?? ""; GameObject val2 = instance.CreateInputField(_menu.transform, new Vector2(0f, 0f), new Vector2(0f, 0f), new Vector2(160f, 555f), (ContentType)0, text2, 18, 270f, 33f); _menuItems["descInput"] = val2; GameObject val3 = GUIManager.Instance.CreateButton("Update", _menu.transform, new Vector2(0f, 0f), new Vector2(0f, 0f), new Vector2(360f, 555f), 90f, 35f); val3.SetActive(true); _menuItems["btnUpdate"] = val3; InputField inputComp = val2.GetComponent<InputField>(); inputComp.text = localPlayerInfo?.Description ?? ""; ((UnityEvent)val3.GetComponent<Button>().onClick).AddListener((UnityAction)delegate { RPCManager.SendPlayerRegistration(inputComp.text); }); _menuItems["teamMembersHeader"] = MakeText("Guild Members:", _menu, new Vector2(200f, 496f), 25, 350f, 40f); FillTeamMembers(val, teamName); Transform obj = val.transform.Find("Scroll View"); ScrollRect val4 = ((obj != null) ? ((Component)obj).GetComponent<ScrollRect>() : null); if ((Object)(object)val4 != (Object)null) { val4.verticalNormalizedPosition = 1f; } GameObject val5 = GUIManager.Instance.CreateButton("Close", _menu.transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0f, -300f), 170f, 45f); val5.SetActive(true); _menuItems["btnClose"] = val5; ((UnityEvent)val5.GetComponent<Button>().onClick).AddListener(new UnityAction(DestroyMenu)); } } public static void UpdateScoreboard() { if ((Object)(object)_scoreboard != (Object)null && _scoreboard.activeSelf) { LoadScoreboard(); } } private static void LoadScoreboard() { //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_01a8: Unknown result type (might be due to invalid IL or missing references) //IL_0225: Unknown result type (might be due to invalid IL or missing references) //IL_027a: 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_0298: Unknown result type (might be due to invalid IL or missing references) //IL_02d4: Unknown result type (might be due to invalid IL or missing references) //IL_02d9: Unknown result type (might be due to invalid IL or missing references) //IL_02df: Expected O, but got Unknown if (GUIManager.Instance == null || !Object.op_Implicit((Object)(object)GUIManager.CustomGUIFront)) { return; } bool active = (Object)(object)_scoreboard != (Object)null && _scoreboard.activeSelf; Object.Destroy((Object)(object)_scoreboard); _scoreboard = GUIManager.Instance.CreateWoodpanel(GUIManager.CustomGUIFront.transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(400f, 0f), 500f, 600f, true); MakeText(RaidSystemPlugin.ScoreboardTitle.Value, _scoreboard, new Vector2(250f, 560f), 28, 450f, 40f); List<PlayerScore> topPlayers = ScoreManager.GetTopPlayers(); int num = 510; int num2 = 0; while (num2 < topPlayers.Count && num > 100) { PlayerScore playerScore = topPlayers[num2]; MakeText($"#{num2 + 1} {playerScore.Nick} [{playerScore.TeamId}] K:{playerScore.Kills} D:{playerScore.Deaths} = {playerScore.TotalPoints}pts", _scoreboard, new Vector2(250f, (float)num), 15, 460f, 25f); num2++; num -= 28; } num -= 10; MakeText("--- Guild Ranking ---", _scoreboard, new Vector2(250f, (float)num), 18, 460f, 25f); num -= 35; foreach (var (arg, num3, num4) in ScoreManager.GetTeamRanking()) { if (num < 50) { break; } MakeText($"{arg} ({num4} members): {num3} pts", _scoreboard, new Vector2(250f, (float)num), 15, 460f, 25f); num -= 25; } GameObject val = GUIManager.Instance.CreateButton("Close", _scoreboard.transform, new Vector2(0.5f, 0.5f), new Vector2(0.5f, 0.5f), new Vector2(0f, -270f), 150f, 40f); val.SetActive(true); ButtonClickedEvent onClick = val.GetComponent<Button>().onClick; object obj = <>c.<>9__8_0; if (obj == null) { UnityAction val2 = delegate { _scoreboard.SetActive(false); }; <>c.<>9__8_0 = val2; obj = (object)val2; } ((UnityEvent)onClick).AddListener((UnityAction)obj); _scoreboard.SetActive(active); } private static void FillTeamMembers(GameObject scrollView, string teamName) { //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) Transform val = scrollView.transform.Find("Scroll View/Viewport/Content"); if ((Object)(object)val == (Object)null) { return; } List<string> teamMemberNicks = GuildsIntegration.GetTeamMemberNicks(teamName); foreach (string item in teamMemberNicks) { GUIManager.Instance.CreateText(item, val, new Vector2(0.5f, 1f), new Vector2(0.5f, 1f), new Vector2(0f, 0f), GUIManager.Instance.AveriaSerifBold, 20, GUIManager.Instance.ValheimOrange, true, Color.black, 300f, 25f, false); } } private static GameObject MakeText(string text, GameObject parent, Vector2 pos, int size, float w, float h) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) return GUIManager.Instance.CreateText(text, parent.transform, new Vector2(0f, 0f), new Vector2(0f, 0f), pos, GUIManager.Instance.AveriaSerifBold, size, GUIManager.Instance.ValheimOrange, true, Color.black, w, h, false); } } public static class GuildsIntegration { public static bool IsActive => API.IsLoaded(); public static string GetPlayerTeam(Player player) { if (IsActive) { Guild playerGuild = API.GetPlayerGuild(player); if (playerGuild != null) { return playerGuild.Name; } } return null; } public static string GetPlayerTeam(long playerID) { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) if (IsActive && (Object)(object)ZNet.instance != (Object)null) { foreach (PlayerInfo player in ZNet.instance.m_players) { ZDOID characterID = player.m_characterID; if (((ZDOID)(ref characterID)).UserID == playerID) { Guild playerGuild = API.GetPlayerGuild(PlayerReference.fromPlayerInfo(player)); if (playerGuild != null) { return playerGuild.Name; } break; } } } return null; } public static string GetOwnGuildName() { if (IsActive) { Guild ownGuild = API.GetOwnGuild(); if (ownGuild != null) { return ownGuild.Name; } } return null; } public static bool AreAllies(Player a, Player b) { if (IsActive) { Guild playerGuild = API.GetPlayerGuild(a); Guild playerGuild2 = API.GetPlayerGuild(b); if (playerGuild != null && playerGuild2 != null) { return playerGuild.Name == playerGuild2.Name; } } return false; } public static bool AreAllies(long playerA, long playerB) { string playerTeam = GetPlayerTeam(playerA); string playerTeam2 = GetPlayerTeam(playerB); return !string.IsNullOrEmpty(playerTeam) && !string.IsNullOrEmpty(playerTeam2) && string.Equals(playerTeam, playerTeam2, StringComparison.OrdinalIgnoreCase); } public static List<string> GetAllTeamNames() { if (IsActive) { List<Guild> guilds = API.GetGuilds(); if (guilds.Count > 0) { return guilds.Select((Guild g) => g.Name).ToList(); } } return new List<string>(); } public static List<string> GetTeamMemberNicks(string teamName) { if (IsActive) { Guild guild = API.GetGuild(teamName); if (guild != null) { return guild.Members.Keys.Select((PlayerReference m) => m.name).ToList(); } } return new List<string>(); } public static List<string> GetOnlineTeamMembers(string teamName) { if (IsActive) { Guild guild = API.GetGuild(teamName); if (guild != null) { return (from p in API.GetOnlinePlayers(guild) select p.name).ToList(); } } return new List<string>(); } public static Color GetGuildColor(string guildName) { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) if (IsActive) { Guild guild = API.GetGuild(guildName); Color result = default(Color); if (guild != null && !string.IsNullOrEmpty(guild.General.color) && ColorUtility.TryParseHtmlString(guild.General.color, ref result)) { return result; } } return ColorFromName(guildName); } public static Color ColorFromName(string name) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrEmpty(name)) { return Color.gray; } int num = 5381; foreach (char c in name) { num = (num << 5) + num + c; } float num2 = (float)Mathf.Abs(num % 360) / 360f; float num3 = 0.6f + (float)Mathf.Abs((num >> 8) % 30) / 100f; float num4 = 0.7f + (float)Mathf.Abs((num >> 16) % 20) / 100f; return Color.HSVToRGB(num2, num3, num4); } } [HarmonyPatch] public static class MapDrawer { public static void RefreshMap() { } [HarmonyPostfix] [HarmonyPatch(typeof(Minimap), "UpdateMap")] private static void OnUpdateMap(Minimap __instance) { //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) int value = RaidSystemPlugin.RadiusDrawMap.Value; if (value <= 0 || (Object)(object)__instance.m_mapTexture == (Object)null) { return; } RaidData raidData = DataStore.Load(); float num = default(float); float num2 = default(float); foreach (TerritoryInfo territory in raidData.Territories) { if (!string.IsNullOrEmpty(territory.OwnerTeamId)) { Color guildColor = GuildsIntegration.GetGuildColor(territory.OwnerTeamId); guildColor.a = RaidSystemPlugin.ColorAlpha.Value; __instance.WorldToMapPoint(new Vector3(territory.X, territory.Y, territory.Z), ref num, ref num2); Circle(__instance.m_mapTexture, (int)(num * (float)((Texture)__instance.m_mapTexture).width), (int)(num2 * (float)((Texture)__instance.m_mapTexture).height), value, guildColor); } } __instance.m_mapTexture.Apply(); } public static void Circle(Texture2D tex, int cx, int cy, int r, Color col) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) for (int i = 0; i <= r; i++) { int num = (int)Mathf.Ceil(Mathf.Sqrt((float)(r * r - i * i))); for (int j = 0; j <= num; j++) { tex.SetPixel(cx + i, cy + j, col); tex.SetPixel(cx - i, cy + j, col); tex.SetPixel(cx + i, cy - j, col); tex.SetPixel(cx - i, cy - j, col); } } } } [Serializable] public class PlayerInfo { public string Nick { get; set; } public string SteamId { get; set; } public string PlayerId { get; set; } public string Description { get; set; } public string TeamId { get; set; } } [Serializable] public class PlayerScore { public string PlayerId { get; set; } public string Nick { get; set; } public string TeamId { get; set; } public int Kills { get; set; } public int Deaths { get; set; } public int Conquests { get; set; } public int Defenses { get; set; } public int TotalPoints => Kills * RaidSystemPlugin.PointsPerKill.Value + Conquests * RaidSystemPlugin.PointsPerConquest.Value + Defenses * RaidSystemPlugin.PointsPerDefense.Value - Deaths * RaidSystemPlugin.PointsLostPerDeath.Value; } [Serializable] public class TerritoryInfo { public string Name { get; set; } public float X { get; set; } public float Y { get; set; } public float Z { get; set; } public string OwnerTeamId { get; set; } public long LastConquestTimestamp { get; set; } } [Serializable] public class RaidData { public List<PlayerInfo> Players { get; set; } = new List<PlayerInfo>(); public List<PlayerScore> Scores { get; set; } = new List<PlayerScore>(); public List<TerritoryInfo> Territories { get; set; } = new List<TerritoryInfo>(); public Dictionary<string, long> Cooldowns { get; set; } = new Dictionary<string, long>(); } public class RaidZone { public string Name { get; set; } public float X { get; set; } public float Z { get; set; } public float WardRadius { get; set; } public float PvpRadius { get; set; } public List<int> AllowedHoursUtc { get; set; } = new List<int>(); public Vector3 Position => new Vector3(X, 0f, Z); public bool IsInWardArea(Vector3 p) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) return Utils.DistanceXZ(p, Position) < WardRadius; } public bool IsInPvpArea(Vector3 p) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) return Utils.DistanceXZ(p, Position) < PvpRadius; } } public enum Toggle { On = 1, Off = 0 } public static class RaidDoorManager { private static float _nextMaintenance; public static void Update() { //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || Time.time < _nextMaintenance) { return; } _nextMaintenance = Time.time + 10f; Door[] array = Object.FindObjectsByType<Door>((FindObjectsSortMode)0); foreach (Door val in array) { if (!((Object)(object)val == (Object)null) && Util.IsRaidEnabledHere(((Component)val).transform.position) && Util.IsRaidDisabledThisTime(((Component)val).transform.position)) { CloseAndRepair(val); } } } public static void Breach(WearNTear wearNTear) { if (!((Object)(object)wearNTear == (Object)null)) { Repair(wearNTear); Door val = FindDoor(wearNTear); if ((Object)(object)val != (Object)null) { SetDoorState(val, open: true); } } } public static void CloseAndRepair(Door door) { if (!((Object)(object)door == (Object)null)) { WearNTear val = ((Component)door).GetComponent<WearNTear>() ?? ((Component)door).GetComponentInParent<WearNTear>(); if ((Object)(object)val != (Object)null) { Repair(val); } SetDoorState(door, open: false); } } public static void CloseAndRepair(WearNTear wearNTear) { if (!((Object)(object)wearNTear == (Object)null)) { Repair(wearNTear); Door val = FindDoor(wearNTear); if ((Object)(object)val != (Object)null) { SetDoorState(val, open: false); } } } public static float GetHealth(WearNTear wearNTear) { if ((Object)(object)wearNTear == (Object)null) { return 0f; } ZNetView val = FindNetView(wearNTear); float? obj; if (val == null) { obj = null; } else { ZDO zDO = val.GetZDO(); obj = ((zDO != null) ? new float?(zDO.GetFloat(ZDOVars.s_health, wearNTear.m_health)) : null); } return obj ?? wearNTear.m_health; } private static Door FindDoor(WearNTear wearNTear) { return ((Component)wearNTear).GetComponent<Door>() ?? ((Component)wearNTear).GetComponentInParent<Door>() ?? ((Component)wearNTear).GetComponentInChildren<Door>(); } private static ZNetView FindNetView(WearNTear wearNTear) { return ((Component)wearNTear).GetComponent<ZNetView>() ?? ((Component)wearNTear).GetComponentInParent<ZNetView>() ?? ((Component)wearNTear).GetComponentInChildren<ZNetView>(); } private static void Repair(WearNTear wearNTear) { try { ZNetView val = FindNetView(wearNTear); if (((val != null) ? val.GetZDO() : null) != null) { float health = wearNTear.m_health; val.GetZDO().Set(ZDOVars.s_health, health); val.GetZDO().Set("health", health); val.InvokeRPC(ZNetView.Everybody, "RPC_HealthChanged", new object[1] { health }); } } catch (Exception ex) { Debug.LogWarning((object)("[RaidSystem] Door repair failed: " + ex.Message)); } } private static void SetDoorState(Door door, bool open) { try { ZNetView component = ((Component)door).GetComponent<ZNetView>(); if ((Object)(object)component != (Object)null && component.IsValid()) { component.GetZDO().Set(ZDOVars.s_state, open ? 1 : 0, false); door.UpdateState(); return; } MethodInfo methodInfo = AccessTools.Method(typeof(Door), "SetState", new Type[1] { typeof(int) }, (Type[])null); if (methodInfo != null) { methodInfo.Invoke(door, new object[1] { open ? 1 : 0 }); } } catch (Exception ex) { Debug.LogWarning((object)("[RaidSystem] Door state change failed: " + ex.Message)); } } } public static class DataStore { private static readonly object _lock = new object(); private static RaidData _cache; private static string FilePath => Path.Combine(RaidSystemPlugin.FileDirectory, "RaidData.json"); public static RaidData Load() { lock (_lock) { if (_cache != null) { return _cache; } if (!Directory.Exists(RaidSystemPlugin.FileDirectory)) { Directory.CreateDirectory(RaidSystemPlugin.FileDirectory); } if (!File.Exists(FilePath)) { _cache = new RaidData(); Save(); return _cache; } try { string value = File.ReadAllText(FilePath); _cache = (string.IsNullOrEmpty(value) ? new RaidData() : (JsonConvert.DeserializeObject<RaidDataWrapper>(value)?.ToRaidData() ?? new RaidData())); } catch (Exception ex) { Debug.LogError((object)("[RaidSystem] Load error: " + ex.Message)); _cache = new RaidData(); } return _cache; } } public static void Save() { lock (_lock) { try { if (_cache != null) { if (!Directory.Exists(RaidSystemPlugin.FileDirectory)) { Directory.CreateDirectory(RaidSystemPlugin.FileDirectory); } RaidDataWrapper value = RaidDataWrapper.FromRaidData(_cache); string contents = JsonConvert.SerializeObject(value, Newtonsoft.Json.Formatting.Indented); string text = FilePath + ".tmp"; File.WriteAllText(text, contents); if (File.Exists(FilePath)) { File.Delete(FilePath); } File.Move(text, FilePath); } } catch (Exception ex) { Debug.LogError((object)("[RaidSystem] Save error: " + ex.Message)); } } } public static void Modify(Action<RaidData> action) { lock (_lock) { if (_cache == null) { Load(); } action(_cache); Save(); } } public static void Invalidate() { lock (_lock) { _cache = null; } } public static string Serialize() { lock (_lock) { if (_cache == null) { Load(); } return JsonConvert.SerializeObject(RaidDataWrapper.FromRaidData(_cache)); } } public static void Deserialize(string json) { lock (_lock) { try { _cache = JsonConvert.DeserializeObject<RaidDataWrapper>(json)?.ToRaidData() ?? new RaidData(); } catch { _cache = new RaidData(); } } } } [Serializable] public class RaidDataWrapper { [Serializable] public class CooldownEntry { public string key; public long timestamp; } public PlayerInfo[] players; public PlayerScore[] scores; public TerritoryInfo[] territories; public CooldownEntry[] cooldowns; public RaidData ToRaidData() { RaidData raidData = new RaidData(); if (players != null) { raidData.Players.AddRange(players); } if (scores != null) { raidData.Scores.AddRange(scores); } if (territories != null) { raidData.Territories.AddRange(territories); } if (cooldowns != null) { CooldownEntry[] array = cooldowns; foreach (CooldownEntry cooldownEntry in array) { raidData.Cooldowns[cooldownEntry.key] = cooldownEntry.timestamp; } } return raidData; } public static RaidDataWrapper FromRaidData(RaidData d) { RaidDataWrapper raidDataWrapper = new RaidDataWrapper { players = d.Players.ToArray(), scores = d.Scores.ToArray(), territories = d.Territories.ToArray() }; List<CooldownEntry> list = new List<CooldownEntry>(); foreach (KeyValuePair<string, long> cooldown in d.Cooldowns) { list.Add(new CooldownEntry { key = cooldown.Key, timestamp = cooldown.Value }); } raidDataWrapper.cooldowns = list.ToArray(); return raidDataWrapper; } } public static class CooldownManager { public static string GetTerritoryKey(Vector3 pos) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) RaidZone raidZoneAt = Util.GetRaidZoneAt(pos); if (raidZoneAt != null) { pos = raidZoneAt.Position; } int num = Mathf.RoundToInt(pos.x / 10f) * 10; int num2 = Mathf.RoundToInt(pos.z / 10f) * 10; return $"{num}_{num2}"; } public static bool IsOnCooldown(Vector3 pos) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) string key = GetTerritoryKey(pos); RaidData raidData = DataStore.Load(); if (!raidData.Cooldowns.TryGetValue(key, out var value)) { return false; } if (DateTimeOffset.UtcNow.ToUnixTimeSeconds() >= value) { DataStore.Modify(delegate(RaidData d) { d.Cooldowns.Remove(key); }); return false; } return true; } public static int GetRemainingMinutes(Vector3 pos) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) string territoryKey = GetTerritoryKey(pos); RaidData raidData = DataStore.Load(); if (!raidData.Cooldowns.TryGetValue(territoryKey, out var value)) { return 0; } long num = value - DateTimeOffset.UtcNow.ToUnixTimeSeconds(); return (num > 0) ? ((int)(num / 60) + 1) : 0; } public static void StartCooldown(Vector3 pos) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) int value = RaidSystemPlugin.RaidCooldownMinutes.Value; if (value > 0) { string key = GetTerritoryKey(pos); long end = DateTimeOffset.UtcNow.ToUnixTimeSeconds() + value * 60; DataStore.Modify(delegate(RaidData d) { d.Cooldowns[key] = end; }); Debug.Log((object)$"[RaidSystem] Cooldown: {key} for {value}min"); } } public static void ClearCooldown(Vector3 pos) { //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) DataStore.Modify(delegate(RaidData d) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) d.Cooldowns.Remove(GetTerritoryKey(pos)); }); } public static void ClearAllCooldowns() { DataStore.Modify(delegate(RaidData d) { d.Cooldowns.Clear(); }); } } public static class ScoreManager { public static void RecordKill(string pid, string nick, string team) { DataStore.Modify(delegate(RaidData d) { GetOrCreate(d, pid, nick, team).Kills++; }); } public static void RecordDeath(string pid, string nick, string team) { DataStore.Modify(delegate(RaidData d) { GetOrCreate(d, pid, nick, team).Deaths++; }); } public static void RecordConquest(string pid, string nick, string team) { DataStore.Modify(delegate(RaidData d) { GetOrCreate(d, pid, nick, team).Conquests++; }); } public static void RecordDefense(string pid, string nick, string team) { DataStore.Modify(delegate(RaidData d) { GetOrCreate(d, pid, nick, team).Defenses++; }); } public static List<PlayerScore> GetTopPlayers(int count = 10) { return DataStore.Load().Scores.OrderByDescending((PlayerScore s) => s.TotalPoints).Take(count).ToList(); } public static List<(string TeamId, int TotalPoints, int Members)> GetTeamRanking() { return (from g in DataStore.Load().Scores.Where((PlayerScore s) => !string.IsNullOrEmpty(s.TeamId)).GroupBy<PlayerScore, string>((PlayerScore s) => s.TeamId, StringComparer.OrdinalIgnoreCase) select (g.Key, g.Sum((PlayerScore s) => s.TotalPoints), g.Count()) into r orderby r.Item2 descending select r).ToList(); } public static PlayerScore GetPlayerScore(string pid) { return DataStore.Load().Scores.FirstOrDefault((PlayerScore s) => s.PlayerId == pid); } public static string SerializeScores() { StringBuilder stringBuilder = new StringBuilder(); foreach (PlayerScore score in DataStore.Load().Scores) { stringBuilder.Append(score.PlayerId).Append('\t').Append(score.Nick) .Append('\t') .Append(score.TeamId) .Append('\t') .Append(score.Kills) .Append('\t') .Append(score.Deaths) .Append('\t') .Append(score.Conquests) .Append('\t') .Append(score.Defenses) .Append('\n'); } return stringBuilder.ToString(); } public static List<PlayerScore> DeserializeScores(string raw) { List<PlayerScore> list = new List<PlayerScore>(); if (string.IsNullOrEmpty(raw)) { return list; } string[] array = raw.Split(new char[1] { '\n' }); foreach (string text in array) { if (!string.IsNullOrWhiteSpace(text)) { string[] array2 = text.Split(new char[1] { '\t' }); if (array2.Length >= 7) { list.Add(new PlayerScore { PlayerId = array2[0], Nick = array2[1], TeamId = array2[2], Kills = (int.TryParse(array2[3], out var result) ? result : 0), Deaths = (int.TryParse(array2[4], out var result2) ? result2 : 0), Conquests = (int.TryParse(array2[5], out var result3) ? result3 : 0), Defenses = (int.TryParse(array2[6], out var result4) ? result4 : 0) }); } } } return list; } public static string FormatLeaderboardForWebhook() { List<PlayerScore> topPlayers = GetTopPlayers(); if (topPlayers.Count == 0) { return "No scores yet."; } StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("**Leaderboard**\n```"); int num = 1; foreach (PlayerScore item in topPlayers) { stringBuilder.AppendLine($"#{num,-3} {item.Nick,-16} [{item.TeamId}] K:{item.Kills} D:{item.Deaths} C:{item.Conquests} Def:{item.Defenses} = {item.TotalPoints}pts"); num++; } stringBuilder.AppendLine("```\n**Guilds:**"); foreach (var (arg, num2, num3) in GetTeamRanking()) { stringBuilder.AppendLine($"> {arg} ({num3} members): **{num2}** pts"); } return stringBuilder.ToString(); } private static PlayerScore GetOrCreate(RaidData data, string pid, string nick, string team) { PlayerScore playerScore = data.Scores.FirstOrDefault((PlayerScore s) => s.PlayerId == pid); if (playerScore != null) { playerScore.Nick = nick; playerScore.TeamId = team; return playerScore; } PlayerScore playerScore2 = new PlayerScore { PlayerId = pid, Nick = nick, TeamId = team }; data.Scores.Add(playerScore2); return playerScore2; } } [HarmonyPatch] public class Patches { [HarmonyPatch(typeof(WearNTear), "Destroy")] public static class DestroyPatch { private static bool Prefix(WearNTear __instance) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)ZNet.instance == (Object)null) { return true; } Vector3 position = ((Component)__instance).transform.position; if (Util.IsRaidEnabledHere(position) && Util.IsRaidDoorOrGate(((Component)__instance).gameObject)) { if (_adminRemovingDoors.Contains(((Object)__instance).GetInstanceID())) { return true; } if (Util.IsRaidDisabledThisTime(position)) { RaidDoorManager.CloseAndRepair(__instance); } else { RaidDoorManager.Breach(__instance); } return false; } return true; } private static void Postfix(WearNTear __instance) { HandleWardDestroyed(__instance, "Destroy"); } } [HarmonyPatch(typeof(WearNTear), "RPC_Remove")] public static class RPCRemovePatch { [HarmonyPriority(800)] private static bool Prefix(WearNTear __instance, long sender) { //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)__instance == (Object)null || (Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer()) { return true; } Vector3 position = ((Component)__instance).transform.position; if (!Util.IsRaidEnabledHere(position) || !Util.IsRaidDoorOrGate(((Component)__instance).gameObject)) { return true; } if (!IsAdminSender(sender)) { return false; } _adminRemovingDoors.Add(((Object)__instance).GetInstanceID()); return true; } private static void Finalizer(WearNTear __instance) { if ((Object)(object)__instance != (Object)null) { _adminRemovingDoors.Remove(((Object)__instance).GetInstanceID()); } } } [HarmonyPatch(typeof(WearNTear), "RPC_Damage")] public static class RPCDamagePatch { [HarmonyPriority(0)] private static bool Prefix(WearNTear __instance, ref HitData hit, ZNetView ___m_nview) { //IL_001d: 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) //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) try { if ((Object)(object)___m_nview == (Object)null) { return false; } Vector3 position = ((Component)__instance).transform.position; bool flag = Util.IsRaidEnabledHere(position); bool flag2 = ((Object)((Component)__instance).gameObject).name.Contains("RaidWard"); bool flag3 = Util.IsRaidDoorOrGate(((Component)__instance).gameObject); if (flag2 && ZNet.instance.IsServer()) { Character attacker = hit.GetAttacker(); Player val = (Player)(object)((attacker is Player) ? attacker : null); if ((Object)(object)val != (Object)null) { _lastWardAttacker = (val.GetPlayerID().ToString(), ((Character)val).m_nview.GetZDO().GetString("playerName", ""), GuildsIntegration.GetPlayerTeam(val)); } } if (!flag) { return true; } if (Util.IsRaidDisabledThisTime(position)) { return false; } if (!flag2 && !flag3) { return false; } if (flag3) { return true; } hit.ApplyModifier(1f - RaidSystemPlugin.WardReductionDamage.Value / 100f); return true; } catch (Exception ex) { Debug.LogError((object)(ex.Message + " - " + ex.StackTrace)); return false; } } } [HarmonyPatch(typeof(WearNTear), "ApplyDamage")] public static class WearNTearApplyDamagePatch { [HarmonyPriority(800)] private static bool Prefix(WearNTear __instance, float damage, ref bool __result) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Unknown result type (might be due to invalid IL or missing references) //IL_00ae: Unknown result type (might be due to invalid IL or missing references) try { if ((Object)(object)__instance == (Object)null || damage <= 0f) { return true; } Vector3 position = ((Component)__instance).transform.position; if (!Util.IsRaidEnabledHere(position)) { return true; } if (IsRaidWard(__instance)) { if (Util.IsRaidDisabledThisTime(position)) { __result = true; return false; } float health = RaidDoorManager.GetHealth(__instance); if (health - damage <= 0f) { HandleWardDestroyed(__instance, "lethal damage"); } return true; } if (!Util.IsRaidDoorOrGate(((Component)__instance).gameObject)) { return true; } if (Util.IsRaidDisabledThisTime(position)) { RaidDoorManager.CloseAndRepair(__instance); __result = true; return false; } float health2 = RaidDoorManager.GetHealth(__instance); if (health2 - damage > 0f) { return true; } RaidDoorManager.Breach(__instance); __result = true; return false; } catch (Exception ex) { Debug.LogWarning((object)("[RaidSystem] Door lethal damage patch failed: " + ex.Message)); return true; } } } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] private static class ZNetOnNewConnectionPatch { public static void Postfix(ZNet __instance) { if (!__instance.IsServer()) { RaidSystemPlugin.SteamId = ZNet.GetUID().ToString(); } } } [HarmonyPatch(typeof(Game), "Logout")] public static class LogoutPatch { private static void Postfix() { hasAwake = false; _lastWardAttacker = default((string, string, string)); _handledWardDestructions.Clear(); _adminRemovingDoors.Clear(); } } [HarmonyPatch(typeof(Player), "OnSpawned")] public static class OnSpawnedPatch { private static void Postfix() { //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown if (!hasAwake) { hasAwake = true; ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "RaidSystem_RequestFullSync", new object[1] { (object)new ZPackage() }); } } } [HarmonyPatch(typeof(Player), "CheckCanRemovePiece")] public static class CheckCanRemovePiecePatch { [HarmonyPriority(0)] private static bool Prefix(Piece piece) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) return SynchronizationManager.Instance.PlayerIsAdmin || !Util.IsRaidEnabledHere(((Component)piece).transform.position); } } [HarmonyPatch(typeof(Player), "PlacePiece")] public static class NoBuildPatch { [HarmonyPriority(800)] private static bool Prefix(Piece piece, Player __instance) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) return SynchronizationManager.Instance.PlayerIsAdmin || !Util.IsRaidEnabledHere(((Component)__instance).transform.position); } } [HarmonyPatch(typeof(Door), "Interact")] public static class DoorInteractPatch { private static bool Prefix(Door __instance, Humanoid character) { //IL_0008: 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_0059: Unknown result type (might be due to invalid IL or missing references) try { if (!Util.IsRaidEnabledHere(((Component)__instance).transform.position)) { return true; } Player val = (Player)(object)((character is Player) ? character : null); if ((Object)(object)val == (Object)null) { return true; } if (Util.PlayerOwnsTerritory(val, ((Component)__instance).transform.position)) { return true; } string territoryOwner = Util.GetTerritoryOwner(((Component)__instance).transform.position); ((Character)val).Message((MessageType)2, string.IsNullOrEmpty(territoryOwner) ? "Territorio sem dono." : ("Acesso restrito a guild dominante: " + territoryOwner), 0, (Sprite)null); return false; } catch (Exception ex) { Debug.LogWarning((object)("[RaidSystem] Door access check failed: " + ex.Message)); return true; } } } [HarmonyPatch(typeof(Character), "ApplyDamage")] public static class ApplyDamagePatch { public static void Postfix(Character __instance, HitData hit) { //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Expected O, but got Unknown //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Expected O, but got Unknown try { if (!(__instance.GetHealth() > 0f) && !((Object)(object)hit.GetAttacker() == (Object)null) && hit.GetAttacker().IsPlayer() && __instance.IsPlayer() && ZNet.instance.IsServer()) { Player val = (Player)hit.GetAttacker(); Player val2 = (Player)__instance; string playerTeam = GuildsIntegration.GetPlayerTeam(val); string playerTeam2 = GuildsIntegration.GetPlayerTeam(val2); if (!string.IsNullOrEmpty(playerTeam) && !string.IsNullOrEmpty(playerTeam2) && !(playerTeam == playerTeam2)) { ScoreManager.RecordKill(val.GetPlayerID().ToString(), ((Character)val).m_nview.GetZDO().GetString("playerName", ""), playerTeam); ScoreManager.RecordDeath(val2.GetPlayerID().ToString(), ((Character)val2).m_nview.GetZDO().GetString("playerName", ""), playerTeam2); dWebHook.SendRaidMessage("**[Abate]** **" + ((Character)val).m_nview.GetZDO().GetString("playerName", "") + "** [" + playerTeam + "] eliminou **" + ((Character)val2).m_nview.GetZDO().GetString("playerName", "") + "** [" + playerTeam2 + "].\n" + ScoreManager.FormatLeaderboardForWebhook()); } } } catch (Exception ex) { Debug.Log((object)("ApplyDamage error: " + ex.Message)); } } } public static bool hasAwake; private static (string pid, string nick, string teamId) _lastWardAttacker; private static readonly HashSet<int> _handledWardDestructions = new HashSet<int>(); private static readonly HashSet<int> _adminRemovingDoors = new HashSet<int>(); private static bool IsRaidWard(WearNTear wearNTear) { if ((Object)(object)wearNTear == (Object)null) { return false; } GameObject val = (((Object)(object)wearNTear.m_piece != (Object)null) ? ((Component)wearNTear.m_piece).gameObject : ((Component)wearNTear).gameObject); return (Object)(object)val != (Object)null && ((Object)val).name.Contains("RaidWard"); } private static void HandleWardDestroyed(WearNTear wearNTear, string source) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer() || !IsRaidWard(wearNTear)) { return; } Vector3 position = ((Component)wearNTear).transform.position; if (!Util.IsRaidEnabledHere(position)) { return; } int instanceID = ((Object)wearNTear).GetInstanceID(); if (_handledWardDestructions.Add(instanceID)) { Quaternion rotation = ((Component)wearNTear).transform.rotation; Debug.Log((object)$"[RaidSystem] RaidWard destroyed by {source} at X:{position.x:F0} Z:{position.z:F0}; scheduling respawn."); if (_lastWardAttacker.pid != null && !string.IsNullOrEmpty(_lastWardAttacker.teamId)) { RPCManager.HandleConquest(_lastWardAttacker.pid, _lastWardAttacker.nick, _lastWardAttacker.teamId, position); } else { Debug.LogWarning((object)"[RaidSystem] RaidWard destroyed without a valid guild attacker; respawning without conquest."); } _lastWardAttacker = default((string, string, string)); Util.RespawnWard(position, rotation); } } private static bool IsAdminSender(long sender) { if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer()) { return false; } ZNetPeer peer = ZNet.instance.GetPeer(sender); object obj; if (peer == null) { obj = null; } else { ISocket socket = peer.m_socket; obj = ((socket != null) ? socket.GetHostName() : null); } string text = (string)obj; return !string.IsNullOrEmpty(text) && ZNet.instance.IsAdmin(text); } } [HarmonyPatch] internal class RPCManager { [HarmonyPatch(typeof(Game), "Start")] public static class GameStartPatch { public static void Postfix() { if (ZRoutedRpc.instance != null) { ZRoutedRpc.instance.Register<ZPackage>("RaidSystem_RequestFullSync", (Action<long, ZPackage>)RPC_RequestFullSync); ZRoutedRpc.instance.Register<ZPackage>("RaidSystem_FullSyncResponse", (Action<long, ZPackage>)RPC_FullSyncResponse); ZRoutedRpc.instance.Register<ZPackage>("RaidSystem_UpdatePlayerData", (Action<long, ZPackage>)RPC_UpdatePlayerData); ZRoutedRpc.instance.Register<ZPackage>("RaidSystem_RequestScores", (Action<long, ZPackage>)RPC_RequestScores); ZRoutedRpc.instance.Register<ZPackage>("RaidSystem_ScoresResponse", (Action<long, ZPackage>)RPC_ScoresResponse); ZRoutedRpc.instance.Register<ZPackage>("RaidSystem_Conquest", (Action<long, ZPackage>)RPC_ConquestNotification); Debug.Log((object)"[RaidSystem] RPCs registered."); } } } public static void RPC_RequestFullSync(long sender, ZPackage pkg) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown if (ZNet.instance.IsServer()) { ZPackage val = new ZPackage(); val.Write(DataStore.Serialize()); ZRoutedRpc.instance.InvokeRoutedRPC(sender, "RaidSystem_FullSyncResponse", new object[1] { val }); } } public static void RPC_FullSyncResponse(long sender, ZPackage pkg) { if (ZNet.instance.IsServer()) { return; } string text = pkg.ReadString(); if (string.IsNullOrEmpty(text)) { return; } DataStore.Deserialize(text); Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer != (Object)null) { string pid = localPlayer.GetPlayerID().ToString(); PlayerInfo playerInfo = (RaidSystemPlugin.LocalPlayerInfo = DataStore.Load().Players.FirstOrDefault((PlayerInfo p) => p.PlayerId == pid)); string ownGuildName = GuildsIntegration.GetOwnGuildName(); RaidSystemPlugin.HasTeam = !string.IsNullOrEmpty(ownGuildName); if (playerInfo != null) { playerInfo.TeamId = ownGuildName; } } GUI.LoadMenu(); } public static void RPC_UpdatePlayerData(long sender, ZPackage pkg) { if (!ZNet.instance.IsServer()) { return; } string nick = pkg.ReadString(); string steamId = pkg.ReadString(); string playerId = pkg.ReadString(); string desc = pkg.ReadString(); string teamId = pkg.ReadString(); if (long.TryParse(playerId, out var result)) { teamId = GuildsIntegration.GetPlayerTeam(result); } if (string.IsNullOrEmpty(teamId)) { return; } string previousTeam = null; DataStore.Modify(delegate(RaidData data) { PlayerInfo playerInfo = data.Players.FirstOrDefault((PlayerInfo p) => p.PlayerId == playerId); if (playerInfo == null) { playerInfo = new PlayerInfo(); data.Players.Add(playerInfo); } previousTeam = playerInfo.TeamId; playerInfo.Nick = nick; playerInfo.SteamId = steamId; playerInfo.PlayerId = playerId; playerInfo.Description = desc; playerInfo.TeamId = teamId; }); if (!string.Equals(previousTeam, teamId, StringComparison.OrdinalIgnoreCase)) { string text = (string.IsNullOrEmpty(previousTeam) ? "entrou na guild" : ("mudou de **" + previousTeam + "** para")); dWebHook.SendRaidMessage("**[RaidSystem]** " + nick + " " + text + " **" + teamId + "**."); } BroadcastFullSync(); } public static void BroadcastFullSync() { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown if (ZNet.instance.IsServer()) { ZPackage val = new ZPackage(); val.Write(DataStore.Serialize()); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "RaidSystem_FullSyncResponse", new object[1] { val }); } } public static void RPC_RequestScores(long sender, ZPackage pkg) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown if (ZNet.instance.IsServer()) { ZPackage val = new ZPackage(); val.Write(ScoreManager.SerializeScores()); ZRoutedRpc.instance.InvokeRoutedRPC(sender, "RaidSystem_ScoresResponse", new object[1] { val }); } } public static void RPC_ScoresResponse(long sender, ZPackage pkg) { if (!ZNet.instance.IsServer()) { List<PlayerScore> collection = ScoreManager.DeserializeScores(pkg.ReadString()); RaidData raidData = DataStore.Load(); raidData.Scores.Clear(); raidData.Scores.AddRange(collection); GUI.UpdateScoreboard(); } } public static void RPC_ConquestNotification(long sender, ZPackage pkg) { if (!ZNet.instance.IsServer()) { string text = pkg.ReadString(); string text2 = pkg.ReadString(); string text3 = pkg.ReadString(); float num = pkg.ReadSingle(); float num2 = pkg.ReadSingle(); int num3 = pkg.ReadInt(); string text4 = (string.IsNullOrEmpty(text3) ? $"X:{(int)num} Z:{(int)num2}" : text3); string text5 = text2 + " (" + text + ") " + RaidSystemPlugin.ConquestMessage.Value + " " + text4; if (num3 > 0) { text5 += $" [Protecao: {num3}min]"; } MessageHud instance = MessageHud.instance; if (instance != null) { instance.ShowMessage((MessageType)2, text5, 0, (Sprite)null, false); } } } public static void HandleConquest(string pid, string nick, string teamId, Vector3 pos) { //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Expected O, but got Unknown //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) if (!ZNet.instance.IsServer()) { return; } RaidZone raidZoneAt = Util.GetRaidZoneAt(pos); string zoneName = raidZoneAt?.Name ?? $"X:{(int)pos.x} Z:{(int)pos.z}"; Vector3 territoryPosition = raidZoneAt?.Position ?? pos; DataStore.Modify(delegate(RaidData data) { TerritoryInfo territoryInfo = data.Territories.FirstOrDefault((TerritoryInfo t) => string.Equals(t.Name, zoneName, StringComparison.OrdinalIgnoreCase)); if (territoryInfo == null) { territoryInfo = new TerritoryInfo { Name = zoneName }; data.Territories.Add(territoryInfo); } territoryInfo.X = territoryPosition.x; territoryInfo.Y = territoryPosition.y; territoryInfo.Z = territoryPosition.z; territoryInfo.OwnerTeamId = teamId; territoryInfo.LastConquestTimestamp = DateTimeOffset.UtcNow.ToUnixTimeSeconds(); }); ScoreManager.RecordConquest(pid, nick, teamId); ZPackage val = new ZPackage(); val.Write(nick); val.Write(teamId); val.Write(zoneName); val.Write(pos.x); val.Write(pos.z); val.Write(0); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.Everybody, "RaidSystem_Conquest", new object[1] { val }); string text = "**[Conquista]** **" + teamId + "** conquistou **" + zoneName + "** com **" + nick + "**.\n"; text += ScoreManager.FormatLeaderboardForWebhook(); dWebHook.SendRaidMessage(text); BroadcastFullSync(); } public static void SendPlayerRegistration(string desc = "") { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Expected O, but got Unknown Player localPlayer = Player.m_localPlayer; if (!((Object)(object)localPlayer == (Object)null)) { string ownGuildName = GuildsIntegration.GetOwnGuildName(); if (string.IsNullOrEmpty(ownGuildName)) { ((Character)localPlayer).Message((MessageType)2, "Entre em uma guild para usar o RaidSystem.", 0, (Sprite)null); return; } ZPackage val = new ZPackage(); val.Write(((Character)localPlayer).m_nview.GetZDO().GetString("playerName", "")); val.Write(RaidSystemPlugin.SteamId); val.Write(localPlayer.GetPlayerID().ToString()); val.Write(desc); val.Write(ownGuildName); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "RaidSystem_UpdatePlayerData", new object[1] { val }); } } } [BepInPlugin("Detalhes.RaidSystem", "RaidSystem", "2.0.0")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class RaidSystemPlugin : BaseUnityPlugin { public const string PluginGUID = "Detalhes.RaidSystem"; public const string PluginName = "RaidSystem"; public const string PluginVersion = "2.0.0"; public const string DefaultWebhookUrl = ""; private Harmony _harmony; private static readonly ConfigSync _configSync = new ConfigSync("Detalhes.RaidSystem") { DisplayName = "RaidSystem", CurrentVersion = "2.0.0", MinimumRequiredVersion = "2.0.0" }; public static readonly string ModPath = Path.GetDirectoryName(typeof(RaidSystemPlugin).Assembly.Location); public static readonly string FileDirectory = Path.Combine(Paths.ConfigPath, "RaidSystem"); public static PlayerInfo LocalPlayerInfo; public static bool HasTeam = false; public static string SteamId = ""; private static ConfigEntry<Toggle> _serverConfigLocked; public static ConfigEntry<string> RaidTimeToAllowUtc; public static ConfigEntry<string> RaidEnabledPositions; public static ConfigEntry<int> AreaRadius; public static ConfigEntry<float> WardReductionDamage; public static ConfigEntry<int> HitPoints; public static ConfigEntry<int> SpawnDelayMS; public static ConfigEntry<int> Scale; public static ConfigEntry<int> RaidCooldownMinutes; public static ConfigEntry<int> PointsPerKill; public static ConfigEntry<int> PointsPerConquest; public static ConfigEntry<int> PointsPerDefense; public static ConfigEntry<int> PointsLostPerDeath; public static ConfigEntry<float> ColorAlpha; public static ConfigEntry<int> RadiusDrawMap; public static ConfigEntry<string> WebhookUrl; public static ConfigEntry<string> ConquestMessage; public static ConfigEntry<string> ScoreboardTitle; public static ConfigEntry<KeyCode> KeyboardShortcut; public static ConfigEntry<KeyCode> ScoreboardShortcut; public static RaidSystemPlugin Instance { get; private set; } public static bool GuildsInstalled { get; private set; } private ConfigEntry<T> config<T>(string group, string name, T value, ConfigDescription desc, bool sync = true) { ConfigEntry<T> val = ((BaseUnityPlugin)this).Config.Bind<T>(group, name, value, desc); SyncedConfigEntry<T> syncedConfigEntry = _configSync.AddConfigEntry<T>(val); syncedConfigEntry.SynchronizedConfig = sync; return val; } private ConfigEntry<T> config<T>(string group, string name, T value, string desc, bool sync = 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(desc, (AcceptableValueBase)null, Array.Empty<object>()), sync); } private void Awake() { //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown Instance = this; ((BaseUnityPlugin)this).Config.SaveOnConfigSet = true; GuildsInstalled = API.IsLoaded(); ((BaseUnityPlugin)this).Logger.LogInfo((object)$"Guilds mod active: {GuildsInstalled}"); BindConfigs(); WriteDefaultConfigExample(); WardSetup.LoadAssets(); _harmony = new Harmony("Detalhes.RaidSystem"); _harmony.PatchAll(); ((BaseUnityPlugin)this).Logger.LogInfo((object)"RaidSystem v2.0.0 loaded."); } private void Update() { //IL_003c: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Expected O, but got Unknown //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Expected O, but got Unknown RaidDoorManager.Update(); Player localPlayer = Player.m_localPlayer; if (Object.op_Implicit((Object)(object)localPlayer) && !((Character)localPlayer).IsDead() && !((Character)localPlayer).InCutscene() && !((Character)localPlayer).IsTeleporting()) { if (Input.GetKeyDown(KeyboardShortcut.Value)) { GUI.ToggleMenu(); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "RaidSystem_RequestFullSync", new object[1] { (object)new ZPackage() }); } if (Input.GetKeyDown(ScoreboardShortcut.Value)) { GUI.ToggleScoreboard(); ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "RaidSystem_RequestScores", new object[1] { (object)new ZPackage() }); } } } private void OnDestroy() { Harmony harmony = _harmony; if (harmony != null) { harmony.UnpatchSelf(); } } private void BindConfigs() { _serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, "Only admins can change config."); _configSync.AddLockingConfigEntry<Toggle>(_serverConfigLocked); RaidTimeToAllowUtc = config("2 - Raid Rules", "Raid Hours (UTC)", "0-24", "Global UTC hours when raids are enabled. Supports ranges like 18-24, comma lists like 18,19,20, or * for all day."); RaidEnabledPositions = config("2 - Raid Rules", "Raid Zones", "", "Named zones: name,x,z,wardRadius,pvpRadius[,hoursUtc]|... Per-zone hours use UTC ranges separated by semicolon, for example Castelo,500,300,150,300,18-24;0-2. Empty disables territorial raid rules."); AreaRadius = config("2 - Raid Rules", "Area Radius", 150, "Radius around ward for raid zone."); WardReductionDamage = config("2 - Raid Rules", "Ward Damage Reduction %", 99f, "Damage reduction % on structures."); HitPoints = config("2 - Raid Rules", "Ward HP", 10000, "Hit points of raid ward."); SpawnDelayMS = config("2 - Raid Rules", "Respawn Delay (ms)", 5000, "Delay before ward respawns."); Scale = config("2 - Raid Rules", "Ward Scale", 3, "Scale multiplier of ward object."); RaidCooldownMinutes = config("3 - Cooldown", "Cooldown Minutes", 0, "Legacy setting. Raid availability is controlled by Raid Hours (UTC)."); PointsPerKill = config("4 - Scoring", "Points Per Kill", 10, "Points per enemy kill."); PointsPerConquest = config("4 - Scoring", "Points Per Conquest", 50, "Points for conquering territory."); PointsPerDefense = config("4 - Scoring", "Points Per Defense", 25, "Points for defending territory."); PointsLostPerDeath = config("4 - Scoring", "Points Lost Per Death", 3, "Points lost on death."); ColorAlpha = config("6 - Visual", "Map Color Alpha", 0.7f, "Territory overlay transparency."); RadiusDrawMap = config("6 - Visual", "Map Draw Radius", 30, "Territory circle radius on map."); WebhookUrl = config("7 - Integration", "Discord Webhook URL", "", "Discord webhook for RaidSystem notifications."); ConquestMessage = config("8 - UI Text", "Conquest Message", "conquistou o território em:", "Conquest notification text."); ScoreboardTitle = config("8 - UI Text", "Scoreboard Title", "Ranking de Guerra", "Scoreboard title."); KeyboardShortcut = config<KeyCode>("9 - Client", "Menu Key", (KeyCode)280, "Open raid menu.", sync: false); ScoreboardShortcut = config<KeyCode>("9 - Client", "Scoreboard Key", (KeyCode)281, "Open scoreboard.", sync: false); } private void WriteDefaultConfigExample() { try { if (!Directory.Exists(FileDirectory)) { Directory.CreateDirectory(FileDirectory); } string text = Path.Combine(FileDirectory, "RaidSystem.Default.cfg"); StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("## RaidSystem default configuration example"); stringBuilder.AppendLine("## Copy values from this file into BepInEx/config/Detalhes.RaidSystem.cfg if needed."); stringBuilder.AppendLine("## Raid Hours use UTC, not local server time."); stringBuilder.AppendLine("## Raid Zones format: name,x,z,wardRadius,pvpRadius[,hoursUtc]|name,x,z,wardRadius,pvpRadius[,hoursUtc]"); stringBuilder.AppendLine("## Per-zone hours use UTC ranges like 6-18 or 18-6. End hour is exclusive."); stringBuilder.AppendLine("## Because Raid Zones uses commas between fields, multiple per-zone hour windows must use semicolon: 18-24;0-2;6."); stringBuilder.AppendLine(); AppendConfig(stringBuilder, "1 - General", "Lock Configuration", "On", "Only admins can change synchronized config."); AppendConfig(stringBuilder, "2 - Raid Rules", "Raid Hours (UTC)", "18-24", "Global fallback hours when a zone has no own hours. Example opens from 18:00 through 23:59 UTC."); AppendConfig(stringBuilder, "2 - Raid Rules", "Raid Zones", "Castelo,500,300,150,300,18-24;0-2|Porto,800,-200,120,250,6-18|Arena,0,0,200,400,*", "Example named raid areas with optional per-zone UTC hours. Empty disables territorial raid rules."); AppendConfig(stringBuilder, "2 - Raid Rules", "Area Radius", "150", "Fallback ward radius when a zone does not specify one."); AppendConfig(stringBuilder, "2 - Raid Rules", "Ward Damage Reduction %", "99", "Damage reduction applied to RaidWard damage."); AppendConfig(stringBuilder, "2 - Raid Rules", "Ward HP", "10000", "RaidWard health."); AppendConfig(stringBuilder, "2 - Raid Rules", "Respawn Delay (ms)", "5000", "Delay before RaidWard respawns after conquest."); AppendConfig(stringBuilder, "2 - Raid Rules", "Ward Scale", "3", "RaidWard visual scale."); AppendConfig(stringBuilder, "3 - Cooldown", "Cooldown Minutes", "0", "Legacy setting. Raid availability is controlled by Raid Hours (UTC)."); AppendConfig(stringBuilder, "4 - Scoring", "Points Per Kill", "10", "Points per enemy kill."); AppendConfig(stringBuilder, "4 - Scoring", "Points Per Conquest", "50", "Points per conquered territory."); AppendConfig(stringBuilder, "4 - Scoring", "Points Per Defense", "25", "Reserved defense score value."); AppendConfig(stringBuilder, "4 - Scoring", "Points Lost Per Death", "3", "Points lost per death."); AppendConfig(stringBuilder, "6 - Visual", "Map Color Alpha", "0.7", "Territory overlay transparency."); AppendConfig(stringBuilder, "6 - Visual", "Map Draw Radius", "30", "Territory circle radius on minimap texture."); AppendConfig(stringBuilder, "7 - Integration", "Discord Webhook URL", "", "Discord webhook used for guild, kill, and conquest notifications."); AppendConfig(stringBuilder, "8 - UI Text", "Conquest Message", "conquistou o territorio em:", "Center-screen conquest notification text."); AppendConfig(stringBuilder, "8 - UI Text", "Scoreboard Title", "Ranking de Guerra", "Scoreboard title."); AppendConfig(stringBuilder, "9 - Client", "Menu Key", "PageUp", "Client key to open the raid menu."); AppendConfig(stringBuilder, "9 - Client", "Scoreboard Key", "PageDown", "Client key to open the scoreboard."); File.WriteAllText(text, stringBuilder.ToString(), Encoding.UTF8); ((BaseUnityPlugin)this).Logger.LogInfo((object)("RaidSystem default config example written to " + text)); } catch (Exception ex) { ((BaseUnityPlugin)this).Logger.LogWarning((object)("Could not write RaidSystem default config example: " + ex.Message)); } } private static void AppendConfig(StringBuilder sb, string section, string key, string value, string description) { sb.AppendLine("[" + section + "]"); sb.AppendLine("## " + description); sb.AppendLine(key + " = " + value); sb.AppendLine(); } } public static class Util { private static List<RaidZone> _cachedZones; private static string _cachedZoneString; public static List<RaidZone> GetRaidZones() { string value = RaidSystemPlugin.RaidEnabledPositions.Value; if (_cachedZones != null && _cachedZoneString == value) { return _cachedZones; } _cachedZoneString = value; _cachedZones = ParseZones(value); return _cachedZones; } private static List<RaidZone> ParseZones(string cfg) { List<RaidZone> list = new List<RaidZone>(); if (string.IsNullOrWhiteSpace(cfg)) { return list; } string[] array = cfg.Split(new char[1] { '|' }); foreach (string text in array) { if (!string.IsNullOrWhiteSpace(text)) { string[] array2 = text.Split(new char[1] { ',' }); if (array2.Length >= 3 && float.TryParse(array2[1].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result) && float.TryParse(array2[2].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out var result2)) { float result3; float num = ((array2.Length > 3 && float.TryParse(array2[3].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out result3)) ? result3 : ((float)RaidSystemPlugin.AreaRadius.Value)); float result4; float pvpRadius = ((array2.Length > 4 && float.TryParse(array2[4].Trim(), NumberStyles.Float, CultureInfo.InvariantCulture, out result4)) ? result4 : num); list.Add(new RaidZone { Name = array2[0].Trim(), X = result, Z = result2, WardRadius = num, PvpRadius = pvpRadius, AllowedHoursUtc = ((array2.Length > 5) ? ParseHours(array2[5], allowComma: false) : new List<int>()) }); } } } return list; } private static List<int> ParseHours(string cfg, bool allowComma) { HashSet<int> hashSet = new HashSet<int>(); if (string.IsNullOrWhiteSpace(cfg)) { return hashSet.ToList(); } if (cfg.Trim().Equals("*", StringComparison.OrdinalIgnoreCase) || cfg.Trim().Equals("all", StringComparison.OrdinalIgnoreCase)) { return Enumerable.Range(0, 24).ToList(); } char[] separator = ((!allowComma) ? new char[1] { ';' } : new char[2] { ',', ';' }); string[] array = cfg.Split(separator); foreach (string text in array) { string text2 = text.Trim(); if (string.IsNullOrWhiteSpace(text2)) { continue; } string[] array2 = text2.Split(new char[1] { '-' }); int result3; if (array2.Length == 2 && int.TryParse(array2[0].Trim(), out var result) && int.TryParse(array2[1].Trim(), out var result2)) { int num = NormalizeHour(result); int num2 = NormalizeHour(result2); if (num == num2 && result != result2) { foreach (int item in Enumerable.Range(0, 24)) { hashSet.Add(item); } } else { for (int num3 = num; num3 != num2; num3 = NormalizeHour(num3 + 1)) { hashSet.Add(num3); } } } else if (int.TryParse(text2, out result3)) { hashSet.Add(NormalizeHour(result3)); } } return hashSet.OrderBy((int h) => h).ToList(); } private static int NormalizeHour(int hour) { hour %= 24; return (hour < 0) ? (hour + 24) : hour; } public static string GetZoneNameAt(Vector3 pos) { //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 (string.IsNullOrWhiteSpace(RaidSystemPlugin.RaidEnabledPositions.Value)) { return null; } return GetRaidZones().FirstOrDefault((RaidZone z) => z.IsInWardArea(pos))?.Name; } public static RaidZone GetRaidZoneAt(Vector3 pos) { //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 (string.IsNullOrWhiteSpace(RaidSystemPlugin.RaidEnabledPositions.Value)) { return null; } return GetRaidZones().FirstOrDefault((RaidZone z) => z.IsInWardArea(pos)); } public static TerritoryInfo GetTerritoryAt(Vector3 pos) { //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) //IL_0010: Unknown result type (might be due to invalid IL or missing references) RaidZone zone = GetRaidZoneAt(pos); RaidData raidData = DataStore.Load(); if (zone != null) { TerritoryInfo territoryInfo = raidData.Territories.FirstOrDefault((TerritoryInfo t) => string.Equals(t.Name, zone.Name, StringComparison.OrdinalIgnoreCase)); if (territoryInfo != null) { return territoryInfo; } } return raidData.Territories.FirstOrDefault((TerritoryInfo t) => Utils.DistanceXZ(pos, new Vector3(t.X, t.Y, t.Z)) < (float)RaidSystemPlugin.AreaRadius.Value); } public static string GetTerritoryOwner(Vector3 pos) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return GetTerritoryAt(pos)?.OwnerTeamId; } public static bool PlayerOwnsTerritory(Player player, Vector3 pos) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)player == (Object)null) { return false; } string territoryOwner = GetTerritoryOwner(pos); if (string.IsNullOrEmpty(territoryOwner)) { return true; } string playerTeam = GuildsIntegration.GetPlayerTeam(player); return !string.IsNullOrEmpty(playerTeam) && string.Equals(playerTeam, territoryOwner, StringComparison.OrdinalIgnoreCase); } public static bool IsRaidDoorOrGate(GameObject gameObject) { if ((Object)(object)gameObject == (Object)null) { return false; } if ((Object)(object)gameObject.GetComponent<Door>() != (Object)null || (Object)(object)gameObject.GetComponentInParent<Door>() != (Object)null || (Object)(object)gameObject.GetComponentInChildren<Door>() != (Object)null) { return true; } string text = ((Object)gameObject).name.ToLowerInvariant(); return text.Contains("door") || text.Contains("gate") || text.Contains("portao"); } public static bool IsRaidEnabledHere(Vector3 position) { //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 (string.IsNullOrWhiteSpace(RaidSystemPlugin.RaidEnabledPositions.Value)) { return false; } return GetRaidZones().Any((RaidZone z) => z.IsInWardArea(position)); } public static bool IsRaidDisabledThisTime() { return !ParseHours(RaidSystemPlugin.RaidTimeToAllowUtc.Value, allowComma: true).Contains(DateTime.UtcNow.Hour); } public static bool IsRaidDisabledThisTime(Vector3 position) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) RaidZone raidZoneAt = GetRaidZoneAt(position); if (raidZoneAt?.AllowedHoursUtc != null && raidZoneAt.AllowedHoursUtc.Count > 0) { return !raidZoneAt.AllowedHoursUtc.Contains(DateTime.UtcNow.Hour); } return IsRaidDisabledThisTime(); } public static void RespawnWard(Vector3 position, Quaternion rotation) { //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer()) { Debug.LogWarning((object)"[RaidSystem] RaidWard respawn requested outside server context."); return; } if ((Object)(object)RaidSystemPlugin.Instance == (Object)null) { Debug.LogWarning((object)"[RaidSystem] RaidWard respawn requested before plugin instance was ready."); return; } Debug.Log((object)$"[RaidSystem] RaidWard respawn scheduled at X:{position.x:F0} Z:{position.z:F0} in {RaidSystemPlugin.SpawnDelayMS.Value}ms."); ((MonoBehaviour)RaidSystemPlugin.Instance).StartCoroutine(RespawnWardRoutine(position, rotation)); } private static IEnumerator RespawnWardRoutine(Vector3 position, Quaternion rotation) { //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) //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) yield return (object)new WaitForSeconds(Mathf.Max(0f, (float)RaidSystemPlugin.SpawnDelayMS.Value / 1000f)); ZNetScene instance = ZNetScene.instance; GameObject prefab = ((instance != null) ? instance.GetPrefab("RaidWard") : null); if ((Object)(object)prefab == (Object)null) { Debug.LogWarning((object)"[RaidSystem] RaidWard prefab not found for respawn."); yield break; } GameObject ward = Object.Instantiate<GameObject>(prefab, position, rotation); WearNTear wearNTear = ward.GetComponent<WearNTear>(); ZNetView nview = ward.GetComponent<ZNetView>(); int num; if ((Object)(object)wearNTear != (Object)null) { num = ((((nview != null) ? nview.GetZDO() : null) != null) ? 1 : 0); } else { num = 0; } if (num != 0) { nview.GetZDO().Set(ZDOVars.s_health, wearNTear.m_health); } Debug.Log((object)$"[RaidSystem] RaidWard respawned at X:{position.x:F0} Z:{position.z:F0}."); } public static bool CheckInPrivateArea(Vector3 point, bool flash = false) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) foreach (PrivateArea allArea in PrivateArea.m_allAreas) { if (((Object)((Component)allArea.m_piece).gameObject).name.Contains("dverger_guardstone") || !allArea.IsEnabled() || !allArea.IsInside(point, 0f)) { continue; } if (flash) { allArea.FlashShield(false); } return true; } return false; } } [HarmonyPatch] public static class WardSetup { private static bool _registeredInHammer; public static GameObject RaidWardPrefab { get; private set; } public static void LoadAssets() { PrefabManager.OnPrefabsRegistered += AddRaidWardPrefab; PieceManager.OnPiecesRegistered += RegisterRaidWardPiece; } private static void AddRaidWardPrefab() { //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)RaidWardPrefab != (Object)null) { return; } GameObject prefab = PrefabManager.Instance.GetPrefab("guard_stone"); RaidWardPrefab = PrefabManager.Instance.CreateClonedPrefab("RaidWard", "guard_stone"); if ((Object)(object)RaidWardPrefab == (Object)null) { Debug.LogError((object)"[RaidSystem] guard_stone not found for RaidWard clone!"); return; } float num = RaidSystemPlugin.Scale.Value; RaidWardPrefab.transform.localScale = Vector3.one * num; WearNTear component = RaidWardPrefab.GetComponent<WearNTear>(); if ((Object)(object)component != (Object)null) { component.m_health = RaidSystemPlugin.HitPoints.Value; component.m_noRoofWear = false; component.m_noSupportWear = false; } Piece component2 = RaidWardPrefab.GetComponent<Piece>(); if ((Object)(object)component2 != (Object)null) { Piece val = (((Object)(object)prefab != (Object)null) ? prefab.GetComponent<Piece>() : null); component2.m_name = "Raid Ward"; component2.m_description = "Territorial ward for faction warfare."; component2.m_comfort = 0; if ((Object)(object)component2.m_icon == (Object)null && (Object)(object)val != (Object)null) { component2.m_icon = val.m_icon; } ConfigureRequirements(component2); } PrivateArea component3 = RaidWardPrefab.GetComponent<PrivateArea>(); if ((Object)(object)component3 != (Object)null) { component3.m_radius = RaidSystemPlugin.AreaRadius.Value; component3.m_name = "RaidWard"; } TintVisuals(RaidWardPrefab); AddGlow(RaidWardPrefab); RemoveServerUnsafeVisualComponents(RaidWardPrefab); PrefabManager.OnPrefabsRegistered -= AddRaidWardPrefab; Debug.Log((object)$"[RaidSystem] RaidWard created: scale={num}, HP={RaidSystemPlugin.HitPoints.Value}"); } private static void RegisterRaidWardPiece() { if (!_registeredInHammer) { if ((Object)(object)RaidWardPrefab == (Object)null) { AddRaidWardPrefab(); } if (!((Object)(object)RaidWardPrefab == (Object)null)) { PieceManager.Instance.RegisterPieceInPieceTable(RaidWardPrefab, "Hammer", "Misc"); _registeredInHammer = true; PieceManager.OnPiecesRegistered -= RegisterRaidWardPiece; Debug.Log((object)"[RaidSystem] RaidWard added to hammer using Jotunn PieceManager."); } } } [HarmonyPrefix] [HarmonyPatch(typeof(ZNetScene), "GetPrefabNames")] [HarmonyPriority(0)] private static bool ZNetScene_GetPrefabNames(ZNetScene __instance, ref List<string> __result) { __instance.m_prefabs.RemoveAll((GameObject prefab) => (Object)(object)prefab == (Object)null); __result = (from prefab in __instance.m_prefabs where (Object)(object)prefab != (Object)null select ((Object)prefab).name into name where !string.IsNullOrEmpty(name) select name).ToList(); return false; } [HarmonyPatch(typeof(Player), "UpdateKnownRecipesList")] [HarmonyPrefix] private static void Player_UpdateKnownRecipesList() { CleanPieceTables(); } private static void CleanPieceTables() { PieceTable[] array = Resources.FindObjectsOfTypeAll<PieceTable>(); for (int i = 0; i < array.Length; i++) { array[i]?.m_pieces?.RemoveAll((GameObject piece) => (Object)(object)piece == (Object)null || !Object.op_Implicit((Object)(object)piece)); } } private static void ConfigureRequirements(Piece piece) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected O, but got Unknown //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Expected O, but got Unknown ItemDrop itemDrop = GetItemDrop("Stone"); ItemDrop itemDrop2 = GetItemDrop("SurtlingCore"); List<Requirement> list = new List<Requirement>(); if ((Object)(object)itemDrop != (Object)null) { list.Add(new Requirement { m_resItem = itemDrop, m_amount = 1000, m_recover = false }); } if ((Object)(object)itemDrop2 != (Object)null) { list.Add(new Requirement { m_resItem = itemDrop2, m_amount = 10, m_recover = false }); } if (list.Count > 0) { piece.m_resources = list.ToArray(); return; } piece.m_resources = (Requirement[])(((object)piece.m_resources?.Where((Requirement requirement) => requirement != null && (Object)(object)requirement.m_resItem != (Object)null).ToArray()) ?? ((object)new Requirement[0])); } private static void TintVisuals(GameObject ward) { //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Expected O, but got Unknown //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_0129: Unknown result type (might be due to invalid IL or missing references) Color val = default(Color); ((Color)(ref val))..ctor(0.9f, 0.2f, 0.15f, 0.4f); Color val2 = default(Color); ((Color)(ref val2))..ctor(0.8f, 0.1f, 0.1f, 1f); MeshRenderer[] componentsInChildren = ward.GetComponentsInChildren<MeshRenderer>(true); foreach (MeshRenderer val3 in componentsInChildren) { if (!((Object)((Component)val3).gameObject).name.Contains("shield") && !((Object)((Component)val3).gameObject).name.Contains("Shield") && !((Object)((Component)val3).gameObject).name.Contains("dome") && !((Object)((Component)val3).gameObject).name.Contains("AreaMarker")) { continue; } Material[] sharedMaterials = ((Renderer)val3).sharedMaterials; foreach (Material val4 in sharedMaterials) { if (!((Object)(object)val4 == (Object)null)) { Material val5 = new Material(val4); if (val5.HasProperty("_Color")) { val5.SetColor("_Color", val); } if (val5.HasProperty("_EmissionColor")) { val5.SetColor("_EmissionColor", val2); val5.EnableKeyword("_EMISSION"); } ((Renderer)val3).material = val5; } } } } private static void AddGlow(GameObject ward) { //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Expected O, but got Unknown //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) Light componentInChildren = ward.GetComponentInChildren<Light>(true); if ((Object)(object)componentInChildren != (Object)null) { componentInChildren.color = new Color(0.9f, 0.2f, 0.1f); componentInChildren.intensity = 2f; componentInChildren.range = 15f; return; } GameObject val = new GameObject("RaidWardGlow"); val.transform.SetParent(ward.transform); val.transform.localPosition = new Vector3(0f, 2f, 0f); Light val2 = val.AddComponent<Light>(); val2.type = (LightType)2; val2.color = new Color(0.9f, 0.2f, 0.1f); val2.intensity = 1.5f; val2.range = 12f; val2.shadows = (LightShadows)0; } private static void RemoveServerUnsafeVisualComponents(GameObject ward) { MonoBehaviour[] componentsInChildren = ward.GetComponentsInChildren<MonoBehaviour>(true); foreach (MonoBehaviour val in componentsInChildren) { if (!((Object)(object)val == (Object)null) && !(((object)val).GetType().Name != "ShieldDomeImageEffect")) { Object.DestroyImmediate((Object)(object)val); Debug.Log((object)"[RaidSystem] Removed ShieldDomeImageEffect from RaidWard prefab."); } } } private static ItemDrop GetItemDrop(string name) { GameObject prefab = PrefabManager.Instance.GetPrefab(name); return ((Object)(object)prefab != (Object)null) ? prefab.GetComponent<ItemDrop>() : null; } } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [<8bf8826f-ad98-4d3a-b323-51f23ac8d3f7>Embedded] internal sealed class <8bf8826f-ad98-4d3a-b323-51f23ac8d3f7>EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] [<8bf8826f-ad98-4d3a-b323-51f23ac8d3f7>Embedded] [CompilerGenerated] internal sealed class <71f0ecca-928e-4c3d-9e42-f9564f7ffbd4>NullableAttribute : Attribute { public readonly byte[] NullableFlags; public <71f0ecca-928e-4c3d-9e42-f9564f7ffbd4>NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public <71f0ecca-928e-4c3d-9e42-f9564f7ffbd4>NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [<8bf8826f-ad98-4d3a-b323-51f23ac8d3f7>Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class <789cbfbb-e2b4-4b05-8ff6-d8ea4ab18157>NullableContextAttribute : Attribute { public readonly byte Flag; public <789cbfbb-e2b4-4b05-8ff6-d8ea4ab18157>NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [<8bf8826f-ad98-4d3a-b323-51f23ac8d3f7>Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ServerSync { [<71f0ecca-928e-4c3d-9e42-f9564f7ffbd4>Nullable(0)] [PublicAPI] [<789cbfbb-e2b4-4b05-8ff6-d8ea4ab18157>NullableContext(1)] internal abstract class OwnConfigEntryBase { [<71f0ecca-928e-4c3d-9e42-f9564f7ffbd4>Nullable(2)] public object LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [<789cbfbb-e2b4-4b05-8ff6-d8ea4ab18157>NullableContext(1)] [<71f0ecca-928e-4c3d-9e42-f9564f7ffbd4>Nullable(0)] [PublicAPI] internal class SyncedConfigEntry<[<71f0ecca-928e-4c3d-9e42-f9564f7ffbd4>Nullable(2)] 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; base..ctor(); } public void AssignLocalValue(T value) { if (LocalBaseValue == null) { Value = value; } else { LocalBaseValue = value; } } } [<789cbfbb-e2b4-4b05-8ff6-d8ea4ab18157>NullableContext(2)] [<71f0ecca-928e-4c3d-9e42-f9564f7ffbd4>Nullable(0)] internal abstract class CustomSyncedValueBase { public object LocalBaseValue; [<71f0ecca-928e-4c3d-9e42-f9564f7ffbd4>Nullable(1)] public readonly string Identifier; [<71f0ecca-928e-4c3d-9e42-f9564f7ffbd4>Nullable(1)] 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; [<789cbfbb-e2b4-4b05-8ff6-d8ea4ab18157>NullableContext(1)] 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; }; } } [<789cbfbb-e2b4-4b05-8ff6-d8ea4ab18157>NullableContext(1)] [<71f0ecca-928e-4c3d-9e42-f9564f7ffbd4>Nullable(0)] [PublicAPI] internal sealed class CustomSyncedValue<[<71f0ecca-928e-4c3d-9e42-f9564f7ffbd4>Nullable(2)] T> : 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; } } } internal class ConfigurationManagerAttributes { [UsedImplicitly] public bool? ReadOnly = false; } [<789cbfbb-e2b4-4b05-8ff6-d8ea4ab18157>NullableContext(1)] [<71f0ecca-928e-4c3d-9e42-f9564f7ffbd4>Nullable(0)] [PublicAPI] internal class ConfigSync { [HarmonyPatch(typeof(ZRpc), "HandlePackage")] [<789cbfbb-e2b4-4b05-8ff6-d8ea4ab18157>NullableContext(0)] private static class SnatchCurrentlyHandlingRPC { [<71f0ecca-928e-4c3d-9e42-f9564f7ffbd4>Nullable(2)] public static ZRpc currentRpc; [HarmonyPrefix] [<789cbfbb-e2b4-4b05-8ff6-d8ea4ab18157>NullableContext(1)] private static void Prefix(ZRpc __instance) { currentRpc = __instance; } } [HarmonyPatch(typeof(ZNet), "Awake")] [<789cbfbb-e2b4-4b05-8ff6-d8ea4ab18157>NullableContext(0)] internal static class RegisterRPCPatch { [<789cbfbb-e2b4-4b05-8ff6-d8ea4ab18157>NullableContext(1)] [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()); } [<789cbfbb-e2b4-4b05-8ff6-d8ea4ab18157>NullableContext(1)] 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)); } } [<789cbfbb-e2b4-4b05-8ff6-d8ea4ab18157>NullableContext(1)] static IEnumerator WatchAdminListChanges() { MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); 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> adminPeer = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); return ((object)listContainsId == null) ? adminList.Contains(hostName) : ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })); }).ToList(); List<ZNetPeer> nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList(); SendAdmin(nonAdminPeer, isAdmin: false); SendAdmin(adminPeer, isAdmin: true); } } } } } [<789cbfbb-e2b4-4b05-8ff6-d8ea4ab18157>NullableContext(0)] [HarmonyPatch(typeof(ZNet), "OnNewConnection")] private static class RegisterClientRPCPatch { [<789cbfbb-e2b4-4b05-8ff6-d8ea4ab18157>NullableContext(1)] [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); } } } [<789cbfbb-e2b4-4b05-8ff6-d8ea4ab18157>NullableContext(0)] private class ParsedConfigs { [<71f0ecca-928e-4c3d-9e42-f9564f7ffbd4>Nullable(new byte[] { 1, 1, 2 })] public readonly Dictionary<OwnConfigEntryBase, object> configValues = new Dictionary<OwnConfigEntryBase, object>(); [<71f0ecca-928e-4c3d-9e42-f9564f7ffbd4>Nullable(new byte[] { 1, 1, 2 })] public readonly Dictionary<CustomSyncedValueBase, object> customValues = new Dictionary<CustomSyncedValueBase, object>(); } [<789cbfbb-e2b4-4b05-8ff6-d8ea4ab18157>NullableContext(0)] [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")] [<71f0ecca-928e-4c3d-9e42-f9564f7ffbd4>Nullable(0)] private class SendConfigsAfterLogin { [<71f0ecca-928e-4c3d-9e42-f9564f7ffbd4>Nullable(0)] private class BufferingSocket : ZPlayFabSocket, ISocket { public volatile bool finished = false; public volatile int versionMatchQueued = -1; public readonly List<ZPackage> Package = new List<ZPackage>(); public readonly ISocket Original; public BufferingSocket(ISocket original) { Original = original; ((ZPlayFa