// Consolidated decompiled source — KG-Marketplace_And_Server_NPCs_Revamped v9.8.3 // Generated by Hexium's decompiled-source browser. Best-effort concatenation of every type in this // version's manifest — decompiler output isn't guaranteed to compile as-is. using UnityEngine; using UnityEngine.EventSystems; using System.Collections.Generic; using UnityEngine.UI; using System; using UnityEngine.Sprites; using System.Runtime.CompilerServices; using BepInEx.Configuration; using JetBrains.Annotations; using System.Collections; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using HarmonyLib; using BepInEx; using TMPro; using System.ComponentModel; using System.Reflection.Emit; using System.Text.RegularExpressions; using BepInEx.Bootstrap; using System.Text; using fastJSON; using Marketplace.ExternalLoads; using Marketplace.Modules.NPC; using Marketplace.Modules.Quests; using Marketplace.Modules.TerritorySystem; using Marketplace.Stats; using YamlDotNet.Serialization; using Marketplace.Modules.Global_Options; using Marketplace.Paths; using System.Linq.Expressions; using BepInEx.Logging; using HarmonyLib.Tools; using ServerSync; using UnityEngine.Rendering; using Marketplace.Modules.Buffer; using Marketplace.Modules.Dialogues; using Marketplace.Modules.Trader; using Splatform; using UnityEngine.Networking; using UnityEngine.Video; using Marketplace.Modules.Banker; using Marketplace.UI_OptimizationHandler; using API; using Marketplace.OtherModsAPIs; using Groups; using System.Net; using System.Threading.Tasks; using Guilds; using Marketplace.Modules.Factions; using Marketplace.Modules.Leaderboard; using Jewelcrafting; using Marketplace.DB; using Marketplace.DiscordStuff; using Marketplace.Modules.CMS; using LiteDB; using GUIFramework; using Marketplace.Modules.Gambler; using Marketplace.Modules.MainMarketplace; using Marketplace.Modules.ServerInfo; using Marketplace.Modules.Teleporter; using Marketplace.Modules.Transmogrification; using ItemDataManager; using UnityEngine.SceneManagement; using ItemManager; using Marketplace.Hammer; using Marketplace.Modules.Feedback; using System.Collections.Concurrent; using System.Threading; using UnityEngine.Audio; using System.Runtime.InteropServices; using System.Dynamic; using System.Collections.Specialized; using System.Xml.Serialization; using YamlDotNet.Core; using YamlDotNet.Serialization.Converters; using YamlDotNet.Serialization.NamingConventions; using YamlDotNet.Core.Events; using YamlDotNet.Serialization.Utilities; using YamlDotNet.Helpers; using YamlDotNet.Serialization.BufferedDeserialization; using YamlDotNet.Serialization.NodeDeserializers; using YamlDotNet.Serialization.NodeTypeResolvers; using YamlDotNet.Serialization.ObjectFactories; using YamlDotNet.Serialization.Schemas; using YamlDotNet.Serialization.TypeInspectors; using YamlDotNet.Serialization.TypeResolvers; using YamlDotNet.Serialization.ValueDeserializers; using System.Diagnostics.CodeAnalysis; using YamlDotNet.Serialization.EventEmitters; using YamlDotNet.Serialization.ObjectGraphTraversalStrategies; using YamlDotNet.Serialization.ObjectGraphVisitors; using YamlDotNet.Serialization.Callbacks; using YamlDotNet.Core.ObjectPool; using YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators; using System.Diagnostics; using YamlDotNet.Core.Tokens; using System.Collections.ObjectModel; using LiteDB.Engine; using LiteDB.Vector; using LiteDB.Client.Shared; using Microsoft.Win32.SafeHandles; using System.Security; using System.Security.Cryptography; using System.Buffers; using LiteDB.Utils; using LiteDB.Utils.Extensions; // ---- kg.Marketplace.dll::Marketplace.Resources.Marketplace_UnityCode.dll :: DragUIMPASN ---- public class DragUIMPASN : MonoBehaviour, IDragHandler, IEventSystemHandler { private RectTransform dragRect; private float maxX; private float maxY; private float LastWidth; private float LastHeight; private void Awake() { dragRect = GetComponent(); LastWidth = Screen.width; LastHeight = Screen.height; maxX = dragRect.rect.width / 2f * 1.4f; maxY = dragRect.rect.height / 2f * 1.4f; } private bool CanDrag(Vector2 newPos) { bool num = newPos.x < (float)Screen.width - maxX; bool flag = newPos.y < (float)Screen.height - maxY; bool flag2 = newPos.x > maxX; bool flag3 = newPos.y > maxY; return num && flag && flag2 && flag3; } public void OnDrag(PointerEventData eventData) { Vector2 newPos = dragRect.anchoredPosition + eventData.delta; if (CanDrag(newPos)) { dragRect.anchoredPosition += eventData.delta; } } } // ---- kg.Marketplace.dll::Marketplace.Resources.Marketplace_UnityCode.dll :: Enchantment_Rotate ---- public class Enchantment_Rotate : MonoBehaviour { public Vector3 RotateOffset; private Vector3 RotateMulti; private void Update() { RotateMulti = Vector3.Lerp(RotateMulti, RotateOffset, Time.deltaTime); base.transform.rotation *= Quaternion.Euler(RotateMulti); } } // ---- kg.Marketplace.dll::Marketplace.Resources.Marketplace_UnityCode.dll :: ExtendUI ---- public class ExtendUI : MonoBehaviour, IDragHandler, IEventSystemHandler { [SerializeField] private List ToMove = new List(); private Dictionary InitialData = new Dictionary(); private RectTransform dragRect; private float currentSize; private float InitY; private void Awake() { dragRect = GetComponent(); InitY = dragRect.anchoredPosition.y; foreach (RectTransform item in ToMove) { InitialData.Add(item, item.rect.height); } } public void OnDrag(PointerEventData eventData) { float num = eventData.delta.y / 1.4f / 0.72f; currentSize += num; if (currentSize > 0f) { currentSize = 0f; } foreach (KeyValuePair initialDatum in InitialData) { initialDatum.Key.SetSizeWithCurrentAnchors(RectTransform.Axis.Vertical, initialDatum.Value - currentSize); } dragRect.anchoredPosition = new Vector2(dragRect.anchoredPosition.x, InitY + currentSize); } } // ---- kg.Marketplace.dll::Marketplace.Resources.Marketplace_UnityCode.dll :: FixedGridLayoutGroup ---- public class FixedGridLayoutGroup : GridLayoutGroup { public override void SetLayoutHorizontal() { SetCellsAlongAxis(0); } public override void SetLayoutVertical() { SetCellsAlongAxis(1); } private void SetCellsAlongAxis(int axis) { int count = base.rectChildren.Count; if (axis == 0) { for (int i = 0; i < count; i++) { RectTransform rectTransform = base.rectChildren[i]; m_Tracker.Add(this, rectTransform, DrivenTransformProperties.Anchors | DrivenTransformProperties.AnchoredPosition | DrivenTransformProperties.SizeDelta); rectTransform.anchorMin = Vector2.up; rectTransform.anchorMax = Vector2.up; rectTransform.sizeDelta = base.cellSize; } return; } float x = base.rectTransform.rect.size.x; float y = base.rectTransform.rect.size.y; int num = 1; int num2 = 1; if (m_Constraint == Constraint.FixedColumnCount) { num = m_ConstraintCount; if (count > num) { num2 = count / num + ((count % num > 0) ? 1 : 0); } } else if (m_Constraint != Constraint.FixedRowCount) { num = ((!(base.cellSize.x + base.spacing.x <= 0f)) ? Mathf.Max(1, Mathf.FloorToInt((x - (float)base.padding.horizontal + base.spacing.x + 0.001f) / (base.cellSize.x + base.spacing.x))) : int.MaxValue); num2 = ((!(base.cellSize.y + base.spacing.y <= 0f)) ? Mathf.Max(1, Mathf.FloorToInt((y - (float)base.padding.vertical + base.spacing.y + 0.001f) / (base.cellSize.y + base.spacing.y))) : int.MaxValue); } else { num2 = m_ConstraintCount; if (count > num2) { num = count / num2 + ((count % num2 > 0) ? 1 : 0); } } int num3 = (int)base.startCorner % 2; int num4 = (int)base.startCorner / 2; int num5; int num6; int num7; if (base.startAxis == Axis.Horizontal) { num5 = num; num6 = Mathf.Clamp(num, 1, count); num7 = Mathf.Clamp(num2, 1, Mathf.CeilToInt((float)count / (float)num5)); } else { num5 = num2; num7 = Mathf.Clamp(num2, 1, count); num6 = Mathf.Clamp(num, 1, Mathf.CeilToInt((float)count / (float)num5)); } int num8 = count % num5; Vector2 vector = new Vector2((float)num6 * base.cellSize.x + (float)(num6 - 1) * base.spacing.x, (float)num7 * base.cellSize.y + (float)(num7 - 1) * base.spacing.y); Vector2 vector2 = new Vector2(GetStartOffset(0, vector.x), GetStartOffset(1, vector.y)); int num9 = ((num8 == 0) ? num5 : num8); int num10 = ((base.startAxis == Axis.Horizontal) ? num9 : num6); int num11 = ((base.startAxis == Axis.Vertical) ? num9 : num7); Vector2 vector3 = new Vector2((float)num10 * base.cellSize.x + (float)(num10 - 1) * base.spacing.x, (float)num11 * base.cellSize.y + (float)(num11 - 1) * base.spacing.y); Vector2 vector4 = new Vector2(GetStartOffset(0, vector3.x), GetStartOffset(1, vector3.y)); for (int j = 0; j < count; j++) { Vector2 vector5 = ((j + 1 > count - num9) ? vector4 : vector2); int num12; int num13; if (base.startAxis == Axis.Horizontal) { num12 = j % num5; num13 = j / num5; } else { num12 = j / num5; num13 = j % num5; } if (num3 == 1) { num12 = num6 - 1 - num12; } if (num4 == 1) { num13 = num7 - 1 - num13; } SetChildAlongAxis(base.rectChildren[j], 0, vector5.x + (base.cellSize[0] + base.spacing[0]) * (float)num12, base.cellSize[0]); SetChildAlongAxis(base.rectChildren[j], 1, vector5.y + (base.cellSize[1] + base.spacing[1]) * (float)num13, base.cellSize[1]); } } } // ---- kg.Marketplace.dll::Marketplace.Resources.Marketplace_UnityCode.dll :: LocalizeCustom ---- public class LocalizeCustom : MonoBehaviour { private void Awake() { Text component = GetComponent(); component.text = Localization.instance.Localize(component.text); } } // ---- kg.Marketplace.dll::Marketplace.Resources.Marketplace_UnityCode.dll :: NoDragScroll ---- public class NoDragScroll : ScrollRect { public override void OnBeginDrag(PointerEventData eventData) { } public override void OnDrag(PointerEventData eventData) { } public override void OnEndDrag(PointerEventData eventData) { } } // ---- kg.Marketplace.dll::Marketplace.Resources.Marketplace_UnityCode.dll :: SoulAltarAnimEvent ---- public class SoulAltarAnimEvent : MonoBehaviour { private Action _onSoulAltarAnimEvent; public void Trigger() { _onSoulAltarAnimEvent(); } public void SetAction(Action action) { _onSoulAltarAnimEvent = action; } } // ---- kg.Marketplace.dll::Marketplace.Resources.Marketplace_UnityCode.dll :: UIParticleSystem ---- [ExecuteInEditMode] [RequireComponent(typeof(CanvasRenderer))] [RequireComponent(typeof(ParticleSystem))] public class UIParticleSystem : MaskableGraphic { public Texture particleTexture; public Sprite particleSprite; private Transform _transform; private ParticleSystem _particleSystem; private ParticleSystem.Particle[] _particles; private UIVertex[] _quad = new UIVertex[4]; private Vector4 _uv = Vector4.zero; private ParticleSystem.TextureSheetAnimationModule _textureSheetAnimation; private int _textureSheetAnimationFrames; private Vector2 _textureSheedAnimationFrameSize; public override Texture mainTexture { get { if ((bool)particleTexture) { return particleTexture; } if ((bool)particleSprite) { return particleSprite.texture; } return null; } } protected bool Initialize() { if (_transform == null) { _transform = base.transform; } ParticleSystemRenderer particleSystemRenderer = GetComponent(); if (_particleSystem == null) { _particleSystem = GetComponent(); if (_particleSystem == null) { return false; } if (particleSystemRenderer == null) { particleSystemRenderer = _particleSystem.gameObject.AddComponent(); } Material sharedMaterial = particleSystemRenderer.sharedMaterial; if ((bool)sharedMaterial && sharedMaterial.HasProperty("_MainTex")) { particleTexture = sharedMaterial.mainTexture; } _particleSystem.scalingMode = ParticleSystemScalingMode.Local; _particles = null; } else if (Application.isPlaying) { _ = particleSystemRenderer.material == null; } else { _ = particleSystemRenderer.sharedMaterial == null; } if (_particles == null) { _particles = new ParticleSystem.Particle[_particleSystem.maxParticles]; } if ((bool)particleTexture) { _uv = new Vector4(0f, 0f, 1f, 1f); } else if ((bool)particleSprite) { _uv = DataUtility.GetOuterUV(particleSprite); } _textureSheetAnimation = _particleSystem.textureSheetAnimation; _textureSheetAnimationFrames = 0; _textureSheedAnimationFrameSize = Vector2.zero; if (_textureSheetAnimation.enabled) { _textureSheetAnimationFrames = _textureSheetAnimation.numTilesX * _textureSheetAnimation.numTilesY; _textureSheedAnimationFrameSize = new Vector2(1f / (float)_textureSheetAnimation.numTilesX, 1f / (float)_textureSheetAnimation.numTilesY); } return true; } protected override void Awake() { base.Awake(); if (!Initialize()) { base.enabled = false; } } protected override void OnPopulateMesh(VertexHelper vh) { if (!Application.isPlaying && !Initialize()) { return; } vh.Clear(); if (!base.gameObject.activeInHierarchy) { return; } int particles = _particleSystem.GetParticles(_particles); for (int i = 0; i < particles; i++) { ParticleSystem.Particle particle = _particles[i]; Vector2 vector = ((_particleSystem.simulationSpace == ParticleSystemSimulationSpace.Local) ? particle.position : _transform.InverseTransformPoint(particle.position)); float num = (0f - particle.rotation) * (MathF.PI / 180f); float f = num + MathF.PI / 2f; Color32 currentColor = particle.GetCurrentColor(_particleSystem); float num2 = particle.GetCurrentSize(_particleSystem) * 0.5f; if (_particleSystem.scalingMode == ParticleSystemScalingMode.Shape) { vector /= base.canvas.scaleFactor; } Vector4 uv = _uv; if (_textureSheetAnimation.enabled) { float num3 = 1f - particle.remainingLifetime / particle.startLifetime; num3 = Mathf.Repeat(num3 * (float)_textureSheetAnimation.cycleCount, 1f); int num4 = 0; switch (_textureSheetAnimation.animation) { case ParticleSystemAnimationType.WholeSheet: num4 = Mathf.FloorToInt(num3 * (float)_textureSheetAnimationFrames); break; case ParticleSystemAnimationType.SingleRow: { num4 = Mathf.FloorToInt(num3 * (float)_textureSheetAnimation.numTilesX); int rowIndex = _textureSheetAnimation.rowIndex; num4 += rowIndex * _textureSheetAnimation.numTilesX; break; } } num4 %= _textureSheetAnimationFrames; uv.x = (float)(num4 % _textureSheetAnimation.numTilesX) * _textureSheedAnimationFrameSize.x; uv.y = (float)Mathf.FloorToInt(num4 / _textureSheetAnimation.numTilesX) * _textureSheedAnimationFrameSize.y; uv.z = uv.x + _textureSheedAnimationFrameSize.x; uv.w = uv.y + _textureSheedAnimationFrameSize.y; } _quad[0] = UIVertex.simpleVert; _quad[0].color = currentColor; _quad[0].uv0 = new Vector2(uv.x, uv.y); _quad[1] = UIVertex.simpleVert; _quad[1].color = currentColor; _quad[1].uv0 = new Vector2(uv.x, uv.w); _quad[2] = UIVertex.simpleVert; _quad[2].color = currentColor; _quad[2].uv0 = new Vector2(uv.z, uv.w); _quad[3] = UIVertex.simpleVert; _quad[3].color = currentColor; _quad[3].uv0 = new Vector2(uv.z, uv.y); if (num == 0f) { Vector2 vector2 = new Vector2(vector.x - num2, vector.y - num2); Vector2 vector3 = new Vector2(vector.x + num2, vector.y + num2); _quad[0].position = new Vector2(vector2.x, vector2.y); _quad[1].position = new Vector2(vector2.x, vector3.y); _quad[2].position = new Vector2(vector3.x, vector3.y); _quad[3].position = new Vector2(vector3.x, vector2.y); } else { Vector2 vector4 = new Vector2(Mathf.Cos(num), Mathf.Sin(num)) * num2; Vector2 vector5 = new Vector2(Mathf.Cos(f), Mathf.Sin(f)) * num2; _quad[0].position = vector - vector4 - vector5; _quad[1].position = vector - vector4 + vector5; _quad[2].position = vector + vector4 + vector5; _quad[3].position = vector + vector4 - vector5; } vh.AddUIVertexQuad(_quad); } } private void Update() { if (Application.isPlaying) { _particleSystem.Simulate(Time.unscaledDeltaTime, withChildren: false, restart: false); SetAllDirty(); } } private void LateUpdate() { if (!Application.isPlaying) { SetAllDirty(); } } } // ---- kg.Marketplace.dll :: Microsoft.CodeAnalysis.EmbeddedAttribute ---- namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } // ---- kg.Marketplace.dll :: ServerSync.OwnConfigEntryBase ---- namespace ServerSync { [PublicAPI] public abstract class OwnConfigEntryBase { public object? LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } } // ---- kg.Marketplace.dll :: ServerSync.SyncedConfigEntry`1 ---- namespace ServerSync { [PublicAPI] public class SyncedConfigEntry(ConfigEntry sourceConfig) : OwnConfigEntryBase { public readonly ConfigEntry SourceConfig = sourceConfig; public override ConfigEntryBase BaseConfig => SourceConfig; public T Value { get { return SourceConfig.Value; } set { SourceConfig.Value = value; } } public void AssignLocalValue(T value) { if (LocalBaseValue == null) { Value = value; } else { LocalBaseValue = value; } } } } // ---- kg.Marketplace.dll :: ServerSync.CustomSyncedValueBase ---- namespace ServerSync { public abstract class CustomSyncedValueBase { public object? LocalBaseValue; public readonly string Identifier; public readonly Type Type; private object? boxedValue; protected bool localIsOwner; public readonly int Priority; public object? BoxedValue { get { return boxedValue; } set { boxedValue = value; this.ValueChanged?.Invoke(); } } public event Action? ValueChanged; public void Update() { this.ValueChanged?.Invoke(); } 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; }; } } } // ---- kg.Marketplace.dll :: ServerSync.CustomSyncedValue`1 ---- namespace ServerSync { [PublicAPI] public sealed class CustomSyncedValue : CustomSyncedValueBase { public T Value { get { return (T)base.BoxedValue; } set { base.BoxedValue = value; } } public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0) : base(configSync, identifier, typeof(T), priority) { Value = value; } public void AssignLocalValue(T value) { if (localIsOwner) { Value = value; } else { LocalBaseValue = value; } } } } // ---- kg.Marketplace.dll :: ServerSync.ConfigurationManagerAttributes ---- namespace ServerSync { internal class ConfigurationManagerAttributes { [UsedImplicitly] public bool? ReadOnly = false; } } // ---- kg.Marketplace.dll :: ServerSync.ConfigSync ---- namespace ServerSync { [PublicAPI] public class ConfigSync { [HarmonyPatch(typeof(ZRpc), "HandlePackage")] private static class SnatchCurrentlyHandlingRPC { public static ZRpc? currentRpc; [HarmonyPrefix] private static void Prefix(ZRpc __instance) { currentRpc = __instance; } } [HarmonyPatch(typeof(ZNet), "Awake")] internal static class RegisterRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance) { isServer = __instance.IsServer(); foreach (ConfigSync configSync2 in configSyncs) { ZRoutedRpc.instance.Register(configSync2.Name + " ConfigSync", configSync2.RPC_FromOtherClientConfigSync); if (isServer) { configSync2.InitialSyncDone = true; Debug.Log("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections"); } } if (isServer) { __instance.StartCoroutine(WatchAdminListChanges()); } static void SendAdmin(List peers, bool isAdmin) { ZPackage package = ConfigsToPackage(null, null, new <>z__ReadOnlySingleElementList(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = isAdmin })); ConfigSync configSync = configSyncs.First(); if (configSync != null) { ZNet.instance.StartCoroutine(configSync.sendZPackage(peers, package)); } } static IEnumerator WatchAdminListChanges() { MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId"); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); List CurrentList = new List(adminList.GetList()); while (true) { yield return new WaitForSeconds(30f); if (!adminList.GetList().SequenceEqual(CurrentList)) { CurrentList = new List(adminList.GetList()); List list = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); return ((object)listContainsId != null) ? ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })) : adminList.Contains(hostName); }).ToList(); List peers = ZNet.instance.GetPeers().Except(list).ToList(); SendAdmin(peers, isAdmin: false); SendAdmin(list, isAdmin: true); } } } } } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] private static class RegisterClientRPCPatch { [HarmonyPostfix] private static void Postfix(ZNet __instance, ZNetPeer peer) { if (__instance.IsServer()) { return; } foreach (ConfigSync configSync in configSyncs) { peer.m_rpc.Register(configSync.Name + " ConfigSync", configSync.RPC_FromServerConfigSync); } } } private class ParsedConfigs { public readonly Dictionary configValues = new Dictionary(); public readonly Dictionary customValues = new Dictionary(); } [HarmonyPatch(typeof(ZNet), "Shutdown")] private class ResetConfigsOnShutdown { [HarmonyPostfix] private static void Postfix() { ProcessingServerUpdate = true; foreach (ConfigSync configSync in configSyncs) { configSync.resetConfigsFromServer(); configSync.IsSourceOfTruth = true; configSync.InitialSyncDone = false; } ProcessingServerUpdate = false; } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] private class SendConfigsAfterLogin { private class BufferingSocket(ISocket original) : ZPlayFabSocket, ISocket { public volatile bool finished; public volatile int versionMatchQueued = -1; public readonly List Package = new List(); public readonly ISocket Original = original; public new bool IsConnected() { return Original.IsConnected(); } public new ZPackage Recv() { return Original.Recv(); } public new int GetSendQueueSize() { return Original.GetSendQueueSize(); } public new int GetCurrentSendRate() { return Original.GetCurrentSendRate(); } public new bool IsHost() { return Original.IsHost(); } public new void Dispose() { Original.Dispose(); } public new bool GotNewData() { return Original.GotNewData(); } public new void Close() { Original.Close(); } public new string GetEndPointString() { return Original.GetEndPointString(); } public new void GetAndResetStats(out int totalSent, out int totalRecv) { Original.GetAndResetStats(out totalSent, out totalRecv); } public new void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec) { Original.GetConnectionQuality(out localQuality, out remoteQuality, out ping, out outByteSec, out inByteSec); } public new ISocket Accept() { return Original.Accept(); } public new int GetHostPort() { return Original.GetHostPort(); } public new bool Flush() { return Original.Flush(); } public new string GetHostName() { return Original.GetHostName(); } public new void VersionMatch() { if (finished) { Original.VersionMatch(); } else { versionMatchQueued = Package.Count; } } public new void Send(ZPackage pkg) { int pos = pkg.GetPos(); pkg.SetPos(0); int num = pkg.ReadInt(); if ((num == "PeerInfo".GetStableHashCode() || num == "RoutedRPC".GetStableHashCode() || num == "ZDOData".GetStableHashCode()) && !finished) { ZPackage zPackage = new ZPackage(pkg.GetArray()); zPackage.SetPos(pos); Package.Add(zPackage); } else { pkg.SetPos(pos); Original.Send(pkg); } } } [HarmonyPriority(800)] [HarmonyPrefix] private static void Prefix(ref Dictionary? __state, ZNet __instance, ZRpc rpc) { if (!__instance.IsServer()) { return; } BufferingSocket bufferingSocket = new BufferingSocket(rpc.GetSocket()); AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket); if (AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }).Invoke(__instance, new object[1] { rpc }) is ZNetPeer obj && ZNet.m_onlineBackend != OnlineBackendType.Steamworks) { FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket"); if (fieldInfo.GetValue(obj) is ZPlayFabSocket zPlayFabSocket) { typeof(ZPlayFabSocket).GetField("m_remotePlayerId").SetValue(bufferingSocket, zPlayFabSocket.m_remotePlayerId); } fieldInfo.SetValue(obj, bufferingSocket); } if (__state == null) { __state = new Dictionary(); } __state[Assembly.GetExecutingAssembly()] = bufferingSocket; } [HarmonyPostfix] private static void Postfix(Dictionary __state, ZNet __instance, ZRpc rpc) { ZNetPeer peer; if (__instance.IsServer()) { object obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }).Invoke(__instance, new object[1] { rpc }); peer = obj as ZNetPeer; if (peer == null) { SendBufferedData(); } else { __instance.StartCoroutine(sendAsync()); } } IEnumerator sendAsync() { foreach (ConfigSync configSync in configSyncs) { List list = new List(); if (configSync.CurrentVersion != null) { list.Add(new PackageEntry { section = "Internal", key = "serverversion", type = typeof(string), value = configSync.CurrentVersion }); } MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId"); SyncedList syncedList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); list.Add(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = (((object)methodInfo == null) ? ((object)syncedList.Contains(rpc.GetSocket().GetHostName())) : methodInfo.Invoke(ZNet.instance, new object[2] { syncedList, rpc.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select((OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, list, partial: false); yield return __instance.StartCoroutine(configSync.sendZPackage(new List(1) { peer }, package)); } SendBufferedData(); } void SendBufferedData() { if (rpc.GetSocket() is BufferingSocket bufferingSocket) { AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original); if (AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }).Invoke(__instance, new object[1] { rpc }) is ZNetPeer obj2) { AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(obj2, bufferingSocket.Original); } } BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()]; bufferingSocket2.finished = true; for (int i = 0; i < bufferingSocket2.Package.Count; i++) { if (i == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } bufferingSocket2.Original.Send(bufferingSocket2.Package[i]); } if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } } } } private class PackageEntry { public string section; public string key; public Type type; public object? value; } [HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")] private static class PreventSavingServerInfo { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, ref string __result) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || isWritableConfig(ownConfigEntryBase)) { return true; } __result = TomlTypeConverter.ConvertToString(ownConfigEntryBase.LocalBaseValue, __instance.SettingType); return false; } } [HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")] private static class PreventConfigRereadChangingValues { [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, string value) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null) { return true; } try { ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType); } catch (Exception ex) { Debug.LogWarning($"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}"); } return false; } } private class InvalidDeserializationTypeException : Exception { public string expected; public string received; public string field = ""; } public static bool ProcessingServerUpdate; public readonly string Name; public string? DisplayName; public string? CurrentVersion; public string? MinimumRequiredVersion; public bool ModRequired; private bool? forceConfigLocking; private bool isSourceOfTruth = true; private static readonly HashSet configSyncs; private readonly HashSet allConfigs = new HashSet(); private HashSet allCustomValues = new HashSet(); private static bool isServer; private static bool lockExempt; private OwnConfigEntryBase? lockedConfig; private const byte PARTIAL_CONFIGS = 1; private const byte FRAGMENTED_CONFIG = 2; private const byte COMPRESSED_CONFIG = 4; private readonly Dictionary> configValueCache = new Dictionary>(); private readonly List> cacheExpirations = new List>(); private static long packageCounter; public bool IsLocked { get { bool? flag = forceConfigLocking; bool num; if (!flag.HasValue) { if (lockedConfig == null) { goto IL_0051; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag == true; } if (num) { return !lockExempt; } goto IL_0051; IL_0051: return false; } set { forceConfigLocking = value; } } public bool IsAdmin { get { if (!lockExempt) { return isSourceOfTruth; } return true; } } public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } public event Action? SourceOfTruthChanged; private event Action? lockedConfigChanged; static ConfigSync() { ProcessingServerUpdate = false; configSyncs = new HashSet(); lockExempt = false; packageCounter = 0L; RuntimeHelpers.RunClassConstructor(typeof(VersionCheck).TypeHandle); } public ConfigSync(string name) { Name = name; configSyncs.Add(this); new VersionCheck(this); } public SyncedConfigEntry AddConfigEntry(ConfigEntry configEntry) { OwnConfigEntryBase ownConfigEntryBase = configData(configEntry); SyncedConfigEntry syncedEntry = ownConfigEntryBase as SyncedConfigEntry; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry(configEntry); AccessTools.DeclaredField(typeof(ConfigDescription), "k__BackingField").SetValue(configEntry.Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(configEntry.Description.Tags ?? Array.Empty()).Concat(new <>z__ReadOnlySingleElementList(syncedEntry)).ToArray()); configEntry.SettingChanged += delegate { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(ZRoutedRpc.Everybody, configEntry); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry AddLockingConfigEntry(ConfigEntry lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry(lockingConfig); lockingConfig.SettingChanged += delegate { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry)lockedConfig; } internal void AddCustomValue(CustomSyncedValueBase customValue) { if (allCustomValues.Select((CustomSyncedValueBase v) => v.Identifier).Concat(new <>z__ReadOnlySingleElementList("serverversion")).Contains(customValue.Identifier)) { throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)"); } allCustomValues.Add(customValue); allCustomValues = new HashSet(allCustomValues.OrderByDescending((CustomSyncedValueBase v) => v.Priority)); customValue.ValueChanged += delegate { if (!ProcessingServerUpdate) { Broadcast(ZRoutedRpc.Everybody, customValue); } }; } private void RPC_FromServerConfigSync(ZRpc rpc, ZPackage package) { lockedConfigChanged += serverLockedSettingChanged; IsSourceOfTruth = false; if (HandleConfigSyncRPC(0L, package, clientUpdate: false)) { InitialSyncDone = true; } } private void RPC_FromOtherClientConfigSync(long sender, ZPackage package) { HandleConfigSyncRPC(sender, package, clientUpdate: true); } private bool HandleConfigSyncRPC(long sender, ZPackage package, bool clientUpdate) { try { if (isServer && IsLocked) { string text = SnatchCurrentlyHandlingRPC.currentRpc?.GetSocket()?.GetHostName(); if (text != null) { MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId"); SyncedList syncedList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); if (!(((object)methodInfo == null) ? syncedList.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { syncedList, text })))) { return false; } } } cacheExpirations.RemoveAll(delegate(KeyValuePair kv) { if (kv.Key < DateTimeOffset.Now.Ticks) { configValueCache.Remove(kv.Value); return true; } return false; }); byte b = package.ReadByte(); if ((b & 2) != 0) { long num = package.ReadLong(); string text2 = sender.ToString() + num; if (!configValueCache.TryGetValue(text2, out SortedDictionary value)) { value = new SortedDictionary(); configValueCache[text2] = value; cacheExpirations.Add(new KeyValuePair(DateTimeOffset.Now.AddSeconds(60.0).Ticks, text2)); } int key = package.ReadInt(); int num2 = package.ReadInt(); value.Add(key, package.ReadByteArray()); if (value.Count < num2) { return false; } configValueCache.Remove(text2); package = new ZPackage(value.Values.SelectMany((byte[] a) => a).ToArray()); b = package.ReadByte(); } ProcessingServerUpdate = true; if ((b & 4) != 0) { 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); ConfigFile configFile = null; bool saveOnConfigSet = false; foreach (KeyValuePair configValue in parsedConfigs.configValues) { if (!isServer && configValue.Key.LocalBaseValue == null) { configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue; } if (configFile == null) { configFile = configValue.Key.BaseConfig.ConfigFile; saveOnConfigSet = configFile.SaveOnConfigSet; configFile.SaveOnConfigSet = false; } configValue.Key.BaseConfig.BoxedValue = configValue.Value; } if (configFile != null) { configFile.SaveOnConfigSet = saveOnConfigSet; configFile.Save(); } foreach (KeyValuePair customValue in parsedConfigs.customValues) { if (!isServer) { CustomSyncedValueBase key2 = customValue.Key; if (key2.LocalBaseValue == null) { key2.LocalBaseValue = customValue.Key.BoxedValue; } } customValue.Key.BoxedValue = customValue.Value; } Debug.Log(string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name)); if (!isServer) { serverLockedSettingChanged(); } return true; } finally { ProcessingServerUpdate = false; } } private ParsedConfigs ReadConfigsFromPackage(ZPackage package) { ParsedConfigs parsedConfigs = new ParsedConfigs(); Dictionary dictionary = allConfigs.Where((OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary((OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, (OwnConfigEntryBase c) => c); Dictionary dictionary2 = allCustomValues.ToDictionary((CustomSyncedValueBase c) => c.Identifier, (CustomSyncedValueBase c) => c); int num = package.ReadInt(); for (int num2 = 0; num2 < num; num2++) { string text = package.ReadString(); string text2 = package.ReadString(); string text3 = package.ReadString(); Type type = Type.GetType(text3); if (text3 == "" || type != null) { object obj; try { obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type)); } catch (InvalidDeserializationTypeException ex) { Debug.LogWarning("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected); continue; } OwnConfigEntryBase value2; if (text == "Internal") { CustomSyncedValueBase value; if (text2 == "serverversion") { if (obj?.ToString() != CurrentVersion) { Debug.LogWarning("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown")); } } else if (text2 == "lockexempt") { if (obj is bool flag) { lockExempt = flag; } } else if (dictionary2.TryGetValue(text2, out value)) { if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3) { parsedConfigs.customValues[value] = obj; continue; } Debug.LogWarning("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName); } } else if (dictionary.TryGetValue(text + "_" + text2, out value2)) { Type type2 = configType(value2.BaseConfig); if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3) { parsedConfigs.configValues[value2] = obj; continue; } Debug.LogWarning("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName); } else { Debug.LogWarning("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match."); } continue; } Debug.LogWarning("Got invalid type " + text3 + ", abort reading of received configs"); return new ParsedConfigs(); } return parsedConfigs; } private static bool isWritableConfig(OwnConfigEntryBase config) { ConfigSync configSync = configSyncs.FirstOrDefault((ConfigSync cs) => cs.allConfigs.Contains(config)); if (configSync == null) { return true; } if (!configSync.IsSourceOfTruth && config.SynchronizedConfig && config.LocalBaseValue != null) { if (!configSync.IsLocked) { if (config == configSync.lockedConfig) { return lockExempt; } return true; } return false; } return true; } private void serverLockedSettingChanged() { foreach (OwnConfigEntryBase allConfig in allConfigs) { configAttribute(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig); } } private void resetConfigsFromServer() { ConfigFile configFile = null; bool saveOnConfigSet = false; foreach (OwnConfigEntryBase item in allConfigs.Where((OwnConfigEntryBase config) => config.LocalBaseValue != null)) { if (configFile == null) { configFile = item.BaseConfig.ConfigFile; saveOnConfigSet = configFile.SaveOnConfigSet; configFile.SaveOnConfigSet = false; } item.BaseConfig.BoxedValue = item.LocalBaseValue; item.LocalBaseValue = null; } if (configFile != null) { configFile.SaveOnConfigSet = saveOnConfigSet; } foreach (CustomSyncedValueBase item2 in allCustomValues.Where((CustomSyncedValueBase config) => config.LocalBaseValue != null)) { item2.BoxedValue = item2.LocalBaseValue; item2.LocalBaseValue = null; } lockedConfigChanged -= serverLockedSettingChanged; serverLockedSettingChanged(); } private IEnumerator distributeConfigToPeers(ZNetPeer peer, ZPackage package) { ZRoutedRpc rpc = ZRoutedRpc.instance; if (rpc == null) { yield break; } if (package.Size() > 40000) { if (!package.m_stream.TryGetBuffer(out var seg)) { byte[] array = package.m_stream.ToArray(); seg = new ArraySegment(array, 0, array.Length); } int len = seg.Count; int fragments = (len + 40000 - 1) / 40000; long packageIdentifier = ++packageCounter; int fragment = 0; while (fragment < fragments) { foreach (bool item in waitForQueue()) { yield return item; } if (peer.m_socket.IsConnected()) { int num = fragment * 40000; int num2 = Math.Min(40000, len - num); ZPackage zPackage = new ZPackage(); zPackage.Write((byte)2); zPackage.Write(packageIdentifier); zPackage.Write(fragment); zPackage.Write(fragments); zPackage.Write(num2); zPackage.m_stream.Write(seg.Array, seg.Offset + num, num2); SendPackage(zPackage); if (fragment != fragments - 1) { yield return true; } int num3 = fragment + 1; fragment = num3; continue; } break; } yield break; } foreach (bool item2 in waitForQueue()) { yield return item2; } SendPackage(package); void SendPackage(ZPackage pkg) { string text = Name + " ConfigSync"; if (isServer) { peer.m_rpc.Invoke(text, pkg); } else { rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, pkg); } } IEnumerable waitForQueue() { float timeout = Time.time + 30f; while (peer.m_socket.GetSendQueueSize() > 20000) { if (Time.time > timeout) { Debug.Log($"Disconnecting {peer.m_uid} after 30 seconds config sending timeout"); peer.m_rpc.Invoke("Error", ZNet.ConnectionStatus.ErrorConnectFailed); ZNet.instance.Disconnect(peer); break; } yield return false; } } } private IEnumerator sendZPackage(long target, ZPackage package) { if (!ZNet.instance) { return Enumerable.Empty().GetEnumerator(); } List list = (List)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance); if (target != ZRoutedRpc.Everybody) { list = list.Where((ZNetPeer p) => p.m_uid == target).ToList(); } return sendZPackage(list, package); } private IEnumerator sendZPackage(List peers, ZPackage package) { if (!ZNet.instance) { yield break; } if (package.Size() > 10000) { MemoryStream stream = package.m_stream; stream.Position = 0L; package = new ZPackage(); package.m_stream.WriteByte(4); package.m_stream.Position = 5L; using (DeflateStream destination = new DeflateStream(package.m_stream, System.IO.Compression.CompressionLevel.Optimal, leaveOpen: true)) { stream.CopyTo(destination); } long position = package.m_stream.Position; int value = (int)(position - 5); package.m_stream.Position = 1L; package.m_stream.Write(BitConverter.GetBytes(value), 0, 4); } List> writers = (from p in peers where p.IsReady() select distributeConfigToPeers(p, package)).ToList(); writers.RemoveAll((IEnumerator writer) => !writer.MoveNext()); while (writers.Count > 0) { yield return null; writers.RemoveAll((IEnumerator writer) => !writer.MoveNext()); } } private void Broadcast(long target, params ConfigEntryBase[] configs) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(configs); ZNet.instance?.StartCoroutine(sendZPackage(target, package)); } } private void Broadcast(long target, params CustomSyncedValueBase[] customValues) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(null, customValues); ZNet.instance?.StartCoroutine(sendZPackage(target, package)); } } private static OwnConfigEntryBase? configData(ConfigEntryBase config) { return config.Description.Tags?.OfType().SingleOrDefault(); } public static SyncedConfigEntry? ConfigData(ConfigEntry config) { return config.Description.Tags?.OfType>().SingleOrDefault(); } private static T configAttribute(ConfigEntryBase config) { return config.Description.Tags.OfType().First(); } private static Type configType(ConfigEntryBase config) { return configType(config.SettingType); } private static Type configType(Type type) { if (!type.IsEnum) { return type; } return Enum.GetUnderlyingType(type); } private static ZPackage ConfigsToPackage(IEnumerable? configs = null, IEnumerable? customValues = null, IEnumerable? packageEntries = null, bool partial = true) { List list = configs?.Where((ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List(); List list2 = customValues?.ToList() ?? new List(); ZPackage zPackage = new ZPackage(); zPackage.Write(partial ? ((byte)1) : ((byte)0)); zPackage.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0)); foreach (PackageEntry item in packageEntries ?? Array.Empty()) { AddEntryToPackage(zPackage, item); } foreach (CustomSyncedValueBase item2 in list2) { AddEntryToPackage(zPackage, new PackageEntry { section = "Internal", key = item2.Identifier, type = item2.Type, value = item2.BoxedValue }); } foreach (ConfigEntryBase item3 in list) { AddEntryToPackage(zPackage, new PackageEntry { section = item3.Definition.Section, key = item3.Definition.Key, type = configType(item3), value = item3.BoxedValue }); } return zPackage; } private static void AddEntryToPackage(ZPackage package, PackageEntry entry) { package.Write(entry.section); package.Write(entry.key); package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type)); AddValueToZPackage(package, entry.value); } private static string GetZPackageTypeString(Type type) { return type.AssemblyQualifiedName; } private static void AddValueToZPackage(ZPackage package, object? value) { Type type = value?.GetType(); if (value is Enum) { value = ((IConvertible)value).ToType(Enum.GetUnderlyingType(value.GetType()), CultureInfo.InvariantCulture); } else { if (value is ICollection collection) { package.Write(collection.Count); { foreach (object item in collection) { AddValueToZPackage(package, item); } return; } } if ((object)type != null && type.IsValueType && !type.IsPrimitive) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); package.Write(fields.Length); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { package.Write(GetZPackageTypeString(fieldInfo.FieldType)); AddValueToZPackage(package, fieldInfo.GetValue(value)); } return; } } ZRpc.Serialize(new object[1] { value }, ref package); } private static object ReadValueWithTypeFromZPackage(ZPackage package, Type type) { if ((object)type != null && type.IsValueType && !type.IsPrimitive && !type.IsEnum) { FieldInfo[] fields = type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); int num = package.ReadInt(); if (num != fields.Length) { throw new InvalidDeserializationTypeException { received = $"(field count: {num})", expected = $"(field count: {fields.Length})" }; } object uninitializedObject = FormatterServices.GetUninitializedObject(type); FieldInfo[] array = fields; foreach (FieldInfo fieldInfo in array) { string text = package.ReadString(); if (text != GetZPackageTypeString(fieldInfo.FieldType)) { throw new InvalidDeserializationTypeException { received = text, expected = GetZPackageTypeString(fieldInfo.FieldType), field = fieldInfo.Name }; } fieldInfo.SetValue(uninitializedObject, ReadValueWithTypeFromZPackage(package, fieldInfo.FieldType)); } return uninitializedObject; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<, >)) { int num2 = package.ReadInt(); IDictionary dictionary = (IDictionary)Activator.CreateInstance(type); Type type2 = typeof(KeyValuePair<, >).MakeGenericType(type.GenericTypeArguments); FieldInfo field = type2.GetField("key", BindingFlags.Instance | BindingFlags.NonPublic); FieldInfo field2 = type2.GetField("value", BindingFlags.Instance | BindingFlags.NonPublic); for (int j = 0; j < num2; j++) { object obj = ReadValueWithTypeFromZPackage(package, type2); dictionary.Add(field.GetValue(obj), field2.GetValue(obj)); } return dictionary; } if (type != typeof(List) && type.IsGenericType) { Type type3 = typeof(ICollection<>).MakeGenericType(type.GenericTypeArguments[0]); if ((object)type3 != null && type3.IsAssignableFrom(type)) { int num3 = package.ReadInt(); object obj2 = Activator.CreateInstance(type); MethodInfo method = type3.GetMethod("Add"); for (int k = 0; k < num3; k++) { method.Invoke(obj2, new object[1] { ReadValueWithTypeFromZPackage(package, type.GenericTypeArguments[0]) }); } return obj2; } } ParameterInfo parameterInfo = (ParameterInfo)FormatterServices.GetUninitializedObject(typeof(ParameterInfo)); AccessTools.DeclaredField(typeof(ParameterInfo), "ClassImpl").SetValue(parameterInfo, type); List parameters = new List(); ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref parameters); return parameters.First(); } } } // ---- kg.Marketplace.dll :: ServerSync.VersionCheck ---- namespace ServerSync { [PublicAPI] [HarmonyPatch] public class VersionCheck { private static readonly HashSet versionChecks; private static readonly Dictionary notProcessedNames; public string Name; private string? displayName; private string? currentVersion; private string? minimumRequiredVersion; public bool ModRequired = true; private string? ReceivedCurrentVersion; private string? ReceivedMinimumRequiredVersion; private readonly List ValidatedClients = new List(); private ConfigSync? ConfigSync; public string DisplayName { get { return displayName ?? Name; } set { displayName = value; } } public string CurrentVersion { get { return currentVersion ?? "0.0.0"; } set { currentVersion = value; } } public string MinimumRequiredVersion { get { string text = minimumRequiredVersion; if (text == null) { if (!ModRequired) { return "0.0.0"; } text = CurrentVersion; } return text; } set { minimumRequiredVersion = value; } } private static void PatchServerSync() { Patches patchInfo = PatchProcessor.GetPatchInfo(AccessTools.DeclaredMethod(typeof(ZNet), "Awake")); if (patchInfo != null && patchInfo.Postfixes.Count((Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0) { return; } Harmony harmony = new Harmony("org.bepinex.helpers.ServerSync"); foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new <>z__ReadOnlySingleElementList(typeof(VersionCheck))) where t.IsClass select t) { harmony.PatchAll(item); } } static VersionCheck() { versionChecks = new HashSet(); notProcessedNames = new Dictionary(); typeof(ThreadingHelper).GetMethod("StartSyncInvoke").Invoke(ThreadingHelper.Instance, new object[1] { new Action(PatchServerSync) }); } public VersionCheck(string name) { Name = name; ModRequired = true; versionChecks.Add(this); } public VersionCheck(ConfigSync configSync) { ConfigSync = configSync; Name = ConfigSync.Name; versionChecks.Add(this); } public void Initialize() { ReceivedCurrentVersion = null; ReceivedMinimumRequiredVersion = null; if (ConfigSync != null) { Name = ConfigSync.Name; DisplayName = ConfigSync.DisplayName; CurrentVersion = ConfigSync.CurrentVersion; MinimumRequiredVersion = ConfigSync.MinimumRequiredVersion; ModRequired = ConfigSync.ModRequired; } } private bool IsVersionOk() { if (ReceivedMinimumRequiredVersion == null || ReceivedCurrentVersion == null) { return !ModRequired; } bool 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 DisplayName + " is not installed on the server."; } if (!(new Version(CurrentVersion) >= new Version(ReceivedMinimumRequiredVersion))) { return DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". You have version " + CurrentVersion + "."; } return DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + "."; } private string ErrorServer(ZRpc rpc) { return "Disconnect: The client (" + rpc.GetSocket().GetHostName() + ") doesn't have the correct " + DisplayName + " version " + MinimumRequiredVersion; } private string Error(ZRpc? rpc = null) { if (rpc != null) { return ErrorServer(rpc); } return ErrorClient(); } private static VersionCheck[] GetFailedClient() { return versionChecks.Where((VersionCheck check) => !check.IsVersionOk()).ToArray(); } private static VersionCheck[] GetFailedServer(ZRpc rpc) { return versionChecks.Where((VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc)).ToArray(); } private static void Logout() { Game.instance.Logout(); AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, ZNet.ConnectionStatus.ErrorVersion); } private static void DisconnectClient(ZRpc rpc) { rpc.Invoke("Error", 3); } private static void CheckVersion(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, null); } private static void CheckVersion(ZRpc rpc, ZPackage pkg, Action? original) { string text = pkg.ReadString(); string text2 = pkg.ReadString(); string text3 = pkg.ReadString(); bool flag = false; foreach (VersionCheck versionCheck in versionChecks) { if (!(text != versionCheck.Name)) { Debug.Log("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + "."); versionCheck.ReceivedMinimumRequiredVersion = text2; versionCheck.ReceivedCurrentVersion = text3; if (ZNet.instance.IsServer() && versionCheck.IsVersionOk()) { versionCheck.ValidatedClients.Add(rpc); } flag = true; } } if (flag) { return; } pkg.SetPos(0); if (original != null) { original(rpc, pkg); if (pkg.GetPos() == 0) { notProcessedNames.Add(text, text3); } } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] [HarmonyPrefix] private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance) { VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient()); if (array.Length == 0) { return true; } VersionCheck[] array2 = array; foreach (VersionCheck versionCheck in array2) { Debug.LogWarning(versionCheck.Error(rpc)); } if (__instance.IsServer()) { DisconnectClient(rpc); } else { Logout(); } return false; } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] [HarmonyPrefix] private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance) { notProcessedNames.Clear(); IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc); if (dictionary.Contains("ServerSync VersionCheck".GetStableHashCode())) { object obj = dictionary["ServerSync VersionCheck".GetStableHashCode()]; Action action = (Action)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj); peer.m_rpc.Register("ServerSync VersionCheck", delegate(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, action); }); } else { peer.m_rpc.Register("ServerSync VersionCheck", CheckVersion); } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.Initialize(); if (versionCheck.ModRequired || __instance.IsServer()) { Debug.Log("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + "."); ZPackage zPackage = new ZPackage(); zPackage.Write(versionCheck.Name); zPackage.Write(versionCheck.MinimumRequiredVersion); zPackage.Write(versionCheck.CurrentVersion); peer.m_rpc.Invoke("ServerSync VersionCheck", zPackage); } } } [HarmonyPatch(typeof(ZNet), "Disconnect")] [HarmonyPrefix] private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance) { if (!__instance.IsServer()) { return; } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.ValidatedClients.Remove(peer.m_rpc); } } [HarmonyPatch(typeof(FejdStartup), "ShowConnectError")] [HarmonyPostfix] private static void ShowConnectionError(FejdStartup __instance) { if (!__instance.m_connectionFailedPanel.activeSelf || ZNet.GetConnectionStatus() != ZNet.ConnectionStatus.ErrorVersion) { return; } bool flag = false; VersionCheck[] failedClient = GetFailedClient(); if (failedClient.Length != 0) { string text = string.Join("\n", failedClient.Select((VersionCheck check) => check.Error())); TMP_Text connectionFailedError = __instance.m_connectionFailedError; connectionFailedError.text = connectionFailedError.text + "\n" + text; flag = true; } foreach (KeyValuePair item in notProcessedNames.OrderBy, string>((KeyValuePair kv) => kv.Key)) { if (!__instance.m_connectionFailedError.text.Contains(item.Key)) { TMP_Text connectionFailedError2 = __instance.m_connectionFailedError; connectionFailedError2.text = connectionFailedError2.text + "\nServer expects you to have " + item.Key + " (Version: " + item.Value + ") installed."; flag = true; } } if (flag) { RectTransform component = __instance.m_connectionFailedPanel.transform.Find("Image").GetComponent(); Vector2 sizeDelta = component.sizeDelta; sizeDelta.x = 675f; component.sizeDelta = sizeDelta; __instance.m_connectionFailedError.ForceMeshUpdate(); float num = __instance.m_connectionFailedError.renderedHeight + 105f; RectTransform component2 = component.transform.Find("ButtonOk").GetComponent(); component2.anchoredPosition = new Vector2(component2.anchoredPosition.x, component2.anchoredPosition.y - (num - component.sizeDelta.y) / 2f); sizeDelta = component.sizeDelta; sizeDelta.y = num; component.sizeDelta = sizeDelta; } } } } // ---- kg.Marketplace.dll :: ItemManager.CraftingTable ---- namespace ItemManager { [PublicAPI] public 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, Custom } } // ---- kg.Marketplace.dll :: ItemManager.ConversionPiece ---- namespace ItemManager { [PublicAPI] public enum ConversionPiece { Disabled, [InternalName("smelter")] Smelter, [InternalName("charcoal_kiln")] CharcoalKiln, [InternalName("blastfurnace")] BlastFurnace, [InternalName("windmill")] Windmill, [InternalName("piece_spinningwheel")] SpinningWheel, [InternalName("eitrrefinery")] EitrRefinery, Custom } } // ---- kg.Marketplace.dll :: ItemManager.InternalName ---- namespace ItemManager { public class InternalName : Attribute { public readonly string internalName; public InternalName(string internalName) { this.internalName = internalName; } } } // ---- kg.Marketplace.dll :: ItemManager.RequiredResourceList ---- namespace ItemManager { [PublicAPI] public class RequiredResourceList { public readonly List Requirements = new List(); 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 amountConfig, int quality = 0) { Requirements.Add(new Requirement { itemName = itemName, amountConfig = amountConfig, quality = quality }); } } } // ---- kg.Marketplace.dll :: ItemManager.CraftingStationList ---- namespace ItemManager { [PublicAPI] public class CraftingStationList { public readonly List Stations = new List(); 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 }); } } } // ---- kg.Marketplace.dll :: ItemManager.ItemRecipe ---- namespace ItemManager { [PublicAPI] public 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; public ConfigEntryBase? RecipeIsActive; } } // ---- kg.Marketplace.dll :: ItemManager.Trade ---- namespace ItemManager { [PublicAPI] public class Trade { public Trader Trader; public uint Price; public uint Stack = 1u; public string? RequiredGlobalKey; } } // ---- kg.Marketplace.dll :: ItemManager.Trader ---- namespace ItemManager { [PublicAPI] [Flags] public enum Trader { None = 0, Haldor = 1, Hildir = 2 } } // ---- kg.Marketplace.dll :: ItemManager.Requirement ---- namespace ItemManager { public struct Requirement { public string itemName; public int amount; public ConfigEntry? amountConfig; [Description("Set to a non-zero value to apply the requirement only for a specific quality")] public int quality; } } // ---- kg.Marketplace.dll :: ItemManager.CraftingStationConfig ---- namespace ItemManager { public struct CraftingStationConfig { public CraftingTable Table; public int level; public string? custom; } } // ---- kg.Marketplace.dll :: ItemManager.Configurability ---- namespace ItemManager { [Flags] public enum Configurability { Disabled = 0, Recipe = 1, Stats = 2, Drop = 4, Trader = 8, Full = 0xF } } // ---- kg.Marketplace.dll :: ItemManager.DropTargets ---- namespace ItemManager { [PublicAPI] public class DropTargets { public readonly List Drops = new List(); 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 ?? min), levelMultiplier = levelMultiplier }); } } } // ---- kg.Marketplace.dll :: ItemManager.DropTarget ---- namespace ItemManager { public struct DropTarget { public string creature; public int min; public int max; public float chance; public bool levelMultiplier; } } // ---- kg.Marketplace.dll :: ItemManager.Toggle ---- namespace ItemManager { public enum Toggle { On = 1, Off = 0 } } // ---- kg.Marketplace.dll :: ItemManager.Item ---- namespace ItemManager { [PublicAPI] public class Item { private class ItemConfig { public ConfigEntry? craft; public ConfigEntry? upgrade; public ConfigEntry table; public ConfigEntry tableLevel; public ConfigEntry customTable; public ConfigEntry? maximumTableLevel; public ConfigEntry requireOneIngredient; public ConfigEntry qualityResultAmountMultiplier; } private class TraderConfig { public ConfigEntry trader; public ConfigEntry price; public ConfigEntry stack; public ConfigEntry requiredGlobalKey; } private class RequirementQuality { public int quality; } private class ConfigurationManagerAttributes { [UsedImplicitly] public int? Order; [UsedImplicitly] public bool? Browsable; [UsedImplicitly] public string? Category; [UsedImplicitly] public Action? CustomDrawer; public Func? browsability; } [PublicAPI] public enum DamageModifier { Normal, Resistant, Weak, Immune, Ignore, VeryResistant, VeryWeak, None } private delegate void setDmgFunc(ref HitData.DamageTypes dmg, float value); private class SerializedRequirements { public readonly List Reqs; public SerializedRequirements(List reqs) { Reqs = reqs; } public SerializedRequirements(string reqs) : this(reqs.Split(new char[1] { ',' }).Select(delegate(string r) { string[] array = r.Split(new char[1] { ':' }); int result; int result2; return new Requirement { itemName = array[0], amount = ((array.Length <= 1 || !int.TryParse(array[1], out result)) ? 1 : result), quality = ((array.Length > 2 && int.TryParse(array[2], out result2)) ? result2 : 0) }; }).ToList()) { } public override string ToString() { return string.Join(",", Reqs.Select((Requirement r) => $"{r.itemName}:{r.amount}" + ((r.quality > 0) ? $":{r.quality}" : ""))); } public static ItemDrop? fetchByName(ObjectDB objectDB, string name) { ItemDrop itemDrop = objectDB.GetItemPrefab(name)?.GetComponent(); if (itemDrop == null) { Debug.LogWarning("The required item '" + name + "' does not exist."); } return itemDrop; } public static Piece.Requirement[] toPieceReqs(ObjectDB objectDB, SerializedRequirements craft, SerializedRequirements upgrade) { Dictionary dictionary = craft.Reqs.Where((Requirement r) => r.itemName != "").ToDictionary((Requirement r) => r.itemName, delegate(Requirement r) { ItemDrop itemDrop3 = ResItem(r); return ((object)itemDrop3 == null) ? null : new Piece.Requirement { m_amount = (r.amountConfig?.Value ?? r.amount), m_resItem = itemDrop3, m_amountPerLevel = 0 }; }); List list = dictionary.Values.Where((Piece.Requirement v) => v != null).ToList(); foreach (Requirement item in upgrade.Reqs.Where((Requirement r) => r.itemName != "")) { if (item.quality > 0) { ItemDrop itemDrop = ResItem(item); if ((object)itemDrop != null) { Piece.Requirement requirement = new Piece.Requirement { m_resItem = itemDrop, m_amountPerLevel = (item.amountConfig?.Value ?? item.amount), m_amount = 0 }; list.Add(requirement); requirementQuality.Add(requirement, new RequirementQuality { quality = item.quality }); } continue; } if (!dictionary.TryGetValue(item.itemName, out var value) || value == null) { ItemDrop itemDrop2 = ResItem(item); if ((object)itemDrop2 != null) { string itemName = item.itemName; Piece.Requirement obj = new Piece.Requirement { m_resItem = itemDrop2, m_amount = 0 }; Piece.Requirement requirement2 = obj; dictionary[itemName] = obj; value = requirement2; list.Add(value); } } if (value != null) { value.m_amountPerLevel = item.amountConfig?.Value ?? item.amount; } } return list.ToArray(); ItemDrop? ResItem(Requirement r) { return fetchByName(objectDB, r.itemName); } } } private class SerializedDrop { public readonly List Drops; public SerializedDrop(List drops) { Drops = drops; } public SerializedDrop(string drops) { Drops = ((drops == "") ? Array.Empty() : drops.Split(new char[1] { ',' })).Select(delegate(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"; float result3; return new DropTarget { creature = array[0], chance = ((array.Length > 1 && float.TryParse(array[1], out result3)) ? result3 : 1f), min = result, max = result2, levelMultiplier = levelMultiplier }; }).ToList(); } public override string ToString() { return string.Join(",", Drops.Select((DropTarget r) => $"{r.creature}:{r.chance.ToString(CultureInfo.InvariantCulture)}:{r.min}:" + ((r.min == r.max) ? "" : $"{r.max}") + (r.levelMultiplier ? "" : ":0"))); } private static Character? fetchByName(ZNetScene netScene, string name) { Character character = netScene.GetPrefab(name)?.GetComponent(); if (character == null) { Debug.LogWarning("The drop target character '" + name + "' does not exist."); } return character; } public Dictionary toCharacterDrops(ZNetScene netScene, GameObject item) { Dictionary dictionary = new Dictionary(); foreach (DropTarget drop in Drops) { Character character = fetchByName(netScene, drop.creature); if ((object)character != null) { dictionary[character] = new CharacterDrop.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 registeredItems = new List(); private static readonly Dictionary itemDropMap = new Dictionary(); private static Dictionary>> activeRecipes = new Dictionary>>(); private static Dictionary hiddenCraftRecipes = new Dictionary(); private static Dictionary hiddenUpgradeRecipes = new Dictionary(); private static Dictionary> itemCraftConfigs = new Dictionary>(); private static Dictionary> itemDropConfigs = new Dictionary>(); private Dictionary characterDrops = new Dictionary(); private readonly Dictionary statsConfigs = new Dictionary(); private static readonly ConditionalWeakTable requirementQuality = new ConditionalWeakTable(); public static Configurability DefaultConfigurability = Configurability.Full; public Configurability? Configurable; private Configurability configurationVisible = Configurability.Full; 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 Conversions = new List(); internal List conversions = new List(); public Dictionary Recipes = new Dictionary(); private LocalizeKey? _name; private LocalizeKey? _description; private static object? configManager; private static Localization? _english; private static BaseUnityPlugin? _plugin; private static bool hasConfigSync = true; 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.")] public ConfigEntryBase? RecipeIsActive { get { return this[""].RecipeIsActive; } 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 ItemRecipe value)) { return value; } return Recipes[name] = new ItemRecipe(); } } public LocalizeKey Name { get { LocalizeKey name = _name; if (name != null) { return name; } ItemDrop.ItemData.SharedData shared = Prefab.GetComponent().m_itemData.m_shared; if (shared.m_name.StartsWith("$")) { _name = new LocalizeKey(shared.m_name); } else { string text = "$item_" + Prefab.name.Replace(" ", "_"); _name = new LocalizeKey(text).English(shared.m_name); shared.m_name = text; } return _name; } } public LocalizeKey Description { get { LocalizeKey description = _description; if (description != null) { return description; } ItemDrop.ItemData.SharedData shared = Prefab.GetComponent().m_itemData.m_shared; if (shared.m_description.StartsWith("$")) { _description = new LocalizeKey(shared.m_description); } else { string text = "$itemdesc_" + Prefab.name.Replace(" ", "_"); _description = new LocalizeKey(text).English(shared.m_description); shared.m_description = text; } return _description; } } private static Localization english => _english ?? (_english = LocalizationCache.ForLanguage("English")); private static BaseUnityPlugin plugin { get { if ((object)_plugin == null) { IEnumerable 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(source.First((TypeInfo t) => t.IsClass && typeof(BaseUnityPlugin).IsAssignableFrom(t))); } return _plugin; } } private static object? configSync { 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()] = this; Prefab.GetComponent().m_itemData.m_dropPrefab = Prefab; } public void ToggleConfigurationVisibility(Configurability visible) { configurationVisible = visible; if (itemDropConfigs.TryGetValue(this, out ConfigEntry value)) { Toggle(value, Configurability.Drop); } if (itemCraftConfigs.TryGetValue(this, out Dictionary value2)) { foreach (ItemConfig value3 in value2.Values) { ToggleObj(value3, Configurability.Recipe); } } foreach (Conversion conversion in Conversions) { if (conversion.config != null) { ToggleObj(conversion.config, Configurability.Recipe); } } foreach (KeyValuePair statsConfig in statsConfigs) { Toggle(statsConfig.Key, Configurability.Stats); if ((visible & Configurability.Stats) != Configurability.Disabled) { statsConfig.Value(); } } reloadConfigDisplay(); void Toggle(ConfigEntryBase cfg, Configurability check) { object[] tags = cfg.Description.Tags; foreach (object obj in tags) { if (obj is ConfigurationManagerAttributes configurationManagerAttributes) { configurationManagerAttributes.Browsable = (visible & check) != Configurability.Disabled && (configurationManagerAttributes.browsability == null || configurationManagerAttributes.browsability()); } } } void ToggleObj(object obj, Configurability check) { FieldInfo[] fields = obj.GetType().GetFields(); foreach (FieldInfo fieldInfo in fields) { if (fieldInfo.GetValue(obj) is ConfigEntryBase cfg) { Toggle(cfg, 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()); } } private void UpdateItemTableConfig(string recipeKey, CraftingTable table, string customTableValue) { if (activeRecipes.ContainsKey(this) && activeRecipes[this].TryGetValue(recipeKey, out List value)) { value.First().m_enabled = table != CraftingTable.Disabled; if ((uint)table <= 1u) { value.First().m_craftingStation = null; } else if (table == CraftingTable.Custom) { value.First().m_craftingStation = ZNetScene.instance.GetPrefab(customTableValue)?.GetComponent(); } else { value.First().m_craftingStation = ZNetScene.instance.GetPrefab(getInternalName(table)).GetComponent(); } } } private void UpdateCraftConfig(string recipeKey, SerializedRequirements craftRequirements, SerializedRequirements upgradeRequirements) { if (!ObjectDB.instance || !activeRecipes.ContainsKey(this) || !activeRecipes[this].TryGetValue(recipeKey, out List value)) { return; } foreach (Recipe item in value) { item.m_resources = SerializedRequirements.toPieceReqs(ObjectDB.instance, craftRequirements, upgradeRequirements); } } internal static void Patch_FejdStartup() { Type type = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault((Assembly a) => a.GetName().Name == "ConfigurationManager")?.GetType("ConfigurationManager.ConfigurationManager"); if (DefaultConfigurability != Configurability.Disabled) { bool saveOnConfigSet = plugin.Config.SaveOnConfigSet; plugin.Config.SaveOnConfigSet = false; foreach (Item item3 in registeredItems.Where((Item i) => i.configurability != Configurability.Disabled)) { Item item = item3; string name = item.Prefab.GetComponent().m_itemData.m_shared.m_name; string englishName = new Regex("['\\[\"\\]]").Replace(english.Localize(name), "").Trim(); string localizedName = Localization.instance.Localize(name).Trim(); int order = 0; if ((item.configurability & Configurability.Recipe) != Configurability.Disabled) { itemCraftConfigs[item] = new Dictionary(); foreach (string item4 in item.Recipes.Keys.DefaultIfEmpty("")) { string configKey = item4; string text = ((configKey == "") ? "" : (" (" + configKey + ")")); if (!item.Recipes.ContainsKey(configKey) || item.Recipes[configKey].Crafting.Stations.Count <= 0) { continue; } ItemConfig itemConfig2 = (itemCraftConfigs[item][configKey] = new ItemConfig()); ItemConfig cfg = itemConfig2; List hideWhenNoneAttributes = new List(); cfg.table = config(englishName, "Crafting Station" + text, item.Recipes[configKey].Crafting.Stations.First().Table, new ConfigDescription("Crafting station where " + englishName + " is available.", null, new ConfigurationManagerAttributes { Order = (order -= 1), Browsable = ((item.configurationVisible & Configurability.Recipe) != 0), Category = localizedName })); ConfigurationManagerAttributes customTableAttributes = new ConfigurationManagerAttributes { Order = (order -= 1), browsability = CustomTableBrowsability, Browsable = (CustomTableBrowsability() && (item.configurationVisible & Configurability.Recipe) != 0), Category = localizedName }; cfg.customTable = config(englishName, "Custom Crafting Station" + text, item.Recipes[configKey].Crafting.Stations.First().custom ?? "", new ConfigDescription("", null, customTableAttributes)); cfg.table.SettingChanged += TableConfigChanged; cfg.customTable.SettingChanged += TableConfigChanged; ConfigurationManagerAttributes configurationManagerAttributes = new ConfigurationManagerAttributes { Order = (order -= 1), browsability = TableLevelBrowsability, Browsable = (TableLevelBrowsability() && (item.configurationVisible & Configurability.Recipe) != 0), Category = localizedName }; hideWhenNoneAttributes.Add(configurationManagerAttributes); cfg.tableLevel = config(englishName, "Crafting Station Level" + text, item.Recipes[configKey].Crafting.Stations.First().level, new ConfigDescription("Required crafting station level to craft " + englishName + ".", null, configurationManagerAttributes)); cfg.tableLevel.SettingChanged += delegate { if (activeRecipes.ContainsKey(item) && activeRecipes[item].TryGetValue(configKey, out List value)) { value.First().m_minStationLevel = cfg.tableLevel.Value; } }; if (item.Prefab.GetComponent().m_itemData.m_shared.m_maxQuality > 1) { cfg.maximumTableLevel = config(englishName, "Maximum Crafting Station Level" + text, (item.MaximumRequiredStationLevel == int.MaxValue) ? (item.Recipes[configKey].Crafting.Stations.First().level + item.Prefab.GetComponent().m_itemData.m_shared.m_maxQuality - 1) : item.MaximumRequiredStationLevel, new ConfigDescription("Maximum crafting station level to upgrade and repair " + englishName + ".", null, configurationManagerAttributes)); } cfg.requireOneIngredient = config(englishName, "Require only one resource" + text, item.Recipes[configKey].RequireOnlyOneIngredient ? Toggle.On : Toggle.Off, new ConfigDescription("Whether only one of the ingredients is needed to craft " + englishName, null, new ConfigurationManagerAttributes { Order = (order -= 1), Category = localizedName })); ConfigurationManagerAttributes qualityResultAttributes = new ConfigurationManagerAttributes { Order = (order -= 1), browsability = QualityResultBrowsability, Browsable = (QualityResultBrowsability() && (item.configurationVisible & Configurability.Recipe) != 0), Category = localizedName }; cfg.requireOneIngredient.SettingChanged += delegate { if (activeRecipes.ContainsKey(item) && activeRecipes[item].TryGetValue(configKey, out List value)) { foreach (Recipe item5 in value) { item5.m_requireOnlyOneIngredient = cfg.requireOneIngredient.Value == Toggle.On; } } qualityResultAttributes.Browsable = QualityResultBrowsability(); reloadConfigDisplay(); }; cfg.qualityResultAmountMultiplier = config(englishName, "Quality Multiplier" + text, item.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.", null, qualityResultAttributes)); cfg.qualityResultAmountMultiplier.SettingChanged += delegate { if (activeRecipes.ContainsKey(item) && activeRecipes[item].TryGetValue(configKey, out List value)) { foreach (Recipe item6 in value) { item6.m_qualityResultAmountMultiplier = cfg.qualityResultAmountMultiplier.Value; } } }; if ((!item.Recipes[configKey].RequiredItems.Free || item.Recipes[configKey].RequiredItems.Requirements.Count > 0) && item.Recipes[configKey].RequiredItems.Requirements.All((Requirement r) => r.amountConfig == null)) { cfg.craft = itemConfig("Crafting Costs" + text, new SerializedRequirements(item.Recipes[configKey].RequiredItems.Requirements).ToString(), "Item costs to craft " + englishName, isUpgrade: false); } if (item.Prefab.GetComponent().m_itemData.m_shared.m_maxQuality > 1 && (!item.Recipes[configKey].RequiredUpgradeItems.Free || item.Recipes[configKey].RequiredUpgradeItems.Requirements.Count > 0) && item.Recipes[configKey].RequiredUpgradeItems.Requirements.All((Requirement r) => r.amountConfig == null)) { cfg.upgrade = itemConfig("Upgrading Costs" + text, new SerializedRequirements(item.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) { item.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; } ConfigEntry itemConfig(string name2, string value, string desc, bool isUpgrade) { ConfigurationManagerAttributes configurationManagerAttributes2 = new ConfigurationManagerAttributes { CustomDrawer = drawRequirementsConfigTable(item, isUpgrade), Order = (order -= 1), browsability = ItemBrowsability, Browsable = (ItemBrowsability() && (item.configurationVisible & Configurability.Recipe) != 0), Category = localizedName }; hideWhenNoneAttributes.Add(configurationManagerAttributes2); return config(englishName, name2, value, new ConfigDescription(desc, null, configurationManagerAttributes2)); } bool QualityResultBrowsability() { return cfg.requireOneIngredient.Value == Toggle.On; } void TableConfigChanged(object o, EventArgs e) { item.UpdateItemTableConfig(configKey, cfg.table.Value, cfg.customTable.Value); customTableAttributes.Browsable = cfg.table.Value == CraftingTable.Custom; foreach (ConfigurationManagerAttributes item7 in hideWhenNoneAttributes) { item7.Browsable = cfg.table.Value != CraftingTable.Disabled; } reloadConfigDisplay(); } bool TableLevelBrowsability() { return cfg.table.Value != CraftingTable.Disabled; } } if ((item.configurability & Configurability.Drop) != Configurability.Disabled) { ConfigEntry configEntry = (itemDropConfigs[item] = config(englishName, "Drops from", new SerializedDrop(item.DropsFrom.Drops).ToString(), new ConfigDescription(englishName + " drops from this creature.", null, new ConfigurationManagerAttributes { CustomDrawer = drawDropsConfigTable, Category = localizedName, Browsable = ((item.configurationVisible & Configurability.Drop) != 0) }))); ConfigEntry configEntry3 = configEntry; configEntry3.SettingChanged += delegate { item.UpdateCharacterDrop(); }; } for (int num = 0; num < item.Conversions.Count; num++) { string text2 = ((item.Conversions.Count > 1) ? $"{num + 1}. " : ""); Conversion conversion = item.Conversions[num]; conversion.config = new Conversion.ConversionConfig(); int index = num; conversion.config.input = config(englishName, text2 + "Conversion Input Item", conversion.Input, new ConfigDescription("Input item to create " + englishName, null, new ConfigurationManagerAttributes { Category = localizedName, Browsable = ((item.configurationVisible & Configurability.Recipe) != 0) })); conversion.config.input.SettingChanged += delegate { if (index < item.conversions.Count) { ObjectDB instance = ObjectDB.instance; if ((object)instance != null) { ItemDrop itemDrop = SerializedRequirements.fetchByName(instance, conversion.config.input.Value); item.conversions[index].m_from = itemDrop; UpdatePiece(); } } }; conversion.config.piece = config(englishName, text2 + "Conversion Piece", conversion.Piece, new ConfigDescription("Conversion piece used to create " + englishName, null, new ConfigurationManagerAttributes { Category = localizedName, Browsable = ((item.configurationVisible & Configurability.Recipe) != 0) })); conversion.config.piece.SettingChanged += delegate { UpdatePiece(); }; conversion.config.customPiece = config(englishName, text2 + "Conversion Custom Piece", conversion.customPiece ?? "", new ConfigDescription("Custom conversion piece to create " + englishName, null, new ConfigurationManagerAttributes { Category = localizedName, Browsable = ((item.configurationVisible & Configurability.Recipe) != 0) })); conversion.config.customPiece.SettingChanged += delegate { UpdatePiece(); }; void UpdatePiece() { if (index < item.conversions.Count && (bool)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) { Smelter component = ZNetScene.instance.GetPrefab(conversion.config.activePiece).GetComponent(); int num4 = component.m_conversion.IndexOf(item.conversions[index]); if (num4 >= 0) { Smelter[] array2 = Resources.FindObjectsOfTypeAll(); foreach (Smelter smelter in array2) { if (Utils.GetPrefabName(smelter.gameObject) == activePiece) { smelter.m_conversion.RemoveAt(num4); } } } conversion.config.activePiece = null; } if ((object)item.conversions[index].m_from != null && conversion.config.piece.Value != ConversionPiece.Disabled && (object)ZNetScene.instance.GetPrefab(text3)?.GetComponent() != null) { conversion.config.activePiece = text3; Smelter[] array3 = Resources.FindObjectsOfTypeAll(); foreach (Smelter smelter2 in array3) { if (Utils.GetPrefabName(smelter2.gameObject) == text3) { smelter2.m_conversion.Add(item.conversions[index]); } } } } } } } if ((item.configurability & Configurability.Stats) != Configurability.Disabled) { item.statsConfigs.Clear(); ItemDrop.ItemData.SharedData shared = item.Prefab.GetComponent().m_itemData.m_shared; ItemDrop.ItemData.ItemType itemType = shared.m_itemType; statcfg("Weight", "Weight of " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_weight, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_weight = value; }); statcfg("Trader Value", "Trader value of " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_value, delegate(ItemDrop.ItemData.SharedData sharedData, int value) { sharedData.m_value = value; }); bool flag; switch (itemType) { case ItemDrop.ItemData.ItemType.OneHandedWeapon: case ItemDrop.ItemData.ItemType.Bow: case ItemDrop.ItemData.ItemType.Shield: case ItemDrop.ItemData.ItemType.Helmet: case ItemDrop.ItemData.ItemType.Chest: case ItemDrop.ItemData.ItemType.Legs: case ItemDrop.ItemData.ItemType.Hands: case ItemDrop.ItemData.ItemType.TwoHandedWeapon: case ItemDrop.ItemData.ItemType.Shoulder: case ItemDrop.ItemData.ItemType.Tool: case ItemDrop.ItemData.ItemType.TwoHandedWeaponLeft: flag = true; break; default: flag = false; break; } if (flag) { statcfg("Durability", "Durability of " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_maxDurability, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_maxDurability = value; }); statcfg("Durability per Level", "Durability gain per level of " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_durabilityPerLevel, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_durabilityPerLevel = value; }); statcfg("Movement Speed Modifier", "Movement speed modifier of " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_movementModifier, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_movementModifier = value; }); } if (((uint)(itemType - 3) <= 2u || itemType == ItemDrop.ItemData.ItemType.TwoHandedWeapon || itemType == ItemDrop.ItemData.ItemType.TwoHandedWeaponLeft) ? true : false) { statcfg("Block Armor", "Block armor of " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_blockPower, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_blockPower = value; }); statcfg("Block Armor per Level", "Block armor per level for " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_blockPowerPerLevel, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_blockPowerPerLevel = value; }); statcfg("Block Force", "Block force of " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_deflectionForce, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_deflectionForce = value; }); statcfg("Block Force per Level", "Block force per level for " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_deflectionForcePerLevel, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_deflectionForcePerLevel = value; }); statcfg("Parry Bonus", "Parry bonus of " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_timedBlockBonus, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_timedBlockBonus = value; }); } else if (((uint)(itemType - 6) <= 1u || (uint)(itemType - 11) <= 1u || itemType == ItemDrop.ItemData.ItemType.Shoulder) ? true : false) { statcfg("Armor", "Armor of " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_armor, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_armor = value; }); statcfg("Armor per Level", "Armor per level for " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_armorPerLevel, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_armorPerLevel = value; }); } Skills.SkillType skillType = shared.m_skillType; if ((skillType == Skills.SkillType.Axes || skillType == Skills.SkillType.Pickaxes) ? true : false) { statcfg("Tool tier", "Tool tier of " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_toolTier, delegate(ItemDrop.ItemData.SharedData sharedData, int value) { sharedData.m_toolTier = value; }); } if (((uint)(itemType - 5) <= 2u || (uint)(itemType - 11) <= 1u || itemType == ItemDrop.ItemData.ItemType.Shoulder) ? true : false) { Dictionary modifiers = shared.m_damageModifiers.ToDictionary((HitData.DamageModPair d) => d.m_type, (HitData.DamageModPair d) => (DamageModifier)d.m_modifier); foreach (HitData.DamageType damageType in ((HitData.DamageType[])Enum.GetValues(typeof(HitData.DamageType))).Except(new <>z__ReadOnlyArray(new HitData.DamageType[5] { HitData.DamageType.Chop, HitData.DamageType.Pickaxe, HitData.DamageType.Spirit, HitData.DamageType.Physical, HitData.DamageType.Elemental }))) { statcfg(damageType.ToString() + " Resistance", damageType.ToString() + " resistance of " + englishName + ".", (ItemDrop.ItemData.SharedData _) => (!modifiers.TryGetValue(damageType, out var value)) ? DamageModifier.None : value, delegate(ItemDrop.ItemData.SharedData sharedData, DamageModifier value) { HitData.DamageModPair damageModPair = new HitData.DamageModPair { m_type = damageType, m_modifier = (HitData.DamageModifier)value }; for (int i = 0; i < sharedData.m_damageModifiers.Count; i++) { if (sharedData.m_damageModifiers[i].m_type == damageType) { if (value == DamageModifier.None) { sharedData.m_damageModifiers.RemoveAt(i); } else { sharedData.m_damageModifiers[i] = damageModPair; } return; } } if (value != DamageModifier.None) { sharedData.m_damageModifiers.Add(damageModPair); } }); } } if (itemType == ItemDrop.ItemData.ItemType.Consumable && shared.m_food > 0f) { statcfg("Health", "Health value of " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_food, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_food = value; }); statcfg("Stamina", "Stamina value of " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_foodStamina, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_foodStamina = value; }); statcfg("Eitr", "Eitr value of " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_foodEitr, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_foodEitr = value; }); statcfg("Duration", "Duration of " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_foodBurnTime, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_foodBurnTime = value; }); statcfg("Health Regen", "Health regen value of " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_foodRegen, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_foodRegen = value; }); } if (shared.m_skillType == Skills.SkillType.BloodMagic) { statcfg("Health Cost", "Health cost of " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_attack.m_attackHealth, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_attack.m_attackHealth = value; }); statcfg("Health Cost Percentage", "Health cost percentage of " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_attack.m_attackHealthPercentage, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_attack.m_attackHealthPercentage = value; }); } skillType = shared.m_skillType; if ((uint)(skillType - 9) <= 1u) { statcfg("Eitr Cost", "Eitr cost of " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_attack.m_attackEitr, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_attack.m_attackEitr = value; }); } if (((uint)(itemType - 3) <= 1u || itemType == ItemDrop.ItemData.ItemType.TwoHandedWeapon || itemType == ItemDrop.ItemData.ItemType.TwoHandedWeaponLeft) ? true : false) { statcfg("Knockback", "Knockback of " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_attackForce, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_attackForce = value; }); statcfg("Backstab Bonus", "Backstab bonus of " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_backstabBonus, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_backstabBonus = value; }); statcfg("Attack Stamina", "Attack stamina of " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_attack.m_attackStamina, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_attack.m_attackStamina = value; }); SetDmg("True", (HitData.DamageTypes dmg) => dmg.m_damage, delegate(ref HitData.DamageTypes dmg, float val) { dmg.m_damage = val; }); SetDmg("Slash", (HitData.DamageTypes dmg) => dmg.m_slash, delegate(ref HitData.DamageTypes dmg, float val) { dmg.m_slash = val; }); SetDmg("Pierce", (HitData.DamageTypes dmg) => dmg.m_pierce, delegate(ref HitData.DamageTypes dmg, float val) { dmg.m_pierce = val; }); SetDmg("Blunt", (HitData.DamageTypes dmg) => dmg.m_blunt, delegate(ref HitData.DamageTypes dmg, float val) { dmg.m_blunt = val; }); SetDmg("Chop", (HitData.DamageTypes dmg) => dmg.m_chop, delegate(ref HitData.DamageTypes dmg, float val) { dmg.m_chop = val; }); SetDmg("Pickaxe", (HitData.DamageTypes dmg) => dmg.m_pickaxe, delegate(ref HitData.DamageTypes dmg, float val) { dmg.m_pickaxe = val; }); SetDmg("Fire", (HitData.DamageTypes dmg) => dmg.m_fire, delegate(ref HitData.DamageTypes dmg, float val) { dmg.m_fire = val; }); SetDmg("Poison", (HitData.DamageTypes dmg) => dmg.m_poison, delegate(ref HitData.DamageTypes dmg, float val) { dmg.m_poison = val; }); SetDmg("Frost", (HitData.DamageTypes dmg) => dmg.m_frost, delegate(ref HitData.DamageTypes dmg, float val) { dmg.m_frost = val; }); SetDmg("Lightning", (HitData.DamageTypes dmg) => dmg.m_lightning, delegate(ref HitData.DamageTypes dmg, float val) { dmg.m_lightning = val; }); SetDmg("Spirit", (HitData.DamageTypes dmg) => dmg.m_spirit, delegate(ref HitData.DamageTypes dmg, float val) { dmg.m_spirit = val; }); if (itemType == ItemDrop.ItemData.ItemType.Bow) { statcfg("Projectiles", "Number of projectiles that " + englishName + " shoots at once.", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_attack.m_projectileBursts, delegate(ItemDrop.ItemData.SharedData sharedData, int value) { sharedData.m_attack.m_projectileBursts = value; }); statcfg("Burst Interval", "Time between the projectiles " + englishName + " shoots at once.", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_attack.m_burstInterval, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_attack.m_burstInterval = value; }); statcfg("Minimum Accuracy", "Minimum accuracy for " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_attack.m_projectileAccuracyMin, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_attack.m_projectileAccuracyMin = value; }); statcfg("Accuracy", "Accuracy for " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_attack.m_projectileAccuracy, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_attack.m_projectileAccuracy = value; }); statcfg("Minimum Velocity", "Minimum velocity for " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_attack.m_projectileVelMin, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_attack.m_projectileVelMin = value; }); statcfg("Velocity", "Velocity for " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_attack.m_projectileVel, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_attack.m_projectileVel = value; }); statcfg("Maximum Draw Time", "Time until " + englishName + " is fully drawn at skill level 0.", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_attack.m_drawDurationMin, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_attack.m_drawDurationMin = value; }); statcfg("Stamina Drain", "Stamina drain per second while drawing " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => sharedData.m_attack.m_drawStaminaDrain, delegate(ItemDrop.ItemData.SharedData sharedData, float value) { sharedData.m_attack.m_drawStaminaDrain = value; }); } } } List traderAttributes; if ((item.configurability & Configurability.Trader) != Configurability.Disabled) { traderAttributes = new List(); item.traderConfig = new TraderConfig { trader = config(englishName, "Trader Selling", item.Trade.Trader, new ConfigDescription("Which traders sell " + englishName + ".", null, new ConfigurationManagerAttributes { Order = (order -= 1), Browsable = ((item.configurationVisible & Configurability.Trader) != 0), Category = localizedName })) }; item.traderConfig.trader.SettingChanged += delegate { item.ReloadTraderConfiguration(); foreach (ConfigurationManagerAttributes item8 in traderAttributes) { item8.Browsable = TraderBrowsability(); } reloadConfigDisplay(); }; item.traderConfig.price = traderConfig("Trader Price", item.Trade.Price, "Price of " + englishName + " at the trader."); item.traderConfig.stack = traderConfig("Trader Stack", item.Trade.Stack, "Stack size of " + englishName + " in the trader. Also known as the number of items sold by a trader in one transaction."); item.traderConfig.requiredGlobalKey = traderConfig("Trader Required Global Key", item.Trade.RequiredGlobalKey ?? "", "Required global key to unlock " + englishName + " at the trader."); if (item.traderConfig.trader.Value != Trader.None) { PrefabManager.AddItemToTrader(item.Prefab, item.traderConfig.trader.Value, item.traderConfig.price.Value, item.traderConfig.stack.Value, item.traderConfig.requiredGlobalKey.Value); } } else if (item.Trade.Trader != Trader.None) { PrefabManager.AddItemToTrader(item.Prefab, item.Trade.Trader, item.Trade.Price, item.Trade.Stack, item.Trade.RequiredGlobalKey); } void SetDmg(string dmgType, Func readDmg, setDmgFunc setDmg) { statcfg(dmgType + " Damage", dmgType + " damage dealt by " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => readDmg(sharedData.m_damages), delegate(ItemDrop.ItemData.SharedData sharedData, float val) { setDmg(ref sharedData.m_damages, val); }); statcfg(dmgType + " Damage Per Level", dmgType + " damage dealt increase per level for " + englishName + ".", (ItemDrop.ItemData.SharedData sharedData) => readDmg(sharedData.m_damagesPerLevel), delegate(ItemDrop.ItemData.SharedData sharedData, float val) { setDmg(ref sharedData.m_damagesPerLevel, val); }); } void statcfg(string configName, string description, Func readDefault, Action setValue) where T : notnull { ItemDrop.ItemData.SharedData shared2 = item.Prefab.GetComponent().m_itemData.m_shared; ConfigEntry cfg2 = config(englishName, configName, readDefault(shared2), new ConfigDescription(description, null, new ConfigurationManagerAttributes { Category = localizedName, Browsable = ((item.configurationVisible & Configurability.Stats) != 0) })); if ((item.configurationVisible & Configurability.Stats) != Configurability.Disabled) { setValue(shared2, cfg2.Value); } item.statsConfigs.Add(cfg2, ApplyConfig); cfg2.SettingChanged += delegate { if ((item.configurationVisible & Configurability.Stats) != Configurability.Disabled) { ApplyConfig(); } }; void ApplyConfig() { item.ApplyToAllInstances(delegate(ItemDrop.ItemData itemData) { setValue(itemData.m_shared, cfg2.Value); }); } } bool TraderBrowsability() { return item.traderConfig.trader.Value != Trader.None; } ConfigEntry traderConfig(string name2, T value, string desc) where T : notnull { ConfigurationManagerAttributes configurationManagerAttributes2 = new ConfigurationManagerAttributes { Order = (order -= 1), browsability = TraderBrowsability, Browsable = (TraderBrowsability() && (item.configurationVisible & Configurability.Trader) != 0), Category = localizedName }; traderAttributes.Add(configurationManagerAttributes2); ConfigEntry configEntry4 = config(englishName, name2, value, new ConfigDescription(desc, null, configurationManagerAttributes2)); configEntry4.SettingChanged += delegate { item.ReloadTraderConfiguration(); }; return configEntry4; } } 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 recipe in item2.Recipes) { KeyValuePair kv = recipe; RequiredResourceList[] array = new RequiredResourceList[2] { kv.Value.RequiredItems, kv.Value.RequiredUpgradeItems }; foreach (RequiredResourceList requiredResourceList in array) { for (int num3 = 0; num3 < requiredResourceList.Requirements.Count; num3++) { ConfigEntry amountCfg; int resourceIndex; if ((item2.configurability & Configurability.Recipe) != Configurability.Disabled) { amountCfg = requiredResourceList.Requirements[num3].amountConfig; if (amountCfg != null) { resourceIndex = num3; amountCfg.SettingChanged += ConfigChanged2; } } void ConfigChanged2(object o, EventArgs e) { if ((bool)ObjectDB.instance && activeRecipes.ContainsKey(item2) && activeRecipes[item2].TryGetValue(kv.Key, out List value)) { foreach (Recipe item9 in value) { item9.m_resources[resourceIndex].m_amount = amountCfg.Value; } } } } } } item2.InitializeNewRegisteredItem(); } } private void InitializeNewRegisteredItem() { foreach (KeyValuePair recipe in Recipes) { KeyValuePair kv = recipe; ConfigEntryBase enabledCfg = kv.Value.RecipeIsActive; if (enabledCfg != null) { enabledCfg.GetType().GetEvent("SettingChanged").AddEventHandler(enabledCfg, new EventHandler(ConfigChanged)); } void ConfigChanged(object o, EventArgs e) { if ((bool)ObjectDB.instance && activeRecipes.ContainsKey(this) && activeRecipes[this].TryGetValue(kv.Key, out List value)) { foreach (Recipe item in value) { item.m_enabled = (int)enabledCfg.BoxedValue != 0; } } } } } public void ReloadCraftingConfiguration() { if ((bool)ObjectDB.instance && (object)ObjectDB.instance.GetItemPrefab(Prefab.name.GetStableHashCode()) == null) { registerRecipesInObjectDB(ObjectDB.instance); ObjectDB.instance.m_items.Add(Prefab); ObjectDB.instance.m_itemByHash.Add(Prefab.name.GetStableHashCode(), Prefab); ZNetScene.instance.m_prefabs.Add(Prefab); ZNetScene.instance.m_namedPrefabs.Add(Prefab.name.GetStableHashCode(), Prefab); } foreach (string item in Recipes.Keys.DefaultIfEmpty("")) { if (Recipes.TryGetValue(item, out ItemRecipe 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 callback) { callback(prefab.GetComponent().m_itemData); string name = prefab.GetComponent().m_itemData.m_shared.m_name; Inventory[] source = (from c in Player.s_players.Select((Player p) => p.GetInventory()).Concat(from c in UnityEngine.Object.FindObjectsOfType() select c.GetInventory()) where c != null select c).ToArray(); foreach (ItemDrop.ItemData item in (from i in (from p in ObjectDB.instance.m_items select p.GetComponent() into c where (bool)c && (bool)c.GetComponent() select c).Concat(ItemDrop.s_instances) select i.m_itemData).Concat(source.SelectMany((Inventory i) => i.GetAllItems()))) { if (item.m_shared.m_name == name) { callback(item); } } } public void ApplyToAllInstances(Action callback) { ApplyToAllInstances(Prefab, callback); } private static string getInternalName(T value) where T : struct { return ((InternalName)typeof(T).GetMember(value.ToString())[0].GetCustomAttributes(typeof(InternalName)).First()).internalName; } private void registerRecipesInObjectDB(ObjectDB objectDB) { activeRecipes[this] = new Dictionary>(); itemCraftConfigs.TryGetValue(this, out Dictionary value); foreach (KeyValuePair recipe2 in Recipes) { List list = new List(); foreach (CraftingStationConfig station in recipe2.Value.Crafting.Stations) { ItemConfig itemConfig = value?[recipe2.Key]; Recipe recipe = ScriptableObject.CreateInstance(); string name = Prefab.name; CraftingTable table = station.Table; recipe.name = name + "_Recipe_" + table; recipe.m_amount = recipe2.Value.CraftAmount; recipe.m_enabled = ((itemConfig == null) ? ((int)(recipe2.Value.RecipeIsActive?.BoxedValue ?? ((object)1)) != 0) : (itemConfig.table.Value != CraftingTable.Disabled)); recipe.m_item = Prefab.GetComponent(); recipe.m_resources = SerializedRequirements.toPieceReqs(objectDB, (itemConfig?.craft == null) ? new SerializedRequirements(recipe2.Value.RequiredItems.Requirements) : new SerializedRequirements(itemConfig.craft.Value), (itemConfig?.upgrade == null) ? new SerializedRequirements(recipe2.Value.RequiredUpgradeItems.Requirements) : new SerializedRequirements(itemConfig.upgrade.Value)); table = ((itemConfig == null || list.Count > 0) ? station.Table : itemConfig.table.Value); if ((uint)table <= 1u) { recipe.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 ((object)prefab != null) { recipe.m_craftingStation = prefab.GetComponent(); } else { Debug.LogWarning($"Custom crafting station '{((itemConfig == null || list.Count > 0) ? station.custom : itemConfig.customTable.Value)}' does not exist ({Prefab})"); } } else { recipe.m_craftingStation = ZNetScene.instance.GetPrefab(getInternalName((itemConfig == null || list.Count > 0) ? station.Table : itemConfig.table.Value)).GetComponent(); } recipe.m_minStationLevel = ((itemConfig == null || list.Count > 0) ? station.level : itemConfig.tableLevel.Value); recipe.m_requireOnlyOneIngredient = ((itemConfig == null) ? recipe2.Value.RequireOnlyOneIngredient : (itemConfig.requireOneIngredient.Value == Toggle.On)); recipe.m_qualityResultAmountMultiplier = itemConfig?.qualityResultAmountMultiplier.Value ?? recipe2.Value.QualityResultAmountMultiplier; list.Add(recipe); RequiredResourceList requiredItems = recipe2.Value.RequiredItems; if (requiredItems != null && !requiredItems.Free) { List requirements = requiredItems.Requirements; if (requirements != null && requirements.Count == 0) { hiddenCraftRecipes.Add(recipe, recipe2.Value.RecipeIsActive); } } requiredItems = recipe2.Value.RequiredUpgradeItems; if (requiredItems != null && !requiredItems.Free) { List requirements = requiredItems.Requirements; if (requirements != null && requirements.Count == 0) { hiddenUpgradeRecipes.Add(recipe, recipe2.Value.RecipeIsActive); } } } activeRecipes[this].Add(recipe2.Key, list); objectDB.m_recipes.AddRange(list); } conversions = new List(); for (int i = 0; i < Conversions.Count; i++) { Conversion conversion = Conversions[i]; conversions.Add(new Smelter.ItemConversion { m_from = SerializedRequirements.fetchByName(ObjectDB.instance, conversion.config?.input.Value ?? conversion.Input), m_to = Prefab.GetComponent() }); ConversionPiece conversionPiece = conversion.config?.piece.Value ?? conversion.Piece; string text = null; if (conversionPiece != ConversionPiece.Disabled && (object)conversions[i].m_from != null) { text = ((conversionPiece != ConversionPiece.Custom) ? getInternalName(conversionPiece) : (conversion.config?.customPiece.Value ?? conversion.customPiece)); Smelter smelter = ZNetScene.instance.GetPrefab(text)?.GetComponent(); if ((object)smelter != null) { smelter.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 (__instance.GetItemPrefab("Wood") == null) { return; } hiddenCraftRecipes.Clear(); hiddenUpgradeRecipes.Clear(); foreach (Item registeredItem in registeredItems) { registeredItem.registerRecipesInObjectDB(__instance); } } internal static void Patch_TraderGetAvailableItems(global::Trader __instance, ref List __result) { string prefabName = Utils.GetPrefabName(__instance.gameObject); Trader trader = ((prefabName == "Haldor") ? Trader.Haldor : ((prefabName == "Hildir") ? Trader.Hildir : Trader.None)); Trader trader2 = trader; __result.AddRange(from tuple in PrefabManager.CustomTradeItems.Values where (tuple.Item1 & trader2) != 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(ItemDrop.ItemData item, bool __result) { if (__result) { Player.m_localPlayer.UnequipItem(item); } } internal static void Patch_MaximumRequiredStationLevel(Recipe __instance, ref int __result, int quality) { if (!itemDropMap.TryGetValue(__instance.m_item, out Item value)) { return; } IEnumerable source; if (!itemCraftConfigs.TryGetValue(value, out Dictionary value2)) { source = Array.Empty(); } else { CraftingStation currentCraftingStation = Player.m_localPlayer.GetCurrentCraftingStation(); if ((object)currentCraftingStation != null) { string stationName = Utils.GetPrefabName(currentCraftingStation.gameObject); source = from c in value2.Where(delegate(KeyValuePair 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(ref Dictionary>? __state) { if (__state == null) { __state = new Dictionary>(); } Dictionary dictionary; if (InventoryGui.instance.InCraftTab()) { dictionary = hiddenCraftRecipes; } else { if (!InventoryGui.instance.InUpradeTab()) { return; } dictionary = hiddenUpgradeRecipes; } foreach (Recipe key in dictionary.Keys) { key.m_enabled = false; } __state[Assembly.GetExecutingAssembly()] = dictionary; } internal static void Patch_GetAvailableRecipesFinalizer(Dictionary> __state) { if (!__state.TryGetValue(Assembly.GetExecutingAssembly(), out Dictionary value)) { return; } foreach (KeyValuePair item in value) { item.Key.m_enabled = (int)(item.Value?.BoxedValue ?? ((object)1)) != 0; } } internal static IEnumerable Transpile_SetupRequirementList(IEnumerable instructionsEnumerable, ILGenerator ilg) { List list = instructionsEnumerable.ToList(); MethodInfo method = AccessTools.DeclaredMethod(typeof(InventoryGui), "SetupRequirement"); CodeInstruction codeInstruction = null; CodeInstruction codeInstruction2 = null; LocalBuilder operand = ilg.DeclareLocal(typeof(int)); Dictionary dictionary = new Dictionary(); bool flag = false; int num = 0; int value = 0; for (int i = 0; i < list.Count; i++) { if (list[i].Calls(method)) { codeInstruction = list[i + 2]; codeInstruction2 = list[i + 5]; flag = true; } if (flag) { if (list[i].Branches(out var 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, new <>z__ReadOnlyArray(new CodeInstruction[11] { new CodeInstruction(OpCodes.Ldloc, operand), new CodeInstruction(OpCodes.Brfalse, label2), codeInstruction.Clone(), new CodeInstruction(OpCodes.Ldarg_0), new CodeInstruction(OpCodes.Ldfld, AccessTools.DeclaredField(typeof(InventoryGui), "m_recipeRequirementList")), new CodeInstruction(OpCodes.Ldlen), new CodeInstruction(OpCodes.Bgt, label2), new CodeInstruction(OpCodes.Ldc_I4_0), codeInstruction2.Clone(), new CodeInstruction(OpCodes.Ldc_I4_0), new CodeInstruction(OpCodes.Br, label3) })); list.InsertRange(value - 2, new <>z__ReadOnlyArray(new CodeInstruction[2] { new CodeInstruction(OpCodes.Dup) { labels = new List