using System; using System.Collections; using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.IO.Compression; using System.Linq; using System.Linq.Expressions; using System.Net; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Serialization; using System.Runtime.Versioning; using System.Security; using System.Security.Cryptography; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using JetBrains.Annotations; using Jotunn; using Jotunn.Configs; using Jotunn.Entities; using Jotunn.Managers; using Jotunn.Utils; using MessageRouter; using Microsoft.CodeAnalysis; using ServerSync; using SimpleJson; using Splatform; using TMPro; using UnityEngine; using UnityEngine.Networking; using UnityEngine.SceneManagement; using UnityEngine.UI; using ValheimRoleplay; using ValheimRoleplay.Data; using ValheimRoleplay.Helpers; using ValheimRoleplay.Patches; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Core.Tokens; using YamlDotNet.Helpers; using YamlDotNet.Serialization; using YamlDotNet.Serialization.BufferedDeserialization; using YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators; using YamlDotNet.Serialization.Converters; using YamlDotNet.Serialization.EventEmitters; using YamlDotNet.Serialization.NamingConventions; using YamlDotNet.Serialization.NodeDeserializers; using YamlDotNet.Serialization.NodeTypeResolvers; using YamlDotNet.Serialization.ObjectFactories; using YamlDotNet.Serialization.ObjectGraphTraversalStrategies; using YamlDotNet.Serialization.ObjectGraphVisitors; using YamlDotNet.Serialization.Schemas; using YamlDotNet.Serialization.TypeInspectors; using YamlDotNet.Serialization.TypeResolvers; using YamlDotNet.Serialization.Utilities; using YamlDotNet.Serialization.ValueDeserializers; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: AssemblyTitle("ValheimRoleplay")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("ValheimRoleplay")] [assembly: AssemblyCopyright("Copyright © 2025")] [assembly: AssemblyTrademark("")] [assembly: ComVisible(false)] [assembly: Guid("4358610B-F3F4-4843-B7AF-98B7BC60DCDE")] [assembly: AssemblyFileVersion("2.1.2")] [assembly: AssemblyCompany("Arielle")] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("2.1.2.0")] [module: UnverifiableCode] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [<0f55d190-8dd3-4ef8-9f52-bbe85c5ed529>Embedded] internal sealed class <0f55d190-8dd3-4ef8-9f52-bbe85c5ed529>EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [<0f55d190-8dd3-4ef8-9f52-bbe85c5ed529>Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] [CompilerGenerated] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [<0f55d190-8dd3-4ef8-9f52-bbe85c5ed529>Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class <4713ac70-5c40-4c8e-abac-415a3e416205>NullableContextAttribute : Attribute { public readonly byte Flag; public <4713ac70-5c40-4c8e-abac-415a3e416205>NullableContextAttribute(byte P_0) { Flag = P_0; } } } [Nullable(0)] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public class EventBench { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] [HarmonyPatch(typeof(CraftingStation), "Start")] private class RegisterEventBench { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(CraftingStation __instance) { ZNetView component = ((Component)__instance).GetComponent(); if (((component != null) ? component.GetPrefabName() : null) == PIECE_NAME && !EventStations.Contains(__instance)) { EventStations.Add(__instance); } } } [HarmonyPatch(typeof(CraftingStation), "OnDestroy")] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] private class CraftingStation_Destroy { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Prefix(CraftingStation __instance) { EventStations.Remove(__instance); } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] [HarmonyPatch(typeof(Player), "Update")] public static class Player_Update_EventZone { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(Player __instance) { if ((Object)(object)__instance == (Object)null || !((Character)__instance).IsOwner()) { return; } checkTimer += Time.deltaTime; if (!(checkTimer < 0.25f)) { checkTimer = 0f; long playerID = __instance.GetPlayerID(); bool flag = IsInEventArea(__instance); if (!PlayerZoneState.TryGetValue(playerID, out var value)) { PlayerZoneState[playerID] = flag; } else if (flag != value) { PlayerZoneState[playerID] = flag; string text = (flag ? "You have entered an Event Zone" : "You have left the Event Zone"); ((Character)__instance).Message((MessageType)1, text, 0, (Sprite)null); } } } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] [HarmonyPatch(typeof(Humanoid))] public static class HammerPatches { [HarmonyPrefix] [HarmonyPatch("EquipItem")] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool EquipItem_Prefix(Humanoid __instance, ItemData item) { if (!PREVENT_EQUIP) { return true; } Player val = (Player)(object)((__instance is Player) ? __instance : null); if (val != null) { if (IsAdmin(val)) { return true; } if (IsItemAllowedInEventArea(item)) { return true; } if (!IsInEventArea(val)) { return true; } ((Character)__instance).Message((MessageType)2, PLAYER_MASSAGE_BLOCKED_EQUIP, 0, (Sprite)null); return false; } return true; } } [Nullable(0)] [HarmonyPatch(typeof(Player))] public static class PlayerPatches { [HarmonyPatch("TryPlacePiece")] [HarmonyPrefix] private static bool TryPlacePiece_Prefix(Player __instance, ref bool __result) { if (!PREVENT_BUILDING || IsAdmin(__instance) || !IsInEventArea(__instance)) { return true; } __result = false; ((Character)__instance).Message((MessageType)2, PLAYER_MASSAGE_BLOCKED_PLACE, 0, (Sprite)null); return false; } [HarmonyPrefix] [HarmonyPatch("RemovePiece")] private static bool RemovePiece_Prefix(Player __instance, ref bool __result) { if (!PREVENT_BUILDING || IsAdmin(__instance) || !IsInEventArea(__instance)) { return true; } __result = false; ((Character)__instance).Message((MessageType)2, PLAYER_MASSAGE_BLOCKED_REMOVE, 0, (Sprite)null); return false; } } private static readonly string PIECE_TO_CLONE = "piece_workbench"; private static readonly string PIECE_NAME = "piece_event_bench"; private static readonly string DISPLAY_NAME = "Event Bench"; private static readonly float RANGE = 200f; private static readonly bool PREVENT_BUILDING = true; private static readonly bool PREVENT_EQUIP = true; private static readonly List EventStations = new List(); private static readonly string PLAYER_MASSAGE_BLOCKED_PLACE = "$msg_nobuildzone"; private static readonly string PLAYER_MASSAGE_BLOCKED_REMOVE = "$msg_nobuildzone"; private static readonly string PLAYER_MASSAGE_BLOCKED_EQUIP = "You won't need this here"; private static readonly List FORBIDDEN_ITEMS = new List(); private static readonly List FORBIDDEN_STRINGS = new List(); private static readonly List FORBIDDEN_TYPES = new List { (ItemType)19 }; private static readonly Dictionary PlayerZoneState = new Dictionary(); private static float checkTimer = 0f; private static bool IsAdmin(Player player) { return ClientPatches.isAdmin(); } public static void OnVanillaPrefabsAvailable() { AddToPieceManager(); PrefabManager.OnVanillaPrefabsAvailable -= OnVanillaPrefabsAvailable; } private static void AddToPieceManager() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Expected O, but got Unknown //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Expected O, but got Unknown //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Expected O, but got Unknown //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_0161: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_017b: Unknown result type (might be due to invalid IL or missing references) PieceConfig val = new PieceConfig(); val.Name = DISPLAY_NAME; val.PieceTable = PieceTables.Hammer; val.Category = PieceCategories.Misc; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "SledgeCheat", Amount = 1, Recover = false } }; PieceConfig val2 = val; CustomPiece val3 = new CustomPiece(PIECE_NAME, PIECE_TO_CLONE, val2); PieceManager.Instance.AddPiece(val3); GameObject piecePrefab = val3.PiecePrefab; WearNTear component = piecePrefab.GetComponent(); if ((Object)(object)component != (Object)null) { Object.DestroyImmediate((Object)(object)component); } GameObject prefab = PrefabManager.Instance.GetPrefab("StatueCorgi"); if (!((Object)(object)prefab != (Object)null)) { return; } foreach (Transform item in piecePrefab.transform) { Transform val4 = item; string text = ((Object)val4).name.ToLower(); if (text.Contains("visual") || text.Contains("new")) { Object.DestroyImmediate((Object)(object)((Component)val4).gameObject); } } GameObject obj = Object.Instantiate(prefab); ((Object)obj).name = "visual"; obj.transform.SetParent(piecePrefab.transform, false); obj.transform.localPosition = Vector3.zero; obj.transform.localRotation = Quaternion.identity; obj.transform.localScale = Vector3.one * 0.6f; CraftingStation component2 = piecePrefab.GetComponent(); component2.m_craftRequireRoof = false; component2.m_useDistance = 0f; component2.m_name = "Event Zone"; Collider[] componentsInChildren = obj.GetComponentsInChildren(true); for (int i = 0; i < componentsInChildren.Length; i++) { Object.DestroyImmediate((Object)(object)componentsInChildren[i]); } EffectArea componentInChildren = piecePrefab.GetComponentInChildren(); if ((Object)(object)componentInChildren != (Object)null) { CapsuleCollider[] componentsInChildren2 = ((Component)componentInChildren).GetComponentsInChildren(); for (int i = 0; i < componentsInChildren2.Length; i++) { componentsInChildren2[i].radius = RANGE; } } } private static bool IsInEventArea(Player player) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) Vector3 position = ((Component)player).transform.position; foreach (CraftingStation eventStation in EventStations) { if ((Object)(object)eventStation != (Object)null && Vector3.Distance(((Component)eventStation).transform.position, position) < RANGE) { return true; } } return false; } private static bool IsItemAllowedInEventArea(ItemData item) { //IL_0031: Unknown result type (might be due to invalid IL or missing references) object obj; if (item == null) { obj = null; } else { GameObject dropPrefab = item.m_dropPrefab; obj = ((dropPrefab != null) ? ((Object)dropPrefab).name : null); } string text = (string)obj; if (text == null || item.m_shared == null) { return true; } if (FORBIDDEN_TYPES.Contains(item.m_shared.m_itemType)) { return false; } if (FORBIDDEN_ITEMS.Contains(text)) { return false; } foreach (string fORBIDDEN_STRING in FORBIDDEN_STRINGS) { if (text.IndexOf(fORBIDDEN_STRING, StringComparison.OrdinalIgnoreCase) >= 0) { return false; } } return true; } } [HarmonyPatch(typeof(Character), "UpdateGroundContact")] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [Nullable(0)] public class FallDamagePatch { [CompilerGenerated] private sealed class d__2 : IEnumerable, IEnumerable, IEnumerator, IDisposable, IEnumerator { private int <>1__state; private CodeInstruction <>2__current; private int <>l__initialThreadId; [Nullable(new byte[] { 0, 1 })] private IEnumerable instructions; [Nullable(new byte[] { 0, 1 })] public IEnumerable <>3__instructions; [Nullable(new byte[] { 0, 1 })] private IEnumerator <>7__wrap1; CodeInstruction IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } [DebuggerHidden] public d__2(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || (uint)(num - 1) <= 1u) { try { } finally { <>m__Finally1(); } } <>7__wrap1 = null; <>1__state = -2; } private bool MoveNext() { //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Expected O, but got Unknown try { switch (<>1__state) { default: return false; case 0: <>1__state = -1; <>7__wrap1 = instructions.GetEnumerator(); <>1__state = -3; break; case 1: <>1__state = -3; break; case 2: <>1__state = -3; break; } if (<>7__wrap1.MoveNext()) { CodeInstruction current = <>7__wrap1.Current; if (CodeInstructionExtensions.Calls(current, ClampMethod)) { <>2__current = new CodeInstruction(OpCodes.Call, (object)NewDamageMethod); <>1__state = 1; return true; } <>2__current = current; <>1__state = 2; return true; } <>m__Finally1(); <>7__wrap1 = null; return false; } catch { //try-fault ((IDisposable)this).Dispose(); throw; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (<>7__wrap1 != null) { <>7__wrap1.Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] [return: Nullable(0)] IEnumerator IEnumerable.GetEnumerator() { d__2 d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; d__ = this; } else { d__ = new d__2(0); } d__.instructions = <>3__instructions; return d__; } [DebuggerHidden] [return: Nullable(0)] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)this).GetEnumerator(); } } private static readonly MethodInfo ClampMethod = AccessTools.Method(typeof(Mathf), "Clamp01", (Type[])null, (Type[])null); private static readonly MethodInfo NewDamageMethod = AccessTools.Method(typeof(FallDamagePatch), "CalculateFallDamage", (Type[])null, (Type[])null); [IteratorStateMachine(typeof(d__2))] private static IEnumerable Transpiler(IEnumerable instructions) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__2(-2) { <>3__instructions = instructions }; } public static float CalculateFallDamage(float t) { float num = t * 16f + 4f; if (num <= 4f) { return 0f; } return Mathf.Pow(Mathf.Clamp01((num - 4f) / 52f), 1.5f) * 5f; } } namespace MessageRouter { [Nullable(0)] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static class RoutedRPCDataExtensions { public static void DeserializeFrom(this RoutedRPCData routedRpcData, ref ZPackage sourcePackage) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) routedRpcData.m_msgID = sourcePackage.ReadLong(); routedRpcData.m_senderPeerID = sourcePackage.ReadLong(); routedRpcData.m_targetPeerID = sourcePackage.ReadLong(); routedRpcData.m_targetZDO = sourcePackage.ReadZDOID(); routedRpcData.m_methodHash = sourcePackage.ReadInt(); sourcePackage.ReadPackageTo(ref routedRpcData.m_parameters); } public static void Clear(this RoutedRPCData routedRpcData) { //IL_001e: Unknown result type (might be due to invalid IL or missing references) routedRpcData.m_msgID = 0L; routedRpcData.m_senderPeerID = 0L; routedRpcData.m_targetPeerID = 0L; routedRpcData.m_targetZDO = default(ZDOID); routedRpcData.m_methodHash = 0; ZPackage parameters = routedRpcData.m_parameters; if (parameters != null) { parameters.Clear(); } } } public abstract class RpcMethodHandler { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public abstract bool Process(RoutedRPCData routedRpcData); } public static class ZPackageExtensions { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static void ReadPackageTo(this ZPackage sourcePackage, ref ZPackage targetPackage) { int num = sourcePackage.m_reader.ReadInt32(); targetPackage.m_writer.Flush(); targetPackage.m_stream.SetLength(num); targetPackage.m_stream.Position = 0L; sourcePackage.m_reader.Read(targetPackage.m_stream.GetBuffer(), 0, num); } } [HarmonyPatch(typeof(ZRoutedRpc))] internal static class ZRoutedRpcPatch { [HarmonyPrefix] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [HarmonyPatch("RPC_RoutedRPC")] private static bool RPC_RoutedRPCPrefix(ZRoutedRpc __instance, ZRpc rpc, ZPackage pkg) { if (__instance.m_server) { RoutedRpcManager.ProcessRoutedRPC(__instance, rpc, pkg); return false; } return true; } } [HarmonyPatch(typeof(ZNet))] internal static class ZNetPatch { [HarmonyPostfix] [HarmonyPatch("Start")] private static void StartPostfix() { RoutedRpcManager.SetupServerPeer(); } } [Nullable(0)] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static class RoutedRpcManager { public static readonly Dictionary HashCodeToMethodNameCache = new Dictionary(); private static readonly Dictionary> _rpcMethodHandlers = new Dictionary>(); private static readonly RoutedRPCData _routedRpcData = new RoutedRPCData(); private static long _serverPeerId = 0L; public static long ServerPeerId => _serverPeerId; public static void SetupServerPeer() { _serverPeerId = ZDOMan.s_instance.m_sessionID; } public static void RPC_ServerModerationLog(long sender, string json) { ZLog.Log((object)("[VRP] SERVER RECEIVED LOG: " + json)); if ((Object)(object)ZNet.instance != (Object)null) { ((MonoBehaviour)ZNet.instance).StartCoroutine(Api.LogInsert(json)); } } public static void ServerModerationLog(string player, string steamId, string item, string action, string creator, string raw, int isAdmin = 0) { DbLog logEntry = new DbLog { p = player, s = steamId, i = item, a = action, c = creator, r = raw, m = isAdmin }; if ((Object)(object)ZNet.instance != (Object)null) { ((MonoBehaviour)ZNet.instance).StartCoroutine(Api.LogInsert(logEntry)); } } public static void AddHandler(string methodName, RpcMethodHandler handler) { int stableHashCode = StringExtensionMethods.GetStableHashCode(methodName); HashCodeToMethodNameCache[stableHashCode] = methodName; ServerModerationLog("server", "", "", "rpcmanager", "handler", $"Adding handler for {methodName} ({stableHashCode}): {handler.GetType().FullName}"); if (!_rpcMethodHandlers.TryGetValue(stableHashCode, out var value)) { value = new List(); _rpcMethodHandlers[stableHashCode] = value; } value.Add(handler); } public static void ProcessRoutedRPC(ZRoutedRpc routedRpc, ZRpc rpc, ZPackage package) { _routedRpcData.DeserializeFrom(ref package); long targetPeerID = _routedRpcData.m_targetPeerID; long id = routedRpc.m_id; if (targetPeerID == id || targetPeerID == 0L) { routedRpc.HandleRoutedRPC(_routedRpcData); } if ((targetPeerID != id || targetPeerID == _serverPeerId) && ProcessHandlers(_routedRpcData)) { routedRpc.RouteRPC(_routedRpcData); } } public static bool ProcessHandlers(RoutedRPCData routedRpcData) { if (!_rpcMethodHandlers.TryGetValue(routedRpcData.m_methodHash, out var value)) { return true; } bool flag = true; foreach (RpcMethodHandler item in value) { flag &= item.Process(routedRpcData); } return flag; } public static string MethodHashToString(int methodHash) { if (HashCodeToMethodNameCache.TryGetValue(methodHash, out var value)) { return value; } return $"RPC_{methodHash}"; } } } namespace ValheimRoleplay { [Serializable] [Nullable(0)] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public class DbLog { public string p { get; set; } = ""; public string s { get; set; } = ""; public int m { get; set; } public string i { get; set; } = ""; public string a { get; set; } = ""; public string b { get; set; } = ""; public string c { get; set; } = ""; public string r { get; set; } = ""; public string ToJson() { return $"{{\"p\":\"{p}\",\"s\":\"{s}\",\"m\":{m},\"i\":\"{i}\",\"a\":\"{a}\",\"b\":\"{b}\",\"c\":\"{c}\",\"r\":\"{Escape(r)}\"}}"; } private string Escape(string str) { return str?.Replace("\"", "\\\"") ?? ""; } } [Serializable] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [Nullable(0)] public class DbPlayer { public string player { get; set; } } [Serializable] [Nullable(0)] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public class DbWhitelist { public bool isAuthenticating; public int pid { get; set; } public int cid { get; set; } public string steamid { get; set; } public string charactername { get; set; } public bool isnew { get; set; } public bool permadeath { get; set; } public string season { get; set; } public int admincharacter { get; set; } } [Serializable] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [Nullable(0)] public class DbWhitelistNew { public int pid { get; set; } public int cid { get; set; } public string steamid { get; set; } public string charName { get; set; } } [Serializable] [Nullable(0)] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public class DbSkills { public string charactername { get; set; } public string skill { get; set; } public int cap { get; set; } } [Serializable] [Nullable(0)] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public class DbPieces { public string itemName { get; set; } public string recipeName { get; set; } public string groups { get; set; } public int is_enabled { get; set; } public bool deleted { get; set; } } [Serializable] [Nullable(0)] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public class DbGroup { public string charactername { get; set; } public string craftgroup { get; set; } public bool deleted { get; set; } } [Serializable] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [Nullable(0)] public class DbRecipe { public string itemName { get; set; } public string recipeName { get; set; } public string groups { get; set; } public int is_enabled { get; set; } public bool deleted { get; set; } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [Nullable(0)] internal class Api { [CompilerGenerated] private sealed class d__1 : IEnumerator, IDisposable, IEnumerator { private int <>1__state; [Nullable(0)] private object <>2__current; [Nullable(0)] public string json; [Nullable(0)] private UnityWebRequest 5__2; object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } [DebuggerHidden] public d__1(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } 5__2 = null; <>1__state = -2; } private bool MoveNext() { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Expected O, but got Unknown //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Expected O, but got Unknown //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Invalid comparison between Unknown and I4 bool result; try { switch (<>1__state) { default: result = false; break; case 0: { <>1__state = -1; string text = "http://127.0.0.1:3333/logs/add"; 5__2 = new UnityWebRequest(text, "POST"); <>1__state = -3; byte[] bytes = Encoding.UTF8.GetBytes(json); 5__2.uploadHandler = (UploadHandler)new UploadHandlerRaw(bytes); 5__2.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); 5__2.SetRequestHeader("Content-Type", "application/json"); <>2__current = 5__2.SendWebRequest(); <>1__state = 1; result = true; break; } case 1: <>1__state = -3; if ((int)5__2.result != 1) { ZLog.LogWarning((object)("[LogInsert Error]: " + 5__2.error + " | Response: " + 5__2.downloadHandler.text)); } result = false; <>m__Finally1(); break; } } catch { //try-fault ((IDisposable)this).Dispose(); throw; } return result; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (5__2 != null) { ((IDisposable)5__2).Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [CompilerGenerated] private sealed class d__5 : IEnumerator, IDisposable, IEnumerator { private int <>1__state; [Nullable(0)] private object <>2__current; [Nullable(0)] private UnityWebRequest 5__2; object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } [DebuggerHidden] public d__5(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { 5__2 = null; <>1__state = -2; } private bool MoveNext() { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Invalid comparison between Unknown and I4 switch (<>1__state) { default: return false; case 0: <>1__state = -1; 5__2 = UnityWebRequest.Get("http://127.0.0.1:3333/groups/"); <>2__current = 5__2.SendWebRequest(); <>1__state = 1; return true; case 1: <>1__state = -1; if ((int)5__2.result == 1) { DbGroup[] array = SimpleJson.DeserializeObject(Encoding.UTF8.GetString(5__2.downloadHandler.data)); if (array != null) { ServerPatches.groups.Clear(); DbGroup[] array2 = array; foreach (DbGroup item in array2) { ServerPatches.groups.Add(item); } ZLog.Log((object)$"[VRP] Server now has {ServerPatches.groups.Count} groups in memory."); } else { ZLog.LogError((object)"error groups json"); } } else { ZLog.LogError((object)"error in groups request"); } return false; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [CompilerGenerated] private sealed class d__7 : IEnumerator, IDisposable, IEnumerator { private int <>1__state; [Nullable(0)] private object <>2__current; [Nullable(0)] private UnityWebRequest 5__2; object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } [DebuggerHidden] public d__7(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { 5__2 = null; <>1__state = -2; } private bool MoveNext() { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Invalid comparison between Unknown and I4 switch (<>1__state) { default: return false; case 0: <>1__state = -1; 5__2 = UnityWebRequest.Get("http://127.0.0.1:3333/pieces"); <>2__current = 5__2.SendWebRequest(); <>1__state = 1; return true; case 1: <>1__state = -1; if ((int)5__2.result == 1) { ServerPatches.piecesraw = Encoding.UTF8.GetString(5__2.downloadHandler.data); } else { ZLog.LogError((object)"error in pieces request"); } return false; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [CompilerGenerated] private sealed class d__6 : IEnumerator, IDisposable, IEnumerator { private int <>1__state; [Nullable(0)] private object <>2__current; [Nullable(0)] private UnityWebRequest 5__2; object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } [DebuggerHidden] public d__6(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { 5__2 = null; <>1__state = -2; } private bool MoveNext() { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Invalid comparison between Unknown and I4 switch (<>1__state) { default: return false; case 0: <>1__state = -1; 5__2 = UnityWebRequest.Get("http://127.0.0.1:3333/recipes"); <>2__current = 5__2.SendWebRequest(); <>1__state = 1; return true; case 1: <>1__state = -1; if ((int)5__2.result == 1) { ServerPatches.recipesraw = Encoding.UTF8.GetString(5__2.downloadHandler.data); } else { ZLog.LogError((object)"error in recipes request"); } return false; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [CompilerGenerated] private sealed class d__8 : IEnumerator, IDisposable, IEnumerator { private int <>1__state; [Nullable(0)] private object <>2__current; [Nullable(0)] private UnityWebRequest 5__2; object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } [DebuggerHidden] public d__8(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { 5__2 = null; <>1__state = -2; } private bool MoveNext() { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Invalid comparison between Unknown and I4 switch (<>1__state) { default: return false; case 0: <>1__state = -1; 5__2 = UnityWebRequest.Get("http://127.0.0.1:3333/skills"); <>2__current = 5__2.SendWebRequest(); <>1__state = 1; return true; case 1: <>1__state = -1; if ((int)5__2.result == 1) { DbSkills[] array = SimpleJson.DeserializeObject(ServerPatches.skillsraw = Encoding.UTF8.GetString(5__2.downloadHandler.data)); if (array != null) { ServerPatches.skills.Clear(); DbSkills[] array2 = array; foreach (DbSkills item in array2) { ServerPatches.skills.Add(item); } ZLog.Log((object)$"[VRP] Server now has {ServerPatches.skills.Count} skill groups in memory."); } else { ZLog.LogError((object)"error skills json"); } } else { ZLog.LogError((object)"error in skills request"); } return false; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [CompilerGenerated] private sealed class d__4 : IEnumerator, IDisposable, IEnumerator { private int <>1__state; [Nullable(0)] private object <>2__current; [Nullable(0)] private UnityWebRequest 5__2; object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } [DebuggerHidden] public d__4(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { 5__2 = null; <>1__state = -2; } private bool MoveNext() { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Invalid comparison between Unknown and I4 switch (<>1__state) { default: return false; case 0: <>1__state = -1; 5__2 = UnityWebRequest.Get("http://127.0.0.1:3333/whitelist/"); <>2__current = 5__2.SendWebRequest(); <>1__state = 1; return true; case 1: <>1__state = -1; if ((int)5__2.result == 1) { DbWhitelist[] array = SimpleJson.DeserializeObject(Encoding.UTF8.GetString(5__2.downloadHandler.data)); if (array != null) { ServerPatches.whitelist.Clear(); DbWhitelist[] array2 = array; foreach (DbWhitelist item in array2) { ServerPatches.whitelist.Add(item); } } else { ZLog.LogError((object)"error whitelist json"); } } else { ZLog.LogError((object)"error in whitelist request"); } return false; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [CompilerGenerated] private sealed class d__2 : IEnumerator, IDisposable, IEnumerator { private int <>1__state; [Nullable(0)] private object <>2__current; [Nullable(0)] public string steamid; [Nullable(0)] public string charName; public int cid; public int pid; [Nullable(0)] public DbWhitelist originalObj; [Nullable(0)] private UnityWebRequest 5__2; object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } [DebuggerHidden] public d__2(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } 5__2 = null; <>1__state = -2; } private bool MoveNext() { //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Expected O, but got Unknown //IL_008a: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Expected O, but got Unknown //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Expected O, but got Unknown bool result; try { switch (<>1__state) { default: result = false; break; case 0: { <>1__state = -1; string s = SimpleJson.SerializeObject((object)new DbWhitelistNew { steamid = steamid, charName = charName, cid = cid, pid = pid }); 5__2 = new UnityWebRequest("http://127.0.0.1:3333/whitelist/new", "POST"); <>1__state = -3; byte[] bytes = Encoding.UTF8.GetBytes(s); 5__2.uploadHandler = (UploadHandler)new UploadHandlerRaw(bytes); 5__2.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); 5__2.SetRequestHeader("Content-Type", "application/json"); <>2__current = 5__2.SendWebRequest(); <>1__state = 1; result = true; break; } case 1: <>1__state = -3; ZLog.Log((object)("api whitelist sent " + charName + " " + steamid)); originalObj.isAuthenticating = false; result = false; <>m__Finally1(); break; } } catch { //try-fault ((IDisposable)this).Dispose(); throw; } return result; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (5__2 != null) { ((IDisposable)5__2).Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [CompilerGenerated] private sealed class d__3 : IEnumerator, IDisposable, IEnumerator { private int <>1__state; [Nullable(0)] private object <>2__current; [Nullable(0)] public DbWhitelist deadplayer; [Nullable(0)] private UnityWebRequest 5__2; object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } [DebuggerHidden] public d__3(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } 5__2 = null; <>1__state = -2; } private bool MoveNext() { //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Expected O, but got Unknown //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Expected O, but got Unknown //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Expected O, but got Unknown bool result; try { switch (<>1__state) { default: result = false; break; case 0: { <>1__state = -1; deadplayer.permadeath = true; string s = SimpleJson.SerializeObject((object)deadplayer); 5__2 = new UnityWebRequest("http://127.0.0.1:3333/whitelist/dead", "POST"); <>1__state = -3; byte[] bytes = Encoding.UTF8.GetBytes(s); 5__2.uploadHandler = (UploadHandler)new UploadHandlerRaw(bytes); 5__2.downloadHandler = (DownloadHandler)new DownloadHandlerBuffer(); 5__2.SetRequestHeader("Content-Type", "application/json"); <>2__current = 5__2.SendWebRequest(); <>1__state = 1; result = true; break; } case 1: <>1__state = -3; ZLog.Log((object)("api permadeath sent " + deadplayer.charactername + " " + deadplayer.steamid)); result = false; <>m__Finally1(); break; } } catch { //try-fault ((IDisposable)this).Dispose(); throw; } return result; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } private void <>m__Finally1() { <>1__state = -1; if (5__2 != null) { ((IDisposable)5__2).Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } public static IEnumerator LogInsert(DbLog logEntry) { return LogInsert(SimpleJson.SerializeObject((object)logEntry)); } [IteratorStateMachine(typeof(d__1))] public static IEnumerator LogInsert(string json) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__1(0) { json = json }; } [IteratorStateMachine(typeof(d__2))] public static IEnumerator WhitelistAuth(string steamid, string charName, int pid, int cid, DbWhitelist originalObj) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__2(0) { steamid = steamid, charName = charName, pid = pid, cid = cid, originalObj = originalObj }; } [IteratorStateMachine(typeof(d__3))] public static IEnumerator WhitelistPermadeath(DbWhitelist deadplayer) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__3(0) { deadplayer = deadplayer }; } [IteratorStateMachine(typeof(d__4))] public static IEnumerator ServerGetWhitelist() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__4(0); } [IteratorStateMachine(typeof(d__5))] public static IEnumerator ServerGetGroups() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__5(0); } [IteratorStateMachine(typeof(d__6))] public static IEnumerator ServerGetRecipes() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__6(0); } [IteratorStateMachine(typeof(d__7))] public static IEnumerator ServerGetPieces() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__7(0); } [IteratorStateMachine(typeof(d__8))] public static IEnumerator ServerGetSkillcaps() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__8(0); } } [Nullable(0)] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public class StatusOverlayManager : MonoBehaviour { private static StatusOverlayManager _instance; private GameObject _masterOverlay; private Image _overlayImage; private float _targetAlpha; private const float FadeSpeed = 1.5f; public static StatusOverlayManager Instance { get { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected O, but got Unknown if ((Object)(object)_instance == (Object)null) { GameObject val = new GameObject("StatusOverlayManager_AutoCreated"); _instance = val.AddComponent(); Object.DontDestroyOnLoad((Object)val); } return _instance; } } private void Awake() { //IL_0053: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_instance == (Object)null) { _instance = this; Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject); } else if ((Object)(object)_instance != (Object)(object)this) { Object.Destroy((Object)(object)((Component)this).gameObject); return; } _masterOverlay = VignetteHelper.CreateOverlay("MasterStatusOverlay", new Color(1f, 1f, 1f, 0f)); if ((Object)(object)_masterOverlay != (Object)null) { _overlayImage = _masterOverlay.GetComponentInChildren(); } } private void Update() { //IL_0023: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_masterOverlay == (Object)null || (Object)(object)_overlayImage == (Object)null) { return; } float a = ((Graphic)_overlayImage).color.a; if (!Mathf.Approximately(a, _targetAlpha)) { float num = Mathf.MoveTowards(a, _targetAlpha, Time.deltaTime * 1.5f); VignetteHelper.SetIntensity(_masterOverlay, num); if (num <= 0f && _targetAlpha == 0f) { _masterOverlay.SetActive(false); } } } public void UpdateOverlay(Color color, float intensity, bool enabled, float strength = 1f) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)_masterOverlay == (Object)null) { return; } if (enabled) { _targetAlpha = intensity * strength; _masterOverlay.SetActive(true); if ((Object)(object)_overlayImage != (Object)null) { Color color2 = color; color2.a = ((Graphic)_overlayImage).color.a; ((Graphic)_overlayImage).color = color2; } } else { _targetAlpha = 0f; } } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [Nullable(0)] internal static class BundleCache { [Nullable(0)] public sealed class Scope : IDisposable { private readonly string _path; public AssetBundle Bundle { get; } public Scope(string keyOrPath) { _path = Resolve(keyOrPath); Bundle = Acquire(_path); } public void Dispose() { Release(_path); } } [Nullable(new byte[] { 1, 1, 0, 1 })] private static readonly Dictionary _cache = new Dictionary(); private static readonly Dictionary _aliases = new Dictionary(StringComparer.OrdinalIgnoreCase) { { "bandage", "Arielle-ValheimRoleplay/Assets/bandage" }, { "ploam", "Arielle-ValheimRoleplay/Assets/ploam" }, { "mushbundle", "Arielle-ValheimRoleplay/Assets/gold" }, { "bonefirebundle", "Arielle-ValheimRoleplay/Assets/bonefire" }, { "vrpbundle", "Arielle-ValheimRoleplay/Assets/stoneage" }, { "valonbundle", "Arielle-ValheimRoleplay/Assets/valon" }, { "phatbundle", "Arielle-ValheimRoleplay/Assets/phats" }, { "loraxbundle", "Arielle-ValheimRoleplay/Assets/loraxia" }, { "bronzehelm", "Arielle-ValheimRoleplay/Assets/bronzehelmsrgb" } }; private static string Resolve(string keyOrPath) { if (string.IsNullOrWhiteSpace(keyOrPath)) { throw new ArgumentException("Bundle key/path is null or empty.", "keyOrPath"); } if (keyOrPath.Contains("/") || keyOrPath.Contains("\\")) { return keyOrPath; } if (_aliases.TryGetValue(keyOrPath, out var value)) { return value; } return keyOrPath; } public static AssetBundle GetBundle(string keyOrPath) { return Acquire(keyOrPath); } public static AssetBundle Acquire(string keyOrPath) { string text = Resolve(keyOrPath); if (_cache.TryGetValue(text, out (AssetBundle, int) value)) { _cache[text] = (value.Item1, value.Item2 + 1); return value.Item1; } AssetBundle val = AssetUtils.LoadAssetBundle(text); if ((Object)(object)val != (Object)null) { GameObject[] array = val.LoadAllAssets(); foreach (GameObject val2 in array) { Component[] componentsInChildren = val2.GetComponentsInChildren(true); for (int j = 0; j < componentsInChildren.Length; j++) { if ((Object)(object)componentsInChildren[j] == (Object)null) { ZLog.LogError((object)("[VRP ERROR] Bundle '" + keyOrPath + "' contains a MISSING SCRIPT on Prefab: '" + ((Object)val2).name + "'")); ZLog.LogError((object)("[VRP FIX] Open Unity, find '" + ((Object)val2).name + "', remove the 'Missing (Script)' component, and re-export.")); } } } } _cache[text] = (val, 1); return val; } public static void Release(string keyOrPath) { string key = Resolve(keyOrPath); if (_cache.TryGetValue(key, out (AssetBundle, int) value)) { int num = value.Item2 - 1; if (num <= 0) { value.Item1.Unload(false); _cache.Remove(key); } else { _cache[key] = (value.Item1, num); } } } } internal static class Env { public static bool IsDedicated { get { //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Invalid comparison between Unknown and I4 if (!((Object)(object)ZNet.instance != (Object)null) || !ZNet.instance.IsDedicated()) { return (int)SystemInfo.graphicsDeviceType == 4; } return true; } } } [Nullable(0)] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static class ServingTrayHelper { private static void CreatePrefabForServingTray(GameObject prefab, string name, string description, string category = "VRP", string displayName = null) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Expected O, but got Unknown //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown PieceConfig val = new PieceConfig(); val.Name = displayName ?? name; val.Description = description; val.PieceTable = PieceTables.ServingTray; val.Category = category; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = name, Amount = 1 } }; PieceConfig val2 = val; PieceManager.Instance.AddPiece(new CustomPiece(prefab, false, val2)); } public static void AddToServingTray(CustomItem item, string category = "VRP") { CreatePrefabForServingTray(item.ItemPrefab, ((Object)item.ItemDrop).name, item.ItemDrop.m_itemData.m_shared.m_description, category, item.ItemDrop.GetHoverName()); } public static void AddToServingTray(string foodPrefabName, string category = "VRP") { GameObject prefab = PrefabManager.Instance.GetPrefab(foodPrefabName); ItemDrop val = (Object.op_Implicit((Object)(object)prefab) ? prefab.GetComponent() : null); if (!Object.op_Implicit((Object)(object)val)) { ZLog.LogWarning((object)("Food prefab '" + foodPrefabName + "' not found or missing ItemDrop.")); return; } string text = "ST_" + ((Object)prefab).name; if (PieceManager.Instance.GetPiece(text) != null) { ZLog.Log((object)("Piece '" + text + "' already added; skipping.")); return; } string hoverName = val.GetHoverName(); string description = val.m_itemData?.m_shared?.m_description ?? ""; val.m_itemData?.m_shared?.m_icons?.FirstOrDefault(); CreatePrefabForServingTray(prefab, foodPrefabName, description, category, hoverName); } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [Nullable(0)] [BepInPlugin("Arielle.ValheimRoleplay", "ValheimRoleplay", "2.1.2")] [BepInDependency(/*Could not decode attribute arguments.*/)] public class VRPMod : BaseUnityPlugin { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] public enum Toggle { On = 1, Off = 0 } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] private class ConfigurationManagerAttributes { [UsedImplicitly] public int? Order; [UsedImplicitly] public bool? Browsable; [UsedImplicitly] [Nullable(2)] public string Category; [UsedImplicitly] [Nullable(new byte[] { 2, 1 })] public Action CustomDrawer; } internal const string ModName = "ValheimRoleplay"; internal const string ModVersion = "2.1.2"; internal const string Author = "Arielle"; private const string ModGUID = "Arielle.ValheimRoleplay"; private static string ConfigFileName = "Arielle.ValheimRoleplay.cfg"; private static string ConfigFileFullPath; public static VRPMod Instance; public static ConfigEntry _vrpLore; public static ConfigEntry _drunkChance; public static ConfigEntry gatedBiomes; public static ConfigEntry preventBuilding; public static ConfigEntry preventExploring; public static ConfigEntry preventInteraction; public static ConfigEntry _lockTimeEnabled; public static ConfigEntry _lockedTimeValue; public static ConfigEntry _eternalWinterEnabled; public static ConfigEntry _coinCostLevel2; public static ConfigEntry _coinCostLevel3; public static ConfigEntry _coinCostLevel4; internal static string ConnectionError; private readonly Harmony _harmony = new Harmony("Arielle.ValheimRoleplay"); public static readonly ManualLogSource ValheimRoleplayLogger; private static readonly ConfigSync ConfigSync; private static ConfigEntry _serverConfigLocked; internal static ConfigEntry _debugMode; public static bool DebugMode() { return _debugMode.Value == Toggle.On; } public void Awake() { //IL_0257: Unknown result type (might be due to invalid IL or missing references) //IL_0261: Expected O, but got Unknown Instance = this; _serverConfigLocked = config("1 - General", "Lock Configuration", Toggle.On, "If on, the configuration is locked and can be changed by server admins only."); ConfigSync.AddLockingConfigEntry(_serverConfigLocked); _vrpLore = config("2 - VRP", "Season Lore", "Hello World", "Intro text for new players."); ConfigSync.AddConfigEntry(_vrpLore); _debugMode = config("2 - VRP", "Debug Mode", Toggle.Off, "If on, will write extra logs. May cause performance issues."); ConfigSync.AddConfigEntry(_debugMode); _drunkChance = config("3 - Custom", "Drunk Chance", 0.25f, "Chance [0..1] to gain Drunk when consuming an alcoholic drink."); ConfigSync.AddConfigEntry(_drunkChance); gatedBiomes = config("4 - Progression", "Gated Biomes", (Biome)0, "Biome list."); ConfigSync.AddConfigEntry(gatedBiomes); preventBuilding = config("4 - Progression", "No Build", value: true, "Prevent usage of hammers, hoe, cultivator."); ConfigSync.AddConfigEntry(gatedBiomes); preventExploring = config("4 - Progression", "No Explore", value: true, "Prevent minimap from exploring."); ConfigSync.AddConfigEntry(gatedBiomes); preventInteraction = config("4 - Progression", "No Interaction", value: true, "Prevent interaction with any interactable object."); ConfigSync.AddConfigEntry(gatedBiomes); _eternalWinterEnabled = config("5 - Winter", "Enabled", value: true, "Begin the eternal winter."); ConfigSync.AddConfigEntry(_eternalWinterEnabled); _lockTimeEnabled = config("6 - Freeze Time", "Enabled", value: true, "Enable the time lock."); ConfigSync.AddConfigEntry(_eternalWinterEnabled); _lockedTimeValue = config("6 - Time of Day", "Time of Day", 0.6f, "Freeze time."); ConfigSync.AddConfigEntry(_lockedTimeValue); _coinCostLevel2 = config("7 - Coin Costs", "Level 2 Cost", 10, "Coin cost for Quality level 2 gear."); _coinCostLevel3 = config("7 - Coin Costs", "Level 3 Cost", 50, "Coin cost for Quality level 3 gear."); _coinCostLevel4 = config("7 - Coin Costs", "Level 4 Cost", 500, "Coin cost for Quality level 4 gear."); Application.logMessageReceived += new LogCallback(SuppressMissingScriptLogs); _harmony.PatchAll(); JotunnPatches.AddVariants(); SetupWatcher(); } private void SuppressMissingScriptLogs(string condition, string stackTrace, LogType type) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 if ((int)type == 2) { condition.Contains("The referenced script on this Behaviour"); } } private void OnDestroy() { ((BaseUnityPlugin)this).Config.Save(); Harmony harmony = _harmony; if (harmony != null) { harmony.UnpatchSelf(); } } private void SetupWatcher() { FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Paths.ConfigPath, ConfigFileName); fileSystemWatcher.Changed += ReadConfigValues; fileSystemWatcher.Created += ReadConfigValues; fileSystemWatcher.Renamed += ReadConfigValues; fileSystemWatcher.IncludeSubdirectories = true; fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher.EnableRaisingEvents = true; } private void ReadConfigValues(object sender, FileSystemEventArgs e) { if (!File.Exists(ConfigFileFullPath)) { return; } try { ValheimRoleplayLogger.LogDebug((object)"ReadConfigValues called"); ((BaseUnityPlugin)this).Config.Reload(); } catch { ValheimRoleplayLogger.LogError((object)("There was an issue loading your " + ConfigFileName)); ValheimRoleplayLogger.LogError((object)"Please check your config entries for spelling and format!"); } } private ConfigEntry config<[Nullable(2)] T>(string group, string name, T value, ConfigDescription description, bool synchronizedSetting = true) { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Expected O, but got Unknown ConfigDescription val = new ConfigDescription(description.Description + (synchronizedSetting ? " [Synced with Server]" : " [Not Synced with Server]"), description.AcceptableValues, description.Tags); ConfigEntry val2 = ((BaseUnityPlugin)this).Config.Bind(group, name, value, val); ConfigSync.AddConfigEntry(val2).SynchronizedConfig = synchronizedSetting; return val2; } private ConfigEntry config<[Nullable(2)] T>(string group, string name, T value, string description, bool synchronizedSetting = true) { //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown return config(group, name, value, new ConfigDescription(description, (AcceptableValueBase)null, Array.Empty()), synchronizedSetting); } static VRPMod() { string configPath = Paths.ConfigPath; char directorySeparatorChar = Path.DirectorySeparatorChar; ConfigFileFullPath = configPath + directorySeparatorChar + ConfigFileName; ConnectionError = ""; ValheimRoleplayLogger = Logger.CreateLogSource("ValheimRoleplay"); ConfigSync = new ConfigSync("Arielle.ValheimRoleplay") { DisplayName = "ValheimRoleplay", CurrentVersion = "2.1.2", MinimumRequiredVersion = "2.1.2" }; _serverConfigLocked = null; _debugMode = null; } } public static class KeyboardExtensions { public static bool IsKeyDown(this KeyboardShortcut shortcut) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) if ((int)((KeyboardShortcut)(ref shortcut)).MainKey != 0 && Input.GetKeyDown(((KeyboardShortcut)(ref shortcut)).MainKey)) { return ((KeyboardShortcut)(ref shortcut)).Modifiers.All((Func)Input.GetKey); } return false; } public static bool IsKeyHeld(this KeyboardShortcut shortcut) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) if ((int)((KeyboardShortcut)(ref shortcut)).MainKey != 0 && Input.GetKey(((KeyboardShortcut)(ref shortcut)).MainKey)) { return ((KeyboardShortcut)(ref shortcut)).Modifiers.All((Func)Input.GetKey); } return false; } } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] public static class RegisterAndCheckVersion { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Prefix(ZNetPeer peer, ref ZNet __instance) { //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Expected O, but got Unknown VRPMod.ValheimRoleplayLogger.LogDebug((object)"Registering version RPC handler"); peer.m_rpc.Register("ValheimRoleplay_VersionCheck", (Action)RpcHandlers.RPC_ValheimRoleplay_Version); VRPMod.ValheimRoleplayLogger.LogInfo((object)"Invoking version check"); ZPackage val = new ZPackage(); val.Write("2.1.2"); peer.m_rpc.Invoke("ValheimRoleplay_VersionCheck", new object[1] { val }); } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] [Nullable(0)] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static class VerifyClient { private static bool Prefix(ZRpc rpc, ZPackage pkg, ref ZNet __instance) { if (!__instance.IsServer() || RpcHandlers.ValidatedPeers.Contains(rpc)) { return true; } VRPMod.ValheimRoleplayLogger.LogWarning((object)("Peer (" + rpc.m_socket.GetHostName() + ") never sent version or couldn't due to previous disconnect, disconnecting")); rpc.Invoke("Error", new object[1] { 3 }); return false; } private static void Postfix(ZNet __instance) { //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Expected O, but got Unknown ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "ValheimRoleplayRequestAdminSync", new object[1] { (object)new ZPackage() }); } } [HarmonyPatch(typeof(FejdStartup), "ShowConnectError")] public class ShowConnectionError { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(FejdStartup __instance) { if (__instance.m_connectionFailedPanel.activeSelf) { __instance.m_connectionFailedError.fontSizeMax = 25f; __instance.m_connectionFailedError.fontSizeMin = 15f; TMP_Text connectionFailedError = __instance.m_connectionFailedError; connectionFailedError.text = connectionFailedError.text + "\n" + VRPMod.ConnectionError; } } } [HarmonyPatch(typeof(ZNet), "Disconnect")] public static class RemoveDisconnectedPeerFromVerified { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Prefix(ZNetPeer peer, ref ZNet __instance) { if (__instance.IsServer()) { VRPMod.ValheimRoleplayLogger.LogInfo((object)("Peer (" + peer.m_rpc.m_socket.GetHostName() + ") disconnected, removing from validated list")); RpcHandlers.ValidatedPeers.Remove(peer.m_rpc); } } } [Nullable(0)] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static class RpcHandlers { public static readonly List ValidatedPeers = new List(); public static void RPC_ValheimRoleplay_Version(ZRpc rpc, ZPackage pkg) { string text = pkg.ReadString(); VRPMod.ValheimRoleplayLogger.LogInfo((object)("Version check, local: 2.1.2, remote: " + text)); if (text != "2.1.2") { VRPMod.ConnectionError = "ValheimRoleplay Installed: 2.1.2\n Needed: " + text; if (ZNet.instance.IsServer()) { VRPMod.ValheimRoleplayLogger.LogWarning((object)("Peer (" + rpc.m_socket.GetHostName() + ") has incompatible version, disconnecting...")); rpc.Invoke("Error", new object[1] { 3 }); } } else if (!ZNet.instance.IsServer()) { VRPMod.ValheimRoleplayLogger.LogInfo((object)"Received same version from server!"); } else { VRPMod.ValheimRoleplayLogger.LogInfo((object)("Adding peer (" + rpc.m_socket.GetHostName() + ") to validated list")); ValidatedPeers.Add(rpc); } } public static string ComputeHashForMod() { using SHA256 sHA = SHA256.Create(); byte[] array = sHA.ComputeHash(File.ReadAllBytes(Assembly.GetExecutingAssembly().Location)); StringBuilder stringBuilder = new StringBuilder(); byte[] array2 = array; foreach (byte b in array2) { stringBuilder.Append(b.ToString("X2")); } return stringBuilder.ToString(); } } } namespace ValheimRoleplay.Helpers { [Nullable(0)] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static class PlantableHelper { [Nullable(0)] public class PlantablePickableConfig { public string PlantName; private string _pickableName; private string _prefabName; private string _displayName; private string _description; public RequirementConfig[] Requirements; public int Yield = 3; public float GrowTime = 3000f; public float MinScale = 1f; public float MaxScale = 1.5f; public bool NeedCultivatedGround = true; public Biome AllowedBiomes = (Biome)895; public string PickableName { get { if (string.IsNullOrEmpty(_pickableName)) { return "Pickable_" + PlantName; } return _pickableName; } set { _pickableName = value; } } public string PrefabName { get { if (string.IsNullOrEmpty(_prefabName)) { return "sapling_" + PlantName; } return _prefabName; } set { _prefabName = value; } } public string DisplayName { get { if (string.IsNullOrEmpty(_displayName)) { return PlantName; } return _displayName; } set { _displayName = value; } } public string Description { get { if (string.IsNullOrEmpty(_description)) { return "Plant " + DisplayName; } return _description; } set { _description = value; } } } public static CustomPiece MakePlantablePickable(PlantablePickableConfig cfg) { //IL_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Expected O, but got Unknown //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Expected O, but got Unknown //IL_00c6: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) try { CustomPiece val = new CustomPiece(cfg.PrefabName, "sapling_carrot", new PieceConfig { PieceTable = "_CultivatorPieceTable", Name = cfg.PlantName, Description = cfg.Description, Icon = PrefabManager.Instance.GetPrefab(cfg.PlantName).GetComponent().m_itemData.GetIcon(), Requirements = cfg.Requirements }); Transform val2 = val.PiecePrefab.transform.Find("Visual"); if ((Object)(object)val2 != (Object)null) { Object.DestroyImmediate((Object)(object)((Component)val2).gameObject); } GameObject val3 = Object.Instantiate(PrefabManager.Instance.GetPrefab(cfg.PickableName), val.PiecePrefab.transform); ((Object)val3).name = "Visual"; val3.transform.localPosition = Vector3.zero; val3.transform.localRotation = Quaternion.identity; val3.transform.localScale = Vector3.one * 0.6f; Component[] components = val3.GetComponents(); foreach (Component val4 in components) { if (!(val4 is Transform) && !(val4 is MeshFilter) && !(val4 is MeshRenderer)) { Object.DestroyImmediate((Object)(object)val4); } } val3.layer = LayerMask.NameToLayer("piece"); string text = "cultivated_" + cfg.PlantName; GameObject val5 = PrefabManager.Instance.CreateClonedPrefab(text, cfg.PickableName); if ((Object)(object)val5 != (Object)null) { Pickable component = val5.GetComponent(); if ((Object)(object)component != (Object)null) { component.m_amount = cfg.Yield; component.m_respawnTimeMinutes = 0f; component.m_hideWhenPicked = null; } PrefabManager.Instance.AddPrefab(val5); } Plant component2 = val.PiecePrefab.GetComponent(); if ((Object)(object)component2 != (Object)null) { component2.m_name = cfg.PlantName; component2.m_minScale = cfg.MinScale; component2.m_maxScale = cfg.MaxScale; component2.m_needCultivatedGround = cfg.NeedCultivatedGround; component2.m_growTime = cfg.GrowTime; component2.m_grownPrefabs = null; component2.m_grownPrefabs = (GameObject[])(object)new GameObject[1] { val5 }; } PieceManager.Instance.AddPiece(val); } catch (Exception arg) { ZLog.LogError((object)$"[VRP] Error creating plantable '{cfg?.PlantName}': {arg}"); throw; } return null; } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [Nullable(0)] public static class RecipeHelper { public static void AddCoinExchange(string name, int coinAmount, params string[] trophies) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_0042: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Expected O, but got Unknown //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Expected O, but got Unknown RequirementConfig[] requirements = ((IEnumerable)trophies).Select((Func)([<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] (string t) => new RequirementConfig { Item = t, Amount = 1 })).ToArray(); CustomRecipe val = new CustomRecipe(new RecipeConfig { Name = name, Item = "Coins", Amount = coinAmount, Requirements = requirements, RequireOnlyOneIngredient = true }); ItemManager.Instance.AddRecipe(val); } public static void addMaterial(AssetBundle bundle, string prefabname) { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown try { GameObject val = bundle.LoadAsset(prefabname); if (Object.op_Implicit((Object)(object)val)) { CustomItem val2 = new CustomItem(val, true); ItemManager.Instance.AddItem(val2); if (VRPMod.DebugMode()) { ZLog.Log((object)("vrp added material " + prefabname)); } } else { ZLog.LogWarning((object)("vrp did not find prefab " + prefabname)); } } catch (Exception ex) { Logger.LogError((object)("vrp failed to add item " + prefabname)); Logger.LogError((object)ex); } } public static void addvrpitem(string prefabname, ref AssetBundle ab, ItemConfig ic) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown try { GameObject val = ab.LoadAsset(prefabname); if (Object.op_Implicit((Object)(object)val)) { CustomItem val2 = new CustomItem(val, true, ic); ItemManager.Instance.AddItem(val2); if (VRPMod.DebugMode()) { ZLog.Log((object)("vrp added item " + prefabname)); } } else { ZLog.LogWarning((object)("vrp did not find prefab " + prefabname)); } } catch (Exception ex) { Logger.LogError((object)(prefabname + ex.Message)); } } } [Nullable(0)] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static class VignetteHelper { private static Sprite _generatedVignette; public static GameObject CreateOverlay(string name, Color color, bool startEnabled = false) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Expected O, but got Unknown //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) GameObject val = new GameObject(name); Object.DontDestroyOnLoad((Object)(object)val); Canvas obj = val.AddComponent(); obj.renderMode = (RenderMode)0; obj.sortingOrder = 90; CanvasScaler obj2 = val.AddComponent(); obj2.uiScaleMode = (ScaleMode)1; obj2.referenceResolution = new Vector2(1920f, 1080f); GameObject val2 = new GameObject("VignetteImage"); val2.transform.SetParent(val.transform); Image obj3 = val2.AddComponent(); if ((Object)(object)_generatedVignette == (Object)null) { _generatedVignette = CreateRadialSprite(); } obj3.sprite = _generatedVignette; obj3.type = (Type)0; ((Graphic)obj3).color = color; ((Graphic)obj3).raycastTarget = false; RectTransform component = ((Component)obj3).GetComponent(); component.anchorMin = Vector2.zero; component.anchorMax = Vector2.one; component.offsetMin = Vector2.zero; component.offsetMax = Vector2.one; val.SetActive(startEnabled); return val; } private static Sprite CreateRadialSprite() { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Expected O, but got Unknown //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) int num = 256; Texture2D val = new Texture2D(num, num); ((Texture)val).wrapMode = (TextureWrapMode)1; float num2 = (float)num / 2f; for (int i = 0; i < num; i++) { for (int j = 0; j < num; j++) { float num3 = Mathf.Clamp01(Mathf.Pow(Vector2.Distance(new Vector2((float)j, (float)i), new Vector2(num2, num2)) / num2, 2.5f)); val.SetPixel(j, i, new Color(1f, 1f, 1f, num3)); } } val.Apply(); return Sprite.Create(val, new Rect(0f, 0f, (float)num, (float)num), new Vector2(0.5f, 0.5f)); } public static void SetIntensity(GameObject overlay, float intensity) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) if (!((Object)(object)overlay == (Object)null)) { Image componentInChildren = overlay.GetComponentInChildren(); if ((Object)(object)componentInChildren != (Object)null) { Color color = ((Graphic)componentInChildren).color; color.a = Mathf.Clamp(intensity, 0f, 0.95f); ((Graphic)componentInChildren).color = color; } } } } } namespace ValheimRoleplay.Patches { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [Nullable(0)] public static class MessageData { private static readonly Random _rng = new Random(); private static readonly string[] FarmerWardNoAccessMessages = new string[10] { "Hands off, thief. The soil remembers.", "You feel eyes on your back. Put it down.", "Not yours. Walk away while you still can.", "The ward hums… as if it knows your name.", "Touch it again and the farmers will hear of it.", "Nox whispers in your ear... \ud835\udd31\ud835\udd1e\ud835\udd28\ud835\udd22 \ud835\udd26\ud835\udd31 \ud835\udd1e\ud835\udd2b\ud835\udd21 ℑ \ud835\udd30\ud835\udd25\ud835\udd1e\ud835\udd29\ud835\udd29 \ud835\udd31\ud835\udd1e\ud835\udd28\ud835\udd22 \ud835\udd36\ud835\udd2c\ud835\udd32.", "\ud835\udd17\ud835\udd25\ud835\udd22 \ud835\udd0f\ud835\udd26\ud835\udd24\ud835\udd25\ud835\udd31 \ud835\udd30\ud835\udd22\ud835\udd22\ud835\udd30 \ud835\udd31\ud835\udd25\ud835\udd22 \ud835\udd25\ud835\udd1e\ud835\udd2b\ud835\udd21 \ud835\udd31\ud835\udd25\ud835\udd1e\ud835\udd31 \ud835\udd20\ud835\udd2c\ud835\udd33\ud835\udd22\ud835\udd31\ud835\udd30. \ud835\udd07\ud835\udd2f\ud835\udd1e\ud835\udd34 \ud835\udd1f\ud835\udd1e\ud835\udd20\ud835\udd28, \ud835\udd2c\ud835\udd2f \ud835\udd1f\ud835\udd22 \ud835\udd2f\ud835\udd22\ud835\udd21\ud835\udd32\ud835\udd20\ud835\udd22\ud835\udd21 \ud835\udd31\ud835\udd2c \ud835\udd1e\ud835\udd30\ud835\udd25.", "\ud835\udd17\ud835\udd25\ud835\udd22 \ud835\udd16\ud835\udd2c\ud835\udd29\ud835\udd30\ud835\udd34\ud835\udd2c\ud835\udd2f\ud835\udd2b \ud835\udd30\ud835\udd2c\ud835\udd34 \ud835\udd34\ud835\udd26\ud835\udd31\ud835\udd25 \ud835\udd30\ud835\udd34\ud835\udd22\ud835\udd1e\ud835\udd31; \ud835\udd31\ud835\udd25\ud835\udd22 \ud835\udd31\ud835\udd25\ud835\udd26\ud835\udd22\ud835\udd23 \ud835\udd2f\ud835\udd22\ud835\udd1e\ud835\udd2d\ud835\udd30 \ud835\udd2c\ud835\udd2b\ud835\udd29\ud835\udd36 \ud835\udd30\ud835\udd2c\ud835\udd2f\ud835\udd2f\ud835\udd2c\ud835\udd34.", "\ud835\udd04 \ud835\udd25\ud835\udd2c\ud835\udd29\ud835\udd29\ud835\udd2c\ud835\udd34 \ud835\udd25\ud835\udd1e\ud835\udd2f\ud835\udd33\ud835\udd22\ud835\udd30\ud835\udd31 \ud835\udd23\ud835\udd2c\ud835\udd2f \ud835\udd1e \ud835\udd25\ud835\udd2c\ud835\udd29\ud835\udd29\ud835\udd2c\ud835\udd34 \ud835\udd30\ud835\udd2c\ud835\udd32\ud835\udd29. \ud835\udd17\ud835\udd25\ud835\udd22 \ud835\udd10\ud835\udd26\ud835\udd30\ud835\udd31 \ud835\udd30\ud835\udd25\ud835\udd1e\ud835\udd29\ud835\udd29 \ud835\udd1f\ud835\udd22 \ud835\udd36\ud835\udd2c\ud835\udd32\ud835\udd2f \ud835\udd2c\ud835\udd2b\ud835\udd29\ud835\udd36 \ud835\udd2a\ud835\udd22\ud835\udd1e\ud835\udd29.", "You swear the crops just *watched* you." }; public static string GetFarmerWardMessage() { if (FarmerWardNoAccessMessages.Length == 0) { return "No access."; } lock (_rng) { return FarmerWardNoAccessMessages[_rng.Next(FarmerWardNoAccessMessages.Length)]; } } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [Nullable(0)] public static class ModData { public static readonly List RequiredMods = new List { "COM.JOTUNN.JOTUNN", "ARIELLE.VALHEIMROLEPLAY", "ARIELLE.RPCHATTER", "ARIELLE.BESTDRESSED", "SOLOREDIS.RTDBIOMES", "1010101110.VRPSTABLE", "ASHARPPEN.VALHEIM.SPAWN_THAT", "ASHARPPEN.VALHEIM.DROP_THAT", "ORG.BEPINEX.PLUGINS.SERVERCHARACTERS", "AZUMATT.AZUANTIARTHRITICCRAFTING", "ORG.JROBSONCHASE.VALHEIM.PLUGINS.POSITIONALAUDIO", "COM.VALHEIMMODDING.NEWTONSOFTJSONDETECTOR", "AZUMATT.FASTLINK", "ORG.BEPINEX.PLUGINS.CREATURELEVELCONTROL", "BLACKS7AR.COREWOODPIECES", "BLACKS7AR.OREMINES", "BLACKS7AR.FINEWOODPIECES", "ORG.BEPINEX.PLUGINS.BACKPACKS", "BLACKS7AR.MAGICREVAMP", "CEBERO.TORVALDSAFFORDABLEPAINTERS", "COM.DRAKEMODS.DRAKESRENAMEIT", "COOKIEMILK.README", "GRAVEBEAR.ODINSFOODBARRELS", "BETTERCONTINENTS", "HU.JARD.CLEARSKIES", "SHUDNAL.CIRCLETEXTENDED", "SHUDNAL.MOREGATESEXTENDED", "SOUTHSIL.SOUTHSILARMOR", "ITEM_STAND_ALL_ITEMS", "EXPAND_WORLD_DATA", "ORG.BEPINEX.PLUGINS.GAPFILLER", "COM.BENTO.MISSINGPIECES", "ORG.BEPINEX.PLUGINS.MOREMISSINGPIECES" }; public static readonly List OptionalMods = new List { "BLACKS7AR.ONEHANDWEAPONONTHEHIP", "BLACKS7AR.WEAPONHOLSTEROVERHAUL", "ZENDRAGON.ZEN.MODLIB", "ZENDRAGON.ZENREDECORATE", "COM.VALHEIMMODDING.YAMLDOTNETDETECTOR", "BRUCE.VALHEIM.COMFYMODS.GIZMO", "AZUMATT.SEARCHABLEBUILDMENU", "NEOBOTICS.VALHEIM_MOD.HUDCOMPASS", "BRUCE.VALHEIM.COMFY.DUMPSTERFIRE", "AZUMATT.AZUHOVERSTATS", "ADVIZE.PLANTEASILY", "ARIELLE.MOREMAPPINS", "COM.MAXSCH.VALHEIM.WHICHMODADDEDTHIS", "COM.MAXSCH.VALHEIM.LOCALIZATIONCACHE", "ORG.BEPINEX.VALHEIM.DISPLAYINFO", "COM.ORIANAVENTURE.MOD.NOGRASS", "ZENDRAGON.ZENITEMSTANDS", "COM.MAXSCH.VALHEIM.TIMEOUTLIMIT", "CW_JESSE.BETTERNETWORKING", "REDSEIKO.VALHEIM.SEARSCATALOG", "AZUMATT.FIRSTPERSONMODE", "VALHEIMADJUSTEXPOSURE", "VALHEIMADJUSTBRIGHTNESS" }; public static readonly List AdminMods = new List { "UPGRADE_WORLD", "SERVER_DEVCOMMANDS", "SKTOOLBOX", "COOLEY.EASYSPAWNER", "TERRAINRESET", "MAPTELEPORT", "MARCOPOGO.PLANBUILD", "UNITYEXPLORER", "INFINITY_HAMMER", "VNEI", "DEVCOMMANDS", "XRAY", "ESP", "WORLD_EDIT_COMMANDS", "ZONESCOUTER" }; } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [Nullable(0)] public static class PlantData { public static readonly Dictionary PlantAnywhere = new Dictionary { { "Beech_Sapling", "Beech sapling" }, { "Birch_Sapling", "Birch Sapling" }, { "FirTree_Sapling", "Fir Sapling" }, { "Oak_Sapling", "Oak Sapling" }, { "PineTree_Sapling", "Pine Sapling" }, { "sapling_barley", "Barley" }, { "sapling_jotunpuffs", "Jotunpuffs" }, { "sapling_magecap", "Magecap" } }; public static readonly List PickablePlantConfigs = new List { new PlantableHelper.PlantablePickableConfig { PlantName = "Mushroom", PickableName = "Pickable_Mushroom", PrefabName = "sapling_mushroom_r", DisplayName = "Mushroom", Description = "Grow mushrooms with this quick trick!", Yield = 6, Requirements = (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "Mushroom", Amount = 2 }, new RequirementConfig { Item = "BoneFragments", Amount = 1 } } }, new PlantableHelper.PlantablePickableConfig { PlantName = "MushroomYellow", PickableName = "Pickable_Mushroom_yellow", PrefabName = "sapling_mushroom_y", DisplayName = "Yellow Mushroom", Description = "Grow yellow mushrooms", Requirements = (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "Mushroom", Amount = 2 }, new RequirementConfig { Item = "BoneFragments", Amount = 1 } } }, new PlantableHelper.PlantablePickableConfig { PlantName = "MushroomBlue", PickableName = "Pickable_Mushroom_blue", PrefabName = "sapling_mushroom_blue", DisplayName = "Blue Mushroom", Description = "Grow blue mushrooms", Yield = 6, Requirements = (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "MushroomBlue", Amount = 2 }, new RequirementConfig { Item = "BoneFragments", Amount = 1 } } }, new PlantableHelper.PlantablePickableConfig { PlantName = "Thistle", PickableName = "Pickable_Thistle", PrefabName = "sapling_thistle", DisplayName = "Thistle", Description = "Grow thistle with this quick trick!", Yield = 6, Requirements = (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "Thistle", Amount = 2 }, new RequirementConfig { Item = "BoneFragments", Amount = 1 } } }, new PlantableHelper.PlantablePickableConfig { PlantName = "StoneRock", PickableName = "Pickable_StoneRock", PrefabName = "sapling_stonerock", DisplayName = "Rock", Description = "Everyone enjoys a happy rock garden!", Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "Stone", Amount = 20 } }, Yield = 1 }, new PlantableHelper.PlantablePickableConfig { PlantName = "Dandelion", PickableName = "Pickable_Dandelion", PrefabName = "sapling_dandelion", DisplayName = "Dandelion", Description = "Grow dandelion", Yield = 6, Requirements = (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "Dandelion", Amount = 2 }, new RequirementConfig { Item = "BoneFragments", Amount = 1 } } }, new PlantableHelper.PlantablePickableConfig { PlantName = "Fiddleheadfern", PickableName = "Pickable_Fiddlehead", PrefabName = "sapling_fiddlehead", DisplayName = "Fiddlehead", Description = "Grow fiddlehead with this quick trick!", Yield = 6, Requirements = (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "Fiddleheadfern", Amount = 2 }, new RequirementConfig { Item = "BoneFragments", Amount = 1 } } } }; } [Nullable(0)] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static class RecipeData { [Nullable(0)] public class SimpleRecipe { public string Item { get; set; } public int Amount { get; set; } public string CraftingStation { get; set; } = string.Empty; public Dictionary Requirements { get; set; } } [Nullable(0)] public class ComplexRecipe { public string Item { get; set; } public int Amount { get; set; } = 1; public string CraftingStation { get; set; } = string.Empty; public string Description { get; set; } public int StationLevel { get; set; } = 1; [Nullable(new byte[] { 1, 1, 0 })] [field: Nullable(new byte[] { 1, 1, 0 })] public Dictionary Requirements { [return: Nullable(new byte[] { 1, 1, 0 })] get; [param: Nullable(new byte[] { 1, 1, 0 })] set; } public string BundleKey { get; set; } } public static readonly Dictionary TrophyConversion = new Dictionary { { 2, "TrophyBoar,TrophyNeck" }, { 5, "TrophyDeer,TrophyGreydwarf,TrophySkeleton" }, { 10, "TrophyHare,TrophyDvergr,TrophyBjorn,TrophyEikthyr,TrophyForestTroll,TrophyFrostTroll,TrophyGreydwarfBrute,TrophyGreydwarfShaman,TrophySkeletonPoison,TrophyBlob,TrophyDraugr,TrophySurtling,TrophyLeech,TrophyWolf" }, { 20, "TrophyTheElder,TrophySkeletonHildir,TrophyAbomination,TrophyWraith,TrophyDraugrElite,TrophySerpent,TrophyHatchling,TrophyUlv,TrophyFenring,TrophyLox" }, { 30, "TrophyBonemass,TrophyCultist,TrophyGoblin" }, { 40, "TrophyCultist_Hildir,TrophySGolem,TrophyDragonQueen,TrophyBjornUndead,TrophyGrowth,TrophyGoblinShaman,TrophyDeathsquito,TrophyGoblinBrute,TrophySeeker,TrophyAsksvin" }, { 50, "TrophyGoblinBruteBrosBrute,TrophyGoblinBruteBrosShaman,TrophyGoblinKing,TrophyTick,TrophySeekerBrute,TrophyGjall,TrophyCharredArcher,TrophyCharredMage,TrophyCharredMelee" }, { 60, "TrophySeekerQueen,TrophyMorgen,TrophyFallenValkyrie,TrophyFader" } }; public static readonly Dictionary MerchantRecipes = new Dictionary { ["vrp_merchantb0"] = new SimpleRecipe { Item = "Coins", Amount = 10, Requirements = new Dictionary { ["AmberPearl"] = 1 } }, ["vrp_merchantb1"] = new SimpleRecipe { Item = "Coins", Amount = 20, Requirements = new Dictionary { ["Ruby"] = 1 } }, ["vrp_merchantb3"] = new SimpleRecipe { Item = "Coins", Amount = 5, Requirements = new Dictionary { ["Amber"] = 1 } }, ["vrp_merchantb4"] = new SimpleRecipe { Item = "Coins", Amount = 30, Requirements = new Dictionary { ["SilverNecklace"] = 1 } }, ["vrp_merchantbb0"] = new SimpleRecipe { Item = "AmberPearl", Amount = 1, Requirements = new Dictionary { ["Coins"] = 15 } }, ["vrp_merchantbb1"] = new SimpleRecipe { Item = "Ruby", Amount = 1, Requirements = new Dictionary { ["Coins"] = 25 } }, ["vrp_merchantbb3"] = new SimpleRecipe { Item = "Amber", Amount = 1, Requirements = new Dictionary { ["Coins"] = 10 } }, ["vrp_merchantbb4"] = new SimpleRecipe { Item = "SilverNecklace", Amount = 1, Requirements = new Dictionary { ["Coins"] = 35 } }, ["vrp_merchant9"] = new SimpleRecipe { Item = "FishingBait", Amount = 20, Requirements = new Dictionary { ["Floam"] = 10 } }, ["vrp_merchant10"] = new SimpleRecipe { Item = "FishingRod", Amount = 1, Requirements = new Dictionary { ["Floam"] = 50, ["Wood"] = 10 } }, ["vrp_merchant11"] = new SimpleRecipe { Item = "HelmetYule", Amount = 1, Requirements = new Dictionary { ["DeerHide"] = 1, ["Raspberry"] = 5 } }, ["vrp_merchant12"] = new SimpleRecipe { Item = "BeltStrength", Amount = 1, Requirements = new Dictionary { ["TrinketBronzeHealth"] = 1, ["AmberPearl"] = 50, ["BjornHide"] = 10 } }, ["vrp_merchant13"] = new SimpleRecipe { Item = "HelmetDverger", Amount = 1, Requirements = new Dictionary { ["Coins"] = 950 } }, ["vrp_merchant14"] = new SimpleRecipe { Item = "Thunderstone", Amount = 1, Requirements = new Dictionary { ["Stone"] = 20, ["CryptKey"] = 10 } }, ["vrp_merchant15"] = new SimpleRecipe { Item = "YmirRemains", Amount = 1, Requirements = new Dictionary { ["Entrails"] = 30, ["Floam"] = 30, ["TrophyDraugr"] = 1 } }, ["vrp_merchant17"] = new SimpleRecipe { Item = "Floam", Amount = 10, Requirements = new Dictionary { ["Coins"] = 20 } }, ["vrp_merchant170"] = new SimpleRecipe { Item = "Gloam", Amount = 1, Requirements = new Dictionary { ["Coins"] = 100, ["Floam"] = 5 } }, ["vrp_merchant171"] = new SimpleRecipe { Item = "Guck", Amount = 1, Requirements = new Dictionary { ["Pukeberries"] = 10, ["GreydwarfEye"] = 10, ["Coins"] = 20 } }, ["vrp_merchant18"] = new SimpleRecipe { Item = "Crystal", Amount = 1, Requirements = new Dictionary { ["Stone"] = 10, ["Coins"] = 25 } }, ["vrp_merchant19"] = new SimpleRecipe { Item = "Tar", Amount = 1, Requirements = new Dictionary { ["Resin"] = 25, ["Coal"] = 20, ["Coins"] = 20 } } }; public static readonly Dictionary MagicItems = new Dictionary { ["vrp_fireessence"] = new SimpleRecipe { Item = "BMR_FireEssence", Amount = 5, Requirements = new Dictionary { ["Coins"] = 1, ["Floam"] = 1 } }, ["vrp_iceessence"] = new SimpleRecipe { Item = "BMR_IceEssence", Amount = 5, Requirements = new Dictionary { ["Coins"] = 1, ["Floam"] = 1 } }, ["vrp_lightningessence"] = new SimpleRecipe { Item = "BMR_LightningEssence", Amount = 5, Requirements = new Dictionary { ["Coins"] = 1, ["Floam"] = 1 } }, ["vrp_toxicessence"] = new SimpleRecipe { Item = "BMR_PoisonEssence", Amount = 5, Requirements = new Dictionary { ["Coins"] = 1, ["Floam"] = 1 } } }; public static readonly Dictionary MakeItCraftableRecipes; public static readonly Dictionary VRP_Armor; public static readonly Dictionary VRP_Misc; static RecipeData() { Dictionary dictionary = new Dictionary(); dictionary["vrp_barbkit"] = new SimpleRecipe { Item = "BarberKit", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["Tin"] = 5, ["Amber"] = 10, ["DeerHide"] = 5, ["Feathers"] = 50 } }; dictionary["vrp_ironpit"] = new SimpleRecipe { Item = "Ironpit", Amount = 1, CraftingStation = "forge", Requirements = new Dictionary { ["Iron"] = 10 } }; dictionary["vrp_firework"] = new SimpleRecipe { Item = "FireworksRocket_White", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["Coins"] = 25 } }; dictionary["vrp_sparkler"] = new SimpleRecipe { Item = "Sparkler", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["Coins"] = 25 } }; dictionary["vrp_hat5"] = new SimpleRecipe { Item = "HelmetHat5", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 6, ["Raspberry"] = 2 } }; dictionary["vrp_hat10"] = new SimpleRecipe { Item = "HelmetHat10", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 6, ["Raspberry"] = 2 } }; dictionary["vrp_hat1"] = new SimpleRecipe { Item = "HelmetHat1", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 6, ["Blueberries"] = 2 } }; dictionary["vrp_hat6"] = new SimpleRecipe { Item = "HelmetHat6", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 6, ["Dandelion"] = 2 } }; dictionary["vrp_hat2"] = new SimpleRecipe { Item = "HelmetHat2", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 6, ["Pukeberries"] = 2 } }; dictionary["vrp_hat7"] = new SimpleRecipe { Item = "HelmetHat7", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 6, ["Bloodbag"] = 2 } }; dictionary["vrp_hat3"] = new SimpleRecipe { Item = "HelmetHat3", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 6, ["WolfPelt"] = 1 } }; dictionary["vrp_hat8"] = new SimpleRecipe { Item = "HelmetHat8", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 6, ["WolfPelt"] = 1 } }; dictionary["vrp_hat4"] = new SimpleRecipe { Item = "HelmetHat4", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 6, ["BlackMetalScrap"] = 1 } }; dictionary["vrp_hat9"] = new SimpleRecipe { Item = "HelmetHat9", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 6, ["Bilebag"] = 1 } }; dictionary["vrp_hatsweat"] = new SimpleRecipe { Item = "HelmetSweatBand", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["Floam"] = 6, ["LeatherScraps"] = 1 } }; dictionary["vrp_tunic1"] = new SimpleRecipe { Item = "ArmorTunic1", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 8, ["Blueberries"] = 5, ["Coins"] = 5 } }; dictionary["vrp_tunic10"] = new SimpleRecipe { Item = "ArmorTunic10", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 8, ["Floam"] = 5, ["Coins"] = 5 } }; dictionary["vrp_tunic4"] = new SimpleRecipe { Item = "ArmorTunic4", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 8, ["Raspberry"] = 5, ["Coins"] = 5 } }; dictionary["vrp_tunic7"] = new SimpleRecipe { Item = "ArmorTunic7", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 8, ["Dandelion"] = 5, ["Coins"] = 5 } }; dictionary["vrp_tunic2"] = new SimpleRecipe { Item = "ArmorTunic2", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 8, ["Blueberries"] = 5, ["SilverNecklace"] = 1 } }; dictionary["vrp_tunic5"] = new SimpleRecipe { Item = "ArmorTunic5", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 8, ["Raspberry"] = 5, ["SilverNecklace"] = 1 } }; dictionary["vrp_tunic8"] = new SimpleRecipe { Item = "ArmorTunic8", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 8, ["Dandelion"] = 5, ["SilverNecklace"] = 1 } }; dictionary["vrp_tunic3"] = new SimpleRecipe { Item = "ArmorTunic3", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 8, ["Blueberries"] = 5, ["Amber"] = 2 } }; dictionary["vrp_tunic6"] = new SimpleRecipe { Item = "ArmorTunic6", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 8, ["Raspberry"] = 5, ["Amber"] = 2 } }; dictionary["vrp_tunic9"] = new SimpleRecipe { Item = "ArmorTunic9", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 8, ["Dandelion"] = 5, ["Amber"] = 2 } }; dictionary["vrp_transmute_tin"] = new SimpleRecipe { Item = "Tin", Amount = 1, CraftingStation = "piece_cauldron", Requirements = new Dictionary { ["Iron"] = 1, ["Amber"] = 1 } }; dictionary["vrp_transmute_copper"] = new SimpleRecipe { Item = "Copper", Amount = 1, CraftingStation = "piece_cauldron", Requirements = new Dictionary { ["Iron"] = 1, ["Amber"] = 1 } }; dictionary["vrp_transmute_iron"] = new SimpleRecipe { Item = "Iron", Amount = 1, CraftingStation = "piece_cauldron", Requirements = new Dictionary { ["Silver"] = 2, ["AmberPearl"] = 1 } }; dictionary["vrp_transmute_silver"] = new SimpleRecipe { Item = "Silver", Amount = 1, CraftingStation = "piece_cauldron", Requirements = new Dictionary { ["BlackMetal"] = 2, ["AmberPearl"] = 1 } }; dictionary["vrp_transmute_blackmetal"] = new SimpleRecipe { Item = "BlackMetal", Amount = 1, CraftingStation = "piece_cauldron", Requirements = new Dictionary { ["Iron"] = 10, ["Ruby"] = 1, ["Eitr"] = 1 } }; dictionary["vrp_transmute_softtissue"] = new SimpleRecipe { Item = "Softtissue", Amount = 1, CraftingStation = "piece_cauldron", Requirements = new Dictionary { ["BlackMetal"] = 2, ["Ruby"] = 1 } }; dictionary["vrp_transmute_flametal"] = new SimpleRecipe { Item = "FlametalOreNew", Amount = 1, CraftingStation = "piece_cauldron", Requirements = new Dictionary { ["FlametalOre"] = 1, ["Amber"] = 1 } }; dictionary["vrp_redjute"] = new SimpleRecipe { Item = "JuteRed", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["LinenThread"] = 2, ["Raspberry"] = 2 } }; dictionary["vrp_bluejute"] = new SimpleRecipe { Item = "JuteBlue", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["LinenThread"] = 2, ["Blueberries "] = 2 } }; dictionary["vrp_dress1"] = new SimpleRecipe { Item = "ArmorDress1", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 8, ["Blueberries"] = 5, ["Coins"] = 5 } }; dictionary["vrp_dress10"] = new SimpleRecipe { Item = "ArmorDress10", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 8, ["Floam"] = 5, ["Coins"] = 5 } }; dictionary["vrp_dress4"] = new SimpleRecipe { Item = "ArmorDress4", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 8, ["Raspberry"] = 5, ["Coins"] = 5 } }; dictionary["vrp_dress7"] = new SimpleRecipe { Item = "ArmorDress7", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 8, ["Dandelion"] = 5, ["Coins"] = 5 } }; dictionary["vrp_dress2"] = new SimpleRecipe { Item = "ArmorDress2", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 8, ["Blueberries"] = 5, ["SilverNecklace"] = 1 } }; dictionary["vrp_dress5"] = new SimpleRecipe { Item = "ArmorDress5", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 8, ["Raspberry"] = 5, ["SilverNecklace"] = 1 } }; dictionary["vrp_dress8"] = new SimpleRecipe { Item = "ArmorDress8", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["Dandelion"] = 5, ["SilverNecklace"] = 1 } }; dictionary["vrp_dress3"] = new SimpleRecipe { Item = "ArmorDress3", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 8, ["Blueberries"] = 5, ["Amber"] = 2 } }; dictionary["vrp_dress6"] = new SimpleRecipe { Item = "ArmorDress6", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 8, ["Raspberry"] = 5, ["Amber"] = 2 } }; dictionary["vrp_dress9"] = new SimpleRecipe { Item = "ArmorDress9", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["DeerHide"] = 8, ["Dandelion"] = 5, ["Amber"] = 2 } }; dictionary["vrp_strawhat"] = new SimpleRecipe { Item = "HelmetStrawHat", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["LeatherScraps"] = 2, ["CarrotSeeds"] = 2 } }; dictionary["vrp_strawtunic"] = new SimpleRecipe { Item = "ArmorHarvester1", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["LeatherScraps"] = 2, ["CarrotSeeds"] = 2 } }; dictionary["vrp_strawdress"] = new SimpleRecipe { Item = "ArmorHarvester2", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["LeatherScraps"] = 2, ["CarrotSeeds"] = 2 } }; dictionary["vrp_curedsquirrelhamstring"] = new SimpleRecipe { Item = "CuredSquirrelHamstring", Amount = 1, CraftingStation = "piece_cauldron", Requirements = new Dictionary { ["RawMeat"] = 3, ["Dandelion"] = 1 } }; dictionary["vrp_feaster"] = new SimpleRecipe { Item = "Feaster", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["Wood"] = 10, ["Resin"] = 5 } }; dictionary["vrp_barrelrings"] = new SimpleRecipe { Item = "BarrelRings", Amount = 3, CraftingStation = "", Requirements = new Dictionary { ["Tin"] = 1 } }; dictionary["vrp_candlewick"] = new SimpleRecipe { Item = "CandleWick", Amount = 1, CraftingStation = "", Requirements = new Dictionary { ["Honey"] = 2, ["Resin"] = 5 } }; dictionary["vrp_powdereddragonegg"] = new SimpleRecipe { Item = "PowderedDragonEgg", Amount = 5, CraftingStation = "piece_preptable", Requirements = new Dictionary { ["DragonEgg"] = 1, ["Obsidian"] = 10 } }; dictionary["vrp_pungentpebbles"] = new SimpleRecipe { Item = "PungentPebbles", Amount = 5, CraftingStation = "piece_cauldron", Requirements = new Dictionary { ["GreydwarfEye"] = 5, ["Pukeberries"] = 3 } }; dictionary["vrp_scythehandle"] = new SimpleRecipe { Item = "ScytheHandle", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["LeatherScraps"] = 5, ["ElderBark"] = 10 } }; dictionary["vrp_fragrantbundle"] = new SimpleRecipe { Item = "FragrantBundle", Amount = 5, CraftingStation = "piece_preptable", Requirements = new Dictionary { ["Thistle"] = 3, ["Dandelion"] = 3, ["Cloudberry"] = 3 } }; dictionary["vrp_freshseaweed"] = new SimpleRecipe { Item = "FreshSeaweed", Amount = 5, CraftingStation = "piece_cauldron", Requirements = new Dictionary { ["Thistle"] = 5, ["BoneFragments"] = 3 } }; dictionary["vrp_mushroombzerker"] = new SimpleRecipe { Item = "MushroomBzerker", Amount = 5, CraftingStation = "piece_cauldron", Requirements = new Dictionary { ["Bloodbag"] = 5, ["Pukeberries"] = 5 } }; dictionary["vrp_spicemistlands"] = new SimpleRecipe { Item = "SpiceMistlands", Amount = 5, CraftingStation = "piece_preptable", Requirements = new Dictionary { ["Dandelion"] = 10, ["MushroomMagecap"] = 5 } }; dictionary["vrp_spicemountains"] = new SimpleRecipe { Item = "SpiceMountains", Amount = 5, CraftingStation = "piece_preptable", Requirements = new Dictionary { ["BoneFragments"] = 3, ["Onion"] = 5 } }; dictionary["vrp_spiceoceans"] = new SimpleRecipe { Item = "SpiceOceans", Amount = 5, CraftingStation = "piece_preptable", Requirements = new Dictionary { ["SerpentScale"] = 5, ["Thistle"] = 5 } }; dictionary["vrp_spiceplains"] = new SimpleRecipe { Item = "SpicePlains", Amount = 5, CraftingStation = "piece_preptable", Requirements = new Dictionary { ["Cloudberry"] = 10, ["MushroomYellow"] = 5 } }; dictionary["vrp_vinegreenseeds"] = new SimpleRecipe { Item = "VineGreenSeeds", Amount = 10, CraftingStation = "", Requirements = new Dictionary { ["Coins"] = 100 } }; dictionary["vrp_spiceashlands"] = new SimpleRecipe { Item = "SpiceAshlands", Amount = 5, CraftingStation = "piece_preptable", Requirements = new Dictionary { ["MushroomSmokePuff"] = 10, ["Barley"] = 5 } }; dictionary["vrp_spiceashlands"] = new SimpleRecipe { Item = "SpiceAshlands", Amount = 5, CraftingStation = "piece_preptable", Requirements = new Dictionary { ["MushroomSmokePuff"] = 10, ["Barley"] = 5 } }; dictionary["vrp_spiceforests"] = new SimpleRecipe { Item = "SpiceForests", Amount = 5, CraftingStation = "piece_preptable", Requirements = new Dictionary { ["MushroomYellow"] = 10, ["Dandelion"] = 10 } }; dictionary["vrp_vial"] = new SimpleRecipe { Item = "BlobVial", Amount = 5, CraftingStation = "piece_preptable", Requirements = new Dictionary { ["Coins"] = 150 } }; dictionary["vrp_charcoalresin"] = new SimpleRecipe { Item = "CharcoalResin", Amount = 1, CraftingStation = "", Requirements = new Dictionary { ["Coal"] = 3, ["Resin"] = 3 } }; dictionary["vrp_potshard"] = new SimpleRecipe { Item = "Pot_Shard_Green", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["Flint"] = 5, ["Stone"] = 5, ["Floam"] = 5 } }; dictionary["vrp_axehead1"] = new SimpleRecipe { Item = "AxeHead1", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["Flint"] = 5, ["Floam"] = 5 } }; dictionary["vrp_axehead2"] = new SimpleRecipe { Item = "AxeHead2", Amount = 1, CraftingStation = "piece_workbench", Requirements = new Dictionary { ["Stone"] = 5, ["Floam"] = 5 } }; MakeItCraftableRecipes = dictionary; VRP_Armor = new Dictionary { ["LeatherChestRed"] = new ComplexRecipe { Item = "LeatherChestRed", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 1, BundleKey = "vrpbundle", Requirements = new Dictionary { ["DeerHide"] = (6, 10), ["BoneFragments"] = (0, 10) } }, ["LeatherChestGreen"] = new ComplexRecipe { Item = "LeatherChestGreen", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 1, BundleKey = "vrpbundle", Requirements = new Dictionary { ["DeerHide"] = (6, 10), ["BoneFragments"] = (0, 10) } }, ["LeatherChestBlue"] = new ComplexRecipe { Item = "LeatherChestBlue", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 1, BundleKey = "vrpbundle", Requirements = new Dictionary { ["DeerHide"] = (6, 10), ["BoneFragments"] = (0, 10) } }, ["LeatherTrousersRed"] = new ComplexRecipe { Item = "LeatherTrousersRed", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 1, BundleKey = "vrpbundle", Requirements = new Dictionary { ["DeerHide"] = (6, 10), ["BoneFragments"] = (0, 10) } }, ["LeatherTrousersGreen"] = new ComplexRecipe { Item = "LeatherTrousersGreen", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 1, BundleKey = "vrpbundle", Requirements = new Dictionary { ["DeerHide"] = (6, 10), ["BoneFragments"] = (0, 10) } }, ["LeatherTrousersBlue"] = new ComplexRecipe { Item = "LeatherTrousersBlue", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 1, BundleKey = "vrpbundle", Requirements = new Dictionary { ["DeerHide"] = (6, 10), ["BoneFragments"] = (0, 10) } }, ["LeatherHelmRed"] = new ComplexRecipe { Item = "LeatherHelmRed", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 1, BundleKey = "vrpbundle", Requirements = new Dictionary { ["DeerHide"] = (6, 10), ["BoneFragments"] = (0, 10) } }, ["LeatherHelmBlue"] = new ComplexRecipe { Item = "LeatherHelmBlue", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 1, BundleKey = "vrpbundle", Requirements = new Dictionary { ["DeerHide"] = (6, 10), ["BoneFragments"] = (0, 10) } }, ["LeatherHelmGreen"] = new ComplexRecipe { Item = "LeatherHelmGreen", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 1, BundleKey = "vrpbundle", Requirements = new Dictionary { ["DeerHide"] = (6, 10), ["BoneFragments"] = (0, 10) } }, ["TrollChestBlack"] = new ComplexRecipe { Item = "TrollChestBlack", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 2, BundleKey = "vrpbundle", Requirements = new Dictionary { ["TrollHide"] = (5, 5), ["BoneFragments"] = (2, 5) } }, ["TrollChestBrown"] = new ComplexRecipe { Item = "TrollChestBrown", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 2, BundleKey = "vrpbundle", Requirements = new Dictionary { ["TrollHide"] = (5, 5), ["BoneFragments"] = (2, 5) } }, ["TrollChestWhite"] = new ComplexRecipe { Item = "TrollChestWhite", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 2, BundleKey = "vrpbundle", Requirements = new Dictionary { ["TrollHide"] = (5, 5), ["BoneFragments"] = (2, 5) } }, ["TrollHoodBlack"] = new ComplexRecipe { Item = "TrollHoodBlack", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 2, BundleKey = "vrpbundle", Requirements = new Dictionary { ["TrollHide"] = (5, 5), ["BoneFragments"] = (2, 5) } }, ["TrollHoodBrown"] = new ComplexRecipe { Item = "TrollHoodBrown", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 2, BundleKey = "vrpbundle", Requirements = new Dictionary { ["TrollHide"] = (5, 5), ["BoneFragments"] = (2, 5) } }, ["TrollHoodWhite"] = new ComplexRecipe { Item = "TrollHoodWhite", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 2, BundleKey = "vrpbundle", Requirements = new Dictionary { ["TrollHide"] = (5, 5), ["BoneFragments"] = (2, 5) } }, ["TrollLegsBlack"] = new ComplexRecipe { Item = "TrollLegsBlack", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 2, BundleKey = "vrpbundle", Requirements = new Dictionary { ["TrollHide"] = (5, 5), ["BoneFragments"] = (2, 5) } }, ["TrollLegsBrown"] = new ComplexRecipe { Item = "TrollLegsBrown", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 2, BundleKey = "vrpbundle", Requirements = new Dictionary { ["TrollHide"] = (5, 5), ["BoneFragments"] = (2, 5) } }, ["TrollLegsWhite"] = new ComplexRecipe { Item = "TrollLegsWhite", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 2, BundleKey = "vrpbundle", Requirements = new Dictionary { ["TrollHide"] = (5, 5), ["BoneFragments"] = (2, 5) } }, ["BronzeHelmRed"] = new ComplexRecipe { Item = "BronzeHelmRed", Amount = 1, CraftingStation = "forge", StationLevel = 1, BundleKey = "bronzehelm", Requirements = new Dictionary { ["Bronze"] = (5, 2), ["DeerHide"] = (2, 2), ["LeatherScraps"] = (2, 2), ["Crystal"] = (1, 0) } }, ["BronzeHelmGreen"] = new ComplexRecipe { Item = "BronzeHelmGreen", Amount = 1, CraftingStation = "forge", StationLevel = 1, BundleKey = "bronzehelm", Requirements = new Dictionary { ["Bronze"] = (5, 2), ["DeerHide"] = (2, 2), ["LeatherScraps"] = (2, 2), ["Crystal"] = (1, 0) } }, ["BronzeHelmBlue"] = new ComplexRecipe { Item = "BronzeHelmBlue", Amount = 1, CraftingStation = "forge", StationLevel = 1, BundleKey = "bronzehelm", Requirements = new Dictionary { ["Bronze"] = (5, 2), ["DeerHide"] = (2, 2), ["LeatherScraps"] = (2, 2), ["Crystal"] = (1, 0) } }, ["BWspiritChest"] = new ComplexRecipe { Item = "BWspiritChest", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 99, BundleKey = "vrpbundle", Requirements = new Dictionary { ["SledgeCheat"] = (1, 0) } }, ["BWspiritLegs"] = new ComplexRecipe { Item = "BWspiritLegs", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 99, BundleKey = "vrpbundle", Requirements = new Dictionary { ["SledgeCheat"] = (1, 0) } }, ["BWspiritHood"] = new ComplexRecipe { Item = "BWspiritHood", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 99, BundleKey = "vrpbundle", Requirements = new Dictionary { ["SledgeCheat"] = (1, 0) } }, ["GoldSpiritChest"] = new ComplexRecipe { Item = "GoldSpiritChest", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 99, BundleKey = "vrpbundle", Requirements = new Dictionary { ["SledgeCheat"] = (1, 0) } }, ["GoldSpiritLegs"] = new ComplexRecipe { Item = "GoldSpiritLegs", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 99, BundleKey = "vrpbundle", Requirements = new Dictionary { ["SledgeCheat"] = (1, 0) } }, ["GoldSpiritHelm"] = new ComplexRecipe { Item = "GoldSpiritHelm", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 99, BundleKey = "vrpbundle", Requirements = new Dictionary { ["SledgeCheat"] = (1, 0) } }, ["RedSpiritChest"] = new ComplexRecipe { Item = "RedSpiritChest", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 99, BundleKey = "vrpbundle", Requirements = new Dictionary { ["SledgeCheat"] = (1, 0) } }, ["RedSpiritLegs"] = new ComplexRecipe { Item = "RedSpiritLegs", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 99, BundleKey = "vrpbundle", Requirements = new Dictionary { ["SledgeCheat"] = (1, 0) } }, ["RedSpiritHelm"] = new ComplexRecipe { Item = "RedSpiritHelm", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 99, BundleKey = "vrpbundle", Requirements = new Dictionary { ["SledgeCheat"] = (1, 0) } }, ["WarSpiritChest"] = new ComplexRecipe { Item = "WarSpiritChest", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 99, BundleKey = "vrpbundle", Requirements = new Dictionary { ["SledgeCheat"] = (1, 0) } }, ["WarSpiritHelm"] = new ComplexRecipe { Item = "WarSpiritHelm", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 99, BundleKey = "vrpbundle", Requirements = new Dictionary { ["SledgeCheat"] = (1, 0) } }, ["WarSpiritLegs"] = new ComplexRecipe { Item = "WarSpiritLegs", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 99, BundleKey = "vrpbundle", Requirements = new Dictionary { ["SledgeCheat"] = (1, 0) } }, ["OrangeSpiritChest"] = new ComplexRecipe { Item = "OrangeSpiritChest", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 99, BundleKey = "loraxbundle", Requirements = new Dictionary { ["SledgeCheat"] = (1, 0) } }, ["OrangeSpiritHelm"] = new ComplexRecipe { Item = "OrangeSpiritHelm", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 99, BundleKey = "loraxbundle", Requirements = new Dictionary { ["SledgeCheat"] = (1, 0) } }, ["PartyHatRed"] = new ComplexRecipe { Item = "PartyHatRed", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 2, BundleKey = "phatbundle", Requirements = new Dictionary { ["DeerHide"] = (1, 0), ["Raspberry"] = (5, 0) } }, ["PartyHatGreen"] = new ComplexRecipe { Item = "PartyHatGreen", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 2, BundleKey = "phatbundle", Requirements = new Dictionary { ["DeerHide"] = (1, 0), ["Guck"] = (5, 0) } }, ["PartyHatBlue"] = new ComplexRecipe { Item = "PartyHatBlue", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 2, BundleKey = "phatbundle", Requirements = new Dictionary { ["DeerHide"] = (1, 0), ["Blueberries"] = (5, 0) } }, ["PartyHatYellow"] = new ComplexRecipe { Item = "PartyHatYellow", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 2, BundleKey = "phatbundle", Requirements = new Dictionary { ["DeerHide"] = (1, 0), ["Dandelion"] = (5, 0) } }, ["PartyHatPurple"] = new ComplexRecipe { Item = "PartyHatPurple", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 2, BundleKey = "phatbundle", Requirements = new Dictionary { ["DeerHide"] = (1, 0), ["Raspberry"] = (2, 0), ["Blueberries"] = (2, 0) } } }; VRP_Misc = new Dictionary { ["CultivatorIron"] = new ComplexRecipe { Item = "CultivatorIron", Amount = 1, CraftingStation = "forge", StationLevel = 2, BundleKey = "bandage", Description = "A farm tool made of more durable iron", Requirements = new Dictionary { ["Iron"] = (10, 2), ["Guck"] = (1, 1) } }, ["Handcuffs"] = new ComplexRecipe { Item = "Handcuffs", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 1, BundleKey = "bandage", Requirements = new Dictionary { ["DeerHide"] = (1, 0), ["Gloam"] = (1, 0) } }, ["Bandage"] = new ComplexRecipe { Item = "Bandage", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 1, BundleKey = "bandage", Requirements = new Dictionary { ["LeatherScraps"] = (1, 0), ["Floam"] = (10, 0) } }, ["BandageShiny"] = new ComplexRecipe { Item = "BandageShiny", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 1, BundleKey = "bandage", Requirements = new Dictionary { ["DeerHide"] = (1, 0), ["Gloam"] = (1, 0) } }, ["Eyepatch"] = new ComplexRecipe { Item = "Eyepatch", Amount = 1, CraftingStation = "piece_workbench", StationLevel = 1, BundleKey = "bandage", Requirements = new Dictionary { ["DeerHide"] = (1, 0), ["Floam"] = (1, 0) } } }; } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [Nullable(0)] public static class BalanceData { [Nullable(new byte[] { 1, 1, 0 })] public static readonly Dictionary ItemWeights = new Dictionary { { "item_coins", (0f, 99999) } }; public static readonly Dictionary FoodValues; public static readonly Dictionary WeaponValues; public static readonly Dictionary ProjectileValues; public static readonly Dictionary ItemOverrides; public static readonly Dictionary WeaponOverrides; public static readonly HashSet ArmorSetsToRemove; static BalanceData() { Dictionary obj = new Dictionary { { "item_blueberries", new FoodStats(5f, 10f) }, { "item_raspberries", new FoodStats(5f, 10f) }, { "item_cloudberries", new FoodStats(5f, 10f) }, { "Floam", new FoodStats(10f, 15f, 10f, 300f) }, { "Gloam", new FoodStats(10f, 25f, 25f, 3600f) } }; float? food = 25f; float? stamina = 15f; float? regen = 1f; obj.Add("item_asksvin_meat_cooked", new FoodStats(food, stamina, null, null, regen)); float? food2 = 25f; float? stamina2 = 15f; regen = 1f; obj.Add("item_bonemawmeat_cooked", new FoodStats(food2, stamina2, null, null, regen)); float? food3 = 25f; float? stamina3 = 15f; regen = 1f; obj.Add("item_bug_meat_cooked", new FoodStats(food3, stamina3, null, null, regen)); float? food4 = 25f; float? stamina4 = 15f; regen = 1f; obj.Add("item_chicken_meat_cooked", new FoodStats(food4, stamina4, null, null, regen)); float? food5 = 25f; float? stamina5 = 15f; regen = 1f; obj.Add("item_deer_meat_cooked", new FoodStats(food5, stamina5, null, null, regen)); float? food6 = 25f; float? stamina6 = 15f; regen = 1f; obj.Add("item_egg_cooked", new FoodStats(food6, stamina6, null, null, regen)); float? food7 = 25f; float? stamina7 = 15f; regen = 1f; obj.Add("item_hare_meat_cooked", new FoodStats(food7, stamina7, null, null, regen)); float? food8 = 25f; float? stamina8 = 15f; regen = 1f; obj.Add("item_loxmeat_cooked", new FoodStats(food8, stamina8, null, null, regen)); float? food9 = 25f; float? stamina9 = 15f; regen = 1f; obj.Add("item_boar_meat_cooked", new FoodStats(food9, stamina9, null, null, regen)); float? food10 = 25f; float? stamina10 = 15f; regen = 1f; obj.Add("item_volture_meat_cooked", new FoodStats(food10, stamina10, null, null, regen)); float? food11 = 25f; float? stamina11 = 15f; regen = 1f; obj.Add("item_wolf_meat_cooked", new FoodStats(food11, stamina11, null, null, regen)); float? food12 = 25f; float? stamina12 = 15f; regen = 1f; obj.Add("item_necktailgrilled", new FoodStats(food12, stamina12, null, null, regen)); float? food13 = 25f; float? stamina13 = 15f; regen = 1f; obj.Add("item_serpentmeatcooked", new FoodStats(food13, stamina13, null, null, regen)); FoodValues = obj; WeaponValues = new Dictionary { { "item_sword", new WeaponStats { SecondaryAttackStamina = 40f, SecondaryDamageMultiplier = 2.2f } }, { "GREATSWORD", new WeaponStats { SecondaryDamageMultiplier = 2.2f } }, { "THSword", new WeaponStats { SecondaryDamageMultiplier = 2.2f } }, { "item_knife", new WeaponStats { BackstabBonus = 4f, LastChainMultiplier = 2f, SecondaryAttackStamina = 30f, SecondaryDamageMultiplier = 3f } }, { "item_atgeir", new WeaponStats { PrimaryAttackStamina = 8f, SecondaryAttackStamina = 30f, ForceMultiplier = 12f } }, { "BOW", new WeaponStats { PrimaryAttackStamina = 2f } }, { "item_spear_", new WeaponStats { AttackHeight = 1f, AttackRange = 2.2f, SecondaryAttackStamina = 50f, SecondaryConsumeItem = false, SecondaryDestroyProjectile = true } } }; ProjectileValues = new Dictionary { { "item_spear_", new ProjectileStats { RespawnItemOnHit = false } } }; ItemOverrides = new Dictionary(StringComparer.InvariantCultureIgnoreCase) { { "item_chest_rags", new ItemOverride { FrostResist = true } }, { "item_cape_ash", new ItemOverride { FrostResist = true } }, { "item_cape_asksvin", new ItemOverride { FrostResist = true } }, { "item_cape_deerhide", new ItemOverride { FrostResist = true } }, { "item_cape_feather", new ItemOverride { FrostResist = true } }, { "item_cape_linen", new ItemOverride { FrostResist = true } }, { "item_cape_trollhide", new ItemOverride { FrostResist = true } }, { "item_chest_tunic2", new ItemOverride { FrostResist = true } }, { "item_chest_tunic5", new ItemOverride { FrostResist = true } }, { "item_chest_tunic8", new ItemOverride { FrostResist = true } }, { "item_chest_root", new ItemOverride { RemoveSetBonus = true, RemoveResistances = true } }, { "item_legs_root", new ItemOverride { RemoveSetBonus = true, EitrRegenModifier = 0.1f } }, { "item_helmet_root", new ItemOverride { RemoveSetBonus = true, EitrRegenModifier = 0.1f } }, { "BanditHelm", new ItemOverride { Armor = 1f, MaxQuality = 1 } }, { "Valon", new ItemOverride { Armor = 1f, MaxQuality = 1 } }, { "item_helmet_padded", new ItemOverride { Armor = 24f } }, { "item_chest_pcuirass", new ItemOverride { Armor = 24f } }, { "item_legs_pgreaves", new ItemOverride { Armor = 24f } }, { "item_helmet_drake", new ItemOverride { Armor = 24f } }, { "item_chest_wolf", new ItemOverride { Armor = 24f } }, { "item_legs_wolf", new ItemOverride { Armor = 24f } }, { "item_helmet_berserker", new ItemOverride { Armor = 6f, RemoveSetBonus = true, MovementSpeed = 0f } }, { "item_chest_berserker", new ItemOverride { Armor = 6f, RemoveSetBonus = true, MovementSpeed = 0f } }, { "item_legs_berserker", new ItemOverride { Armor = 6f, RemoveSetBonus = true, MovementSpeed = 0f } }, { "item_helmet_berserker_undead", new ItemOverride { Armor = 18f, RemoveSetBonus = true, MovementSpeed = 0f } }, { "item_chest_berserker_undead", new ItemOverride { Armor = 18f, RemoveSetBonus = true, MovementSpeed = 0f } }, { "item_legs_berserker_undead", new ItemOverride { Armor = 18f, RemoveSetBonus = true, MovementSpeed = 0f } }, { "item_helmet_fenris", new ItemOverride { Armor = 18f, RemoveSetBonus = true, MovementSpeed = 0f } }, { "item_chest_fenris", new ItemOverride { Armor = 18f, RemoveSetBonus = true, MovementSpeed = 0f } }, { "item_legs_fenris", new ItemOverride { Armor = 18f, RemoveSetBonus = true, MovementSpeed = 0f } }, { "item_trollhelm", new ItemOverride { Armor = 9f, RemoveSetBonus = true } }, { "item_SvenHelm", new ItemOverride { RemoveSetBonus = true } }, { "bmr_polarwolf_cape", new ItemOverride { RemoveSetBonus = true } }, { "bmr_seeker_cape", new ItemOverride { RemoveSetBonus = true } }, { "bmr_sorcerers_cape", new ItemOverride { RemoveSetBonus = true } }, { "item_ss_serpentcape", new ItemOverride { FrostResist = true } }, { "item_ss_cape_lightwraith", new ItemOverride { FrostResist = true } }, { "item_ss_cape_boar", new ItemOverride { FrostResist = true } }, { "bmr_tattered_cape", new ItemOverride { FrostResist = true } }, { "bmr_crimson_cape", new ItemOverride { FrostResist = true } } }; WeaponOverrides = new Dictionary(StringComparer.InvariantCultureIgnoreCase) { { "item_axe_blackmetal", new WeaponOverride { Slash = 80f } }, { "item_sledge_iron", new WeaponOverride { Blunt = 70f } }, { "item_mace_needle", new WeaponOverride { Blunt = 65f, Pierce = 0f, Poison = 30f } }, { "item_sword_blackmetal", new WeaponOverride { Slash = 75f } }, { "item_sword_krom", new WeaponOverride { Slash = 95f } }, { "item_atgeir_blackmetal", new WeaponOverride { Pierce = 85f } }, { "item_fistweapon_bjorn", new WeaponOverride { Slash = 25f, Blunt = 15f } }, { "item_fistweapon_fenris", new WeaponOverride { Slash = 55f, Blunt = 25f, Pierce = 5f, PrimaryUseStamina = 12f } }, { "item_fistweapon_bjorn_undead", new WeaponOverride { Slash = 65f, Blunt = 35f, Pierce = 10f } }, { "item_atgeir_himminafl", new WeaponOverride { Pierce = 125f, Lightning = 40f } }, { "item_knife_blackmetal", new WeaponOverride { Slash = 25f, Pierce = 25f, Lightning = 12f } }, { "item_battleaxe_blackmetal", new WeaponOverride { Slash = 90f, Poison = 30f } }, { "item_bow_draugrfang", new WeaponOverride { Pierce = 52f } }, { "item_arrow_silver", new WeaponOverride { Pierce = 52f, Spirit = 26f } }, { "item_arrow_obsidian", new WeaponOverride { Pierce = 52f, Blunt = 26f } }, { "item_arrow_needle", new WeaponOverride { Pierce = 52f, Poison = 40f } }, { "item_arrow_carapace", new WeaponOverride { Pierce = 62f, Frost = 62f } }, { "item_arrow_charred", new WeaponOverride { Pierce = 62f, Fire = 62f, Lightning = 62f } }, { "item_axe_iron2", new WeaponOverride { Slash = 50f, BlockArmor = 21f, Chop = 50f } }, { "item_axe_silver2", new WeaponOverride { Slash = 70f, BlockArmor = 30f, Chop = 60f, Lightning = 0f, Frost = 20f } }, { "item_axe_mist", new WeaponOverride { Slash = 80f, BlockArmor = 30f, Chop = 80f, Lightning = 0f, Spirit = 20f } }, { "item_shield_blackmetal", new WeaponOverride { BlockArmor = 60f, BlockForce = 40f } }, { "vrp-shieldblackmetal", new WeaponOverride { BlockArmor = 60f, BlockForce = 40f } }, { "item_shield_blackmetal_tower", new WeaponOverride { BlockArmor = 85f, BlockForce = 125f } }, { "vrp-shieldblackmetaltower", new WeaponOverride { BlockArmor = 85f, BlockForce = 125f } } }; ArmorSetsToRemove = new HashSet(StringComparer.InvariantCultureIgnoreCase) { "Horseaker", "horseset_t1", "horseset_t2", "Lightweight", "Fenris", "King of the Necks", "Chieftain", "Trollfighter", "Knighthood", "Berserk", "Undead", "Whitefang's Blessing", "Enchanted Stone", "Shieldmaiden", "Sven's Aim", "Bjorn's Might", "Loxgol", "Barbarian", "Nordstrom", "Moonlight", "Gjall-hunter", "Frostbite", "Wraith", "Druidic", "Runic", "Jötunn Born", "Blademaster", "Ascended", "Demonic", "Pestilent", "Yagluth's Chosen", "Sainthood", "Unspoken Fear", "Dragon Blood", "Frenzied", "Deep North", "Dragon Queen's Blessing", "Gift of Thetis", "Pureheart", "Wings", "Ragnarok" }; } } public struct FoodStats { public float? Food; public float? Stamina; public float? Eitr; public float? BurnTime; public float? Regen; public FoodStats(float? food = null, float? stamina = null, float? eitr = null, float? burnTime = null, float? regen = null) { Food = food; Stamina = stamina; Eitr = eitr; BurnTime = burnTime; Regen = regen; } } public struct WeaponStats { public float? BackstabBonus; public float? LastChainMultiplier; public float? PrimaryAttackStamina; public float? SecondaryAttackStamina; public float? SecondaryDamageMultiplier; public float? ForceMultiplier; public float? AttackRange; public float? AttackHeight; public bool? SecondaryConsumeItem; public bool? SecondaryDestroyProjectile; } public struct ProjectileStats { public bool? RespawnItemOnHit; } public struct ItemOverride { public bool RemoveSetBonus; public bool RemoveResistances; public bool FrostResist; public float? EitrRegenModifier; public float? Armor; public float? ArmorPerLevel; public float? MovementSpeed; public int? MaxQuality; } public struct WeaponOverride { public float? Slash { get; set; } public float? SlashPerLevel { get; set; } public float? Chop { get; set; } public float? ChopPerLevel { get; set; } public float? Pierce { get; set; } public float? PiercePerLevel { get; set; } public float? Blunt { get; set; } public float? BluntPerLevel { get; set; } public float? BlockArmor { get; set; } public float? BlockForce { get; set; } public float? ParryBonus { get; set; } public float? Backstab { get; set; } public float? MovementSpeedPenalty { get; set; } public float? PrimaryUseStamina { get; set; } public float? SecondaryUseStamina { get; set; } public float? Lightning { get; set; } public float? Frost { get; set; } public float? Poison { get; set; } public float? Fire { get; set; } public float? Spirit { get; set; } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [Nullable(0)] public static class StringExtensions { public static bool ContainsIgnoreCase(this string source, string toCheck) { if (source == null) { return false; } return source.IndexOf(toCheck, StringComparison.InvariantCultureIgnoreCase) >= 0; } public static bool EqualsIgnoreCase(this string source, string toCheck) { return string.Equals(source, toCheck, StringComparison.InvariantCultureIgnoreCase); } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [Nullable(0)] internal class BalancePatches { public static void ApplyBalanceTweaks() { ItemAdjustments(); } private static void Run(string phase, ItemDrop id, Action action) { try { action(); } catch (Exception ex) { string text = id?.m_itemData?.m_shared?.m_name ?? ((id != null) ? ((Object)id).name : null) ?? ""; ZLog.LogError((object)("[" + phase + "] failed on '" + text + "'")); if (VRPMod.DebugMode()) { ZLog.LogError((object)ex.ToString()); } } } private static void ItemAdjustments() { ZLog.Log((object)$"Balancing the scales... for {(ObjectDB.instance?.m_items?.Count).GetValueOrDefault()} items"); try { if ((Object)(object)ObjectDB.instance == (Object)null || ObjectDB.instance.m_items == null) { ZLog.LogError((object)"ObjectDB or m_items is null; aborting ItemAdjustments."); return; } for (int i = 0; i < ObjectDB.instance.m_items.Count; i++) { GameObject val = ObjectDB.instance.m_items[i]; ItemDrop id = (Object.op_Implicit((Object)(object)val) ? val.GetComponent() : null); Run("AdjustWeights", id, delegate { AdjustWeights(id); }); Run("AdjustFood", id, delegate { AdjustFood(id); }); Run("AdjustTrinkets", id, delegate { AdjustTrinkets(id); }); Run("AdjustWeapons", id, delegate { AdjustWeapons(id); }); Run("AdjustArmor", id, delegate { AdjustArmor(id); }); Run("AdjustDurability", id, delegate { AdjustDurability(id); }); Run("RemoveSetBonuses", id, delegate { RemoveSetBonuses(id); }); } } catch (Exception ex) { ZLog.LogError((object)"error adjusting items (top-level)"); if (VRPMod.DebugMode()) { ZLog.LogError((object)ex.ToString()); } } finally { PrefabManager.OnVanillaPrefabsAvailable -= ItemAdjustments; } } private static void AdjustWeights(ItemDrop id) { if ((Object)(object)id == (Object)null || id.m_itemData?.m_shared == null) { return; } string text = id.m_itemData.m_shared.m_name.Replace("$", ""); foreach (KeyValuePair itemWeight in BalanceData.ItemWeights) { if (text.Contains(itemWeight.Key)) { id.m_itemData.m_shared.m_weight = itemWeight.Value.Item1; if (itemWeight.Value.Item2.HasValue) { id.m_itemData.m_shared.m_maxStackSize = itemWeight.Value.Item2.Value; } if (VRPMod.DebugMode()) { ZLog.Log((object)$"{itemWeight.Key} adjusted {itemWeight.Value.Item1}"); } } } } private static void AdjustFood(ItemDrop id) { //IL_0116: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)id == (Object)null || id.m_itemData?.m_shared == null) { return; } string name = id.m_itemData.m_shared.m_name; foreach (KeyValuePair foodValue in BalanceData.FoodValues) { if (name.Contains(foodValue.Key)) { FoodStats value = foodValue.Value; SharedData shared = id.m_itemData.m_shared; if (value.Food.HasValue) { shared.m_food = value.Food.Value; } if (value.Stamina.HasValue) { shared.m_foodStamina = value.Stamina.Value; } if (value.Eitr.HasValue) { shared.m_foodEitr = value.Eitr.Value; } if (value.BurnTime.HasValue) { shared.m_foodBurnTime = value.BurnTime.Value; } if (value.Regen.HasValue) { shared.m_foodRegen = value.Regen.Value; } shared.m_itemType = (ItemType)2; if (VRPMod.DebugMode()) { ZLog.Log((object)$"Adjusted food: {name} -> food:{value.Food}, stam:{value.Stamina}, eitr:{value.Eitr}, burn:{value.BurnTime}, regen:{value.Regen}"); } } } } private static void AdjustWeapons(ItemDrop id) { //IL_0310: Unknown result type (might be due to invalid IL or missing references) //IL_0315: Unknown result type (might be due to invalid IL or missing references) //IL_0319: Unknown result type (might be due to invalid IL or missing references) //IL_031e: Unknown result type (might be due to invalid IL or missing references) //IL_0537: Unknown result type (might be due to invalid IL or missing references) //IL_0539: Unknown result type (might be due to invalid IL or missing references) //IL_0540: Unknown result type (might be due to invalid IL or missing references) //IL_0542: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)id == (Object)null || id.m_itemData?.m_shared == null) { return; } string name = id.m_itemData.m_shared.m_name; string source = name.Replace("$", ""); foreach (KeyValuePair weaponValue in BalanceData.WeaponValues) { if (name.Contains(weaponValue.Key)) { SharedData shared = id.m_itemData.m_shared; WeaponStats value = weaponValue.Value; if (value.BackstabBonus.HasValue) { shared.m_backstabBonus = value.BackstabBonus.Value; } if (value.LastChainMultiplier.HasValue) { shared.m_attack.m_lastChainDamageMultiplier = value.LastChainMultiplier.Value; } if (value.PrimaryAttackStamina.HasValue) { shared.m_attack.m_attackStamina = value.PrimaryAttackStamina.Value; } if (value.SecondaryAttackStamina.HasValue) { shared.m_secondaryAttack.m_attackStamina = value.SecondaryAttackStamina.Value; } if (value.SecondaryDamageMultiplier.HasValue) { shared.m_secondaryAttack.m_damageMultiplier = value.SecondaryDamageMultiplier.Value; } if (value.ForceMultiplier.HasValue) { shared.m_secondaryAttack.m_forceMultiplier = value.ForceMultiplier.Value; } if (value.AttackRange.HasValue) { shared.m_attack.m_attackRange = value.AttackRange.Value; } if (value.AttackHeight.HasValue) { shared.m_attack.m_attackHeight = value.AttackHeight.Value; } if (value.SecondaryConsumeItem.HasValue) { shared.m_secondaryAttack.m_consumeItem = value.SecondaryConsumeItem.Value; } if (value.SecondaryDestroyProjectile.HasValue) { shared.m_secondaryAttack.m_destroyPreviousProjectile = value.SecondaryDestroyProjectile.Value; } if (VRPMod.DebugMode()) { ZLog.Log((object)("Weapon adjusted: " + name)); } } } foreach (KeyValuePair projectileValue in BalanceData.ProjectileValues) { if (name.Contains(projectileValue.Key)) { GameObject attackProjectile = id.m_itemData.m_shared.m_secondaryAttack.m_attackProjectile; Projectile val = ((attackProjectile != null) ? attackProjectile.GetComponent() : null); if ((Object)(object)val != (Object)null && projectileValue.Value.RespawnItemOnHit.HasValue) { val.m_respawnItemOnHit = projectileValue.Value.RespawnItemOnHit.Value; } } } foreach (KeyValuePair weaponOverride in BalanceData.WeaponOverrides) { if (!source.EqualsIgnoreCase(weaponOverride.Key)) { continue; } try { SharedData shared2 = id.m_itemData.m_shared; WeaponOverride value2 = weaponOverride.Value; DamageTypes damages = shared2.m_damages; DamageTypes damagesPerLevel = shared2.m_damagesPerLevel; if (value2.Slash.HasValue) { damages.m_slash = value2.Slash.Value; } if (value2.Pierce.HasValue) { damages.m_pierce = value2.Pierce.Value; } if (value2.Blunt.HasValue) { damages.m_blunt = value2.Blunt.Value; } if (value2.Chop.HasValue) { damages.m_chop = value2.Chop.Value; } if (value2.Fire.HasValue) { damages.m_fire = value2.Fire.Value; } if (value2.Frost.HasValue) { damages.m_frost = value2.Frost.Value; } if (value2.Lightning.HasValue) { damages.m_lightning = value2.Lightning.Value; } if (value2.Poison.HasValue) { damages.m_poison = value2.Poison.Value; } if (value2.Spirit.HasValue) { damages.m_spirit = value2.Spirit.Value; } if (value2.SlashPerLevel.HasValue) { damagesPerLevel.m_slash = value2.SlashPerLevel.Value; } if (value2.PiercePerLevel.HasValue) { damagesPerLevel.m_pierce = value2.PiercePerLevel.Value; } if (value2.BluntPerLevel.HasValue) { damagesPerLevel.m_blunt = value2.BluntPerLevel.Value; } if (value2.ChopPerLevel.HasValue) { damagesPerLevel.m_chop = value2.ChopPerLevel.Value; } shared2.m_damages = damages; shared2.m_damagesPerLevel = damagesPerLevel; if (value2.BlockArmor.HasValue) { shared2.m_blockPower = value2.BlockArmor.Value; } if (value2.BlockForce.HasValue) { shared2.m_deflectionForce = value2.BlockForce.Value; } if (value2.ParryBonus.HasValue) { shared2.m_timedBlockBonus = value2.ParryBonus.Value; } if (value2.Backstab.HasValue) { shared2.m_backstabBonus = value2.Backstab.Value; } if (value2.MovementSpeedPenalty.HasValue) { float value3 = value2.MovementSpeedPenalty.Value; shared2.m_movementModifier = ((value3 <= 0f) ? value3 : (0f - Mathf.Abs(value3))); } if (source.ContainsIgnoreCase("item_axe_silver2") || source.ContainsIgnoreCase("item_axe_iron2")) { shared2.m_attackStatusEffect = null; shared2.m_toolTier = 2; } if (value2.PrimaryUseStamina.HasValue && shared2.m_attack != null) { shared2.m_attack.m_attackStamina = value2.PrimaryUseStamina.Value; } if (value2.SecondaryUseStamina.HasValue && shared2.m_secondaryAttack != null) { shared2.m_secondaryAttack.m_attackStamina = value2.SecondaryUseStamina.Value; } if (VRPMod.DebugMode()) { ZLog.Log((object)("Weapon override applied to " + name)); } break; } catch (Exception ex) { if (VRPMod.DebugMode()) { ZLog.LogError((object)("Error trying to apply weapon override to " + name + ": " + ex.Message)); } break; } } } private static void AdjustTrinkets(ItemDrop id) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Invalid comparison between Unknown and I4 if (!((Object)(object)id == (Object)null) && id.m_itemData?.m_shared != null) { SharedData shared = id.m_itemData.m_shared; if ((int)shared.m_itemType == 24) { shared.m_fullAdrenalineSE = null; shared.m_maxAdrenaline = 0f; } } } private static void AdjustArmor(ItemDrop id) { //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_01d2: Unknown result type (might be due to invalid IL or missing references) //IL_01da: Unknown result type (might be due to invalid IL or missing references) //IL_01df: Unknown result type (might be due to invalid IL or missing references) //IL_019e: Unknown result type (might be due to invalid IL or missing references) //IL_01a3: Unknown result type (might be due to invalid IL or missing references) //IL_01a8: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)id == (Object)null || id.m_itemData?.m_shared == null) { return; } string name = id.m_itemData.m_shared.m_name; string text = name.Replace("$", ""); if (text.ContainsIgnoreCase("item_ss_cape_boar")) { id.m_itemData.m_shared.m_attackStaminaModifier = 0f; } ItemOverride? itemOverride = null; if (BalanceData.ItemOverrides.TryGetValue(text, out var value)) { itemOverride = value; } else { foreach (KeyValuePair item in BalanceData.ItemOverrides.OrderByDescending([<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] (KeyValuePair e) => e.Key.Length)) { if (text.ContainsIgnoreCase(item.Key)) { itemOverride = item.Value; break; } } } if (!itemOverride.HasValue) { return; } ItemOverride value2 = itemOverride.Value; try { SharedData shared = id.m_itemData.m_shared; if (value2.RemoveSetBonus) { shared.m_setName = ""; shared.m_setSize = 0; shared.m_setStatusEffect = null; shared.m_equipStatusEffect = null; } if (value2.RemoveResistances) { shared.m_damageModifiers.Clear(); } if (value2.FrostResist) { int num = shared.m_damageModifiers.FindIndex((DamageModPair m) => (int)m.m_type == 64); if (num != -1) { DamageModPair value3 = shared.m_damageModifiers[num]; value3.m_modifier = (DamageModifier)7; shared.m_damageModifiers[num] = value3; } else { shared.m_damageModifiers.Add(new DamageModPair { m_type = (DamageType)64, m_modifier = (DamageModifier)7 }); } } if (value2.MovementSpeed.HasValue) { shared.m_movementModifier = value2.MovementSpeed.Value; } if (value2.EitrRegenModifier.HasValue) { shared.m_eitrRegenModifier = value2.EitrRegenModifier.Value; } if (value2.Armor.HasValue) { shared.m_armor = value2.Armor.Value; } if (value2.ArmorPerLevel.HasValue) { shared.m_armorPerLevel = value2.ArmorPerLevel.Value; } if (value2.MaxQuality.HasValue) { shared.m_maxQuality = value2.MaxQuality.Value; } if (VRPMod.DebugMode()) { ZLog.Log((object)("Item override applied to " + name)); } } catch { if (VRPMod.DebugMode()) { ZLog.LogError((object)("Error trying to apply override to " + name)); } } } private static void AdjustDurability(ItemDrop id) { //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Invalid comparison between Unknown and I4 //IL_00c0: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)id == (Object)null || id.m_itemData?.m_shared == null) { return; } SharedData shared = id.m_itemData.m_shared; ItemType itemType = shared.m_itemType; if (ItemTypeHash.DurabilityPatchTypes.Contains(itemType) && shared.m_canBeReparied) { if (ItemTypeHash.WeaponTypes.Contains(itemType)) { shared.m_maxDurability = 200f; } if (shared.m_maxDurability > 1500f) { shared.m_maxDurability = 1500f; } shared.m_canBeReparied = false; float num = (((int)itemType == 19) ? 10f : 5f); shared.m_maxDurability *= num; if (VRPMod.DebugMode()) { ZLog.Log((object)$"Adjusted durability: {shared.m_name} to {shared.m_maxDurability} (type {itemType})"); } } if (ItemTypeHash.ArmorTypes.Contains(itemType)) { shared.m_equipDuration = 3f; } } private static void RemoveSetBonuses(ItemDrop id) { if ((Object)(object)id == (Object)null || id.m_itemData?.m_shared == null) { return; } string setName = id.m_itemData.m_shared.m_setName; if (string.IsNullOrEmpty(setName)) { return; } foreach (string item in BalanceData.ArmorSetsToRemove) { if (setName.ContainsIgnoreCase(item)) { id.m_itemData.m_shared.m_setName = ""; id.m_itemData.m_shared.m_setSize = 0; id.m_itemData.m_shared.m_setStatusEffect = null; if (VRPMod.DebugMode()) { ZLog.Log((object)("Set bonus removed from item: " + id.m_itemData.m_shared.m_name + " (matched: " + item + ")")); } break; } } } } public class BuildPiecePatch { public static void CustomPieces() { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Expected O, but got Unknown //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Expected O, but got Unknown //IL_00ef: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0107: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Expected O, but got Unknown //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_011c: Expected O, but got Unknown //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_013c: Expected O, but got Unknown //IL_0166: Unknown result type (might be due to invalid IL or missing references) //IL_016b: Unknown result type (might be due to invalid IL or missing references) //IL_0176: Unknown result type (might be due to invalid IL or missing references) //IL_017e: Unknown result type (might be due to invalid IL or missing references) //IL_0186: Expected O, but got Unknown //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Expected O, but got Unknown //IL_01b6: Unknown result type (might be due to invalid IL or missing references) //IL_01bc: Expected O, but got Unknown //IL_01e6: Unknown result type (might be due to invalid IL or missing references) //IL_01eb: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: Unknown result type (might be due to invalid IL or missing references) //IL_01fd: Unknown result type (might be due to invalid IL or missing references) //IL_0205: Expected O, but got Unknown //IL_020b: Unknown result type (might be due to invalid IL or missing references) //IL_0211: Expected O, but got Unknown //IL_022a: Unknown result type (might be due to invalid IL or missing references) //IL_0230: Expected O, but got Unknown //IL_025a: Unknown result type (might be due to invalid IL or missing references) //IL_025f: Unknown result type (might be due to invalid IL or missing references) //IL_026a: Unknown result type (might be due to invalid IL or missing references) //IL_0272: Unknown result type (might be due to invalid IL or missing references) //IL_027a: Expected O, but got Unknown //IL_027c: Unknown result type (might be due to invalid IL or missing references) //IL_0281: Unknown result type (might be due to invalid IL or missing references) //IL_028c: Unknown result type (might be due to invalid IL or missing references) //IL_0294: Unknown result type (might be due to invalid IL or missing references) //IL_029c: Expected O, but got Unknown //IL_02a2: Unknown result type (might be due to invalid IL or missing references) //IL_02a8: Expected O, but got Unknown //IL_02c1: Unknown result type (might be due to invalid IL or missing references) //IL_02c7: Expected O, but got Unknown //IL_02f1: Unknown result type (might be due to invalid IL or missing references) //IL_02f6: Unknown result type (might be due to invalid IL or missing references) //IL_0301: Unknown result type (might be due to invalid IL or missing references) //IL_0309: Unknown result type (might be due to invalid IL or missing references) //IL_0311: Expected O, but got Unknown //IL_0313: Unknown result type (might be due to invalid IL or missing references) //IL_0318: Unknown result type (might be due to invalid IL or missing references) //IL_0323: Unknown result type (might be due to invalid IL or missing references) //IL_032b: Unknown result type (might be due to invalid IL or missing references) //IL_0333: Expected O, but got Unknown //IL_0335: Unknown result type (might be due to invalid IL or missing references) //IL_033a: Unknown result type (might be due to invalid IL or missing references) //IL_0345: Unknown result type (might be due to invalid IL or missing references) //IL_034d: Unknown result type (might be due to invalid IL or missing references) //IL_0355: Expected O, but got Unknown //IL_0357: Unknown result type (might be due to invalid IL or missing references) //IL_035c: Unknown result type (might be due to invalid IL or missing references) //IL_0367: Unknown result type (might be due to invalid IL or missing references) //IL_036f: Unknown result type (might be due to invalid IL or missing references) //IL_0377: Expected O, but got Unknown //IL_037d: Unknown result type (might be due to invalid IL or missing references) //IL_0383: Expected O, but got Unknown //IL_039c: Unknown result type (might be due to invalid IL or missing references) //IL_03a2: Expected O, but got Unknown //IL_03cc: Unknown result type (might be due to invalid IL or missing references) //IL_03d1: Unknown result type (might be due to invalid IL or missing references) //IL_03dc: Unknown result type (might be due to invalid IL or missing references) //IL_03e3: Unknown result type (might be due to invalid IL or missing references) //IL_03eb: Expected O, but got Unknown //IL_03ed: Unknown result type (might be due to invalid IL or missing references) //IL_03f2: Unknown result type (might be due to invalid IL or missing references) //IL_03fd: Unknown result type (might be due to invalid IL or missing references) //IL_0405: Unknown result type (might be due to invalid IL or missing references) //IL_040d: Expected O, but got Unknown //IL_040f: Unknown result type (might be due to invalid IL or missing references) //IL_0414: Unknown result type (might be due to invalid IL or missing references) //IL_041f: Unknown result type (might be due to invalid IL or missing references) //IL_0426: Unknown result type (might be due to invalid IL or missing references) //IL_042e: Expected O, but got Unknown //IL_0434: Unknown result type (might be due to invalid IL or missing references) //IL_043a: Expected O, but got Unknown //IL_0453: Unknown result type (might be due to invalid IL or missing references) //IL_0459: Expected O, but got Unknown //IL_0483: Unknown result type (might be due to invalid IL or missing references) //IL_0488: Unknown result type (might be due to invalid IL or missing references) //IL_0493: Unknown result type (might be due to invalid IL or missing references) //IL_049a: Unknown result type (might be due to invalid IL or missing references) //IL_04a2: Expected O, but got Unknown //IL_04a4: Unknown result type (might be due to invalid IL or missing references) //IL_04a9: Unknown result type (might be due to invalid IL or missing references) //IL_04b4: Unknown result type (might be due to invalid IL or missing references) //IL_04bb: Unknown result type (might be due to invalid IL or missing references) //IL_04c3: Expected O, but got Unknown //IL_04c9: Unknown result type (might be due to invalid IL or missing references) //IL_04cf: Expected O, but got Unknown //IL_04e8: Unknown result type (might be due to invalid IL or missing references) //IL_04ee: Expected O, but got Unknown //IL_0518: Unknown result type (might be due to invalid IL or missing references) //IL_051d: Unknown result type (might be due to invalid IL or missing references) //IL_0528: Unknown result type (might be due to invalid IL or missing references) //IL_052f: Unknown result type (might be due to invalid IL or missing references) //IL_0537: Expected O, but got Unknown //IL_0539: Unknown result type (might be due to invalid IL or missing references) //IL_053e: Unknown result type (might be due to invalid IL or missing references) //IL_0549: Unknown result type (might be due to invalid IL or missing references) //IL_0550: Unknown result type (might be due to invalid IL or missing references) //IL_0558: Expected O, but got Unknown //IL_055e: Unknown result type (might be due to invalid IL or missing references) //IL_0564: Expected O, but got Unknown //IL_057d: Unknown result type (might be due to invalid IL or missing references) //IL_0583: Expected O, but got Unknown //IL_05c3: Unknown result type (might be due to invalid IL or missing references) //IL_05c8: Unknown result type (might be due to invalid IL or missing references) //IL_05d3: Unknown result type (might be due to invalid IL or missing references) //IL_05da: Unknown result type (might be due to invalid IL or missing references) //IL_05e2: Expected O, but got Unknown //IL_05e4: Unknown result type (might be due to invalid IL or missing references) //IL_05e9: Unknown result type (might be due to invalid IL or missing references) //IL_05f4: Unknown result type (might be due to invalid IL or missing references) //IL_05fb: Unknown result type (might be due to invalid IL or missing references) //IL_0603: Expected O, but got Unknown //IL_0609: Unknown result type (might be due to invalid IL or missing references) //IL_060f: Expected O, but got Unknown //IL_0628: Unknown result type (might be due to invalid IL or missing references) //IL_062e: Expected O, but got Unknown //IL_066e: Unknown result type (might be due to invalid IL or missing references) //IL_0673: Unknown result type (might be due to invalid IL or missing references) //IL_067e: Unknown result type (might be due to invalid IL or missing references) //IL_0685: Unknown result type (might be due to invalid IL or missing references) //IL_068d: Expected O, but got Unknown //IL_068f: Unknown result type (might be due to invalid IL or missing references) //IL_0694: Unknown result type (might be due to invalid IL or missing references) //IL_069f: Unknown result type (might be due to invalid IL or missing references) //IL_06a6: Unknown result type (might be due to invalid IL or missing references) //IL_06ae: Expected O, but got Unknown //IL_06b0: Unknown result type (might be due to invalid IL or missing references) //IL_06b5: Unknown result type (might be due to invalid IL or missing references) //IL_06c0: Unknown result type (might be due to invalid IL or missing references) //IL_06c7: Unknown result type (might be due to invalid IL or missing references) //IL_06cf: Expected O, but got Unknown //IL_06d5: Unknown result type (might be due to invalid IL or missing references) //IL_06db: Expected O, but got Unknown //IL_06f4: Unknown result type (might be due to invalid IL or missing references) //IL_06fa: Expected O, but got Unknown //IL_073a: Unknown result type (might be due to invalid IL or missing references) //IL_073f: Unknown result type (might be due to invalid IL or missing references) //IL_074a: Unknown result type (might be due to invalid IL or missing references) //IL_0751: Unknown result type (might be due to invalid IL or missing references) //IL_0759: Expected O, but got Unknown //IL_075b: Unknown result type (might be due to invalid IL or missing references) //IL_0760: Unknown result type (might be due to invalid IL or missing references) //IL_076b: Unknown result type (might be due to invalid IL or missing references) //IL_0772: Unknown result type (might be due to invalid IL or missing references) //IL_077a: Expected O, but got Unknown //IL_077c: Unknown result type (might be due to invalid IL or missing references) //IL_0781: Unknown result type (might be due to invalid IL or missing references) //IL_078c: Unknown result type (might be due to invalid IL or missing references) //IL_0793: Unknown result type (might be due to invalid IL or missing references) //IL_079b: Expected O, but got Unknown //IL_07a1: Unknown result type (might be due to invalid IL or missing references) //IL_07a7: Expected O, but got Unknown //IL_07c0: Unknown result type (might be due to invalid IL or missing references) //IL_07c6: Expected O, but got Unknown //IL_0806: Unknown result type (might be due to invalid IL or missing references) //IL_080b: Unknown result type (might be due to invalid IL or missing references) //IL_0816: Unknown result type (might be due to invalid IL or missing references) //IL_081d: Unknown result type (might be due to invalid IL or missing references) //IL_0825: Expected O, but got Unknown //IL_0827: Unknown result type (might be due to invalid IL or missing references) //IL_082c: Unknown result type (might be due to invalid IL or missing references) //IL_0837: Unknown result type (might be due to invalid IL or missing references) //IL_083e: Unknown result type (might be due to invalid IL or missing references) //IL_0846: Expected O, but got Unknown //IL_084c: Unknown result type (might be due to invalid IL or missing references) //IL_0852: Expected O, but got Unknown //IL_086b: Unknown result type (might be due to invalid IL or missing references) //IL_0871: Expected O, but got Unknown //IL_08b1: Unknown result type (might be due to invalid IL or missing references) //IL_08b6: Unknown result type (might be due to invalid IL or missing references) //IL_08c1: Unknown result type (might be due to invalid IL or missing references) //IL_08c8: Unknown result type (might be due to invalid IL or missing references) //IL_08d0: Expected O, but got Unknown //IL_08d2: Unknown result type (might be due to invalid IL or missing references) //IL_08d7: Unknown result type (might be due to invalid IL or missing references) //IL_08e2: Unknown result type (might be due to invalid IL or missing references) //IL_08e9: Unknown result type (might be due to invalid IL or missing references) //IL_08f1: Expected O, but got Unknown //IL_08f7: Unknown result type (might be due to invalid IL or missing references) //IL_08fd: Expected O, but got Unknown //IL_0916: Unknown result type (might be due to invalid IL or missing references) //IL_091c: Expected O, but got Unknown //IL_095c: Unknown result type (might be due to invalid IL or missing references) //IL_0961: Unknown result type (might be due to invalid IL or missing references) //IL_096c: Unknown result type (might be due to invalid IL or missing references) //IL_0974: Unknown result type (might be due to invalid IL or missing references) //IL_097c: Expected O, but got Unknown //IL_097e: Unknown result type (might be due to invalid IL or missing references) //IL_0983: Unknown result type (might be due to invalid IL or missing references) //IL_098e: Unknown result type (might be due to invalid IL or missing references) //IL_0995: Unknown result type (might be due to invalid IL or missing references) //IL_099d: Expected O, but got Unknown //IL_09a3: Unknown result type (might be due to invalid IL or missing references) //IL_09a9: Expected O, but got Unknown //IL_09c2: Unknown result type (might be due to invalid IL or missing references) //IL_09c8: Expected O, but got Unknown //IL_09f2: Unknown result type (might be due to invalid IL or missing references) //IL_09f7: Unknown result type (might be due to invalid IL or missing references) //IL_0a02: Unknown result type (might be due to invalid IL or missing references) //IL_0a0a: Unknown result type (might be due to invalid IL or missing references) //IL_0a12: Expected O, but got Unknown //IL_0a14: Unknown result type (might be due to invalid IL or missing references) //IL_0a19: Unknown result type (might be due to invalid IL or missing references) //IL_0a24: Unknown result type (might be due to invalid IL or missing references) //IL_0a2c: Unknown result type (might be due to invalid IL or missing references) //IL_0a34: Expected O, but got Unknown //IL_0a36: Unknown result type (might be due to invalid IL or missing references) //IL_0a3b: Unknown result type (might be due to invalid IL or missing references) //IL_0a46: Unknown result type (might be due to invalid IL or missing references) //IL_0a4d: Unknown result type (might be due to invalid IL or missing references) //IL_0a55: Expected O, but got Unknown //IL_0a5b: Unknown result type (might be due to invalid IL or missing references) //IL_0a61: Expected O, but got Unknown //IL_0a97: Unknown result type (might be due to invalid IL or missing references) //IL_0a9d: Expected O, but got Unknown //IL_0abc: Unknown result type (might be due to invalid IL or missing references) //IL_0ac1: Unknown result type (might be due to invalid IL or missing references) //IL_0acc: Unknown result type (might be due to invalid IL or missing references) //IL_0ad3: Unknown result type (might be due to invalid IL or missing references) //IL_0adb: Expected O, but got Unknown //IL_0add: Unknown result type (might be due to invalid IL or missing references) //IL_0ae2: Unknown result type (might be due to invalid IL or missing references) //IL_0aed: Unknown result type (might be due to invalid IL or missing references) //IL_0af5: Expected O, but got Unknown //IL_0af7: Unknown result type (might be due to invalid IL or missing references) //IL_0afc: Unknown result type (might be due to invalid IL or missing references) //IL_0b07: Unknown result type (might be due to invalid IL or missing references) //IL_0b0f: Expected O, but got Unknown //IL_0b15: Unknown result type (might be due to invalid IL or missing references) //IL_0b1f: Expected O, but got Unknown //IL_0b3d: Unknown result type (might be due to invalid IL or missing references) //IL_0b43: Expected O, but got Unknown //IL_0b7f: Unknown result type (might be due to invalid IL or missing references) //IL_0b84: Unknown result type (might be due to invalid IL or missing references) //IL_0b8f: Unknown result type (might be due to invalid IL or missing references) //IL_0b98: Expected O, but got Unknown //IL_0b9a: Unknown result type (might be due to invalid IL or missing references) //IL_0b9f: Unknown result type (might be due to invalid IL or missing references) //IL_0baa: Unknown result type (might be due to invalid IL or missing references) //IL_0bb2: Expected O, but got Unknown //IL_0bb8: Unknown result type (might be due to invalid IL or missing references) //IL_0bc2: Expected O, but got Unknown ZLog.Log((object)"VRP PIECES"); try { PieceConfig val; try { val = new PieceConfig(); val.Name = "WardFarmer"; val.Description = "Protect your crops!"; val.PieceTable = "_HammerPieceTable"; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "Floam", Amount = 10, Recover = true } }; CustomPiece val2 = new CustomPiece("vrp_ward_farmer", "guard_stone", val); PieceManager.Instance.AddPiece(val2); ZLog.Log((object)"Farmer Ward added."); } catch (Exception ex) { ZLog.LogError((object)ex.Message); ZLog.Log((object)ex.StackTrace); } using (BundleCache.Scope scope = new BundleCache.Scope("Arielle-ValheimRoleplay/Assets/bandage")) { AssetBundle bundle = scope.Bundle; GameObject obj = bundle.LoadAsset("ward_floam"); val = new PieceConfig(); val.Name = "WardFloam"; val.Description = "Protect your area with floam!"; val.PieceTable = "_HammerPieceTable"; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "Floam", Amount = 10, Recover = true } }; CustomPiece val3 = new CustomPiece(obj, true, val); PieceManager.Instance.AddPiece(val3); GameObject obj2 = bundle.LoadAsset("ward_gloam"); val = new PieceConfig(); val.Name = "WardGloam"; val.Description = "Protect your area with shiny gloam! longer ranger than floam!"; val.PieceTable = "_HammerPieceTable"; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "Gloam", Amount = 50, Recover = true } }; CustomPiece val4 = new CustomPiece(obj2, true, val); PieceManager.Instance.AddPiece(val4); } val = new PieceConfig(); val.Name = "WardAdmin"; val.Description = "Protect your area admin"; val.PieceTable = "_HammerPieceTable"; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "SwordCheat", Amount = 1, Recover = false } }; CustomPiece val5 = new CustomPiece("vrp_ward_admin", "guard_stone", val); if (val5 != null) { PieceManager.Instance.AddPiece(val5); } val = new PieceConfig(); val.Name = "WardSmall"; val.Description = "Protect your area small"; val.PieceTable = "_HammerPieceTable"; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "Floam", Amount = 10, Recover = true }, new RequirementConfig { Item = "Stone", Amount = 10, Recover = true } }; val5 = new CustomPiece("vrp_ward_seed", "guard_stone", val); if (val5 != null) { PieceManager.Instance.AddPiece(val5); } val = new PieceConfig(); val.Name = "StoneCutter"; val.Description = "Cut stones for building"; val.PieceTable = "_HammerPieceTable"; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[4] { new RequirementConfig { Item = "FineWood", Amount = 20, Recover = true }, new RequirementConfig { Item = "RoundLog", Amount = 20, Recover = true }, new RequirementConfig { Item = "Stone", Amount = 20, Recover = true }, new RequirementConfig { Item = "Flint", Amount = 20, Recover = true } }; val5 = new CustomPiece("vrp_stonecutter", "piece_stonecutter", val); if (val5 != null) { PieceManager.Instance.AddPiece(val5); } val = new PieceConfig(); val.Name = "Armor Stand"; val.Description = "Armor stand"; val.PieceTable = "_HammerPieceTable"; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[3] { new RequirementConfig { Item = "Wood", Amount = 8, Recover = true }, new RequirementConfig { Item = "Resin", Amount = 10, Recover = true }, new RequirementConfig { Item = "BoneFragments", Amount = 5, Recover = true } }; val5 = new CustomPiece("vrp_armorstand", "ArmorStand", val); if (val5 != null) { PieceManager.Instance.AddPiece(val5); } val = new PieceConfig(); val.Name = "Item Stand"; val.Description = "Item stand"; val.PieceTable = "_HammerPieceTable"; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "Wood", Amount = 1, Recover = true }, new RequirementConfig { Item = "Resin", Amount = 1, Recover = true } }; val5 = new CustomPiece("vrp_itemstand", "itemstand", val); if (val5 != null) { PieceManager.Instance.AddPiece(val5); } val = new PieceConfig(); val.Name = "Item Stand"; val.Description = "Item stand"; val.PieceTable = "_HammerPieceTable"; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "Wood", Amount = 1, Recover = true }, new RequirementConfig { Item = "Resin", Amount = 1, Recover = true } }; val5 = new CustomPiece("vrp_itemstandh", "itemstandh", val); if (val5 != null) { PieceManager.Instance.AddPiece(val5); } val = new PieceConfig(); val.Name = "Metal Wall"; val.Description = "Metal Wall"; val.PieceTable = "_HammerPieceTable"; val.CraftingStation = CraftingStations.Forge; val.Category = PieceCategories.HeavyBuild; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "Copper", Amount = 2, Recover = true }, new RequirementConfig { Item = "Iron", Amount = 1, Recover = true } }; val5 = new CustomPiece("vrp_dvergr_wall", "piece_dvergr_metal_wall_2x2", val); if (val5 != null) { PieceManager.Instance.AddPiece(val5); } val = new PieceConfig(); val.Name = "Wall Lantern"; val.Description = "Wall Lantern"; val.PieceTable = "_HammerPieceTable"; val.CraftingStation = CraftingStations.Forge; val.Category = PieceCategories.Furniture; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[3] { new RequirementConfig { Item = "Copper", Amount = 2, Recover = true }, new RequirementConfig { Item = "Chain", Amount = 1, Recover = true }, new RequirementConfig { Item = "Lantern", Amount = 1, Recover = true } }; val5 = new CustomPiece("vrp_dvergr_lantern", "piece_dvergr_lantern", val); if (val5 != null) { PieceManager.Instance.AddPiece(val5); } val = new PieceConfig(); val.Name = "Lantern Pole"; val.Description = "Lantern on a pole"; val.PieceTable = "_HammerPieceTable"; val.CraftingStation = CraftingStations.Forge; val.Category = PieceCategories.Furniture; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[3] { new RequirementConfig { Item = "Copper", Amount = 3, Recover = true }, new RequirementConfig { Item = "Chain", Amount = 1, Recover = true }, new RequirementConfig { Item = "Lantern", Amount = 1, Recover = true } }; val5 = new CustomPiece("vrp_dvergr_lantern_pole", "piece_dvergr_lantern_pole", val); if (val5 != null) { PieceManager.Instance.AddPiece(val5); } val = new PieceConfig(); val.Name = "Spiral Staircase Left"; val.Description = "Spiral Staircase Left"; val.PieceTable = "_HammerPieceTable"; val.Category = PieceCategories.Furniture; val.CraftingStation = CraftingStations.Workbench; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "FineWood", Amount = 5, Recover = true }, new RequirementConfig { Item = "Copper", Amount = 2, Recover = true } }; val5 = new CustomPiece("vrp_spiralstair", "piece_dvergr_spiralstair", val); if (val5 != null) { PieceManager.Instance.AddPiece(val5); } val = new PieceConfig(); val.Name = "Spiral Staircase Right"; val.Description = "Spiral Staircase Right"; val.PieceTable = "_HammerPieceTable"; val.Category = PieceCategories.Furniture; val.CraftingStation = CraftingStations.Workbench; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "FineWood", Amount = 5, Recover = true }, new RequirementConfig { Item = "Copper", Amount = 2, Recover = true } }; val5 = new CustomPiece("vrp_spiralstair_right", "piece_dvergr_spiralstair_right", val); if (val5 != null) { PieceManager.Instance.AddPiece(val5); } val = new PieceConfig(); val.Name = "Large Metal Gate"; val.Description = "A massive metal gate"; val.PieceTable = "_HammerPieceTable"; val.Category = PieceCategories.HeavyBuild; val.CraftingStation = CraftingStations.Forge; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "Iron", Amount = 10, Recover = true }, new RequirementConfig { Item = "Copper", Amount = 2, Recover = true } }; val5 = new CustomPiece("vrp_bigmetal_gate", "flametal_gate", val); if (val5 != null) { PieceManager.Instance.AddPiece(val5); } val = new PieceConfig(); val.Name = "Prep Table"; val.Description = "Used to prepare ingredients and cut fish"; val.PieceTable = "_HammerPieceTable"; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[3] { new RequirementConfig { Item = "FineWood", Amount = 20, Recover = true }, new RequirementConfig { Item = "LeatherScraps", Amount = 15, Recover = true }, new RequirementConfig { Item = "KnifeButcher", Amount = 1, Recover = true } }; val5 = new CustomPiece("vrp_preptable", "piece_preptable", val); if (val5 != null) { PieceManager.Instance.AddPiece(val5); } using (BundleCache.Scope scope2 = new BundleCache.Scope("bonefirebundle")) { GameObject val6 = scope2.Bundle.LoadAsset("Bonefire"); PieceManager instance = PieceManager.Instance; val = new PieceConfig(); val.PieceTable = "_HammerPieceTable"; val.Category = PieceCategories.Misc; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[3] { new RequirementConfig { Item = "WitheredBone", Amount = 4, Recover = true }, new RequirementConfig { Item = "LeatherScraps", Amount = 4 }, new RequirementConfig { Item = "Guck", Amount = 1 } }; instance.AddPiece(new CustomPiece(val6, false, val)); } PieceManager instance2 = PieceManager.Instance; val = new PieceConfig(); val.Name = "Bad Raft"; val.PieceTable = "Hammer"; val.Category = "Misc"; val.Enabled = true; val.Description = "an ocean faring ship made of wood and floam... somehow? when destroyed it poofs"; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "Wood", Amount = 10 }, new RequirementConfig { Item = "Floam", Amount = 2 } }; instance2.AddPiece(new CustomPiece("BadRaft", "Raft", val)); } catch (Exception ex2) { ZLog.LogError((object)"error adding vrp items custom pieces"); if (VRPMod.DebugMode()) { ZLog.LogError((object)ex2.Message); } } finally { PrefabManager.OnVanillaPrefabsAvailable -= CustomPieces; } } public static void MissingPieces() { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Expected O, but got Unknown //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Expected O, but got Unknown //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Expected O, but got Unknown //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00ee: Expected O, but got Unknown //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Expected O, but got Unknown //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Expected O, but got Unknown //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_0169: Unknown result type (might be due to invalid IL or missing references) //IL_0171: Expected O, but got Unknown //IL_0189: Unknown result type (might be due to invalid IL or missing references) //IL_0193: Expected O, but got Unknown //IL_0194: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Expected O, but got Unknown //IL_01d5: Unknown result type (might be due to invalid IL or missing references) //IL_01da: Unknown result type (might be due to invalid IL or missing references) //IL_01e5: Unknown result type (might be due to invalid IL or missing references) //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_01f4: Expected O, but got Unknown //IL_020c: Unknown result type (might be due to invalid IL or missing references) //IL_0216: Expected O, but got Unknown //IL_0217: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Expected O, but got Unknown //IL_0258: Unknown result type (might be due to invalid IL or missing references) //IL_025d: Unknown result type (might be due to invalid IL or missing references) //IL_0268: Unknown result type (might be due to invalid IL or missing references) //IL_026f: Unknown result type (might be due to invalid IL or missing references) //IL_0277: Expected O, but got Unknown //IL_0291: Unknown result type (might be due to invalid IL or missing references) //IL_029b: Expected O, but got Unknown //IL_029c: Unknown result type (might be due to invalid IL or missing references) //IL_02a3: Expected O, but got Unknown //IL_02dd: Unknown result type (might be due to invalid IL or missing references) //IL_02e2: Unknown result type (might be due to invalid IL or missing references) //IL_02ed: Unknown result type (might be due to invalid IL or missing references) //IL_02f4: Unknown result type (might be due to invalid IL or missing references) //IL_02fc: Expected O, but got Unknown //IL_0316: Unknown result type (might be due to invalid IL or missing references) //IL_0320: Expected O, but got Unknown //IL_0321: Unknown result type (might be due to invalid IL or missing references) //IL_0328: Expected O, but got Unknown //IL_0362: Unknown result type (might be due to invalid IL or missing references) //IL_0367: Unknown result type (might be due to invalid IL or missing references) //IL_0372: Unknown result type (might be due to invalid IL or missing references) //IL_037a: Unknown result type (might be due to invalid IL or missing references) //IL_0382: Expected O, but got Unknown //IL_039c: Unknown result type (might be due to invalid IL or missing references) //IL_03a6: Expected O, but got Unknown //IL_03a7: Unknown result type (might be due to invalid IL or missing references) //IL_03ae: Expected O, but got Unknown //IL_03e8: Unknown result type (might be due to invalid IL or missing references) //IL_03ed: Unknown result type (might be due to invalid IL or missing references) //IL_03f8: Unknown result type (might be due to invalid IL or missing references) //IL_0400: Unknown result type (might be due to invalid IL or missing references) //IL_0408: Expected O, but got Unknown //IL_0422: Unknown result type (might be due to invalid IL or missing references) //IL_042c: Expected O, but got Unknown //IL_042d: Unknown result type (might be due to invalid IL or missing references) //IL_0434: Expected O, but got Unknown //IL_046e: Unknown result type (might be due to invalid IL or missing references) //IL_0473: Unknown result type (might be due to invalid IL or missing references) //IL_047e: Unknown result type (might be due to invalid IL or missing references) //IL_0486: Unknown result type (might be due to invalid IL or missing references) //IL_048e: Expected O, but got Unknown //IL_04a8: Unknown result type (might be due to invalid IL or missing references) //IL_04b2: Expected O, but got Unknown //IL_04b3: Unknown result type (might be due to invalid IL or missing references) //IL_04ba: Expected O, but got Unknown //IL_04f4: Unknown result type (might be due to invalid IL or missing references) //IL_04f9: Unknown result type (might be due to invalid IL or missing references) //IL_0504: Unknown result type (might be due to invalid IL or missing references) //IL_050c: Unknown result type (might be due to invalid IL or missing references) //IL_0514: Expected O, but got Unknown //IL_052e: Unknown result type (might be due to invalid IL or missing references) //IL_0538: Expected O, but got Unknown //IL_0539: Unknown result type (might be due to invalid IL or missing references) //IL_0540: Expected O, but got Unknown //IL_057a: Unknown result type (might be due to invalid IL or missing references) //IL_057f: Unknown result type (might be due to invalid IL or missing references) //IL_058a: Unknown result type (might be due to invalid IL or missing references) //IL_0592: Unknown result type (might be due to invalid IL or missing references) //IL_059a: Expected O, but got Unknown //IL_05b4: Unknown result type (might be due to invalid IL or missing references) //IL_05be: Expected O, but got Unknown ZLog.Log((object)"MISSING PIECES"); try { PieceConfig val = new PieceConfig(); val.Name = "$piece_stone_floor"; val.Description = "4x4 stone floor"; val.PieceTable = "Hammer"; val.Category = PieceCategories.HeavyBuild; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "Stone", Amount = 10, Recover = true } }; PieceConfig val2 = val; PieceManager.Instance.AddPiece(new CustomPiece("vrp_stone_floor", "stone_floor", val2)); val = new PieceConfig(); val.Name = "$piece_wood_ledge"; val.Description = "Small wooden shelf"; val.PieceTable = "Hammer"; val.Category = PieceCategories.Furniture; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "Wood", Amount = 2, Recover = true } }; PieceConfig val3 = val; PieceManager.Instance.AddPiece(new CustomPiece("vrp_shelf", "wood_ledge", val3)); val = new PieceConfig(); val.Name = "$piece_BlackMarble_2x2_Enforced"; val.Description = "A sturdy piece of black marble, 2x2 in size."; val.PieceTable = "Hammer"; val.Category = PieceCategories.HeavyBuild; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "BlackMarble", Amount = 8, Recover = true } }; PieceConfig val4 = val; PieceManager.Instance.AddPiece(new CustomPiece("vrp_blackmarble_2x2_enforced", "blackmarble_2x2_enforced", val4)); val = new PieceConfig(); val.Name = "$piece_BlackMarble_Tile_Wall_2x4"; val.Description = "A large black marble wall tile, 2x4 in size."; val.PieceTable = "Hammer"; val.Category = PieceCategories.HeavyBuild; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "BlackMarble", Amount = 8, Recover = true } }; PieceConfig val5 = val; PieceManager.Instance.AddPiece(new CustomPiece("vrp_blackmarble_tile_wall_2x4", "blackmarble_tile_wall_2x4", val5)); val = new PieceConfig(); val.Name = "$piece_BlackMarble_Tile_Wall_2x2"; val.Description = "A medium-sized black marble wall tile, 2x2 in size."; val.PieceTable = "Hammer"; val.Category = PieceCategories.HeavyBuild; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "BlackMarble", Amount = 4, Recover = true } }; PieceConfig val6 = val; PieceManager.Instance.AddPiece(new CustomPiece("vrp_blackmarble_tile_wall_2x2", "blackmarble_tile_wall_2x2", val6)); val = new PieceConfig(); val.Name = "$piece_BlackMarble_Tile_Wall_1x1"; val.Description = "A small black marble wall tile, 1x1 in size."; val.PieceTable = "Hammer"; val.Category = PieceCategories.HeavyBuild; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "BlackMarble", Amount = 2, Recover = true } }; PieceConfig val7 = val; PieceManager.Instance.AddPiece(new CustomPiece("vrp_blackmarble_tile_wall_1x1", "blackmarble_tile_wall_1x1", val7)); val = new PieceConfig(); val.Name = "$piece_BlackMarble_Head_Big01"; val.Description = "A decorative black marble statue, large size."; val.PieceTable = "Hammer"; val.Category = PieceCategories.HeavyBuild; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "BlackMarble", Amount = 10, Recover = true } }; PieceConfig val8 = val; PieceManager.Instance.AddPiece(new CustomPiece("vrp_blackmarble_head_big01", "blackmarble_head_big01", val8)); val = new PieceConfig(); val.Name = "$piece_BlackMarble_Head_Big02"; val.Description = "A decorative black marble statue, large size."; val.PieceTable = "Hammer"; val.Category = PieceCategories.HeavyBuild; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "BlackMarble", Amount = 10, Recover = true } }; PieceConfig val9 = val; PieceManager.Instance.AddPiece(new CustomPiece("vrp_blackmarble_head_big02", "blackmarble_head_big02", val9)); val = new PieceConfig(); val.Name = "$piece_BlackMarble_Head01"; val.Description = "A decorative black marble head statue."; val.PieceTable = "Hammer"; val.Category = PieceCategories.HeavyBuild; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "BlackMarble", Amount = 10, Recover = true } }; PieceConfig val10 = val; PieceManager.Instance.AddPiece(new CustomPiece("vrp_blackmarble_head01", "blackmarble_head01", val10)); val = new PieceConfig(); val.Name = "$piece_BlackMarble_Head02"; val.Description = "A decorative black marble head statue."; val.PieceTable = "Hammer"; val.Category = PieceCategories.HeavyBuild; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "BlackMarble", Amount = 10, Recover = true } }; PieceConfig val11 = val; PieceManager.Instance.AddPiece(new CustomPiece("vrp_blackmarble_head02", "blackmarble_head02", val11)); val = new PieceConfig(); val.Name = "$piece_MetalBar_1x2"; val.Description = "A structural metal bar, 1x2 in size."; val.PieceTable = "Hammer"; val.Category = PieceCategories.HeavyBuild; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "BlackMarble", Amount = 10, Recover = true } }; PieceConfig val12 = val; PieceManager.Instance.AddPiece(new CustomPiece("vrp_metalbar_1x2", "metalbar_1x2", val12)); } catch (Exception ex) { ZLog.LogError((object)ex); } finally { PrefabManager.OnPrefabsRegistered -= MissingPieces; } } } [HarmonyPatch(typeof(Player), "StartEmote")] public static class ChampionEmotePatch { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static void Postfix(Player __instance, string emote) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) if (emote == null || !emote.Equals("challenge", StringComparison.OrdinalIgnoreCase)) { return; } Vector3 position = ((Component)__instance).transform.position; foreach (Player allPlayer in Player.GetAllPlayers()) { if (!((Object)(object)allPlayer == (Object)null) && !((Object)(object)allPlayer == (Object)(object)__instance) && Vector3.Distance(position, ((Component)allPlayer).transform.position) <= 10f && ((Character)allPlayer).GetSEMan().HaveStatusEffect(StringExtensionMethods.GetStableHashCode("Champion"))) { allPlayer.StartEmote("flex", true); } } } } public class CoinCostManager { [HarmonyPatch(typeof(Player), "GetAvailableRecipes")] private static class Player_GetAvailableRecipes_Patch { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref List available) { AddCoinCost(ref available); } } [HarmonyPatch(typeof(Requirement), "GetAmount")] private class Requirement_GetAmount_Patch { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(Requirement __instance, int qualityLevel, ref int __result) { if (qualityLevel > 1 && (Object)(object)__instance.m_resItem != (Object)null && __instance.m_resItem.m_itemData.m_shared.m_name == "$item_coins") { if (qualityLevel == 2) { __result = VRPMod._coinCostLevel2.Value; } else if (qualityLevel == 3) { __result = VRPMod._coinCostLevel3.Value; } else if (qualityLevel >= 4) { __result = VRPMod._coinCostLevel4.Value; } } } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void AddCoinCost(ref List recipes) { //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Invalid comparison between Unknown and I4 //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Invalid comparison between Unknown and I4 //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Invalid comparison between Unknown and I4 //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Invalid comparison between Unknown and I4 //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Invalid comparison between Unknown and I4 //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Unknown result type (might be due to invalid IL or missing references) //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Expected O, but got Unknown //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Invalid comparison between Unknown and I4 //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Invalid comparison between Unknown and I4 //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Invalid comparison between Unknown and I4 GameObject itemPrefab = ObjectDB.instance.GetItemPrefab("Coins"); if ((Object)(object)itemPrefab == (Object)null) { return; } ItemDrop coins = itemPrefab.GetComponent(); foreach (Recipe recipe in recipes) { if (!((Object)(object)recipe.m_item == (Object)null)) { ItemType itemType = recipe.m_item.m_itemData.m_shared.m_itemType; if (((int)itemType == 6 || (int)itemType == 7 || (int)itemType == 11 || (int)itemType == 17 || (int)itemType == 5 || (int)itemType == 4 || (int)itemType == 3 || (int)itemType == 14) && !recipe.m_resources.Any((Requirement r) => (Object)(object)r.m_resItem == (Object)(object)coins)) { Requirement item = new Requirement { m_resItem = coins, m_amount = 0, m_amountPerLevel = 0, m_recover = true }; List list = recipe.m_resources.ToList(); list.Add(item); recipe.m_resources = list.ToArray(); } } } } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [Nullable(0)] public static class DanceBombPatch { public static StatusEffect DanceFeverSE; public static void RegisterDanceBomb() { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_00c4: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Expected O, but got Unknown //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Expected O, but got Unknown //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_0120: Expected O, but got Unknown //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Expected O, but got Unknown //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0147: Expected O, but got Unknown ZLog.Log((object)"VRP DANCE BOMB"); try { CustomItem val = new CustomItem("DanceBomb", "BombSmoke"); ItemManager.Instance.AddItem(val); GameObject itemPrefab = val.ItemPrefab; RecolorSmoke(itemPrefab); ItemDrop component = itemPrefab.GetComponent(); SharedData shared = component.m_itemData.m_shared; component.m_itemData.m_shared.m_name = "Gleefire Flask"; component.m_itemData.m_shared.m_description = "Bottled laughter and distilled merriment. All who breathe its fumes feel the music stirring in their bones."; shared.m_damages = default(DamageTypes); shared.m_blockPower = 0f; shared.m_blockPowerPerLevel = 0f; shared.m_deflectionForce = 0f; shared.m_timedBlockBonus = 0f; shared.m_attackForce = 0f; shared.m_backstabBonus = 0f; ZLog.Log((object)"[VRP] DanceBomb registered."); RecipeConfig val2 = new RecipeConfig(); val2.Name = "Recipe_DanceBomb"; val2.Item = "DanceBomb"; val2.Amount = 3; val2.CraftingStation = "piece_workbench"; val2.MinStationLevel = 1; val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[3] { new RequirementConfig("Resin", 5, 0, true), new RequirementConfig("Honey", 2, 0, true), new RequirementConfig("Thistle", 1, 0, true) }; RecipeConfig val3 = val2; ItemManager.Instance.AddRecipe(new CustomRecipe(val3)); } catch (Exception ex) { ZLog.LogError((object)"error creating dance bomb"); if (VRPMod.DebugMode()) { ZLog.LogError((object)ex.ToString()); } } finally { PrefabManager.OnPrefabsRegistered -= RegisterDanceBomb; } } private static void RecolorSmoke(GameObject prefab) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) ParticleSystem[] componentsInChildren = prefab.GetComponentsInChildren(true); for (int i = 0; i < componentsInChildren.Length; i++) { MainModule main = componentsInChildren[i].main; ((MainModule)(ref main)).startColor = MinMaxGradient.op_Implicit(new Color(1f, 0.3f, 0.7f, 0.9f)); } } } [HarmonyPatch(typeof(Aoe), "OnHit")] public static class DanceBomb_AoeHit_Patch { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(Aoe __instance, Collider collider) { if ((Object)(object)__instance == (Object)null || !((Object)__instance).name.Contains("DanceBomb") || !Object.op_Implicit((Object)(object)__instance.m_nview) || !__instance.m_nview.IsOwner()) { return; } Character componentInParent = ((Component)collider).GetComponentInParent(); Player val = (Player)(object)((componentInParent is Player) ? componentInParent : null); if (val != null) { int stableHashCode = StringExtensionMethods.GetStableHashCode("DanceFever"); if (!((Character)val).m_seman.HaveStatusEffect(stableHashCode)) { ((Character)val).m_seman.AddStatusEffect(stableHashCode, false, 0, 0f); } } } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [Nullable(0)] public class DeathPatch { [HarmonyPriority(200)] [HarmonyPatch(typeof(Player), "ConsumeItem")] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] public static class MedConsume { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(Inventory inventory, ItemData item, ref bool __result, ref Player __instance) { if (!__result || (Object)(object)__instance == (Object)null || item?.m_shared == null || (Object)(object)((Character)__instance).m_nview == (Object)null || !((Character)__instance).m_nview.IsValid() || !((Character)__instance).IsOwner()) { return; } if ((IsItem(item, "Bandage") || IsItem(item, "Crude Bandage")) && ((Character)__instance).m_seman.HaveStatusEffect(StringExtensionMethods.GetStableHashCode("Wounded"))) { ((Character)__instance).m_seman.AddStatusEffect(_bandaged.StatusEffect, false, 0, 0f); } if ((IsItem(item, "BandageShiny") || IsItem(item, "Quality Bandage")) && ((Character)__instance).m_seman.HaveStatusEffect(StringExtensionMethods.GetStableHashCode("Wounded"))) { ((Character)__instance).m_seman.AddStatusEffect(_goodbandaged.StatusEffect, false, 0, 0f); } if (IsItem(item, "MedKit") || IsItem(item, "Medical Kit")) { int num = 0; num += (((Character)__instance).m_seman.RemoveStatusEffect(StringExtensionMethods.GetStableHashCode("Wounded"), false) ? 1 : 0); num += (((Character)__instance).m_seman.RemoveStatusEffect(StringExtensionMethods.GetStableHashCode("Dazed"), false) ? 1 : 0); num += (((Character)__instance).m_seman.RemoveStatusEffect(StringExtensionMethods.GetStableHashCode("Winded"), false) ? 1 : 0); num += (((Character)__instance).m_seman.RemoveStatusEffect(StringExtensionMethods.GetStableHashCode("PANIC"), false) ? 1 : 0); num += (((Character)__instance).m_seman.RemoveStatusEffect(StringExtensionMethods.GetStableHashCode("Bandaged"), false) ? 1 : 0); num += (((Character)__instance).m_seman.RemoveStatusEffect(StringExtensionMethods.GetStableHashCode("WellBandaged"), false) ? 1 : 0); ((Character)__instance).m_seman.AddStatusEffect(StringExtensionMethods.GetStableHashCode("Mended"), false, 0, 0f); ClearStreak(__instance); if (VRPMod.DebugMode()) { ZLog.Log((object)$"[VRP:Item] MedKit → removed {num} effect(s)."); } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] static bool IsItem(ItemData it, string prefabOrDisplay) { if (!Object.op_Implicit((Object)(object)it.m_dropPrefab) || !(((Object)it.m_dropPrefab).name == prefabOrDisplay)) { return string.Equals(it.m_shared?.m_name, prefabOrDisplay, StringComparison.Ordinal); } return true; } } } [HarmonyPatch(typeof(Player), "OnDeath")] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] private static class ReworkDeath { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool Prefix(ref Player __instance) { //IL_0083: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Invalid comparison between Unknown and I4 //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Invalid comparison between Unknown and I4 //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_013b: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00ea: Unknown result type (might be due to invalid IL or missing references) //IL_01fa: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Unknown result type (might be due to invalid IL or missing references) //IL_0201: Unknown result type (might be due to invalid IL or missing references) //IL_0254: Expected I4, but got Unknown //IL_046f: Unknown result type (might be due to invalid IL or missing references) long playerID = __instance.GetPlayerID(); int num = 1; bool flag = false; if (((Character)__instance).m_seman.HaveStatusEffect(StringExtensionMethods.GetStableHashCode("PVPLoss"))) { flag = true; } if (((Character)__instance).m_seman.HaveStatusEffect(StringExtensionMethods.GetStableHashCode("Winded"))) { num = 2; } if (((Character)__instance).m_seman.HaveStatusEffect(StringExtensionMethods.GetStableHashCode("Dazed"))) { num = 3; } if (((Character)__instance).m_seman.HaveStatusEffect(StringExtensionMethods.GetStableHashCode("Wounded"))) { num = GetStreak(__instance) + 1; } deathpoint = ((Component)__instance).transform.position; bool flag2 = (int)((Character)__instance).m_lastHit.m_hitType == 2 || (int)((Character)__instance).m_lastHit.m_hitType == 14; if (VRPMod.DebugMode()) { ZLog.Log((object)$"[VRP:Death] Player {playerID} died. streak={num}, pos={deathpoint}, lastHit={((Character)__instance).m_lastHit.m_hitType}"); } string playerName = __instance.GetPlayerName(); string hitTypeAsString = GetHitTypeAsString(((Character)__instance).m_lastHit.m_hitType); string text = $"{playerName} | died | {num} | {hitTypeAsString} | {deathpoint}"; ZLog.Log((object)text); ClientPatches.SendModerationLog(playerName, "", "", $"Died ({num})", $"{num} death", text, hitTypeAsString); if (num == 1 || num == 2) { if (VRPMod.DebugMode()) { ZLog.Log((object)$"[VRP:Death] Branch=InPlaceRespawn (#{num})"); } ((Character)__instance).m_nview.GetZDO().Set("dead", true); ((Character)__instance).m_nview.InvokeRPC(ZNetView.Everybody, "OnDeath", Array.Empty()); Game.instance.IncrementPlayerStat((PlayerStatType)0, 1f); HitType hitType = ((Character)__instance).m_lastHit.m_hitType; switch ((int)hitType) { case 0: Game.instance.IncrementPlayerStat((PlayerStatType)55, 1f); break; case 1: Game.instance.IncrementPlayerStat((PlayerStatType)56, 1f); break; case 2: Game.instance.IncrementPlayerStat((PlayerStatType)57, 1f); break; case 3: Game.instance.IncrementPlayerStat((PlayerStatType)58, 1f); break; case 4: Game.instance.IncrementPlayerStat((PlayerStatType)59, 1f); break; case 5: Game.instance.IncrementPlayerStat((PlayerStatType)60, 1f); break; case 6: Game.instance.IncrementPlayerStat((PlayerStatType)61, 1f); break; case 7: Game.instance.IncrementPlayerStat((PlayerStatType)62, 1f); break; case 8: Game.instance.IncrementPlayerStat((PlayerStatType)64, 1f); break; case 9: Game.instance.IncrementPlayerStat((PlayerStatType)63, 1f); break; case 10: Game.instance.IncrementPlayerStat((PlayerStatType)65, 1f); break; case 11: Game.instance.IncrementPlayerStat((PlayerStatType)66, 1f); break; case 12: Game.instance.IncrementPlayerStat((PlayerStatType)67, 1f); break; case 13: Game.instance.IncrementPlayerStat((PlayerStatType)68, 1f); break; case 14: Game.instance.IncrementPlayerStat((PlayerStatType)69, 1f); break; case 15: Game.instance.IncrementPlayerStat((PlayerStatType)70, 1f); break; case 16: Game.instance.IncrementPlayerStat((PlayerStatType)71, 1f); break; case 17: Game.instance.IncrementPlayerStat((PlayerStatType)72, 1f); break; case 18: Game.instance.IncrementPlayerStat((PlayerStatType)73, 1f); break; default: ZLog.LogWarning((object)("Not implemented death type " + ((object)(HitType)(ref ((Character)__instance).m_lastHit.m_hitType)).ToString())); break; } __instance.CreateDeathEffects(); if (VRPMod.DebugMode()) { ZLog.Log((object)"[VRP:Death] Skipping tombstone; keeping all inventory."); } float pct = ((num != 1) ? (flag ? 0.2f : 0.05f) : (flag ? 0f : 0.03f)); DamageEquippedArmorByPercent(__instance, pct); __instance.m_timeSinceDeath = 0f; Game.instance.GetPlayerProfile().SetLogoutPoint(deathpoint); Game.instance.RequestRespawn(2f, false); List list = new List((num != 1) ? new string[2] { "Dazed", "PANIC" } : new string[2] { "Winded", "PANIC" }); if (flag2) { list.Add("PVPLoss"); } if (VRPMod.DebugMode()) { ZLog.Log((object)("[VRP:Death] Queuing effects: " + string.Join(", ", list))); } QueueEffects(__instance, list.ToArray()); SetStreak(__instance, num); if (VRPMod.DebugMode()) { ZLog.Log((object)$"[VRP:Death] In-place respawn scheduled; new streak={num}"); } return false; } if (VRPMod.DebugMode()) { ZLog.Log((object)"[VRP:Death] Branch=VanillaRespawn (3rd+) + Wounded on spawn"); } QueueEffects(__instance, "Wounded"); float pct2 = (flag2 ? 0.5f : 0.05f); DamageEquippedArmorByPercent(__instance, pct2); SetStreak(__instance, num); if (VRPMod.DebugMode()) { ZLog.Log((object)$"[VRP:Death] Passing through to vanilla OnDeath; streak now {num}"); } return true; } } private static CustomStatusEffect _winded; private static CustomStatusEffect _dazed; private static CustomStatusEffect _wounded; private static CustomStatusEffect _panic; private static CustomStatusEffect _bandaged; private static CustomStatusEffect _goodbandaged; private static CustomStatusEffect _pvploss; private static CustomStatusEffect _recenthealed; private const string Z_DeathStreak = "vrp_death_streak"; private const string Z_PendingSE = "vrp_pending_se"; private static readonly Dictionary DeathStreak = new Dictionary(); private static bool PVP_ONLY = false; private static readonly Dictionary> PendingSE = new Dictionary>(); private static Vector3 deathpoint = Vector3.zero; private static Vector3 lumbyspawn = new Vector3(0f, 35f, -4f); public static void AddDeathStatuses() { //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Expected O, but got Unknown //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: Expected O, but got Unknown //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_0140: Expected O, but got Unknown //IL_01cf: Unknown result type (might be due to invalid IL or missing references) //IL_01d9: Expected O, but got Unknown //IL_024f: Unknown result type (might be due to invalid IL or missing references) //IL_0258: Unknown result type (might be due to invalid IL or missing references) //IL_0260: Unknown result type (might be due to invalid IL or missing references) //IL_0265: Unknown result type (might be due to invalid IL or missing references) //IL_0273: Unknown result type (might be due to invalid IL or missing references) //IL_027c: Unknown result type (might be due to invalid IL or missing references) //IL_0284: Unknown result type (might be due to invalid IL or missing references) //IL_0289: Unknown result type (might be due to invalid IL or missing references) //IL_0297: Unknown result type (might be due to invalid IL or missing references) //IL_02a0: Unknown result type (might be due to invalid IL or missing references) //IL_02a8: Unknown result type (might be due to invalid IL or missing references) //IL_02ad: Unknown result type (might be due to invalid IL or missing references) //IL_02bb: Unknown result type (might be due to invalid IL or missing references) //IL_02c4: Unknown result type (might be due to invalid IL or missing references) //IL_02cd: Unknown result type (might be due to invalid IL or missing references) //IL_02d2: Unknown result type (might be due to invalid IL or missing references) //IL_02e0: Unknown result type (might be due to invalid IL or missing references) //IL_02e9: Unknown result type (might be due to invalid IL or missing references) //IL_02f5: Unknown result type (might be due to invalid IL or missing references) //IL_02fa: Unknown result type (might be due to invalid IL or missing references) //IL_0301: Unknown result type (might be due to invalid IL or missing references) //IL_030b: Expected O, but got Unknown //IL_0397: Unknown result type (might be due to invalid IL or missing references) //IL_03a1: Expected O, but got Unknown //IL_0405: Unknown result type (might be due to invalid IL or missing references) //IL_040f: Expected O, but got Unknown //IL_0473: Unknown result type (might be due to invalid IL or missing references) //IL_047d: Expected O, but got Unknown ZLog.Log((object)"VRP invoking death..."); StatusEffect statusEffect = ObjectDB.instance.GetStatusEffect(StringExtensionMethods.GetStableHashCode("SoftDeath")); if (!Object.op_Implicit((Object)(object)statusEffect)) { ZLog.LogError((object)"Soft Death not found."); return; } SE_Stats obj = ScriptableObject.CreateInstance(); ((StatusEffect)obj).m_icon = statusEffect.m_icon; ((Object)obj).name = "Winded"; ((StatusEffect)obj).m_name = "Winded"; ((StatusEffect)obj).m_ttl = 600f; ((StatusEffect)obj).m_repeatInterval = 0f; _winded = new CustomStatusEffect((StatusEffect)(object)obj, false); ItemManager.Instance.AddStatusEffect(_winded); SE_Stats obj2 = ScriptableObject.CreateInstance(); ((StatusEffect)obj2).m_icon = statusEffect.m_icon; ((Object)obj2).name = "Dazed"; ((StatusEffect)obj2).m_name = "Dazed"; ((StatusEffect)obj2).m_ttl = 600f; ((StatusEffect)obj2).m_repeatInterval = 0f; _dazed = new CustomStatusEffect((StatusEffect)(object)obj2, false); ItemManager.Instance.AddStatusEffect(_dazed); SE_Stats obj3 = ScriptableObject.CreateInstance(); ((StatusEffect)obj3).m_icon = statusEffect.m_icon; ((Object)obj3).name = "Wounded"; ((StatusEffect)obj3).m_name = "Wounded"; ((StatusEffect)obj3).m_ttl = 0f; ((StatusEffect)obj3).m_repeatInterval = 0f; obj3.m_speedModifier = -0.8f; obj3.m_damageModifier = -0.8f; _wounded = new CustomStatusEffect((StatusEffect)(object)obj3, false); ItemManager.Instance.AddStatusEffect(_wounded); StatusEffect statusEffect2 = ObjectDB.instance.GetStatusEffect(StringExtensionMethods.GetStableHashCode("WindRun")); SE_Stats obj4 = ScriptableObject.CreateInstance(); ((StatusEffect)obj4).m_icon = statusEffect2.m_icon; ((Object)obj4).name = "PVPLoss"; ((StatusEffect)obj4).m_name = "PVPLoss"; ((StatusEffect)obj4).m_ttl = 300f; obj4.m_tickInterval = 5f; obj4.m_speedModifier = 0f; obj4.m_damageModifier = -1f; ((StatusEffect)obj4).m_repeatMessage = "You lost the fight and better sit down."; ((StatusEffect)obj4).m_repeatInterval = 10f; _pvploss = new CustomStatusEffect((StatusEffect)(object)obj4, false); ItemManager.Instance.AddStatusEffect(_pvploss); SE_Stats obj5 = ScriptableObject.CreateInstance(); ((StatusEffect)obj5).m_icon = statusEffect.m_icon; ((Object)obj5).name = "PANIC"; ((StatusEffect)obj5).m_name = "PANIC"; ((StatusEffect)obj5).m_ttl = 30f; ((StatusEffect)obj5).m_repeatInterval = 0f; obj5.m_tickInterval = 1f; obj5.m_healthPerTick = 5f; obj5.m_addMaxCarryWeight = 300f; obj5.m_mods.Add(new DamageModPair { m_modifier = (DamageModifier)5, m_type = (DamageType)1 }); obj5.m_mods.Add(new DamageModPair { m_modifier = (DamageModifier)5, m_type = (DamageType)4 }); obj5.m_mods.Add(new DamageModPair { m_modifier = (DamageModifier)5, m_type = (DamageType)2 }); obj5.m_mods.Add(new DamageModPair { m_modifier = (DamageModifier)5, m_type = (DamageType)32 }); obj5.m_mods.Add(new DamageModPair { m_modifier = (DamageModifier)5, m_type = (DamageType)256 }); _panic = new CustomStatusEffect((StatusEffect)(object)obj5, false); ItemManager.Instance.AddStatusEffect(_panic); StatusEffect statusEffect3 = ObjectDB.instance.GetStatusEffect(StringExtensionMethods.GetStableHashCode("Staff_shield")); if (!Object.op_Implicit((Object)(object)statusEffect3)) { ZLog.LogError((object)"SE Staff_shield not found."); return; } SE_Stats obj6 = ScriptableObject.CreateInstance(); ((StatusEffect)obj6).m_icon = statusEffect3.m_icon; ((Object)obj6).name = "Bandaged"; ((StatusEffect)obj6).m_name = "Bandaged"; ((StatusEffect)obj6).m_ttl = 60f; ((StatusEffect)obj6).m_cooldown = 30f; obj6.m_speedModifier = 0.8f; obj6.m_damageModifier = 1f; _bandaged = new CustomStatusEffect((StatusEffect)(object)obj6, false); ItemManager.Instance.AddStatusEffect(_bandaged); SE_Stats obj7 = ScriptableObject.CreateInstance(); ((StatusEffect)obj7).m_icon = statusEffect3.m_icon; ((Object)obj7).name = "WellBandaged"; ((StatusEffect)obj7).m_name = "WellBandaged"; ((StatusEffect)obj7).m_ttl = 180f; ((StatusEffect)obj7).m_cooldown = 30f; obj7.m_speedModifier = 0.8f; obj7.m_damageModifier = 1f; _goodbandaged = new CustomStatusEffect((StatusEffect)(object)obj7, false); ItemManager.Instance.AddStatusEffect(_goodbandaged); SE_Stats obj8 = ScriptableObject.CreateInstance(); ((StatusEffect)obj8).m_icon = statusEffect3.m_icon; ((Object)obj8).name = "Mended"; ((StatusEffect)obj8).m_name = "Mended"; ((StatusEffect)obj8).m_ttl = 150f; ((StatusEffect)obj8).m_repeatInterval = 0f; obj8.m_speedModifier = -0.1f; obj8.m_addMaxCarryWeight = -100f; _recenthealed = new CustomStatusEffect((StatusEffect)(object)obj8, false); ItemManager.Instance.AddStatusEffect(_recenthealed); AddMedicalItems(); } private static void AddMedicalItems() { AddMedKit(); } public static void AddMedKit() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Expected O, but got Unknown //IL_0049: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Expected O, but got Unknown //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Expected O, but got Unknown //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0095: Expected O, but got Unknown //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Expected O, but got Unknown //IL_00be: Unknown result type (might be due to invalid IL or missing references) if (ItemManager.Instance.GetItem("VRP_MedKit") == null) { ItemConfig val = new ItemConfig(); val.Name = "Medical Kit"; val.Description = "a medical kit with everything you need to cure wounds"; val.CraftingStation = "piece_workbench"; val.MinStationLevel = 2; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[3] { new RequirementConfig { Item = "DeerHide", Amount = 1 }, new RequirementConfig { Item = "Floam", Amount = 1 }, new RequirementConfig { Item = "Amber", Amount = 1 } }; ItemConfig val2 = val; CustomItem val3 = new CustomItem("MedKit", "BarberKit", val2); val3.ItemDrop.m_itemData.m_shared.m_itemType = (ItemType)2; val3.ItemDrop.m_itemData.m_shared.m_name = "Medical Kit"; val3.ItemDrop.m_itemData.m_shared.m_maxStackSize = 20; val3.ItemDrop.m_itemData.m_shared.m_weight = 50f; val3.ItemDrop.m_itemData.m_shared.m_consumeStatusEffect = _recenthealed.StatusEffect; ItemManager.Instance.AddItem(val3); } } private static int GetStreak(Player p) { long playerID = p.GetPlayerID(); if (DeathStreak.TryGetValue(playerID, out var value)) { return value; } object obj; if (p == null) { obj = null; } else { ZNetView nview = ((Character)p).m_nview; obj = ((nview != null) ? nview.GetZDO() : null); } ZDO val = (ZDO)obj; if (val != null) { int @int = val.GetInt("vrp_death_streak", 0); DeathStreak[playerID] = @int; return @int; } return 0; } private static void SetStreak(Player p, int s) { long playerID = p.GetPlayerID(); DeathStreak[playerID] = s; ZNetView val = ((Character)(p?)).m_nview; if ((Object)(object)val != (Object)null && val.IsValid() && val.IsOwner()) { val.GetZDO().Set("vrp_death_streak", s); } } private static void ClearStreak(Player p) { DeathStreak.Remove(p.GetPlayerID()); ZNetView val = ((Character)(p?)).m_nview; if ((Object)(object)val != (Object)null && val.IsValid() && val.IsOwner()) { val.GetZDO().Set("vrp_death_streak", 0); } } private static void QueueEffects(Player p, params string[] effectNames) { long playerID = p.GetPlayerID(); if (!PendingSE.TryGetValue(playerID, out var value)) { value = new List(); PendingSE[playerID] = value; } value.Clear(); foreach (string text in effectNames) { value.Add(StringExtensionMethods.GetStableHashCode(text)); } if (VRPMod.DebugMode()) { ZLog.Log((object)("[VRP:Death] Stored pending effects: " + string.Join(",", value))); } } private static string GetHitTypeAsString(HitType t) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Expected I4, but got Unknown string result = "Unknown"; switch ((int)t) { case 0: result = "Undefined"; break; case 1: result = "EnemyHit"; break; case 2: result = "PlayerHit"; break; case 3: result = "Fall"; break; case 4: result = "Drowning"; break; case 5: result = "Burning"; break; case 6: result = "Freezing"; break; case 7: result = "Poison"; break; case 8: result = "Water"; break; case 9: result = "Smoke"; break; case 10: result = "EdgeOfWorld"; break; case 11: result = "Impact"; break; case 12: result = "Cart"; break; case 13: result = "Tree"; break; case 14: result = "Self"; break; case 15: result = "Structural"; break; case 16: result = "Turret"; break; case 17: result = "Boat"; break; case 18: result = "Stalagtite"; break; } return result; } private static void DamageEquippedArmorByPercent(Player p, float pct) { if (!((Object)(object)((Character)(p?)).m_nview == (Object)null) && ((Character)p).m_nview.IsOwner() && ((Humanoid)p).m_inventory != null) { pct = Mathf.Clamp01(pct); if (!(pct <= 0f)) { Hit(((Humanoid)p).m_chestItem); Hit(((Humanoid)p).m_legItem); Hit(((Humanoid)p).m_helmetItem); Hit(((Humanoid)p).m_shoulderItem); ((Humanoid)p).m_inventory.Changed(); } } void Hit(ItemData it) { if (it != null && it.m_shared != null && it.m_shared.m_useDurability) { float maxDurability = it.GetMaxDurability(); if (!(maxDurability <= 0f)) { float num = maxDurability * pct; it.m_durability = Mathf.Max(0f, it.m_durability - num); } } } } public static int ApplyPendingOnSpawn(Player p) { long playerID = p.GetPlayerID(); if (!PendingSE.TryGetValue(playerID, out var value)) { return 0; } int num = 0; foreach (int item in value) { if (!((Character)p).m_seman.HaveStatusEffect(item)) { ((Character)p).m_seman.AddStatusEffect(item, true, 0, 0f); num++; } } value.Clear(); return num; } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [Nullable(0)] public class DrinkablesPatch { [HarmonyPatch(typeof(Player), "ConsumeItem")] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] private static class VRP_DrunkOnConsume { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(Player __instance, ItemData item, ref bool __result) { if (!__result || item == null || (Object)(object)((Character)(__instance?)).m_nview == (Object)null || !((Character)__instance).m_nview.IsOwner()) { return; } StatusEffect val = item.m_shared?.m_consumeStatusEffect; if ((Object)(object)val == (Object)null || !IsAlcoholEffect(val)) { return; } SEMan sEMan = ((Character)__instance).GetSEMan(); if (sEMan == null) { return; } if (sEMan.HaveStatusEffect(VeryDrunkHash)) { sEMan.AddStatusEffect(VeryDrunkHash, true, 0, 0f); return; } if (sEMan.HaveStatusEffect(DrunkHash)) { sEMan.RemoveStatusEffect(DrunkHash, false); sEMan.AddStatusEffect(VeryDrunkHash, true, 0, 0f); return; } float num = Mathf.Clamp01(VRPMod._drunkChance?.Value ?? 0.05f); if (Random.value <= num) { sEMan.AddStatusEffect(DrunkHash, true, 0, 0f); } } } [HarmonyPatch(typeof(Player), "ConsumeItem")] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] private static class VRP_RolledThistle_Consume { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(Player __instance, ItemData item, ref bool __result) { if (__result && !((Object)(object)__instance == (Object)null) && item != null && !((Object)(object)((Character)__instance).m_nview == (Object)null) && ((Character)__instance).m_nview.IsOwner() && ((Object.op_Implicit((Object)(object)item.m_dropPrefab) && ((Object)item.m_dropPrefab).name == "RolledThistle") || string.Equals(item.m_shared?.m_name, "RolledThistle", StringComparison.Ordinal))) { for (int i = 0; i < __instance.m_foods.Count; i++) { __instance.m_foods[i].m_time = __instance.m_foods[i].m_time * 0.5f; } StatusEffect statusEffect = ((Character)__instance).m_seman.GetStatusEffect(StringExtensionMethods.GetStableHashCode("Rested")); if ((Object)(object)statusEffect != (Object)null) { statusEffect.m_time += 5f; } else if (VRPMod.DebugMode()) { ZLog.Log((object)"[VRP:Thistle] Rested not present; nothing to double"); } } } } private static CustomStatusEffect _juiced; private static CustomStatusEffect _jacked; private static CustomStatusEffect _tipsy; private static CustomStatusEffect _musty; private static CustomStatusEffect _hot; private static CustomStatusEffect _joy; private static CustomStatusEffect _poozy; private static CustomStatusEffect _drunk; private static CustomStatusEffect _verydrunk; private static CustomStatusEffect _smokedthistle; private static CustomStatusEffect _seModer; private static CustomStatusEffect _seWishbone; public static int DrunkHash => StringExtensionMethods.GetStableHashCode("se_drunk"); public static int VeryDrunkHash => StringExtensionMethods.GetStableHashCode("se_verydrunk"); internal static bool IsAlcoholEffect(StatusEffect se) { CustomStatusEffect tipsy = _tipsy; if (!((Object)(object)se == (Object)(object)((tipsy != null) ? tipsy.StatusEffect : null))) { CustomStatusEffect musty = _musty; if (!((Object)(object)se == (Object)(object)((musty != null) ? musty.StatusEffect : null))) { CustomStatusEffect joy = _joy; if (!((Object)(object)se == (Object)(object)((joy != null) ? joy.StatusEffect : null))) { CustomStatusEffect poozy = _poozy; return (Object)(object)se == (Object)(object)((poozy != null) ? poozy.StatusEffect : null); } } } return true; } private static void LoadDrinkStatuses() { //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Expected O, but got Unknown //IL_012a: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Expected O, but got Unknown //IL_01cd: Unknown result type (might be due to invalid IL or missing references) //IL_01d7: Expected O, but got Unknown //IL_027b: Unknown result type (might be due to invalid IL or missing references) //IL_0285: Expected O, but got Unknown //IL_0354: Unknown result type (might be due to invalid IL or missing references) //IL_035e: Expected O, but got Unknown //IL_0320: Unknown result type (might be due to invalid IL or missing references) //IL_0329: Unknown result type (might be due to invalid IL or missing references) //IL_0332: Unknown result type (might be due to invalid IL or missing references) //IL_033e: Unknown result type (might be due to invalid IL or missing references) //IL_040f: Unknown result type (might be due to invalid IL or missing references) //IL_0419: Expected O, but got Unknown //IL_04be: Unknown result type (might be due to invalid IL or missing references) //IL_04c8: Expected O, but got Unknown //IL_0561: Unknown result type (might be due to invalid IL or missing references) //IL_056b: Expected O, but got Unknown //IL_0603: Unknown result type (might be due to invalid IL or missing references) //IL_060d: Expected O, but got Unknown //IL_067d: Unknown result type (might be due to invalid IL or missing references) //IL_0687: Expected O, but got Unknown //IL_0780: Unknown result type (might be due to invalid IL or missing references) //IL_078a: Expected O, but got Unknown //IL_071c: Unknown result type (might be due to invalid IL or missing references) //IL_0726: Expected O, but got Unknown ItemDrop component = PrefabManager.Instance.GetPrefab("MeadTasty").GetComponent(); StatusEffect obj = Object.Instantiate(component.m_itemData.m_shared.m_consumeStatusEffect); SE_Stats val = (SE_Stats)(object)((obj is SE_Stats) ? obj : null); if ((Object)(object)val != (Object)null) { ((Object)val).name = "se_alcohol"; ((StatusEffect)val).m_cooldown = 3f; ((StatusEffect)val).m_name = "Tipsy"; ((StatusEffect)val).m_tooltip = "Alcohol is great!"; val.m_healthOverTime = 0f; val.m_staminaRegenMultiplier = 3f; val.m_healthRegenMultiplier = 0.5f; ((StatusEffect)val).m_ttl = 10f; } _tipsy = new CustomStatusEffect((StatusEffect)(object)val, false); ItemManager.Instance.AddStatusEffect(_tipsy); StatusEffect obj2 = Object.Instantiate(component.m_itemData.m_shared.m_consumeStatusEffect); SE_Stats val2 = (SE_Stats)(object)((obj2 is SE_Stats) ? obj2 : null); if ((Object)(object)val2 != (Object)null) { ((Object)val2).name = "Musty"; ((StatusEffect)val2).m_cooldown = 3f; ((StatusEffect)val2).m_name = "Musty"; ((StatusEffect)val2).m_tooltip = "this feels strange"; val2.m_healthOverTime = 0f; val2.m_staminaRegenMultiplier = 1f; val2.m_healthRegenMultiplier = 1f; ((StatusEffect)val2).m_ttl = 10f; } _musty = new CustomStatusEffect((StatusEffect)(object)val2, false); ItemManager.Instance.AddStatusEffect(_musty); StatusEffect obj3 = Object.Instantiate(component.m_itemData.m_shared.m_consumeStatusEffect); SE_Stats val3 = (SE_Stats)(object)((obj3 is SE_Stats) ? obj3 : null); if ((Object)(object)val3 != (Object)null) { ((Object)val3).name = "se_juiced"; ((StatusEffect)val3).m_cooldown = 15f; ((StatusEffect)val3).m_name = "Juiced"; ((StatusEffect)val3).m_tooltip = "Sugar Rush zoom zoom!"; val3.m_healthOverTime = 0f; val3.m_staminaRegenMultiplier = 1f; val3.m_healthRegenMultiplier = 1f; val3.m_speedModifier = 0.2f; ((StatusEffect)val3).m_ttl = 120f; } _juiced = new CustomStatusEffect((StatusEffect)(object)val3, false); ItemManager.Instance.AddStatusEffect(_juiced); StatusEffect obj4 = Object.Instantiate(component.m_itemData.m_shared.m_consumeStatusEffect); SE_Stats val4 = (SE_Stats)(object)((obj4 is SE_Stats) ? obj4 : null); if ((Object)(object)val4 != (Object)null) { ((Object)val4).name = "se_juiced2"; ((StatusEffect)val4).m_cooldown = 15f; ((StatusEffect)val4).m_name = "Jacked"; ((StatusEffect)val4).m_tooltip = "SWEET! You feel stamina returning slowly!"; val4.m_healthOverTime = 0f; val4.m_staminaRegenMultiplier = 1f; val4.m_healthRegenMultiplier = 1f; val4.m_staminaOverTime = 240f; val4.m_staminaOverTimeDuration = 120f; ((StatusEffect)val4).m_ttl = 120f; } _jacked = new CustomStatusEffect((StatusEffect)(object)val4, false); ItemManager.Instance.AddStatusEffect(_jacked); StatusEffect obj5 = Object.Instantiate(component.m_itemData.m_shared.m_consumeStatusEffect); SE_Stats val5 = (SE_Stats)(object)((obj5 is SE_Stats) ? obj5 : null); if ((Object)(object)val5 != (Object)null) { ((Object)val5).name = "se_hot"; ((StatusEffect)val5).m_cooldown = 60f; ((StatusEffect)val5).m_name = "HOT"; ((StatusEffect)val5).m_tooltip = "IT BURNS"; val5.m_healthOverTime = 0f; val5.m_staminaRegenMultiplier = 1f; val5.m_healthRegenMultiplier = 1f; val5.m_runStaminaDrainModifier = -0.2f; DamageModPair item = new DamageModPair { m_modifier = (DamageModifier)1, m_type = (DamageType)64 }; val5.m_mods.Add(item); ((StatusEffect)val5).m_ttl = 120f; } _hot = new CustomStatusEffect((StatusEffect)(object)val5, false); ItemManager.Instance.AddStatusEffect(_hot); StatusEffect obj6 = Object.Instantiate(component.m_itemData.m_shared.m_consumeStatusEffect); SE_Stats val6 = (SE_Stats)(object)((obj6 is SE_Stats) ? obj6 : null); if ((Object)(object)val6 != (Object)null) { ((Object)val6).name = "se_joy"; ((StatusEffect)val6).m_cooldown = 5f; ((StatusEffect)val6).m_name = "Joy"; ((StatusEffect)val6).m_tooltip = "HAPPY HAPPY JOY JOY"; val6.m_healthOverTime = 0f; val6.m_staminaRegenMultiplier = 1f; val6.m_healthRegenMultiplier = 1f; val6.m_addMaxCarryWeight = 100f; val6.m_jumpStaminaUseModifier = -1f; ((StatusEffect)val6).m_ttl = 240f; } _joy = new CustomStatusEffect((StatusEffect)(object)val6, false); ItemManager.Instance.AddStatusEffect(_joy); StatusEffect obj7 = Object.Instantiate(component.m_itemData.m_shared.m_consumeStatusEffect); SE_Stats val7 = (SE_Stats)(object)((obj7 is SE_Stats) ? obj7 : null); if ((Object)(object)val7 != (Object)null) { ((Object)val7).name = "Poozy"; ((StatusEffect)val7).m_cooldown = 600f; ((StatusEffect)val7).m_name = "Poozy"; ((StatusEffect)val7).m_tooltip = "i have a sinking feeling about this"; val7.m_healthOverTime = 0f; val7.m_staminaRegenMultiplier = 1f; val7.m_healthRegenMultiplier = 1f; val7.m_speedModifier = -0.5f; ((StatusEffect)val7).m_ttl = 120f; } _poozy = new CustomStatusEffect((StatusEffect)(object)val7, false); ItemManager.Instance.AddStatusEffect(_poozy); StatusEffect obj8 = Object.Instantiate(component.m_itemData.m_shared.m_consumeStatusEffect); SE_Stats val8 = (SE_Stats)(object)((obj8 is SE_Stats) ? obj8 : null); if ((Object)(object)val8 != (Object)null) { ((Object)val8).name = "se_drunk"; ((StatusEffect)val8).m_name = "Drunk"; ((StatusEffect)val8).m_tooltip = "Your feet forget the path."; ((StatusEffect)val8).m_cooldown = 30f; ((StatusEffect)val8).m_ttl = 120f; val8.m_speedModifier = -0.15f; val8.m_runStaminaDrainModifier = 0.15f; val8.m_staminaRegenMultiplier = 0.8f; } _drunk = new CustomStatusEffect((StatusEffect)(object)val8, false); ItemManager.Instance.AddStatusEffect(_drunk); StatusEffect obj9 = Object.Instantiate(component.m_itemData.m_shared.m_consumeStatusEffect); SE_Stats val9 = (SE_Stats)(object)((obj9 is SE_Stats) ? obj9 : null); if ((Object)(object)val9 != (Object)null) { ((Object)val9).name = "se_verydrunk"; ((StatusEffect)val9).m_name = "Wasted"; ((StatusEffect)val9).m_tooltip = "Your liver hates you."; ((StatusEffect)val9).m_cooldown = 30f; ((StatusEffect)val9).m_ttl = 90f; val9.m_speedModifier = -0.25f; val9.m_runStaminaDrainModifier = 0.65f; val9.m_staminaRegenMultiplier = 0.9f; } _verydrunk = new CustomStatusEffect((StatusEffect)(object)val9, false); ItemManager.Instance.AddStatusEffect(_verydrunk); StatusEffect statusEffect = ObjectDB.instance.GetStatusEffect(StringExtensionMethods.GetStableHashCode("Smoked")); SE_Stats obj10 = ScriptableObject.CreateInstance(); ((StatusEffect)obj10).m_icon = statusEffect.m_icon; ((Object)obj10).name = "Thistled"; ((StatusEffect)obj10).m_name = "Thistled"; ((StatusEffect)obj10).m_ttl = 60f; obj10.m_speedModifier = -0.15f; ((StatusEffect)obj10).m_repeatInterval = 0f; _smokedthistle = new CustomStatusEffect((StatusEffect)(object)obj10, false); ItemManager.Instance.AddStatusEffect(_smokedthistle); StatusEffect statusEffect2 = ObjectDB.instance.GetStatusEffect(StringExtensionMethods.GetStableHashCode("GP_Moder")); SE_Stats val10 = (SE_Stats)(object)((statusEffect2 is SE_Stats) ? statusEffect2 : null); if ((Object)(object)val10 != (Object)null) { SE_Stats obj11 = Object.Instantiate(val10); ((Object)obj11).name = "se_mead_moder"; ((StatusEffect)obj11).m_name = "Sailor's Favor"; ((StatusEffect)obj11).m_tooltip = "The winds favor your sails."; obj11.m_staminaRegenMultiplier = 1f; obj11.m_eitrRegenMultiplier = 1f; obj11.m_addMaxCarryWeight = 0f; obj11.m_speedModifier = 0f; ((StatusEffect)obj11).m_ttl = 600f; _seModer = new CustomStatusEffect((StatusEffect)(object)obj11, false); ItemManager.Instance.AddStatusEffect(_seModer); } StatusEffect statusEffect3 = ObjectDB.instance.GetStatusEffect(StringExtensionMethods.GetStableHashCode("Wishbone")); SE_Stats obj12 = ScriptableObject.CreateInstance(); ((StatusEffect)obj12).m_icon = statusEffect3.m_icon; ((Object)obj12).name = "se_wishbone"; ((StatusEffect)obj12).m_name = "Dowsing Spirit"; ((StatusEffect)obj12).m_ttl = 300f; _seWishbone = new CustomStatusEffect((StatusEffect)(object)obj12, false); ItemManager.Instance.AddStatusEffect(_seWishbone); } public static void AddCustomDrinks() { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Expected O, but got Unknown //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Expected O, but got Unknown //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Expected O, but got Unknown //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_0168: Unknown result type (might be due to invalid IL or missing references) //IL_016f: Expected O, but got Unknown //IL_01ae: Unknown result type (might be due to invalid IL or missing references) //IL_01b3: Unknown result type (might be due to invalid IL or missing references) //IL_01be: Unknown result type (might be due to invalid IL or missing references) //IL_01c7: Expected O, but got Unknown //IL_01c9: Unknown result type (might be due to invalid IL or missing references) //IL_01ce: Unknown result type (might be due to invalid IL or missing references) //IL_01d9: Unknown result type (might be due to invalid IL or missing references) //IL_01e1: Expected O, but got Unknown //IL_01e8: Unknown result type (might be due to invalid IL or missing references) //IL_01ef: Expected O, but got Unknown //IL_0201: Unknown result type (might be due to invalid IL or missing references) //IL_02a9: Unknown result type (might be due to invalid IL or missing references) //IL_02b0: Expected O, but got Unknown //IL_02e2: Unknown result type (might be due to invalid IL or missing references) //IL_02e7: Unknown result type (might be due to invalid IL or missing references) //IL_02f2: Unknown result type (might be due to invalid IL or missing references) //IL_02fa: Expected O, but got Unknown //IL_02fc: Unknown result type (might be due to invalid IL or missing references) //IL_0301: Unknown result type (might be due to invalid IL or missing references) //IL_030c: Unknown result type (might be due to invalid IL or missing references) //IL_0314: Expected O, but got Unknown //IL_0316: Unknown result type (might be due to invalid IL or missing references) //IL_031b: Unknown result type (might be due to invalid IL or missing references) //IL_0326: Unknown result type (might be due to invalid IL or missing references) //IL_032e: Expected O, but got Unknown //IL_0330: Unknown result type (might be due to invalid IL or missing references) //IL_0335: Unknown result type (might be due to invalid IL or missing references) //IL_0340: Unknown result type (might be due to invalid IL or missing references) //IL_0348: Expected O, but got Unknown //IL_034f: Unknown result type (might be due to invalid IL or missing references) //IL_0355: Expected O, but got Unknown //IL_03a4: Unknown result type (might be due to invalid IL or missing references) //IL_03ab: Expected O, but got Unknown //IL_03de: Unknown result type (might be due to invalid IL or missing references) //IL_03e3: Unknown result type (might be due to invalid IL or missing references) //IL_03ee: Unknown result type (might be due to invalid IL or missing references) //IL_03f6: Expected O, but got Unknown //IL_03fd: Unknown result type (might be due to invalid IL or missing references) //IL_0403: Expected O, but got Unknown //IL_042e: Unknown result type (might be due to invalid IL or missing references) //IL_04b9: Unknown result type (might be due to invalid IL or missing references) //IL_04be: Unknown result type (might be due to invalid IL or missing references) //IL_04c9: Unknown result type (might be due to invalid IL or missing references) //IL_04d4: Unknown result type (might be due to invalid IL or missing references) //IL_04e1: Expected O, but got Unknown //IL_04dc: Unknown result type (might be due to invalid IL or missing references) //IL_04e2: Expected O, but got Unknown //IL_050e: Unknown result type (might be due to invalid IL or missing references) //IL_0515: Expected O, but got Unknown //IL_0547: Unknown result type (might be due to invalid IL or missing references) //IL_054c: Unknown result type (might be due to invalid IL or missing references) //IL_0557: Unknown result type (might be due to invalid IL or missing references) //IL_055f: Expected O, but got Unknown //IL_0561: Unknown result type (might be due to invalid IL or missing references) //IL_0566: Unknown result type (might be due to invalid IL or missing references) //IL_0571: Unknown result type (might be due to invalid IL or missing references) //IL_0579: Expected O, but got Unknown //IL_057b: Unknown result type (might be due to invalid IL or missing references) //IL_0580: Unknown result type (might be due to invalid IL or missing references) //IL_058b: Unknown result type (might be due to invalid IL or missing references) //IL_0593: Expected O, but got Unknown //IL_059a: Unknown result type (might be due to invalid IL or missing references) //IL_05a1: Expected O, but got Unknown //IL_05eb: Unknown result type (might be due to invalid IL or missing references) //IL_05f2: Expected O, but got Unknown //IL_0625: Unknown result type (might be due to invalid IL or missing references) //IL_062a: Unknown result type (might be due to invalid IL or missing references) //IL_0635: Unknown result type (might be due to invalid IL or missing references) //IL_063d: Expected O, but got Unknown //IL_0644: Unknown result type (might be due to invalid IL or missing references) //IL_064b: Expected O, but got Unknown //IL_0678: Unknown result type (might be due to invalid IL or missing references) //IL_0700: Unknown result type (might be due to invalid IL or missing references) //IL_0705: Unknown result type (might be due to invalid IL or missing references) //IL_0710: Unknown result type (might be due to invalid IL or missing references) //IL_071b: Unknown result type (might be due to invalid IL or missing references) //IL_0728: Expected O, but got Unknown //IL_0723: Unknown result type (might be due to invalid IL or missing references) //IL_072a: Expected O, but got Unknown //IL_0741: Unknown result type (might be due to invalid IL or missing references) //IL_0748: Expected O, but got Unknown //IL_077a: Unknown result type (might be due to invalid IL or missing references) //IL_077f: Unknown result type (might be due to invalid IL or missing references) //IL_078a: Unknown result type (might be due to invalid IL or missing references) //IL_0792: Expected O, but got Unknown //IL_0794: Unknown result type (might be due to invalid IL or missing references) //IL_0799: Unknown result type (might be due to invalid IL or missing references) //IL_07a4: Unknown result type (might be due to invalid IL or missing references) //IL_07ac: Expected O, but got Unknown //IL_07ae: Unknown result type (might be due to invalid IL or missing references) //IL_07b3: Unknown result type (might be due to invalid IL or missing references) //IL_07be: Unknown result type (might be due to invalid IL or missing references) //IL_07c6: Expected O, but got Unknown //IL_07cd: Unknown result type (might be due to invalid IL or missing references) //IL_07d4: Expected O, but got Unknown //IL_0826: Unknown result type (might be due to invalid IL or missing references) //IL_082d: Expected O, but got Unknown //IL_084b: Unknown result type (might be due to invalid IL or missing references) //IL_0850: Unknown result type (might be due to invalid IL or missing references) //IL_085b: Unknown result type (might be due to invalid IL or missing references) //IL_0863: Expected O, but got Unknown //IL_086a: Unknown result type (might be due to invalid IL or missing references) //IL_0871: Expected O, but got Unknown //IL_089e: Unknown result type (might be due to invalid IL or missing references) //IL_092e: Unknown result type (might be due to invalid IL or missing references) //IL_0933: Unknown result type (might be due to invalid IL or missing references) //IL_093e: Unknown result type (might be due to invalid IL or missing references) //IL_0949: Unknown result type (might be due to invalid IL or missing references) //IL_0956: Expected O, but got Unknown //IL_0951: Unknown result type (might be due to invalid IL or missing references) //IL_0958: Expected O, but got Unknown //IL_096f: Unknown result type (might be due to invalid IL or missing references) //IL_0976: Expected O, but got Unknown //IL_09a8: Unknown result type (might be due to invalid IL or missing references) //IL_09ad: Unknown result type (might be due to invalid IL or missing references) //IL_09b8: Unknown result type (might be due to invalid IL or missing references) //IL_09c0: Expected O, but got Unknown //IL_09c2: Unknown result type (might be due to invalid IL or missing references) //IL_09c7: Unknown result type (might be due to invalid IL or missing references) //IL_09d2: Unknown result type (might be due to invalid IL or missing references) //IL_09da: Expected O, but got Unknown //IL_09e1: Unknown result type (might be due to invalid IL or missing references) //IL_09e8: Expected O, but got Unknown //IL_0a45: Unknown result type (might be due to invalid IL or missing references) //IL_0a4c: Expected O, but got Unknown //IL_0a7f: Unknown result type (might be due to invalid IL or missing references) //IL_0a84: Unknown result type (might be due to invalid IL or missing references) //IL_0a8f: Unknown result type (might be due to invalid IL or missing references) //IL_0a97: Expected O, but got Unknown //IL_0a9e: Unknown result type (might be due to invalid IL or missing references) //IL_0aa5: Expected O, but got Unknown //IL_0ad2: Unknown result type (might be due to invalid IL or missing references) //IL_0b62: Unknown result type (might be due to invalid IL or missing references) //IL_0b67: Unknown result type (might be due to invalid IL or missing references) //IL_0b72: Unknown result type (might be due to invalid IL or missing references) //IL_0b7d: Unknown result type (might be due to invalid IL or missing references) //IL_0b8a: Expected O, but got Unknown //IL_0b85: Unknown result type (might be due to invalid IL or missing references) //IL_0b8c: Expected O, but got Unknown //IL_0baf: Unknown result type (might be due to invalid IL or missing references) //IL_0bb6: Expected O, but got Unknown //IL_0be8: Unknown result type (might be due to invalid IL or missing references) //IL_0bed: Unknown result type (might be due to invalid IL or missing references) //IL_0bf8: Unknown result type (might be due to invalid IL or missing references) //IL_0c01: Expected O, but got Unknown //IL_0c03: Unknown result type (might be due to invalid IL or missing references) //IL_0c08: Unknown result type (might be due to invalid IL or missing references) //IL_0c13: Unknown result type (might be due to invalid IL or missing references) //IL_0c1b: Expected O, but got Unknown //IL_0c1d: Unknown result type (might be due to invalid IL or missing references) //IL_0c22: Unknown result type (might be due to invalid IL or missing references) //IL_0c2d: Unknown result type (might be due to invalid IL or missing references) //IL_0c35: Expected O, but got Unknown //IL_0c37: Unknown result type (might be due to invalid IL or missing references) //IL_0c3c: Unknown result type (might be due to invalid IL or missing references) //IL_0c47: Unknown result type (might be due to invalid IL or missing references) //IL_0c4f: Expected O, but got Unknown //IL_0c56: Unknown result type (might be due to invalid IL or missing references) //IL_0c5d: Expected O, but got Unknown //IL_0caa: Unknown result type (might be due to invalid IL or missing references) //IL_0caf: Unknown result type (might be due to invalid IL or missing references) //IL_0cba: Unknown result type (might be due to invalid IL or missing references) //IL_0cc2: Unknown result type (might be due to invalid IL or missing references) //IL_0ccd: Unknown result type (might be due to invalid IL or missing references) //IL_0cd9: Expected O, but got Unknown //IL_0cd4: Unknown result type (might be due to invalid IL or missing references) //IL_0cdb: Expected O, but got Unknown //IL_0d08: Unknown result type (might be due to invalid IL or missing references) //IL_0d77: Unknown result type (might be due to invalid IL or missing references) //IL_0d7c: Unknown result type (might be due to invalid IL or missing references) //IL_0d87: Unknown result type (might be due to invalid IL or missing references) //IL_0d92: Unknown result type (might be due to invalid IL or missing references) //IL_0d9a: Unknown result type (might be due to invalid IL or missing references) //IL_0daa: Expected O, but got Unknown //IL_0da5: Unknown result type (might be due to invalid IL or missing references) //IL_0daf: Expected O, but got Unknown //IL_0dbc: Unknown result type (might be due to invalid IL or missing references) //IL_0dc3: Expected O, but got Unknown //IL_0df9: Unknown result type (might be due to invalid IL or missing references) //IL_0dfe: Unknown result type (might be due to invalid IL or missing references) //IL_0e09: Unknown result type (might be due to invalid IL or missing references) //IL_0e11: Expected O, but got Unknown //IL_0e13: Unknown result type (might be due to invalid IL or missing references) //IL_0e18: Unknown result type (might be due to invalid IL or missing references) //IL_0e23: Unknown result type (might be due to invalid IL or missing references) //IL_0e2b: Expected O, but got Unknown //IL_0e40: Unknown result type (might be due to invalid IL or missing references) //IL_0e47: Expected O, but got Unknown //IL_0e59: Unknown result type (might be due to invalid IL or missing references) //IL_0ee3: Unknown result type (might be due to invalid IL or missing references) //IL_0eea: Expected O, but got Unknown //IL_0f1c: Unknown result type (might be due to invalid IL or missing references) //IL_0f21: Unknown result type (might be due to invalid IL or missing references) //IL_0f2c: Unknown result type (might be due to invalid IL or missing references) //IL_0f35: Expected O, but got Unknown //IL_0f37: Unknown result type (might be due to invalid IL or missing references) //IL_0f3c: Unknown result type (might be due to invalid IL or missing references) //IL_0f47: Unknown result type (might be due to invalid IL or missing references) //IL_0f4f: Expected O, but got Unknown //IL_0f51: Unknown result type (might be due to invalid IL or missing references) //IL_0f56: Unknown result type (might be due to invalid IL or missing references) //IL_0f61: Unknown result type (might be due to invalid IL or missing references) //IL_0f69: Expected O, but got Unknown //IL_0f70: Unknown result type (might be due to invalid IL or missing references) //IL_0f77: Expected O, but got Unknown //IL_0fa9: Unknown result type (might be due to invalid IL or missing references) //IL_0fb0: Expected O, but got Unknown //IL_0fdb: Unknown result type (might be due to invalid IL or missing references) //IL_0fe0: Unknown result type (might be due to invalid IL or missing references) //IL_0feb: Unknown result type (might be due to invalid IL or missing references) //IL_0ff3: Expected O, but got Unknown //IL_0ffa: Unknown result type (might be due to invalid IL or missing references) //IL_1001: Expected O, but got Unknown //IL_102e: Unknown result type (might be due to invalid IL or missing references) //IL_109f: Unknown result type (might be due to invalid IL or missing references) //IL_10a4: Unknown result type (might be due to invalid IL or missing references) //IL_10af: Unknown result type (might be due to invalid IL or missing references) //IL_10ba: Unknown result type (might be due to invalid IL or missing references) //IL_10c7: Expected O, but got Unknown //IL_10c2: Unknown result type (might be due to invalid IL or missing references) //IL_10c9: Expected O, but got Unknown //IL_10ec: Unknown result type (might be due to invalid IL or missing references) //IL_10f3: Expected O, but got Unknown //IL_1125: Unknown result type (might be due to invalid IL or missing references) //IL_112a: Unknown result type (might be due to invalid IL or missing references) //IL_1135: Unknown result type (might be due to invalid IL or missing references) //IL_113d: Expected O, but got Unknown //IL_113f: Unknown result type (might be due to invalid IL or missing references) //IL_1144: Unknown result type (might be due to invalid IL or missing references) //IL_114f: Unknown result type (might be due to invalid IL or missing references) //IL_1157: Expected O, but got Unknown //IL_1159: Unknown result type (might be due to invalid IL or missing references) //IL_115e: Unknown result type (might be due to invalid IL or missing references) //IL_1169: Unknown result type (might be due to invalid IL or missing references) //IL_1172: Expected O, but got Unknown //IL_1179: Unknown result type (might be due to invalid IL or missing references) //IL_1180: Expected O, but got Unknown //IL_11b2: Unknown result type (might be due to invalid IL or missing references) //IL_11b9: Expected O, but got Unknown //IL_11e4: Unknown result type (might be due to invalid IL or missing references) //IL_11e9: Unknown result type (might be due to invalid IL or missing references) //IL_11f4: Unknown result type (might be due to invalid IL or missing references) //IL_11fc: Expected O, but got Unknown //IL_1203: Unknown result type (might be due to invalid IL or missing references) //IL_120a: Expected O, but got Unknown //IL_1237: Unknown result type (might be due to invalid IL or missing references) //IL_12a8: Unknown result type (might be due to invalid IL or missing references) //IL_12ad: Unknown result type (might be due to invalid IL or missing references) //IL_12b8: Unknown result type (might be due to invalid IL or missing references) //IL_12c3: Unknown result type (might be due to invalid IL or missing references) //IL_12d0: Expected O, but got Unknown //IL_12cb: Unknown result type (might be due to invalid IL or missing references) //IL_12d2: Expected O, but got Unknown try { LoadDrinkStatuses(); ItemDrop component = PrefabManager.Instance.GetPrefab("MeadTasty").GetComponent(); ItemConfig val; using (BundleCache.Scope scope = new BundleCache.Scope("Arielle-ValheimRoleplay/Assets/bandage")) { AssetBundle bundle = scope.Bundle; val = new ItemConfig(); val.Name = "RaspberryJuice"; val.Description = "tropical drink pink!"; val.Amount = 10; val.CraftingStation = "piece_MeadCauldron"; val.MinStationLevel = 1; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "Raspberry", Amount = 10 }, new RequirementConfig { Item = "coconut", Amount = 5 } }; CustomItem val2 = new CustomItem(bundle, "cocodrinkpink", true, val); val2.ItemDrop.m_itemData.m_shared.m_itemType = (ItemType)2; val2.ItemDrop.m_itemData.m_shared.m_ammoType = component.m_itemData.m_shared.m_ammoType; val2.ItemDrop.m_itemData.m_shared.m_attack.m_attackAnimation = "emote_drink"; val2.ItemDrop.m_itemData.m_shared.m_consumeStatusEffect = _juiced.StatusEffect; val2.ItemDrop.m_itemData.m_shared.m_maxStackSize = 10; ItemManager.Instance.AddItem(val2); val = new ItemConfig(); val.Name = "BlueberryJuice"; val.Description = "tropical drink blue!"; val.Amount = 10; val.CraftingStation = "piece_MeadCauldron"; val.MinStationLevel = 1; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "Blueberries", Amount = 10 }, new RequirementConfig { Item = "coconut", Amount = 5 } }; CustomItem val3 = new CustomItem(bundle, "cocodrinkblue", true, val); val3.ItemDrop.m_itemData.m_shared.m_itemType = (ItemType)2; val3.ItemDrop.m_itemData.m_shared.m_ammoType = component.m_itemData.m_shared.m_ammoType; val3.ItemDrop.m_itemData.m_shared.m_attack.m_attackAnimation = "emote_drink"; val3.ItemDrop.m_itemData.m_shared.m_consumeStatusEffect = _jacked.StatusEffect; val3.ItemDrop.m_itemData.m_shared.m_maxStackSize = 10; ItemManager.Instance.AddItem(val3); } val = new ItemConfig(); val.Description = "A fragrant blend of blossoms and honey, ready to ferment into fine flower wine."; val.Amount = 1; val.CraftingStation = "piece_MeadCauldron"; val.MinStationLevel = 1; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[4] { new RequirementConfig { Item = "Dandelion", Amount = 5 }, new RequirementConfig { Item = "GreydwarfEye", Amount = 5 }, new RequirementConfig { Item = "Thistle", Amount = 5 }, new RequirementConfig { Item = "Honey", Amount = 5 } }; CustomItem val4 = new CustomItem("MushJoy", "MeadBaseTasty", val); val4.ItemDrop.m_itemData.m_shared.m_name = "Flower Mush"; val4.ItemDrop.m_itemData.m_shared.m_consumeStatusEffect = _joy.StatusEffect; ItemManager.Instance.AddItem(val4); val = new ItemConfig(); val.Description = "Sweet wine steeped with meadow blooms, light and fragrant as a spring breeze."; val.Amount = 20; val.CraftingStation = ""; val.MinStationLevel = 1; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "SledgeCheat", Amount = 1 } }; CustomItem val5 = new CustomItem("JoyWine", "BarleyWine", val); val5.ItemDrop.m_itemData.m_shared.m_name = "Flower Wine"; val5.ItemDrop.m_itemData.m_shared.m_itemType = (ItemType)2; val5.ItemDrop.m_itemData.m_shared.m_ammoType = component.m_itemData.m_shared.m_ammoType; val5.ItemDrop.m_itemData.m_shared.m_attack.m_attackAnimation = "emote_drink"; val5.ItemDrop.m_itemData.m_shared.m_consumeStatusEffect = _joy.StatusEffect; val5.ItemDrop.m_itemData.m_shared.m_maxStackSize = 20; ItemManager.Instance.AddItem(val5); CustomItemConversion val6 = new CustomItemConversion((ConversionConfig)new FermenterConversionConfig { FromItem = "MushJoy", ToItem = "JoyWine", ProducedItems = 10 }); ItemManager.Instance.AddItemConversion(val6); StatusEffect statusEffect = ObjectDB.instance.GetStatusEffect(StringExtensionMethods.GetStableHashCode("Burning")); val = new ItemConfig(); val.Description = "It smells of sulfur and bad decisions."; val.Amount = 1; val.CraftingStation = "piece_MeadCauldron"; val.MinStationLevel = 1; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[3] { new RequirementConfig { Item = "Honey", Amount = 5 }, new RequirementConfig { Item = "SurtlingCore", Amount = 2 }, new RequirementConfig { Item = "Coal", Amount = 5 } }; CustomItem val7 = new CustomItem("MeadBaseFire", "MeadBaseTamer", val); val7.ItemDrop.m_itemData.m_shared.m_name = "Surtling Mash"; val7.ItemDrop.m_itemData.m_shared.m_consumeStatusEffect = statusEffect; ItemManager.Instance.AddItem(val7); val = new ItemConfig(); val.Description = "It has a firey kick."; val.Amount = 20; val.CraftingStation = ""; val.MinStationLevel = 1; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "SledgeCheat", Amount = 1 } }; CustomItem val8 = new CustomItem("SurtlingBrew", "MeadTamer", val); val8.ItemDrop.m_itemData.m_shared.m_name = "Surtling Brew"; val8.ItemDrop.m_itemData.m_shared.m_itemType = (ItemType)2; val8.ItemDrop.m_itemData.m_shared.m_ammoType = component.m_itemData.m_shared.m_ammoType; val8.ItemDrop.m_itemData.m_shared.m_attack.m_attackAnimation = "emote_drink"; val8.ItemDrop.m_itemData.m_shared.m_consumeStatusEffect = statusEffect; val8.ItemDrop.m_itemData.m_shared.m_maxStackSize = 20; ItemManager.Instance.AddItem(val8); CustomItemConversion val9 = new CustomItemConversion((ConversionConfig)new FermenterConversionConfig { FromItem = "MeadBaseFire", ToItem = "SurtlingBrew", ProducedItems = 10 }); ItemManager.Instance.AddItemConversion(val9); val = new ItemConfig(); val.Description = "Mushroom mash from the swamp, awaiting the fermenter’s magic."; val.Amount = 1; val.CraftingStation = "piece_MeadCauldron"; val.MinStationLevel = 1; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[3] { new RequirementConfig { Item = "Pukeberries", Amount = 2 }, new RequirementConfig { Item = "Ooze", Amount = 2 }, new RequirementConfig { Item = "Dandelion", Amount = 5 } }; CustomItem val10 = new CustomItem("MushSwamp", "MeadBaseTasty", val); val10.ItemDrop.m_itemData.m_shared.m_name = "Swamp Mush"; val10.ItemDrop.m_itemData.m_shared.m_consumeStatusEffect = _poozy.StatusEffect; ItemManager.Instance.AddItem(val10); val = new ItemConfig(); val.Description = "Bitter swamp-mushroom brew, fills you with a sinking sensation if your guts are strong enough to keep it down"; val.Amount = 1; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "SledgeCheat", Amount = 2 } }; CustomItem val11 = new CustomItem("BeerSwamp", "Tankard", val); val11.ItemDrop.m_itemData.m_shared.m_name = "Poozle"; val11.ItemDrop.m_itemData.m_shared.m_itemType = (ItemType)2; val11.ItemDrop.m_itemData.m_shared.m_ammoType = component.m_itemData.m_shared.m_ammoType; val11.ItemDrop.m_itemData.m_shared.m_attack.m_attackAnimation = "emote_drink"; val11.ItemDrop.m_itemData.m_shared.m_consumeStatusEffect = _poozy.StatusEffect; val11.ItemDrop.m_itemData.m_shared.m_maxStackSize = 30; ItemManager.Instance.AddItem(val11); CustomItemConversion val12 = new CustomItemConversion((ConversionConfig)new FermenterConversionConfig { FromItem = "MushSwamp", ToItem = "BeerSwamp", ProducedItems = 10 }); ItemManager.Instance.AddItemConversion(val12); val = new ItemConfig(); val.Description = "Pine-tipped barley wort, needing time to become hearty forest beer."; val.Amount = 1; val.CraftingStation = "piece_MeadCauldron"; val.MinStationLevel = 1; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "Thistle", Amount = 5 }, new RequirementConfig { Item = "Mushroom", Amount = 5 } }; CustomItem val13 = new CustomItem("MushForest", "MeadBaseTasty", val); val13.ItemDrop.m_itemData.m_shared.m_name = "Forest Mush"; val13.ItemDrop.m_itemData.m_shared.m_consumeStatusEffect = _musty.StatusEffect; ItemManager.Instance.AddItem(val13); ServingTrayHelper.AddToServingTray(val5, "Mead"); val = new ItemConfig(); val.Description = "Hearty ale with pine and barley, best after a long hunt in the wilds."; val.Amount = 20; val.CraftingStation = ""; val.MinStationLevel = 1; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "SledgeCheat", Amount = 1 } }; CustomItem val14 = new CustomItem("BeerForest", "MeadTasty", val); val14.ItemDrop.m_itemData.m_shared.m_name = "Musky Beer"; val14.ItemDrop.m_itemData.m_shared.m_itemType = (ItemType)2; val14.ItemDrop.m_itemData.m_shared.m_ammoType = component.m_itemData.m_shared.m_ammoType; val14.ItemDrop.m_itemData.m_shared.m_attack.m_attackAnimation = "emote_drink"; val14.ItemDrop.m_itemData.m_shared.m_consumeStatusEffect = _musty.StatusEffect; val14.ItemDrop.m_itemData.m_shared.m_maxStackSize = 20; ItemManager.Instance.AddItem(val14); CustomItemConversion val15 = new CustomItemConversion((ConversionConfig)new FermenterConversionConfig { FromItem = "MushForest", ToItem = "BeerForest", ProducedItems = 10 }); ItemManager.Instance.AddItemConversion(val15); ServingTrayHelper.AddToServingTray(val14, "Mead"); val = new ItemConfig(); val.Description = "Thistle-bitten mush, steeped for the green fairy."; val.Amount = 1; val.CraftingStation = CraftingStations.MeadKetill; val.MinStationLevel = 1; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[4] { new RequirementConfig { Item = "Pukeberries", Amount = 10 }, new RequirementConfig { Item = "NeckTail", Amount = 5 }, new RequirementConfig { Item = "Honey", Amount = 5 }, new RequirementConfig { Item = "Guck", Amount = 1 } }; CustomItem val16 = new CustomItem("MushWyrmwood", "MeadBaseTasty", val); val16.ItemDrop.m_itemData.m_shared.m_name = "Wyrmwood Mush"; val16.ItemDrop.m_itemData.m_shared.m_description = "Bitter green spirit steeped in thistle and honey. Sip carefully."; ItemManager.Instance.AddItem(val16); CustomItem val17 = new CustomItem("WyrmwoodSpirit", "MeadSwimmer", new ItemConfig { Description = "Bitter green spirit steeped in thistle and honey. Sip carefully.", Amount = 20, CraftingStation = "", MinStationLevel = 1 }); val17.ItemDrop.m_itemData.m_shared.m_name = "Wyrmwood Spirit"; val17.ItemDrop.m_itemData.m_shared.m_itemType = (ItemType)2; val17.ItemDrop.m_itemData.m_shared.m_attack.m_attackAnimation = "emote_drink"; val17.ItemDrop.m_itemData.m_shared.m_consumeStatusEffect = _verydrunk.StatusEffect; val17.ItemDrop.m_itemData.m_shared.m_maxStackSize = 20; ItemManager.Instance.AddItem(val17); ItemManager.Instance.AddItemConversion(new CustomItemConversion((ConversionConfig)new FermenterConversionConfig { FromItem = "MushWyrmwood", ToItem = "WyrmwoodSpirit", ProducedItems = 10, Station = "fermenter" })); ServingTrayHelper.AddToServingTray(val17, "Mead"); val = new ItemConfig(); val.Name = "Rolled Thistle"; val.Description = "rolled up thistle"; val.CraftingStation = "piece_workbench"; val.MinStationLevel = 2; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "Thistle", Amount = 3 }, new RequirementConfig { Item = "Floam", Amount = 1 } }; ItemConfig val18 = val; CustomItem val19 = new CustomItem("RolledThistle", "Thistle", val18); val19.ItemDrop.m_itemData.m_shared.m_itemType = (ItemType)2; val19.ItemDrop.m_itemData.m_shared.m_name = "Rolled Thistle"; val19.ItemDrop.m_itemData.m_shared.m_maxStackSize = 20; val19.ItemDrop.m_itemData.m_shared.m_weight = 0.5f; val19.ItemDrop.m_itemData.m_shared.m_consumeStatusEffect = _smokedthistle.StatusEffect; ItemManager.Instance.AddItem(val19); val = new ItemConfig(); val.Description = "A swirl of blue eyes and honey, waiting to find the wind."; val.Amount = 1; val.CraftingStation = "piece_MeadCauldron"; val.MinStationLevel = 1; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[3] { new RequirementConfig { Item = "GreydwarfEye", Amount = 10 }, new RequirementConfig { Item = "Gloam", Amount = 1 }, new RequirementConfig { Item = "Honey", Amount = 5 } }; CustomItem val20 = new CustomItem("MushWayfinder", "MeadBaseSwimmer", val); val20.ItemDrop.m_itemData.m_shared.m_name = "Wayfinder's Mead Base"; ItemManager.Instance.AddItem(val20); val = new ItemConfig(); val.Description = "It grants even a novice the instincts of an expert sailor."; val.Amount = 20; val.CraftingStation = ""; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "SledgeCheat", Amount = 1 } }; CustomItem val21 = new CustomItem("MeadModer", "MeadLightfoot", val); val21.ItemDrop.m_itemData.m_shared.m_name = "Wayfinder's Brew"; val21.ItemDrop.m_itemData.m_shared.m_itemType = (ItemType)2; val21.ItemDrop.m_itemData.m_shared.m_attack.m_attackAnimation = "emote_drink"; SharedData shared = val21.ItemDrop.m_itemData.m_shared; CustomStatusEffect seModer = _seModer; shared.m_consumeStatusEffect = ((seModer != null) ? seModer.StatusEffect : null); val21.ItemDrop.m_itemData.m_shared.m_maxStackSize = 20; ItemManager.Instance.AddItem(val21); CustomItemConversion val22 = new CustomItemConversion((ConversionConfig)new FermenterConversionConfig { FromItem = "MushWayfinder", ToItem = "MeadModer", ProducedItems = 10 }); ItemManager.Instance.AddItemConversion(val22); ServingTrayHelper.AddToServingTray(val21, "Mead"); val = new ItemConfig(); val.Description = "A dead man's key. The bones of a pirate. A bit of honey to dilute the horror of the pot."; val.Amount = 1; val.CraftingStation = "piece_MeadCauldron"; val.MinStationLevel = 1; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[3] { new RequirementConfig { Item = "CryptKey", Amount = 1 }, new RequirementConfig { Item = "Honey", Amount = 5 }, new RequirementConfig { Item = "BoneFragments", Amount = 10 } }; CustomItem val23 = new CustomItem("MushDowser", "MeadBaseLightFoot", val); val23.ItemDrop.m_itemData.m_shared.m_name = "Dead Man Ale Base"; ItemManager.Instance.AddItem(val23); val = new ItemConfig(); val.Description = "A heavy, metallic liquid. It causes your blood to pulse when standing over secret treasures."; val.Amount = 20; val.CraftingStation = ""; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "SledgeCheat", Amount = 1 } }; CustomItem val24 = new CustomItem("MeadWishbone", "MeadEitrLingering", val); val24.ItemDrop.m_itemData.m_shared.m_name = "Dead Man's Ale"; val24.ItemDrop.m_itemData.m_shared.m_itemType = (ItemType)2; val24.ItemDrop.m_itemData.m_shared.m_attack.m_attackAnimation = "emote_drink"; SharedData shared2 = val24.ItemDrop.m_itemData.m_shared; CustomStatusEffect seWishbone = _seWishbone; shared2.m_consumeStatusEffect = ((seWishbone != null) ? seWishbone.StatusEffect : null); val24.ItemDrop.m_itemData.m_shared.m_maxStackSize = 20; ItemManager.Instance.AddItem(val24); CustomItemConversion val25 = new CustomItemConversion((ConversionConfig)new FermenterConversionConfig { FromItem = "MushDowser", ToItem = "MeadWishbone", ProducedItems = 10 }); ItemManager.Instance.AddItemConversion(val25); ServingTrayHelper.AddToServingTray(val24, "Mead"); } catch (Exception ex) { ZLog.LogError((object)"error vrp custom materials"); if (VRPMod.DebugMode()) { ZLog.LogError((object)ex.Message); } } finally { PrefabManager.OnPrefabsRegistered -= AddCustomDrinks; } } } public class ExploitDisabled { [HarmonyPatch(typeof(Terminal), "TryRunCommand")] private class Terminal_TryRunCommand_Patch { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool Prefix(string text) { string text2 = text.Trim().ToLower(); if (text2.StartsWith("bind ") || text2 == "bind" || text2.StartsWith("alias ") || text2 == "alias") { if ((Object)(object)ZNet.instance != (Object)null && ClientPatches.isAdmin()) { return true; } Console.instance.Print("Access Denied: Only Admins can use bind commands."); return false; } return true; } } } public class HiddenDiscoveriesPatch { [HarmonyPatch(typeof(MessageHud), "QueueUnlockMsg")] private class MessageHud_QueueUnlockMsg_Patch { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool Prefix(string topic, string description) { ZLog.Log((object)("unlocked:" + topic + ":" + description)); return false; } } [HarmonyPatch(typeof(Menu), "OnCurrentPlayers")] private class Menu_OnCurrentPlayers_Patch { private static bool Prefix() { if ((Object)(object)ZNet.instance != (Object)null && ClientPatches.isAdmin()) { return true; } if ((Object)(object)Player.m_localPlayer != (Object)null) { ((Character)Player.m_localPlayer).Message((MessageType)2, "Only Admins can view the Player List.", 0, (Sprite)null); } return false; } } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [Nullable(0)] public static class ItemTypeHash { public static readonly HashSet DurabilityPatchTypes = new HashSet { (ItemType)7, (ItemType)11, (ItemType)6, (ItemType)17, (ItemType)5, (ItemType)3, (ItemType)14, (ItemType)22, (ItemType)19, (ItemType)4 }; public static readonly HashSet WeaponTypes = new HashSet { (ItemType)3, (ItemType)14, (ItemType)4 }; public static readonly HashSet ArmorTypes = new HashSet { (ItemType)7, (ItemType)11, (ItemType)6, (ItemType)17, (ItemType)18 }; } public static class MagicAddition { public static void RegisterMagicChanges() { //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Expected O, but got Unknown //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00f8: Expected O, but got Unknown try { ZLog.Log((object)"VRP: Registering Magic Item Recipes..."); foreach (KeyValuePair magicItem in RecipeData.MagicItems) { if ((Object)(object)Cache.GetPrefab(magicItem.Value.Item) == (Object)null) { ZLog.LogWarning((object)("VRP: Skipping recipe '" + magicItem.Key + "' because target item '" + magicItem.Value.Item + "' was not found. (Missing Dependency?)")); continue; } CustomRecipe val = new CustomRecipe(new RecipeConfig { Name = magicItem.Key, Item = magicItem.Value.Item, Amount = magicItem.Value.Amount, Requirements = ((IEnumerable>)magicItem.Value.Requirements).Select((Func, RequirementConfig>)((KeyValuePair r) => new RequirementConfig { Item = r.Key, Amount = r.Value })).ToArray() }); ItemManager.Instance.AddRecipe(val); } } catch (Exception ex) { ZLog.LogError((object)"error creating dance bomb"); if (VRPMod.DebugMode()) { ZLog.LogError((object)ex.ToString()); } } finally { PrefabManager.OnPrefabsRegistered -= RegisterMagicChanges; } } } public class MagicOverridePatch { [HarmonyPatch(typeof(Humanoid), "EquipItem")] public static class MyMagicOverridePatch { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [HarmonyPriority(800)] private static bool Prefix(Humanoid __instance, ItemData item, ref bool __result) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) Scene activeScene = SceneManager.GetActiveScene(); if (((Scene)(ref activeScene)).name != "main") { return true; } if ((Object)(object)__instance == (Object)null || !((Character)__instance).IsPlayer() || item == null) { return true; } if (ClientPatches.isAdmin()) { __result = true; return true; } if (item.m_shared.m_ammoType.Contains("ammo_spells")) { int num = 0; ItemData helmetItem = __instance.m_helmetItem; if (helmetItem != null && helmetItem.m_shared.m_eitrRegenModifier > 0f) { num++; } ItemData chestItem = __instance.m_chestItem; if (chestItem != null && chestItem.m_shared.m_eitrRegenModifier > 0f) { num++; } ItemData legItem = __instance.m_legItem; if (legItem != null && legItem.m_shared.m_eitrRegenModifier > 0f) { num++; } ItemData shoulderItem = __instance.m_shoulderItem; if (shoulderItem != null && shoulderItem.m_shared.m_eitrRegenModifier > 0f) { num++; } if (num < 3) { ((Character)__instance).Message((MessageType)2, "Your clothes are not enriched with enough eitr!", 0, (Sprite)null); __result = false; return false; } __result = true; } return true; } } } public class ClientPatches { [HarmonyPatch(typeof(GameVersion), "ToString")] private class fixver { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(GameVersion __instance, ref string __result) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0001: Unknown result type (might be due to invalid IL or missing references) if (__instance == Version.CurrentVersion) { __result += "-vrp2.1.2"; } } } [HarmonyPatch(typeof(FejdStartup), "ShowCharacterSelection")] public static class checkforbadmods2 { private static void Postfix() { if (!VRPMod.DebugMode()) { return; } StringBuilder stringBuilder = new StringBuilder("Mods Installed:\n"); foreach (KeyValuePair pluginInfo in Chainloader.PluginInfos) { string text = pluginInfo.Key.ToString().ToUpperInvariant(); string text2 = $"{pluginInfo.Value.Metadata.Name} - {pluginInfo.Value.Metadata.Version}"; stringBuilder.AppendLine(text2 + " : " + text); } ZLog.Log((object)stringBuilder.ToString()); } } [HarmonyPatch(typeof(ZNet), "RPC_ClientHandshake")] public static class checkforbadmods { private static void Postfix() { //IL_0235: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)ZNet.instance == (Object)null || ZNet.instance.IsServer()) { return; } ZLog.Log((object)"[VRP] Running Mod Security Check..."); HashSet hashSet = new HashSet(Chainloader.PluginInfos.Keys.Select((string k) => k.ToUpperInvariant()), StringComparer.OrdinalIgnoreCase); HashSet allowed = new HashSet(StringComparer.OrdinalIgnoreCase); ModData.RequiredMods.ForEach([<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] (string m) => { allowed.Add(m.ToUpperInvariant()); }); ModData.OptionalMods.ForEach([<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] (string m) => { allowed.Add(m.ToUpperInvariant()); }); if (isAdmin()) { ModData.AdminMods.ForEach([<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] (string m) => { allowed.Add(m.ToUpperInvariant()); }); } bool flag = false; List list = new List(); List list2 = new List(); foreach (string requiredMod in ModData.RequiredMods) { if (!hashSet.Contains(requiredMod.ToUpperInvariant())) { list.Add(requiredMod); flag = true; } } foreach (string item in hashSet) { if (!allowed.Contains(item)) { list2.Add(item); flag = true; } } if (flag) { Game instance = Game.instance; object obj; if (instance == null) { obj = null; } else { PlayerProfile playerProfile = instance.GetPlayerProfile(); obj = ((playerProfile != null) ? playerProfile.GetName() : null); } if (obj == null) { Player localPlayer = Player.m_localPlayer; obj = ((localPlayer != null) ? localPlayer.GetPlayerName() : null) ?? "unknown"; } string player = (string)obj; if (list.Count > 0) { string text = "Missing required mods: " + string.Join(", ", list); ZLog.LogError((object)text); ServerPatches.ServerModerationLog(player, "", "", "modpack", "", "", 0, text); } if (list2.Count > 0) { string text2 = "Unauthorized mods detected: " + string.Join(", ", list2); ZLog.LogError((object)text2); ServerPatches.ServerModerationLog(player, "", "", "modpack", "", "", 0, text2); } ZNet.m_connectionStatus = (ConnectionStatus)12; } } } [HarmonyPatch(typeof(Player), "UpdateBiome")] public static class Patch_Player_UpdateBiome_ProgressionGate { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [HarmonyPostfix] private static void Postfix(Player __instance) { if (!((Object)(object)__instance != (Object)(object)Player.m_localPlayer)) { ProgressionPatch.ApplySE(); } } } [HarmonyPatch(typeof(Player), "UpdateBiome")] public class Patch_Player_UpdateBiome { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Finalizer(Player __instance, Exception __exception) { if (__exception is NullReferenceException) { ZLog.LogError((object)$"[Patch_Player_UpdateBiome] Finalizer caught NullReferenceException:\n{__exception}"); } } } [HarmonyPatch(typeof(EnemyHud), "TestShow")] public static class hudfix { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool Prefix(ref Character c, ref EnemyHud __instance, ref bool __result) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) __result = false; float num = Vector3.SqrMagnitude(((Component)c).transform.position - __instance.m_refPoint); if (c.IsBoss() && num < __instance.m_maxShowDistanceBoss * __instance.m_maxShowDistanceBoss) { __result = ((Component)c).GetComponent().IsAlerted(); } else if (c.IsPlayer() && !isAdmin()) { float num2 = 2f; __result = !c.IsCrouching() && num < num2 * num2; __result = false; } else if (num < 100f) { __result = true; } return false; } } [HarmonyPatch(typeof(WearNTear), "RPC_Damage")] public static class DamageWard { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool Prefix(long sender, HitData hit, WearNTear __instance) { //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Expected O, but got Unknown //IL_00b3: Unknown result type (might be due to invalid IL or missing references) bool result = true; if (hit != null && (Object)(object)hit.GetAttacker() != (Object)null && hit.GetAttacker().IsPlayer() && (Object)(object)((Component)__instance).gameObject != (Object)null) { Player val = (Player)hit.GetAttacker(); if (((Object)((Component)__instance).gameObject).name.Contains("chest") || ((Object)((Component)__instance).gameObject).name.Contains("guard_stone") || ((Object)((Component)__instance).gameObject).name.Contains("vrp_ward")) { foreach (PrivateArea allArea in PrivateArea.m_allAreas) { if (allArea.IsEnabled() && allArea.IsInside(hit.m_point, 1f)) { bool flag = isAdmin(); string raw = ((Object)((Component)__instance).gameObject).name + " damaged | " + allArea.m_piece.m_creator + " creator | " + val.GetPlayerID() + " damage by"; SendModerationLog(((Character)val).GetHoverName(), "", ((Object)((Component)__instance).gameObject).name, "damaged", allArea.m_piece.m_creator.ToString(), raw, "", flag ? 1 : 0); if (flag) { result = true; } else if (allArea.m_piece.m_creator != val.GetPlayerID() && !allArea.IsPermitted(val.GetPlayerID())) { allArea.FlashShield(false); result = false; } } } } } return result; } } [Nullable(0)] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [HarmonyPatch(typeof(PrivateArea), "Awake")] private class wardrange { private static bool Prefix(ref PrivateArea __instance) { if (!Object.op_Implicit((Object)(object)__instance)) { return true; } Piece component = ((Component)__instance).gameObject.GetComponent(); float radius = 5f; if ((Object)(object)component != (Object)null) { radius = component.m_name switch { "WardAdmin" => 100f, "WardGloam" => 40f, "WardFloam" => 25f, "WardSmall" => 5f, "WardFarmer" => 35f, _ => 25f, }; } __instance.m_radius = radius; return true; } private static void Postfix(ref PrivateArea __instance) { //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) if (!Object.op_Implicit((Object)(object)__instance)) { return; } if ((Object)(object)__instance.m_areaMarker != (Object)null) { __instance.m_areaMarker.m_radius = __instance.m_radius; } if (__instance.m_flashEffect != null && __instance.m_flashEffect.m_effectPrefabs != null && __instance.m_flashEffect.m_effectPrefabs.Length != 0) { ParticleSystem componentInChildren = ((Component)__instance.m_flashEffect.m_effectPrefabs[0].m_prefab.transform).GetComponentInChildren(); if ((Object)(object)componentInChildren != (Object)null) { MainModule main = componentInChildren.main; ((MainModule)(ref main)).startSize = MinMaxCurve.op_Implicit(__instance.m_radius * 2f); } } } } [HarmonyPatch(typeof(PrivateArea), "GetHoverText")] private class wardText { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref string __result, ref PrivateArea __instance) { if ((Object)(object)Player.m_localPlayer == (Object)null || string.IsNullOrWhiteSpace(__result)) { return; } string value = ((Character)Player.m_localPlayer).GetHoverName().ToUpperInvariant(); string text = __result.ToUpperInvariant(); long @long = __instance.m_nview.GetZDO().GetLong("decaytimer", 123L); DateTime? dateTime = null; if (@long != 0L && @long != 123) { dateTime = new DateTime(@long, DateTimeKind.Utc); } DateTime utcNow = DateTime.UtcNow; if (IsAdminWard(__instance)) { __result = "ADMIN WARD" + Environment.NewLine + "[BUILD/DESTRUCTION NOT ALLOWED]" + Environment.NewLine + "[LOOTING BOXES IS ALLOWED (open ticket)]"; return; } if (!isAdmin() && !text.Contains(value)) { if (__instance.IsEnabled()) { __result = "unauthorized - active"; } else if (!IsAdminWard(__instance) && dateTime.HasValue && utcNow > dateTime.Value.AddDays(10.0)) { dateTime.Value.ToLocalTime(); __result = "unauthorized - dead" + Environment.NewLine + text + "'s ward is dead" + Environment.NewLine + "[RAID ALLOWED (open ticket)]"; } else { __result = "unauthorized - deactivated" + Environment.NewLine + "[RAID NOT ALLOWED]" + Environment.NewLine + " press e to add yourself to this ward"; } return; } if (!IsAdminWard(__instance) && dateTime.HasValue) { DateTime dateTime2 = dateTime.Value.AddDays(10.0); DateTime dateTime3 = dateTime2.ToLocalTime(); TimeSpan timeSpan = dateTime2 - DateTime.UtcNow; if (timeSpan < TimeSpan.Zero) { timeSpan = TimeSpan.Zero; } string text2 = ((timeSpan.TotalDays >= 1.0) ? $"{Math.Floor(timeSpan.TotalDays)}d {timeSpan.Hours}h" : ((timeSpan.TotalHours >= 1.0) ? $"{Math.Floor(timeSpan.TotalHours)}h {timeSpan.Minutes}m" : $"{timeSpan.Minutes}m")); __result = __result + "\n[" + dateTime3.ToShortDateString() + " " + dateTime3.ToShortTimeString() + "] expires • " + text2 + " left" + Environment.NewLine; } Piece component = ((Component)__instance).gameObject.GetComponent(); if ((Object)(object)component != (Object)null) { if (component.m_name == "WardGloam") { __result += "use 5 gloam to recharge this ward!"; } if (component.m_name == "WardFloam" || component.m_name == "WardSmall" || component.m_name == "WardFarmer") { __result += "use 5 floam to recharge this ward!"; } } } } [HarmonyPatch(typeof(PrivateArea), "UseItem")] private class wardupdate { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(Humanoid user, ItemData item, ref PrivateArea __instance, ref bool __result) { Piece component = ((Component)__instance).gameObject.GetComponent(); if (!((Object)(object)component != (Object)null)) { return; } if (component.m_name == "WardGloam" && item.m_shared.m_name == "Gloam") { if (__instance.m_nview.IsValid()) { Inventory inventory = user.GetInventory(); if (inventory.CountItems(item.m_shared.m_name, -1, true) >= 5) { ((Character)user).Message((MessageType)2, "the ward is recharged", 0, (Sprite)null); inventory.RemoveItem(item, 5); __instance.m_nview.GetZDO().Set("decaytimer", DateTime.UtcNow.Ticks); } } __result = true; } if ((!(component.m_name == "WardFloam") && !(component.m_name == "WardSmall") && !(component.m_name == "WardFarmer") && !(component.m_name == "Ward")) || !(item.m_shared.m_name == "Floam")) { return; } if (__instance.m_nview.IsValid()) { Inventory inventory2 = user.GetInventory(); if (inventory2.CountItems(item.m_shared.m_name, -1, true) >= 5) { ((Character)user).Message((MessageType)2, "the ward is recharged", 0, (Sprite)null); inventory2.RemoveItem(item, 5); __instance.m_nview.GetZDO().Set("decaytimer", DateTime.UtcNow.Ticks); } } __result = true; } } [HarmonyPatch(typeof(Pickable), "Interact")] private static class Ward_Pickable_Interact { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool Prefix(Pickable __instance, Humanoid character, bool repeat, bool alt, ref bool __result) { //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)__instance == (Object)null || (Object)(object)character == (Object)null) { return true; } if (isAdmin()) { return true; } Player val = (Player)(object)((character is Player) ? character : null); if ((Object)(object)val == (Object)null) { if (VRPMod.DebugMode()) { ZLog.Log((object)"Player is null for pickable check"); } return true; } long playerID = val.GetPlayerID(); Vector3 position = ((Component)__instance).transform.position; foreach (PrivateArea allArea in PrivateArea.m_allAreas) { if ((Object)(object)allArea == (Object)null || !allArea.IsEnabled() || !allArea.IsInside(position, 0f)) { continue; } if (IsAdminWard(allArea)) { if (VRPMod.DebugMode()) { ZLog.Log((object)"Player is in admin ward for pickable check"); } return true; } if (allArea.m_piece.m_creator == val.GetPlayerID()) { if (VRPMod.DebugMode()) { ZLog.Log((object)"Player is owner of this ward for pickable check"); } return true; } if (allArea.IsPermitted(playerID)) { if (VRPMod.DebugMode()) { ZLog.Log((object)"Player is allowed in this ward for pickable check"); } return true; } if (!IsFarmerWard(allArea)) { continue; } try { allArea.FlashShield(false); } catch { } ((Character)character).Message((MessageType)2, MessageData.GetFarmerWardMessage(), 0, (Sprite)null); if (VRPMod.DebugMode()) { ZLog.Log((object)"Player is not allowed for pickable check"); string text = string.Join("; ", from kv in allArea.GetPermittedPlayers() select $"{kv.Key}:{kv.Value}"); ZLog.Log((object)("Permitted players: " + text)); ZLog.Log((object)$"Current player: {playerID}"); } __result = __instance.m_useInteractAnimation; return false; } return true; } } [HarmonyPatch(typeof(PrivateArea), "Interact")] public static class wardinteract { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool Prefix(ref Humanoid human, ref bool hold, PrivateArea __instance) { if ((isAdmin() || __instance.IsPermitted(Player.m_localPlayer.GetPlayerID())) && !hold) { __instance.m_nview.InvokeRPC("ToggleEnabled", new object[1] { __instance.m_piece.m_creator }); return false; } return true; } } [HarmonyPatch(typeof(PrivateArea), "CheckAccess")] public static class wardaccess { private static void Postfix(Vector3 point, float radius, bool flash, ref bool __result) { if (isAdmin()) { __result = true; } if (!__result && t_DoorAccessBypass) { __result = true; } } } [HarmonyPatch(typeof(Container), "CheckAccess")] public static class AdminWardContainerAccess { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(Container __instance, long playerID, ref bool __result) { //IL_0014: Unknown result type (might be due to invalid IL or missing references) if (!__result && (Object)(object)__instance != (Object)null && IsInsideEnabledAdminWard(((Component)__instance).transform.position)) { __result = true; } } } [HarmonyPatch(typeof(Container), "GetHoverText")] public static class AdminWardContainerHover { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(Container __instance, ref string __result) { //IL_0029: Unknown result type (might be due to invalid IL or missing references) if (!string.IsNullOrEmpty(__result) && !((Object)(object)__instance == (Object)null) && __result.IndexOf("$piece_noaccess", StringComparison.OrdinalIgnoreCase) >= 0 && IsInsideEnabledAdminWard(((Component)__instance).transform.position)) { __result = __result.Replace("\n$piece_noaccess", string.Empty).Replace("$piece_noaccess", string.Empty); } } } [HarmonyPatch(typeof(Door), "Interact")] private static class AdminWardDoorInteract { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Prefix(Door __instance, Humanoid character, bool hold, bool alt) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) try { if (character is Player && IsInsideEnabledAdminWard(((Component)__instance).transform.position)) { t_DoorAccessBypass = true; } } catch (Exception ex) { ZLog.LogWarning((object)ex.Message); } } private static void Postfix() { t_DoorAccessBypass = false; } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [Nullable(0)] [HarmonyPatch(typeof(PrivateArea), "UpdateStatus")] public static class WardStatus { [HarmonyPriority(0)] [HarmonyPostfix] private static void Postfix(PrivateArea __instance) { //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) try { if (!Object.op_Implicit((Object)(object)__instance)) { return; } ZNetView nview = __instance.m_nview; if (!Object.op_Implicit((Object)(object)nview)) { ZLog.LogWarning((object)"[WardStatusPatch] m_nview missing on postfix."); } else { if (!nview.IsValid() || !nview.IsOwner() || IsAdminWardSafe(__instance)) { return; } ZDO zDO = nview.GetZDO(); if (zDO == null) { ZLog.LogWarning((object)"[WardStatusPatch] ZDO is null on postfix."); return; } long @long = zDO.GetLong("decaytimer", 0L); string text = SafeGetCreatorName(__instance); Vector3 val; try { val = ((!Object.op_Implicit((Object)(object)__instance) || !Object.op_Implicit((Object)(object)((Component)__instance).transform)) ? zDO.GetPosition() : ((Component)__instance).transform.position); } catch { val = zDO.GetPosition(); } string text2 = $"pos=({val.x:0.0}, {val.y:0.0}, {val.z:0.0})"; string name = ((Object)((Component)__instance).gameObject).name; name = name.Replace("(Clone)", "").Trim(); if (@long == 0L) { long ticks = DateTime.UtcNow.Ticks; if (Object.op_Implicit((Object)(object)nview) && nview.IsValid()) { zDO.Set("decaytimer", ticks); if (Object.op_Implicit((Object)(object)nview) && nview.IsValid()) { nview.InvokeRPC(ZNetView.Everybody, "RPC_MarkDirty", Array.Empty()); } SendModerationLog(text, "", name, "new ward", text, text2, "pos: " + text2); if (VRPMod.DebugMode()) { ZLog.Log((object)(name + ", \"new ward\", " + text + ", " + text2)); } } return; } DateTime dateTime; try { dateTime = new DateTime(@long, DateTimeKind.Utc); } catch { long ticks2 = DateTime.UtcNow.Ticks; zDO.Set("decaytimer", ticks2); if (Object.op_Implicit((Object)(object)nview) && nview.IsValid()) { nview.InvokeRPC(ZNetView.Everybody, "RPC_MarkDirty", Array.Empty()); } return; } if (!(DateTime.UtcNow > dateTime.AddDays(10.0)) || !Object.op_Implicit((Object)(object)__instance) || !Object.op_Implicit((Object)(object)nview) || !nview.IsValid()) { return; } bool flag = false; try { flag = __instance.IsEnabled(); } catch { flag = false; } if (flag) { string raw = "Expired on " + dateTime.ToLongDateString() + " at " + DateTime.UtcNow.ToLongTimeString() + " UTC " + text2; SendModerationLog(text, "", name, "ward expired", text, raw, text2); try { __instance.SetEnabled(false); } catch { } if (Object.op_Implicit((Object)(object)nview) && nview.IsValid()) { nview.InvokeRPC(ZNetView.Everybody, "RPC_MarkDirty", Array.Empty()); } } } } catch (Exception arg) { ZLog.LogError((object)$"[WardStatusPatch] Exception in postfix: {arg}"); } } private static bool IsAdminWardSafe(PrivateArea pa) { try { if (!Object.op_Implicit((Object)(object)pa)) { return false; } return IsAdminWard(pa); } catch { return false; } } private static string SafeGetCreatorName(PrivateArea pa) { try { if (!Object.op_Implicit((Object)(object)pa)) { return string.Empty; } return pa.GetCreatorName() ?? string.Empty; } catch { return string.Empty; } } } [HarmonyPatch(typeof(Container), "CheckAccess")] public static class ContainerAccessPatch { private static void Postfix(long playerID, ref bool __result) { if (isAdmin(Player.GetPlayer(playerID).GetPlayerName())) { __result = true; } } } [HarmonyPatch(typeof(ItemStand), "Interact")] private class standFix { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool Prefix(Humanoid user, bool hold, ItemStand __instance) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) return PrivateArea.CheckAccess(((Component)__instance).transform.position, 0f, true, false); } } [HarmonyPatch(typeof(ConsoleCommand), "RunAction")] public static class cheatlogg { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ConsoleEventArgs args, ConsoleCommand __instance) { try { if ((Object)(object)Player.m_localPlayer == (Object)null) { return; } string text = __instance.Command?.ToLower(); if (!string.IsNullOrWhiteSpace(text) && !CommandData.OmitCommands.Contains(text)) { string playerName = Player.m_localPlayer.GetPlayerName(); string steamId = GetSteamId(); int num = (isAdmin() ? 1 : 0); if (num == 0 || text.Equals("spawn", StringComparison.OrdinalIgnoreCase) || text.StartsWith("spawn ", StringComparison.OrdinalIgnoreCase)) { SendModerationLog(playerName, steamId, "", "CHEAT COMMAND", "", "", text, num); } } } catch (Exception ex) { if (VRPMod.DebugMode()) { ZLog.LogError((object)ex.Message); } } } } [HarmonyPatch(typeof(EnvMan), "CanSleep")] public static class cansleepyes { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(EnvMan __instance, bool __result) { __result = true; } } [HarmonyPatch(typeof(Humanoid), "EquipItem")] public static class PlayerEquip { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ItemData item, bool triggerEquipEffects, ref Humanoid __instance) { playerEqp(ref item, ref __instance); } } [HarmonyPatch(typeof(Humanoid), "UnequipItem")] public static class PlayerUnEquip { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ItemData item, bool triggerEquipEffects, ref Humanoid __instance) { playerEqp(ref item, ref __instance); } } [HarmonyPatch(typeof(Player), "ConsumeItem")] public static class ConsumeLog { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(Inventory inventory, ItemData item, ref bool __result, ref Player __instance) { if (__result && (Object)(object)__instance != (Object)null && item != null && item.m_shared != null && ((Character)__instance).m_nview.IsValid()) { ((Character)__instance).IsOwner(); if (!isAdmin()) { string creator = ((item.m_crafterID == 0L) ? " | uncrafted | " : (" | crafted by | " + item.m_crafterName + " ")); SendModerationLog(__instance.GetPlayerName(), "", item.m_shared.m_name, "consume", creator, ""); } } } } [HarmonyPatch(typeof(Sign), "SetText")] public static class SignText { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(string text, Sign __instance) { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) if (!isAdmin()) { string text2 = ((Component)__instance).transform.position.x + " "; text2 = text2 + ((Component)__instance).transform.position.z + " "; text2 += ((Component)__instance).transform.position.y; SendModerationLog(Player.m_localPlayer.GetPlayerName(), "", text, "sign_text", "", text2); } } } [HarmonyPatch(typeof(TeleportWorld), "SetText")] public static class TeleportText { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(string text, TeleportWorld __instance) { SendModerationLog(Player.m_localPlayer.GetPlayerName(), "", text, "teleport_text", "", ""); } } [HarmonyPatch(typeof(UserInfo), "GetDisplayName")] [HarmonyPriority(500)] public static class Patch_UserInfo_GetDisplayName { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Prefix(ref UserInfo __instance) { Player val = null; List s_players = Player.s_players; for (int i = 0; i < s_players.Count; i++) { if (s_players[i].GetPlayerName().Equals(__instance.Name)) { val = s_players[i]; break; } } if ((Object)(object)val == (Object)null || (Object)(object)((Character)val).m_nview == (Object)null) { return; } ZDO zDO = ((Character)val).m_nview.GetZDO(); if (zDO != null) { bool @bool = zDO.GetBool("isAnonymous", false); string text = zDO.GetString("secretName", "???"); if (string.IsNullOrWhiteSpace(text)) { text = "???"; } if (@bool) { __instance.Name = text; } } } } [HarmonyPatch(typeof(Chat), "InputText")] public static class ChatText { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref Chat __instance) { //IL_01cb: Unknown result type (might be due to invalid IL or missing references) //IL_01d0: Unknown result type (might be due to invalid IL or missing references) //IL_01d7: Unknown result type (might be due to invalid IL or missing references) //IL_01e8: Unknown result type (might be due to invalid IL or missing references) //IL_01f9: Unknown result type (might be due to invalid IL or missing references) _ = ((TMP_InputField)((Terminal)__instance).m_input).text; if (!((Object)(object)Chat.instance != (Object)null) || !((Object)(object)((Terminal)Chat.instance).m_input != (Object)null) || string.IsNullOrWhiteSpace(((TMP_InputField)((Terminal)Chat.instance).m_input).text)) { return; } bool flag = true; try { if (((TMP_InputField)((Terminal)__instance).m_input).text.StartsWith("/bc ")) { SendBroadcast(((TMP_InputField)((Terminal)__instance).m_input).text.Substring(4)); flag = false; } if (((TMP_InputField)((Terminal)__instance).m_input).text.StartsWith("/sleepers") && Object.op_Implicit((Object)(object)Player.m_localPlayer)) { int hash = ZSyncAnimation.GetHash("attach_bed"); bool @bool = ((Character)Player.m_localPlayer).m_zanim.m_animator.GetBool(hash); ((Character)Player.m_localPlayer).m_zanim.SetBool("attach_bed", !@bool); flag = false; } if (((TMP_InputField)((Terminal)__instance).m_input).text.StartsWith("/wake") && Object.op_Implicit((Object)(object)Player.m_localPlayer)) { ZSyncAnimation.GetHash("attach_bed"); ((Character)Player.m_localPlayer).m_zanim.SetBool("attach_bed", false); flag = false; } if (((TMP_InputField)((Terminal)__instance).m_input).text.StartsWith("/vomit") && Object.op_Implicit((Object)(object)Player.m_localPlayer)) { ((Character)Player.m_localPlayer).m_seman.AddStatusEffect(StringExtensionMethods.GetStableHashCode("Puke"), false, 0, 0f); flag = false; } if (((TMP_InputField)((Terminal)__instance).m_input).text.StartsWith("/reporthole") && Object.op_Implicit((Object)(object)Player.m_localPlayer)) { string text = ((TMP_InputField)((Terminal)__instance).m_input).text; string text2 = ""; if (text.Length > 11) { text2 = text.Substring(11).Trim(); } Vector3 position = ((Component)Player.m_localPlayer).transform.position; string text3 = $"goto {Mathf.RoundToInt(position.x)} {Mathf.RoundToInt(position.z)} {Mathf.RoundToInt(position.y)}"; string text4 = "Hole reported at [" + text3 + "]"; if (!string.IsNullOrEmpty(text2)) { text4 = text4 + " - " + text2; } SendModerationLog(GetDisplayName(Player.m_localPlayer.GetPlayerName()), "", "", "reporthole", "", text4, text3, 1); flag = false; } if (isAdmin()) { flag = false; } } catch (Exception) { ZLog.LogError((object)"failed text processing"); } if (flag) { SendModerationLog(GetDisplayName(Player.m_localPlayer.GetPlayerName()), "", "", "chat_text", Player.m_localPlayer.GetPlayerName(), "", ((TMP_InputField)((Terminal)Chat.instance).m_input).text); } } } [HarmonyPatch(typeof(Player), "SetIntro")] public static class SpawnLog { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(bool intro, Player __instance) { if (!ZNet.instance.IsServer() && (Object)(object)__instance != (Object)null && ((Character)__instance).m_nview.IsValid() && ZRoutedRpc.instance != null) { ZLog.LogWarning((object)("FRESH " + __instance.GetPlayerName())); SendModerationLog(__instance.GetPlayerName(), "", "", "Fresh", "", ""); } } } [HarmonyPatch(typeof(Chat), "Awake")] private class textinputfix { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref Chat __instance) { __instance.m_worldTextTTL = 20f; ((TMP_InputField)((Terminal)__instance).m_input).characterLimit = 300; __instance.m_hideDelay = 10f; Graphic[] componentsInChildren = ((Component)((Terminal)__instance).m_chatWindow).GetComponentsInChildren(); for (int i = 0; i < componentsInChildren.Length; i++) { componentsInChildren[i].raycastTarget = false; } } } [HarmonyPatch(typeof(Talker), "Awake")] private class talkerrange { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref Talker __instance) { __instance.m_normalDistance = 25f; __instance.m_visperDistance = 5f; __instance.m_shoutDistance = 150f; } } [HarmonyPatch(typeof(Chat), "SendText")] private class notglobalshouts { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool Prefix(ref Type type, ref string text) { if (Object.op_Implicit((Object)(object)Player.m_localPlayer)) { ((Component)Player.m_localPlayer).GetComponent().Say(type, text); } return false; } } [HarmonyPatch(typeof(Chat), "GetShoutWorldTexts")] private class nominimapshouts { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref List texts) { texts.Clear(); } } [HarmonyPatch(typeof(Chat), "UpdateWorldTextField")] private static class nopings { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref WorldTextInstance wt) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 if ((int)wt.m_type == 3) { ((TMP_Text)wt.m_textMeshField).text = ""; wt.m_text = ""; } } } [HarmonyPatch(typeof(Player), "FixedUpdate")] private class playerposty { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(Player __instance) { //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_01a0: Unknown result type (might be due to invalid IL or missing references) //IL_01db: Unknown result type (might be due to invalid IL or missing references) //IL_0303: Unknown result type (might be due to invalid IL or missing references) //IL_03b8: Unknown result type (might be due to invalid IL or missing references) PumpModerationLog(Time.deltaTime); if ((Object)(object)__instance == (Object)null || (Object)(object)((Character)__instance).m_nview == (Object)null || !((Character)__instance).m_nview.IsValid() || !((Character)__instance).m_nview.IsOwner() || (Object)(object)Player.m_localPlayer == (Object)null || (Object)(object)__instance != (Object)(object)Player.m_localPlayer) { return; } if ((Object)(object)InventoryGui.instance != (Object)null && (Object)(object)InventoryGui.instance.m_pvp != (Object)null) { InventoryGui.instance.m_pvp.isOn = true; } if (!((Character)__instance).IsPVPEnabled()) { __instance.SetPVP(true); } if (((Character)__instance).m_seman == null) { return; } int stableHashCode = StringExtensionMethods.GetStableHashCode("Poozy"); ((Character)__instance).m_swimDepth = (((Character)__instance).m_seman.HaveStatusEffect(stableHashCode) ? 30f : 1.5f); StatusEffect statusEffect = ((Character)__instance).m_seman.GetStatusEffect(StringExtensionMethods.GetStableHashCode("Wounded")); StatusEffect statusEffect2 = ((Character)__instance).m_seman.GetStatusEffect(StringExtensionMethods.GetStableHashCode("se_verydrunk")); StatusEffect statusEffect3 = ((Character)__instance).m_seman.GetStatusEffect(StringExtensionMethods.GetStableHashCode("se_drunk")); StatusEffect statusEffect4 = ((Character)__instance).m_seman.GetStatusEffect(StringExtensionMethods.GetStableHashCode("Thistled")); StatusEffect statusEffect5 = ((Character)__instance).m_seman.GetStatusEffect(StringExtensionMethods.GetStableHashCode("DanceFever")); StatusEffect statusEffect6 = ((Character)__instance).m_seman.GetStatusEffect(StringExtensionMethods.GetStableHashCode("se_wishbone")); if ((Object)(object)statusEffect != (Object)null) { StatusOverlayManager.Instance.UpdateOverlay(new Color(0.5f, 0f, 0f), 0.8f, enabled: true, 1.2f); } else if ((Object)(object)statusEffect4 != (Object)null) { StatusOverlayManager.Instance.UpdateOverlay(new Color(0f, 0.5f, 0.5f), 0.3f, enabled: true, 0.8f); } else if ((Object)(object)statusEffect2 != (Object)null) { StatusOverlayManager.Instance.UpdateOverlay(new Color(10f, 5f, 0f, 0.6f), 0.3f, enabled: true); Dictionary emoteChance = new Dictionary { { "Puke", 0.1f }, { "rest", 0.2f }, { "sit", 0.3f }, { "despair", 0.35f }, { "cry", 0.3f }, { "blowkiss", 0.4f }, { "headbang", 0.6f }, { "challenge", 0.7f } }; HandleAlcoholProc(__instance, StringExtensionMethods.GetStableHashCode("se_verydrunk"), emoteChance); } else if (Object.op_Implicit((Object)(object)statusEffect3)) { Dictionary emoteChance2 = new Dictionary { { "sit", 0.05f }, { "headbang", 0.2f }, { "toast", 0.3f } }; HandleAlcoholProc(__instance, StringExtensionMethods.GetStableHashCode("se_drunk"), emoteChance2, 20f); } else if (Object.op_Implicit((Object)(object)statusEffect5)) { StatusOverlayManager.Instance.UpdateOverlay(new Color(1f, 0.3f, 0.7f), 0.4f, enabled: true, 0.5f); Dictionary emoteChance3 = new Dictionary { { "dance", 0.15f }, { "headbang", 0.45f }, { "vibe", 0.95f } }; HandleAlcoholProc(__instance, StringExtensionMethods.GetStableHashCode("DanceFever"), emoteChance3); } else if ((Object)(object)statusEffect6 != (Object)null) { if (!((Character)__instance).m_seman.HaveStatusEffect(StringExtensionMethods.GetStableHashCode("Wishbone"))) { ((Character)__instance).m_seman.AddStatusEffect(StringExtensionMethods.GetStableHashCode("Wishbone"), false, 0, 0f); } } else if ((Object)(object)StatusOverlayManager.Instance != (Object)null) { StatusOverlayManager.Instance.UpdateOverlay(Color.clear, 0f, enabled: false); if (((Character)__instance).m_seman.HaveStatusEffect(StringExtensionMethods.GetStableHashCode("Wishbone"))) { ((Character)__instance).m_seman.RemoveStatusEffect(StringExtensionMethods.GetStableHashCode("Wishbone"), false); } } } } [HarmonyPatch(typeof(Character), "RPC_Damage")] public static class RPC_Damage_HarpoonedGate_Patch { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Prefix(Character __instance, HitData hit) { if (hit.m_statusEffectHash == StringExtensionMethods.GetStableHashCode("Harpooned")) { bool flag = false; if (!((!__instance.IsPlayer()) ? __instance.IsTamed() : __instance.GetSEMan().HaveStatusEffect(StringExtensionMethods.GetStableHashCode("PVPLoss")))) { hit.m_statusEffectHash = 0; return; } hit.m_damage.m_blunt = 0f; hit.m_damage.m_slash = 0f; hit.m_damage.m_pierce = 0f; hit.m_damage.m_chop = 0f; hit.m_damage.m_pickaxe = 0f; hit.m_damage.m_fire = 0f; hit.m_damage.m_frost = 0f; hit.m_damage.m_lightning = 0f; hit.m_damage.m_poison = 0f; hit.m_damage.m_spirit = 0f; hit.m_damage.m_damage = 0f; } } } [HarmonyPatch(typeof(Character), "ApplyDamage")] public static class HarpoonedDropsOnDamage_Patch { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(Character __instance, HitData hit) { //IL_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Invalid comparison between Unknown and I4 //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0029: Invalid comparison between Unknown and I4 //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Invalid comparison between Unknown and I4 //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Invalid comparison between Unknown and I4 int stableHashCode = StringExtensionMethods.GetStableHashCode("Harpooned"); if (__instance.GetSEMan().HaveStatusEffect(stableHashCode) && (int)hit.m_hitType != 5 && (int)hit.m_hitType != 7 && (int)hit.m_hitType != 6 && (int)hit.m_hitType != 9 && hit.GetTotalDamage() > 0.1f) { __instance.GetSEMan().RemoveStatusEffect(stableHashCode, false); } } } [HarmonyPatch(typeof(Minimap), "UpdateExplore")] private class fixexplore { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref Minimap __instance, float dt, Player player) { //IL_0054: Unknown result type (might be due to invalid IL or missing references) float num = (((Object)(object)player.GetControlledShip() == (Object)null) ? __instance.m_exploreRadius : 180f); Minimap obj = __instance; obj.m_exploreTimer += Time.deltaTime; if (__instance.m_exploreTimer > __instance.m_exploreInterval) { __instance.m_exploreTimer = 0f; __instance.Explore(((Component)player).transform.position, num); } } } [HarmonyPatch(typeof(Fireplace), "Awake")] private class fixfireplace { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref Fireplace __instance) { Fireplace obj = __instance; obj.m_secPerFuel *= 5f; } } [HarmonyPatch(typeof(Fireplace), "UpdateFireplace")] private class updatefireplace { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref Fireplace __instance) { if (__instance.m_nview.IsValid() && __instance.m_nview.IsOwner() && __instance.m_nview.GetZDO().GetFloat("fuel", 0f) == 0f && !__instance.IsBurning() && (((Object)__instance).name == "fire_pit(Clone)" || ((Object)__instance).name == "rk_campfire(Clone)")) { WearNTear component = ((Component)__instance).gameObject.GetComponent(); if ((Object)(object)component != (Object)null) { component.Remove(false); } } } } [HarmonyPatch(typeof(Ship), "Awake")] public static class shipfix { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref Ship __instance) { __instance.m_minWaterImpactForce = 100f; } } [HarmonyPatch(typeof(WearNTear), "OnPlaced")] private class shipCreated { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref WearNTear __instance) { if (Object.op_Implicit((Object)(object)__instance)) { Ship component = ((Component)__instance).gameObject.GetComponent(); if (Object.op_Implicit((Object)(object)component) && Object.op_Implicit((Object)(object)component.m_nview) && component.m_nview.IsValid()) { component.m_nview.GetZDO().Set("creatorName", Game.instance.GetPlayerProfile().GetName()); SendModerationLog("", "", ((Object)((Component)component).gameObject).name, "", "ship created", Game.instance.GetPlayerProfile().GetName()); } } } } [HarmonyPatch(typeof(Ship), "OnDestroyed")] private class shipDestroyed { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref Ship __instance) { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_004f: Unknown result type (might be due to invalid IL or missing references) //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) if (__instance.IsOwner() && Object.op_Implicit((Object)(object)__instance.m_nview) && __instance.m_nview.IsValid()) { List list = new List(); Player.GetPlayersInRange(((Component)__instance).transform.position, 30f, list); string text = ((Component)__instance).transform.position.x + " "; text = text + ((Component)__instance).transform.position.z + " "; text += ((Component)__instance).transform.position.y; SendModerationLog(string.Join(",", list.Select((Player p) => p.GetPlayerName())), "", ((Object)((Component)__instance).gameObject).name, "ship destroyed", __instance.m_nview.GetZDO().GetString("creatorName", ""), text); } } } [HarmonyPatch(typeof(Player), "StartDoodadControl")] private class shipControlled { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref ShipControlls shipControl) { Component controlledComponent = shipControl.GetControlledComponent(); Ship val = (Ship)(object)((controlledComponent is Ship) ? controlledComponent : null); if ((Object)(object)val != (Object)null) { SendModerationLog(Game.instance.GetPlayerProfile().GetName(), "", ((Object)shipControl.GetControlledComponent().gameObject).name, "ship controlled", val.m_nview.GetZDO().GetString("creatorName", ""), ""); } } } [HarmonyPatch(typeof(Bed), "GetHoverText")] private class bedName { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref Bed __instance, ref string __result) { if (!((Object)(object)Player.m_localPlayer == (Object)null)) { long owner = __instance.GetOwner(); long playerID = Player.m_localPlayer.GetPlayerID(); _ = ((Object)((Component)__instance).gameObject).name; if (owner != 0L && owner != playerID) { __result = "Someone else sleeps here."; } } } } [HarmonyPatch(typeof(ShipControlls), "GetHoverText")] private class shipName { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref ShipControlls __instance, ref string __result) { Component controlledComponent = __instance.GetControlledComponent(); Ship val = (Ship)(object)((controlledComponent is Ship) ? controlledComponent : null); if ((Object)(object)val != (Object)null) { __result = __result + Environment.NewLine + ((Object)((Component)val).gameObject).name + " " + val.m_nview.GetZDO().GetString("creatorName", ""); } } } [HarmonyPatch(typeof(Ship), "UpdateUpsideDmg")] private class raftdmg { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(float dt, Ship __instance) { //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Invalid comparison between Unknown and I4 //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_0088: Expected O, but got Unknown //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) raftdmgcounter += dt; if (!(raftdmgcounter > 2f)) { return; } raftdmgcounter = 0f; if (__instance.IsOwner() && Object.op_Implicit((Object)(object)__instance.m_nview) && __instance.m_nview.IsValid() && ((Object)((Component)__instance).gameObject).name == "Raft(Clone)" && (int)Heightmap.FindBiome(((Component)__instance).transform.position) == 256) { IDestructible component = ((Component)__instance).GetComponent(); if (component != null) { HitData val = new HitData(); val.m_damage.m_blunt = 1f; val.m_point = ((Component)__instance).transform.position; val.m_dir = Vector3.up; component.Damage(val); } } } } [HarmonyPatch(typeof(Game), "SpawnPlayer")] private class respawnclass { private static bool s_registered; private static void Postfix() { ZLog.DevLog((object)"Running custom SpawnPlayer PostFix"); try { if (!s_registered && ZRoutedRpc.instance != null) { ZRoutedRpc.instance.Register("ClientSetClass", (Method)RPC_SetClass); s_registered = true; } } catch (Exception ex) { ZLog.LogWarning((object)"Registering Class Didn't work"); ZLog.LogError((object)ex); } ZRoutedRpc.instance.InvokeRoutedRPC("ServerGetClass", new object[1] { Player.m_localPlayer.GetPlayerName() }); } } [HarmonyPatch(typeof(Skill), "Raise")] private class SkillCapPatch { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref Skill __instance) { if (isAdmin()) { return; } float num = 20f; string text = ((object)(SkillType)(ref __instance.m_info.m_skill)).ToString().ToLower(); bool flag = true; switch (text) { case "blocking": num = 50f; break; case "crafting": case "pickaxes": case "jump": case "ride": case "swim": case "fishing": case "woodcutting": case "run": case "sneak": num = 100f; break; default: flag = false; break; } if (!flag && playerskills.TryGetValue(text, out var value) && value > 0) { num = value; } if (__instance.m_level > num) { __instance.m_level = num; __instance.m_accumulator = 0f; if (VRPMod.DebugMode()) { ZLog.LogWarning((object)$"Skill {text} set to {num}"); } } } } [HarmonyPatch(typeof(Player), "GetMaxCarryWeight")] private class laborerweightfix { private static void Postfix(ref float __result) { if (groups.Contains("Laborer")) { __result += 200f; } } } [HarmonyPatch(typeof(EnvMan), "Awake")] private class envmanawakefix { private static void Postfix() { EnvMan.instance.m_dayLengthSec = 3600L; } } [HarmonyPatch(typeof(TextViewer), "ShowText")] private class textviewerfix { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Prefix(Style style, string topic, ref string textId, bool autoHide) { if (textId.Contains("lore_intro")) { string text = ConvertIntroText(VRPMod._vrpLore.Value); textId = text; } } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [Nullable(0)] [HarmonyPatch(typeof(Container), "Awake")] public static class ApplyContainerSizeChanges { private static void Prefix(ref Container __instance) { applyContainerSizes(__instance); } private static void applyContainerSizes(Container instance) { if (Object.op_Implicit((Object)(object)instance.m_wagon)) { instance.m_width = 6; instance.m_height = 4; return; } Transform parent = ((Component)instance).gameObject.transform.parent; Ship val = ((parent != null) ? ((Component)parent).GetComponent() : null); if (Object.op_Implicit((Object)(object)val)) { if (((Object)val).name.StartsWith("VikingShip")) { instance.m_width = 6; instance.m_height = 4; } else if (((Object)val).name.StartsWith("Karve")) { instance.m_width = 4; instance.m_height = 3; } else if (((Object)val).name.StartsWith("Kurve")) { instance.m_width = 1; instance.m_height = 1; } } else if (((Object)instance).name.StartsWith("piece_chest_wood")) { instance.m_width = 5; instance.m_height = 4; } else if (((Object)instance).name.StartsWith("piece_chest_private")) { instance.m_width = 5; instance.m_height = 3; } else if (((Object)instance).name.StartsWith("piece_chest_blackmetal")) { instance.m_width = 7; instance.m_height = 6; } else if (((Object)instance).name.StartsWith("piece_gift1")) { instance.m_width = 4; instance.m_height = 2; } else if (((Object)instance).name.StartsWith("piece_gift2")) { instance.m_width = 4; instance.m_height = 2; } else if (((Object)instance).name.StartsWith("piece_gift3")) { instance.m_width = 4; instance.m_height = 2; } else if (((Object)instance).name.StartsWith("piece_chest")) { instance.m_width = 7; instance.m_height = 4; } else if (((Object)instance).name.StartsWith("piece_pot3")) { instance.m_width = 2; instance.m_height = 2; } else if (((Object)instance).name.StartsWith("piece_pot1")) { instance.m_width = 4; instance.m_height = 4; } else if (((Object)instance).name.StartsWith("piece_pot2")) { instance.m_width = 4; instance.m_height = 7; } } } [HarmonyPatch(typeof(ConsoleCommand), "IsValid")] private static class cheatfix { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool Prefix(ref bool __result, ref Terminal context, ref ConsoleCommand __instance) { __result = Object.op_Implicit((Object)(object)ZNet.instance) && Object.op_Implicit((Object)(object)Player.m_localPlayer) && (!__instance.IsCheat || isAdmin()); return false; } } [HarmonyPatch(typeof(Fish), "Interact")] private static class fishfix { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool Prefix(ref Humanoid character, bool repeat, bool alt, ref Fish __instance, ref bool __result) { __result = !repeat && __instance.Pickup(character); return false; } } [HarmonyPatch(typeof(Fish), "Start")] private static class fishhookfix { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref Fish __instance) { __instance.m_baseHookChance = 0.8f; } } [HarmonyPatch(typeof(FishingFloat), "Awake")] private static class floathfix { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref FishingFloat __instance) { __instance.m_range = 20f; } } [HarmonyPatch(typeof(Trader), "Start")] private static class traderbye { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref Trader __instance) { ((Component)__instance).gameObject.SetActive(false); } } [HarmonyPatch(typeof(Piece), "SetCreator")] private static class piecelog { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(long uid, ref Piece __instance) { //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Unknown result type (might be due to invalid IL or missing references) //IL_008f: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) if (isAdmin()) { return; } Player player = Player.GetPlayer(uid); if (Object.op_Implicit((Object)(object)player) && Object.op_Implicit((Object)(object)__instance.m_nview) && __instance.m_nview.GetZDO() != null) { string text = ((Component)__instance).transform.position.x + " "; text = text + ((Component)__instance).transform.position.z + " "; text += ((Component)__instance).transform.position.y; SendModerationLog(player.GetPlayerName(), "", ((Object)((Component)__instance).gameObject).name, "piece created", "", text); __instance.m_nview.GetZDO().Set("creatorName", player.GetPlayerName()); if (__instance.m_name == "Ward") { ZRoutedRpc.instance.InvokeRoutedRPC("ServerSetWard", new object[2] { player.GetPlayerName(), true }); } } } } [HarmonyPatch(typeof(Piece), "DropResources")] private static class piecelogd { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref Piece __instance) { //IL_0033: Unknown result type (might be due to invalid IL or missing references) //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) if (!isAdmin() && Object.op_Implicit((Object)(object)__instance.m_nview) && __instance.m_nview.IsOwner()) { string text = ((Component)__instance).transform.position.x + " "; text = text + ((Component)__instance).transform.position.z + " "; text += ((Component)__instance).transform.position.y; List list = new List(); Player.GetPlayersInRange(((Component)__instance).transform.position, 30f, list); SendModerationLog(string.Join(",", list.Select((Player p) => p.GetPlayerName())), "", ((Object)((Component)__instance).gameObject).name, "piece destroyed", __instance.m_nview.GetZDO().GetString("creatorName", ""), text); ZRoutedRpc.instance.InvokeRoutedRPC("ServerSetWard", new object[2] { __instance.m_nview.GetZDO().GetString("creatorName", ""), false }); } } } [HarmonyPatch(typeof(Container), "RPC_RequestOpen")] private static class chestlog { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref Container __instance, long uid, long playerID) { //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00e6: Unknown result type (might be due to invalid IL or missing references) //IL_00eb: Unknown result type (might be due to invalid IL or missing references) if (isAdmin()) { return; } Player player = Player.GetPlayer(playerID); if (!((Object)(object)player != (Object)null) || !((Character)player).m_nview.IsValid() || !((Object)(object)__instance.m_nview != (Object)null) || !__instance.m_nview.IsValid()) { return; } string creator = ""; if ((Object)(object)__instance.m_piece != (Object)null) { ZDO zDO = __instance.m_piece.m_nview.GetZDO(); if (zDO != null && zDO.IsValid()) { creator = zDO.GetString("creatorName", ""); } } string text = ((Component)__instance).transform.position.x + " "; text = text + ((Component)__instance).transform.position.z + " "; text += ((Component)__instance).transform.position.y; SendModerationLog(((Character)player).GetHoverName(), "", ((Object)((Component)__instance).gameObject).name, "chest open", creator, text); } } [HarmonyPatch(typeof(InventoryGui), "DoCrafting")] private static class craftlog { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(Player player, ref InventoryGui __instance) { int isAdmin = (ClientPatches.isAdmin() ? 1 : 0); SendModerationLog(((Character)player).GetHoverName(), "", __instance.m_craftRecipe.m_item.m_itemData.m_shared.m_name, "item created", "", "", "", isAdmin); } } [HarmonyPatch(typeof(Player), "Awake")] private static class playerawake { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref Player __instance) { __instance.m_hardDeathCooldown = 1f; } } [Nullable(0)] [HarmonyPatch(typeof(Player), "OnSpawned")] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static class novalk_clean { [CompilerGenerated] private sealed class d__2 : IEnumerator, IDisposable, IEnumerator { private int <>1__state; [Nullable(0)] private object <>2__current; [Nullable(0)] public Player p; object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } [DebuggerHidden] public d__2(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Expected O, but got Unknown switch (<>1__state) { default: return false; case 0: <>1__state = -1; <>2__current = (object)new WaitForSeconds(0.3f); <>1__state = 1; return true; case 1: { <>1__state = -1; int num = DeathPatch.ApplyPendingOnSpawn(p); if (VRPMod.DebugMode()) { ZLog.Log((object)$"[VRP:Spawn] applied {num} queued effect(s)"); } return false; } } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [CompilerGenerated] private sealed class d__3 : IEnumerator, IDisposable, IEnumerator { private int <>1__state; [Nullable(0)] private object <>2__current; object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } [DebuggerHidden] public d__3(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Expected O, but got Unknown switch (<>1__state) { default: return false; case 0: <>1__state = -1; if (((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer()) || IsSkillDataLoaded || isAdmin()) { return false; } ZLog.LogWarning((object)"[VRP:Sync] Player spawned but skill caps aren't loaded yet. Monitoring data stream."); break; case 1: <>1__state = -1; break; } if (!IsSkillDataLoaded && (Object)(object)Player.m_localPlayer != (Object)null) { if ((Object)(object)MessageHud.instance != (Object)null) { MessageHud.instance.ShowMessage((MessageType)2, "Syncing server data... Please wait a moment before interacting!", 0, (Sprite)null, false); } <>2__current = (object)new WaitForSeconds(2f); <>1__state = 1; return true; } if ((Object)(object)Player.m_localPlayer != (Object)null && (Object)(object)MessageHud.instance != (Object)null) { MessageHud.instance.ShowMessage((MessageType)2, "Data synced successfully!", 0, (Sprite)null, false); ZLog.Log((object)"[VRP:Sync] Skill caps caught up. Monitoring routine stopped successfully."); } return false; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } [HarmonyPrefix] [HarmonyPriority(800)] private static void Prefix(Player __instance, ref bool spawnValkyrie) { showIntro = spawnValkyrie; spawnValkyrie = false; if (VRPMod.DebugMode()) { ZLog.Log((object)"[VRP:NoValk] Prefix: forcing spawnValkyrie=false (vanilla OnSpawned will still run)"); } } [HarmonyPriority(0)] [HarmonyPostfix] private static void Postfix(Player __instance) { if (!Object.op_Implicit((Object)(object)__instance) || !((Character)__instance).IsOwner()) { return; } __instance.SetIntro(showIntro); if (Object.op_Implicit((Object)(object)Minimap.instance) && Object.op_Implicit((Object)(object)Minimap.instance.m_smallRoot)) { Minimap.instance.m_smallRoot.SetActive(false); Image component = Minimap.instance.m_smallRoot.GetComponent(); if (Object.op_Implicit((Object)(object)component)) { ((Behaviour)component).enabled = false; } } if (VRPMod.DebugMode()) { ZLog.Log((object)"[VRP:NoValk] Postfix: intro disabled and minimap hidden"); } ((MonoBehaviour)__instance).StartCoroutine(ApplyEffectsDelayed(__instance)); ((MonoBehaviour)__instance).StartCoroutine(WaitForSkillCapsRoutine()); } [IteratorStateMachine(typeof(d__2))] private static IEnumerator ApplyEffectsDelayed(Player p) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__2(0) { p = p }; } [IteratorStateMachine(typeof(d__3))] private static IEnumerator WaitForSkillCapsRoutine() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__3(0); } } [HarmonyPatch(typeof(Game), "Awake")] private static class noarrived { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref Game __instance) { __instance.m_firstSpawn = false; } } [HarmonyPatch(typeof(Minimap), "Update")] public static class ForceHideMinimapPatch { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(Minimap __instance) { if (!__instance.m_largeRoot.activeSelf && __instance.m_smallRoot.activeSelf) { __instance.m_smallRoot.SetActive(false); Image component = __instance.m_smallRoot.GetComponent(); if (Object.op_Implicit((Object)(object)component)) { ((Behaviour)component).enabled = false; } } } } [HarmonyPatch(typeof(Player), "HaveSeenTutorial")] private static class notutorial { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(string name, ref bool __result) { __result = true; } } [HarmonyPatch(typeof(TombStone), "Awake")] private static class nocorpserun { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref TombStone __instance) { __instance.m_lootStatusEffect = null; __instance.m_worldText.text = ""; } } [HarmonyPatch(typeof(TombStone), "Start")] private static class notombstonename { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref TombStone __instance) { __instance.m_worldText.text = ""; if (Object.op_Implicit((Object)(object)Player.m_localPlayer) && Player.m_localPlayer.GetPlayerName() == __instance.m_nview.GetZDO().GetString("ownerName", "")) { __instance.m_worldText.text = "Mine"; } } } [HarmonyPatch(typeof(TombStone), "Setup")] private static class notombstonename2 { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref TombStone __instance) { __instance.m_worldText.text = ""; if (Object.op_Implicit((Object)(object)Player.m_localPlayer) && Player.m_localPlayer.GetPlayerName() == __instance.m_nview.GetZDO().GetString("ownerName", "")) { __instance.m_worldText.text = "Mine"; } } } [HarmonyPatch(typeof(TombStone), "GetHoverText")] private static class notombstonemessage { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref TombStone __instance, ref string __result) { __result = "dont touch"; } } [HarmonyPatch(typeof(MapTable), "OnRead", new Type[] { typeof(Switch), typeof(Humanoid), typeof(ItemData), typeof(bool) })] private static class noaddmap { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool Prefix(Switch caller, Humanoid user, ItemData item, bool __result) { __result = false; return false; } } [HarmonyPatch(typeof(MapTable), "OnWrite")] private static class nogetmap { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool Prefix(Switch caller, Humanoid user, ItemData item, bool __result) { __result = false; return false; } } [HarmonyPatch(typeof(Door), "HaveKey")] private static class consumekeys { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref Humanoid player, ref Door __instance, ref bool __result) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Unknown result type (might be due to invalid IL or missing references) if (__result) { string raw = ((Component)__instance).transform.position.x + " " + ((Component)__instance).transform.position.z + " " + ((Component)__instance).transform.position.y; SendModerationLog(((Character)player).GetHoverName(), "", __instance.m_keyItem.m_itemData.m_shared.m_name, "Key", "", raw); player.GetInventory().RemoveItem(__instance.m_keyItem.m_itemData.m_shared.m_name, 1, -1, true); } } } [HarmonyPatch(typeof(Character), "InInterior", new Type[] { typeof(Transform) })] private static class buildindungeonlol { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(Transform me, ref bool __result) { if (isAdmin()) { __result = false; } } } [HarmonyPatch(typeof(Inventory), "IsTeleportable")] private static class teleporteverything { private static void Postfix(ref bool __result) { __result = true; } } [HarmonyPatch(typeof(InventoryGui), "HaveRepairableItems")] private static class norepairgui { private static void Postfix(ref bool __result) { if (!isAdmin()) { __result = false; } } } [HarmonyPatch(typeof(Vagon), "AttachTo")] private static class cartlogattach { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(Vagon __instance) { if (!isAdmin()) { Piece component = ((Component)__instance).gameObject.GetComponent(); ZLog.Log((object)"Player touched cart"); SendModerationLog(((Character)Player.m_localPlayer).GetHoverName(), "", ((Object)((Component)__instance).gameObject).name, "cart control", component.m_nview.GetZDO().GetString("creatorName", ""), ""); } } } [HarmonyPatch(typeof(Player), "Awake")] public static class Player_ParryCost_Patch { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static void Postfix(Player __instance) { ((Humanoid)__instance).m_perfectBlockStaminaDrain = 15f; } } [HarmonyPatch(typeof(PlayerCustomizaton), "OnBeardLeft")] private static class beardpatchelft { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool Prefix(ref PlayerCustomizaton __instance) { __instance.SetBeard(__instance.GetBeardIndex() - 1); return false; } } [HarmonyPatch(typeof(PlayerCustomizaton), "OnBeardRight")] private static class beardpatchright { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool Prefix(ref PlayerCustomizaton __instance) { __instance.SetBeard(__instance.GetBeardIndex() + 1); return false; } } [HarmonyPatch(typeof(Player), "GetTotalFoodValue")] private static class foodburntime { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref float hp, ref float stamina, ref float eitr, Player __instance) { hp = __instance.m_baseHP; stamina = __instance.m_baseStamina; eitr = 0f; foreach (Food food in __instance.m_foods) { hp += food.m_item.m_shared.m_food; stamina += food.m_item.m_shared.m_foodStamina; eitr += food.m_item.m_shared.m_foodEitr; } } } [HarmonyPatch(typeof(Incinerator), "Incinerate")] private static class incinlog { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Prefix(ref Incinerator __instance, long uid) { foreach (ItemData allItem in __instance.m_container.m_inventory.GetAllItems()) { SendModerationLog(((Character)Player.m_localPlayer).GetHoverName(), "", allItem.m_shared.m_name, "incinerator", allItem.m_crafterName, allItem.m_shared.m_name + " " + allItem.m_stack); } } } [HarmonyPatch(typeof(RandEventSystem), "GetPossibleRandomEvents")] private static class disableRaids { private static void Postfix([Nullable(new byte[] { 1, 0, 1 })] ref List> __result) { __result.Clear(); } } [Nullable(0)] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [HarmonyPatch(typeof(Sign), "Awake")] private static class SignAwakePatch { private static void Prefix(Sign __instance) { //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Unknown result type (might be due to invalid IL or missing references) //IL_007a: Unknown result type (might be due to invalid IL or missing references) //IL_0081: Unknown result type (might be due to invalid IL or missing references) //IL_00bd: Unknown result type (might be due to invalid IL or missing references) Transform val = Utils.FindChild(((Component)__instance).transform, "Text", (IterativeSearchType)0); if ((Object)(object)val != (Object)null) { Text component = ((Component)val).GetComponent(); if ((Object)(object)component != (Object)null) { GameObject val2 = new GameObject("Text"); val2.transform.SetParent(((Component)val).transform.parent); Transform transform = ((Component)val).transform; val2.transform.localPosition = transform.localPosition; val2.transform.localRotation = transform.localRotation; val2.transform.localScale = transform.localScale; TextMeshProUGUI val3 = val2.AddComponent(); ((TMP_Text)val3).text = component.text; ((TMP_Text)val3).font = TMP_FontAsset.CreateFontAsset(component.font); ((TMP_Text)val3).fontSize = component.fontSize; ((Graphic)val3).color = ((Graphic)component).color; ((TMP_Text)val3).alignment = (TextAlignmentOptions)514; __instance.m_textWidget = val3; Object.Destroy((Object)(object)((Component)component).gameObject); } } } private static void Postfix(Sign __instance) { if (!((Behaviour)__instance).enabled) { ((Behaviour)__instance).enabled = true; } } } [Nullable(1)] public static List groups = new List(); [Nullable(1)] public static List skillcaps = new List(); [Nullable(1)] public static Dictionary playerskills = new Dictionary(StringComparer.OrdinalIgnoreCase); public static bool IsSkillDataLoaded = false; [Nullable(1)] public static List recipes = new List(); public static bool IsRecipeDataLoaded = false; [Nullable(1)] public static List pieces = new List(); public static bool IsPieceDataLoaded = false; [Nullable(1)] public static HashSet groupSet = new HashSet(StringComparer.OrdinalIgnoreCase); [Nullable(1)] public static HashSet disabledPiecesCache = new HashSet(StringComparer.OrdinalIgnoreCase); public static bool canWard = false; private static float badFoodTimer = 0f; private static float badFoodInterval = 5f; private static bool ateBadFood = false; [Nullable(1)] private static readonly Dictionary _nextDrunkCheckAt = new Dictionary(); [Nullable(1)] private static readonly Dictionary _nextDanceCheckAt = new Dictionary(); [ThreadStatic] private static bool t_DoorAccessBypass; [Nullable(1)] public static List admins = new List { "Admin", "Unknown", "Nocturn", "Solsworn", "Solstice", "Nox", "Hearthwarden Utu", "Utu", "Vitus", "Baelor", "Salem", "Valamaricus", "Lussios", "Demophiles", "Orion", "Celine", "Historian", "Analise", "Adaline", "Cerise", "Caelie" }; [Nullable(1)] private static readonly Queue _modLogQueue = new Queue(); [Nullable(1)] private static readonly object _modLogLock = new object(); private const int MODLOG_BURST = 8; private const float MODLOG_RATE = 8f; private const int MODLOG_MAX_QUEUE = 500; private static float _modLogTokens = 8f; [Nullable(1)] private static Dictionary _adminWardCache = new Dictionary(); [Nullable(1)] private static readonly StringComparer EmoteCmp = StringComparer.OrdinalIgnoreCase; private static float raftdmgcounter = 0f; private static bool showIntro = false; [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static bool Contains(string source, string toCheck, StringComparison comp) { Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US"); string text = source.ToUpperInvariant(); string value = toCheck.ToUpperInvariant(); return text.Contains(value); } public static bool isAdmin() { if ((Object)(object)Game.instance != (Object)null && Game.instance.m_playerProfile != null) { string playerName = Game.instance.m_playerProfile.m_playerName.Trim().ToUpperInvariant(); return admins.Any((string admin) => admin.Trim().ToUpperInvariant() == playerName); } return false; } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static bool isAdmin(string name) { bool num = admins.Contains(name.ToUpperInvariant()); if (num) { ZLog.Log((object)(name + " is an admin")); } return num; } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void EnqueueModerationLog(string logjson) { lock (_modLogLock) { if (_modLogQueue.Count >= 500) { _modLogQueue.Dequeue(); } _modLogQueue.Enqueue(logjson); } } private static void PumpModerationLog(float dt) { if (ZRoutedRpc.instance == null || ZRoutedRpc.instance.m_server) { return; } _modLogTokens = Mathf.Min(8f, _modLogTokens + 8f * dt); while (_modLogTokens >= 1f) { string text = null; lock (_modLogLock) { if (_modLogQueue.Count == 0) { break; } text = _modLogQueue.Dequeue(); } string text2 = text; if (VRPMod.DebugMode()) { ZLog.Log((object)("SEND PAYLOAD " + text2)); } if (!string.IsNullOrEmpty(text2)) { ZRoutedRpc.instance.InvokeRoutedRPC(ZRoutedRpc.instance.GetServerPeerID(), "ServerModerationLog", new object[1] { text2 }); _modLogTokens -= 1f; continue; } break; } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static void SendModerationLog(string player, string steamId, string item, string action, string creator, string raw, string subaction = "", int isAdmin = 0) { string input = SimpleJson.SerializeObject((object)new DbLog { p = player, s = steamId, m = isAdmin, i = item, a = action, b = subaction, c = creator, r = raw }); input = Regex.Replace(input, "[^\\u0009\\u000A\\u000D\\u0020-\\u007E]", ""); if (ZRoutedRpc.instance != null && !ZRoutedRpc.instance.m_server) { EnqueueModerationLog(input); } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static void SendBroadcast(string message) { if (ZRoutedRpc.instance != null && !ZRoutedRpc.instance.m_server) { ServerPatches.RPC_Broadcast(0L, message); } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static string ConvertIntroText(string otext) { ZLog.Log((object)"Intro text hashed"); if (string.IsNullOrEmpty(otext)) { return string.Empty; } return WebUtility.HtmlDecode(Regex.Replace(Regex.Replace(otext, "", Environment.NewLine, RegexOptions.IgnoreCase), "<[^>]+>", string.Empty)); } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static void playerEqp(ref ItemData item, ref Humanoid huma) { if (!isAdmin() && item != null && item.IsEquipable() && (Object)(object)huma != (Object)null && ((Character)huma).IsPlayer()) { Humanoid obj = huma; Player val = (Player)(object)((obj is Player) ? obj : null); if ((Object)(object)val != (Object)null && ((Character)val).m_nview.IsValid() && (Object)(object)Player.m_localPlayer != (Object)null) { string raw = ((Character)val).GetHoverName() + " | equip | " + item.m_shared.m_name + ((item.m_crafterID == 0L) ? " | uncrafted | " : (" | crafted by | " + item.m_crafterName + " ")); SendModerationLog(((Character)val).GetHoverName(), "", item.m_shared.m_name, "equip", (item.m_crafterID == 0L) ? " | uncrafted | " : (" | crafted by | " + item.m_crafterName + " "), raw); } } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static void RPC_SetClass(long sender, string groups, string recipesraw, string piecesraw, string skillsraw) { if (!((Object)(object)ZNet.instance != (Object)null) || ZNet.instance.IsServer()) { return; } ZLog.LogWarning((object)("got groups from server " + groups)); ClientPatches.groups = groups.Split(new char[1] { ',' }).ToList(); groupSet = new HashSet(from g in groups.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries) select g.Trim(), StringComparer.OrdinalIgnoreCase); DbRecipe[] array = SimpleJson.DeserializeObject(recipesraw); if (array != null) { recipes.Clear(); DbRecipe[] array2 = array; foreach (DbRecipe dbRecipe in array2) { if (!dbRecipe.deleted) { recipes.Add(dbRecipe); } } IsRecipeDataLoaded = true; } else { ZLog.LogError((object)"error recipes json"); } DbPieces[] array3 = SimpleJson.DeserializeObject(piecesraw); if (array3 != null) { pieces.Clear(); DbPieces[] array4 = array3; foreach (DbPieces item in array4) { pieces.Add(item); } IsPieceDataLoaded = true; } else { ZLog.LogError((object)"error pieces json"); } if (!string.IsNullOrEmpty(skillsraw)) { string[] array5 = skillsraw.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries); string text = ""; string[] array6 = array5; for (int i = 0; i < array6.Length; i++) { string[] array7 = array6[i].Split(new char[1] { ':' }); if (array7.Length == 2) { string text2 = array7[0].Trim().ToLower(); if (int.TryParse(array7[1].Trim(), out var result)) { playerskills[text2] = result; text += $"{text2}:{result};"; } } } ZLog.LogWarning((object)("got skills from server " + text)); IsSkillDataLoaded = true; } ObjectdbPatches.RebuildDisabledCache(); } public static void RPC_SetWard(long sender, bool canPlaceWard) { if ((Object)(object)ZNet.instance != (Object)null && !ZNet.instance.IsServer()) { ZLog.LogWarning((object)("got ward status from server " + canPlaceWard)); canWard = canPlaceWard; } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool IsAdminWard(PrivateArea pa) { if ((Object)(object)pa == (Object)null) { return false; } int instanceID = ((Object)((Component)pa).gameObject).GetInstanceID(); if (_adminWardCache.TryGetValue(instanceID, out var value)) { return value; } Piece component = ((Component)pa).gameObject.GetComponent(); bool flag = (Object)(object)component != (Object)null && component.m_name == "WardAdmin"; _adminWardCache[instanceID] = flag; if (VRPMod.DebugMode()) { ZLog.Log((object)$"ADMIN WARD? {flag}"); } return flag; } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool IsFarmerWard(PrivateArea pa) { if ((Object)(object)pa == (Object)null) { return false; } Piece component = ((Component)pa).gameObject.GetComponent(); bool flag = (Object)(object)component != (Object)null && component.m_name == "WardFarmer"; if (VRPMod.DebugMode()) { ZLog.Log((object)$"FARMER WARD? {flag}"); } return flag; } private static bool IsInsideEnabledAdminWard(Vector3 point) { //IL_0027: Unknown result type (might be due to invalid IL or missing references) foreach (PrivateArea allArea in PrivateArea.m_allAreas) { if (!((Object)(object)allArea == (Object)null) && allArea.IsEnabled() && allArea.IsInside(point, 0f) && IsAdminWard(allArea)) { return true; } } return false; } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static string GetSteamId() { if ((Object)(object)ZNet.instance == (Object)null) { return "unknown"; } foreach (ZNetPeer peer in ZNet.instance.GetPeers()) { if (peer.m_playerName == Player.m_localPlayer.GetPlayerName()) { return peer.m_uid.ToString(); } } return "unknown"; } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static bool isValidName(string input) { return Regex.IsMatch(input, "^[\\p{L}\\s]+$"); } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static string GetDisplayName(string playerName) { Player val = null; foreach (Player s_player in Player.s_players) { if (s_player.GetPlayerName().Equals(playerName)) { val = s_player; break; } } if ((Object)(object)val == (Object)null || (Object)(object)((Character)val).m_nview == (Object)null) { return playerName; } ZDO zDO = ((Character)val).m_nview.GetZDO(); if (zDO == null) { return playerName; } bool @bool = zDO.GetBool("isAnonymous", false); string @string = zDO.GetString("secretName", playerName); if (!@bool) { return playerName; } return @string; } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void TryPuke(Player p) { ((Character)p).m_seman.AddStatusEffect(StringExtensionMethods.GetStableHashCode("Puke"), false, 0, 0f); if (VRPMod.DebugMode()) { ZLog.Log((object)"Puke!"); } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void TrySleepers(Player p) { ((Character)p).m_zanim.SetBool("attach_bed", true); if (VRPMod.DebugMode()) { ZLog.Log((object)"Sleepers!"); } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void TrySit(Player p) { p.StartEmote("sit", false); if (VRPMod.DebugMode()) { ZLog.Log((object)"Sit!"); } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void TryEmote(Player p, string emote) { p.StartEmote(emote, false); if (VRPMod.DebugMode()) { ZLog.Log((object)(emote + "!")); } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void HandleAlcoholProc(Player p, int statusHash, Dictionary emoteChance = null, float cadenceSeconds = 10f) { StatusEffect statusEffect = ((Character)p).m_seman.GetStatusEffect(statusHash); long playerID = p.GetPlayerID(); if ((Object)(object)statusEffect != (Object)null) { float time = Time.time; if (_nextDrunkCheckAt.TryGetValue(playerID, out var value) && !(time >= value)) { return; } _nextDrunkCheckAt[playerID] = time + cadenceSeconds; float value2 = Random.value; if (VRPMod.DebugMode()) { ZLog.Log((object)$"[VRP] {statusEffect.m_name} proc roll {value2:0.000}"); } { foreach (KeyValuePair item in from kv in emoteChance where kv.Value > 0f select new KeyValuePair(kv.Key, Mathf.Clamp01(kv.Value)) into kv orderby kv.Value select kv) { if (value2 < item.Value) { if (EmoteCmp.Equals(item.Key, "Puke")) { TryPuke(p); } else { TryEmote(p, item.Key); } if (VRPMod.DebugMode()) { ZLog.Log((object)$"[VRP] {statusEffect.m_name} -> triggered '{item.Key}' @ p={item.Value:0.000}"); } break; } } return; } } _nextDrunkCheckAt.Remove(playerID); } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void SetActiveRecursive(GameObject go, bool a) { go.SetActive(a); for (int i = 0; i < go.transform.childCount; i++) { SetActiveRecursive(((Component)go.transform.GetChild(i)).gameObject, a); } } } [Nullable(0)] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] internal class JotunnPatches { private static bool _foodInitialized; public static void AddVariants() { PrefabManager.OnVanillaPrefabsAvailable += CustomMaterials; PrefabManager.OnVanillaPrefabsAvailable += CustomShields; PrefabManager.OnVanillaPrefabsAvailable += CustomArrows; PrefabManager.OnVanillaPrefabsAvailable += CustomArmor; PrefabManager.OnVanillaPrefabsAvailable += CustomWeapons; PrefabManager.OnVanillaPrefabsAvailable += TerrainChanges; PrefabManager.OnVanillaPrefabsAvailable += CustomFood; PrefabManager.OnVanillaPrefabsAvailable += AddMerchantItems; PrefabManager.OnVanillaPrefabsAvailable += AddMissingRecipes; PrefabManager.OnVanillaPrefabsAvailable += MiscVRPItemsChanges; PrefabManager.OnVanillaPrefabsAvailable += CustomPlants; PrefabManager.OnVanillaPrefabsAvailable += BuildPiecePatch.CustomPieces; PrefabManager.OnVanillaPrefabsAvailable += EventBench.OnVanillaPrefabsAvailable; PrefabManager.OnPrefabsRegistered += DeathPatch.AddDeathStatuses; PrefabManager.OnPrefabsRegistered += StatusEffectPatch.AddHandcuffStatus; PrefabManager.OnPrefabsRegistered += StatusEffectPatch.AddChampionStatus; PrefabManager.OnPrefabsRegistered += DrinkablesPatch.AddCustomDrinks; PrefabManager.OnPrefabsRegistered += StatusEffectPatch.AddDanceStatus; PrefabManager.OnPrefabsRegistered += DanceBombPatch.RegisterDanceBomb; PrefabManager.OnPrefabsRegistered += MagicAddition.RegisterMagicChanges; PrefabManager.OnPrefabsRegistered += AddFishItems; PrefabManager.OnPrefabsRegistered += BuildPiecePatch.MissingPieces; PrefabManager.OnPrefabsRegistered += EditStatusEffects; PrefabManager.OnPrefabsRegistered += PowerBeltPatch.PowerBelts; } private static void CustomShields() { //IL_0012: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Expected O, but got Unknown //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0053: Expected O, but got Unknown //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) //IL_0065: Unknown result type (might be due to invalid IL or missing references) //IL_006c: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Expected O, but got Unknown //IL_01e1: Unknown result type (might be due to invalid IL or missing references) //IL_01e6: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Unknown result type (might be due to invalid IL or missing references) //IL_01f9: Unknown result type (might be due to invalid IL or missing references) //IL_0201: Expected O, but got Unknown //IL_0203: Unknown result type (might be due to invalid IL or missing references) //IL_0208: Unknown result type (might be due to invalid IL or missing references) //IL_0213: Unknown result type (might be due to invalid IL or missing references) //IL_021a: Unknown result type (might be due to invalid IL or missing references) //IL_0222: Expected O, but got Unknown //IL_0224: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Unknown result type (might be due to invalid IL or missing references) //IL_0234: Unknown result type (might be due to invalid IL or missing references) //IL_023b: Unknown result type (might be due to invalid IL or missing references) //IL_0243: Expected O, but got Unknown //IL_026b: Unknown result type (might be due to invalid IL or missing references) //IL_0270: Unknown result type (might be due to invalid IL or missing references) //IL_027b: Unknown result type (might be due to invalid IL or missing references) //IL_0283: Unknown result type (might be due to invalid IL or missing references) //IL_028b: Expected O, but got Unknown //IL_028d: Unknown result type (might be due to invalid IL or missing references) //IL_0292: Unknown result type (might be due to invalid IL or missing references) //IL_029d: Unknown result type (might be due to invalid IL or missing references) //IL_02a4: Unknown result type (might be due to invalid IL or missing references) //IL_02ac: Expected O, but got Unknown //IL_02d4: Unknown result type (might be due to invalid IL or missing references) //IL_02d9: Unknown result type (might be due to invalid IL or missing references) //IL_02e4: Unknown result type (might be due to invalid IL or missing references) //IL_02ec: Unknown result type (might be due to invalid IL or missing references) //IL_02f5: Expected O, but got Unknown //IL_02f7: Unknown result type (might be due to invalid IL or missing references) //IL_02fc: Unknown result type (might be due to invalid IL or missing references) //IL_0307: Unknown result type (might be due to invalid IL or missing references) //IL_030e: Unknown result type (might be due to invalid IL or missing references) //IL_0316: Expected O, but got Unknown //IL_033e: Unknown result type (might be due to invalid IL or missing references) //IL_0343: Unknown result type (might be due to invalid IL or missing references) //IL_034e: Unknown result type (might be due to invalid IL or missing references) //IL_0356: Unknown result type (might be due to invalid IL or missing references) //IL_035f: Expected O, but got Unknown //IL_0361: Unknown result type (might be due to invalid IL or missing references) //IL_0366: Unknown result type (might be due to invalid IL or missing references) //IL_0371: Unknown result type (might be due to invalid IL or missing references) //IL_0379: Unknown result type (might be due to invalid IL or missing references) //IL_0381: Expected O, but got Unknown //IL_03a9: Unknown result type (might be due to invalid IL or missing references) //IL_03ae: Unknown result type (might be due to invalid IL or missing references) //IL_03b9: Unknown result type (might be due to invalid IL or missing references) //IL_03c1: Unknown result type (might be due to invalid IL or missing references) //IL_03ca: Expected O, but got Unknown //IL_03cc: Unknown result type (might be due to invalid IL or missing references) //IL_03d1: Unknown result type (might be due to invalid IL or missing references) //IL_03dc: Unknown result type (might be due to invalid IL or missing references) //IL_03e3: Unknown result type (might be due to invalid IL or missing references) //IL_03eb: Expected O, but got Unknown //IL_0413: Unknown result type (might be due to invalid IL or missing references) //IL_0418: Unknown result type (might be due to invalid IL or missing references) //IL_0423: Unknown result type (might be due to invalid IL or missing references) //IL_042b: Unknown result type (might be due to invalid IL or missing references) //IL_0434: Expected O, but got Unknown //IL_0436: Unknown result type (might be due to invalid IL or missing references) //IL_043b: Unknown result type (might be due to invalid IL or missing references) //IL_0446: Unknown result type (might be due to invalid IL or missing references) //IL_044d: Unknown result type (might be due to invalid IL or missing references) //IL_0455: Expected O, but got Unknown //IL_0457: Unknown result type (might be due to invalid IL or missing references) //IL_045c: Unknown result type (might be due to invalid IL or missing references) //IL_0467: Unknown result type (might be due to invalid IL or missing references) //IL_046e: Unknown result type (might be due to invalid IL or missing references) //IL_0476: Expected O, but got Unknown //IL_049e: Unknown result type (might be due to invalid IL or missing references) //IL_04a3: Unknown result type (might be due to invalid IL or missing references) //IL_04ae: Unknown result type (might be due to invalid IL or missing references) //IL_04b6: Unknown result type (might be due to invalid IL or missing references) //IL_04bf: Expected O, but got Unknown //IL_04c1: Unknown result type (might be due to invalid IL or missing references) //IL_04c6: Unknown result type (might be due to invalid IL or missing references) //IL_04d1: Unknown result type (might be due to invalid IL or missing references) //IL_04d9: Unknown result type (might be due to invalid IL or missing references) //IL_04e1: Expected O, but got Unknown //IL_04e3: Unknown result type (might be due to invalid IL or missing references) //IL_04e8: Unknown result type (might be due to invalid IL or missing references) //IL_04f3: Unknown result type (might be due to invalid IL or missing references) //IL_04fa: Unknown result type (might be due to invalid IL or missing references) //IL_0502: Expected O, but got Unknown //IL_052a: Unknown result type (might be due to invalid IL or missing references) //IL_052f: Unknown result type (might be due to invalid IL or missing references) //IL_053a: Unknown result type (might be due to invalid IL or missing references) //IL_0542: Unknown result type (might be due to invalid IL or missing references) //IL_054b: Expected O, but got Unknown //IL_054d: Unknown result type (might be due to invalid IL or missing references) //IL_0552: Unknown result type (might be due to invalid IL or missing references) //IL_055d: Unknown result type (might be due to invalid IL or missing references) //IL_0564: Unknown result type (might be due to invalid IL or missing references) //IL_056c: Expected O, but got Unknown //IL_056e: Unknown result type (might be due to invalid IL or missing references) //IL_0573: Unknown result type (might be due to invalid IL or missing references) //IL_057e: Unknown result type (might be due to invalid IL or missing references) //IL_0585: Unknown result type (might be due to invalid IL or missing references) //IL_058d: Expected O, but got Unknown //IL_05b5: Unknown result type (might be due to invalid IL or missing references) //IL_05ba: Unknown result type (might be due to invalid IL or missing references) //IL_05c5: Unknown result type (might be due to invalid IL or missing references) //IL_05cd: Unknown result type (might be due to invalid IL or missing references) //IL_05d6: Expected O, but got Unknown //IL_05d8: Unknown result type (might be due to invalid IL or missing references) //IL_05dd: Unknown result type (might be due to invalid IL or missing references) //IL_05e8: Unknown result type (might be due to invalid IL or missing references) //IL_05f0: Unknown result type (might be due to invalid IL or missing references) //IL_05f8: Expected O, but got Unknown //IL_05fa: Unknown result type (might be due to invalid IL or missing references) //IL_05ff: Unknown result type (might be due to invalid IL or missing references) //IL_060a: Unknown result type (might be due to invalid IL or missing references) //IL_0611: Unknown result type (might be due to invalid IL or missing references) //IL_0619: Expected O, but got Unknown ZLog.Log((object)"VRP Shields"); try { _ = new RequirementConfig[3] { new RequirementConfig { Item = "Wood", Amount = 10, AmountPerLevel = 5 }, new RequirementConfig { Item = "Resin", Amount = 4, AmountPerLevel = 2 }, new RequirementConfig { Item = "LeatherScraps", Amount = 4, AmountPerLevel = 2 } }; Sprite[] icons = null; Texture2D styleTex = null; if (!Env.IsDedicated) { Sprite val = AssetUtils.LoadSpriteFromFile("Arielle-ValheimRoleplay/Assets/varx.png"); Sprite val2 = AssetUtils.LoadSpriteFromFile("Arielle-ValheimRoleplay/Assets/varcir.png"); Sprite val3 = AssetUtils.LoadSpriteFromFile("Arielle-ValheimRoleplay/Assets/varsquare.png"); Sprite val4 = AssetUtils.LoadSpriteFromFile("Arielle-ValheimRoleplay/Assets/varrunes.png"); Sprite val5 = AssetUtils.LoadSpriteFromFile("Arielle-ValheimRoleplay/Assets/varblack.png"); Sprite val6 = AssetUtils.LoadSpriteFromFile("Arielle-ValheimRoleplay/Assets/vargreen.png"); Sprite val7 = AssetUtils.LoadSpriteFromFile("Arielle-ValheimRoleplay/Assets/varblue.png"); Sprite val8 = AssetUtils.LoadSpriteFromFile("Arielle-ValheimRoleplay/Assets/varred.png"); Sprite val9 = AssetUtils.LoadSpriteFromFile("Arielle-ValheimRoleplay/Assets/vartree.png"); Sprite val10 = AssetUtils.LoadSpriteFromFile("Arielle-ValheimRoleplay/Assets/varskull.png"); Sprite val11 = AssetUtils.LoadSpriteFromFile("Arielle-ValheimRoleplay/Assets/varocto.png"); Sprite val12 = AssetUtils.LoadSpriteFromFile("Arielle-ValheimRoleplay/Assets/varspider.png"); Sprite val13 = AssetUtils.LoadSpriteFromFile("Arielle-ValheimRoleplay/Assets/varves.png"); Sprite val14 = AssetUtils.LoadSpriteFromFile("Arielle-ValheimRoleplay/Assets/varbluestripe.png"); Sprite val15 = AssetUtils.LoadSpriteFromFile("Arielle-ValheimRoleplay/Assets/varrwb.png"); Sprite val16 = AssetUtils.LoadSpriteFromFile("Arielle-ValheimRoleplay/Assets/varredwhite.png"); styleTex = AssetUtils.LoadTexture("Arielle-ValheimRoleplay/Assets/var_vrp.png", true); icons = (Sprite[])(object)new Sprite[16] { val5, val6, val7, val8, val9, val10, val11, val12, val4, val13, val14, val15, val, val2, val3, val16 }; } AddShield("vrp-woodshield", "ShieldWood", "Wooden shield", "A simple wooden shield with a special design", "piece_workbench", (RequirementConfig[])(object)new RequirementConfig[3] { new RequirementConfig { Item = "Wood", Amount = 10, AmountPerLevel = 5 }, new RequirementConfig { Item = "Resin", Amount = 4, AmountPerLevel = 2 }, new RequirementConfig { Item = "LeatherScraps", Amount = 4, AmountPerLevel = 2 } }); AddShield("vrp-woodtower", "ShieldWoodTower", "Wooden Tower shield", "A rough but heavy wooden shield with a special design", "piece_workbench", (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "Wood", Amount = 10, AmountPerLevel = 5 }, new RequirementConfig { Item = "LeatherScraps", Amount = 6, AmountPerLevel = 3 } }); AddShield("vrp-ironbanded", "ShieldBanded", "Banded shield", "Designed Banded with hoops of iron, a true warrior's companion.", "forge", (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "FineWood", Amount = 10, AmountPerLevel = 10 }, new RequirementConfig { Item = "Iron", Amount = 8, AmountPerLevel = 4 } }); AddShield("vrp-irontower", "ShieldIronTower", "Iron Tower shield", "A tall shield of strong iron with special design", "forge", (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "FineWood", Amount = 15, AmountPerLevel = 10 }, new RequirementConfig { Item = "Iron", Amount = 10, AmountPerLevel = 5 } }); AddShield("vrp-shieldsilver", "ShieldSilver", "Silver shield", "A shield of radiant silver with special design.", "forge", (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "FineWood", Amount = 10, AmountPerLevel = 10 }, new RequirementConfig { Item = "Silver", Amount = 8, AmountPerLevel = 4 } }); AddShield("vrp-shieldblackmetal", "ShieldBlackmetal", "Black metal shield", "Specially designed, fashioned from the strongest metal, able to turn even the deadliest blades.", "forge", (RequirementConfig[])(object)new RequirementConfig[3] { new RequirementConfig { Item = "FineWood", Amount = 10, AmountPerLevel = 10 }, new RequirementConfig { Item = "BlackMetal", Amount = 8, AmountPerLevel = 4 }, new RequirementConfig { Item = "Chain", Amount = 5, AmountPerLevel = 2 } }); AddShield("vrp-shieldblackmetaltower", "ShieldBlackmetalTower", "Black metal tower shield", "A tower shield of gleaming dark metal.", "forge", (RequirementConfig[])(object)new RequirementConfig[3] { new RequirementConfig { Item = "FineWood", Amount = 10, AmountPerLevel = 10 }, new RequirementConfig { Item = "BlackMetal", Amount = 10, AmountPerLevel = 6 }, new RequirementConfig { Item = "Chain", Amount = 7, AmountPerLevel = 2 } }); AddShield("vrp-shieldflametal", "ShieldFlametal", "Flametal shield", "Specially designed, the shield is and always will be a viking's most important weapon.", "blackforge", (RequirementConfig[])(object)new RequirementConfig[3] { new RequirementConfig { Item = "FineWood", Amount = 10, AmountPerLevel = 10 }, new RequirementConfig { Item = "FlametalNew", Amount = 8, AmountPerLevel = 4 }, new RequirementConfig { Item = "Chain", Amount = 5, AmountPerLevel = 2 } }); AddShield("vrp-shieldflamemetaltower", "ShieldFlametalTower", "Flametal tower shield", "Specially designed. The best defence is a great defence", "blackforge", (RequirementConfig[])(object)new RequirementConfig[3] { new RequirementConfig { Item = "FineWood", Amount = 10, AmountPerLevel = 10 }, new RequirementConfig { Item = "FlametalNew", Amount = 10, AmountPerLevel = 6 }, new RequirementConfig { Item = "Chain", Amount = 7, AmountPerLevel = 2 } }); void AddShield(string id, string clone, string name, string desc, string station, RequirementConfig[] reqs) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected O, but got Unknown //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Expected O, but got Unknown ItemConfig val17 = new ItemConfig { Name = name, Description = desc, CraftingStation = station, Requirements = reqs }; if (icons != null) { val17.Icons = icons; val17.StyleTex = styleTex; } CustomItem val18 = new CustomItem(id, clone, val17); ItemManager.Instance.AddItem(val18); } } catch (Exception ex) { ZLog.LogError((object)"error adding vrp items custom shields"); if (VRPMod.DebugMode()) { ZLog.LogError((object)ex.Message); } } finally { PrefabManager.OnVanillaPrefabsAvailable -= CustomShields; } } private static void CustomArrows() { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_0043: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Expected O, but got Unknown //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_0070: Expected O, but got Unknown //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Unknown result type (might be due to invalid IL or missing references) //IL_008a: Expected O, but got Unknown //IL_0090: Unknown result type (might be due to invalid IL or missing references) //IL_0096: Expected O, but got Unknown try { ItemConfig val = new ItemConfig(); val.Description = "the stone is not very sharp, needs extra feathers"; val.Amount = 20; val.CraftingStation = "piece_workbench"; val.MinStationLevel = 1; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[3] { new RequirementConfig { Item = "Stone", Amount = 5 }, new RequirementConfig { Item = "Feathers", Amount = 5 }, new RequirementConfig { Item = "Wood", Amount = 8 } }; CustomItem val2 = new CustomItem("ArrowStone", "ArrowFlint", val); val2.ItemDrop.m_itemData.m_shared.m_name = "Stone Arrow"; val2.ItemDrop.m_itemData.m_shared.m_damages.m_pierce = 0f; val2.ItemDrop.m_itemData.m_shared.m_damages.m_blunt = 25f; ItemManager.Instance.AddItem(val2); } catch (Exception ex) { ZLog.LogError((object)"error adding vrp items custom arrows"); if (VRPMod.DebugMode()) { ZLog.LogError((object)ex.Message); } } finally { PrefabManager.OnVanillaPrefabsAvailable -= CustomArrows; } } private static void CustomWeapons() { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Expected O, but got Unknown //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Expected O, but got Unknown //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Expected O, but got Unknown //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Expected O, but got Unknown //IL_013d: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Expected O, but got Unknown //IL_017a: Unknown result type (might be due to invalid IL or missing references) //IL_017f: Unknown result type (might be due to invalid IL or missing references) //IL_018a: Unknown result type (might be due to invalid IL or missing references) //IL_0192: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Expected O, but got Unknown //IL_019d: Unknown result type (might be due to invalid IL or missing references) //IL_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_01ad: Unknown result type (might be due to invalid IL or missing references) //IL_01b4: Unknown result type (might be due to invalid IL or missing references) //IL_01bc: Expected O, but got Unknown //IL_01cf: Unknown result type (might be due to invalid IL or missing references) //IL_01d5: Expected O, but got Unknown //IL_026e: Unknown result type (might be due to invalid IL or missing references) //IL_0275: Expected O, but got Unknown //IL_02ab: Unknown result type (might be due to invalid IL or missing references) //IL_02b0: Unknown result type (might be due to invalid IL or missing references) //IL_02bb: Unknown result type (might be due to invalid IL or missing references) //IL_02c4: Expected O, but got Unknown //IL_02c6: Unknown result type (might be due to invalid IL or missing references) //IL_02cb: Unknown result type (might be due to invalid IL or missing references) //IL_02d6: Unknown result type (might be due to invalid IL or missing references) //IL_02de: Expected O, but got Unknown //IL_02e0: Unknown result type (might be due to invalid IL or missing references) //IL_02e5: Unknown result type (might be due to invalid IL or missing references) //IL_02f0: Unknown result type (might be due to invalid IL or missing references) //IL_02f8: Expected O, but got Unknown //IL_030d: Unknown result type (might be due to invalid IL or missing references) //IL_0314: Expected O, but got Unknown //IL_03ce: Unknown result type (might be due to invalid IL or missing references) //IL_03d5: Expected O, but got Unknown //IL_040b: Unknown result type (might be due to invalid IL or missing references) //IL_0410: Unknown result type (might be due to invalid IL or missing references) //IL_041b: Unknown result type (might be due to invalid IL or missing references) //IL_0424: Expected O, but got Unknown //IL_0426: Unknown result type (might be due to invalid IL or missing references) //IL_042b: Unknown result type (might be due to invalid IL or missing references) //IL_0436: Unknown result type (might be due to invalid IL or missing references) //IL_043e: Expected O, but got Unknown //IL_0440: Unknown result type (might be due to invalid IL or missing references) //IL_0445: Unknown result type (might be due to invalid IL or missing references) //IL_0450: Unknown result type (might be due to invalid IL or missing references) //IL_0458: Expected O, but got Unknown //IL_046d: Unknown result type (might be due to invalid IL or missing references) //IL_0474: Expected O, but got Unknown //IL_072f: Unknown result type (might be due to invalid IL or missing references) //IL_0736: Expected O, but got Unknown //IL_076c: Unknown result type (might be due to invalid IL or missing references) //IL_0771: Unknown result type (might be due to invalid IL or missing references) //IL_077c: Unknown result type (might be due to invalid IL or missing references) //IL_0785: Expected O, but got Unknown //IL_0787: Unknown result type (might be due to invalid IL or missing references) //IL_078c: Unknown result type (might be due to invalid IL or missing references) //IL_0797: Unknown result type (might be due to invalid IL or missing references) //IL_07a0: Expected O, but got Unknown //IL_07a2: Unknown result type (might be due to invalid IL or missing references) //IL_07a7: Unknown result type (might be due to invalid IL or missing references) //IL_07b2: Unknown result type (might be due to invalid IL or missing references) //IL_07bb: Expected O, but got Unknown //IL_07bd: Unknown result type (might be due to invalid IL or missing references) //IL_07c2: Unknown result type (might be due to invalid IL or missing references) //IL_07cd: Unknown result type (might be due to invalid IL or missing references) //IL_07d5: Expected O, but got Unknown //IL_07ea: Unknown result type (might be due to invalid IL or missing references) //IL_07f1: Expected O, but got Unknown ZLog.Log((object)"VRP WEAPONS"); try { ItemConfig val = new ItemConfig(); val.Name = "$item_shield_solsworn"; val.Description = "Solsworn Shield."; val.CraftingStation = CraftingStations.Forge; val.MinStationLevel = 2; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "Iron", Amount = 10 }, new RequirementConfig { Item = "Wood", Amount = 20 } }; ItemConfig val2 = val; CustomItem val3 = new CustomItem("ShieldSolsworn", "ShieldFlametal", val2); val3.ItemDrop.m_itemData.m_shared.m_name = "Solsworn Shield"; val3.ItemDrop.m_itemData.m_shared.m_armor = 52f; val3.ItemDrop.m_itemData.m_shared.m_timedBlockBonus = 1.5f; val3.ItemDrop.m_itemData.m_shared.m_blockPower = 150f; val3.ItemDrop.m_itemData.m_shared.m_damages.m_chop = 50f; val3.ItemDrop.m_itemData.m_shared.m_toolTier = 2; ItemManager.Instance.AddItem(val3); val = new ItemConfig(); val.Name = "$item_fistweapon_iron"; val.Description = "Iron reinforced knuckles."; val.CraftingStation = CraftingStations.Forge; val.MinStationLevel = 2; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "Iron", Amount = 20, AmountPerLevel = 10 }, new RequirementConfig { Item = "FistBjornClaw", Amount = 1, AmountPerLevel = 0 } }; ItemConfig val4 = val; CustomItem val5 = new CustomItem("SwampFists", "FistBjornClaw", val4); val5.ItemDrop.m_itemData.m_shared.m_name = "Iron Reinforced Knuckles"; val5.ItemDrop.m_itemData.m_shared.m_damages.m_slash = 45f; val5.ItemDrop.m_itemData.m_shared.m_damages.m_blunt = 20f; val5.ItemDrop.m_itemData.m_shared.m_attack.m_attackStamina = 10f; val5.ItemDrop.m_itemData.m_shared.m_toolTier = 2; ItemManager.Instance.AddItem(val5); val = new ItemConfig(); val.Name = "$item_axe_iron2"; val.Description = "Some axe chop tree. Some axe chop leg."; val.CraftingStation = CraftingStations.Forge; val.MinStationLevel = 2; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[3] { new RequirementConfig { Item = "Iron", Amount = 40 }, new RequirementConfig { Item = "AxeHead1", Amount = 1 }, new RequirementConfig { Item = "AxeHead2", Amount = 1 } }; ItemConfig val6 = val; CustomItem val7 = new CustomItem("SwampAxes", "AxeBerzerkr", val6); val7.ItemDrop.m_itemData.m_shared.m_name = "Iron Axes"; val7.ItemDrop.m_itemData.m_shared.m_damages.m_slash = 55f; val7.ItemDrop.m_itemData.m_shared.m_attack.m_attackStamina = 10f; val7.ItemDrop.m_itemData.m_shared.m_blockPower = 21f; val7.ItemDrop.m_itemData.m_shared.m_damages.m_chop = 50f; val7.ItemDrop.m_itemData.m_shared.m_toolTier = 2; ItemManager.Instance.AddItem(val7); val = new ItemConfig(); val.Name = "$item_axe_silver2"; val.Description = "The only way to make room for new life is to cut down old growth"; val.CraftingStation = CraftingStations.Forge; val.MinStationLevel = 4; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[3] { new RequirementConfig { Item = "Silver", Amount = 40 }, new RequirementConfig { Item = "AxeHead1", Amount = 1 }, new RequirementConfig { Item = "AxeHead2", Amount = 1 } }; ItemConfig val8 = val; CustomItem val9 = new CustomItem("SilverAxes", "AxeBerzerkr", val8); val9.ItemDrop.m_itemData.m_shared.m_name = "Silver Axes"; val9.ItemDrop.m_itemData.m_shared.m_damages.m_slash = 70f; val9.ItemDrop.m_itemData.m_shared.m_attack.m_attackStamina = 12f; val9.ItemDrop.m_itemData.m_shared.m_blockPower = 30f; val9.ItemDrop.m_itemData.m_shared.m_damages.m_chop = 60f; val9.ItemDrop.m_itemData.m_shared.m_toolTier = 2; val9.ItemDrop.m_itemData.m_shared.m_damages.m_lightning = 0f; val9.ItemDrop.m_itemData.m_shared.m_damages.m_frost = 15f; val9.ItemDrop.m_itemData.m_shared.m_attackStatusEffect = null; val9.ItemDrop.m_itemData.m_shared.m_attackStatusEffectChance = 0f; val9.ItemDrop.m_itemData.m_shared.m_attack.m_spawnOnHitChance = 0f; val9.ItemDrop.m_itemData.m_shared.m_attack.m_triggerEffect = null; val9.ItemDrop.m_itemData.m_shared.m_hitEffect.m_effectPrefabs = (EffectData[])(object)new EffectData[0]; GameObject prefab = PrefabManager.Instance.GetPrefab("AxeBerzerkrLightning"); if ((Object)(object)prefab != (Object)null) { GameObject itemPrefab = val9.ItemPrefab; MeshRenderer componentInChildren = prefab.GetComponentInChildren(); MeshRenderer componentInChildren2 = itemPrefab.GetComponentInChildren(); if ((Object)(object)componentInChildren != (Object)null && (Object)(object)componentInChildren2 != (Object)null) { ((Renderer)componentInChildren2).sharedMaterials = ((Renderer)componentInChildren).sharedMaterials; MeshFilter component = ((Component)componentInChildren).GetComponent(); MeshFilter component2 = ((Component)componentInChildren2).GetComponent(); if (Object.op_Implicit((Object)(object)component) && Object.op_Implicit((Object)(object)component2)) { component2.sharedMesh = component.sharedMesh; } } Renderer[] componentsInChildren = prefab.GetComponentsInChildren(true); Renderer[] componentsInChildren2 = itemPrefab.GetComponentsInChildren(true); foreach (Renderer target2 in componentsInChildren2) { Renderer val10 = ((IEnumerable)componentsInChildren).FirstOrDefault((Func)([<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] (Renderer r) => ((Object)r).name == ((Object)target2).name)); if ((Object)(object)val10 != (Object)null) { target2.sharedMaterials = val10.sharedMaterials; MeshFilter component3 = ((Component)val10).GetComponent(); MeshFilter component4 = ((Component)target2).GetComponent(); if (Object.op_Implicit((Object)(object)component3) && Object.op_Implicit((Object)(object)component4)) { component4.sharedMesh = component3.sharedMesh; } } } } ItemManager.Instance.AddItem(val9); val = new ItemConfig(); val.Name = "$item_axe_mist"; val.Description = "Forged for the Strigoi of the deep fog; they possess no heartbeat of their own, so they must borrow yours."; val.CraftingStation = CraftingStations.BlackForge; val.MinStationLevel = 2; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[4] { new RequirementConfig { Item = "FineWood", Amount = 10 }, new RequirementConfig { Item = "Iron", Amount = 15 }, new RequirementConfig { Item = "Eitr", Amount = 10 }, new RequirementConfig { Item = "GiantBloodSack", Amount = 3 } }; ItemConfig val11 = val; CustomItem val12 = new CustomItem("MistAxes", "AxeBerzerkr", val11); val12.ItemDrop.m_itemData.m_shared.m_name = "Bloodreaper Axes"; val12.ItemDrop.m_itemData.m_shared.m_damages.m_slash = 85f; val12.ItemDrop.m_itemData.m_shared.m_damages.m_spirit = 20f; val12.ItemDrop.m_itemData.m_shared.m_damages.m_chop = 70f; val12.ItemDrop.m_itemData.m_shared.m_toolTier = 4; val12.ItemDrop.m_itemData.m_shared.m_attackStatusEffect = null; val12.ItemDrop.m_itemData.m_shared.m_attackStatusEffectChance = 0f; val12.ItemDrop.m_itemData.m_shared.m_attack.m_spawnOnHitChance = 0f; val12.ItemDrop.m_itemData.m_shared.m_hitEffect.m_effectPrefabs = (EffectData[])(object)new EffectData[0]; GameObject prefab2 = PrefabManager.Instance.GetPrefab("AxeBerzerkrBlood"); if ((Object)(object)prefab2 != (Object)null) { GameObject itemPrefab2 = val12.ItemPrefab; MeshRenderer componentInChildren3 = prefab2.GetComponentInChildren(); MeshRenderer componentInChildren4 = itemPrefab2.GetComponentInChildren(); if ((Object)(object)componentInChildren3 != (Object)null && (Object)(object)componentInChildren4 != (Object)null) { ((Renderer)componentInChildren4).sharedMaterials = ((Renderer)componentInChildren3).sharedMaterials; MeshFilter component5 = ((Component)componentInChildren3).GetComponent(); MeshFilter component6 = ((Component)componentInChildren4).GetComponent(); if (Object.op_Implicit((Object)(object)component5) && Object.op_Implicit((Object)(object)component6)) { component6.sharedMesh = component5.sharedMesh; } } Renderer[] componentsInChildren3 = prefab2.GetComponentsInChildren(true); Renderer[] componentsInChildren2 = itemPrefab2.GetComponentsInChildren(true); foreach (Renderer target in componentsInChildren2) { Renderer val13 = ((IEnumerable)componentsInChildren3).FirstOrDefault((Func)([<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] (Renderer r) => ((Object)r).name == ((Object)target).name)); if ((Object)(object)val13 != (Object)null) { target.sharedMaterials = val13.sharedMaterials; MeshFilter component7 = ((Component)val13).GetComponent(); MeshFilter component8 = ((Component)target).GetComponent(); if (Object.op_Implicit((Object)(object)component7) && Object.op_Implicit((Object)(object)component8)) { component8.sharedMesh = component7.sharedMesh; } } } } ItemManager.Instance.AddItem(val12); } catch (Exception ex) { ZLog.LogError((object)"error adding vrp items custom weapons"); if (VRPMod.DebugMode()) { ZLog.LogError((object)ex.Message); } } finally { PrefabManager.OnVanillaPrefabsAvailable -= CustomWeapons; } } private static void CustomArmor() { //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_0160: Expected O, but got Unknown //IL_0196: Unknown result type (might be due to invalid IL or missing references) //IL_019b: Unknown result type (might be due to invalid IL or missing references) //IL_01a6: Unknown result type (might be due to invalid IL or missing references) //IL_01af: Expected O, but got Unknown //IL_01c2: Unknown result type (might be due to invalid IL or missing references) //IL_01c9: Expected O, but got Unknown //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_00fe: Expected O, but got Unknown ZLog.Log((object)"VRP ARMER"); try { foreach (IGrouping> item in RecipeData.VRP_Armor.GroupBy, string>([<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] (KeyValuePair kv) => kv.Value.BundleKey, StringComparer.OrdinalIgnoreCase)) { using BundleCache.Scope scope = new BundleCache.Scope(item.Key); AssetBundle ab = scope.Bundle; if ((Object)(object)ab == (Object)null) { Logger.LogWarning((object)("Missing bundle for recipe group: " + item.Key)); continue; } foreach (KeyValuePair item2 in item) { string key = item2.Key; RecipeData.ComplexRecipe value = item2.Value; RequirementConfig[] requirements = ((IEnumerable>)value.Requirements).Select((Func, RequirementConfig>)([<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] (KeyValuePair req) => new RequirementConfig { Item = req.Key, Amount = req.Value.baseAmount, AmountPerLevel = req.Value.perLevel })).ToArray(); ItemConfig ic = new ItemConfig { CraftingStation = value.CraftingStation, MinStationLevel = value.StationLevel, Requirements = requirements }; RecipeHelper.addvrpitem(key, ref ab, ic); } } using BundleCache.Scope scope2 = new BundleCache.Scope("valonbundle"); AssetBundle bundle = scope2.Bundle; ItemConfig val = new ItemConfig(); val.Name = "BanditHelm"; val.Description = "A weird hat to hide your identity"; val.CraftingStation = "piece_workbench"; val.MinStationLevel = 1; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "Wood", Amount = 10 } }; ItemConfig val2 = val; CustomItem val3 = new CustomItem(bundle, "ValonHelm", false, val2); ItemManager.Instance.AddItem(val3); } catch (Exception ex) { ZLog.LogError((object)"error adding vrp items custom armors"); if (VRPMod.DebugMode()) { ZLog.LogError((object)ex.Message); } } finally { PrefabManager.OnVanillaPrefabsAvailable -= CustomArmor; } } private static void AllowPlantEverywhere(string prefabName, string niceName) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) GameObject prefab = PrefabManager.Instance.GetPrefab(prefabName); if (Object.op_Implicit((Object)(object)prefab)) { Piece val = default(Piece); if (prefab.TryGetComponent(ref val)) { val.m_onlyInBiome = (Biome)895; } Plant val2 = default(Plant); if (prefab.TryGetComponent(ref val2)) { val2.m_biome = (Biome)895; } if (VRPMod.DebugMode()) { ZLog.Log((object)("[VRP] " + niceName + " can now be planted in all biomes.")); } } } private static void CustomPlants() { //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Expected O, but got Unknown //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00bc: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Expected O, but got Unknown //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_00e3: Expected O, but got Unknown //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_0111: Expected O, but got Unknown //IL_0127: Unknown result type (might be due to invalid IL or missing references) //IL_012c: Unknown result type (might be due to invalid IL or missing references) //IL_0137: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Expected O, but got Unknown //IL_014d: Unknown result type (might be due to invalid IL or missing references) //IL_0153: Expected O, but got Unknown //IL_0173: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Expected O, but got Unknown //IL_0188: Unknown result type (might be due to invalid IL or missing references) //IL_0192: Expected O, but got Unknown //IL_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01ab: Expected O, but got Unknown //IL_01ba: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Expected O, but got Unknown //IL_01d3: Unknown result type (might be due to invalid IL or missing references) //IL_01dd: Expected O, but got Unknown //IL_01ec: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: Expected O, but got Unknown //IL_0205: Unknown result type (might be due to invalid IL or missing references) //IL_020f: Expected O, but got Unknown //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0228: Expected O, but got Unknown //IL_0233: Unknown result type (might be due to invalid IL or missing references) //IL_0238: Unknown result type (might be due to invalid IL or missing references) //IL_0243: Unknown result type (might be due to invalid IL or missing references) //IL_024e: Unknown result type (might be due to invalid IL or missing references) //IL_025e: Expected O, but got Unknown //IL_0259: Unknown result type (might be due to invalid IL or missing references) //IL_0260: Expected O, but got Unknown ZLog.Log((object)"VRP PLANTS"); try { foreach (KeyValuePair item in PlantData.PlantAnywhere) { AllowPlantEverywhere(item.Key, item.Value); } foreach (PlantableHelper.PlantablePickableConfig pickablePlantConfig in PlantData.PickablePlantConfigs) { PlantableHelper.MakePlantablePickable(pickablePlantConfig); } using BundleCache.Scope scope = new BundleCache.Scope("Arielle-ValheimRoleplay/Assets/bandage"); AssetBundle bundle = scope.Bundle; PieceConfig val = new PieceConfig(); val.PieceTable = "_CultivatorPieceTable"; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "palm_seed", Amount = 1, Recover = false } }; CustomPiece val2 = new CustomPiece(bundle, "palmtree_sapling", true, val); if (val2 != null) { if (VRPMod.DebugMode()) { ZLog.Log((object)"vrp added palmtree_sapling"); } PieceManager.Instance.AddPiece(val2); } val = new PieceConfig(); val.PieceTable = "_CultivatorPieceTable"; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "palmer_seed", Amount = 1, Recover = false } }; CustomPiece val3 = new CustomPiece(bundle, "palmertree_sapling", true, val); if (val3 != null) { if (VRPMod.DebugMode()) { ZLog.Log((object)"vrp added palmertree_sapling"); } PieceManager.Instance.AddPiece(val3); } VegetationConfig val4 = new VegetationConfig(); ZoneManager.Instance.AddCustomVegetation(new CustomVegetation(bundle, "palmtree", true, val4)); ZoneManager.Instance.AddCustomVegetation(new CustomVegetation(bundle, "palmertree", true, val4)); ZoneManager.Instance.AddCustomVegetation(new CustomVegetation(bundle, "palmtree_var", true, val4)); ZoneManager.Instance.AddCustomVegetation(new CustomVegetation(bundle, "palmtree_var2", true, val4)); ZoneManager.Instance.AddCustomVegetation(new CustomVegetation(bundle, "palmplant", true, val4)); ZoneManager.Instance.AddCustomVegetation(new CustomVegetation(bundle, "palmplant2", true, val4)); ZoneManager.Instance.AddCustomVegetation(new CustomVegetation(bundle, "palmplant3", true, val4)); CustomPiece val5 = new CustomPiece("replant_vrp", "replant_v2", new PieceConfig { PieceTable = "_HoePieceTable", Name = "Grass", Description = "grass come back!" }); PieceManager.Instance.AddPiece(val5); } catch (Exception ex) { ZLog.LogError((object)"error adding vrp items custom plants"); if (VRPMod.DebugMode()) { ZLog.LogError((object)ex.Message); } } finally { PrefabManager.OnVanillaPrefabsAvailable -= CustomPlants; } } private static void CustomFood() { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Expected O, but got Unknown //IL_0088: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0098: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Expected O, but got Unknown //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00a7: Unknown result type (might be due to invalid IL or missing references) //IL_00b2: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Expected O, but got Unknown //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c6: Expected O, but got Unknown //IL_00d8: Unknown result type (might be due to invalid IL or missing references) ZLog.Log((object)"VRP FOOD"); try { if (ItemManager.Instance.GetItem("MushroomSoup") != null) { _foodInitialized = true; return; } ItemConfig val = new ItemConfig(); val.Description = "a hearty earthy smelling soup"; val.Amount = 2; val.CraftingStation = "piece_cauldron"; val.MinStationLevel = 1; val.PieceTable = PieceTables.ServingTray; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[3] { new RequirementConfig { Item = "MushroomYellow", Amount = 2 }, new RequirementConfig { Item = "Mushroom", Amount = 2 }, new RequirementConfig { Item = "Honey", Amount = 2 } }; CustomItem val2 = new CustomItem("MushroomSoup", "SerpentStew", val); SharedData shared = val2.ItemDrop.m_itemData.m_shared; shared.m_itemType = (ItemType)2; shared.m_name = "Mushroom Soup"; shared.m_food = 38f; shared.m_foodStamina = 38f; ItemManager.Instance.AddItem(val2); ServingTrayHelper.AddToServingTray(val2); _foodInitialized = true; } catch (Exception ex) { ZLog.LogError((object)"error adding vrp items custom food"); if (VRPMod.DebugMode()) { ZLog.LogError((object)ex.Message); } } finally { PrefabManager.OnVanillaPrefabsAvailable -= CustomFood; } } private static void AddMerchantItems() { //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00bf: Unknown result type (might be due to invalid IL or missing references) //IL_00ff: Expected O, but got Unknown //IL_00fa: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Expected O, but got Unknown //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Expected O, but got Unknown //IL_0157: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_016f: Expected O, but got Unknown //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_0176: Unknown result type (might be due to invalid IL or missing references) //IL_0181: Unknown result type (might be due to invalid IL or missing references) //IL_018d: Expected O, but got Unknown //IL_01a0: Unknown result type (might be due to invalid IL or missing references) //IL_01a7: Expected O, but got Unknown //IL_01b1: Unknown result type (might be due to invalid IL or missing references) //IL_01b6: Unknown result type (might be due to invalid IL or missing references) //IL_01c1: Unknown result type (might be due to invalid IL or missing references) //IL_01cd: Expected O, but got Unknown ZLog.Log((object)"VRP Merchant"); try { foreach (KeyValuePair item in RecipeData.TrophyConversion) { RecipeHelper.AddCoinExchange($"vrp_merchant_{item.Key}", item.Key, item.Value.Split(new char[1] { ',' })); } foreach (KeyValuePair merchantRecipe in RecipeData.MerchantRecipes) { CustomRecipe val = new CustomRecipe(new RecipeConfig { Name = merchantRecipe.Key, Item = merchantRecipe.Value.Item, Amount = merchantRecipe.Value.Amount, Requirements = ((IEnumerable>)merchantRecipe.Value.Requirements).Select((Func, RequirementConfig>)([<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] (KeyValuePair r) => new RequirementConfig { Item = r.Key, Amount = r.Value })).ToArray() }); ItemManager.Instance.AddRecipe(val); } using BundleCache.Scope scope = new BundleCache.Scope("mushbundle"); AssetBundle ab = scope.Bundle; ItemConfig val2 = new ItemConfig(); val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "Tankard", Amount = 1 }, new RequirementConfig { Item = "Coins", Amount = 999 } }; RecipeHelper.addvrpitem("TankardGold", ref ab, val2); val2 = new ItemConfig(); val2.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "Coins", Amount = 20000 } }; RecipeHelper.addvrpitem("BandGold", ref ab, val2); } catch (Exception ex) { ZLog.LogError((object)"error adding vrp items custom food"); if (VRPMod.DebugMode()) { ZLog.LogError((object)ex.Message); } } finally { PrefabManager.OnVanillaPrefabsAvailable -= AddMerchantItems; } } private static void AddMissingRecipes() { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0058: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_00aa: Expected O, but got Unknown //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Expected O, but got Unknown ZLog.Log((object)"VRP Missing Recipes"); try { foreach (KeyValuePair makeItCraftableRecipe in RecipeData.MakeItCraftableRecipes) { CustomRecipe val = new CustomRecipe(new RecipeConfig { Name = makeItCraftableRecipe.Key, Item = makeItCraftableRecipe.Value.Item, Amount = makeItCraftableRecipe.Value.Amount, CraftingStation = makeItCraftableRecipe.Value.CraftingStation, Requirements = ((IEnumerable>)makeItCraftableRecipe.Value.Requirements).Select((Func, RequirementConfig>)([<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] (KeyValuePair r) => new RequirementConfig { Item = r.Key, Amount = r.Value })).ToArray() }); ItemManager.Instance.AddRecipe(val); } } catch (Exception ex) { ZLog.LogError((object)"error adding vrp items custom food"); if (VRPMod.DebugMode()) { ZLog.LogError((object)ex.Message); } } finally { PrefabManager.OnVanillaPrefabsAvailable -= AddMissingRecipes; } } private static void CustomMaterials() { try { using BundleCache.Scope scope = new BundleCache.Scope("Arielle-ValheimRoleplay/Assets/bandage"); AssetBundle bundle = scope.Bundle; RecipeHelper.addMaterial(bundle, "Floam"); RecipeHelper.addMaterial(bundle, "Gloam"); RecipeHelper.addMaterial(bundle, "palm_seed"); RecipeHelper.addMaterial(bundle, "palmer_seed"); RecipeHelper.addMaterial(bundle, "coconut"); addPrefab(bundle, "BubbleSpawnerHuge"); addPrefab(bundle, "BubbleSpawnerBig"); addPrefab(bundle, "BubbleSpawnerSmall"); addPrefab(bundle, "palm_log"); addPrefab(bundle, "palm_log2"); addPrefab(bundle, "palm_loghalf"); addPrefab(bundle, "palm_loghalf2"); addPrefab(bundle, "palm_stub"); addPrefab(bundle, "palm_stub2"); } catch (Exception ex) { ZLog.LogError((object)"error vrp custom materials"); if (VRPMod.DebugMode()) { ZLog.LogError((object)ex.Message); } } finally { PrefabManager.OnVanillaPrefabsAvailable -= CustomMaterials; } } private static void TerrainChanges() { try { GameObject prefab = PrefabManager.Instance.GetPrefab("paved_road_v2"); if (Object.op_Implicit((Object)(object)prefab)) { Piece val = default(Piece); if (prefab.TryGetComponent(ref val)) { val.m_allowAltGroundPlacement = false; val.m_craftingStation = null; if (VRPMod.DebugMode()) { ZLog.Log((object)"[VRP] paved_road_v2: disallow alt placement"); } } TerrainOp val2 = default(TerrainOp); if (prefab.TryGetComponent(ref val2)) { val2.m_settings.m_smooth = false; val2.m_settings.m_level = false; if (VRPMod.DebugMode()) { ZLog.Log((object)"[VRP] paved_road_v2: disable smooth/level"); } } } else if (VRPMod.DebugMode()) { ZLog.LogWarning((object)"[VRP] paved_road_v2 prefab not found"); } GameObject prefab2 = PrefabManager.Instance.GetPrefab("cultivate_v2"); if (Object.op_Implicit((Object)(object)prefab2)) { Piece val3 = default(Piece); if (prefab2.TryGetComponent(ref val3)) { val3.m_allowAltGroundPlacement = false; if (VRPMod.DebugMode()) { ZLog.Log((object)"[VRP] cultivate_v2: disallow alt placement"); } } TerrainOp val4 = default(TerrainOp); if (prefab2.TryGetComponent(ref val4)) { val4.m_settings.m_smooth = false; val4.m_settings.m_level = false; if (VRPMod.DebugMode()) { ZLog.Log((object)"[VRP] cultivate_v2: disable smooth/level"); } } } else if (VRPMod.DebugMode()) { ZLog.LogWarning((object)"[VRP] cultivate_v2 prefab not found"); } } catch (Exception ex) { ZLog.LogError((object)"error vrp terrain changes"); if (VRPMod.DebugMode()) { ZLog.LogError((object)ex.Message); } } finally { PrefabManager.OnVanillaPrefabsAvailable -= TerrainChanges; } } private static void MiscVRPItemsChanges() { //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Expected O, but got Unknown try { foreach (KeyValuePair item in RecipeData.VRP_Misc) { AssetBundle ab = BundleCache.GetBundle(item.Value.BundleKey); if ((Object)(object)ab == (Object)null) { Logger.LogWarning((object)("Missing bundle for recipe: " + item.Key)); continue; } RequirementConfig[] requirements = ((IEnumerable>)item.Value.Requirements).Select((Func, RequirementConfig>)([<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] (KeyValuePair req) => new RequirementConfig { Item = req.Key, Amount = req.Value.baseAmount, AmountPerLevel = req.Value.perLevel })).ToArray(); ItemConfig val = new ItemConfig { CraftingStation = item.Value.CraftingStation, MinStationLevel = item.Value.StationLevel, Requirements = requirements }; if (!string.IsNullOrWhiteSpace(item.Value.Description)) { val.Description = item.Value.Description; } RecipeHelper.addvrpitem(item.Key, ref ab, val); } } catch (Exception ex) { ZLog.LogError((object)"error vrp misc items"); if (VRPMod.DebugMode()) { ZLog.LogError((object)ex.Message); } } finally { PrefabManager.OnVanillaPrefabsAvailable -= MiscVRPItemsChanges; } } internal static void DurabilityIncrease() { ZLog.Log((object)"VRP DURABILITY"); for (int i = 0; i < ObjectDB.instance.m_items.Count; i++) { ObjectDB.instance.m_items[i].GetComponent(); } } private static void PoisonFood() { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Expected O, but got Unknown //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Expected O, but got Unknown //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_006b: Unknown result type (might be due to invalid IL or missing references) //IL_0073: Expected O, but got Unknown //IL_0085: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Expected O, but got Unknown ZLog.Log((object)"VRP SPECIAL CUISINE"); try { ItemConfig val = new ItemConfig(); val.Name = "pDeerStew"; val.Description = "Fall-apart tender"; val.CraftingStation = "piece_cauldron"; val.MinStationLevel = 2; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "DeerStew", Amount = 1 }, new RequirementConfig { Item = "MushroomYellow", Amount = 1 } }; ItemConfig val2 = val; CustomItem val3 = new CustomItem("pDeerStew", "DeerStew", val2); ItemManager.Instance.AddItem(val3); } catch (Exception ex) { ZLog.LogError((object)ex); } finally { PrefabManager.OnPrefabsRegistered -= PoisonFood; } } private static void AddWineBeer() { //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a3: Expected O, but got Unknown //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Expected O, but got Unknown //IL_01ca: Unknown result type (might be due to invalid IL or missing references) //IL_01d1: Expected O, but got Unknown //IL_0273: Unknown result type (might be due to invalid IL or missing references) //IL_027a: Expected O, but got Unknown //IL_0328: Unknown result type (might be due to invalid IL or missing references) //IL_032f: Expected O, but got Unknown //IL_03fb: Unknown result type (might be due to invalid IL or missing references) //IL_0402: Expected O, but got Unknown //IL_03c7: Unknown result type (might be due to invalid IL or missing references) //IL_03d0: Unknown result type (might be due to invalid IL or missing references) //IL_03d9: Unknown result type (might be due to invalid IL or missing references) //IL_03e5: Unknown result type (might be due to invalid IL or missing references) //IL_04b0: Unknown result type (might be due to invalid IL or missing references) //IL_04b7: Expected O, but got Unknown //IL_04ce: Unknown result type (might be due to invalid IL or missing references) //IL_04d5: Expected O, but got Unknown //IL_0507: Unknown result type (might be due to invalid IL or missing references) //IL_050c: Unknown result type (might be due to invalid IL or missing references) //IL_0517: Unknown result type (might be due to invalid IL or missing references) //IL_051f: Expected O, but got Unknown //IL_0521: Unknown result type (might be due to invalid IL or missing references) //IL_0526: Unknown result type (might be due to invalid IL or missing references) //IL_0531: Unknown result type (might be due to invalid IL or missing references) //IL_0539: Expected O, but got Unknown //IL_0540: Unknown result type (might be due to invalid IL or missing references) //IL_0547: Expected O, but got Unknown //IL_0574: Unknown result type (might be due to invalid IL or missing references) //IL_060b: Unknown result type (might be due to invalid IL or missing references) //IL_0612: Expected O, but got Unknown //IL_0644: Unknown result type (might be due to invalid IL or missing references) //IL_0649: Unknown result type (might be due to invalid IL or missing references) //IL_0654: Unknown result type (might be due to invalid IL or missing references) //IL_065c: Expected O, but got Unknown //IL_065e: Unknown result type (might be due to invalid IL or missing references) //IL_0663: Unknown result type (might be due to invalid IL or missing references) //IL_066e: Unknown result type (might be due to invalid IL or missing references) //IL_0676: Expected O, but got Unknown //IL_0678: Unknown result type (might be due to invalid IL or missing references) //IL_067d: Unknown result type (might be due to invalid IL or missing references) //IL_0688: Unknown result type (might be due to invalid IL or missing references) //IL_0690: Expected O, but got Unknown //IL_0692: Unknown result type (might be due to invalid IL or missing references) //IL_0697: Unknown result type (might be due to invalid IL or missing references) //IL_06a2: Unknown result type (might be due to invalid IL or missing references) //IL_06aa: Expected O, but got Unknown //IL_06b1: Unknown result type (might be due to invalid IL or missing references) //IL_06b8: Expected O, but got Unknown //IL_0707: Unknown result type (might be due to invalid IL or missing references) //IL_070e: Expected O, but got Unknown //IL_0741: Unknown result type (might be due to invalid IL or missing references) //IL_0746: Unknown result type (might be due to invalid IL or missing references) //IL_0751: Unknown result type (might be due to invalid IL or missing references) //IL_0759: Expected O, but got Unknown //IL_0760: Unknown result type (might be due to invalid IL or missing references) //IL_0767: Expected O, but got Unknown //IL_0794: Unknown result type (might be due to invalid IL or missing references) //IL_0821: Unknown result type (might be due to invalid IL or missing references) //IL_0826: Unknown result type (might be due to invalid IL or missing references) //IL_0831: Unknown result type (might be due to invalid IL or missing references) //IL_083c: Unknown result type (might be due to invalid IL or missing references) //IL_0849: Expected O, but got Unknown //IL_0844: Unknown result type (might be due to invalid IL or missing references) //IL_084b: Expected O, but got Unknown //IL_0862: Unknown result type (might be due to invalid IL or missing references) //IL_0869: Expected O, but got Unknown //IL_089b: Unknown result type (might be due to invalid IL or missing references) //IL_08a0: Unknown result type (might be due to invalid IL or missing references) //IL_08ab: Unknown result type (might be due to invalid IL or missing references) //IL_08b3: Expected O, but got Unknown //IL_08b5: Unknown result type (might be due to invalid IL or missing references) //IL_08ba: Unknown result type (might be due to invalid IL or missing references) //IL_08c5: Unknown result type (might be due to invalid IL or missing references) //IL_08cd: Expected O, but got Unknown //IL_08cf: Unknown result type (might be due to invalid IL or missing references) //IL_08d4: Unknown result type (might be due to invalid IL or missing references) //IL_08df: Unknown result type (might be due to invalid IL or missing references) //IL_08e7: Expected O, but got Unknown //IL_08ee: Unknown result type (might be due to invalid IL or missing references) //IL_08f5: Expected O, but got Unknown //IL_0944: Unknown result type (might be due to invalid IL or missing references) //IL_094b: Expected O, but got Unknown //IL_0969: Unknown result type (might be due to invalid IL or missing references) //IL_096e: Unknown result type (might be due to invalid IL or missing references) //IL_0979: Unknown result type (might be due to invalid IL or missing references) //IL_0981: Expected O, but got Unknown //IL_0988: Unknown result type (might be due to invalid IL or missing references) //IL_098f: Expected O, but got Unknown //IL_09bc: Unknown result type (might be due to invalid IL or missing references) //IL_0a49: Unknown result type (might be due to invalid IL or missing references) //IL_0a4e: Unknown result type (might be due to invalid IL or missing references) //IL_0a59: Unknown result type (might be due to invalid IL or missing references) //IL_0a64: Unknown result type (might be due to invalid IL or missing references) //IL_0a71: Expected O, but got Unknown //IL_0a6c: Unknown result type (might be due to invalid IL or missing references) //IL_0a73: Expected O, but got Unknown ZLog.Log((object)"VRP WINE"); try { ItemDrop component = PrefabManager.Instance.GetPrefab("MeadTasty").GetComponent(); StatusEffect obj = Object.Instantiate(component.m_itemData.m_shared.m_consumeStatusEffect); SE_Stats val = (SE_Stats)(object)((obj is SE_Stats) ? obj : null); if ((Object)(object)val != (Object)null) { ((Object)val).name = "se_alcohol"; ((StatusEffect)val).m_cooldown = 3f; ((StatusEffect)val).m_name = "Tipsy"; ((StatusEffect)val).m_tooltip = "Alcohol is great!"; val.m_healthOverTime = 0f; val.m_staminaRegenMultiplier = 3f; val.m_healthRegenMultiplier = 0.5f; ((StatusEffect)val).m_ttl = 10f; } CustomStatusEffect val2 = new CustomStatusEffect((StatusEffect)(object)val, false); ItemManager.Instance.AddStatusEffect(val2); StatusEffect obj2 = Object.Instantiate(component.m_itemData.m_shared.m_consumeStatusEffect); SE_Stats val3 = (SE_Stats)(object)((obj2 is SE_Stats) ? obj2 : null); if ((Object)(object)val3 != (Object)null) { ((Object)val3).name = "Musty"; ((StatusEffect)val3).m_cooldown = 300f; ((StatusEffect)val3).m_name = "Musty"; ((StatusEffect)val3).m_tooltip = "this feels strange"; val3.m_healthOverTime = 0f; val3.m_staminaRegenMultiplier = 1f; val3.m_healthRegenMultiplier = 1f; ((StatusEffect)val3).m_ttl = 600f; } CustomStatusEffect val4 = new CustomStatusEffect((StatusEffect)(object)val3, false); ItemManager.Instance.AddStatusEffect(val4); StatusEffect obj3 = Object.Instantiate(component.m_itemData.m_shared.m_consumeStatusEffect); SE_Stats val5 = (SE_Stats)(object)((obj3 is SE_Stats) ? obj3 : null); if ((Object)(object)val5 != (Object)null) { ((Object)val5).name = "Poozy"; ((StatusEffect)val5).m_cooldown = 600f; ((StatusEffect)val5).m_name = "Poozy"; ((StatusEffect)val5).m_tooltip = "i have a sinking feeling about this"; val5.m_healthOverTime = 0f; val5.m_staminaRegenMultiplier = 1f; val5.m_healthRegenMultiplier = 1f; ((StatusEffect)val5).m_ttl = 20f; } CustomStatusEffect val6 = new CustomStatusEffect((StatusEffect)(object)val5, false); ItemManager.Instance.AddStatusEffect(val6); StatusEffect obj4 = Object.Instantiate(component.m_itemData.m_shared.m_consumeStatusEffect); SE_Stats val7 = (SE_Stats)(object)((obj4 is SE_Stats) ? obj4 : null); if ((Object)(object)val7 != (Object)null) { ((Object)val7).name = "se_juiced"; ((StatusEffect)val7).m_cooldown = 15f; ((StatusEffect)val7).m_name = "Juiced"; ((StatusEffect)val7).m_tooltip = "Sugar Rush zoom zoom!"; val7.m_healthOverTime = 0f; val7.m_staminaRegenMultiplier = 1f; val7.m_healthRegenMultiplier = 1f; val7.m_speedModifier = 0.2f; ((StatusEffect)val7).m_ttl = 120f; } CustomStatusEffect val8 = new CustomStatusEffect((StatusEffect)(object)val7, false); ItemManager.Instance.AddStatusEffect(val8); StatusEffect obj5 = Object.Instantiate(component.m_itemData.m_shared.m_consumeStatusEffect); SE_Stats val9 = (SE_Stats)(object)((obj5 is SE_Stats) ? obj5 : null); if ((Object)(object)val9 != (Object)null) { ((Object)val9).name = "se_juiced2"; ((StatusEffect)val9).m_cooldown = 15f; ((StatusEffect)val9).m_name = "Jacked"; ((StatusEffect)val9).m_tooltip = "SWEET! You feel stamina returning slowly!"; val9.m_healthOverTime = 0f; val9.m_staminaRegenMultiplier = 1f; val9.m_healthRegenMultiplier = 1f; val9.m_staminaOverTime = 240f; val9.m_staminaOverTimeDuration = 120f; ((StatusEffect)val9).m_ttl = 120f; } CustomStatusEffect val10 = new CustomStatusEffect((StatusEffect)(object)val9, false); ItemManager.Instance.AddStatusEffect(val10); StatusEffect obj6 = Object.Instantiate(component.m_itemData.m_shared.m_consumeStatusEffect); SE_Stats val11 = (SE_Stats)(object)((obj6 is SE_Stats) ? obj6 : null); if ((Object)(object)val11 != (Object)null) { ((Object)val11).name = "se_hot"; ((StatusEffect)val11).m_cooldown = 60f; ((StatusEffect)val11).m_name = "HOT"; ((StatusEffect)val11).m_tooltip = "IT BURNS"; val11.m_healthOverTime = 0f; val11.m_staminaRegenMultiplier = 1f; val11.m_healthRegenMultiplier = 1f; val11.m_runStaminaDrainModifier = -0.2f; DamageModPair item = default(DamageModPair); item.m_modifier = (DamageModifier)1; item.m_type = (DamageType)64; val11.m_mods.Add(item); ((StatusEffect)val11).m_ttl = 120f; } CustomStatusEffect val12 = new CustomStatusEffect((StatusEffect)(object)val11, false); ItemManager.Instance.AddStatusEffect(val12); StatusEffect obj7 = Object.Instantiate(component.m_itemData.m_shared.m_consumeStatusEffect); SE_Stats val13 = (SE_Stats)(object)((obj7 is SE_Stats) ? obj7 : null); if ((Object)(object)val13 != (Object)null) { ((Object)val13).name = "se_joy"; ((StatusEffect)val13).m_cooldown = 5f; ((StatusEffect)val13).m_name = "Joy"; ((StatusEffect)val13).m_tooltip = "HAPPY HAPPY JOY JOY"; val13.m_healthOverTime = 0f; val13.m_staminaRegenMultiplier = 1f; val13.m_healthRegenMultiplier = 1f; val13.m_addMaxCarryWeight = 100f; val13.m_jumpStaminaUseModifier = -1f; ((StatusEffect)val13).m_ttl = 240f; } CustomStatusEffect val14 = new CustomStatusEffect((StatusEffect)(object)val13, false); ItemManager.Instance.AddStatusEffect(val14); ItemConfig val15 = new ItemConfig(); val15.Description = "AHHHHH ITS HOT"; val15.Amount = 2; val15.CraftingStation = "piece_cauldron"; val15.MinStationLevel = 1; val15.Requirements = (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "SurtlingCore", Amount = 1 }, new RequirementConfig { Item = "Honey", Amount = 5 } }; CustomItem val16 = new CustomItem("FireWater", "MeadTasty", val15); val16.ItemDrop.m_itemData.m_shared.m_name = "FireWater"; val16.ItemDrop.m_itemData.m_shared.m_itemType = (ItemType)2; val16.ItemDrop.m_itemData.m_shared.m_ammoType = component.m_itemData.m_shared.m_ammoType; val16.ItemDrop.m_itemData.m_shared.m_attack.m_attackAnimation = "emote_drink"; val16.ItemDrop.m_itemData.m_shared.m_consumeStatusEffect = val12.StatusEffect; val16.ItemDrop.m_itemData.m_shared.m_maxStackSize = 10; ItemManager.Instance.AddItem(val16); val15 = new ItemConfig(); val15.Description = "This mush smells quite pleasant, throw it in a fermenter?"; val15.Amount = 1; val15.CraftingStation = "piece_cauldron"; val15.MinStationLevel = 1; val15.Requirements = (RequirementConfig[])(object)new RequirementConfig[4] { new RequirementConfig { Item = "Dandelion", Amount = 5 }, new RequirementConfig { Item = "GreydwarfEye", Amount = 5 }, new RequirementConfig { Item = "Thistle", Amount = 5 }, new RequirementConfig { Item = "Honey", Amount = 5 } }; CustomItem val17 = new CustomItem("MushJoy", "MeadBaseTasty", val15); val17.ItemDrop.m_itemData.m_shared.m_name = "Flower Mush"; val17.ItemDrop.m_itemData.m_shared.m_consumeStatusEffect = val14.StatusEffect; ItemManager.Instance.AddItem(val17); val15 = new ItemConfig(); val15.Description = "A robust, bittersweet liquor full of the pleasant flavors of hope and the subtle notes of sorrow."; val15.Amount = 20; val15.CraftingStation = ""; val15.MinStationLevel = 1; val15.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "SledgeCheat", Amount = 1 } }; CustomItem val18 = new CustomItem("JoyWine", "BarleyWine", val15); val18.ItemDrop.m_itemData.m_shared.m_name = "Flower Wine"; val18.ItemDrop.m_itemData.m_shared.m_itemType = (ItemType)2; val18.ItemDrop.m_itemData.m_shared.m_ammoType = component.m_itemData.m_shared.m_ammoType; val18.ItemDrop.m_itemData.m_shared.m_attack.m_attackAnimation = "emote_drink"; val18.ItemDrop.m_itemData.m_shared.m_consumeStatusEffect = val14.StatusEffect; val18.ItemDrop.m_itemData.m_shared.m_maxStackSize = 20; ItemManager.Instance.AddItem(val18); CustomItemConversion val19 = new CustomItemConversion((ConversionConfig)new FermenterConversionConfig { FromItem = "MushJoy", ToItem = "JoyWine", ProducedItems = 10 }); ItemManager.Instance.AddItemConversion(val19); val15 = new ItemConfig(); val15.Description = "Well we mushed up some stuff, lets ferment it and see what happens"; val15.Amount = 1; val15.CraftingStation = "piece_cauldron"; val15.MinStationLevel = 1; val15.Requirements = (RequirementConfig[])(object)new RequirementConfig[3] { new RequirementConfig { Item = "Pukeberries", Amount = 2 }, new RequirementConfig { Item = "Ooze", Amount = 2 }, new RequirementConfig { Item = "Dandelion", Amount = 5 } }; CustomItem val20 = new CustomItem("MushSwamp", "MeadBaseTasty", val15); val20.ItemDrop.m_itemData.m_shared.m_name = "Swamp Mush"; val20.ItemDrop.m_itemData.m_shared.m_consumeStatusEffect = val6.StatusEffect; ItemManager.Instance.AddItem(val20); val15 = new ItemConfig(); val15.Description = "Cloudy, Murky, I guess it's still drinkable right?"; val15.Amount = 1; val15.Requirements = (RequirementConfig[])(object)new RequirementConfig[1] { new RequirementConfig { Item = "SledgeCheat", Amount = 2 } }; CustomItem val21 = new CustomItem("BeerSwamp", "Tankard", val15); val21.ItemDrop.m_itemData.m_shared.m_name = "Poozle"; val21.ItemDrop.m_itemData.m_shared.m_itemType = (ItemType)2; val21.ItemDrop.m_itemData.m_shared.m_ammoType = component.m_itemData.m_shared.m_ammoType; val21.ItemDrop.m_itemData.m_shared.m_attack.m_attackAnimation = "emote_drink"; val21.ItemDrop.m_itemData.m_shared.m_consumeStatusEffect = val6.StatusEffect; val21.ItemDrop.m_itemData.m_shared.m_maxStackSize = 30; ItemManager.Instance.AddItem(val21); CustomItemConversion val22 = new CustomItemConversion((ConversionConfig)new FermenterConversionConfig { FromItem = "MushSwamp", ToItem = "BeerSwamp", ProducedItems = 10 }); ItemManager.Instance.AddItemConversion(val22); } catch (Exception ex) { ZLog.LogError((object)ex); } finally { PrefabManager.OnPrefabsRegistered -= AddWineBeer; } } private static void EditStatusEffects() { //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_01c1: Unknown result type (might be due to invalid IL or missing references) //IL_01e0: Unknown result type (might be due to invalid IL or missing references) //IL_01ff: Unknown result type (might be due to invalid IL or missing references) ZLog.LogWarning((object)("VRP found status effects " + ObjectDB.instance.m_StatusEffects.Count())); for (int i = 0; i < ObjectDB.instance.m_StatusEffects.Count(); i++) { ZLog.LogWarning((object)ObjectDB.instance.m_StatusEffects[i].m_name); if (ObjectDB.instance.m_StatusEffects[i].m_name == "Chieftain - Boar") { ((SE_Stats)ObjectDB.instance.m_StatusEffects[i]).m_staminaRegenMultiplier = 1f; ((SE_Stats)ObjectDB.instance.m_StatusEffects[i]).m_healthRegenMultiplier = 1f; ((SE_Stats)ObjectDB.instance.m_StatusEffects[i]).m_skillLevel = (SkillType)10; ((SE_Stats)ObjectDB.instance.m_StatusEffects[i]).m_skillLevelModifier = 2f; ((SE_Stats)ObjectDB.instance.m_StatusEffects[i]).m_skillLevel2 = (SkillType)9; ((SE_Stats)ObjectDB.instance.m_StatusEffects[i]).m_skillLevelModifier2 = 2f; ((StatusEffect)(SE_Stats)ObjectDB.instance.m_StatusEffects[i]).m_tooltip = "vrp"; GameObject prefab = PrefabManager.Instance.GetPrefab("chiefhelmboar"); if ((Object)(object)prefab != (Object)null) { ItemDrop component = prefab.GetComponent(); if ((Object)(object)component != (Object)null) { component.m_itemData.m_shared.m_setStatusEffect = ObjectDB.instance.m_StatusEffects[i]; } } } if (!(ObjectDB.instance.m_StatusEffects[i].m_name == "Chieftain - Deer")) { continue; } ((SE_Stats)ObjectDB.instance.m_StatusEffects[i]).m_skillLevelModifier = 2f; ((SE_Stats)ObjectDB.instance.m_StatusEffects[i]).m_runStaminaDrainModifier = 0f; ((StatusEffect)(SE_Stats)ObjectDB.instance.m_StatusEffects[i]).m_tooltip = "vrp"; GameObject prefab2 = PrefabManager.Instance.GetPrefab("chiefhelmdeer"); if ((Object)(object)prefab2 != (Object)null) { ItemDrop component2 = prefab2.GetComponent(); if ((Object)(object)component2 != (Object)null) { component2.m_itemData.m_shared.m_setStatusEffect = ObjectDB.instance.m_StatusEffects[i]; } } } GameObject prefab3 = PrefabManager.Instance.GetPrefab("MeadPoisonResist"); if ((Object)(object)prefab3 != (Object)null) { ItemDrop component3 = prefab3.GetComponent(); if ((Object)(object)component3 != (Object)null) { component3.m_itemData.m_shared.m_consumeStatusEffect.m_ttl = 360f; } } GameObject prefab4 = PrefabManager.Instance.GetPrefab("MeadFrostResist"); if ((Object)(object)prefab4 != (Object)null) { ItemDrop component4 = prefab4.GetComponent(); if ((Object)(object)component4 != (Object)null) { component4.m_itemData.m_shared.m_consumeStatusEffect.m_ttl = 360f; } } } private static void AddFishItems() { //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_001a: Expected O, but got Unknown //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Expected O, but got Unknown //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Unknown result type (might be due to invalid IL or missing references) //IL_0071: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Expected O, but got Unknown //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Expected O, but got Unknown //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Expected O, but got Unknown //IL_0111: Unknown result type (might be due to invalid IL or missing references) //IL_0117: Expected O, but got Unknown //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_0149: Unknown result type (might be due to invalid IL or missing references) //IL_0154: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Expected O, but got Unknown //IL_015e: Unknown result type (might be due to invalid IL or missing references) //IL_0163: Unknown result type (might be due to invalid IL or missing references) //IL_016e: Unknown result type (might be due to invalid IL or missing references) //IL_0176: Expected O, but got Unknown //IL_0178: Unknown result type (might be due to invalid IL or missing references) //IL_017d: Unknown result type (might be due to invalid IL or missing references) //IL_0188: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Expected O, but got Unknown //IL_0196: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Expected O, but got Unknown //IL_01f4: Unknown result type (might be due to invalid IL or missing references) //IL_01fa: Expected O, but got Unknown //IL_0227: Unknown result type (might be due to invalid IL or missing references) //IL_022c: Unknown result type (might be due to invalid IL or missing references) //IL_0237: Unknown result type (might be due to invalid IL or missing references) //IL_023f: Expected O, but got Unknown //IL_0241: Unknown result type (might be due to invalid IL or missing references) //IL_0246: Unknown result type (might be due to invalid IL or missing references) //IL_0251: Unknown result type (might be due to invalid IL or missing references) //IL_0259: Expected O, but got Unknown //IL_025f: Unknown result type (might be due to invalid IL or missing references) //IL_0265: Expected O, but got Unknown ZLog.Log((object)"VRP FISH"); try { ItemConfig val = new ItemConfig(); val.Description = "smells strongly of fish with shiny bits"; val.Amount = 2; val.CraftingStation = "piece_cauldron"; val.MinStationLevel = 1; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[3] { new RequirementConfig { Item = "FishRaw", Amount = 4 }, new RequirementConfig { Item = "MushroomBlue", Amount = 1 }, new RequirementConfig { Item = "Thistle", Amount = 2 } }; CustomItem val2 = new CustomItem("FishSoup", "BlackSoup", val); val2.ItemDrop.m_itemData.m_shared.m_name = "Fish Soup"; val2.ItemDrop.m_itemData.m_shared.m_food = 30f; val2.ItemDrop.m_itemData.m_shared.m_foodStamina = 60f; val2.ItemDrop.m_itemData.m_shared.m_foodBurnTime = 3000f; val = new ItemConfig(); val.Description = "crispy, sweet, and salty!"; val.Amount = 2; val.CraftingStation = "piece_cauldron"; val.MinStationLevel = 1; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[3] { new RequirementConfig { Item = "FishRaw", Amount = 4 }, new RequirementConfig { Item = "Mushroom", Amount = 2 }, new RequirementConfig { Item = "Carrot", Amount = 2 } }; CustomItem val3 = new CustomItem("FishSkewer", "WolfMeatSkewer", val); val3.ItemDrop.m_itemData.m_shared.m_name = "Fish Skewer"; val3.ItemDrop.m_itemData.m_shared.m_food = 58f; val3.ItemDrop.m_itemData.m_shared.m_foodStamina = 22f; val = new ItemConfig(); val.Description = "fish thats been frozen so it stays fresh longer!"; val.Amount = 2; val.CraftingStation = "piece_cauldron"; val.MinStationLevel = 1; val.Requirements = (RequirementConfig[])(object)new RequirementConfig[2] { new RequirementConfig { Item = "FishRaw", Amount = 4 }, new RequirementConfig { Item = "FreezeGland", Amount = 2 } }; CustomItem val4 = new CustomItem("FishFrozen", "FishCooked", val); val4.ItemDrop.m_itemData.m_shared.m_name = "Fish Freeze"; val4.ItemDrop.m_itemData.m_shared.m_food = 50f; val4.ItemDrop.m_itemData.m_shared.m_foodStamina = 50f; val4.ItemDrop.m_itemData.m_shared.m_foodRegen = 5f; val4.ItemDrop.m_itemData.m_shared.m_foodBurnTime = 3600f; ItemManager.Instance.AddItem(val2); ItemManager.Instance.AddItem(val3); ItemManager.Instance.AddItem(val4); ServingTrayHelper.AddToServingTray(val2); ServingTrayHelper.AddToServingTray(val3); ServingTrayHelper.AddToServingTray(val4); } catch (Exception ex) { ZLog.LogError((object)"error adding fishitems"); ZLog.LogError((object)ex); } finally { PrefabManager.OnPrefabsRegistered -= AddFishItems; } } private static void addPrefab(AssetBundle bundle, string prefabname) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown try { GameObject val = bundle.LoadAsset(prefabname); if (Object.op_Implicit((Object)(object)val)) { PrefabManager.Instance.AddPrefab(new CustomPrefab(val, true)); if (VRPMod.DebugMode()) { ZLog.Log((object)("vrp added prefab " + prefabname)); } } else { ZLog.LogWarning((object)("vrp did not find prefab " + prefabname)); } } catch (Exception ex) { Logger.LogError((object)("vrp failed to add prefab " + prefabname)); Logger.LogError((object)ex); } } private static void addPiece(AssetBundle bundle, string prefabname, RequirementConfig[] reqs, string category = "Misc") { //IL_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Expected O, but got Unknown //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Expected O, but got Unknown try { GameObject val = bundle.LoadAsset(prefabname); if (!Object.op_Implicit((Object)(object)val)) { return; } if (Object.op_Implicit((Object)(object)val.GetComponent())) { Transform val2 = (from k in val.GetComponentsInChildren() where ((Object)((Component)k).gameObject).name == "sail_full" select k).FirstOrDefault(); if (Object.op_Implicit((Object)(object)val2)) { SkinnedMeshRenderer component = ((Component)val2).gameObject.GetComponent(); if (Object.op_Implicit((Object)(object)component)) { Material[] sharedMaterials = ((Renderer)component).sharedMaterials; foreach (Material obj in sharedMaterials) { string name = ((Object)obj.shader).name; obj.shader = Shader.Find(name); } } } } CustomPiece val3 = new CustomPiece(val, true, new PieceConfig { PieceTable = "Hammer", Category = category, Requirements = reqs }); if (val3 != null) { if (VRPMod.DebugMode()) { ZLog.Log((object)("vrp added piece " + prefabname)); } PieceManager.Instance.AddPiece(val3); } } catch (Exception ex) { Logger.LogError((object)("vrp failed to add piece " + prefabname)); Logger.LogError((object)ex); } } } internal class ListPatches { [HarmonyPatch(typeof(ZNet), "GetOtherPublicPlayers")] private class playpinsadminmap { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool Prefix(ref List playerList, ref ZNet __instance) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_0026: Unknown result type (might be due to invalid IL or missing references) //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) foreach (PlayerInfo player in __instance.m_players) { if (player.m_publicPosition || ClientPatches.isAdmin()) { ZDOID characterID = player.m_characterID; if (!((ZDOID)(ref characterID)).IsNone() && !(player.m_characterID == __instance.m_characterID)) { playerList.Add(player); } } } return false; } } } public static class Extensions { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static T[] Append<[Nullable(2)] T>(this T[] array, T item) { if (array == null) { return new T[1] { item }; } T[] array2 = new T[array.Length + 1]; array.CopyTo(array2, 0); array2[array.Length] = item; return array2; } } internal class ObjectdbPatches { [HarmonyPatch(typeof(PieceTable), "UpdateAvailable")] private class buildpicesfix { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Prefix(HashSet knownRecipies, Player player, bool hideUnavailable, bool noPlacementCost, PieceTable __instance) { foreach (GameObject piece in __instance.m_pieces) { if ((Object)(object)piece == (Object)null) { continue; } Piece component = piece.GetComponent(); if ((Object)(object)component != (Object)null) { bool flag = isPieceDisabledFast(component.m_name); if (VRPMod.DebugMode()) { ZLog.Log((object)$"Piece {component.m_name} disabled:{flag}"); } component.m_enabled = !flag; if (!(component.m_name == "Ward") && !(component.m_name == "$piece_guardstone")) { } } else { bool flag2 = isPieceDisabledFast(((Object)piece).name); piece.SetActive(!flag2); if (VRPMod.DebugMode() && flag2) { ZLog.Log((object)(((Object)piece).name + "disabled")); } } } } } [HarmonyPatch(typeof(Player), "GetAvailableRecipes")] private class hideRecipes { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref List available) { if (VRPMod.DebugMode()) { ZLog.Log((object)$"[VRP Custom] GetAvailableRecipes Postfix running. Current count: {available.Count}"); } List list = new List(); foreach (Recipe item in available) { if (isDisabled(item.m_item.m_itemData.m_shared.m_name)) { list.Add(item); } } foreach (Recipe item2 in list) { available.Remove(item2); } } } [HarmonyPatch(typeof(ObjectDB), "Awake")] internal class ObjectDBPatch { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ObjectDB __instance) { if ((Object)(object)__instance != (Object)null && __instance.m_items.Count > 0) { ZLog.Log((object)"ObjectDB Awake patched. Applying balance..."); BalancePatches.ApplyBalanceTweaks(); } } } [HarmonyPatch(typeof(Character), "Awake")] private class leveleffectspatch { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref Character __instance) { if (__instance.m_onLevelSet == null && (Object)(object)__instance.m_visual != (Object)null && (Object)(object)((Component)__instance).GetComponentInChildren() == (Object)null) { __instance.m_visual.SetActive(false); LevelEffects obj = ((Component)__instance).gameObject.AddComponent(); obj.m_character = __instance; obj.m_baseEnableObject = null; obj.m_mainRender = __instance.m_visual.GetComponentInChildren(); __instance.m_visual.SetActive(true); } } } [HarmonyPatch(typeof(LevelEffects), "Start")] private class ApplyLevelVisualisationPatch { private static float mobScale = 0f; private static float maxMobLevel = 11f; [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Prefix(ref LevelEffects __instance) { //IL_002c: Unknown result type (might be due to invalid IL or missing references) //IL_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Expected O, but got Unknown //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Expected O, but got Unknown //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00ef: Expected O, but got Unknown float num = 1f; Character componentInParent = ((Component)__instance).GetComponentInParent(); if ((Object)(object)componentInParent != (Object)null) { GameObject visual = componentInParent.GetVisual(); if (Object.op_Implicit((Object)(object)visual)) { num = visual.transform.localScale.x; } else { ZLog.LogWarning((object)"did not find visual"); } } else { ZLog.LogWarning((object)"did not find character"); } if (__instance.m_levelSetups.Count == 0) { LevelSetup val = new LevelSetup(); val.m_scale = num; val.m_hue = 0.3f; val.m_saturation = 0.3f; val.m_value = 0.1f; __instance.m_levelSetups.Add(val); LevelSetup item = new LevelSetup(); val.m_scale = num + num * mobScale; val.m_hue = 0.4f; val.m_saturation = 0.35f; val.m_value = 0.15f; __instance.m_levelSetups.Add(item); } for (int i = 2; (float)i <= maxMobLevel; i++) { LevelSetup val2 = new LevelSetup(); LevelSetup val3 = __instance.m_levelSetups[i - 1]; LevelSetup val4 = __instance.m_levelSetups[i - 2]; val2.m_scale = val3.m_scale + num * mobScale; val2.m_hue = val3.m_hue * 1.5f - val4.m_hue; val2.m_saturation = val3.m_saturation * 1.5f - val4.m_saturation; val2.m_value = val3.m_value * 1.5f - val4.m_value; val2.m_enableObject = val3.m_enableObject; __instance.m_levelSetups.Add(val2); } if ((Object)(object)componentInParent != (Object)null && Object.op_Implicit((Object)(object)componentInParent.GetVisual())) { componentInParent.m_visual.SetActive(false); componentInParent.m_visual.SetActive(true); } } } public static void RebuildDisabledCache() { ClientPatches.disabledPiecesCache.Clear(); if (ClientPatches.isAdmin()) { return; } foreach (DbPieces piece in ClientPatches.pieces) { if (piece.is_enabled == 0) { ClientPatches.disabledPiecesCache.Add(piece.itemName); if (VRPMod.DebugMode()) { ZLog.Log((object)("Piece disabled globally: " + piece.itemName)); } } else if (!string.IsNullOrWhiteSpace(piece.groups) && !(from g in piece.groups.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries) select g.Trim()).Any((string req) => ClientPatches.groupSet.Contains(req))) { ClientPatches.disabledPiecesCache.Add(piece.itemName); if (VRPMod.DebugMode()) { ZLog.Log((object)("Piece disabled for player: " + piece.itemName)); } } } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static bool isPieceDisabledFast(string pieceName) { if (ClientPatches.isAdmin()) { return false; } return ClientPatches.disabledPiecesCache.Contains(pieceName); } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static bool isDisabled(string recipeName) { if (ClientPatches.isAdmin()) { return false; } if (ClientPatches.recipes == null || ClientPatches.recipes.Count == 0) { return false; } try { DbRecipe dbRecipe = ClientPatches.recipes.FirstOrDefault((DbRecipe r) => r.recipeName.Equals(recipeName, StringComparison.OrdinalIgnoreCase) || r.itemName.Equals(recipeName, StringComparison.OrdinalIgnoreCase)); if (dbRecipe == null) { return false; } if (dbRecipe.is_enabled == 0) { return true; } if (!string.IsNullOrWhiteSpace(dbRecipe.groups)) { Player localPlayer = Player.m_localPlayer; string text = ((localPlayer != null) ? localPlayer.GetPlayerName() : null); if (string.IsNullOrEmpty(text)) { return false; } List myGroups = ClientPatches.groups; bool flag = (from g in dbRecipe.groups.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries) select g.Trim()).ToList().Any((string req) => myGroups.Any((string myG) => myG.Equals(req, StringComparison.OrdinalIgnoreCase))); if (VRPMod.DebugMode()) { ZLog.Log((object)$"[VRP] {text} | Recipe: {recipeName} | Has Access: {flag} | Groups Found: {myGroups.Count}"); } return !flag; } } catch (Exception ex) { ZLog.LogError((object)("[VRP] Error in isDisabled for " + recipeName + ": " + ex.Message)); return false; } return false; } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static bool isPieceDisabled(string pieceName) { if (ClientPatches.isAdmin()) { return false; } if (ClientPatches.pieces == null || ClientPatches.pieces.Count == 0) { return false; } try { DbPieces dbPieces = ClientPatches.pieces.FirstOrDefault((DbPieces p) => p.itemName != null && (p.itemName.Equals(pieceName, StringComparison.OrdinalIgnoreCase) || p.itemName.Equals(pieceName.TrimStart(new char[1] { '$' }), StringComparison.OrdinalIgnoreCase))); if (dbPieces == null) { ZLog.LogWarning((object)("Piece " + pieceName + " not found. Default allow.")); return false; } if (dbPieces.is_enabled == 0) { return true; } if (!string.IsNullOrWhiteSpace(dbPieces.groups)) { Player localPlayer = Player.m_localPlayer; string text = ((localPlayer != null) ? localPlayer.GetPlayerName() : null); if (string.IsNullOrEmpty(text)) { return false; } List source = (from g in dbPieces.groups.Split(new char[1] { ',' }, StringSplitOptions.RemoveEmptyEntries) select g.Trim()).ToList(); List myGroups = ClientPatches.groups; bool flag = source.Any((string req) => myGroups.Any((string myG) => myG.Equals(req, StringComparison.OrdinalIgnoreCase))); if (VRPMod.DebugMode()) { ZLog.Log((object)$"[VRP] {text} | Piece: {pieceName} | Has Access: {flag} | Groups Found: {myGroups.Count}"); } return !flag; } } catch (Exception ex) { ZLog.LogError((object)("[VRP] Error in isPieceDisabled for " + pieceName + ": " + ex.Message)); } return false; } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [Nullable(0)] public class PickableReplacer { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] [HarmonyPatch(typeof(Pickable), "Awake")] public static class Pickable_Awake { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref Pickable __instance) { string prefabName = __instance.m_nview.GetPrefabName(); if (prefabName == "Pickable_DvergrMineTreasure") { __instance.m_amount = 0; __instance.m_minAmountScaled = 0; __instance.m_extraDrops.m_drops = INFESTED_MINE_RANDOM_ITEMS; } if (prefabName == "Pickable_MeatPile") { __instance.m_extraDrops.m_drops = MEAT_PILE_RANDOM_ITEMS; } } } [HarmonyPatch(typeof(PickableItem), "SetupRandomPrefab")] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] public static class PickableItem_SetupRandomPrefab { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Prefix(ref PickableItem __instance) { switch (__instance.m_nview.GetPrefabName()) { case "Pickable_ForestCryptRandom": __instance.m_randomItemPrefabs = FOREST_CRYPT_RANDOM_ITEMS.ToArray(); break; case "Pickable_SunkenCryptRandom": __instance.m_randomItemPrefabs = SUNKEN_CRYPT_RANDOM_ITEMS.ToArray(); break; case "Pickable_MountainCaveRandom": __instance.m_randomItemPrefabs = MOUNTAIN_CAVE_RANDOM_ITEMS.ToArray(); break; case "Pickable_Item": __instance.m_randomItemPrefabs = GENERIC_RANDOM_ITEMS.ToArray(); break; } } } private static readonly List GENERIC_RANDOM_ITEMS = new List { new RandomItem { m_itemPrefab = ObjectDB.instance.GetItemPrefab("Stone").GetComponent(), m_stackMin = 1, m_stackMax = 5 } }; private static readonly List FOREST_CRYPT_RANDOM_ITEMS = new List { new RandomItem { m_itemPrefab = ObjectDB.instance.GetItemPrefab("Carrot").GetComponent(), m_stackMin = 1, m_stackMax = 5 }, new RandomItem { m_itemPrefab = ObjectDB.instance.GetItemPrefab("Blueberries").GetComponent(), m_stackMin = 1, m_stackMax = 5 }, new RandomItem { m_itemPrefab = ObjectDB.instance.GetItemPrefab("Raspberry").GetComponent(), m_stackMin = 1, m_stackMax = 5 } }; private static readonly List SUNKEN_CRYPT_RANDOM_ITEMS = new List { new RandomItem { m_itemPrefab = ObjectDB.instance.GetItemPrefab("WitheredBone").GetComponent(), m_stackMin = 1, m_stackMax = 1 }, new RandomItem { m_itemPrefab = ObjectDB.instance.GetItemPrefab("WitheredBone").GetComponent(), m_stackMin = 1, m_stackMax = 1 }, new RandomItem { m_itemPrefab = ObjectDB.instance.GetItemPrefab("Thistle").GetComponent(), m_stackMin = 1, m_stackMax = 3 }, new RandomItem { m_itemPrefab = ObjectDB.instance.GetItemPrefab("Thistle").GetComponent(), m_stackMin = 1, m_stackMax = 3 }, new RandomItem { m_itemPrefab = ObjectDB.instance.GetItemPrefab("Turnip").GetComponent(), m_stackMin = 1, m_stackMax = 3 }, new RandomItem { m_itemPrefab = ObjectDB.instance.GetItemPrefab("Stone").GetComponent(), m_stackMin = 1, m_stackMax = 5 } }; private static readonly List MOUNTAIN_CAVE_RANDOM_ITEMS = new List { new RandomItem { m_itemPrefab = ObjectDB.instance.GetItemPrefab("WolfHairBundle").GetComponent(), m_stackMin = 1, m_stackMax = 1 }, new RandomItem { m_itemPrefab = ObjectDB.instance.GetItemPrefab("WolfClaw").GetComponent(), m_stackMin = 1, m_stackMax = 1 } }; private static readonly List INFESTED_MINE_RANDOM_ITEMS = new List { new DropData { m_item = ObjectDB.instance.GetItemPrefab("Softtissue"), m_stackMin = 2, m_stackMax = 5, m_weight = 1f, m_dontScale = false }, new DropData { m_item = ObjectDB.instance.GetItemPrefab("GiantBloodSack"), m_stackMin = 1, m_stackMax = 2, m_weight = 1f, m_dontScale = false }, new DropData { m_item = ObjectDB.instance.GetItemPrefab("Bilebag"), m_stackMin = 1, m_stackMax = 1, m_weight = 1f, m_dontScale = false } }; private static readonly List MEAT_PILE_RANDOM_ITEMS = new List { new DropData { m_item = ObjectDB.instance.GetItemPrefab("WolfHairBundle"), m_stackMin = 1, m_stackMax = 1, m_weight = 1f, m_dontScale = false }, new DropData { m_item = ObjectDB.instance.GetItemPrefab("WolfClaw"), m_stackMin = 1, m_stackMax = 1, m_weight = 1f, m_dontScale = false } }; private static readonly List TREASURE_PREFABS = new List { "Coins", "Amber", "SilverNecklace", "AmberPearl", "Ruby" }; private static bool IsTreasure(string prefabName) { if (prefabName == null) { return false; } return TREASURE_PREFABS.Contains(prefabName); } public static void ListAllPrefabs() { //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_01f6: Unknown result type (might be due to invalid IL or missing references) //IL_01fb: Unknown result type (might be due to invalid IL or missing references) //IL_0247: Unknown result type (might be due to invalid IL or missing references) //IL_0263: Unknown result type (might be due to invalid IL or missing references) //IL_026f: Unknown result type (might be due to invalid IL or missing references) //IL_0288: Unknown result type (might be due to invalid IL or missing references) //IL_0294: Unknown result type (might be due to invalid IL or missing references) //IL_02b2: Unknown result type (might be due to invalid IL or missing references) //IL_02d5: Unknown result type (might be due to invalid IL or missing references) List prefabs = ZNetScene.instance.m_prefabs; foreach (GameObject item in prefabs) { PickableItem component = item.GetComponent(); if ((Object)(object)component != (Object)null) { for (int i = 0; i < component.m_randomItemPrefabs.Length; i++) { string name = ((Object)component.m_randomItemPrefabs[i].m_itemPrefab).name; if (IsTreasure(name)) { Logger.LogInfo((object)("PickableItem " + ((Object)item).name + ": Has treasure drop " + name)); } else if (((Object)component).name == "Pickable_MountainCaveRandom") { Logger.LogInfo((object)("PickableItem " + ((Object)item).name + ": Has other drop " + name)); } } } Pickable component2 = item.GetComponent(); if (!((Object)(object)component2 != (Object)null)) { continue; } if (IsTreasure(((Object)component2.m_itemPrefab).name)) { Logger.LogInfo((object)("Pickable " + ((Object)item).name + ": Has treasure drop " + ((Object)component2.m_itemPrefab).name)); } if (((Object)component2).name == "Pickable_DvergrMineTreasure" || ((Object)component2).name == "Pickable_MeatPile") { Logger.LogInfo((object)("Pickable " + ((Object)item).name + ": " + $"({component2.m_extraDrops.m_dropMin} - {component2.m_extraDrops.m_dropMax}) " + $"extra drop chance {component2.m_extraDrops.m_dropChance}")); Logger.LogInfo((object)("Pickable " + ((Object)item).name + ": " + $"amount: {component2.m_amount}, m_minAmountScaled: {component2.m_minAmountScaled}")); } for (int j = 0; j < component2.m_extraDrops.m_drops.Count; j++) { DropData val = component2.m_extraDrops.m_drops[j]; if (((Object)component2).name == "Pickable_DvergrMineTreasure" || ((Object)component2).name == "Pickable_MeatPile") { Logger.LogInfo((object)("Pickable " + ((Object)item).name + ": Has drop " + ((Object)val.m_item).name + ". " + $"({val.m_stackMin} - {val.m_stackMax}) " + $"weight {val.m_weight}, dontscale: {val.m_dontScale}")); } else if (IsTreasure(((Object)val.m_item).name)) { Logger.LogInfo((object)("Pickable " + ((Object)item).name + ": Has extra treasure drop " + ((Object)val.m_item).name)); } } } Logger.LogInfo((object)$"Total Prefabs Loaded: {prefabs.Count}"); } } public class PlayerPinPatch { [HarmonyPatch(typeof(ZNet), "RPC_PlayerList")] public static class Client_PlayerListSync_Patch { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool Prefix(ZRpc rpc, ZPackage pkg) { //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_004c: Unknown result type (might be due to invalid IL or missing references) //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0092: Unknown result type (might be due to invalid IL or missing references) //IL_00af: Unknown result type (might be due to invalid IL or missing references) ZNet.instance.m_players.Clear(); int num = pkg.ReadInt(); for (int i = 0; i < num; i++) { PlayerInfo item = default(PlayerInfo); item.m_name = pkg.ReadString(); item.m_characterID = pkg.ReadZDOID(); item.m_userInfo.m_id = new PlatformUserID(pkg.ReadString()); item.m_userInfo.m_displayName = pkg.ReadString(); item.m_serverAssignedDisplayName = pkg.ReadString(); item.m_publicPosition = pkg.ReadBool(); if (pkg.ReadBool()) { item.m_position = pkg.ReadVector3(); } else { item.m_position = Vector3.zero; } ZNet.instance.m_players.Add(item); } return false; } } } public class PowerBeltPatch { public static void PowerBelts() { try { foreach (KeyValuePair item in PowerData.PowerBeltConfig) { AddBelt(item.Key, item.Value); } } catch (Exception) { ZLog.LogError((object)"error adding power belts"); } finally { PrefabManager.OnVanillaPrefabsAvailable -= PowerBelts; } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void AddBelt(string NewPrefab, PowerData.BeltRecipe belt) { //IL_0195: Unknown result type (might be due to invalid IL or missing references) //IL_019c: Expected O, but got Unknown //IL_01f6: Unknown result type (might be due to invalid IL or missing references) //IL_0200: Expected O, but got Unknown //IL_0220: Unknown result type (might be due to invalid IL or missing references) //IL_0225: Unknown result type (might be due to invalid IL or missing references) //IL_0231: Unknown result type (might be due to invalid IL or missing references) //IL_0238: Unknown result type (might be due to invalid IL or missing references) //IL_0244: Unknown result type (might be due to invalid IL or missing references) //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0261: Expected O, but got Unknown //IL_025c: Unknown result type (might be due to invalid IL or missing references) //IL_0262: Expected O, but got Unknown //IL_02e6: Unknown result type (might be due to invalid IL or missing references) //IL_0331: Unknown result type (might be due to invalid IL or missing references) try { if ((Object)(object)ObjectDB.instance.GetItemPrefab(NewPrefab) != (Object)null) { ZLog.Log((object)("[VRPBelts] Item '" + NewPrefab + "' already exists. Skipping creation.")); return; } StatusEffect val = null; if (!string.IsNullOrEmpty(belt.TargetSe)) { if (belt.TargetSe.Equals("Champion", StringComparison.OrdinalIgnoreCase) && (Object)(object)StatusEffectPatch.ChampionSE != (Object)null) { val = StatusEffectPatch.ChampionSE; ZLog.Log((object)("[VRPBelts] Using cached ChampionSE for " + NewPrefab)); } else { val = ObjectDB.instance.GetStatusEffect(StringExtensionMethods.GetStableHashCode(belt.TargetSe)); if ((Object)(object)val != (Object)null) { ZLog.Log((object)("[VRPBelts] Priority TargetSe found: Using '" + belt.TargetSe + "' for " + NewPrefab)); } else { ZLog.LogWarning((object)("[VRPBelts] TargetSe '" + belt.TargetSe + "' defined but NOT found in ObjectDB. Falling back.")); } } } if ((Object)(object)val == (Object)null) { string sourceSe = belt.SourceSe; StatusEffect statusEffect = ObjectDB.instance.GetStatusEffect(StringExtensionMethods.GetStableHashCode(sourceSe)); if ((Object)(object)statusEffect == (Object)null) { ZLog.LogError((object)("Could not find source effect " + sourceSe + " for belt " + NewPrefab)); return; } string text = sourceSe + "_Perm"; StatusEffect statusEffect2 = ObjectDB.instance.GetStatusEffect(StringExtensionMethods.GetStableHashCode(text)); if ((Object)(object)statusEffect2 != (Object)null) { val = statusEffect2; ZLog.Log((object)("[VRPBelts] Using existing cloned StatusEffect '" + text + "'")); } else { StatusEffect obj = Object.Instantiate(statusEffect); ((Object)obj).name = text; obj.m_ttl = 0f; obj.m_cooldown = 0f; obj.m_startMessage = belt.StartMessage; obj.m_flashIcon = false; CustomStatusEffect val2 = new CustomStatusEffect(obj, false); ItemManager.Instance.AddStatusEffect(val2); val = val2.StatusEffect; ZLog.Log((object)("[VRPBelts] Created new cloned StatusEffect '" + text + "'")); } } List list = new List(); foreach (KeyValuePair requirement in belt.Requirements) { list.Add(new RequirementConfig(requirement.Key, requirement.Value, 0, true)); } CustomItem val3 = new CustomItem(NewPrefab, belt.BasePrefabName, new ItemConfig { Description = belt.Description, Amount = 1, CraftingStation = belt.CraftingStation, MinStationLevel = belt.MinStationLevel, Requirements = list.ToArray() }); val3.ItemDrop.m_itemData.m_shared.m_name = belt.Name; val3.ItemDrop.m_itemData.m_shared.m_equipStatusEffect = val; if (NewPrefab == "BeltSweat") { MeshRenderer[] componentsInChildren = val3.ItemPrefab.GetComponentsInChildren(); for (int i = 0; i < componentsInChildren.Length; i++) { Material[] materials = ((Renderer)componentsInChildren[i]).materials; foreach (Material val4 in materials) { val4.SetColor("_Color", new Color(1f, 0.84f, 0f)); if (val4.HasProperty("_MetalGloss")) { val4.SetFloat("_MetalGloss", 1f); } val4.EnableKeyword("_EMISSION"); val4.SetColor("_EmissionColor", new Color(0.2f, 0.15f, 0f)); } } } ItemManager.Instance.AddItem(val3); } catch (Exception arg) { ZLog.LogError((object)$"[VRPBelts] Error adding '{NewPrefab}': {arg}"); } } } public static class ProgressionPatch { [Nullable(0)] [HarmonyPatch] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static class PreventInteractions { private static IEnumerable TargetMethods() { return (from p in typeof(Player).Assembly.GetTypes() where typeof(Interactable).IsAssignableFrom(p) where p.Name != "Interactable" where p.Name != "Ladder" where p.Name != "ShipControlls" where p.Name != "Sadle" where p.Name != "Chair" where p.Name != "TombStone" select p).SelectMany([<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] (Type t) => new List { AccessTools.Method(t, "Interact", (Type[])null, (Type[])null), AccessTools.Method(t, "UseItem", (Type[])null, (Type[])null) }); } private static bool Prefix(Humanoid __0) { if (!VRPMod.preventInteraction.Value) { return true; } if ((Object)(object)__0 != (Object)null && IsGated(__0)) { ((Character)__0).Message((MessageType)2, "$msg_nobuildzone", 0, (Sprite)null); return false; } return true; } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [HarmonyPatch(typeof(Player), "SetPlaceMode")] [Nullable(0)] public static class Player_SetPlaceMode_PreventBuilding { private static void Prefix(Player __instance, ref PieceTable buildPieces, ref PieceTable __state) { if (VRPMod.preventBuilding.Value && IsGated((Humanoid)(object)__instance)) { __state = buildPieces; buildPieces = null; } } private static void Postfix(ref PieceTable buildPieces, ref PieceTable __state) { if (!((Object)(object)__state == (Object)null)) { buildPieces = __state; } } } [HarmonyPatch(typeof(Player), "InPlaceMode")] public static class Player_InPlaceMode_PreventBuilding { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool Prefix(Player __instance, ref bool __result) { if (!VRPMod.preventBuilding.Value) { return true; } if (!IsGated((Humanoid)(object)__instance)) { return true; } __result = false; return false; } } [HarmonyPatch(typeof(Minimap), "UpdateExplore")] public static class Minimap_UpdateExplore_PreventExplore { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Prefix(Minimap __instance, Player player) { if (VRPMod.preventExploring.Value && IsGated((Humanoid)(object)player)) { __instance.m_exploreTimer = 0f; } } } [HarmonyPatch(typeof(Terminal), "InitTerminal")] public static class Terminal_Init_PurgeBiomeGate { [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static ConsoleEvent <>9__0_0; internal void b__0_0(ConsoleEventArgs args) { SE_BiomeGate.RemoveBiomeGateFromObjectDB("BiomeGate"); Console instance = Console.instance; if (instance != null) { ((Terminal)instance).AddString("Purged BiomeGate status effect (disabled adds, removed template, cleared players)."); } } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(Terminal __instance) { //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Expected O, but got Unknown //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_002b: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Expected O, but got Unknown object obj = <>c.<>9__0_0; if (obj == null) { ConsoleEvent val = delegate { SE_BiomeGate.RemoveBiomeGateFromObjectDB("BiomeGate"); Console instance2 = Console.instance; if (instance2 != null) { ((Terminal)instance2).AddString("Purged BiomeGate status effect (disabled adds, removed template, cleared players)."); } }; <>c.<>9__0_0 = val; obj = (object)val; } new ConsoleCommand("purge_biomegate", "Disable and remove BiomeGate status effect", (ConsoleEvent)obj, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); new ConsoleCommand("getid", "getid — exact match only (case-sensitive)", (ConsoleEvent)delegate(ConsoleEventArgs args) { Terminal val2 = args.Context ?? __instance; if (args.Args.Length < 2) { val2.AddString("usage: getid "); val2.AddString(" - exact, case-sensitive match"); val2.AddString(" - try prefab name (e.g. AmberPearl)"); } else if (!Object.op_Implicit((Object)(object)ObjectDB.instance) || ObjectDB.instance.m_items == null) { val2.AddString("ObjectDB not ready"); } else { string text = string.Join(" ", args.Args, 1, args.Args.Length - 1); foreach (GameObject item in ObjectDB.instance.m_items) { if (Object.op_Implicit((Object)(object)item)) { ItemDrop component = item.GetComponent(); if (Object.op_Implicit((Object)(object)component) && component.m_itemData?.m_shared != null) { string name = component.m_itemData.m_shared.m_name; string name2 = ((Object)item).name; Localization instance = Localization.instance; string text2 = ((instance != null) ? instance.Localize(name) : null) ?? name; if (name2 == text || name == text || text2 == text) { val2.AddString(name); return; } } } } val2.AddString("no exact match for '" + text + "'"); val2.AddString("tip: prefab names are case-sensitive (e.g., AmberPearl)"); } }, false, false, false, false, false, (ConsoleOptionsFetcher)null, false, false, false); } } private static Biome _lastBiome; private static bool _lastIsAdmin; private static bool _lastHadEffect; private static bool _lastPlayable; private static bool _lastInGated; public static void ApplySE() { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b5: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_021f: Unknown result type (might be due to invalid IL or missing references) //IL_0220: Unknown result type (might be due to invalid IL or missing references) //IL_01e8: Unknown result type (might be due to invalid IL or missing references) //IL_012e: Unknown result type (might be due to invalid IL or missing references) //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_013a: Unknown result type (might be due to invalid IL or missing references) //IL_014b: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) //IL_0100: Unknown result type (might be due to invalid IL or missing references) Player localPlayer = Player.m_localPlayer; if ((Object)(object)localPlayer == (Object)null) { return; } bool flag = ClientPatches.isAdmin(); Biome currentBiome = localPlayer.m_currentBiome; bool flag2 = (int)currentBiome != 0 && ((Enum)VRPMod.gatedBiomes.Value).HasFlag((Enum)(object)currentBiome); bool flag3 = !((Character)localPlayer).InCutscene() && !((Character)localPlayer).IsTeleporting(); SEMan sEMan = ((Character)localPlayer).GetSEMan(); bool flag4 = sEMan.HaveStatusEffect(SE_BiomeGate.statusEffectBiomeGateHash); if (flag) { if (flag4) { if (VRPMod.DebugMode()) { ZLog.Log((object)"Admin detected; removing biome-gate effect"); } sEMan.RemoveStatusEffect(SE_BiomeGate.statusEffectBiomeGateHash, false); flag4 = false; } _lastBiome = currentBiome; _lastIsAdmin = flag; _lastHadEffect = flag4; _lastPlayable = flag3; _lastInGated = flag2; } else { if (currentBiome == _lastBiome && flag4 == _lastHadEffect && flag == _lastIsAdmin && flag3 == _lastPlayable && flag2 == _lastInGated) { return; } if (!flag && flag3 && flag2) { if (!flag4) { if (VRPMod.DebugMode()) { ZLog.Log((object)$"Applying biome-gate effect (biome: {currentBiome})"); } sEMan.AddStatusEffect(SE_BiomeGate.statusEffectBiomeGateHash, false, 0, 0f); Vector3 position = ((Component)Player.m_localPlayer).transform.position; string raw = $"goto {Mathf.RoundToInt(position.x)} {Mathf.RoundToInt(position.z)} {Mathf.RoundToInt(position.y)}"; ClientPatches.SendModerationLog(ClientPatches.GetDisplayName(localPlayer.GetPlayerName()), "", ((object)(Biome)(ref currentBiome)).ToString(), "progression", localPlayer.GetPlayerName(), raw); flag4 = true; } } else if (flag4) { if (VRPMod.DebugMode()) { ZLog.Log((object)"Removing biome-gate effect (left gated biome or not playable)"); } sEMan.RemoveStatusEffect(SE_BiomeGate.statusEffectBiomeGateHash, false); flag4 = false; } if (VRPMod.DebugMode()) { ZLog.Log((object)$"[BiomeGate] biome={currentBiome} admin={flag} gated={flag2} playable={flag3} haveEffect={flag4}"); } _lastBiome = currentBiome; _lastIsAdmin = flag; _lastHadEffect = flag4; _lastPlayable = flag3; _lastInGated = flag2; } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool IsGated(Humanoid human) { Player val = (Player)(object)((human is Player) ? human : null); if (val != null && ((Character)val).GetSEMan().HaveStatusEffect(SE_BiomeGate.statusEffectBiomeGateHash)) { return (Object)(object)Ship.GetLocalShip() == (Object)null; } return false; } } public class Season14 { [HarmonyPatch(typeof(EnvMan), "FixedUpdate")] public static class LockTimePatch { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(EnvMan __instance) { if (VRPMod._lockTimeEnabled.Value) { __instance.m_smoothDayFraction = VRPMod._lockedTimeValue.Value; } } } [HarmonyPatch(typeof(EnvMan), "IsFreezing")] public static class ForceFreezingPatch { public static bool Prefix(ref bool __result) { if (VRPMod._eternalWinterEnabled.Value) { __result = true; return false; } return true; } } } public static class Beehive_Patch { [HarmonyPatch(typeof(Beehive), "CheckBiome")] public static class CheckBiome_Patch { public static bool Prefix(ref bool __result) { __result = true; return false; } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [HarmonyPatch(typeof(Beehive), "UpdateBees")] [Nullable(0)] public static class UpdateBees_Patch { public static void Prefix(Beehive __instance) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) if (IsNearFire(((Component)__instance).transform.position)) { __instance.m_maxHoney = 8; __instance.m_maxCover = 0f; __instance.m_effectOnlyInDaylight = false; } } public static void Postfix(Beehive __instance) { __instance.m_effectOnlyInDaylight = true; } } [HarmonyPatch(typeof(Plant), "UpdateHealth")] public static class Plant_FireWarmth_Patch { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static void Postfix(Plant __instance) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Invalid comparison between Unknown and I4 //IL_002f: Unknown result type (might be due to invalid IL or missing references) //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Invalid comparison between Unknown and I4 if (((int)__instance.m_status == 3 || (int)__instance.m_status == 7 || (int)__instance.m_status == 1) && IsNearFire(((Component)__instance).transform.position)) { __instance.m_status = (Status)0; } } } [HarmonyPatch(typeof(Beehive), "Interact")] public static class Interact_Patch { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static bool Prefix(Beehive __instance, Humanoid character, ref bool __result) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) if (__instance.GetHoneyLevel() <= 0 && !EnvMan.IsDaylight() && IsNearFire(((Component)__instance).transform.position)) { if (!__instance.HaveFreeSpace()) { ((Character)character).Message((MessageType)2, __instance.m_freespaceText, 0, (Sprite)null); } else { ((Character)character).Message((MessageType)2, "The bees are warmed by the fire", 0, (Sprite)null); } __result = true; return false; } return true; } } public static bool IsNearFire(Vector3 position) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) return Object.op_Implicit((Object)(object)EffectArea.IsPointInsideArea(position, (Type)1, 5f)); } } [Nullable(0)] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] internal class ServerPatches { [Nullable(0)] [HarmonyPatch(typeof(ZNet), "Awake")] public static class Znetawakfix { [CompilerGenerated] private sealed class d__1 : IEnumerator, IDisposable, IEnumerator { private int <>1__state; [Nullable(0)] private object <>2__current; object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] [return: Nullable(0)] get { return <>2__current; } } [DebuggerHidden] public d__1(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { //IL_0106: Unknown result type (might be due to invalid IL or missing references) //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Expected O, but got Unknown //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Expected O, but got Unknown switch (<>1__state) { default: return false; case 0: <>1__state = -1; <>2__current = (object)new WaitUntil((Func)(() => (Object)(object)ZNet.instance != (Object)null)); <>1__state = 1; return true; case 1: <>1__state = -1; <>2__current = Api.ServerGetWhitelist(); <>1__state = 2; return true; case 2: <>1__state = -1; <>2__current = Api.ServerGetGroups(); <>1__state = 3; return true; case 3: <>1__state = -1; <>2__current = Api.ServerGetRecipes(); <>1__state = 4; return true; case 4: <>1__state = -1; <>2__current = Api.ServerGetPieces(); <>1__state = 5; return true; case 5: <>1__state = -1; <>2__current = Api.ServerGetSkillcaps(); <>1__state = 6; return true; case 6: { <>1__state = -1; string text = Utils.GetSaveDataPath((FileSource)1) + "/wardlist.txt"; wardlist = new SyncedList(new FileLocation((FileSource)1, text), "A list of characters with a ward"); ZLog.Log((object)"Server initialization complete."); return false; } } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } private static void Postfix(ZNet __instance) { if (__instance.IsServer() && Env.IsDedicated) { ZLog.LogWarning((object)"VRP SERVER 2.1.2"); ServerModerationLog("server", "", "", "server started", "", DateTime.Now.ToString() + " server started", 1); ((MonoBehaviour)__instance).StartCoroutine(ServerInitialization()); } } [IteratorStateMachine(typeof(d__1))] private static IEnumerator ServerInitialization() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__1(0); } } [HarmonyPatch(typeof(ZNet), "Update")] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] public static class Znetupdatepost { private static void Postfix() { if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer()) { apiupdatetimer += Time.deltaTime; if (apiupdatetimer > 66f && !ZNet.instance.IsSaving() && !iskicking) { apiupdatetimer = 0f; ZLog.Log((object)"vrp api update"); Game.instance.ServerLog(); ((MonoBehaviour)ZNet.instance).StartCoroutine(Api.ServerGetWhitelist()); ((MonoBehaviour)ZNet.instance).StartCoroutine(Api.ServerGetGroups()); ((MonoBehaviour)ZNet.instance).StartCoroutine(Api.ServerGetRecipes()); ((MonoBehaviour)ZNet.instance).StartCoroutine(Api.ServerGetPieces()); ((MonoBehaviour)ZNet.instance).StartCoroutine(Api.ServerGetSkillcaps()); } if ((DateTime.Now.Hour == 5 || DateTime.Now.Hour == 17) && DateTime.Now.Minute == 0 && !iswarning) { iswarning = true; RPC_Broadcast(0L, "SCHEDULED SERVER REBOOT IN 10 MINUTES!"); ServerModerationLog("server", "", "10 minute warning", "reboot", "", "reboot warning", 1); ZLog.Log((object)"vrp reboot warning"); } if ((DateTime.Now.Hour == 5 || DateTime.Now.Hour == 17) && DateTime.Now.Minute == 5 && !iswarning2) { iswarning2 = true; RPC_Broadcast(0L, "SCHEDULED SERVER REBOOT! LOG OFF NOW!"); ServerModerationLog("server", "", "2nd warning", "reboot", "", "reboot warning 2", 1); ZLog.Log((object)"vrp reboot warning 2"); } if ((DateTime.Now.Hour == 5 || DateTime.Now.Hour == 17) && DateTime.Now.Minute == 9 && !iskicking) { iskicking = true; RPC_Broadcast(0L, "SCHEDULED SERVER REBOOT! ALL PLAYERS WILL BE KICKED NOW! YOU HAD 2 WARNINGS!"); ServerModerationLog("server", "", "final kick warning", "reboot", "", "reboot warning 3", 1); ZLog.Log((object)"vrp reboot warning 3"); } if ((DateTime.Now.Hour == 5 || DateTime.Now.Hour == 17) && DateTime.Now.Minute == 10 && iswarning && !isrebooting) { ZLog.Log((object)"vrp rebooting now"); isrebooting = true; ServerModerationLog("server", "", "rebooting now", "reboot", "", "rebooting now", 1); RPC_Broadcast(0L, "SCHEDULED SERVER REBOOT NOW!"); Game.instance.Shutdown(true); } } } } [HarmonyPatch(typeof(ZNetScene), "Awake")] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] public class HorseSFXMuter { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ZNetScene __instance) { GameObject prefab = __instance.GetPrefab("sfx_horse_idle"); if (!((Object)(object)prefab == (Object)null)) { ZSFX component = prefab.GetComponent(); if ((Object)(object)component != (Object)null) { component.m_vol = 0f; component.m_audioSource = null; Debug.Log((object)"[HorseSFXMuter] ZSFX disabled on sfx_horse_idle."); } AudioSource component2 = prefab.GetComponent(); if ((Object)(object)component2 != (Object)null) { component2.clip = null; ((Behaviour)component2).enabled = false; Debug.Log((object)"[HorseSFXMuter] AudioSource disabled on sfx_horse_idle."); } } } } [HarmonyPatch(typeof(ZDOMan))] [HarmonyPatch(new Type[] { typeof(int) })] [HarmonyPatch(/*Could not decode attribute arguments.*/)] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] public static class AddCustomeRPCHere { private static void Postfix() { ZRoutedRpc.instance.m_functions.Remove(StringExtensionMethods.GetStableHashCode("ServerModerationLog")); ZRoutedRpc.instance.Register("ServerModerationLog", (Action)RoutedRpcManager.RPC_ServerModerationLog); ZLog.Log((object)"[VRP] Cleaned and Registered ServerModerationLog RPC."); ZRoutedRpc.instance.Register("ServerGetClass", (Action)RPC_GetClass); ZRoutedRpc.instance.Register("ServerResetKeys", (Action)RPC_ResetKeys); ZRoutedRpc.instance.Register("ServerBroadcast", (Action)RPC_Broadcast); ZRoutedRpc.instance.Register("ServerGetWard", (Action)RPC_GetWard); ZRoutedRpc.instance.Register("ServerSetWard", (Action)RPC_SetWard); } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] [HarmonyPatch(typeof(ZDOMan), "AddPeer")] public static class PeerAdded { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ZNetPeer netPeer, ZDOMan __instance) { if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer()) { string hostName = netPeer.m_socket.GetHostName(); string playerName = netPeer.m_playerName; ServerModerationLog(playerName, hostName, "", "connected", playerName, hostName + "|" + playerName + " Connected"); } } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] [HarmonyPatch(typeof(ZDOMan), "RemovePeer")] public static class PeerRemoved { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ZNetPeer netPeer, ZDOMan __instance) { //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0032: Unknown result type (might be due to invalid IL or missing references) //IL_0044: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)ZNet.instance == (Object)null || !ZNet.instance.IsServer()) { return; } string hostName = netPeer.m_socket.GetHostName(); string text = ""; if (netPeer.m_characterID != ZDOID.None) { ZDO zDO = ZDOMan.instance.GetZDO(netPeer.m_characterID); if (zDO != null) { text = zDO.GetString(ZDOVars.s_playerName, ""); } } ServerModerationLog(text, hostName, "", "disconnected", text, hostName + "|" + text + " Disconnected"); } } [HarmonyPatch(typeof(FejdStartup), "IsPublicPasswordValid")] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] public static class Passwordfix { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(string password, World world, ref bool __result) { __result = true; } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] [HarmonyPatch(typeof(FejdStartup), "NeedPassword")] public static class Passwordfix2 { private static void Postfix(ref bool __result) { __result = false; } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] [HarmonyPatch(typeof(ZNet), "IsAllowed")] public static class CharWhitelist { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool Prefix(ref bool __result, string hostName, string playerName, ZNet __instance) { string text = hostName + "|" + playerName; bool flag = __instance.m_bannedList.Contains(hostName); bool flag2 = false; string subaction = ""; foreach (DbWhitelist item in whitelist) { if (!(item.charactername.ToUpperInvariant() == playerName.ToUpperInvariant())) { continue; } if (item.isnew && item.admincharacter == 0) { if (!item.isAuthenticating) { item.isAuthenticating = true; ((MonoBehaviour)ZNet.instance).StartCoroutine(Api.WhitelistAuth(hostName, playerName, item.pid, item.cid, item)); } flag2 = true; item.isnew = false; } else if (item.steamid == hostName) { flag2 = true; } if (item.permadeath) { flag2 = false; subaction = "Character is marked dead"; } } if (flag) { subaction = "Player marked banned"; } if (!flag2) { subaction = "Character not found on whitelist. Check spelling"; } if (flag || !flag2) { __result = false; ServerModerationLog(playerName, hostName, "", "whitelist fail", playerName, "IsAllowed failed: " + text, 0, subaction); } else { __result = true; } return false; } } [HarmonyPatch(typeof(ZNet), "CheckWhiteList")] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] public static class CheckCharWhitelist { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool Prefix(ZNet __instance) { if (__instance.m_peers != null) { if (__instance.m_peers.Count > 0) { foreach (ZNetPeer item in __instance.m_peers.ToList()) { if (!item.IsReady() || ((ZDOID)(ref item.m_characterID)).IsNone()) { continue; } string text = item.m_playerName.ToUpperInvariant(); string hostName = item.m_socket.GetHostName(); string text2 = hostName + "|" + text; if (iskicking) { __instance.InternalKick(item); } else { if (whitelist.Count <= 0) { continue; } bool flag = false; foreach (DbWhitelist item2 in whitelist) { if (!(item2.charactername.ToUpperInvariant() == text)) { continue; } if (item2.isnew) { if (!item2.isAuthenticating) { item2.isAuthenticating = true; ((MonoBehaviour)ZNet.instance).StartCoroutine(Api.WhitelistAuth(hostName, text, item2.pid, item2.cid, item2)); } flag = true; item2.isnew = false; } else if (item2.steamid == hostName) { flag = true; } else if (item2.admincharacter == 1) { flag = true; } if (item2.permadeath) { flag = false; } } if (!flag) { ZLog.Log((object)("Kicking player not in permitted list " + text2)); ServerModerationLog(text, hostName, "", "whitelist kick", "", "Kicking player not in whitelist " + text2); __instance.InternalKick(item); } } } } foreach (string item3 in timers.Keys.ToList()) { timers[item3] -= 1; if (timers[item3] < 0) { __instance.Kick(item3); timers.Remove(item3); } } } return false; } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] private static class fixver2 { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] [HarmonyPriority(0)] private static bool Prefix(ZRpc rpc, ref ZPackage pkg) { pkg.ReadLong(); string text = pkg.ReadString(); pkg.SetPos(0); if (ZNet.instance.IsServer() && !text.Contains("-vrp2.1.2")) { rpc.Invoke("Error", new object[1] { 3 }); ZLog.Log((object)("Client " + rpc.m_socket.GetHostName() + " vrp version error: " + text)); string hostName = rpc.m_socket.GetHostName(); ServerModerationLog(hostName, "", "", "version", "", "Client " + hostName + " vrp version error: " + text, 0, "vrp version error: " + text); return false; } return true; } } public static Dictionary timers = new Dictionary(); public static List groups = new List(); public static List skills = new List(); public static string recipesraw = ""; public static string piecesraw = ""; public static string skillsraw = ""; public static List whitelist = new List(); public static SyncedList wardlist; public static float apiupdatetimer = 13f; public static bool iswarning = false; public static bool iswarning2 = false; public static bool iskicking = false; public static bool isrebooting = false; public static void ServerModerationLog(string player, string steamId, string item, string action, string creator, string raw, int isAdmin = 0, string subaction = "") { DbLog logEntry = new DbLog { p = player, s = steamId, i = item, a = action, c = creator, r = raw, m = isAdmin, b = subaction }; if ((Object)(object)ZNet.instance != (Object)null) { ((MonoBehaviour)ZNet.instance).StartCoroutine(Api.LogInsert(logEntry)); } } public static void RPC_GetClass(long sender, string playername) { string text = ""; if (!((Object)(object)ZNet.instance != (Object)null) || !ZNet.instance.IsServer() || string.IsNullOrWhiteSpace(playername)) { return; } ZNetPeer peerByPlayerName = ZNet.instance.GetPeerByPlayerName(playername); if (peerByPlayerName == null || !peerByPlayerName.IsReady()) { return; } foreach (DbGroup group in groups) { if (group.charactername.ToUpperInvariant() == playername.ToUpperInvariant()) { if (!string.IsNullOrWhiteSpace(text)) { text += ","; } text += group.craftgroup; } } string text2 = string.Join(",", from s in skills where s.charactername.Equals(playername, StringComparison.OrdinalIgnoreCase) select $"{s.skill}:{s.cap}"); ZRoutedRpc.instance.InvokeRoutedRPC(peerByPlayerName.m_uid, "ClientSetClass", new object[4] { text, recipesraw, piecesraw, text2 }); } public static void RPC_GetWard(long sender, string playername) { if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer() && !string.IsNullOrWhiteSpace(playername)) { ZNetPeer peerByPlayerName = ZNet.instance.GetPeerByPlayerName(playername); if (peerByPlayerName != null && peerByPlayerName.IsReady()) { bool flag = !wardlist.Contains(playername); ZRoutedRpc.instance.InvokeRoutedRPC(peerByPlayerName.m_uid, "ClientSetWard", new object[1] { flag }); } } } public static void RPC_SetWard(long sender, string playername, bool add) { if (!((Object)(object)ZNet.instance != (Object)null) || !ZNet.instance.IsServer() || string.IsNullOrWhiteSpace(playername)) { return; } ZNetPeer peerByPlayerName = ZNet.instance.GetPeerByPlayerName(playername); if (peerByPlayerName != null && peerByPlayerName.IsReady()) { if (add) { wardlist.Add(playername); } else { wardlist.Remove(playername); } RPC_GetWard(sender, playername); } } public static void RPC_ModerationLog(long sender, string logjson) { ZLog.Log((object)("[VRP SERVER] RPC_ModerationLog received: " + logjson)); ((MonoBehaviour)VRPMod.Instance).StartCoroutine(Api.LogInsert(logjson)); } public static void RPC_Broadcast(long sender, string msg) { if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer()) { MessageHud.instance.MessageAll((MessageType)2, msg); } } public static void RPC_ResetKeys(long sender) { if ((Object)(object)ZNet.instance != (Object)null && ZNet.instance.IsServer() && Object.op_Implicit((Object)(object)ZoneSystem.instance)) { ZNetPeer peer = ZNet.instance.GetPeer(sender); string steamId = ""; string creator = ""; if (peer != null) { steamId = peer.m_uid.ToString(); creator = peer.m_playerName; } ZLog.LogWarning((object)"Reset global keys"); ServerModerationLog("server", steamId, "", "Reset global keys", creator, "Reset global keys", 1); ZoneSystem.instance.ResetGlobalKeys(); } } } [Nullable(0)] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public class SE_BiomeGate : SE_Stats { [HarmonyPatch(typeof(ObjectDB), "Awake")] [Nullable(0)] public static class ObjectDB_Awake_AddStatusEffects { public static void AddCustomStatusEffects(ObjectDB odb) { //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00be: Unknown result type (might be due to invalid IL or missing references) if (odb.m_StatusEffects.Count > 0 && !odb.m_StatusEffects.Any([<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] (StatusEffect se) => ((Object)se).name == "ProgressGate")) { SE_BiomeGate sE_BiomeGate = ScriptableObject.CreateInstance(); ((Object)sE_BiomeGate).name = "ProgressGate"; ((StatusEffect)sE_BiomeGate).m_nameHash = statusEffectBiomeGateHash; ((StatusEffect)sE_BiomeGate).m_icon = odb.m_StatusEffects.Find([<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] (StatusEffect se) => (Object)(object)se.m_icon != (Object)null && ((Object)se.m_icon).name.IndexOf("immobilized") != -1)?.m_icon; ((StatusEffect)sE_BiomeGate).m_flashIcon = true; ((SE_Stats)sE_BiomeGate).m_modifyAttackSkill = (SkillType)999; ((SE_Stats)sE_BiomeGate).m_raiseSkill = (SkillType)999; ((StatusEffect)sE_BiomeGate).m_startMessageType = (MessageType)2; ((StatusEffect)sE_BiomeGate).m_repeatMessageType = (MessageType)2; ((StatusEffect)sE_BiomeGate).m_repeatInterval = 20f; ((StatusEffect)sE_BiomeGate).m_name = "$menu_server_warning"; ((StatusEffect)sE_BiomeGate).m_tooltip = "$tutorial_blackforest_topic"; UpdateStatusEffectProperties(sE_BiomeGate); odb.m_StatusEffects.Add((StatusEffect)(object)sE_BiomeGate); } } private static void Postfix(ObjectDB __instance) { AddCustomStatusEffects(__instance); } } [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] [HarmonyPatch(typeof(ObjectDB), "CopyOtherDB")] public static class ObjectDB_CopyOtherDB_AddStatusEffects { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ObjectDB __instance) { ObjectDB_Awake_AddStatusEffects.AddCustomStatusEffects(__instance); } } public const string statusEffectBiomeGateName = "ProgressGate"; public static readonly int statusEffectBiomeGateHash = StringExtensionMethods.GetStableHashCode("ProgressGate"); public const string statusEffectName = "$menu_server_warning"; public const string statusEffectTooltip = "$tutorial_blackforest_topic"; public override string GetIconText() { return Localization.instance.Localize("$tutorial_blackforest_topic"); } public static void RemoveBiomeGateFromObjectDB(string statuseffect) { ObjectDB instance = ObjectDB.instance; if (!Object.op_Implicit((Object)(object)instance)) { return; } int num = instance.m_StatusEffects.FindIndex([<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] (StatusEffect se) => (Object)(object)se != (Object)null && (se.m_nameHash == StringExtensionMethods.GetStableHashCode(statuseffect) || ((Object)se).name == statuseffect)); if (num >= 0) { StatusEffect val = instance.m_StatusEffects[num]; instance.m_StatusEffects.RemoveAt(num); if (Object.op_Implicit((Object)(object)val)) { Object.Destroy((Object)(object)val); } if (VRPMod.DebugMode()) { ZLog.Log((object)"[BiomeGate] Removed template from ObjectDB"); } } } public static void UpdateBiomeGateProperties() { if (Object.op_Implicit((Object)(object)ObjectDB.instance)) { UpdateStatusEffectProperties(ObjectDB.instance.GetStatusEffect(statusEffectBiomeGateHash) as SE_BiomeGate); } if ((Object)(object)Player.m_localPlayer != (Object)null && ((Character)Player.m_localPlayer).GetSEMan().HaveStatusEffect(statusEffectBiomeGateHash)) { UpdateStatusEffectProperties(((Character)Player.m_localPlayer).GetSEMan().GetStatusEffect(statusEffectBiomeGateHash) as SE_BiomeGate); } } private static void UpdateStatusEffectProperties(SE_BiomeGate statusEffect) { //IL_00b4: Unknown result type (might be due to invalid IL or missing references) //IL_00b9: Unknown result type (might be due to invalid IL or missing references) //IL_00ba: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Invalid comparison between Unknown and I4 //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: Invalid comparison between Unknown and I4 //IL_00c7: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Invalid comparison between Unknown and I4 //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00e0: Unknown result type (might be due to invalid IL or missing references) //IL_00e7: Unknown result type (might be due to invalid IL or missing references) //IL_00e8: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)statusEffect == (Object)null) { return; } ((StatusEffect)statusEffect).m_icon = ObjectDB.instance.m_StatusEffects.Find([<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(0)] (StatusEffect se) => (Object)(object)se.m_icon != (Object)null && ((Object)se.m_icon).name.IndexOf("immobilized") != -1)?.m_icon; ((SE_Stats)statusEffect).m_noiseModifier = 10f; ((SE_Stats)statusEffect).m_stealthModifier = -1f; ((SE_Stats)statusEffect).m_damageModifier = 0f; ((SE_Stats)statusEffect).m_raiseSkillModifier = -100f; ((StatusEffect)statusEffect).m_repeatMessage = "$npc_dvergrrogue_random_private_area_alarm8"; ((StatusEffect)statusEffect).m_startMessage = ""; ((SE_Stats)statusEffect).m_mods.Clear(); foreach (DamageType value in Enum.GetValues(typeof(DamageType))) { if ((int)value != 1024 && (int)value != 31 && (int)value != 224) { ((SE_Stats)statusEffect).m_mods.Add(new DamageModPair { m_modifier = (DamageModifier)6, m_type = value }); } } } } public static class StatusEffectPatch { [HarmonyPatch(typeof(Player), "GetMaxCarryWeight")] private static class Champion_Weight_Patch { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(Player __instance, ref float __result) { if (((Character)__instance).GetSEMan().HaveStatusEffect(StringExtensionMethods.GetStableHashCode("Champion"))) { __result += 200f; } } } [Nullable(1)] public static StatusEffect ChampionSE; public static void AddCustomStatus() { //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Expected O, but got Unknown //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_011f: Unknown result type (might be due to invalid IL or missing references) //IL_012d: Unknown result type (might be due to invalid IL or missing references) //IL_0136: Unknown result type (might be due to invalid IL or missing references) //IL_013e: Unknown result type (might be due to invalid IL or missing references) //IL_0143: Unknown result type (might be due to invalid IL or missing references) //IL_0151: Unknown result type (might be due to invalid IL or missing references) //IL_015a: Unknown result type (might be due to invalid IL or missing references) //IL_0162: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Unknown result type (might be due to invalid IL or missing references) //IL_016e: Unknown result type (might be due to invalid IL or missing references) //IL_0174: Expected O, but got Unknown ZLog.Log((object)"VRP CUSTOM STATUS"); try { if (!Object.op_Implicit((Object)(object)ObjectDB.instance.GetStatusEffect(StringExtensionMethods.GetStableHashCode("Wounded")))) { StatusEffect statusEffect = ObjectDB.instance.GetStatusEffect(StringExtensionMethods.GetStableHashCode("SoftDeath")); if (Object.op_Implicit((Object)(object)statusEffect)) { SE_Stats obj = ScriptableObject.CreateInstance(); ((StatusEffect)obj).m_icon = statusEffect.m_icon; ((StatusEffect)obj).m_name = "Wounded"; ((Object)obj).name = "Wounded"; ((StatusEffect)obj).m_ttl = 1800f; ((StatusEffect)obj).m_repeatInterval = 0f; obj.m_speedModifier = -0.1f; CustomStatusEffect val = new CustomStatusEffect((StatusEffect)(object)obj, false); ItemManager.Instance.AddStatusEffect(val); SE_Stats obj2 = ScriptableObject.CreateInstance(); ((StatusEffect)obj2).m_icon = statusEffect.m_icon; ((StatusEffect)obj2).m_name = "Panic"; ((Object)obj2).name = "Panic"; ((StatusEffect)obj2).m_ttl = 30f; ((StatusEffect)obj2).m_repeatInterval = 0f; obj2.m_tickInterval = 1f; obj2.m_healthPerTick = 5f; obj2.m_addMaxCarryWeight = 300f; obj2.m_mods.Add(new DamageModPair { m_modifier = (DamageModifier)5, m_type = (DamageType)1 }); obj2.m_mods.Add(new DamageModPair { m_modifier = (DamageModifier)5, m_type = (DamageType)4 }); obj2.m_mods.Add(new DamageModPair { m_modifier = (DamageModifier)5, m_type = (DamageType)2 }); CustomStatusEffect val2 = new CustomStatusEffect((StatusEffect)(object)obj2, false); ItemManager.Instance.AddStatusEffect(val2); } } } catch (Exception ex) { ZLog.LogError((object)"error vrp custom statuses"); if (VRPMod.DebugMode()) { ZLog.LogError((object)ex.Message); } } finally { PrefabManager.OnPrefabsRegistered -= AddCustomStatus; } } public static void AddDanceStatus() { //IL_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00c1: Expected O, but got Unknown //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00cc: Expected O, but got Unknown //IL_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Expected O, but got Unknown ZLog.Log((object)"VRP DANCE STATUS"); try { if ((Object)(object)DanceBombPatch.DanceFeverSE != (Object)null) { ZLog.Log((object)"DanceFever already cached."); return; } StatusEffect statusEffect = ObjectDB.instance.GetStatusEffect(StringExtensionMethods.GetStableHashCode("DanceFever")); if (Object.op_Implicit((Object)(object)statusEffect)) { DanceBombPatch.DanceFeverSE = statusEffect; ZLog.Log((object)"DanceFever already exists in ObjectDB; cached it."); return; } StatusEffect statusEffect2 = ObjectDB.instance.GetStatusEffect(StringExtensionMethods.GetStableHashCode("AdrenalineRush4")); if (!Object.op_Implicit((Object)(object)statusEffect2)) { ZLog.LogError((object)"Didn't find AdrenalineRush4 to copy."); return; } StatusEffect obj = Object.Instantiate(statusEffect2); ((Object)obj).name = "DanceFever"; obj.m_tooltip = "You cannot resist the rhythm."; obj.m_ttl = 8f; obj.m_repeatInterval = 0f; obj.m_startEffects = new EffectList(); obj.m_stopEffects = new EffectList(); obj.m_name = "Dance Fever"; CustomStatusEffect val = new CustomStatusEffect(obj, false); ItemManager.Instance.AddStatusEffect(val); DanceBombPatch.DanceFeverSE = val.StatusEffect; ZLog.Log((object)"[VRP] DanceFever status created and cached."); } catch (Exception ex) { ZLog.LogError((object)"error vrp dance status"); if (VRPMod.DebugMode()) { ZLog.LogError((object)ex.ToString()); } } finally { PrefabManager.OnPrefabsRegistered -= AddDanceStatus; } } public static void AddChampionStatus() { //IL_00d4: Unknown result type (might be due to invalid IL or missing references) //IL_00da: Expected O, but got Unknown ZLog.Log((object)"VRP CHAMPION STATUS"); try { if ((Object)(object)ChampionSE != (Object)null) { ZLog.Log((object)"ChampionSE already cached."); return; } StatusEffect statusEffect = ObjectDB.instance.GetStatusEffect(StringExtensionMethods.GetStableHashCode("Champion")); if (Object.op_Implicit((Object)(object)statusEffect)) { ChampionSE = statusEffect; ZLog.Log((object)"Champion status already exists in ObjectDB; cached it."); return; } StatusEffect statusEffect2 = ObjectDB.instance.GetStatusEffect(StringExtensionMethods.GetStableHashCode("Encumbered")); if (!Object.op_Implicit((Object)(object)statusEffect2)) { ZLog.LogError((object)"Didn't find Encumbered to copy."); return; } StatusEffect obj = Object.Instantiate(statusEffect2); ((Object)obj).name = "Champion"; obj.m_name = "Champion"; obj.m_tooltip = "You are the Champion. The belt compels you to answer all challenges."; obj.m_repeatMessage = "Adrenaline fills your veins. You itch for a new fight."; obj.m_ttl = 0f; obj.m_cooldown = 0f; obj.m_flashIcon = false; CustomStatusEffect val = new CustomStatusEffect(obj, false); ItemManager.Instance.AddStatusEffect(val); ChampionSE = val.StatusEffect; ZLog.Log((object)"[VRP] Champion status created and cached."); ZLog.Log((object)"[VRP] Champion status created and cached."); } catch (Exception ex) { ZLog.LogError((object)"error vrp champion status"); if (VRPMod.DebugMode()) { ZLog.LogError((object)ex.ToString()); } } finally { PrefabManager.OnPrefabsRegistered -= AddChampionStatus; } } public static void AddHandcuffStatus() { ZLog.Log((object)"VRP HANDCUFFS"); try { CustomItem item = ItemManager.Instance.GetItem("Handcuffs"); if (item != null) { StatusEffect statusEffect = ObjectDB.instance.GetStatusEffect(StringExtensionMethods.GetStableHashCode("Harpooned")); if (!Object.op_Implicit((Object)(object)statusEffect)) { ZLog.LogError((object)"didn't find harpooned"); } else { item.ItemDrop.m_itemData.m_shared.m_attackStatusEffect = statusEffect; } } } catch (Exception ex) { ZLog.LogError((object)"error vrp handcuff status"); if (VRPMod.DebugMode()) { ZLog.LogError((object)ex.Message); } } finally { PrefabManager.OnPrefabsRegistered -= AddHandcuffStatus; } } } internal class TeleportPatches { [HarmonyPatch(typeof(TeleportWorld), "Interact")] public static class InteractPatch { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool Prefix(ref Humanoid human, ref bool hold, ref bool __result, TeleportWorld __instance) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) if (hold) { __result = false; return false; } if (!PrivateArea.CheckAccess(((Component)__instance).transform.position, 0f, true, false)) { ((Character)human).Message((MessageType)2, "$piece_noaccess", 0, (Sprite)null); __result = true; return false; } TextInput.instance.RequestText((TextReceiver)(object)__instance, "$piece_portal_tag", 50); __result = true; return false; } } [HarmonyPatch(typeof(TeleportWorld), "HaveTarget")] public static class HaveTargetPatch { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool Prefix(ref bool __result, TeleportWorld __instance) { if (__instance.GetText().Contains("server|")) { __result = true; return false; } return true; } } [HarmonyPatch(typeof(TeleportWorld), "TargetFound")] public static class TargetFoundPatch { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static bool Prefix(ref bool __result, TeleportWorld __instance) { if (__instance.GetText().Contains("server|")) { __result = true; return false; } return true; } } [HarmonyPatch(typeof(TeleportWorld), "Teleport")] public static class TeleportPatch { [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] private static void Postfix(ref Player player, TeleportWorld __instance) { //IL_009d: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00df: Unknown result type (might be due to invalid IL or missing references) if (!((Humanoid)player).IsTeleportable()) { ((Character)player).Message((MessageType)2, "$msg_noteleport", 0, (Sprite)null); return; } string text = __instance.GetText(); if (!text.Contains("server|")) { return; } string[] array = text.Split(new char[1] { '|' }); if (array.Length <= 1) { return; } string[] array2 = array[1].Split(new char[1] { ':' }); if (array2.Length != 0) { string obj = array2[0]; int result = 2456; if (array2.Length > 1) { int.TryParse(array2[1], out result); } servertojoin = obj + ":" + result; Vector3 position = ((Component)player).transform.position; position.x -= 2f; position.z -= 2f; ZoneSystem.instance.FindFloor(position, ref position.y); ((Component)player).transform.position = position; ZLog.LogWarning((object)("server portals - logging out and connecting to: " + servertojoin)); Game.instance.Logout(true, true); } } } [HarmonyPatch(typeof(FejdStartup), "Start")] public static class starterfirst { private static void Postfix() { if (servertojoin != "") { ZLog.LogWarning((object)"server portals - starting game"); ZSteamMatchmaking.instance.QueueServerJoin(servertojoin); } } } [HarmonyPatch(typeof(FejdStartup), "ShowCharacterSelection")] public static class starterselect { private static async void Postfix() { if (servertojoin != "") { ZLog.LogWarning((object)"server portals - starting character"); await Task.Delay(500); servertojoin = ""; FejdStartup.instance.OnCharacterStart(); } } } [Nullable(1)] public static string servertojoin = ""; } } namespace ValheimRoleplay.Data { public static class CommandData { [Nullable(1)] public static readonly HashSet OmitCommands = new HashSet { "laugh", "sortcraft", "relax", "rest", "toast", "kneel", "sit", "w", "bind", "cry", "die", "headbang", "comehere", "roar", "help", "bow", "wave", "blowkiss", "thumbsup", "cower", "shrug", "ges", "point", "dance", "cheer", "flex", "despair", "challenge", "unbind", "ur", "nonono", "whisper", "me", "roll", "shuffle", "draw", "tarot.shuffle", "tarot.draw", "farkle.help", "farkle.start", "farkle.bank", "farkle.roll", "farkle.keep", "farkle.score", "setalias", "hide", "save", "clearalias", "say", "ping", "info", "nomap", "s", "shout", "coinflip", "vibe", "loveyou" }; } [Nullable(0)] [<4713ac70-5c40-4c8e-abac-415a3e416205>NullableContext(1)] public static class PowerData { [Serializable] [Nullable(0)] public class BeltRecipe { public string SourceSe { get; set; } = ""; public string TargetSe { get; set; } = ""; public string StartMessage { get; set; } = ""; public string BasePrefabName { get; set; } = ""; public string NewPrefabName { get; set; } = ""; public string Name { get; set; } = ""; public string Description { get; set; } = ""; public string CraftingStation { get; set; } = ""; public int MinStationLevel { get; set; } = 1; public Dictionary Requirements { get; set; } = new Dictionary(); } public static Dictionary PowerBeltConfig = new Dictionary { ["BeltSweat"] = new BeltRecipe { TargetSe = "Champion", StartMessage = "Adrenaline fills your veins. You are the strongest. But you sure sweat a lot.", BasePrefabName = "BeltStrength", NewPrefabName = "BeltSweat", Name = "Championship Belt", Description = "Forged in blackened steel and trimmed in wolf-gold, this belt is not worn - it is earned. \n It has been stained with sweat, blood, and mead across the arenas of the North. Only one warrior stands above all others, and when the horn sounds and the dust settles, this belt is fastened around the waist of the undisputed champion of the ring. \nBut the runes upon it burn with hunger. It compels its bearer to answer every challenge and defend the title until their fists are blood and bone.", CraftingStation = "piece_workbench", MinStationLevel = 1, Requirements = new Dictionary { ["Coins"] = 50 } } }; } } namespace Microsoft.CodeAnalysis { [Embedded] [CompilerGenerated] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] [Embedded] [CompilerGenerated] internal sealed class <1a203302-fe92-49d6-be0f-bfef62526189>NullableAttribute : Attribute { public readonly byte[] NullableFlags; public <1a203302-fe92-49d6-be0f-bfef62526189>NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public <1a203302-fe92-49d6-be0f-bfef62526189>NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] [Embedded] [CompilerGenerated] internal sealed class <6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContextAttribute : Attribute { public readonly byte Flag; public <6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContextAttribute(byte P_0) { Flag = P_0; } } [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] [Embedded] [CompilerGenerated] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace ServerSync { [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(0)] [<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(1)] [PublicAPI] internal abstract class OwnConfigEntryBase { [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(2)] public object LocalBaseValue; public bool SynchronizedConfig = true; public abstract ConfigEntryBase BaseConfig { get; } } [PublicAPI] [<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(1)] [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(0)] internal class SyncedConfigEntry<[<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(2)] T> : OwnConfigEntryBase { public readonly ConfigEntry SourceConfig; public override ConfigEntryBase BaseConfig => (ConfigEntryBase)(object)SourceConfig; public T Value { get { return SourceConfig.Value; } set { SourceConfig.Value = value; } } public SyncedConfigEntry(ConfigEntry sourceConfig) { SourceConfig = sourceConfig; base..ctor(); } public void AssignLocalValue(T value) { if (LocalBaseValue == null) { Value = value; } else { LocalBaseValue = value; } } } [<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(2)] [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(0)] internal abstract class CustomSyncedValueBase { public object LocalBaseValue; [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(1)] public readonly string Identifier; [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(1)] public readonly Type Type; private object boxedValue; protected bool localIsOwner; public readonly int Priority; public object BoxedValue { get { return boxedValue; } set { boxedValue = value; this.ValueChanged?.Invoke(); } } public event Action ValueChanged; [<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(1)] protected CustomSyncedValueBase(ConfigSync configSync, string identifier, Type type, int priority) { Priority = priority; Identifier = identifier; Type = type; configSync.AddCustomValue(this); localIsOwner = configSync.IsSourceOfTruth; configSync.SourceOfTruthChanged += delegate(bool truth) { localIsOwner = truth; }; } } [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(0)] [PublicAPI] [<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(1)] internal sealed class CustomSyncedValue<[<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(2)] T> : CustomSyncedValueBase { public T Value { get { return (T)base.BoxedValue; } set { base.BoxedValue = value; } } public CustomSyncedValue(ConfigSync configSync, string identifier, T value = default(T), int priority = 0) : base(configSync, identifier, typeof(T), priority) { Value = value; } public void AssignLocalValue(T value) { if (localIsOwner) { Value = value; } else { LocalBaseValue = value; } } } internal class ConfigurationManagerAttributes { [UsedImplicitly] public bool? ReadOnly = false; } [<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(1)] [PublicAPI] [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(0)] internal class ConfigSync { [<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] [HarmonyPatch(typeof(ZRpc), "HandlePackage")] private static class SnatchCurrentlyHandlingRPC { [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(2)] public static ZRpc currentRpc; [<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(1)] [HarmonyPrefix] private static void Prefix(ZRpc __instance) { currentRpc = __instance; } } [HarmonyPatch(typeof(ZNet), "Awake")] [<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] internal static class RegisterRPCPatch { [<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(1)] [HarmonyPostfix] private static void Postfix(ZNet __instance) { isServer = __instance.IsServer(); foreach (ConfigSync configSync2 in configSyncs) { ZRoutedRpc.instance.Register(configSync2.Name + " ConfigSync", (Action)configSync2.RPC_FromOtherClientConfigSync); if (isServer) { configSync2.InitialSyncDone = true; Debug.Log((object)("Registered '" + configSync2.Name + " ConfigSync' RPC - waiting for incoming connections")); } } if (isServer) { ((MonoBehaviour)__instance).StartCoroutine(WatchAdminListChanges()); } [<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(1)] static void SendAdmin(List peers, bool isAdmin) { ZPackage package = ConfigsToPackage(null, null, new PackageEntry[1] { new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = isAdmin } }); ConfigSync configSync = configSyncs.First(); if (configSync != null) { ((MonoBehaviour)ZNet.instance).StartCoroutine(configSync.sendZPackage(peers, package)); } } [<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(1)] static IEnumerator WatchAdminListChanges() { MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); List CurrentList = new List(adminList.GetList()); while (true) { yield return (object)new WaitForSeconds(30f); if (!adminList.GetList().SequenceEqual(CurrentList)) { CurrentList = new List(adminList.GetList()); List adminPeer = ZNet.instance.GetPeers().Where(delegate(ZNetPeer p) { string hostName = p.m_rpc.GetSocket().GetHostName(); return ((object)listContainsId == null) ? adminList.Contains(hostName) : ((bool)listContainsId.Invoke(ZNet.instance, new object[2] { adminList, hostName })); }).ToList(); List nonAdminPeer = ZNet.instance.GetPeers().Except(adminPeer).ToList(); SendAdmin(nonAdminPeer, isAdmin: false); SendAdmin(adminPeer, isAdmin: true); } } } } } [HarmonyPatch(typeof(ZNet), "OnNewConnection")] [<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] private static class RegisterClientRPCPatch { [<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(1)] [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", (Action)configSync.RPC_FromServerConfigSync); } } } [<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] private class ParsedConfigs { [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(new byte[] { 1, 1, 2 })] public readonly Dictionary configValues = new Dictionary(); [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(new byte[] { 1, 1, 2 })] public readonly Dictionary customValues = new Dictionary(); } [HarmonyPatch(typeof(ZNet), "Shutdown")] [<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] 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")] [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(0)] private class SendConfigsAfterLogin { [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(0)] private class BufferingSocket : ZPlayFabSocket, ISocket { public volatile bool finished = false; public volatile int versionMatchQueued = -1; public readonly List Package = new List(); public readonly ISocket Original; public BufferingSocket(ISocket original) { Original = original; ((ZPlayFabSocket)this)..ctor(); } public bool IsConnected() { return Original.IsConnected(); } public ZPackage Recv() { return Original.Recv(); } public int GetSendQueueSize() { return Original.GetSendQueueSize(); } public int GetCurrentSendRate() { return Original.GetCurrentSendRate(); } public bool IsHost() { return Original.IsHost(); } public void Dispose() { Original.Dispose(); } public bool GotNewData() { return Original.GotNewData(); } public void Close() { Original.Close(); } public string GetEndPointString() { return Original.GetEndPointString(); } public void GetAndResetStats(out int totalSent, out int totalRecv) { Original.GetAndResetStats(ref totalSent, ref totalRecv); } public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec) { Original.GetConnectionQuality(ref localQuality, ref remoteQuality, ref ping, ref outByteSec, ref inByteSec); } public ISocket Accept() { return Original.Accept(); } public int GetHostPort() { return Original.GetHostPort(); } public bool Flush() { return Original.Flush(); } public string GetHostName() { return Original.GetHostName(); } public void VersionMatch() { if (finished) { Original.VersionMatch(); } else { versionMatchQueued = Package.Count; } } public void Send(ZPackage pkg) { //IL_0057: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Expected O, but got Unknown int pos = pkg.GetPos(); pkg.SetPos(0); int num = pkg.ReadInt(); if ((num == StringExtensionMethods.GetStableHashCode("PeerInfo") || num == StringExtensionMethods.GetStableHashCode("RoutedRPC") || num == StringExtensionMethods.GetStableHashCode("ZDOData")) && !finished) { ZPackage val = new ZPackage(pkg.GetArray()); val.SetPos(pos); Package.Add(val); } else { pkg.SetPos(pos); Original.Send(pkg); } } } [HarmonyPrefix] [HarmonyPriority(800)] private static void Prefix([<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(new byte[] { 2, 1, 1 })] ref Dictionary __state, ZNet __instance, ZRpc rpc) { //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007e: Invalid comparison between Unknown and I4 if (!__instance.IsServer()) { return; } BufferingSocket bufferingSocket = new BufferingSocket(rpc.GetSocket()); AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket); object? obj = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (val != null && (int)ZNet.m_onlineBackend > 0) { FieldInfo fieldInfo = AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket"); object? value = fieldInfo.GetValue(val); ZPlayFabSocket val2 = (ZPlayFabSocket)((value is ZPlayFabSocket) ? value : null); if (val2 != null) { typeof(ZPlayFabSocket).GetField("m_remotePlayerId").SetValue(bufferingSocket, val2.m_remotePlayerId); } fieldInfo.SetValue(val, 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) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); peer = (ZNetPeer)((obj is ZNetPeer) ? obj : null); if (peer == null) { SendBufferedData(); } else { ((MonoBehaviour)__instance).StartCoroutine(sendAsync()); } } void SendBufferedData() { if (rpc.GetSocket() is BufferingSocket bufferingSocket) { AccessTools.DeclaredField(typeof(ZRpc), "m_socket").SetValue(rpc, bufferingSocket.Original); object? obj2 = AccessTools.DeclaredMethod(typeof(ZNet), "GetPeer", new Type[1] { typeof(ZRpc) }, (Type[])null).Invoke(__instance, new object[1] { rpc }); ZNetPeer val = (ZNetPeer)((obj2 is ZNetPeer) ? obj2 : null); if (val != null) { AccessTools.DeclaredField(typeof(ZNetPeer), "m_socket").SetValue(val, bufferingSocket.Original); } } BufferingSocket bufferingSocket2 = __state[Assembly.GetExecutingAssembly()]; bufferingSocket2.finished = true; for (int i = 0; i < bufferingSocket2.Package.Count; i++) { if (i == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } bufferingSocket2.Original.Send(bufferingSocket2.Package[i]); } if (bufferingSocket2.Package.Count == bufferingSocket2.versionMatchQueued) { bufferingSocket2.Original.VersionMatch(); } } IEnumerator sendAsync() { foreach (ConfigSync configSync in configSyncs) { List entries = new List(); if (configSync.CurrentVersion != null) { entries.Add(new PackageEntry { section = "Internal", key = "serverversion", type = typeof(string), value = configSync.CurrentVersion }); } MethodInfo listContainsId = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList adminList = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); entries.Add(new PackageEntry { section = "Internal", key = "lockexempt", type = typeof(bool), value = (((object)listContainsId == null) ? ((object)adminList.Contains(rpc.GetSocket().GetHostName())) : listContainsId.Invoke(ZNet.instance, new object[2] { adminList, rpc.GetSocket().GetHostName() })) }); ZPackage package = ConfigsToPackage(configSync.allConfigs.Select([<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig), configSync.allCustomValues, entries, partial: false); yield return ((MonoBehaviour)__instance).StartCoroutine(configSync.sendZPackage(new List { peer }, package)); } SendBufferedData(); } } } [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(0)] private class PackageEntry { public string section = null; public string key = null; public Type type = null; [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(2)] public object value; } [HarmonyPatch(typeof(ConfigEntryBase), "GetSerializedValue")] [<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] private static class PreventSavingServerInfo { [<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(1)] [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; } } [<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] [HarmonyPatch(typeof(ConfigEntryBase), "SetSerializedValue")] private static class PreventConfigRereadChangingValues { [<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(1)] [HarmonyPrefix] private static bool Prefix(ConfigEntryBase __instance, string value) { OwnConfigEntryBase ownConfigEntryBase = configData(__instance); if (ownConfigEntryBase == null || ownConfigEntryBase.LocalBaseValue == null) { return true; } try { ownConfigEntryBase.LocalBaseValue = TomlTypeConverter.ConvertToValue(value, __instance.SettingType); } catch (Exception ex) { Debug.LogWarning((object)$"Config value of setting \"{__instance.Definition}\" could not be parsed and will be ignored. Reason: {ex.Message}; Value: {value}"); } return false; } } [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(0)] private class InvalidDeserializationTypeException : Exception { public string expected = null; public string received = null; public string field = ""; } public static bool ProcessingServerUpdate; public readonly string Name; [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(2)] public string DisplayName; [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(2)] public string CurrentVersion; [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(2)] public string MinimumRequiredVersion; public bool ModRequired = false; 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; [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(2)] private OwnConfigEntryBase lockedConfig = null; private const byte PARTIAL_CONFIGS = 1; private const byte FRAGMENTED_CONFIG = 2; private const byte COMPRESSED_CONFIG = 4; private readonly Dictionary> configValueCache = new Dictionary>(); [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(new byte[] { 1, 0, 1 })] 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_0052; } num = ((IConvertible)lockedConfig.BaseConfig.BoxedValue).ToInt32(CultureInfo.InvariantCulture) != 0; } else { num = flag.GetValueOrDefault(); } if (!num) { goto IL_0052; } int result = ((!lockExempt) ? 1 : 0); goto IL_0053; IL_0053: return (byte)result != 0; IL_0052: result = 0; goto IL_0053; } set { forceConfigLocking = value; } } public bool IsAdmin => lockExempt || isSourceOfTruth; public bool IsSourceOfTruth { get { return isSourceOfTruth; } private set { if (value != isSourceOfTruth) { isSourceOfTruth = value; this.SourceOfTruthChanged?.Invoke(value); } } } public bool InitialSyncDone { get; private set; } = false; [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(2)] [method: <6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(2)] [field: <1a203302-fe92-49d6-be0f-bfef62526189>Nullable(2)] public event Action SourceOfTruthChanged; [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(2)] [method: <6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(2)] [field: <1a203302-fe92-49d6-be0f-bfef62526189>Nullable(2)] 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<[<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(2)] T>(ConfigEntry configEntry) { OwnConfigEntryBase ownConfigEntryBase = configData((ConfigEntryBase)(object)configEntry); SyncedConfigEntry syncedEntry = ownConfigEntryBase as SyncedConfigEntry; if (syncedEntry == null) { syncedEntry = new SyncedConfigEntry(configEntry); AccessTools.DeclaredField(typeof(ConfigDescription), "k__BackingField").SetValue(((ConfigEntryBase)configEntry).Description, new object[1] { new ConfigurationManagerAttributes() }.Concat(((ConfigEntryBase)configEntry).Description.Tags ?? Array.Empty()).Concat(new SyncedConfigEntry[1] { syncedEntry }).ToArray()); configEntry.SettingChanged += [<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] (object _, EventArgs _) => { if (!ProcessingServerUpdate && syncedEntry.SynchronizedConfig) { Broadcast(ZRoutedRpc.Everybody, (ConfigEntryBase)configEntry); } }; allConfigs.Add(syncedEntry); } return syncedEntry; } public SyncedConfigEntry AddLockingConfigEntry<[<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(0)] T>(ConfigEntry lockingConfig) where T : IConvertible { if (lockedConfig != null) { throw new Exception("Cannot initialize locking ConfigEntry twice"); } lockedConfig = AddConfigEntry(lockingConfig); lockingConfig.SettingChanged += [<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] (object _, EventArgs _) => { this.lockedConfigChanged?.Invoke(); }; return (SyncedConfigEntry)lockedConfig; } internal void AddCustomValue(CustomSyncedValueBase customValue) { if (allCustomValues.Select([<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] (CustomSyncedValueBase v) => v.Identifier).Concat(new string[1] { "serverversion" }).Contains(customValue.Identifier)) { throw new Exception("Cannot have multiple settings with the same name or with a reserved name (serverversion)"); } allCustomValues.Add(customValue); allCustomValues = new HashSet(allCustomValues.OrderByDescending([<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] (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) { //IL_0076: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Expected O, but got Unknown //IL_0250: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Expected O, but got Unknown //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f1: Expected O, but got Unknown try { if (isServer && IsLocked) { ZRpc currentRpc = SnatchCurrentlyHandlingRPC.currentRpc; object obj; if (currentRpc == null) { obj = null; } else { ISocket socket = currentRpc.GetSocket(); obj = ((socket != null) ? socket.GetHostName() : null); } string text = (string)obj; if (text != null) { MethodInfo methodInfo = AccessTools.DeclaredMethod(typeof(ZNet), "ListContainsId", (Type[])null, (Type[])null); SyncedList val = (SyncedList)AccessTools.DeclaredField(typeof(ZNet), "m_adminList").GetValue(ZNet.instance); if (!(((object)methodInfo == null) ? val.Contains(text) : ((bool)methodInfo.Invoke(ZNet.instance, new object[2] { val, text })))) { return false; } } } cacheExpirations.RemoveAll(([<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(new byte[] { 0, 1 })] KeyValuePair kv) => { if (kv.Key < DateTimeOffset.Now.Ticks) { configValueCache.Remove(kv.Value); return true; } return false; }); byte b = package.ReadByte(); if ((b & 2u) != 0) { long num = package.ReadLong(); string text2 = sender.ToString() + num; if (!configValueCache.TryGetValue(text2, out var value)) { value = new SortedDictionary(); 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([<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] (byte[] a) => a).ToArray()); b = package.ReadByte(); } ProcessingServerUpdate = true; if ((b & 4u) != 0) { byte[] buffer = package.ReadByteArray(); MemoryStream stream = new MemoryStream(buffer); MemoryStream memoryStream = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(stream, CompressionMode.Decompress)) { deflateStream.CopyTo(memoryStream); } package = new ZPackage(memoryStream.ToArray()); b = package.ReadByte(); } if ((b & 1) == 0) { resetConfigsFromServer(); } ParsedConfigs parsedConfigs = ReadConfigsFromPackage(package); ConfigFile val2 = null; bool saveOnConfigSet = false; foreach (KeyValuePair configValue in parsedConfigs.configValues) { if (!isServer && configValue.Key.LocalBaseValue == null) { configValue.Key.LocalBaseValue = configValue.Key.BaseConfig.BoxedValue; } if (val2 == null) { val2 = configValue.Key.BaseConfig.ConfigFile; saveOnConfigSet = val2.SaveOnConfigSet; val2.SaveOnConfigSet = false; } configValue.Key.BaseConfig.BoxedValue = configValue.Value; } if (val2 != null) { val2.SaveOnConfigSet = saveOnConfigSet; } 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((object)string.Format("Received {0} configs and {1} custom values from {2} for mod {3}", parsedConfigs.configValues.Count, parsedConfigs.customValues.Count, (isServer || clientUpdate) ? $"client {sender}" : "the server", DisplayName ?? Name)); if (!isServer) { serverLockedSettingChanged(); } return true; } finally { ProcessingServerUpdate = false; } } private ParsedConfigs ReadConfigsFromPackage(ZPackage package) { ParsedConfigs parsedConfigs = new ParsedConfigs(); Dictionary dictionary = allConfigs.Where([<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] (OwnConfigEntryBase c) => c.SynchronizedConfig).ToDictionary([<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] (OwnConfigEntryBase c) => c.BaseConfig.Definition.Section + "_" + c.BaseConfig.Definition.Key, [<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] (OwnConfigEntryBase c) => c); Dictionary dictionary2 = allCustomValues.ToDictionary([<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] (CustomSyncedValueBase c) => c.Identifier, [<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] (CustomSyncedValueBase c) => c); int num = package.ReadInt(); for (int i = 0; i < num; i++) { string text = package.ReadString(); string text2 = package.ReadString(); string text3 = package.ReadString(); Type type = Type.GetType(text3); if (text3 == "" || type != null) { object obj; try { obj = ((text3 == "") ? null : ReadValueWithTypeFromZPackage(package, type)); } catch (InvalidDeserializationTypeException ex) { Debug.LogWarning((object)("Got unexpected struct internal type " + ex.received + " for field " + ex.field + " struct " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + ex.expected)); continue; } OwnConfigEntryBase value2; if (text == "Internal") { CustomSyncedValueBase value; if (text2 == "serverversion") { if (obj?.ToString() != CurrentVersion) { Debug.LogWarning((object)("Received server version is not equal: server version = " + (obj?.ToString() ?? "null") + "; local version = " + (CurrentVersion ?? "unknown"))); } } else if (text2 == "lockexempt") { if (obj is bool flag) { lockExempt = flag; } } else if (dictionary2.TryGetValue(text2, out value)) { if ((text3 == "" && (!value.Type.IsValueType || Nullable.GetUnderlyingType(value.Type) != null)) || GetZPackageTypeString(value.Type) == text3) { parsedConfigs.customValues[value] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for internal value " + text2 + " for mod " + (DisplayName ?? Name) + ", expecting " + value.Type.AssemblyQualifiedName)); } } else if (dictionary.TryGetValue(text + "_" + text2, out value2)) { Type type2 = configType(value2.BaseConfig); if ((text3 == "" && (!type2.IsValueType || Nullable.GetUnderlyingType(type2) != null)) || GetZPackageTypeString(type2) == text3) { parsedConfigs.configValues[value2] = obj; continue; } Debug.LogWarning((object)("Got unexpected type " + text3 + " for " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ", expecting " + type2.AssemblyQualifiedName)); } else { Debug.LogWarning((object)("Received unknown config entry " + text2 + " in section " + text + " for mod " + (DisplayName ?? Name) + ". This may happen if client and server versions of the mod do not match.")); } continue; } Debug.LogWarning((object)("Got invalid type " + text3 + ", abort reading of received configs")); return new ParsedConfigs(); } return parsedConfigs; } private static bool isWritableConfig(OwnConfigEntryBase config) { ConfigSync configSync = configSyncs.FirstOrDefault([<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] (ConfigSync cs) => cs.allConfigs.Contains(config)); if (configSync == null) { return true; } return configSync.IsSourceOfTruth || !config.SynchronizedConfig || config.LocalBaseValue == null || (!configSync.IsLocked && (config != configSync.lockedConfig || lockExempt)); } private void serverLockedSettingChanged() { foreach (OwnConfigEntryBase allConfig in allConfigs) { configAttribute(allConfig.BaseConfig).ReadOnly = !isWritableConfig(allConfig); } } private void resetConfigsFromServer() { ConfigFile val = null; bool saveOnConfigSet = false; foreach (OwnConfigEntryBase item in allConfigs.Where([<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] (OwnConfigEntryBase config) => config.LocalBaseValue != null)) { if (val == null) { val = item.BaseConfig.ConfigFile; saveOnConfigSet = val.SaveOnConfigSet; val.SaveOnConfigSet = false; } item.BaseConfig.BoxedValue = item.LocalBaseValue; item.LocalBaseValue = null; } if (val != null) { val.SaveOnConfigSet = saveOnConfigSet; } foreach (CustomSyncedValueBase item2 in allCustomValues.Where([<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] (CustomSyncedValueBase config) => config.LocalBaseValue != null)) { item2.BoxedValue = item2.LocalBaseValue; item2.LocalBaseValue = null; } lockedConfigChanged -= serverLockedSettingChanged; serverLockedSettingChanged(); } private IEnumerator distributeConfigToPeers(ZNetPeer peer, ZPackage package) { ZRoutedRpc rpc = ZRoutedRpc.instance; if (rpc == null) { yield break; } byte[] data = package.GetArray(); if (data != null && data.LongLength > 250000) { int fragments = (int)(1 + (data.LongLength - 1) / 250000); long packageIdentifier = ++packageCounter; int fragment = 0; while (fragment < fragments) { foreach (bool item in waitForQueue()) { yield return item; } if (peer.m_socket.IsConnected()) { ZPackage fragmentedPackage = new ZPackage(); fragmentedPackage.Write((byte)2); fragmentedPackage.Write(packageIdentifier); fragmentedPackage.Write(fragment); fragmentedPackage.Write(fragments); fragmentedPackage.Write(data.Skip(250000 * fragment).Take(250000).ToArray()); SendPackage(fragmentedPackage); if (fragment != fragments - 1) { yield return true; } int num = fragment + 1; fragment = num; continue; } break; } yield break; } foreach (bool item2 in waitForQueue()) { yield return item2; } SendPackage(package); void SendPackage(ZPackage pkg) { string text = Name + " ConfigSync"; if (isServer) { peer.m_rpc.Invoke(text, new object[1] { pkg }); } else { rpc.InvokeRoutedRPC(peer.m_server ? 0 : peer.m_uid, text, new object[1] { pkg }); } } IEnumerable waitForQueue() { float timeout = Time.time + 30f; while (peer.m_socket.GetSendQueueSize() > 20000) { if (Time.time > timeout) { Debug.Log((object)$"Disconnecting {peer.m_uid} after 30 seconds config sending timeout"); peer.m_rpc.Invoke("Error", new object[1] { (object)(ConnectionStatus)5 }); ZNet.instance.Disconnect(peer); break; } yield return false; } } } private IEnumerator sendZPackage(long target, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { return Enumerable.Empty().GetEnumerator(); } List list = (List)AccessTools.DeclaredField(typeof(ZRoutedRpc), "m_peers").GetValue(ZRoutedRpc.instance); if (target != ZRoutedRpc.Everybody) { list = list.Where([<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] (ZNetPeer p) => p.m_uid == target).ToList(); } return sendZPackage(list, package); } private IEnumerator sendZPackage(List peers, ZPackage package) { if (!Object.op_Implicit((Object)(object)ZNet.instance)) { yield break; } byte[] rawData = package.GetArray(); if (rawData != null && rawData.LongLength > 10000) { ZPackage compressedPackage = new ZPackage(); compressedPackage.Write((byte)4); MemoryStream output = new MemoryStream(); using (DeflateStream deflateStream = new DeflateStream(output, CompressionLevel.Optimal)) { deflateStream.Write(rawData, 0, rawData.Length); } compressedPackage.Write(output.ToArray()); package = compressedPackage; } List> writers = (from peer in peers where peer.IsReady() select peer into p 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 = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } private void Broadcast(long target, params CustomSyncedValueBase[] customValues) { if (!IsLocked || isServer) { ZPackage package = ConfigsToPackage(null, customValues); ZNet instance = ZNet.instance; if (instance != null) { ((MonoBehaviour)instance).StartCoroutine(sendZPackage(target, package)); } } } [return: <1a203302-fe92-49d6-be0f-bfef62526189>Nullable(2)] private static OwnConfigEntryBase configData(ConfigEntryBase config) { return config.Description.Tags?.OfType().SingleOrDefault(); } [return: <1a203302-fe92-49d6-be0f-bfef62526189>Nullable(new byte[] { 2, 1 })] public static SyncedConfigEntry ConfigData<[<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(2)] T>(ConfigEntry config) { return ((ConfigEntryBase)config).Description.Tags?.OfType>().SingleOrDefault(); } private static T configAttribute<[<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(2)] T>(ConfigEntryBase config) { return config.Description.Tags.OfType().First(); } private static Type configType(ConfigEntryBase config) { return configType(config.SettingType); } private static Type configType(Type type) { return type.IsEnum ? Enum.GetUnderlyingType(type) : type; } private static ZPackage ConfigsToPackage([<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(new byte[] { 2, 1 })] IEnumerable configs = null, [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(new byte[] { 2, 1 })] IEnumerable customValues = null, [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(new byte[] { 2, 1 })] IEnumerable packageEntries = null, bool partial = true) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0057: Expected O, but got Unknown List list = configs?.Where([<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] (ConfigEntryBase config) => configData(config).SynchronizedConfig).ToList() ?? new List(); List list2 = customValues?.ToList() ?? new List(); ZPackage val = new ZPackage(); val.Write((byte)(partial ? 1 : 0)); val.Write(list.Count + list2.Count + (packageEntries?.Count() ?? 0)); foreach (PackageEntry item in packageEntries ?? Array.Empty()) { AddEntryToPackage(val, item); } foreach (CustomSyncedValueBase item2 in list2) { AddEntryToPackage(val, new PackageEntry { section = "Internal", key = item2.Identifier, type = item2.Type, value = item2.BoxedValue }); } foreach (ConfigEntryBase item3 in list) { AddEntryToPackage(val, new PackageEntry { section = item3.Definition.Section, key = item3.Definition.Key, type = configType(item3), value = item3.BoxedValue }); } return val; } private static void AddEntryToPackage(ZPackage package, PackageEntry entry) { package.Write(entry.section); package.Write(entry.key); package.Write((entry.value == null) ? "" : GetZPackageTypeString(entry.type)); AddValueToZPackage(package, entry.value); } private static string GetZPackageTypeString(Type type) { return type.AssemblyQualifiedName; } private static void AddValueToZPackage(ZPackage package, [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(2)] 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 source = new List(); ZRpc.Deserialize(new ParameterInfo[2] { null, parameterInfo }, package, ref source); return source.First(); } } [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(0)] [PublicAPI] [HarmonyPatch] [<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(1)] internal class VersionCheck { private static readonly HashSet versionChecks; private static readonly Dictionary notProcessedNames; public string Name; [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(2)] private string displayName; [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(2)] private string currentVersion; [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(2)] private string minimumRequiredVersion; public bool ModRequired = true; [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(2)] private string ReceivedCurrentVersion; [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(2)] private string ReceivedMinimumRequiredVersion; private readonly List ValidatedClients = new List(); [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(2)] private ConfigSync ConfigSync; public string DisplayName { get { return displayName ?? Name; } set { displayName = value; } } public string CurrentVersion { get { return currentVersion ?? "0.0.0"; } set { currentVersion = value; } } public string MinimumRequiredVersion { get { return minimumRequiredVersion ?? (ModRequired ? CurrentVersion : "0.0.0"); } set { minimumRequiredVersion = value; } } private static void PatchServerSync() { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0064: Expected O, but got Unknown Patches patchInfo = PatchProcessor.GetPatchInfo((MethodBase)AccessTools.DeclaredMethod(typeof(ZNet), "Awake", (Type[])null, (Type[])null)); if (patchInfo != null && patchInfo.Postfixes.Count([<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] (Patch p) => p.PatchMethod.DeclaringType == typeof(ConfigSync.RegisterRPCPatch)) > 0) { return; } Harmony val = new Harmony("org.bepinex.helpers.ServerSync"); foreach (Type item in from t in typeof(ConfigSync).GetNestedTypes(BindingFlags.NonPublic).Concat(new Type[1] { typeof(VersionCheck) }) where t.IsClass select t) { val.PatchAll(item); } } static VersionCheck() { versionChecks = new HashSet(); 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 System.Version(CurrentVersion) >= new System.Version(ReceivedMinimumRequiredVersion); bool flag2 = new System.Version(ReceivedCurrentVersion) >= new System.Version(MinimumRequiredVersion); return flag && flag2; } private string ErrorClient() { if (ReceivedMinimumRequiredVersion == null) { return DisplayName + " is not installed on the server."; } return (new System.Version(CurrentVersion) >= new System.Version(ReceivedMinimumRequiredVersion)) ? (DisplayName + " may not be higher than version " + ReceivedCurrentVersion + ". You have version " + CurrentVersion + ".") : (DisplayName + " needs to be at least version " + ReceivedMinimumRequiredVersion + ". 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([<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(2)] ZRpc rpc = null) { return (rpc == null) ? ErrorClient() : ErrorServer(rpc); } private static VersionCheck[] GetFailedClient() { return versionChecks.Where([<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] (VersionCheck check) => !check.IsVersionOk()).ToArray(); } private static VersionCheck[] GetFailedServer(ZRpc rpc) { return versionChecks.Where([<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] (VersionCheck check) => check.ModRequired && !check.ValidatedClients.Contains(rpc)).ToArray(); } private static void Logout() { Game.instance.Logout(true, true); AccessTools.DeclaredField(typeof(ZNet), "m_connectionStatus").SetValue(null, (object)(ConnectionStatus)3); } private static void DisconnectClient(ZRpc rpc) { rpc.Invoke("Error", new object[1] { 3 }); } private static void CheckVersion(ZRpc rpc, ZPackage pkg) { CheckVersion(rpc, pkg, null); } private static void CheckVersion(ZRpc rpc, ZPackage pkg, [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(new byte[] { 2, 1, 1 })] 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((object)("Received " + versionCheck.DisplayName + " version " + text3 + " and minimum version " + text2 + " from the " + (ZNet.instance.IsServer() ? "client" : "server") + ".")); versionCheck.ReceivedMinimumRequiredVersion = text2; versionCheck.ReceivedCurrentVersion = text3; if (ZNet.instance.IsServer() && versionCheck.IsVersionOk()) { versionCheck.ValidatedClients.Add(rpc); } flag = true; } } if (flag) { return; } pkg.SetPos(0); if (original != null) { original(rpc, pkg); if (pkg.GetPos() == 0) { notProcessedNames.Add(text, text3); } } } [HarmonyPatch(typeof(ZNet), "RPC_PeerInfo")] [HarmonyPrefix] private static bool RPC_PeerInfo(ZRpc rpc, ZNet __instance) { VersionCheck[] array = (__instance.IsServer() ? GetFailedServer(rpc) : GetFailedClient()); if (array.Length == 0) { return true; } VersionCheck[] array2 = array; foreach (VersionCheck versionCheck in array2) { Debug.LogWarning((object)versionCheck.Error(rpc)); } if (__instance.IsServer()) { DisconnectClient(rpc); } else { Logout(); } return false; } [HarmonyPrefix] [HarmonyPatch(typeof(ZNet), "OnNewConnection")] private static void RegisterAndCheckVersion(ZNetPeer peer, ZNet __instance) { //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Expected O, but got Unknown notProcessedNames.Clear(); IDictionary dictionary = (IDictionary)typeof(ZRpc).GetField("m_functions", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(peer.m_rpc); if (dictionary.Contains(StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck"))) { object obj = dictionary[StringExtensionMethods.GetStableHashCode("ServerSync VersionCheck")]; Action action = (Action)obj.GetType().GetField("m_action", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(obj); peer.m_rpc.Register("ServerSync VersionCheck", (Action)([<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] (ZRpc rpc, [<1a203302-fe92-49d6-be0f-bfef62526189>Nullable(1)] ZPackage pkg) => { CheckVersion(rpc, pkg, action); })); } else { peer.m_rpc.Register("ServerSync VersionCheck", (Action)CheckVersion); } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.Initialize(); if (versionCheck.ModRequired || __instance.IsServer()) { Debug.Log((object)("Sending " + versionCheck.DisplayName + " version " + versionCheck.CurrentVersion + " and minimum version " + versionCheck.MinimumRequiredVersion + " to the " + (__instance.IsServer() ? "client" : "server") + ".")); ZPackage val = new ZPackage(); val.Write(versionCheck.Name); val.Write(versionCheck.MinimumRequiredVersion); val.Write(versionCheck.CurrentVersion); peer.m_rpc.Invoke("ServerSync VersionCheck", new object[1] { val }); } } } [HarmonyPrefix] [HarmonyPatch(typeof(ZNet), "Disconnect")] private static void RemoveDisconnected(ZNetPeer peer, ZNet __instance) { if (!__instance.IsServer()) { return; } foreach (VersionCheck versionCheck in versionChecks) { versionCheck.ValidatedClients.Remove(peer.m_rpc); } } [HarmonyPostfix] [HarmonyPatch(typeof(FejdStartup), "ShowConnectError")] private static void ShowConnectionError(FejdStartup __instance) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Invalid comparison between Unknown and I4 //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_018b: Unknown result type (might be due to invalid IL or missing references) //IL_0199: Unknown result type (might be due to invalid IL or missing references) //IL_01de: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Unknown result type (might be due to invalid IL or missing references) //IL_01f8: Unknown result type (might be due to invalid IL or missing references) //IL_020a: Unknown result type (might be due to invalid IL or missing references) //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Unknown result type (might be due to invalid IL or missing references) //IL_0229: Unknown result type (might be due to invalid IL or missing references) if (!__instance.m_connectionFailedPanel.activeSelf || (int)ZNet.GetConnectionStatus() != 3) { return; } bool flag = false; VersionCheck[] failedClient = GetFailedClient(); if (failedClient.Length != 0) { string text = string.Join("\n", failedClient.Select([<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] (VersionCheck check) => check.Error())); TMP_Text connectionFailedError = __instance.m_connectionFailedError; connectionFailedError.text = connectionFailedError.text + "\n" + text; flag = true; } foreach (KeyValuePair item in notProcessedNames.OrderBy([<6850fcc8-4c44-4b67-99e3-875d7f2a16c1>NullableContext(0)] (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 = ((Component)__instance.m_connectionFailedPanel.transform.Find("Image")).GetComponent(); Vector2 sizeDelta = component.sizeDelta; sizeDelta.x = 675f; component.sizeDelta = sizeDelta; __instance.m_connectionFailedError.ForceMeshUpdate(false, false); float num = __instance.m_connectionFailedError.renderedHeight + 105f; RectTransform component2 = ((Component)((Component)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; } } } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsReadOnlyAttribute : Attribute { } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } } namespace YamlDotNet { internal sealed class CultureInfoAdapter : CultureInfo { private readonly IFormatProvider provider; public CultureInfoAdapter(CultureInfo baseCulture, IFormatProvider provider) : base(baseCulture.LCID) { this.provider = provider; } public override object? GetFormat(Type? formatType) { return provider.GetFormat(formatType); } } internal static class ReflectionExtensions { private static readonly FieldInfo? RemoteStackTraceField = typeof(Exception).GetField("_remoteStackTraceString", BindingFlags.Instance | BindingFlags.NonPublic); public static Type? BaseType(this Type type) { return type.BaseType; } public static bool IsValueType(this Type type) { return type.IsValueType; } public static bool IsGenericType(this Type type) { return type.IsGenericType; } public static bool IsGenericTypeDefinition(this Type type) { return type.IsGenericTypeDefinition; } public static bool IsInterface(this Type type) { return type.IsInterface; } public static bool IsEnum(this Type type) { return type.IsEnum; } public static bool IsDbNull(this object value) { return value is DBNull; } public static bool HasDefaultConstructor(this Type type, bool allowPrivateConstructors) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public; if (allowPrivateConstructors) { bindingFlags |= BindingFlags.NonPublic; } if (!type.IsValueType) { return type.GetConstructor(bindingFlags, null, Type.EmptyTypes, null) != null; } return true; } public static TypeCode GetTypeCode(this Type type) { return Type.GetTypeCode(type); } public static PropertyInfo? GetPublicProperty(this Type type, string name) { return type.GetProperty(name); } public static FieldInfo? GetPublicStaticField(this Type type, string name) { return type.GetField(name, BindingFlags.Static | BindingFlags.Public); } public static IEnumerable GetProperties(this Type type, bool includeNonPublic) { BindingFlags bindingFlags = BindingFlags.Instance | BindingFlags.Public; if (includeNonPublic) { bindingFlags |= BindingFlags.NonPublic; } if (!type.IsInterface) { return type.GetProperties(bindingFlags); } return new Type[1] { type }.Concat(type.GetInterfaces()).SelectMany((Type i) => i.GetProperties(bindingFlags)); } public static IEnumerable GetPublicProperties(this Type type) { return type.GetProperties(includeNonPublic: false); } public static IEnumerable GetPublicFields(this Type type) { return type.GetFields(BindingFlags.Instance | BindingFlags.Public); } public static IEnumerable GetPublicStaticMethods(this Type type) { return type.GetMethods(BindingFlags.Static | BindingFlags.Public); } public static MethodInfo GetPrivateStaticMethod(this Type type, string name) { return type.GetMethod(name, BindingFlags.Static | BindingFlags.NonPublic) ?? throw new MissingMethodException("Expected to find a method named '" + name + "' in '" + type.FullName + "'."); } public static MethodInfo? GetPublicStaticMethod(this Type type, string name, params Type[] parameterTypes) { return type.GetMethod(name, BindingFlags.Static | BindingFlags.Public, null, parameterTypes, null); } public static MethodInfo? GetPublicInstanceMethod(this Type type, string name) { return type.GetMethod(name, BindingFlags.Instance | BindingFlags.Public); } public static Exception Unwrap(this TargetInvocationException ex) { Exception innerException = ex.InnerException; if (innerException == null) { return ex; } if (RemoteStackTraceField != null) { RemoteStackTraceField.SetValue(innerException, innerException.StackTrace + "\r\n"); } return innerException; } public static bool IsInstanceOf(this Type type, object o) { return type.IsInstanceOfType(o); } public static Attribute[] GetAllCustomAttributes(this PropertyInfo property) { return Attribute.GetCustomAttributes(property, typeof(TAttribute), inherit: true); } } internal static class PropertyInfoExtensions { public static object? ReadValue(this PropertyInfo property, object target) { return property.GetValue(target, null); } } internal static class StandardRegexOptions { public const RegexOptions Compiled = RegexOptions.Compiled; } } namespace YamlDotNet.Serialization { internal abstract class BuilderSkeleton where TBuilder : BuilderSkeleton { internal INamingConvention namingConvention = NullNamingConvention.Instance; internal ITypeResolver typeResolver; internal readonly YamlAttributeOverrides overrides; internal readonly LazyComponentRegistrationList typeConverterFactories; internal readonly LazyComponentRegistrationList typeInspectorFactories; internal bool ignoreFields; internal bool includeNonPublicProperties; internal Settings settings; protected abstract TBuilder Self { get; } internal BuilderSkeleton(ITypeResolver typeResolver) { overrides = new YamlAttributeOverrides(); typeConverterFactories = new LazyComponentRegistrationList { { typeof(YamlDotNet.Serialization.Converters.GuidConverter), (Nothing _) => new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: false) }, { typeof(SystemTypeConverter), (Nothing _) => new SystemTypeConverter() } }; typeInspectorFactories = new LazyComponentRegistrationList(); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); settings = new Settings(); } public TBuilder IgnoreFields() { ignoreFields = true; return Self; } public TBuilder IncludeNonPublicProperties() { includeNonPublicProperties = true; return Self; } public TBuilder EnablePrivateConstructors() { settings.AllowPrivateConstructors = true; return Self; } public TBuilder WithNamingConvention(INamingConvention namingConvention) { this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention"); return Self; } public TBuilder WithTypeResolver(ITypeResolver typeResolver) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); return Self; } public abstract TBuilder WithTagMapping(TagName tag, Type type); public TBuilder WithAttributeOverride(Expression> propertyAccessor, Attribute attribute) { overrides.Add(propertyAccessor, attribute); return Self; } public TBuilder WithAttributeOverride(Type type, string member, Attribute attribute) { overrides.Add(type, member, attribute); return Self; } public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter) { return WithTypeConverter(typeConverter, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter, Action> where) { IYamlTypeConverter typeConverter2 = typeConverter; if (typeConverter2 == null) { throw new ArgumentNullException("typeConverter"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateRegistrationLocationSelector(typeConverter2.GetType(), (Nothing _) => typeConverter2)); return Self; } public TBuilder WithTypeConverter(WrapperFactory typeConverterFactory, Action> where) where TYamlTypeConverter : IYamlTypeConverter { WrapperFactory typeConverterFactory2 = typeConverterFactory; if (typeConverterFactory2 == null) { throw new ArgumentNullException("typeConverterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateTrackingRegistrationLocationSelector(typeof(TYamlTypeConverter), (IYamlTypeConverter wrapped, Nothing _) => typeConverterFactory2(wrapped))); return Self; } public TBuilder WithoutTypeConverter() where TYamlTypeConverter : IYamlTypeConverter { return WithoutTypeConverter(typeof(TYamlTypeConverter)); } public TBuilder WithoutTypeConverter(Type converterType) { if (converterType == null) { throw new ArgumentNullException("converterType"); } typeConverterFactories.Remove(converterType); return Self; } public TBuilder WithTypeInspector(Func typeInspectorFactory) where TTypeInspector : ITypeInspector { return WithTypeInspector(typeInspectorFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public TBuilder WithTypeInspector(Func typeInspectorFactory, Action> where) where TTypeInspector : ITypeInspector { Func typeInspectorFactory2 = typeInspectorFactory; if (typeInspectorFactory2 == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector inner) => typeInspectorFactory2(inner))); return Self; } public TBuilder WithTypeInspector(WrapperFactory typeInspectorFactory, Action> where) where TTypeInspector : ITypeInspector { WrapperFactory typeInspectorFactory2 = typeInspectorFactory; if (typeInspectorFactory2 == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateTrackingRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector wrapped, ITypeInspector inner) => typeInspectorFactory2(wrapped, inner))); return Self; } public TBuilder WithoutTypeInspector() where TTypeInspector : ITypeInspector { return WithoutTypeInspector(typeof(TTypeInspector)); } public TBuilder WithoutTypeInspector(Type inspectorType) { if (inspectorType == null) { throw new ArgumentNullException("inspectorType"); } typeInspectorFactories.Remove(inspectorType); return Self; } protected IEnumerable BuildTypeConverters() { return typeConverterFactories.BuildComponentList(); } } internal delegate TComponent WrapperFactory(TComponentBase wrapped) where TComponent : TComponentBase; internal delegate TComponent WrapperFactory(TComponentBase wrapped, TArgument argument) where TComponent : TComponentBase; [Flags] internal enum DefaultValuesHandling { Preserve = 0, OmitNull = 1, OmitDefaults = 2, OmitEmptyCollections = 4 } internal sealed class Deserializer : IDeserializer { private readonly IValueDeserializer valueDeserializer; public Deserializer() : this(new DeserializerBuilder().BuildValueDeserializer()) { } private Deserializer(IValueDeserializer valueDeserializer) { this.valueDeserializer = valueDeserializer ?? throw new ArgumentNullException("valueDeserializer"); } public static Deserializer FromValueDeserializer(IValueDeserializer valueDeserializer) { return new Deserializer(valueDeserializer); } public T Deserialize(string input) { using StringReader input2 = new StringReader(input); return Deserialize(input2); } public T Deserialize(TextReader input) { return Deserialize(new Parser(input)); } public object? Deserialize(TextReader input) { return Deserialize(input, typeof(object)); } public object? Deserialize(string input, Type type) { using StringReader input2 = new StringReader(input); return Deserialize(input2, type); } public object? Deserialize(TextReader input, Type type) { return Deserialize(new Parser(input), type); } public T Deserialize(IParser parser) { return (T)Deserialize(parser, typeof(T)); } public object? Deserialize(IParser parser) { return Deserialize(parser, typeof(object)); } public object? Deserialize(IParser parser, Type type) { if (parser == null) { throw new ArgumentNullException("parser"); } if (type == null) { throw new ArgumentNullException("type"); } YamlDotNet.Core.Events.StreamStart @event; bool flag = parser.TryConsume(out @event); YamlDotNet.Core.Events.DocumentStart event2; bool flag2 = parser.TryConsume(out event2); object result = null; if (!parser.Accept(out var _) && !parser.Accept(out var _)) { using SerializerState serializerState = new SerializerState(); result = valueDeserializer.DeserializeValue(parser, type, serializerState, valueDeserializer); serializerState.OnDeserialization(); } if (flag2) { parser.Consume(); } if (flag) { parser.Consume(); } return result; } } internal sealed class DeserializerBuilder : BuilderSkeleton { private Lazy objectFactory; private readonly LazyComponentRegistrationList nodeDeserializerFactories; private readonly LazyComponentRegistrationList nodeTypeResolverFactories; private readonly Dictionary tagMappings; private readonly Dictionary typeMappings; private readonly ITypeConverter typeConverter; private bool ignoreUnmatched; private bool duplicateKeyChecking; private bool attemptUnknownTypeDeserialization; protected override DeserializerBuilder Self => this; public DeserializerBuilder() : base((ITypeResolver)new StaticTypeResolver()) { typeMappings = new Dictionary(); objectFactory = new Lazy(() => new DefaultObjectFactory(typeMappings, settings), isThreadSafe: true); tagMappings = new Dictionary { { FailsafeSchema.Tags.Map, typeof(Dictionary) }, { FailsafeSchema.Tags.Str, typeof(string) }, { JsonSchema.Tags.Bool, typeof(bool) }, { JsonSchema.Tags.Float, typeof(double) }, { JsonSchema.Tags.Int, typeof(int) }, { DefaultSchema.Tags.Timestamp, typeof(DateTime) } }; typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner)); typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner); typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner)); typeInspectorFactories.Add(typeof(YamlAttributeOverridesInspector), (ITypeInspector inner) => (overrides == null) ? inner : new YamlAttributeOverridesInspector(inner, overrides.Clone())); typeInspectorFactories.Add(typeof(ReadableAndWritablePropertiesTypeInspector), (ITypeInspector inner) => new ReadableAndWritablePropertiesTypeInspector(inner)); nodeDeserializerFactories = new LazyComponentRegistrationList { { typeof(YamlConvertibleNodeDeserializer), (Nothing _) => new YamlConvertibleNodeDeserializer(objectFactory.Value) }, { typeof(YamlSerializableNodeDeserializer), (Nothing _) => new YamlSerializableNodeDeserializer(objectFactory.Value) }, { typeof(TypeConverterNodeDeserializer), (Nothing _) => new TypeConverterNodeDeserializer(BuildTypeConverters()) }, { typeof(NullNodeDeserializer), (Nothing _) => new NullNodeDeserializer() }, { typeof(ScalarNodeDeserializer), (Nothing _) => new ScalarNodeDeserializer(attemptUnknownTypeDeserialization, typeConverter) }, { typeof(ArrayNodeDeserializer), (Nothing _) => new ArrayNodeDeserializer() }, { typeof(DictionaryNodeDeserializer), (Nothing _) => new DictionaryNodeDeserializer(objectFactory.Value, duplicateKeyChecking) }, { typeof(CollectionNodeDeserializer), (Nothing _) => new CollectionNodeDeserializer(objectFactory.Value) }, { typeof(EnumerableNodeDeserializer), (Nothing _) => new EnumerableNodeDeserializer() }, { typeof(ObjectNodeDeserializer), (Nothing _) => new ObjectNodeDeserializer(objectFactory.Value, BuildTypeInspector(), ignoreUnmatched, duplicateKeyChecking, typeConverter) } }; nodeTypeResolverFactories = new LazyComponentRegistrationList { { typeof(MappingNodeTypeResolver), (Nothing _) => new MappingNodeTypeResolver(typeMappings) }, { typeof(YamlConvertibleTypeResolver), (Nothing _) => new YamlConvertibleTypeResolver() }, { typeof(YamlSerializableTypeResolver), (Nothing _) => new YamlSerializableTypeResolver() }, { typeof(TagNodeTypeResolver), (Nothing _) => new TagNodeTypeResolver(tagMappings) }, { typeof(PreventUnknownTagsNodeTypeResolver), (Nothing _) => new PreventUnknownTagsNodeTypeResolver() }, { typeof(DefaultContainersNodeTypeResolver), (Nothing _) => new DefaultContainersNodeTypeResolver() } }; typeConverter = new ReflectionTypeConverter(); } internal ITypeInspector BuildTypeInspector() { ITypeInspector typeInspector = new WritablePropertiesTypeInspector(typeResolver, includeNonPublicProperties); if (!ignoreFields) { typeInspector = new CompositeTypeInspector(new ReadableFieldsTypeInspector(typeResolver), typeInspector); } return typeInspectorFactories.BuildComponentChain(typeInspector); } public DeserializerBuilder WithAttemptingUnquotedStringTypeDeserialization() { attemptUnknownTypeDeserialization = true; return this; } public DeserializerBuilder WithObjectFactory(IObjectFactory objectFactory) { IObjectFactory objectFactory2 = objectFactory; if (objectFactory2 == null) { throw new ArgumentNullException("objectFactory"); } this.objectFactory = new Lazy(() => objectFactory2, isThreadSafe: true); return this; } public DeserializerBuilder WithObjectFactory(Func objectFactory) { if (objectFactory == null) { throw new ArgumentNullException("objectFactory"); } return WithObjectFactory(new LambdaObjectFactory(objectFactory)); } public DeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer) { return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public DeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer, Action> where) { INodeDeserializer nodeDeserializer2 = nodeDeserializer; if (nodeDeserializer2 == null) { throw new ArgumentNullException("nodeDeserializer"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateRegistrationLocationSelector(nodeDeserializer2.GetType(), (Nothing _) => nodeDeserializer2)); return this; } public DeserializerBuilder WithNodeDeserializer(WrapperFactory nodeDeserializerFactory, Action> where) where TNodeDeserializer : INodeDeserializer { WrapperFactory nodeDeserializerFactory2 = nodeDeserializerFactory; if (nodeDeserializerFactory2 == null) { throw new ArgumentNullException("nodeDeserializerFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeDeserializer), (INodeDeserializer wrapped, Nothing _) => nodeDeserializerFactory2(wrapped))); return this; } public DeserializerBuilder WithoutNodeDeserializer() where TNodeDeserializer : INodeDeserializer { return WithoutNodeDeserializer(typeof(TNodeDeserializer)); } public DeserializerBuilder WithoutNodeDeserializer(Type nodeDeserializerType) { if (nodeDeserializerType == null) { throw new ArgumentNullException("nodeDeserializerType"); } nodeDeserializerFactories.Remove(nodeDeserializerType); return this; } public DeserializerBuilder WithTypeDiscriminatingNodeDeserializer(Action configureTypeDiscriminatingNodeDeserializerOptions, int maxDepth = -1, int maxLength = -1) { TypeDiscriminatingNodeDeserializerOptions typeDiscriminatingNodeDeserializerOptions = new TypeDiscriminatingNodeDeserializerOptions(); configureTypeDiscriminatingNodeDeserializerOptions(typeDiscriminatingNodeDeserializerOptions); TypeDiscriminatingNodeDeserializer nodeDeserializer = new TypeDiscriminatingNodeDeserializer(nodeDeserializerFactories.BuildComponentList(), typeDiscriminatingNodeDeserializerOptions.discriminators, maxDepth, maxLength); return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax s) { s.Before(); }); } public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver) { return WithNodeTypeResolver(nodeTypeResolver, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public DeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver, Action> where) { INodeTypeResolver nodeTypeResolver2 = nodeTypeResolver; if (nodeTypeResolver2 == null) { throw new ArgumentNullException("nodeTypeResolver"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateRegistrationLocationSelector(nodeTypeResolver2.GetType(), (Nothing _) => nodeTypeResolver2)); return this; } public DeserializerBuilder WithNodeTypeResolver(WrapperFactory nodeTypeResolverFactory, Action> where) where TNodeTypeResolver : INodeTypeResolver { WrapperFactory nodeTypeResolverFactory2 = nodeTypeResolverFactory; if (nodeTypeResolverFactory2 == null) { throw new ArgumentNullException("nodeTypeResolverFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeTypeResolver), (INodeTypeResolver wrapped, Nothing _) => nodeTypeResolverFactory2(wrapped))); return this; } public DeserializerBuilder WithoutNodeTypeResolver() where TNodeTypeResolver : INodeTypeResolver { return WithoutNodeTypeResolver(typeof(TNodeTypeResolver)); } public DeserializerBuilder WithoutNodeTypeResolver(Type nodeTypeResolverType) { if (nodeTypeResolverType == null) { throw new ArgumentNullException("nodeTypeResolverType"); } nodeTypeResolverFactories.Remove(nodeTypeResolverType); return this; } public override DeserializerBuilder WithTagMapping(TagName tag, Type type) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (type == null) { throw new ArgumentNullException("type"); } if (tagMappings.TryGetValue(tag, out Type value)) { throw new ArgumentException($"Type already has a registered type '{value.FullName}' for tag '{tag}'", "tag"); } tagMappings.Add(tag, type); return this; } public DeserializerBuilder WithTypeMapping() where TConcrete : TInterface { Type typeFromHandle = typeof(TInterface); Type typeFromHandle2 = typeof(TConcrete); if (!typeFromHandle.IsAssignableFrom(typeFromHandle2)) { throw new InvalidOperationException("The type '" + typeFromHandle2.Name + "' does not implement interface '" + typeFromHandle.Name + "'."); } if (typeMappings.ContainsKey(typeFromHandle)) { typeMappings[typeFromHandle] = typeFromHandle2; } else { typeMappings.Add(typeFromHandle, typeFromHandle2); } return this; } public DeserializerBuilder WithoutTagMapping(TagName tag) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (!tagMappings.Remove(tag)) { throw new KeyNotFoundException($"Tag '{tag}' is not registered"); } return this; } public DeserializerBuilder IgnoreUnmatchedProperties() { ignoreUnmatched = true; return this; } public DeserializerBuilder WithDuplicateKeyChecking() { duplicateKeyChecking = true; return this; } public IDeserializer Build() { return Deserializer.FromValueDeserializer(BuildValueDeserializer()); } public IValueDeserializer BuildValueDeserializer() { return new AliasValueDeserializer(new NodeValueDeserializer(nodeDeserializerFactories.BuildComponentList(), nodeTypeResolverFactories.BuildComponentList(), typeConverter)); } } internal sealed class EmissionPhaseObjectGraphVisitorArgs { private readonly IEnumerable> preProcessingPhaseVisitors; public IObjectGraphVisitor InnerVisitor { get; private set; } public IEventEmitter EventEmitter { get; private set; } public ObjectSerializer NestedObjectSerializer { get; private set; } public IEnumerable TypeConverters { get; private set; } public EmissionPhaseObjectGraphVisitorArgs(IObjectGraphVisitor innerVisitor, IEventEmitter eventEmitter, IEnumerable> preProcessingPhaseVisitors, IEnumerable typeConverters, ObjectSerializer nestedObjectSerializer) { InnerVisitor = innerVisitor ?? throw new ArgumentNullException("innerVisitor"); EventEmitter = eventEmitter ?? throw new ArgumentNullException("eventEmitter"); this.preProcessingPhaseVisitors = preProcessingPhaseVisitors ?? throw new ArgumentNullException("preProcessingPhaseVisitors"); TypeConverters = typeConverters ?? throw new ArgumentNullException("typeConverters"); NestedObjectSerializer = nestedObjectSerializer ?? throw new ArgumentNullException("nestedObjectSerializer"); } public T GetPreProcessingPhaseObjectGraphVisitor() where T : IObjectGraphVisitor { return preProcessingPhaseVisitors.OfType().Single(); } } internal abstract class EventInfo { public IObjectDescriptor Source { get; } protected EventInfo(IObjectDescriptor source) { Source = source ?? throw new ArgumentNullException("source"); } } internal class AliasEventInfo : EventInfo { public AnchorName Alias { get; } public bool NeedsExpansion { get; set; } public AliasEventInfo(IObjectDescriptor source, AnchorName alias) : base(source) { if (alias.IsEmpty) { throw new ArgumentNullException("alias"); } Alias = alias; } } internal class ObjectEventInfo : EventInfo { public AnchorName Anchor { get; set; } public TagName Tag { get; set; } protected ObjectEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class ScalarEventInfo : ObjectEventInfo { public string RenderedValue { get; set; } public ScalarStyle Style { get; set; } public bool IsPlainImplicit { get; set; } public bool IsQuotedImplicit { get; set; } public ScalarEventInfo(IObjectDescriptor source) : base(source) { Style = source.ScalarStyle; RenderedValue = string.Empty; } } internal sealed class MappingStartEventInfo : ObjectEventInfo { public bool IsImplicit { get; set; } public MappingStyle Style { get; set; } public MappingStartEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class MappingEndEventInfo : EventInfo { public MappingEndEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class SequenceStartEventInfo : ObjectEventInfo { public bool IsImplicit { get; set; } public SequenceStyle Style { get; set; } public SequenceStartEventInfo(IObjectDescriptor source) : base(source) { } } internal sealed class SequenceEndEventInfo : EventInfo { public SequenceEndEventInfo(IObjectDescriptor source) : base(source) { } } internal interface IAliasProvider { AnchorName GetAlias(object target); } internal interface IDeserializer { T Deserialize(string input); T Deserialize(TextReader input); object? Deserialize(TextReader input); object? Deserialize(string input, Type type); object? Deserialize(TextReader input, Type type); T Deserialize(IParser parser); object? Deserialize(IParser parser); object? Deserialize(IParser parser, Type type); } internal interface IEventEmitter { void Emit(AliasEventInfo eventInfo, IEmitter emitter); void Emit(ScalarEventInfo eventInfo, IEmitter emitter); void Emit(MappingStartEventInfo eventInfo, IEmitter emitter); void Emit(MappingEndEventInfo eventInfo, IEmitter emitter); void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter); void Emit(SequenceEndEventInfo eventInfo, IEmitter emitter); } internal interface INamingConvention { string Apply(string value); } internal interface INodeDeserializer { bool Deserialize(IParser reader, Type expectedType, Func nestedObjectDeserializer, out object? value); } internal interface INodeTypeResolver { bool Resolve(NodeEvent? nodeEvent, ref Type currentType); } internal interface IObjectAccessor { void Set(string name, object target, object value); object? Read(string name, object target); } internal interface IObjectDescriptor { object? Value { get; } Type Type { get; } Type StaticType { get; } ScalarStyle ScalarStyle { get; } } internal static class ObjectDescriptorExtensions { public static object NonNullValue(this IObjectDescriptor objectDescriptor) { return objectDescriptor.Value ?? throw new InvalidOperationException("Attempted to use a IObjectDescriptor of type '" + objectDescriptor.Type.FullName + "' whose Value is null at a point whete it is invalid to do so. This may indicate a bug in YamlDotNet."); } } internal interface IObjectFactory { object Create(Type type); object? CreatePrimitive(Type type); bool GetDictionary(IObjectDescriptor descriptor, out IDictionary? dictionary, out Type[]? genericArguments); Type GetValueType(Type type); } internal interface IObjectGraphTraversalStrategy { void Traverse(IObjectDescriptor graph, IObjectGraphVisitor visitor, TContext context); } internal interface IObjectGraphVisitor { bool Enter(IObjectDescriptor value, TContext context); bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, TContext context); bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, TContext context); void VisitScalar(IObjectDescriptor scalar, TContext context); void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, TContext context); void VisitMappingEnd(IObjectDescriptor mapping, TContext context); void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, TContext context); void VisitSequenceEnd(IObjectDescriptor sequence, TContext context); } internal interface IPropertyDescriptor { string Name { get; } bool CanWrite { get; } Type Type { get; } Type? TypeOverride { get; set; } int Order { get; set; } ScalarStyle ScalarStyle { get; set; } T? GetCustomAttribute() where T : Attribute; IObjectDescriptor Read(object target); void Write(object target, object? value); } internal interface IRegistrationLocationSelectionSyntax { void InsteadOf() where TRegistrationType : TBaseRegistrationType; void Before() where TRegistrationType : TBaseRegistrationType; void After() where TRegistrationType : TBaseRegistrationType; void OnTop(); void OnBottom(); } internal interface ITrackingRegistrationLocationSelectionSyntax { void InsteadOf() where TRegistrationType : TBaseRegistrationType; } internal interface ISerializer { void Serialize(TextWriter writer, object? graph); string Serialize(object? graph); void Serialize(TextWriter writer, object? graph, Type type); void Serialize(IEmitter emitter, object? graph); void Serialize(IEmitter emitter, object? graph, Type type); } internal interface ITypeInspector { IEnumerable GetProperties(Type type, object? container); IPropertyDescriptor GetProperty(Type type, object? container, string name, [MaybeNullWhen(true)] bool ignoreUnmatched); } internal interface ITypeResolver { Type Resolve(Type staticType, object? actualValue); } internal interface IValueDeserializer { object? DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer); } internal interface IValuePromise { event Action ValueAvailable; } internal interface IValueSerializer { void SerializeValue(IEmitter emitter, object? value, Type? type); } internal interface IYamlConvertible { void Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer); void Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer); } internal delegate object? ObjectDeserializer(Type type); internal delegate void ObjectSerializer(object? value, Type? type = null); [Obsolete("Please use IYamlConvertible instead")] internal interface IYamlSerializable { void ReadYaml(IParser parser); void WriteYaml(IEmitter emitter); } internal interface IYamlTypeConverter { bool Accepts(Type type); object? ReadYaml(IParser parser, Type type); void WriteYaml(IEmitter emitter, object? value, Type type); } internal sealed class LazyComponentRegistrationList : IEnumerable>, IEnumerable { public sealed class LazyComponentRegistration { public readonly Type ComponentType; public readonly Func Factory; public LazyComponentRegistration(Type componentType, Func factory) { ComponentType = componentType; Factory = factory; } } public sealed class TrackingLazyComponentRegistration { public readonly Type ComponentType; public readonly Func Factory; public TrackingLazyComponentRegistration(Type componentType, Func factory) { ComponentType = componentType; Factory = factory; } } private class RegistrationLocationSelector : IRegistrationLocationSelectionSyntax { private readonly LazyComponentRegistrationList registrations; private readonly LazyComponentRegistration newRegistration; public RegistrationLocationSelector(LazyComponentRegistrationList registrations, LazyComponentRegistration newRegistration) { this.registrations = registrations; this.newRegistration = newRegistration; } void IRegistrationLocationSelectionSyntax.InsteadOf() { if (newRegistration.ComponentType != typeof(TRegistrationType)) { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); } int index = registrations.EnsureRegistrationExists(); registrations.entries[index] = newRegistration; } void IRegistrationLocationSelectionSyntax.After() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); int num = registrations.EnsureRegistrationExists(); registrations.entries.Insert(num + 1, newRegistration); } void IRegistrationLocationSelectionSyntax.Before() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); int index = registrations.EnsureRegistrationExists(); registrations.entries.Insert(index, newRegistration); } void IRegistrationLocationSelectionSyntax.OnBottom() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); registrations.entries.Add(newRegistration); } void IRegistrationLocationSelectionSyntax.OnTop() { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); registrations.entries.Insert(0, newRegistration); } } private class TrackingRegistrationLocationSelector : ITrackingRegistrationLocationSelectionSyntax { private readonly LazyComponentRegistrationList registrations; private readonly TrackingLazyComponentRegistration newRegistration; public TrackingRegistrationLocationSelector(LazyComponentRegistrationList registrations, TrackingLazyComponentRegistration newRegistration) { this.registrations = registrations; this.newRegistration = newRegistration; } void ITrackingRegistrationLocationSelectionSyntax.InsteadOf() { if (newRegistration.ComponentType != typeof(TRegistrationType)) { registrations.EnsureNoDuplicateRegistrationType(newRegistration.ComponentType); } int index = registrations.EnsureRegistrationExists(); Func innerComponentFactory = registrations.entries[index].Factory; registrations.entries[index] = new LazyComponentRegistration(newRegistration.ComponentType, (TArgument arg) => newRegistration.Factory(innerComponentFactory(arg), arg)); } } private readonly List entries = new List(); public int Count => entries.Count; public IEnumerable> InReverseOrder { get { int i = entries.Count - 1; while (i >= 0) { yield return entries[i].Factory; int num = i - 1; i = num; } } } public LazyComponentRegistrationList Clone() { LazyComponentRegistrationList lazyComponentRegistrationList = new LazyComponentRegistrationList(); foreach (LazyComponentRegistration entry in entries) { lazyComponentRegistrationList.entries.Add(entry); } return lazyComponentRegistrationList; } public void Clear() { entries.Clear(); } public void Add(Type componentType, Func factory) { entries.Add(new LazyComponentRegistration(componentType, factory)); } public void Remove(Type componentType) { for (int i = 0; i < entries.Count; i++) { if (entries[i].ComponentType == componentType) { entries.RemoveAt(i); return; } } throw new KeyNotFoundException("A component registration of type '" + componentType.FullName + "' was not found."); } public IRegistrationLocationSelectionSyntax CreateRegistrationLocationSelector(Type componentType, Func factory) { return new RegistrationLocationSelector(this, new LazyComponentRegistration(componentType, factory)); } public ITrackingRegistrationLocationSelectionSyntax CreateTrackingRegistrationLocationSelector(Type componentType, Func factory) { return new TrackingRegistrationLocationSelector(this, new TrackingLazyComponentRegistration(componentType, factory)); } public IEnumerator> GetEnumerator() { return entries.Select((LazyComponentRegistration e) => e.Factory).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private int IndexOfRegistration(Type registrationType) { for (int i = 0; i < entries.Count; i++) { if (registrationType == entries[i].ComponentType) { return i; } } return -1; } private void EnsureNoDuplicateRegistrationType(Type componentType) { if (IndexOfRegistration(componentType) != -1) { throw new InvalidOperationException("A component of type '" + componentType.FullName + "' has already been registered."); } } private int EnsureRegistrationExists() { int num = IndexOfRegistration(typeof(TRegistrationType)); if (num == -1) { throw new InvalidOperationException("A component of type '" + typeof(TRegistrationType).FullName + "' has not been registered."); } return num; } } internal static class LazyComponentRegistrationListExtensions { public static TComponent BuildComponentChain(this LazyComponentRegistrationList registrations, TComponent innerComponent) { return registrations.InReverseOrder.Aggregate(innerComponent, (TComponent inner, Func factory) => factory(inner)); } public static TComponent BuildComponentChain(this LazyComponentRegistrationList registrations, TComponent innerComponent, Func argumentBuilder) { Func argumentBuilder2 = argumentBuilder; return registrations.InReverseOrder.Aggregate(innerComponent, (TComponent inner, Func factory) => factory(argumentBuilder2(inner))); } public static List BuildComponentList(this LazyComponentRegistrationList registrations) { return registrations.Select((Func factory) => factory(default(Nothing))).ToList(); } public static List BuildComponentList(this LazyComponentRegistrationList registrations, TArgument argument) { TArgument argument2 = argument; return registrations.Select((Func factory) => factory(argument2)).ToList(); } } [StructLayout(LayoutKind.Sequential, Size = 1)] internal struct Nothing { } internal sealed class ObjectDescriptor : IObjectDescriptor { public object? Value { get; private set; } public Type Type { get; private set; } public Type StaticType { get; private set; } public ScalarStyle ScalarStyle { get; private set; } public ObjectDescriptor(object? value, Type type, Type staticType) : this(value, type, staticType, ScalarStyle.Any) { } public ObjectDescriptor(object? value, Type type, Type staticType, ScalarStyle scalarStyle) { Value = value; Type = type ?? throw new ArgumentNullException("type"); StaticType = staticType ?? throw new ArgumentNullException("staticType"); ScalarStyle = scalarStyle; } } internal delegate IObjectGraphTraversalStrategy ObjectGraphTraversalStrategyFactory(ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable typeConverters, int maximumRecursion); internal sealed class PropertyDescriptor : IPropertyDescriptor { private readonly IPropertyDescriptor baseDescriptor; public string Name { get; set; } public Type Type => baseDescriptor.Type; public Type? TypeOverride { get { return baseDescriptor.TypeOverride; } set { baseDescriptor.TypeOverride = value; } } public int Order { get; set; } public ScalarStyle ScalarStyle { get { return baseDescriptor.ScalarStyle; } set { baseDescriptor.ScalarStyle = value; } } public bool CanWrite => baseDescriptor.CanWrite; public PropertyDescriptor(IPropertyDescriptor baseDescriptor) { this.baseDescriptor = baseDescriptor; Name = baseDescriptor.Name; } public void Write(object target, object? value) { baseDescriptor.Write(target, value); } public T? GetCustomAttribute() where T : Attribute { return baseDescriptor.GetCustomAttribute(); } public IObjectDescriptor Read(object target) { return baseDescriptor.Read(target); } } internal sealed class Serializer : ISerializer { private readonly IValueSerializer valueSerializer; private readonly EmitterSettings emitterSettings; public Serializer() : this(new SerializerBuilder().BuildValueSerializer(), EmitterSettings.Default) { } private Serializer(IValueSerializer valueSerializer, EmitterSettings emitterSettings) { this.valueSerializer = valueSerializer ?? throw new ArgumentNullException("valueSerializer"); this.emitterSettings = emitterSettings ?? throw new ArgumentNullException("emitterSettings"); } public static Serializer FromValueSerializer(IValueSerializer valueSerializer, EmitterSettings emitterSettings) { return new Serializer(valueSerializer, emitterSettings); } public void Serialize(TextWriter writer, object? graph) { Serialize(new Emitter(writer, emitterSettings), graph); } public string Serialize(object? graph) { using StringWriter stringWriter = new StringWriter(); Serialize(stringWriter, graph); return stringWriter.ToString(); } public void Serialize(TextWriter writer, object? graph, Type type) { Serialize(new Emitter(writer, emitterSettings), graph, type); } public void Serialize(IEmitter emitter, object? graph) { if (emitter == null) { throw new ArgumentNullException("emitter"); } EmitDocument(emitter, graph, null); } public void Serialize(IEmitter emitter, object? graph, Type type) { if (emitter == null) { throw new ArgumentNullException("emitter"); } if (type == null) { throw new ArgumentNullException("type"); } EmitDocument(emitter, graph, type); } private void EmitDocument(IEmitter emitter, object? graph, Type? type) { emitter.Emit(new YamlDotNet.Core.Events.StreamStart()); emitter.Emit(new YamlDotNet.Core.Events.DocumentStart()); valueSerializer.SerializeValue(emitter, graph, type); emitter.Emit(new YamlDotNet.Core.Events.DocumentEnd(isImplicit: true)); emitter.Emit(new YamlDotNet.Core.Events.StreamEnd()); } } internal sealed class SerializerBuilder : BuilderSkeleton { private class ValueSerializer : IValueSerializer { private readonly IObjectGraphTraversalStrategy traversalStrategy; private readonly IEventEmitter eventEmitter; private readonly IEnumerable typeConverters; private readonly LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories; public ValueSerializer(IObjectGraphTraversalStrategy traversalStrategy, IEventEmitter eventEmitter, IEnumerable typeConverters, LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories, LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories) { this.traversalStrategy = traversalStrategy; this.eventEmitter = eventEmitter; this.typeConverters = typeConverters; this.preProcessingPhaseObjectGraphVisitorFactories = preProcessingPhaseObjectGraphVisitorFactories; this.emissionPhaseObjectGraphVisitorFactories = emissionPhaseObjectGraphVisitorFactories; } public void SerializeValue(IEmitter emitter, object? value, Type? type) { IEmitter emitter2 = emitter; Type type2 = type ?? ((value != null) ? value.GetType() : typeof(object)); Type staticType = type ?? typeof(object); ObjectDescriptor graph = new ObjectDescriptor(value, type2, staticType); List> preProcessingPhaseObjectGraphVisitors = preProcessingPhaseObjectGraphVisitorFactories.BuildComponentList(typeConverters); foreach (IObjectGraphVisitor item in preProcessingPhaseObjectGraphVisitors) { traversalStrategy.Traverse(graph, item, default(Nothing)); } IObjectGraphVisitor visitor = emissionPhaseObjectGraphVisitorFactories.BuildComponentChain>(new EmittingObjectGraphVisitor(eventEmitter), (IObjectGraphVisitor inner) => new EmissionPhaseObjectGraphVisitorArgs(inner, eventEmitter, preProcessingPhaseObjectGraphVisitors, typeConverters, NestedObjectSerializer)); traversalStrategy.Traverse(graph, visitor, emitter2); void NestedObjectSerializer(object? v, Type? t) { SerializeValue(emitter2, v, t); } } } private ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory; private readonly LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList eventEmitterFactories; private readonly IDictionary tagMappings = new Dictionary(); private readonly IObjectFactory objectFactory; private int maximumRecursion = 50; private EmitterSettings emitterSettings = EmitterSettings.Default; private DefaultValuesHandling defaultValuesHandlingConfiguration; private bool quoteNecessaryStrings; private bool quoteYaml1_1Strings; protected override SerializerBuilder Self => this; public SerializerBuilder() : base((ITypeResolver)new DynamicTypeResolver()) { typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner)); typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner); typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner)); typeInspectorFactories.Add(typeof(YamlAttributeOverridesInspector), (ITypeInspector inner) => (overrides == null) ? inner : new YamlAttributeOverridesInspector(inner, overrides.Clone())); preProcessingPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList, IObjectGraphVisitor> { { typeof(AnchorAssigner), (IEnumerable typeConverters) => new AnchorAssigner(typeConverters) } }; emissionPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList> { { typeof(CustomSerializationObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new CustomSerializationObjectGraphVisitor(args.InnerVisitor, args.TypeConverters, args.NestedObjectSerializer) }, { typeof(AnchorAssigningObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new AnchorAssigningObjectGraphVisitor(args.InnerVisitor, args.EventEmitter, args.GetPreProcessingPhaseObjectGraphVisitor()) }, { typeof(DefaultValuesObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new DefaultValuesObjectGraphVisitor(defaultValuesHandlingConfiguration, args.InnerVisitor, new DefaultObjectFactory()) }, { typeof(CommentsObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new CommentsObjectGraphVisitor(args.InnerVisitor) } }; eventEmitterFactories = new LazyComponentRegistrationList { { typeof(TypeAssigningEventEmitter), (IEventEmitter inner) => new TypeAssigningEventEmitter(inner, requireTagWhenStaticAndActualTypesAreDifferent: false, tagMappings, quoteNecessaryStrings, quoteYaml1_1Strings) } }; objectFactory = new DefaultObjectFactory(); objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable typeConverters, int maximumRecursion) => new FullObjectGraphTraversalStrategy(typeInspector, typeResolver, maximumRecursion, namingConvention, objectFactory); } public SerializerBuilder WithQuotingNecessaryStrings(bool quoteYaml1_1Strings = false) { quoteNecessaryStrings = true; this.quoteYaml1_1Strings = quoteYaml1_1Strings; return this; } public SerializerBuilder WithMaximumRecursion(int maximumRecursion) { if (maximumRecursion <= 0) { throw new ArgumentOutOfRangeException("maximumRecursion", $"The maximum recursion specified ({maximumRecursion}) is invalid. It should be a positive integer."); } this.maximumRecursion = maximumRecursion; return this; } public SerializerBuilder WithEventEmitter(Func eventEmitterFactory) where TEventEmitter : IEventEmitter { return WithEventEmitter(eventEmitterFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public SerializerBuilder WithEventEmitter(Func eventEmitterFactory, Action> where) where TEventEmitter : IEventEmitter { Func eventEmitterFactory2 = eventEmitterFactory; if (eventEmitterFactory2 == null) { throw new ArgumentNullException("eventEmitterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(eventEmitterFactories.CreateRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter inner) => eventEmitterFactory2(inner))); return Self; } public SerializerBuilder WithEventEmitter(WrapperFactory eventEmitterFactory, Action> where) where TEventEmitter : IEventEmitter { WrapperFactory eventEmitterFactory2 = eventEmitterFactory; if (eventEmitterFactory2 == null) { throw new ArgumentNullException("eventEmitterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(eventEmitterFactories.CreateTrackingRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter wrapped, IEventEmitter inner) => eventEmitterFactory2(wrapped, inner))); return Self; } public SerializerBuilder WithoutEventEmitter() where TEventEmitter : IEventEmitter { return WithoutEventEmitter(typeof(TEventEmitter)); } public SerializerBuilder WithoutEventEmitter(Type eventEmitterType) { if (eventEmitterType == null) { throw new ArgumentNullException("eventEmitterType"); } eventEmitterFactories.Remove(eventEmitterType); return this; } public override SerializerBuilder WithTagMapping(TagName tag, Type type) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (type == null) { throw new ArgumentNullException("type"); } if (tagMappings.TryGetValue(type, out var value)) { throw new ArgumentException($"Type already has a registered tag '{value}' for type '{type.FullName}'", "type"); } tagMappings.Add(type, tag); return this; } public SerializerBuilder WithoutTagMapping(Type type) { if (type == null) { throw new ArgumentNullException("type"); } if (!tagMappings.Remove(type)) { throw new KeyNotFoundException("Tag for type '" + type.FullName + "' is not registered"); } return this; } public SerializerBuilder EnsureRoundtrip() { objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable typeConverters, int maximumRecursion) => new RoundtripObjectGraphTraversalStrategy(typeConverters, typeInspector, typeResolver, maximumRecursion, namingConvention, settings, objectFactory); WithEventEmitter((IEventEmitter inner) => new TypeAssigningEventEmitter(inner, requireTagWhenStaticAndActualTypesAreDifferent: true, tagMappings, quoteNecessaryStrings, quoteYaml1_1Strings), delegate(IRegistrationLocationSelectionSyntax loc) { loc.InsteadOf(); }); return WithTypeInspector((ITypeInspector inner) => new ReadableAndWritablePropertiesTypeInspector(inner), delegate(IRegistrationLocationSelectionSyntax loc) { loc.OnBottom(); }); } public SerializerBuilder DisableAliases() { preProcessingPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigner)); emissionPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigningObjectGraphVisitor)); return this; } [Obsolete("The default behavior is now to always emit default values, thefore calling this method has no effect. This behavior is now controlled by ConfigureDefaultValuesHandling.", true)] public SerializerBuilder EmitDefaults() { return ConfigureDefaultValuesHandling(DefaultValuesHandling.Preserve); } public SerializerBuilder ConfigureDefaultValuesHandling(DefaultValuesHandling configuration) { defaultValuesHandlingConfiguration = configuration; return this; } public SerializerBuilder JsonCompatible() { emitterSettings = emitterSettings.WithMaxSimpleKeyLength(int.MaxValue).WithoutAnchorName(); return WithTypeConverter(new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: true), delegate(IRegistrationLocationSelectionSyntax w) { w.InsteadOf(); }).WithTypeConverter(new YamlDotNet.Serialization.Converters.DateTimeConverter(DateTimeKind.Utc, null, true)).WithEventEmitter((IEventEmitter inner) => new JsonEventEmitter(inner), delegate(IRegistrationLocationSelectionSyntax loc) { loc.InsteadOf(); }); } public SerializerBuilder WithNewLine(string newLine) { emitterSettings = emitterSettings.WithNewLine(newLine); return this; } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(TObjectGraphVisitor objectGraphVisitor) where TObjectGraphVisitor : IObjectGraphVisitor { return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitor, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(TObjectGraphVisitor objectGraphVisitor, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { TObjectGraphVisitor objectGraphVisitor2 = objectGraphVisitor; if (objectGraphVisitor2 == null) { throw new ArgumentNullException("objectGraphVisitor"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable _) => objectGraphVisitor2)); return this; } public SerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory2 = objectGraphVisitorFactory; if (objectGraphVisitorFactory2 == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor wrapped, IEnumerable _) => objectGraphVisitorFactory2(wrapped))); return this; } public SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor() where TObjectGraphVisitor : IObjectGraphVisitor { return WithoutPreProcessingPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public SerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if (objectGraphVisitorType == null) { throw new ArgumentNullException("objectGraphVisitorType"); } preProcessingPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); return this; } public SerializerBuilder WithObjectGraphTraversalStrategyFactory(ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory) { this.objectGraphTraversalStrategyFactory = objectGraphTraversalStrategyFactory; return this; } public SerializerBuilder WithEmissionPhaseObjectGraphVisitor(Func objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor { return WithEmissionPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public SerializerBuilder WithEmissionPhaseObjectGraphVisitor(Func objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { Func objectGraphVisitorFactory2 = objectGraphVisitorFactory; if (objectGraphVisitorFactory2 == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory2(args))); return this; } public SerializerBuilder WithEmissionPhaseObjectGraphVisitor(WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory2 = objectGraphVisitorFactory; if (objectGraphVisitorFactory2 == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor wrapped, EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory2(wrapped, args))); return this; } public SerializerBuilder WithoutEmissionPhaseObjectGraphVisitor() where TObjectGraphVisitor : IObjectGraphVisitor { return WithoutEmissionPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public SerializerBuilder WithoutEmissionPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if (objectGraphVisitorType == null) { throw new ArgumentNullException("objectGraphVisitorType"); } emissionPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); return this; } public SerializerBuilder WithIndentedSequences() { emitterSettings = emitterSettings.WithIndentedSequences(); return this; } public ISerializer Build() { return Serializer.FromValueSerializer(BuildValueSerializer(), emitterSettings); } public IValueSerializer BuildValueSerializer() { IEnumerable typeConverters = BuildTypeConverters(); ITypeInspector typeInspector = BuildTypeInspector(); IObjectGraphTraversalStrategy traversalStrategy = objectGraphTraversalStrategyFactory(typeInspector, typeResolver, typeConverters, maximumRecursion); IEventEmitter eventEmitter = eventEmitterFactories.BuildComponentChain(new WriterEventEmitter()); return new ValueSerializer(traversalStrategy, eventEmitter, typeConverters, preProcessingPhaseObjectGraphVisitorFactories.Clone(), emissionPhaseObjectGraphVisitorFactories.Clone()); } internal ITypeInspector BuildTypeInspector() { ITypeInspector typeInspector = new ReadablePropertiesTypeInspector(typeResolver, includeNonPublicProperties); if (!ignoreFields) { typeInspector = new CompositeTypeInspector(new ReadableFieldsTypeInspector(typeResolver), typeInspector); } return typeInspectorFactories.BuildComponentChain(typeInspector); } } internal class Settings { public bool AllowPrivateConstructors { get; set; } } internal abstract class StaticBuilderSkeleton where TBuilder : StaticBuilderSkeleton { internal INamingConvention namingConvention = NullNamingConvention.Instance; internal ITypeResolver typeResolver; internal readonly LazyComponentRegistrationList typeConverterFactories; internal readonly LazyComponentRegistrationList typeInspectorFactories; internal bool includeNonPublicProperties; internal Settings settings; protected abstract TBuilder Self { get; } internal StaticBuilderSkeleton(ITypeResolver typeResolver) { typeConverterFactories = new LazyComponentRegistrationList { { typeof(YamlDotNet.Serialization.Converters.GuidConverter), (Nothing _) => new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: false) } }; typeInspectorFactories = new LazyComponentRegistrationList(); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); settings = new Settings(); } public TBuilder WithNamingConvention(INamingConvention namingConvention) { this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention"); return Self; } public TBuilder WithTypeResolver(ITypeResolver typeResolver) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); return Self; } public abstract TBuilder WithTagMapping(TagName tag, Type type); public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter) { return WithTypeConverter(typeConverter, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public TBuilder WithTypeConverter(IYamlTypeConverter typeConverter, Action> where) { IYamlTypeConverter typeConverter2 = typeConverter; if (typeConverter2 == null) { throw new ArgumentNullException("typeConverter"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateRegistrationLocationSelector(typeConverter2.GetType(), (Nothing _) => typeConverter2)); return Self; } public TBuilder WithTypeConverter(WrapperFactory typeConverterFactory, Action> where) where TYamlTypeConverter : IYamlTypeConverter { WrapperFactory typeConverterFactory2 = typeConverterFactory; if (typeConverterFactory2 == null) { throw new ArgumentNullException("typeConverterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeConverterFactories.CreateTrackingRegistrationLocationSelector(typeof(TYamlTypeConverter), (IYamlTypeConverter wrapped, Nothing _) => typeConverterFactory2(wrapped))); return Self; } public TBuilder WithoutTypeConverter() where TYamlTypeConverter : IYamlTypeConverter { return WithoutTypeConverter(typeof(TYamlTypeConverter)); } public TBuilder WithoutTypeConverter(Type converterType) { if (converterType == null) { throw new ArgumentNullException("converterType"); } typeConverterFactories.Remove(converterType); return Self; } public TBuilder WithTypeInspector(Func typeInspectorFactory) where TTypeInspector : ITypeInspector { return WithTypeInspector(typeInspectorFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public TBuilder WithTypeInspector(Func typeInspectorFactory, Action> where) where TTypeInspector : ITypeInspector { Func typeInspectorFactory2 = typeInspectorFactory; if (typeInspectorFactory2 == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector inner) => typeInspectorFactory2(inner))); return Self; } public TBuilder WithTypeInspector(WrapperFactory typeInspectorFactory, Action> where) where TTypeInspector : ITypeInspector { WrapperFactory typeInspectorFactory2 = typeInspectorFactory; if (typeInspectorFactory2 == null) { throw new ArgumentNullException("typeInspectorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(typeInspectorFactories.CreateTrackingRegistrationLocationSelector(typeof(TTypeInspector), (ITypeInspector wrapped, ITypeInspector inner) => typeInspectorFactory2(wrapped, inner))); return Self; } public TBuilder WithoutTypeInspector() where TTypeInspector : ITypeInspector { return WithoutTypeInspector(typeof(TTypeInspector)); } public TBuilder WithoutTypeInspector(Type inspectorType) { if (inspectorType == null) { throw new ArgumentNullException("inspectorType"); } typeInspectorFactories.Remove(inspectorType); return Self; } protected IEnumerable BuildTypeConverters() { return typeConverterFactories.BuildComponentList(); } } internal abstract class StaticContext { public virtual StaticObjectFactory GetFactory() { throw new NotImplementedException(); } public virtual ITypeInspector GetTypeInspector() { throw new NotImplementedException(); } } internal sealed class StaticDeserializerBuilder : StaticBuilderSkeleton { private readonly StaticContext context; private readonly StaticObjectFactory factory; private readonly LazyComponentRegistrationList nodeDeserializerFactories; private readonly LazyComponentRegistrationList nodeTypeResolverFactories; private readonly Dictionary tagMappings; private readonly ITypeConverter typeConverter; private readonly Dictionary typeMappings; private bool ignoreUnmatched; private bool duplicateKeyChecking; private bool attemptUnknownTypeDeserialization; protected override StaticDeserializerBuilder Self => this; public StaticDeserializerBuilder(StaticContext context) : base((ITypeResolver)new StaticTypeResolver()) { this.context = context; factory = context.GetFactory(); typeMappings = new Dictionary(); tagMappings = new Dictionary { { FailsafeSchema.Tags.Map, typeof(Dictionary) }, { FailsafeSchema.Tags.Str, typeof(string) }, { JsonSchema.Tags.Bool, typeof(bool) }, { JsonSchema.Tags.Float, typeof(double) }, { JsonSchema.Tags.Int, typeof(int) }, { DefaultSchema.Tags.Timestamp, typeof(DateTime) } }; typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner)); typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner); typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner)); nodeDeserializerFactories = new LazyComponentRegistrationList { { typeof(YamlConvertibleNodeDeserializer), (Nothing _) => new YamlConvertibleNodeDeserializer(factory) }, { typeof(YamlSerializableNodeDeserializer), (Nothing _) => new YamlSerializableNodeDeserializer(factory) }, { typeof(TypeConverterNodeDeserializer), (Nothing _) => new TypeConverterNodeDeserializer(BuildTypeConverters()) }, { typeof(NullNodeDeserializer), (Nothing _) => new NullNodeDeserializer() }, { typeof(ScalarNodeDeserializer), (Nothing _) => new ScalarNodeDeserializer(attemptUnknownTypeDeserialization, typeConverter) }, { typeof(StaticArrayNodeDeserializer), (Nothing _) => new StaticArrayNodeDeserializer(factory) }, { typeof(StaticDictionaryNodeDeserializer), (Nothing _) => new StaticDictionaryNodeDeserializer(factory, duplicateKeyChecking) }, { typeof(StaticCollectionNodeDeserializer), (Nothing _) => new StaticCollectionNodeDeserializer(factory) }, { typeof(ObjectNodeDeserializer), (Nothing _) => new ObjectNodeDeserializer(factory, BuildTypeInspector(), ignoreUnmatched, duplicateKeyChecking, typeConverter) } }; nodeTypeResolverFactories = new LazyComponentRegistrationList { { typeof(MappingNodeTypeResolver), (Nothing _) => new MappingNodeTypeResolver(typeMappings) }, { typeof(YamlConvertibleTypeResolver), (Nothing _) => new YamlConvertibleTypeResolver() }, { typeof(YamlSerializableTypeResolver), (Nothing _) => new YamlSerializableTypeResolver() }, { typeof(TagNodeTypeResolver), (Nothing _) => new TagNodeTypeResolver(tagMappings) }, { typeof(PreventUnknownTagsNodeTypeResolver), (Nothing _) => new PreventUnknownTagsNodeTypeResolver() }, { typeof(DefaultContainersNodeTypeResolver), (Nothing _) => new DefaultContainersNodeTypeResolver() } }; typeConverter = new NullTypeConverter(); } internal ITypeInspector BuildTypeInspector() { ITypeInspector typeInspector = context.GetTypeInspector(); return typeInspectorFactories.BuildComponentChain(typeInspector); } public StaticDeserializerBuilder WithAttemptingUnquotedStringTypeDeserialization() { attemptUnknownTypeDeserialization = true; return this; } public StaticDeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer) { return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public StaticDeserializerBuilder WithNodeDeserializer(INodeDeserializer nodeDeserializer, Action> where) { INodeDeserializer nodeDeserializer2 = nodeDeserializer; if (nodeDeserializer2 == null) { throw new ArgumentNullException("nodeDeserializer"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateRegistrationLocationSelector(nodeDeserializer2.GetType(), (Nothing _) => nodeDeserializer2)); return this; } public StaticDeserializerBuilder WithNodeDeserializer(WrapperFactory nodeDeserializerFactory, Action> where) where TNodeDeserializer : INodeDeserializer { WrapperFactory nodeDeserializerFactory2 = nodeDeserializerFactory; if (nodeDeserializerFactory2 == null) { throw new ArgumentNullException("nodeDeserializerFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeDeserializerFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeDeserializer), (INodeDeserializer wrapped, Nothing _) => nodeDeserializerFactory2(wrapped))); return this; } public StaticDeserializerBuilder WithoutNodeDeserializer() where TNodeDeserializer : INodeDeserializer { return WithoutNodeDeserializer(typeof(TNodeDeserializer)); } public StaticDeserializerBuilder WithoutNodeDeserializer(Type nodeDeserializerType) { if (nodeDeserializerType == null) { throw new ArgumentNullException("nodeDeserializerType"); } nodeDeserializerFactories.Remove(nodeDeserializerType); return this; } public StaticDeserializerBuilder WithTypeDiscriminatingNodeDeserializer(Action configureTypeDiscriminatingNodeDeserializerOptions, int maxDepth = -1, int maxLength = -1) { TypeDiscriminatingNodeDeserializerOptions typeDiscriminatingNodeDeserializerOptions = new TypeDiscriminatingNodeDeserializerOptions(); configureTypeDiscriminatingNodeDeserializerOptions(typeDiscriminatingNodeDeserializerOptions); TypeDiscriminatingNodeDeserializer nodeDeserializer = new TypeDiscriminatingNodeDeserializer(nodeDeserializerFactories.BuildComponentList(), typeDiscriminatingNodeDeserializerOptions.discriminators, maxDepth, maxLength); return WithNodeDeserializer(nodeDeserializer, delegate(IRegistrationLocationSelectionSyntax s) { s.Before(); }); } public StaticDeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver) { return WithNodeTypeResolver(nodeTypeResolver, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public StaticDeserializerBuilder WithNodeTypeResolver(INodeTypeResolver nodeTypeResolver, Action> where) { INodeTypeResolver nodeTypeResolver2 = nodeTypeResolver; if (nodeTypeResolver2 == null) { throw new ArgumentNullException("nodeTypeResolver"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateRegistrationLocationSelector(nodeTypeResolver2.GetType(), (Nothing _) => nodeTypeResolver2)); return this; } public StaticDeserializerBuilder WithNodeTypeResolver(WrapperFactory nodeTypeResolverFactory, Action> where) where TNodeTypeResolver : INodeTypeResolver { WrapperFactory nodeTypeResolverFactory2 = nodeTypeResolverFactory; if (nodeTypeResolverFactory2 == null) { throw new ArgumentNullException("nodeTypeResolverFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(nodeTypeResolverFactories.CreateTrackingRegistrationLocationSelector(typeof(TNodeTypeResolver), (INodeTypeResolver wrapped, Nothing _) => nodeTypeResolverFactory2(wrapped))); return this; } public StaticDeserializerBuilder WithoutNodeTypeResolver() where TNodeTypeResolver : INodeTypeResolver { return WithoutNodeTypeResolver(typeof(TNodeTypeResolver)); } public StaticDeserializerBuilder WithoutNodeTypeResolver(Type nodeTypeResolverType) { if (nodeTypeResolverType == null) { throw new ArgumentNullException("nodeTypeResolverType"); } nodeTypeResolverFactories.Remove(nodeTypeResolverType); return this; } public override StaticDeserializerBuilder WithTagMapping(TagName tag, Type type) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (type == null) { throw new ArgumentNullException("type"); } if (tagMappings.TryGetValue(tag, out Type value)) { throw new ArgumentException($"Type already has a registered type '{value.FullName}' for tag '{tag}'", "tag"); } tagMappings.Add(tag, type); return this; } public StaticDeserializerBuilder WithTypeMapping() where TConcrete : TInterface { Type typeFromHandle = typeof(TInterface); Type typeFromHandle2 = typeof(TConcrete); if (!typeFromHandle.IsAssignableFrom(typeFromHandle2)) { throw new InvalidOperationException("The type '" + typeFromHandle2.Name + "' does not implement interface '" + typeFromHandle.Name + "'."); } if (typeMappings.ContainsKey(typeFromHandle)) { typeMappings[typeFromHandle] = typeFromHandle2; } else { typeMappings.Add(typeFromHandle, typeFromHandle2); } return this; } public StaticDeserializerBuilder WithoutTagMapping(TagName tag) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (!tagMappings.Remove(tag)) { throw new KeyNotFoundException($"Tag '{tag}' is not registered"); } return this; } public StaticDeserializerBuilder IgnoreUnmatchedProperties() { ignoreUnmatched = true; return this; } public StaticDeserializerBuilder WithDuplicateKeyChecking() { duplicateKeyChecking = true; return this; } public IDeserializer Build() { return Deserializer.FromValueDeserializer(BuildValueDeserializer()); } public IValueDeserializer BuildValueDeserializer() { return new AliasValueDeserializer(new NodeValueDeserializer(nodeDeserializerFactories.BuildComponentList(), nodeTypeResolverFactories.BuildComponentList(), typeConverter)); } } internal sealed class StaticSerializerBuilder : StaticBuilderSkeleton { private class ValueSerializer : IValueSerializer { private readonly IObjectGraphTraversalStrategy traversalStrategy; private readonly IEventEmitter eventEmitter; private readonly IEnumerable typeConverters; private readonly LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories; public ValueSerializer(IObjectGraphTraversalStrategy traversalStrategy, IEventEmitter eventEmitter, IEnumerable typeConverters, LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories, LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories) { this.traversalStrategy = traversalStrategy; this.eventEmitter = eventEmitter; this.typeConverters = typeConverters; this.preProcessingPhaseObjectGraphVisitorFactories = preProcessingPhaseObjectGraphVisitorFactories; this.emissionPhaseObjectGraphVisitorFactories = emissionPhaseObjectGraphVisitorFactories; } public void SerializeValue(IEmitter emitter, object? value, Type? type) { IEmitter emitter2 = emitter; Type type2 = type ?? ((value != null) ? value.GetType() : typeof(object)); Type staticType = type ?? typeof(object); ObjectDescriptor graph = new ObjectDescriptor(value, type2, staticType); List> preProcessingPhaseObjectGraphVisitors = preProcessingPhaseObjectGraphVisitorFactories.BuildComponentList(typeConverters); foreach (IObjectGraphVisitor item in preProcessingPhaseObjectGraphVisitors) { traversalStrategy.Traverse(graph, item, default(Nothing)); } IObjectGraphVisitor visitor = emissionPhaseObjectGraphVisitorFactories.BuildComponentChain>(new EmittingObjectGraphVisitor(eventEmitter), (IObjectGraphVisitor inner) => new EmissionPhaseObjectGraphVisitorArgs(inner, eventEmitter, preProcessingPhaseObjectGraphVisitors, typeConverters, NestedObjectSerializer)); traversalStrategy.Traverse(graph, visitor, emitter2); void NestedObjectSerializer(object? v, Type? t) { SerializeValue(emitter2, v, t); } } } private readonly StaticContext context; private readonly StaticObjectFactory factory; private ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory; private readonly LazyComponentRegistrationList, IObjectGraphVisitor> preProcessingPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList> emissionPhaseObjectGraphVisitorFactories; private readonly LazyComponentRegistrationList eventEmitterFactories; private readonly IDictionary tagMappings = new Dictionary(); private int maximumRecursion = 50; private EmitterSettings emitterSettings = EmitterSettings.Default; private DefaultValuesHandling defaultValuesHandlingConfiguration; private bool quoteNecessaryStrings; protected override StaticSerializerBuilder Self => this; public StaticSerializerBuilder(StaticContext context) : base((ITypeResolver)new DynamicTypeResolver()) { this.context = context; factory = context.GetFactory(); typeInspectorFactories.Add(typeof(CachedTypeInspector), (ITypeInspector inner) => new CachedTypeInspector(inner)); typeInspectorFactories.Add(typeof(NamingConventionTypeInspector), (ITypeInspector inner) => (!(namingConvention is NullNamingConvention)) ? new NamingConventionTypeInspector(inner, namingConvention) : inner); typeInspectorFactories.Add(typeof(YamlAttributesTypeInspector), (ITypeInspector inner) => new YamlAttributesTypeInspector(inner)); preProcessingPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList, IObjectGraphVisitor> { { typeof(AnchorAssigner), (IEnumerable typeConverters) => new AnchorAssigner(typeConverters) } }; emissionPhaseObjectGraphVisitorFactories = new LazyComponentRegistrationList> { { typeof(CustomSerializationObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new CustomSerializationObjectGraphVisitor(args.InnerVisitor, args.TypeConverters, args.NestedObjectSerializer) }, { typeof(AnchorAssigningObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new AnchorAssigningObjectGraphVisitor(args.InnerVisitor, args.EventEmitter, args.GetPreProcessingPhaseObjectGraphVisitor()) }, { typeof(DefaultValuesObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new DefaultValuesObjectGraphVisitor(defaultValuesHandlingConfiguration, args.InnerVisitor, factory) }, { typeof(CommentsObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => new CommentsObjectGraphVisitor(args.InnerVisitor) } }; eventEmitterFactories = new LazyComponentRegistrationList { { typeof(TypeAssigningEventEmitter), (IEventEmitter inner) => new TypeAssigningEventEmitter(inner, requireTagWhenStaticAndActualTypesAreDifferent: false, tagMappings, quoteNecessaryStrings) } }; objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable typeConverters, int maximumRecursion) => new FullObjectGraphTraversalStrategy(typeInspector, typeResolver, maximumRecursion, namingConvention, factory); } public StaticSerializerBuilder WithQuotingNecessaryStrings() { quoteNecessaryStrings = true; return this; } public StaticSerializerBuilder WithMaximumRecursion(int maximumRecursion) { if (maximumRecursion <= 0) { throw new ArgumentOutOfRangeException("maximumRecursion", $"The maximum recursion specified ({maximumRecursion}) is invalid. It should be a positive integer."); } this.maximumRecursion = maximumRecursion; return this; } public StaticSerializerBuilder WithEventEmitter(Func eventEmitterFactory) where TEventEmitter : IEventEmitter { return WithEventEmitter(eventEmitterFactory, delegate(IRegistrationLocationSelectionSyntax w) { w.OnTop(); }); } public StaticSerializerBuilder WithEventEmitter(Func eventEmitterFactory, Action> where) where TEventEmitter : IEventEmitter { Func eventEmitterFactory2 = eventEmitterFactory; if (eventEmitterFactory2 == null) { throw new ArgumentNullException("eventEmitterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(eventEmitterFactories.CreateRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter inner) => eventEmitterFactory2(inner))); return Self; } public StaticSerializerBuilder WithEventEmitter(WrapperFactory eventEmitterFactory, Action> where) where TEventEmitter : IEventEmitter { WrapperFactory eventEmitterFactory2 = eventEmitterFactory; if (eventEmitterFactory2 == null) { throw new ArgumentNullException("eventEmitterFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(eventEmitterFactories.CreateTrackingRegistrationLocationSelector(typeof(TEventEmitter), (IEventEmitter wrapped, IEventEmitter inner) => eventEmitterFactory2(wrapped, inner))); return Self; } public StaticSerializerBuilder WithoutEventEmitter() where TEventEmitter : IEventEmitter { return WithoutEventEmitter(typeof(TEventEmitter)); } public StaticSerializerBuilder WithoutEventEmitter(Type eventEmitterType) { if (eventEmitterType == null) { throw new ArgumentNullException("eventEmitterType"); } eventEmitterFactories.Remove(eventEmitterType); return this; } public override StaticSerializerBuilder WithTagMapping(TagName tag, Type type) { if (tag.IsEmpty) { throw new ArgumentException("Non-specific tags cannot be maped"); } if (type == null) { throw new ArgumentNullException("type"); } if (tagMappings.TryGetValue(type, out var value)) { throw new ArgumentException($"Type already has a registered tag '{value}' for type '{type.FullName}'", "type"); } tagMappings.Add(type, tag); return this; } public StaticSerializerBuilder WithoutTagMapping(Type type) { if (type == null) { throw new ArgumentNullException("type"); } if (!tagMappings.Remove(type)) { throw new KeyNotFoundException("Tag for type '" + type.FullName + "' is not registered"); } return this; } public StaticSerializerBuilder EnsureRoundtrip() { objectGraphTraversalStrategyFactory = (ITypeInspector typeInspector, ITypeResolver typeResolver, IEnumerable typeConverters, int maximumRecursion) => new RoundtripObjectGraphTraversalStrategy(typeConverters, typeInspector, typeResolver, maximumRecursion, namingConvention, settings, factory); WithEventEmitter((IEventEmitter inner) => new TypeAssigningEventEmitter(inner, requireTagWhenStaticAndActualTypesAreDifferent: true, tagMappings, quoteNecessaryStrings), delegate(IRegistrationLocationSelectionSyntax loc) { loc.InsteadOf(); }); return WithTypeInspector((ITypeInspector inner) => new ReadableAndWritablePropertiesTypeInspector(inner), delegate(IRegistrationLocationSelectionSyntax loc) { loc.OnBottom(); }); } public StaticSerializerBuilder DisableAliases() { preProcessingPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigner)); emissionPhaseObjectGraphVisitorFactories.Remove(typeof(AnchorAssigningObjectGraphVisitor)); return this; } [Obsolete("The default behavior is now to always emit default values, thefore calling this method has no effect. This behavior is now controlled by ConfigureDefaultValuesHandling.", true)] public StaticSerializerBuilder EmitDefaults() { return ConfigureDefaultValuesHandling(DefaultValuesHandling.Preserve); } public StaticSerializerBuilder ConfigureDefaultValuesHandling(DefaultValuesHandling configuration) { defaultValuesHandlingConfiguration = configuration; return this; } public StaticSerializerBuilder JsonCompatible() { emitterSettings = emitterSettings.WithMaxSimpleKeyLength(int.MaxValue).WithoutAnchorName(); return WithTypeConverter(new YamlDotNet.Serialization.Converters.GuidConverter(jsonCompatible: true), delegate(IRegistrationLocationSelectionSyntax w) { w.InsteadOf(); }).WithEventEmitter((IEventEmitter inner) => new JsonEventEmitter(inner), delegate(IRegistrationLocationSelectionSyntax loc) { loc.InsteadOf(); }); } public StaticSerializerBuilder WithNewLine(string newLine) { emitterSettings = emitterSettings.WithNewLine(newLine); return this; } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(TObjectGraphVisitor objectGraphVisitor) where TObjectGraphVisitor : IObjectGraphVisitor { return WithPreProcessingPhaseObjectGraphVisitor(objectGraphVisitor, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(TObjectGraphVisitor objectGraphVisitor, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { TObjectGraphVisitor objectGraphVisitor2 = objectGraphVisitor; if (objectGraphVisitor2 == null) { throw new ArgumentNullException("objectGraphVisitor"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IEnumerable _) => objectGraphVisitor2)); return this; } public StaticSerializerBuilder WithPreProcessingPhaseObjectGraphVisitor(WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory2 = objectGraphVisitorFactory; if (objectGraphVisitorFactory2 == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(preProcessingPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor wrapped, IEnumerable _) => objectGraphVisitorFactory2(wrapped))); return this; } public StaticSerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor() where TObjectGraphVisitor : IObjectGraphVisitor { return WithoutPreProcessingPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public StaticSerializerBuilder WithoutPreProcessingPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if (objectGraphVisitorType == null) { throw new ArgumentNullException("objectGraphVisitorType"); } preProcessingPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); return this; } public StaticSerializerBuilder WithObjectGraphTraversalStrategyFactory(ObjectGraphTraversalStrategyFactory objectGraphTraversalStrategyFactory) { this.objectGraphTraversalStrategyFactory = objectGraphTraversalStrategyFactory; return this; } public StaticSerializerBuilder WithEmissionPhaseObjectGraphVisitor(Func objectGraphVisitorFactory) where TObjectGraphVisitor : IObjectGraphVisitor { return WithEmissionPhaseObjectGraphVisitor(objectGraphVisitorFactory, delegate(IRegistrationLocationSelectionSyntax> w) { w.OnTop(); }); } public StaticSerializerBuilder WithEmissionPhaseObjectGraphVisitor(Func objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { Func objectGraphVisitorFactory2 = objectGraphVisitorFactory; if (objectGraphVisitorFactory2 == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateRegistrationLocationSelector(typeof(TObjectGraphVisitor), (EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory2(args))); return this; } public StaticSerializerBuilder WithEmissionPhaseObjectGraphVisitor(WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory, Action>> where) where TObjectGraphVisitor : IObjectGraphVisitor { WrapperFactory, TObjectGraphVisitor> objectGraphVisitorFactory2 = objectGraphVisitorFactory; if (objectGraphVisitorFactory2 == null) { throw new ArgumentNullException("objectGraphVisitorFactory"); } if (where == null) { throw new ArgumentNullException("where"); } where(emissionPhaseObjectGraphVisitorFactories.CreateTrackingRegistrationLocationSelector(typeof(TObjectGraphVisitor), (IObjectGraphVisitor wrapped, EmissionPhaseObjectGraphVisitorArgs args) => objectGraphVisitorFactory2(wrapped, args))); return this; } public StaticSerializerBuilder WithoutEmissionPhaseObjectGraphVisitor() where TObjectGraphVisitor : IObjectGraphVisitor { return WithoutEmissionPhaseObjectGraphVisitor(typeof(TObjectGraphVisitor)); } public StaticSerializerBuilder WithoutEmissionPhaseObjectGraphVisitor(Type objectGraphVisitorType) { if (objectGraphVisitorType == null) { throw new ArgumentNullException("objectGraphVisitorType"); } emissionPhaseObjectGraphVisitorFactories.Remove(objectGraphVisitorType); return this; } public StaticSerializerBuilder WithIndentedSequences() { emitterSettings = emitterSettings.WithIndentedSequences(); return this; } public ISerializer Build() { return Serializer.FromValueSerializer(BuildValueSerializer(), emitterSettings); } public IValueSerializer BuildValueSerializer() { IEnumerable typeConverters = BuildTypeConverters(); ITypeInspector typeInspector = BuildTypeInspector(); IObjectGraphTraversalStrategy traversalStrategy = objectGraphTraversalStrategyFactory(typeInspector, typeResolver, typeConverters, maximumRecursion); IEventEmitter eventEmitter = eventEmitterFactories.BuildComponentChain(new WriterEventEmitter()); return new ValueSerializer(traversalStrategy, eventEmitter, typeConverters, preProcessingPhaseObjectGraphVisitorFactories.Clone(), emissionPhaseObjectGraphVisitorFactories.Clone()); } internal ITypeInspector BuildTypeInspector() { ITypeInspector typeInspector = context.GetTypeInspector(); return typeInspectorFactories.BuildComponentChain(typeInspector); } } internal sealed class StreamFragment : IYamlConvertible { private readonly List events = new List(); public IList Events => events; void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { events.Clear(); int num = 0; do { if (!parser.MoveNext()) { throw new InvalidOperationException("The parser has reached the end before deserialization completed."); } ParsingEvent current = parser.Current; events.Add(current); num += current.NestingIncrease; } while (num > 0); } void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) { foreach (ParsingEvent @event in events) { emitter.Emit(@event); } } } internal sealed class TagMappings { private readonly IDictionary mappings; public TagMappings() { mappings = new Dictionary(); } public TagMappings(IDictionary mappings) { this.mappings = new Dictionary(mappings); } public void Add(string tag, Type mapping) { mappings.Add(tag, mapping); } internal Type? GetMapping(string tag) { if (!mappings.TryGetValue(tag, out Type value)) { return null; } return value; } } internal sealed class YamlAttributeOverrides { private struct AttributeKey { public readonly Type AttributeType; public readonly string PropertyName; public AttributeKey(Type attributeType, string propertyName) { AttributeType = attributeType; PropertyName = propertyName; } public override bool Equals(object? obj) { if (obj is AttributeKey attributeKey && AttributeType.Equals(attributeKey.AttributeType)) { return PropertyName.Equals(attributeKey.PropertyName); } return false; } public override int GetHashCode() { return YamlDotNet.Core.HashCode.CombineHashCodes(AttributeType.GetHashCode(), PropertyName.GetHashCode()); } } private sealed class AttributeMapping { public readonly Type RegisteredType; public readonly Attribute Attribute; public AttributeMapping(Type registeredType, Attribute attribute) { RegisteredType = registeredType; Attribute = attribute; } public override bool Equals(object? obj) { if (obj is AttributeMapping attributeMapping && RegisteredType.Equals(attributeMapping.RegisteredType)) { return Attribute.Equals(attributeMapping.Attribute); } return false; } public override int GetHashCode() { return YamlDotNet.Core.HashCode.CombineHashCodes(RegisteredType.GetHashCode(), Attribute.GetHashCode()); } public int Matches(Type matchType) { int num = 0; Type type = matchType; while (type != null) { num++; if (type == RegisteredType) { return num; } type = type.BaseType(); } if (matchType.GetInterfaces().Contains(RegisteredType)) { return num; } return 0; } } private readonly Dictionary> overrides = new Dictionary>(); [return: MaybeNull] public T GetAttribute(Type type, string member) where T : Attribute { if (overrides.TryGetValue(new AttributeKey(typeof(T), member), out List value)) { int num = 0; AttributeMapping attributeMapping = null; foreach (AttributeMapping item in value) { int num2 = item.Matches(type); if (num2 > num) { num = num2; attributeMapping = item; } } if (num > 0) { return (T)attributeMapping.Attribute; } } return null; } public void Add(Type type, string member, Attribute attribute) { AttributeMapping item = new AttributeMapping(type, attribute); AttributeKey key = new AttributeKey(attribute.GetType(), member); if (!overrides.TryGetValue(key, out List value)) { value = new List(); overrides.Add(key, value); } else if (value.Contains(item)) { throw new InvalidOperationException($"Attribute ({attribute}) already set for Type {type.FullName}, Member {member}"); } value.Add(item); } public YamlAttributeOverrides Clone() { YamlAttributeOverrides yamlAttributeOverrides = new YamlAttributeOverrides(); foreach (KeyValuePair> @override in overrides) { foreach (AttributeMapping item in @override.Value) { yamlAttributeOverrides.Add(item.RegisteredType, @override.Key.PropertyName, item.Attribute); } } return yamlAttributeOverrides; } public void Add(Expression> propertyAccessor, Attribute attribute) { PropertyInfo propertyInfo = propertyAccessor.AsProperty(); Add(typeof(TClass), propertyInfo.Name, attribute); } } internal sealed class YamlAttributeOverridesInspector : TypeInspectorSkeleton { public sealed class OverridePropertyDescriptor : IPropertyDescriptor { private readonly IPropertyDescriptor baseDescriptor; private readonly YamlAttributeOverrides overrides; private readonly Type classType; public string Name => baseDescriptor.Name; public bool CanWrite => baseDescriptor.CanWrite; public Type Type => baseDescriptor.Type; public Type? TypeOverride { get { return baseDescriptor.TypeOverride; } set { baseDescriptor.TypeOverride = value; } } public int Order { get { return baseDescriptor.Order; } set { baseDescriptor.Order = value; } } public ScalarStyle ScalarStyle { get { return baseDescriptor.ScalarStyle; } set { baseDescriptor.ScalarStyle = value; } } public OverridePropertyDescriptor(IPropertyDescriptor baseDescriptor, YamlAttributeOverrides overrides, Type classType) { this.baseDescriptor = baseDescriptor; this.overrides = overrides; this.classType = classType; } public void Write(object target, object? value) { baseDescriptor.Write(target, value); } public T? GetCustomAttribute() where T : Attribute { return overrides.GetAttribute(classType, Name) ?? baseDescriptor.GetCustomAttribute(); } public IObjectDescriptor Read(object target) { return baseDescriptor.Read(target); } } private readonly ITypeInspector innerTypeDescriptor; private readonly YamlAttributeOverrides overrides; public YamlAttributeOverridesInspector(ITypeInspector innerTypeDescriptor, YamlAttributeOverrides overrides) { this.innerTypeDescriptor = innerTypeDescriptor; this.overrides = overrides; } public override IEnumerable GetProperties(Type type, object? container) { Type type2 = type; IEnumerable enumerable = innerTypeDescriptor.GetProperties(type2, container); if (overrides != null) { enumerable = enumerable.Select((Func)((IPropertyDescriptor p) => new OverridePropertyDescriptor(p, overrides, type2))); } return enumerable; } } internal sealed class YamlAttributesTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; public YamlAttributesTypeInspector(ITypeInspector innerTypeDescriptor) { this.innerTypeDescriptor = innerTypeDescriptor; } public override IEnumerable GetProperties(Type type, object? container) { return from p in (from p in innerTypeDescriptor.GetProperties(type, container) where p.GetCustomAttribute() == null select p).Select((Func)delegate(IPropertyDescriptor p) { PropertyDescriptor propertyDescriptor = new PropertyDescriptor(p); YamlMemberAttribute customAttribute = p.GetCustomAttribute(); if (customAttribute != null) { if (customAttribute.SerializeAs != null) { propertyDescriptor.TypeOverride = customAttribute.SerializeAs; } propertyDescriptor.Order = customAttribute.Order; propertyDescriptor.ScalarStyle = customAttribute.ScalarStyle; if (customAttribute.Alias != null) { propertyDescriptor.Name = customAttribute.Alias; } } return propertyDescriptor; }) orderby p.Order select p; } } internal static class YamlFormatter { public static readonly NumberFormatInfo NumberFormat = new NumberFormatInfo { CurrencyDecimalSeparator = ".", CurrencyGroupSeparator = "_", CurrencyGroupSizes = new int[1] { 3 }, CurrencySymbol = string.Empty, CurrencyDecimalDigits = 99, NumberDecimalSeparator = ".", NumberGroupSeparator = "_", NumberGroupSizes = new int[1] { 3 }, NumberDecimalDigits = 99, NaNSymbol = ".nan", PositiveInfinitySymbol = ".inf", NegativeInfinitySymbol = "-.inf" }; public static string FormatNumber(object number) { return Convert.ToString(number, NumberFormat); } public static string FormatNumber(double number) { return number.ToString("G", NumberFormat); } public static string FormatNumber(float number) { return number.ToString("G", NumberFormat); } public static string FormatBoolean(object boolean) { if (!boolean.Equals(true)) { return "false"; } return "true"; } public static string FormatDateTime(object dateTime) { return ((DateTime)dateTime).ToString("o", CultureInfo.InvariantCulture); } public static string FormatTimeSpan(object timeSpan) { return ((TimeSpan)timeSpan).ToString(); } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] internal sealed class YamlIgnoreAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)] internal sealed class YamlMemberAttribute : Attribute { private DefaultValuesHandling? defaultValuesHandling; public string? Description { get; set; } public Type? SerializeAs { get; set; } public int Order { get; set; } public string? Alias { get; set; } public bool ApplyNamingConventions { get; set; } public ScalarStyle ScalarStyle { get; set; } public DefaultValuesHandling DefaultValuesHandling { get { return defaultValuesHandling.GetValueOrDefault(); } set { defaultValuesHandling = value; } } public bool IsDefaultValuesHandlingSpecified => defaultValuesHandling.HasValue; public YamlMemberAttribute() { ScalarStyle = ScalarStyle.Any; ApplyNamingConventions = true; } public YamlMemberAttribute(Type serializeAs) : this() { SerializeAs = serializeAs ?? throw new ArgumentNullException("serializeAs"); } } [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)] internal sealed class YamlSerializableAttribute : Attribute { } internal sealed class YamlStaticContextAttribute : Attribute { } } namespace YamlDotNet.Serialization.ValueDeserializers { internal sealed class AliasValueDeserializer : IValueDeserializer { private sealed class AliasState : Dictionary, IPostDeserializationCallback { public void OnDeserialization() { foreach (ValuePromise value in base.Values) { if (!value.HasValue) { YamlDotNet.Core.Events.AnchorAlias alias = value.Alias; Mark start = alias.Start; Mark end = alias.End; throw new AnchorNotFoundException(in start, in end, $"Anchor '{alias.Value}' not found"); } } } } private sealed class ValuePromise : IValuePromise { private object? value; public readonly YamlDotNet.Core.Events.AnchorAlias? Alias; public bool HasValue { get; private set; } public object? Value { get { if (!HasValue) { throw new InvalidOperationException("Value not set"); } return value; } set { if (HasValue) { throw new InvalidOperationException("Value already set"); } HasValue = true; this.value = value; this.ValueAvailable?.Invoke(value); } } public event Action? ValueAvailable; public ValuePromise(YamlDotNet.Core.Events.AnchorAlias alias) { Alias = alias; } public ValuePromise(object? value) { HasValue = true; this.value = value; } } private readonly IValueDeserializer innerDeserializer; public AliasValueDeserializer(IValueDeserializer innerDeserializer) { this.innerDeserializer = innerDeserializer ?? throw new ArgumentNullException("innerDeserializer"); } public object? DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer) { if (parser.TryConsume(out var @event)) { if (!state.Get().TryGetValue(@event.Value, out ValuePromise value)) { Mark start = @event.Start; Mark end = @event.End; throw new AnchorNotFoundException(in start, in end, $"Alias ${@event.Value} cannot precede anchor declaration"); } if (!value.HasValue) { return value; } return value.Value; } AnchorName anchorName = AnchorName.Empty; if (parser.Accept(out var event2) && !event2.Anchor.IsEmpty) { anchorName = event2.Anchor; AliasState aliasState = state.Get(); if (!aliasState.ContainsKey(anchorName)) { aliasState[anchorName] = new ValuePromise(new YamlDotNet.Core.Events.AnchorAlias(anchorName)); } } object obj = innerDeserializer.DeserializeValue(parser, expectedType, state, nestedObjectDeserializer); if (!anchorName.IsEmpty) { AliasState aliasState2 = state.Get(); if (!aliasState2.TryGetValue(anchorName, out ValuePromise value2)) { aliasState2.Add(anchorName, new ValuePromise(obj)); } else if (!value2.HasValue) { value2.Value = obj; } else { aliasState2[anchorName] = new ValuePromise(obj); } } return obj; } } internal sealed class NodeValueDeserializer : IValueDeserializer { private readonly IList deserializers; private readonly IList typeResolvers; private readonly ITypeConverter typeConverter; public NodeValueDeserializer(IList deserializers, IList typeResolvers, ITypeConverter typeConverter) { this.deserializers = deserializers ?? throw new ArgumentNullException("deserializers"); this.typeResolvers = typeResolvers ?? throw new ArgumentNullException("typeResolvers"); this.typeConverter = typeConverter ?? throw new ArgumentNullException("typeConverter"); } public object? DeserializeValue(IParser parser, Type expectedType, SerializerState state, IValueDeserializer nestedObjectDeserializer) { IValueDeserializer nestedObjectDeserializer2 = nestedObjectDeserializer; SerializerState state2 = state; parser.Accept(out var @event); Type typeFromEvent = GetTypeFromEvent(@event, expectedType); Mark start; Mark end; try { foreach (INodeDeserializer deserializer in deserializers) { if (deserializer.Deserialize(parser, typeFromEvent, (IParser r, Type t) => nestedObjectDeserializer2.DeserializeValue(r, t, state2, nestedObjectDeserializer2), out object value)) { return typeConverter.ChangeType(value, expectedType); } } } catch (YamlException) { throw; } catch (Exception innerException) { start = @event?.Start ?? Mark.Empty; end = @event?.End ?? Mark.Empty; throw new YamlException(in start, in end, "Exception during deserialization", innerException); } start = @event?.Start ?? Mark.Empty; end = @event?.End ?? Mark.Empty; throw new YamlException(in start, in end, "No node deserializer was able to deserialize the node into type " + expectedType.AssemblyQualifiedName); } private Type GetTypeFromEvent(NodeEvent? nodeEvent, Type currentType) { using (IEnumerator enumerator = typeResolvers.GetEnumerator()) { while (enumerator.MoveNext() && !enumerator.Current.Resolve(nodeEvent, ref currentType)) { } } return currentType; } } } namespace YamlDotNet.Serialization.Utilities { internal interface IPostDeserializationCallback { void OnDeserialization(); } internal interface ITypeConverter { object? ChangeType(object? value, Type expectedType); } internal class NullTypeConverter : ITypeConverter { public object? ChangeType(object? value, Type expectedType) { return value; } } internal sealed class ObjectAnchorCollection { private readonly IDictionary objectsByAnchor = new Dictionary(); private readonly IDictionary anchorsByObject = new Dictionary(); public object this[string anchor] { get { if (objectsByAnchor.TryGetValue(anchor, out object value)) { return value; } throw new AnchorNotFoundException("The anchor '" + anchor + "' does not exists"); } } public void Add(string anchor, object @object) { objectsByAnchor.Add(anchor, @object); if (@object != null) { anchorsByObject.Add(@object, anchor); } } public bool TryGetAnchor(object @object, [MaybeNullWhen(false)] out string? anchor) { return anchorsByObject.TryGetValue(@object, out anchor); } } internal class ReflectionTypeConverter : ITypeConverter { public object? ChangeType(object? value, Type expectedType) { return TypeConverter.ChangeType(value, expectedType); } } internal static class ReflectionUtility { public static Type? GetImplementedGenericInterface(Type type, Type genericInterfaceType) { foreach (Type implementedInterface in GetImplementedInterfaces(type)) { if (implementedInterface.IsGenericType() && implementedInterface.GetGenericTypeDefinition() == genericInterfaceType) { return implementedInterface; } } return null; } public static IEnumerable GetImplementedInterfaces(Type type) { if (type.IsInterface()) { yield return type; } Type[] interfaces = type.GetInterfaces(); for (int i = 0; i < interfaces.Length; i++) { yield return interfaces[i]; } } } internal sealed class SerializerState : IDisposable { private readonly IDictionary items = new Dictionary(); public T Get() where T : class, new() { if (!items.TryGetValue(typeof(T), out object value)) { value = new T(); items.Add(typeof(T), value); } return (T)value; } public void OnDeserialization() { foreach (IPostDeserializationCallback item in items.Values.OfType()) { item.OnDeserialization(); } } public void Dispose() { foreach (IDisposable item in items.Values.OfType()) { item.Dispose(); } } } internal static class StringExtensions { private static string ToCamelOrPascalCase(string str, Func firstLetterTransform) { string text = Regex.Replace(str, "([_\\-])(?[a-z])", (Match match) => match.Groups["char"].Value.ToUpperInvariant(), RegexOptions.IgnoreCase); return firstLetterTransform(text[0]) + text.Substring(1); } public static string ToCamelCase(this string str) { return ToCamelOrPascalCase(str, char.ToLowerInvariant); } public static string ToPascalCase(this string str) { return ToCamelOrPascalCase(str, char.ToUpperInvariant); } public static string FromCamelCase(this string str, string separator) { string separator2 = separator; str = char.ToLower(str[0]) + str.Substring(1); str = Regex.Replace(str.ToCamelCase(), "(?[A-Z])", (Match match) => separator2 + match.Groups["char"].Value.ToLowerInvariant()); return str; } } internal static class TypeConverter { public static T ChangeType(object? value) { return (T)ChangeType(value, typeof(T)); } public static T ChangeType(object? value, IFormatProvider provider) { return (T)ChangeType(value, typeof(T), provider); } public static T ChangeType(object? value, CultureInfo culture) { return (T)ChangeType(value, typeof(T), culture); } public static object? ChangeType(object? value, Type destinationType) { return ChangeType(value, destinationType, CultureInfo.InvariantCulture); } public static object? ChangeType(object? value, Type destinationType, IFormatProvider provider) { return ChangeType(value, destinationType, new CultureInfoAdapter(CultureInfo.CurrentCulture, provider)); } public static object? ChangeType(object? value, Type destinationType, CultureInfo culture) { if (value == null || value.IsDbNull()) { if (!destinationType.IsValueType()) { return null; } return Activator.CreateInstance(destinationType); } Type type = value.GetType(); if (destinationType == type || destinationType.IsAssignableFrom(type)) { return value; } if (destinationType.IsGenericType() && destinationType.GetGenericTypeDefinition() == typeof(Nullable<>)) { Type destinationType2 = destinationType.GetGenericArguments()[0]; object obj = ChangeType(value, destinationType2, culture); return Activator.CreateInstance(destinationType, obj); } if (destinationType.IsEnum()) { if (!(value is string value2)) { return value; } return Enum.Parse(destinationType, value2, ignoreCase: true); } if (destinationType == typeof(bool)) { if ("0".Equals(value)) { return false; } if ("1".Equals(value)) { return true; } } System.ComponentModel.TypeConverter converter = TypeDescriptor.GetConverter(type); if (converter != null && converter.CanConvertTo(destinationType)) { return converter.ConvertTo(null, culture, value, destinationType); } System.ComponentModel.TypeConverter converter2 = TypeDescriptor.GetConverter(destinationType); if (converter2 != null && converter2.CanConvertFrom(type)) { return converter2.ConvertFrom(null, culture, value); } Type[] array = new Type[2] { type, destinationType }; for (int i = 0; i < array.Length; i++) { foreach (MethodInfo publicStaticMethod2 in array[i].GetPublicStaticMethods()) { if (!publicStaticMethod2.IsSpecialName || (!(publicStaticMethod2.Name == "op_Implicit") && !(publicStaticMethod2.Name == "op_Explicit")) || !destinationType.IsAssignableFrom(publicStaticMethod2.ReturnParameter.ParameterType)) { continue; } ParameterInfo[] parameters = publicStaticMethod2.GetParameters(); if (parameters.Length == 1 && parameters[0].ParameterType.IsAssignableFrom(type)) { try { return publicStaticMethod2.Invoke(null, new object[1] { value }); } catch (TargetInvocationException ex) { throw ex.Unwrap(); } } } } if (type == typeof(string)) { try { MethodInfo publicStaticMethod = destinationType.GetPublicStaticMethod("Parse", typeof(string), typeof(IFormatProvider)); if (publicStaticMethod != null) { return publicStaticMethod.Invoke(null, new object[2] { value, culture }); } publicStaticMethod = destinationType.GetPublicStaticMethod("Parse", typeof(string)); if (publicStaticMethod != null) { return publicStaticMethod.Invoke(null, new object[1] { value }); } } catch (TargetInvocationException ex2) { throw ex2.Unwrap(); } } if (destinationType == typeof(TimeSpan)) { return TimeSpan.Parse((string)ChangeType(value, typeof(string), CultureInfo.InvariantCulture)); } return Convert.ChangeType(value, destinationType, CultureInfo.InvariantCulture); } public static void RegisterTypeConverter() where TConverter : System.ComponentModel.TypeConverter { if (!TypeDescriptor.GetAttributes(typeof(TConvertible)).OfType().Any((TypeConverterAttribute a) => a.ConverterTypeName == typeof(TConverter).AssemblyQualifiedName)) { TypeDescriptor.AddAttributes(typeof(TConvertible), new TypeConverterAttribute(typeof(TConverter))); } } } } namespace YamlDotNet.Serialization.TypeResolvers { internal sealed class DynamicTypeResolver : ITypeResolver { public Type Resolve(Type staticType, object? actualValue) { if (actualValue == null) { return staticType; } return actualValue.GetType(); } } internal sealed class StaticTypeResolver : ITypeResolver { public Type Resolve(Type staticType, object? actualValue) { return staticType; } } } namespace YamlDotNet.Serialization.TypeInspectors { internal sealed class CachedTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; private readonly ConcurrentDictionary> cache = new ConcurrentDictionary>(); public CachedTypeInspector(ITypeInspector innerTypeDescriptor) { this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor"); } public override IEnumerable GetProperties(Type type, object? container) { object container2 = container; return cache.GetOrAdd(type, (Type t) => innerTypeDescriptor.GetProperties(t, container2).ToList()); } } internal sealed class CompositeTypeInspector : TypeInspectorSkeleton { private readonly IEnumerable typeInspectors; public CompositeTypeInspector(params ITypeInspector[] typeInspectors) : this((IEnumerable)typeInspectors) { } public CompositeTypeInspector(IEnumerable typeInspectors) { this.typeInspectors = typeInspectors?.ToList() ?? throw new ArgumentNullException("typeInspectors"); } public override IEnumerable GetProperties(Type type, object? container) { Type type2 = type; object container2 = container; return typeInspectors.SelectMany((ITypeInspector i) => i.GetProperties(type2, container2)); } } internal sealed class NamingConventionTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; private readonly INamingConvention namingConvention; public NamingConventionTypeInspector(ITypeInspector innerTypeDescriptor, INamingConvention namingConvention) { this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor"); this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention"); } public override IEnumerable GetProperties(Type type, object? container) { return innerTypeDescriptor.GetProperties(type, container).Select(delegate(IPropertyDescriptor p) { YamlMemberAttribute customAttribute = p.GetCustomAttribute(); return (customAttribute != null && !customAttribute.ApplyNamingConventions) ? p : new PropertyDescriptor(p) { Name = namingConvention.Apply(p.Name) }; }); } } internal sealed class ReadableAndWritablePropertiesTypeInspector : TypeInspectorSkeleton { private readonly ITypeInspector innerTypeDescriptor; public ReadableAndWritablePropertiesTypeInspector(ITypeInspector innerTypeDescriptor) { this.innerTypeDescriptor = innerTypeDescriptor ?? throw new ArgumentNullException("innerTypeDescriptor"); } public override IEnumerable GetProperties(Type type, object? container) { return from p in innerTypeDescriptor.GetProperties(type, container) where p.CanWrite select p; } } internal sealed class ReadableFieldsTypeInspector : TypeInspectorSkeleton { private sealed class ReflectionFieldDescriptor : IPropertyDescriptor { private readonly FieldInfo fieldInfo; private readonly ITypeResolver typeResolver; public string Name => fieldInfo.Name; public Type Type => fieldInfo.FieldType; public Type? TypeOverride { get; set; } public int Order { get; set; } public bool CanWrite => !fieldInfo.IsInitOnly; public ScalarStyle ScalarStyle { get; set; } public ReflectionFieldDescriptor(FieldInfo fieldInfo, ITypeResolver typeResolver) { this.fieldInfo = fieldInfo; this.typeResolver = typeResolver; ScalarStyle = ScalarStyle.Any; } public void Write(object target, object? value) { fieldInfo.SetValue(target, value); } public T? GetCustomAttribute() where T : Attribute { return (T)fieldInfo.GetCustomAttributes(typeof(T), inherit: true).FirstOrDefault(); } public IObjectDescriptor Read(object target) { object value = fieldInfo.GetValue(target); Type type = TypeOverride ?? typeResolver.Resolve(Type, value); return new ObjectDescriptor(value, type, Type, ScalarStyle); } } private readonly ITypeResolver typeResolver; public ReadableFieldsTypeInspector(ITypeResolver typeResolver) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); } public override IEnumerable GetProperties(Type type, object? container) { return type.GetPublicFields().Select((Func)((FieldInfo p) => new ReflectionFieldDescriptor(p, typeResolver))); } } internal sealed class ReadablePropertiesTypeInspector : TypeInspectorSkeleton { private sealed class ReflectionPropertyDescriptor : IPropertyDescriptor { private readonly PropertyInfo propertyInfo; private readonly ITypeResolver typeResolver; public string Name => propertyInfo.Name; public Type Type => propertyInfo.PropertyType; public Type? TypeOverride { get; set; } public int Order { get; set; } public bool CanWrite => propertyInfo.CanWrite; public ScalarStyle ScalarStyle { get; set; } public ReflectionPropertyDescriptor(PropertyInfo propertyInfo, ITypeResolver typeResolver) { this.propertyInfo = propertyInfo ?? throw new ArgumentNullException("propertyInfo"); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); ScalarStyle = ScalarStyle.Any; } public void Write(object target, object? value) { propertyInfo.SetValue(target, value, null); } public T? GetCustomAttribute() where T : Attribute { return (T)propertyInfo.GetAllCustomAttributes().FirstOrDefault(); } public IObjectDescriptor Read(object target) { object obj = propertyInfo.ReadValue(target); Type type = TypeOverride ?? typeResolver.Resolve(Type, obj); return new ObjectDescriptor(obj, type, Type, ScalarStyle); } } private readonly ITypeResolver typeResolver; private readonly bool includeNonPublicProperties; public ReadablePropertiesTypeInspector(ITypeResolver typeResolver) : this(typeResolver, includeNonPublicProperties: false) { } public ReadablePropertiesTypeInspector(ITypeResolver typeResolver, bool includeNonPublicProperties) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); this.includeNonPublicProperties = includeNonPublicProperties; } private static bool IsValidProperty(PropertyInfo property) { if (property.CanRead) { return property.GetGetMethod(nonPublic: true).GetParameters().Length == 0; } return false; } public override IEnumerable GetProperties(Type type, object? container) { return type.GetProperties(includeNonPublicProperties).Where(IsValidProperty).Select((Func)((PropertyInfo p) => new ReflectionPropertyDescriptor(p, typeResolver))); } } internal abstract class TypeInspectorSkeleton : ITypeInspector { public abstract IEnumerable GetProperties(Type type, object? container); public IPropertyDescriptor GetProperty(Type type, object? container, string name, [MaybeNullWhen(true)] bool ignoreUnmatched) { string name2 = name; IEnumerable enumerable = from p in GetProperties(type, container) where p.Name == name2 select p; using IEnumerator enumerator = enumerable.GetEnumerator(); if (!enumerator.MoveNext()) { if (ignoreUnmatched) { return null; } throw new SerializationException("Property '" + name2 + "' not found on type '" + type.FullName + "'."); } IPropertyDescriptor current = enumerator.Current; if (enumerator.MoveNext()) { throw new SerializationException("Multiple properties with the name/alias '" + name2 + "' already exists on type '" + type.FullName + "', maybe you're misusing YamlAlias or maybe you are using the wrong naming convention? The matching properties are: " + string.Join(", ", enumerable.Select((IPropertyDescriptor p) => p.Name).ToArray())); } return current; } } internal sealed class WritablePropertiesTypeInspector : TypeInspectorSkeleton { private sealed class ReflectionPropertyDescriptor : IPropertyDescriptor { private readonly PropertyInfo propertyInfo; private readonly ITypeResolver typeResolver; public string Name => propertyInfo.Name; public Type Type => propertyInfo.PropertyType; public Type? TypeOverride { get; set; } public int Order { get; set; } public bool CanWrite => propertyInfo.CanWrite; public ScalarStyle ScalarStyle { get; set; } public ReflectionPropertyDescriptor(PropertyInfo propertyInfo, ITypeResolver typeResolver) { this.propertyInfo = propertyInfo ?? throw new ArgumentNullException("propertyInfo"); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); ScalarStyle = ScalarStyle.Any; } public void Write(object target, object? value) { propertyInfo.SetValue(target, value, null); } public T? GetCustomAttribute() where T : Attribute { return (T)propertyInfo.GetAllCustomAttributes().FirstOrDefault(); } public IObjectDescriptor Read(object target) { object obj = propertyInfo.ReadValue(target); Type type = TypeOverride ?? typeResolver.Resolve(Type, obj); return new ObjectDescriptor(obj, type, Type, ScalarStyle); } } private readonly ITypeResolver typeResolver; private readonly bool includeNonPublicProperties; public WritablePropertiesTypeInspector(ITypeResolver typeResolver) : this(typeResolver, includeNonPublicProperties: false) { } public WritablePropertiesTypeInspector(ITypeResolver typeResolver, bool includeNonPublicProperties) { this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); this.includeNonPublicProperties = includeNonPublicProperties; } private static bool IsValidProperty(PropertyInfo property) { if (property.CanWrite) { return property.GetSetMethod(nonPublic: true).GetParameters().Length == 1; } return false; } public override IEnumerable GetProperties(Type type, object? container) { return type.GetProperties(includeNonPublicProperties).Where(IsValidProperty).Select((Func)((PropertyInfo p) => new ReflectionPropertyDescriptor(p, typeResolver))) .ToArray(); } } } namespace YamlDotNet.Serialization.Schemas { internal sealed class FailsafeSchema { public static class Tags { public static readonly TagName Map = new TagName("tag:yaml.org,2002:map"); public static readonly TagName Seq = new TagName("tag:yaml.org,2002:seq"); public static readonly TagName Str = new TagName("tag:yaml.org,2002:str"); } } internal sealed class JsonSchema { public static class Tags { public static readonly TagName Null = new TagName("tag:yaml.org,2002:null"); public static readonly TagName Bool = new TagName("tag:yaml.org,2002:bool"); public static readonly TagName Int = new TagName("tag:yaml.org,2002:int"); public static readonly TagName Float = new TagName("tag:yaml.org,2002:float"); } } internal sealed class CoreSchema { public static class Tags { } } internal sealed class DefaultSchema { public static class Tags { public static readonly TagName Timestamp = new TagName("tag:yaml.org,2002:timestamp"); } } } namespace YamlDotNet.Serialization.ObjectGraphVisitors { internal sealed class AnchorAssigner : PreProcessingPhaseObjectGraphVisitorSkeleton, IAliasProvider { private class AnchorAssignment { public AnchorName Anchor; } private readonly IDictionary assignments = new Dictionary(); private uint nextId; public AnchorAssigner(IEnumerable typeConverters) : base(typeConverters) { } protected override bool Enter(IObjectDescriptor value) { if (value.Value != null && assignments.TryGetValue(value.Value, out AnchorAssignment value2)) { if (value2.Anchor.IsEmpty) { value2.Anchor = new AnchorName("o" + nextId.ToString(CultureInfo.InvariantCulture)); nextId++; } return false; } return true; } protected override bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value) { return true; } protected override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value) { return true; } protected override void VisitScalar(IObjectDescriptor scalar) { } protected override void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType) { VisitObject(mapping); } protected override void VisitMappingEnd(IObjectDescriptor mapping) { } protected override void VisitSequenceStart(IObjectDescriptor sequence, Type elementType) { VisitObject(sequence); } protected override void VisitSequenceEnd(IObjectDescriptor sequence) { } private void VisitObject(IObjectDescriptor value) { if (value.Value != null) { assignments.Add(value.Value, new AnchorAssignment()); } } AnchorName IAliasProvider.GetAlias(object target) { if (target != null && assignments.TryGetValue(target, out AnchorAssignment value)) { return value.Anchor; } return AnchorName.Empty; } } internal sealed class AnchorAssigningObjectGraphVisitor : ChainedObjectGraphVisitor { private readonly IEventEmitter eventEmitter; private readonly IAliasProvider aliasProvider; private readonly HashSet emittedAliases = new HashSet(); public AnchorAssigningObjectGraphVisitor(IObjectGraphVisitor nextVisitor, IEventEmitter eventEmitter, IAliasProvider aliasProvider) : base(nextVisitor) { this.eventEmitter = eventEmitter; this.aliasProvider = aliasProvider; } public override bool Enter(IObjectDescriptor value, IEmitter context) { if (value.Value != null) { AnchorName alias = aliasProvider.GetAlias(value.Value); if (!alias.IsEmpty && !emittedAliases.Add(alias)) { AliasEventInfo aliasEventInfo = new AliasEventInfo(value, alias); eventEmitter.Emit(aliasEventInfo, context); return aliasEventInfo.NeedsExpansion; } } return base.Enter(value, context); } public override void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, IEmitter context) { AnchorName alias = aliasProvider.GetAlias(mapping.NonNullValue()); eventEmitter.Emit(new MappingStartEventInfo(mapping) { Anchor = alias }, context); } public override void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, IEmitter context) { AnchorName alias = aliasProvider.GetAlias(sequence.NonNullValue()); eventEmitter.Emit(new SequenceStartEventInfo(sequence) { Anchor = alias }, context); } public override void VisitScalar(IObjectDescriptor scalar, IEmitter context) { ScalarEventInfo scalarEventInfo = new ScalarEventInfo(scalar); if (scalar.Value != null) { scalarEventInfo.Anchor = aliasProvider.GetAlias(scalar.Value); } eventEmitter.Emit(scalarEventInfo, context); } } internal abstract class ChainedObjectGraphVisitor : IObjectGraphVisitor { private readonly IObjectGraphVisitor nextVisitor; protected ChainedObjectGraphVisitor(IObjectGraphVisitor nextVisitor) { this.nextVisitor = nextVisitor; } public virtual bool Enter(IObjectDescriptor value, IEmitter context) { return nextVisitor.Enter(value, context); } public virtual bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, IEmitter context) { return nextVisitor.EnterMapping(key, value, context); } public virtual bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context) { return nextVisitor.EnterMapping(key, value, context); } public virtual void VisitScalar(IObjectDescriptor scalar, IEmitter context) { nextVisitor.VisitScalar(scalar, context); } public virtual void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, IEmitter context) { nextVisitor.VisitMappingStart(mapping, keyType, valueType, context); } public virtual void VisitMappingEnd(IObjectDescriptor mapping, IEmitter context) { nextVisitor.VisitMappingEnd(mapping, context); } public virtual void VisitSequenceStart(IObjectDescriptor sequence, Type elementType, IEmitter context) { nextVisitor.VisitSequenceStart(sequence, elementType, context); } public virtual void VisitSequenceEnd(IObjectDescriptor sequence, IEmitter context) { nextVisitor.VisitSequenceEnd(sequence, context); } } internal sealed class CommentsObjectGraphVisitor : ChainedObjectGraphVisitor { public CommentsObjectGraphVisitor(IObjectGraphVisitor nextVisitor) : base(nextVisitor) { } public override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context) { YamlMemberAttribute customAttribute = key.GetCustomAttribute(); if (customAttribute != null && customAttribute.Description != null) { context.Emit(new YamlDotNet.Core.Events.Comment(customAttribute.Description, isInline: false)); } return base.EnterMapping(key, value, context); } } internal sealed class CustomSerializationObjectGraphVisitor : ChainedObjectGraphVisitor { private readonly IEnumerable typeConverters; private readonly ObjectSerializer nestedObjectSerializer; public CustomSerializationObjectGraphVisitor(IObjectGraphVisitor nextVisitor, IEnumerable typeConverters, ObjectSerializer nestedObjectSerializer) : base(nextVisitor) { IEnumerable enumerable; if (typeConverters == null) { enumerable = Enumerable.Empty(); } else { IEnumerable enumerable2 = typeConverters.ToList(); enumerable = enumerable2; } this.typeConverters = enumerable; this.nestedObjectSerializer = nestedObjectSerializer; } public override bool Enter(IObjectDescriptor value, IEmitter context) { IObjectDescriptor value2 = value; IYamlTypeConverter yamlTypeConverter = typeConverters.FirstOrDefault((IYamlTypeConverter t) => t.Accepts(value2.Type)); if (yamlTypeConverter != null) { yamlTypeConverter.WriteYaml(context, value2.Value, value2.Type); return false; } if (value2.Value is IYamlConvertible yamlConvertible) { yamlConvertible.Write(context, nestedObjectSerializer); return false; } if (value2.Value is IYamlSerializable yamlSerializable) { yamlSerializable.WriteYaml(context); return false; } return base.Enter(value2, context); } } internal sealed class DefaultExclusiveObjectGraphVisitor : ChainedObjectGraphVisitor { public DefaultExclusiveObjectGraphVisitor(IObjectGraphVisitor nextVisitor) : base(nextVisitor) { } private static object? GetDefault(Type type) { if (!type.IsValueType()) { return null; } return Activator.CreateInstance(type); } public override bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value, IEmitter context) { if (!object.Equals(value.Value, GetDefault(value.Type))) { return base.EnterMapping(key, value, context); } return false; } public override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context) { DefaultValueAttribute customAttribute = key.GetCustomAttribute(); object objB = ((customAttribute != null) ? customAttribute.Value : GetDefault(key.Type)); if (!object.Equals(value.Value, objB)) { return base.EnterMapping(key, value, context); } return false; } } internal sealed class DefaultValuesObjectGraphVisitor : ChainedObjectGraphVisitor { private readonly DefaultValuesHandling handling; private readonly IObjectFactory factory; public DefaultValuesObjectGraphVisitor(DefaultValuesHandling handling, IObjectGraphVisitor nextVisitor, IObjectFactory factory) : base(nextVisitor) { this.handling = handling; this.factory = factory; } private object? GetDefault(Type type) { return factory.CreatePrimitive(type); } public override bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context) { DefaultValuesHandling defaultValuesHandling = handling; YamlMemberAttribute customAttribute = key.GetCustomAttribute(); if (customAttribute != null && customAttribute.IsDefaultValuesHandlingSpecified) { defaultValuesHandling = customAttribute.DefaultValuesHandling; } if ((defaultValuesHandling & DefaultValuesHandling.OmitNull) != 0 && value.Value == null) { return false; } if ((defaultValuesHandling & DefaultValuesHandling.OmitEmptyCollections) != 0 && value.Value is IEnumerable enumerable) { IEnumerator enumerator = enumerable.GetEnumerator(); bool flag = enumerator.MoveNext(); if (enumerator is IDisposable disposable) { disposable.Dispose(); } if (!flag) { return false; } } if ((defaultValuesHandling & DefaultValuesHandling.OmitDefaults) != 0) { object objB = key.GetCustomAttribute()?.Value ?? GetDefault(key.Type); if (object.Equals(value.Value, objB)) { return false; } } return base.EnterMapping(key, value, context); } } internal sealed class EmittingObjectGraphVisitor : IObjectGraphVisitor { private readonly IEventEmitter eventEmitter; public EmittingObjectGraphVisitor(IEventEmitter eventEmitter) { this.eventEmitter = eventEmitter; } bool IObjectGraphVisitor.Enter(IObjectDescriptor value, IEmitter context) { return true; } bool IObjectGraphVisitor.EnterMapping(IObjectDescriptor key, IObjectDescriptor value, IEmitter context) { return true; } bool IObjectGraphVisitor.EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, IEmitter context) { return true; } void IObjectGraphVisitor.VisitScalar(IObjectDescriptor scalar, IEmitter context) { eventEmitter.Emit(new ScalarEventInfo(scalar), context); } void IObjectGraphVisitor.VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, IEmitter context) { eventEmitter.Emit(new MappingStartEventInfo(mapping), context); } void IObjectGraphVisitor.VisitMappingEnd(IObjectDescriptor mapping, IEmitter context) { eventEmitter.Emit(new MappingEndEventInfo(mapping), context); } void IObjectGraphVisitor.VisitSequenceStart(IObjectDescriptor sequence, Type elementType, IEmitter context) { eventEmitter.Emit(new SequenceStartEventInfo(sequence), context); } void IObjectGraphVisitor.VisitSequenceEnd(IObjectDescriptor sequence, IEmitter context) { eventEmitter.Emit(new SequenceEndEventInfo(sequence), context); } } internal abstract class PreProcessingPhaseObjectGraphVisitorSkeleton : IObjectGraphVisitor { protected readonly IEnumerable typeConverters; public PreProcessingPhaseObjectGraphVisitorSkeleton(IEnumerable typeConverters) { IEnumerable enumerable; if (typeConverters == null) { enumerable = Enumerable.Empty(); } else { IEnumerable enumerable2 = typeConverters.ToList(); enumerable = enumerable2; } this.typeConverters = enumerable; } bool IObjectGraphVisitor.Enter(IObjectDescriptor value, Nothing context) { IObjectDescriptor value2 = value; if (typeConverters.FirstOrDefault((IYamlTypeConverter t) => t.Accepts(value2.Type)) != null) { return false; } if (value2.Value is IYamlConvertible) { return false; } if (value2.Value is IYamlSerializable) { return false; } return Enter(value2); } bool IObjectGraphVisitor.EnterMapping(IPropertyDescriptor key, IObjectDescriptor value, Nothing context) { return EnterMapping(key, value); } bool IObjectGraphVisitor.EnterMapping(IObjectDescriptor key, IObjectDescriptor value, Nothing context) { return EnterMapping(key, value); } void IObjectGraphVisitor.VisitMappingEnd(IObjectDescriptor mapping, Nothing context) { VisitMappingEnd(mapping); } void IObjectGraphVisitor.VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType, Nothing context) { VisitMappingStart(mapping, keyType, valueType); } void IObjectGraphVisitor.VisitScalar(IObjectDescriptor scalar, Nothing context) { VisitScalar(scalar); } void IObjectGraphVisitor.VisitSequenceEnd(IObjectDescriptor sequence, Nothing context) { VisitSequenceEnd(sequence); } void IObjectGraphVisitor.VisitSequenceStart(IObjectDescriptor sequence, Type elementType, Nothing context) { VisitSequenceStart(sequence, elementType); } protected abstract bool Enter(IObjectDescriptor value); protected abstract bool EnterMapping(IPropertyDescriptor key, IObjectDescriptor value); protected abstract bool EnterMapping(IObjectDescriptor key, IObjectDescriptor value); protected abstract void VisitMappingEnd(IObjectDescriptor mapping); protected abstract void VisitMappingStart(IObjectDescriptor mapping, Type keyType, Type valueType); protected abstract void VisitScalar(IObjectDescriptor scalar); protected abstract void VisitSequenceEnd(IObjectDescriptor sequence); protected abstract void VisitSequenceStart(IObjectDescriptor sequence, Type elementType); } } namespace YamlDotNet.Serialization.ObjectGraphTraversalStrategies { internal class FullObjectGraphTraversalStrategy : IObjectGraphTraversalStrategy { protected struct ObjectPathSegment { public readonly object Name; public readonly IObjectDescriptor Value; public ObjectPathSegment(object name, IObjectDescriptor value) { Name = name; Value = value; } } private readonly int maxRecursion; private readonly ITypeInspector typeDescriptor; private readonly ITypeResolver typeResolver; private readonly INamingConvention namingConvention; private readonly IObjectFactory objectFactory; public FullObjectGraphTraversalStrategy(ITypeInspector typeDescriptor, ITypeResolver typeResolver, int maxRecursion, INamingConvention namingConvention, IObjectFactory objectFactory) { if (maxRecursion <= 0) { throw new ArgumentOutOfRangeException("maxRecursion", maxRecursion, "maxRecursion must be greater than 1"); } this.typeDescriptor = typeDescriptor ?? throw new ArgumentNullException("typeDescriptor"); this.typeResolver = typeResolver ?? throw new ArgumentNullException("typeResolver"); this.maxRecursion = maxRecursion; this.namingConvention = namingConvention ?? throw new ArgumentNullException("namingConvention"); this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); } void IObjectGraphTraversalStrategy.Traverse(IObjectDescriptor graph, IObjectGraphVisitor visitor, TContext context) { Traverse("", graph, visitor, context, new Stack(maxRecursion)); } protected virtual void Traverse(object name, IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path) { if (path.Count >= maxRecursion) { StringBuilder stringBuilder = new StringBuilder(); stringBuilder.AppendLine("Too much recursion when traversing the object graph."); stringBuilder.AppendLine("The path to reach this recursion was:"); Stack> stack = new Stack>(path.Count); int num = 0; foreach (ObjectPathSegment item in path) { string text = item.Name?.ToString() ?? string.Empty; num = Math.Max(num, text.Length); stack.Push(new KeyValuePair(text, item.Value.Type.FullName)); } foreach (KeyValuePair item2 in stack) { stringBuilder.Append(" -> ").Append(item2.Key.PadRight(num)).Append(" [") .Append(item2.Value) .AppendLine("]"); } throw new MaximumRecursionLevelReachedException(stringBuilder.ToString()); } if (!visitor.Enter(value, context)) { return; } path.Push(new ObjectPathSegment(name, value)); try { TypeCode typeCode = value.Type.GetTypeCode(); switch (typeCode) { case TypeCode.Boolean: case TypeCode.Char: case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: case TypeCode.DateTime: case TypeCode.String: visitor.VisitScalar(value, context); return; case TypeCode.Empty: throw new NotSupportedException($"TypeCode.{typeCode} is not supported."); } if (value.IsDbNull()) { visitor.VisitScalar(new ObjectDescriptor(null, typeof(object), typeof(object)), context); } if (value.Value == null || value.Type == typeof(TimeSpan)) { visitor.VisitScalar(value, context); return; } Type underlyingType = Nullable.GetUnderlyingType(value.Type); if (underlyingType != null) { Traverse("Value", new ObjectDescriptor(value.Value, underlyingType, value.Type, value.ScalarStyle), visitor, context, path); } else { TraverseObject(value, visitor, context, path); } } finally { path.Pop(); } } protected virtual void TraverseObject(IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path) { IDictionary dictionary; Type[] genericArguments; if (typeof(IDictionary).IsAssignableFrom(value.Type)) { TraverseDictionary(value, visitor, typeof(object), typeof(object), context, path); } else if (objectFactory.GetDictionary(value, out dictionary, out genericArguments)) { TraverseDictionary(new ObjectDescriptor(dictionary, value.Type, value.StaticType, value.ScalarStyle), visitor, genericArguments[0], genericArguments[1], context, path); } else if (typeof(IEnumerable).IsAssignableFrom(value.Type)) { TraverseList(value, visitor, context, path); } else { TraverseProperties(value, visitor, context, path); } } protected virtual void TraverseDictionary(IObjectDescriptor dictionary, IObjectGraphVisitor visitor, Type keyType, Type valueType, TContext context, Stack path) { visitor.VisitMappingStart(dictionary, keyType, valueType, context); bool flag = dictionary.Type.FullName.Equals("System.Dynamic.ExpandoObject"); foreach (DictionaryEntry? item in (IDictionary)dictionary.NonNullValue()) { DictionaryEntry value = item.Value; object obj = (flag ? namingConvention.Apply(value.Key.ToString()) : value.Key); IObjectDescriptor objectDescriptor = GetObjectDescriptor(obj, keyType); IObjectDescriptor objectDescriptor2 = GetObjectDescriptor(value.Value, valueType); if (visitor.EnterMapping(objectDescriptor, objectDescriptor2, context)) { Traverse(obj, objectDescriptor, visitor, context, path); Traverse(obj, objectDescriptor2, visitor, context, path); } } visitor.VisitMappingEnd(dictionary, context); } private void TraverseList(IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path) { Type valueType = objectFactory.GetValueType(value.Type); visitor.VisitSequenceStart(value, valueType, context); int num = 0; foreach (object item in (IEnumerable)value.NonNullValue()) { Traverse(num, GetObjectDescriptor(item, valueType), visitor, context, path); num++; } visitor.VisitSequenceEnd(value, context); } protected virtual void TraverseProperties(IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path) { visitor.VisitMappingStart(value, typeof(string), typeof(object), context); object obj = value.NonNullValue(); foreach (IPropertyDescriptor property in typeDescriptor.GetProperties(value.Type, obj)) { IObjectDescriptor value2 = property.Read(obj); if (visitor.EnterMapping(property, value2, context)) { Traverse(property.Name, new ObjectDescriptor(property.Name, typeof(string), typeof(string), ScalarStyle.Plain), visitor, context, path); Traverse(property.Name, value2, visitor, context, path); } } visitor.VisitMappingEnd(value, context); } private IObjectDescriptor GetObjectDescriptor(object? value, Type staticType) { return new ObjectDescriptor(value, typeResolver.Resolve(staticType, value), staticType); } } internal class RoundtripObjectGraphTraversalStrategy : FullObjectGraphTraversalStrategy { private readonly IEnumerable converters; private readonly Settings settings; public RoundtripObjectGraphTraversalStrategy(IEnumerable converters, ITypeInspector typeDescriptor, ITypeResolver typeResolver, int maxRecursion, INamingConvention namingConvention, Settings settings, IObjectFactory factory) : base(typeDescriptor, typeResolver, maxRecursion, namingConvention, factory) { this.converters = converters; this.settings = settings; } protected override void TraverseProperties(IObjectDescriptor value, IObjectGraphVisitor visitor, TContext context, Stack path) { IObjectDescriptor value2 = value; if (!value2.Type.HasDefaultConstructor(settings.AllowPrivateConstructors) && !converters.Any((IYamlTypeConverter c) => c.Accepts(value2.Type))) { throw new InvalidOperationException($"Type '{value2.Type}' cannot be deserialized because it does not have a default constructor or a type converter."); } base.TraverseProperties(value2, visitor, context, path); } } } namespace YamlDotNet.Serialization.ObjectFactories { internal sealed class DefaultObjectFactory : ObjectFactoryBase { private readonly Dictionary DefaultGenericInterfaceImplementations = new Dictionary { { typeof(IEnumerable<>), typeof(List<>) }, { typeof(ICollection<>), typeof(List<>) }, { typeof(IList<>), typeof(List<>) }, { typeof(IDictionary<, >), typeof(Dictionary<, >) } }; private readonly Dictionary DefaultNonGenericInterfaceImplementations = new Dictionary { { typeof(IEnumerable), typeof(List) }, { typeof(ICollection), typeof(List) }, { typeof(IList), typeof(List) }, { typeof(IDictionary), typeof(Dictionary) } }; private readonly Settings settings; public DefaultObjectFactory() : this(new Dictionary(), new Settings()) { } public DefaultObjectFactory(IDictionary mappings) : this(mappings, new Settings()) { } public DefaultObjectFactory(IDictionary mappings, Settings settings) { foreach (KeyValuePair mapping in mappings) { if (!mapping.Key.IsAssignableFrom(mapping.Value)) { throw new InvalidOperationException($"Type '{mapping.Value}' does not implement type '{mapping.Key}'."); } DefaultNonGenericInterfaceImplementations.Add(mapping.Key, mapping.Value); } this.settings = settings; } public override object Create(Type type) { if (type.IsInterface()) { Type value2; if (type.IsGenericType()) { if (DefaultGenericInterfaceImplementations.TryGetValue(type.GetGenericTypeDefinition(), out Type value)) { type = value.MakeGenericType(type.GetGenericArguments()); } } else if (DefaultNonGenericInterfaceImplementations.TryGetValue(type, out value2)) { type = value2; } } try { return Activator.CreateInstance(type, settings.AllowPrivateConstructors); } catch (Exception innerException) { throw new InvalidOperationException("Failed to create an instance of type '" + type.FullName + "'.", innerException); } } } internal sealed class LambdaObjectFactory : ObjectFactoryBase { private readonly Func factory; public LambdaObjectFactory(Func factory) { this.factory = factory ?? throw new ArgumentNullException("factory"); } public override object Create(Type type) { return factory(type); } } internal abstract class ObjectFactoryBase : IObjectFactory { public abstract object Create(Type type); public virtual object? CreatePrimitive(Type type) { if (!type.IsValueType()) { return null; } return Activator.CreateInstance(type); } public virtual bool GetDictionary(IObjectDescriptor descriptor, out IDictionary? dictionary, out Type[]? genericArguments) { Type implementedGenericInterface = ReflectionUtility.GetImplementedGenericInterface(descriptor.Type, typeof(IDictionary<, >)); if (implementedGenericInterface != null) { genericArguments = implementedGenericInterface.GetGenericArguments(); object obj = Activator.CreateInstance(typeof(GenericDictionaryToNonGenericAdapter<, >).MakeGenericType(genericArguments), descriptor.Value); dictionary = obj as IDictionary; return true; } genericArguments = null; dictionary = null; return false; } public virtual Type GetValueType(Type type) { Type implementedGenericInterface = ReflectionUtility.GetImplementedGenericInterface(type, typeof(IEnumerable<>)); if (!(implementedGenericInterface != null)) { return typeof(object); } return implementedGenericInterface.GetGenericArguments()[0]; } } internal abstract class StaticObjectFactory : IObjectFactory { public abstract object Create(Type type); public abstract Array CreateArray(Type type, int count); public abstract bool IsDictionary(Type type); public abstract bool IsArray(Type type); public abstract bool IsList(Type type); public abstract Type GetKeyType(Type type); public abstract Type GetValueType(Type type); public virtual object? CreatePrimitive(Type type) { return Type.GetTypeCode(type) switch { TypeCode.Boolean => false, TypeCode.Byte => (byte)0, TypeCode.Int16 => (short)0, TypeCode.Int32 => 0, TypeCode.Int64 => 0L, TypeCode.SByte => (sbyte)0, TypeCode.UInt16 => (ushort)0, TypeCode.UInt32 => 0u, TypeCode.UInt64 => 0uL, TypeCode.Single => 0f, TypeCode.Double => 0.0, TypeCode.Decimal => 0m, TypeCode.Char => '\0', TypeCode.DateTime => default(DateTime), _ => null, }; } public bool GetDictionary(IObjectDescriptor descriptor, out IDictionary? dictionary, out Type[]? genericArguments) { dictionary = null; genericArguments = null; return false; } } } namespace YamlDotNet.Serialization.NodeTypeResolvers { internal sealed class DefaultContainersNodeTypeResolver : INodeTypeResolver { bool INodeTypeResolver.Resolve(NodeEvent? nodeEvent, ref Type currentType) { if (currentType == typeof(object)) { if (nodeEvent is SequenceStart) { currentType = typeof(List); return true; } if (nodeEvent is MappingStart) { currentType = typeof(Dictionary); return true; } } return false; } } internal class MappingNodeTypeResolver : INodeTypeResolver { private readonly IDictionary _mappings; public MappingNodeTypeResolver(IDictionary mappings) { if (mappings == null) { throw new ArgumentNullException("mappings"); } foreach (KeyValuePair mapping in mappings) { if (!mapping.Key.IsAssignableFrom(mapping.Value)) { throw new InvalidOperationException($"Type '{mapping.Value}' does not implement type '{mapping.Key}'."); } } _mappings = mappings; } public bool Resolve(NodeEvent? nodeEvent, ref Type currentType) { if (_mappings.TryGetValue(currentType, out Type value)) { currentType = value; return true; } return false; } } internal class PreventUnknownTagsNodeTypeResolver : INodeTypeResolver { bool INodeTypeResolver.Resolve(NodeEvent? nodeEvent, ref Type currentType) { if (nodeEvent != null && !nodeEvent.Tag.IsEmpty) { Mark start = nodeEvent.Start; Mark end = nodeEvent.End; throw new YamlException(in start, in end, $"Encountered an unresolved tag '{nodeEvent.Tag}'"); } return false; } } internal sealed class TagNodeTypeResolver : INodeTypeResolver { private readonly IDictionary tagMappings; public TagNodeTypeResolver(IDictionary tagMappings) { this.tagMappings = tagMappings ?? throw new ArgumentNullException("tagMappings"); } bool INodeTypeResolver.Resolve(NodeEvent? nodeEvent, ref Type currentType) { if (nodeEvent != null && !nodeEvent.Tag.IsEmpty && tagMappings.TryGetValue(nodeEvent.Tag, out Type value)) { currentType = value; return true; } return false; } } [Obsolete("The mechanism that this class uses to specify type names is non-standard. Register the tags explicitly instead of using this convention.")] internal sealed class TypeNameInTagNodeTypeResolver : INodeTypeResolver { bool INodeTypeResolver.Resolve(NodeEvent? nodeEvent, ref Type currentType) { if (nodeEvent != null && !nodeEvent.Tag.IsEmpty) { Type type = Type.GetType(nodeEvent.Tag.Value.Substring(1), throwOnError: false); if (type != null) { currentType = type; return true; } } return false; } } internal sealed class YamlConvertibleTypeResolver : INodeTypeResolver { public bool Resolve(NodeEvent? nodeEvent, ref Type currentType) { return typeof(IYamlConvertible).IsAssignableFrom(currentType); } } internal sealed class YamlSerializableTypeResolver : INodeTypeResolver { public bool Resolve(NodeEvent? nodeEvent, ref Type currentType) { return typeof(IYamlSerializable).IsAssignableFrom(currentType); } } } namespace YamlDotNet.Serialization.NodeDeserializers { internal sealed class ArrayNodeDeserializer : INodeDeserializer { private sealed class ArrayList : IList, ICollection, IEnumerable { private object?[] data; public bool IsFixedSize => false; public bool IsReadOnly => false; public object? this[int index] { get { return data[index]; } set { data[index] = value; } } public int Count { get; private set; } public bool IsSynchronized => false; public object SyncRoot => data; public ArrayList() { Clear(); } public int Add(object? value) { if (Count == data.Length) { Array.Resize(ref data, data.Length * 2); } data[Count] = value; return Count++; } public void Clear() { data = new object[10]; Count = 0; } bool IList.Contains(object? value) { throw new NotSupportedException(); } int IList.IndexOf(object? value) { throw new NotSupportedException(); } void IList.Insert(int index, object? value) { throw new NotSupportedException(); } void IList.Remove(object? value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } public void CopyTo(Array array, int index) { Array.Copy(data, 0, array, index, Count); } public IEnumerator GetEnumerator() { int i = 0; while (i < Count) { yield return data[i]; int num = i + 1; i = num; } } } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { if (!expectedType.IsArray) { value = false; return false; } Type? elementType = expectedType.GetElementType(); ArrayList arrayList = new ArrayList(); CollectionNodeDeserializer.DeserializeHelper(elementType, parser, nestedObjectDeserializer, arrayList, canUpdate: true); Array array = Array.CreateInstance(elementType, arrayList.Count); arrayList.CopyTo(array, 0); value = array; return true; } } internal abstract class CollectionDeserializer { protected static void DeserializeHelper(Type tItem, IParser parser, Func nestedObjectDeserializer, IList result, bool canUpdate, IObjectFactory objectFactory) { IList result2 = result; parser.Consume(); SequenceEnd @event; while (!parser.TryConsume(out @event)) { ParsingEvent current = parser.Current; object obj = nestedObjectDeserializer(parser, tItem); if (obj is IValuePromise valuePromise) { if (!canUpdate) { Mark start = current?.Start ?? Mark.Empty; Mark end = current?.End ?? Mark.Empty; throw new ForwardAnchorNotSupportedException(in start, in end, "Forward alias references are not allowed because this type does not implement IList<>"); } int index = result2.Add(objectFactory.CreatePrimitive(tItem)); valuePromise.ValueAvailable += delegate(object? v) { result2[index] = v; }; } else { result2.Add(obj); } } } } internal sealed class CollectionNodeDeserializer : INodeDeserializer { private readonly IObjectFactory objectFactory; public CollectionNodeDeserializer(IObjectFactory objectFactory) { this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { bool canUpdate = true; Type implementedGenericInterface = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(ICollection<>)); Type type; IList list; if (implementedGenericInterface != null) { type = implementedGenericInterface.GetGenericArguments()[0]; value = objectFactory.Create(expectedType); list = value as IList; if (list == null) { canUpdate = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(IList<>)) != null; list = (IList)Activator.CreateInstance(typeof(GenericCollectionToNonGenericAdapter<>).MakeGenericType(type), value); } } else { if (!typeof(IList).IsAssignableFrom(expectedType)) { value = null; return false; } type = typeof(object); value = objectFactory.Create(expectedType); list = (IList)value; } DeserializeHelper(type, parser, nestedObjectDeserializer, list, canUpdate); return true; } internal static void DeserializeHelper(Type tItem, IParser parser, Func nestedObjectDeserializer, IList result, bool canUpdate) { IList result2 = result; Type tItem2 = tItem; parser.Consume(); SequenceEnd @event; while (!parser.TryConsume(out @event)) { ParsingEvent current = parser.Current; object obj = nestedObjectDeserializer(parser, tItem2); if (obj is IValuePromise valuePromise) { if (!canUpdate) { Mark start = current?.Start ?? Mark.Empty; Mark end = current?.End ?? Mark.Empty; throw new ForwardAnchorNotSupportedException(in start, in end, "Forward alias references are not allowed because this type does not implement IList<>"); } int index = result2.Add(tItem2.IsValueType() ? Activator.CreateInstance(tItem2) : null); valuePromise.ValueAvailable += delegate(object? v) { result2[index] = YamlDotNet.Serialization.Utilities.TypeConverter.ChangeType(v, tItem2); }; } else { result2.Add(YamlDotNet.Serialization.Utilities.TypeConverter.ChangeType(obj, tItem2)); } } } } internal abstract class DictionaryDeserializer { private readonly bool duplicateKeyChecking; public DictionaryDeserializer(bool duplicateKeyChecking) { this.duplicateKeyChecking = duplicateKeyChecking; } private void TryAssign(IDictionary result, object key, object value, MappingStart propertyName) { if (duplicateKeyChecking && result.Contains(key)) { Mark start = propertyName.Start; Mark end = propertyName.End; throw new YamlException(in start, in end, $"Encountered duplicate key {key}"); } result[key] = value; } protected virtual void Deserialize(Type tKey, Type tValue, IParser parser, Func nestedObjectDeserializer, IDictionary result) { IDictionary result2 = result; MappingStart property = parser.Consume(); MappingEnd @event; while (!parser.TryConsume(out @event)) { object key = nestedObjectDeserializer(parser, tKey); object value = nestedObjectDeserializer(parser, tValue); IValuePromise valuePromise = value as IValuePromise; if (key is IValuePromise valuePromise2) { if (valuePromise == null) { valuePromise2.ValueAvailable += delegate(object? v) { result2[v] = value; }; continue; } bool hasFirstPart = false; valuePromise2.ValueAvailable += delegate(object? v) { if (hasFirstPart) { TryAssign(result2, v, value, property); } else { key = v; hasFirstPart = true; } }; valuePromise.ValueAvailable += delegate(object? v) { if (hasFirstPart) { TryAssign(result2, key, v, property); } else { value = v; hasFirstPart = true; } }; continue; } if (key == null) { throw new ArgumentException("Empty key names are not supported yet.", "key"); } if (valuePromise == null) { TryAssign(result2, key, value, property); continue; } valuePromise.ValueAvailable += delegate(object? v) { result2[key] = v; }; } } } internal class DictionaryNodeDeserializer : DictionaryDeserializer, INodeDeserializer { private readonly IObjectFactory objectFactory; public DictionaryNodeDeserializer(IObjectFactory objectFactory, bool duplicateKeyChecking) : base(duplicateKeyChecking) { this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { Type implementedGenericInterface = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(IDictionary<, >)); Type type; Type type2; IDictionary dictionary; if (implementedGenericInterface != null) { Type[] genericArguments = implementedGenericInterface.GetGenericArguments(); type = genericArguments[0]; type2 = genericArguments[1]; value = objectFactory.Create(expectedType); dictionary = value as IDictionary; if (dictionary == null) { dictionary = (IDictionary)Activator.CreateInstance(typeof(GenericDictionaryToNonGenericAdapter<, >).MakeGenericType(type, type2), value); } } else { if (!typeof(IDictionary).IsAssignableFrom(expectedType)) { value = null; return false; } type = typeof(object); type2 = typeof(object); value = objectFactory.Create(expectedType); dictionary = (IDictionary)value; } Deserialize(type, type2, parser, nestedObjectDeserializer, dictionary); return true; } } internal sealed class EnumerableNodeDeserializer : INodeDeserializer { public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { Type type; if (expectedType == typeof(IEnumerable)) { type = typeof(object); } else { Type implementedGenericInterface = ReflectionUtility.GetImplementedGenericInterface(expectedType, typeof(IEnumerable<>)); if (implementedGenericInterface != expectedType) { value = null; return false; } type = implementedGenericInterface.GetGenericArguments()[0]; } Type arg = typeof(List<>).MakeGenericType(type); value = nestedObjectDeserializer(parser, arg); return true; } } internal sealed class NullNodeDeserializer : INodeDeserializer { public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { value = null; if (parser.Accept(out var @event) && NodeIsNull(@event)) { parser.SkipThisAndNestedEvents(); return true; } return false; } private bool NodeIsNull(NodeEvent nodeEvent) { if (nodeEvent.Tag == "tag:yaml.org,2002:null") { return true; } if (nodeEvent is YamlDotNet.Core.Events.Scalar scalar && scalar.Style == ScalarStyle.Plain && !scalar.IsKey) { string value = scalar.Value; switch (value) { default: return value == "NULL"; case "": case "~": case "null": case "Null": return true; } } return false; } } internal sealed class ObjectNodeDeserializer : INodeDeserializer { private readonly IObjectFactory objectFactory; private readonly ITypeInspector typeDescriptor; private readonly bool ignoreUnmatched; private readonly bool duplicateKeyChecking; private readonly ITypeConverter typeConverter; public ObjectNodeDeserializer(IObjectFactory objectFactory, ITypeInspector typeDescriptor, bool ignoreUnmatched, bool duplicateKeyChecking, ITypeConverter typeConverter) { this.objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); this.typeDescriptor = typeDescriptor ?? throw new ArgumentNullException("typeDescriptor"); this.ignoreUnmatched = ignoreUnmatched; this.duplicateKeyChecking = duplicateKeyChecking; this.typeConverter = typeConverter ?? throw new ArgumentNullException("typeConverter"); } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { if (!parser.TryConsume(out var _)) { value = null; return false; } Type type = Nullable.GetUnderlyingType(expectedType) ?? expectedType; value = objectFactory.Create(type); HashSet hashSet = new HashSet(StringComparer.Ordinal); MappingEnd event2; while (!parser.TryConsume(out event2)) { YamlDotNet.Core.Events.Scalar scalar = parser.Consume(); if (duplicateKeyChecking && !hashSet.Add(scalar.Value)) { Mark start = scalar.Start; Mark end = scalar.End; throw new YamlException(in start, in end, "Encountered duplicate key " + scalar.Value); } try { IPropertyDescriptor property = typeDescriptor.GetProperty(type, null, scalar.Value, ignoreUnmatched); if (property == null) { parser.SkipThisAndNestedEvents(); continue; } object obj = nestedObjectDeserializer(parser, property.Type); if (obj is IValuePromise valuePromise) { object valueRef = value; valuePromise.ValueAvailable += delegate(object? v) { object value3 = typeConverter.ChangeType(v, property.Type); property.Write(valueRef, value3); }; } else { object value2 = typeConverter.ChangeType(obj, property.Type); property.Write(value, value2); } } catch (SerializationException ex) { Mark start = scalar.Start; Mark end = scalar.End; throw new YamlException(in start, in end, ex.Message); } catch (YamlException) { throw; } catch (Exception innerException) { Mark start = scalar.Start; Mark end = scalar.End; throw new YamlException(in start, in end, "Exception during deserialization", innerException); } } return true; } } internal sealed class ScalarNodeDeserializer : INodeDeserializer { private const string BooleanTruePattern = "^(true|y|yes|on)$"; private const string BooleanFalsePattern = "^(false|n|no|off)$"; private readonly bool attemptUnknownTypeDeserialization; private readonly ITypeConverter typeConverter; public ScalarNodeDeserializer(bool attemptUnknownTypeDeserialization, ITypeConverter typeConverter) { this.attemptUnknownTypeDeserialization = attemptUnknownTypeDeserialization; this.typeConverter = typeConverter ?? throw new ArgumentNullException("typeConverter"); } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { if (!parser.TryConsume(out var @event)) { value = null; return false; } Type type = Nullable.GetUnderlyingType(expectedType) ?? expectedType; if (type.IsEnum()) { value = Enum.Parse(type, @event.Value, ignoreCase: true); return true; } TypeCode typeCode = type.GetTypeCode(); switch (typeCode) { case TypeCode.Boolean: value = DeserializeBooleanHelper(@event.Value); break; case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: value = DeserializeIntegerHelper(typeCode, @event.Value); break; case TypeCode.Single: value = float.Parse(@event.Value, YamlFormatter.NumberFormat); break; case TypeCode.Double: value = double.Parse(@event.Value, YamlFormatter.NumberFormat); break; case TypeCode.Decimal: value = decimal.Parse(@event.Value, YamlFormatter.NumberFormat); break; case TypeCode.String: value = @event.Value; break; case TypeCode.Char: value = @event.Value[0]; break; case TypeCode.DateTime: value = DateTime.Parse(@event.Value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind); break; default: if (expectedType == typeof(object)) { if (!@event.IsKey && attemptUnknownTypeDeserialization) { value = AttemptUnknownTypeDeserialization(@event); } else { value = @event.Value; } } else { value = typeConverter.ChangeType(@event.Value, expectedType); } break; } return true; } private object DeserializeBooleanHelper(string value) { bool flag; if (Regex.IsMatch(value, "^(true|y|yes|on)$", RegexOptions.IgnoreCase)) { flag = true; } else { if (!Regex.IsMatch(value, "^(false|n|no|off)$", RegexOptions.IgnoreCase)) { throw new FormatException("The value \"" + value + "\" is not a valid YAML Boolean"); } flag = false; } return flag; } private static object DeserializeIntegerHelper(TypeCode typeCode, string value) { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; int i = 0; bool flag = false; ulong num = 0uL; if (value[0] == '-') { i++; flag = true; } else if (value[0] == '+') { i++; } if (value[i] == '0') { int num2; if (i == value.Length - 1) { num2 = 10; num = 0uL; } else { i++; if (value[i] == 'b') { num2 = 2; i++; } else if (value[i] == 'x') { num2 = 16; i++; } else { num2 = 8; } } for (; i < value.Length; i++) { if (value[i] != '_') { builder.Append(value[i]); } } switch (num2) { case 2: case 8: num = Convert.ToUInt64(builder.ToString(), num2); break; case 16: num = ulong.Parse(builder.ToString(), NumberStyles.HexNumber, YamlFormatter.NumberFormat); break; } } else { string[] array = value.Substring(i).Split(new char[1] { ':' }); num = 0uL; for (int j = 0; j < array.Length; j++) { num *= 60; num += ulong.Parse(array[j].Replace("_", "")); } } if (!flag) { return CastInteger(num, typeCode); } long number = ((num != 9223372036854775808uL) ? checked(-(long)num) : long.MinValue); return CastInteger(number, typeCode); } finally { ((IDisposable)builderWrapper).Dispose(); } } private static object CastInteger(long number, TypeCode typeCode) { return checked(typeCode switch { TypeCode.Byte => (byte)number, TypeCode.Int16 => (short)number, TypeCode.Int32 => (int)number, TypeCode.Int64 => number, TypeCode.SByte => (sbyte)number, TypeCode.UInt16 => (ushort)number, TypeCode.UInt32 => (uint)number, TypeCode.UInt64 => (ulong)number, _ => number, }); } private static object CastInteger(ulong number, TypeCode typeCode) { return checked(typeCode switch { TypeCode.Byte => (byte)number, TypeCode.Int16 => (short)number, TypeCode.Int32 => (int)number, TypeCode.Int64 => (long)number, TypeCode.SByte => (sbyte)number, TypeCode.UInt16 => (ushort)number, TypeCode.UInt32 => (uint)number, TypeCode.UInt64 => number, _ => number, }); } private static object? AttemptUnknownTypeDeserialization(YamlDotNet.Core.Events.Scalar value) { if (value.Style == ScalarStyle.SingleQuoted || value.Style == ScalarStyle.DoubleQuoted || value.Style == ScalarStyle.Folded) { return value.Value; } string v = value.Value; switch (v) { case "": case "~": case "null": case "Null": case "NULL": return null; case "true": case "True": case "TRUE": return true; case "false": case "False": case "FALSE": return false; default: { object value2; if (Regex.IsMatch(v, "0x[0-9a-fA-F]+")) { if (!TryAndSwallow(() => Convert.ToByte(v, 16), out value2) && !TryAndSwallow(() => Convert.ToInt16(v, 16), out value2) && !TryAndSwallow(() => Convert.ToInt32(v, 16), out value2) && !TryAndSwallow(() => Convert.ToInt64(v, 16), out value2) && !TryAndSwallow(() => Convert.ToUInt64(v, 16), out value2)) { return v; } } else if (Regex.IsMatch(v, "0o[0-9a-fA-F]+")) { if (!TryAndSwallow(() => Convert.ToByte(v, 8), out value2) && !TryAndSwallow(() => Convert.ToInt16(v, 8), out value2) && !TryAndSwallow(() => Convert.ToInt32(v, 8), out value2) && !TryAndSwallow(() => Convert.ToInt64(v, 8), out value2) && !TryAndSwallow(() => Convert.ToUInt64(v, 8), out value2)) { return v; } } else { if (!Regex.IsMatch(v, "[-+]?(\\.[0-9]+|[0-9]+(\\.[0-9]*)?)([eE][-+]?[0-9]+)?")) { if (Regex.IsMatch(v, "^[-+]?(\\.inf|\\.Inf|\\.INF)$")) { if (v.StartsWith("-")) { return float.NegativeInfinity; } return float.PositiveInfinity; } if (Regex.IsMatch(v, "^(\\.nan|\\.NaN|\\.NAN)$")) { return float.NaN; } return v; } if (!TryAndSwallow(() => byte.Parse(v), out value2) && !TryAndSwallow(() => short.Parse(v), out value2) && !TryAndSwallow(() => int.Parse(v), out value2) && !TryAndSwallow(() => long.Parse(v), out value2) && !TryAndSwallow(() => ulong.Parse(v), out value2) && !TryAndSwallow(() => float.Parse(v), out value2) && !TryAndSwallow(() => double.Parse(v), out value2)) { return v; } } return value2; } } } private static bool TryAndSwallow(Func attempt, out object? value) { try { value = attempt(); return true; } catch { value = null; return false; } } } internal sealed class StaticArrayNodeDeserializer : INodeDeserializer { private sealed class ArrayList : IList, ICollection, IEnumerable { private object?[] data; public bool IsFixedSize => false; public bool IsReadOnly => false; public object? this[int index] { get { return data[index]; } set { data[index] = value; } } public int Count { get; private set; } public bool IsSynchronized => false; public object SyncRoot => data; public ArrayList() { Clear(); } public int Add(object? value) { if (Count == data.Length) { Array.Resize(ref data, data.Length * 2); } data[Count] = value; return Count++; } public void Clear() { data = new object[10]; Count = 0; } bool IList.Contains(object? value) { throw new NotSupportedException(); } int IList.IndexOf(object? value) { throw new NotSupportedException(); } void IList.Insert(int index, object? value) { throw new NotSupportedException(); } void IList.Remove(object? value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } public void CopyTo(Array array, int index) { Array.Copy(data, 0, array, index, Count); } public IEnumerator GetEnumerator() { int i = 0; while (i < Count) { yield return data[i]; int num = i + 1; i = num; } } } private readonly StaticObjectFactory factory; public StaticArrayNodeDeserializer(StaticObjectFactory factory) { this.factory = factory ?? throw new ArgumentNullException("factory"); } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { if (!factory.IsArray(expectedType)) { value = false; return false; } Type valueType = factory.GetValueType(expectedType); ArrayList arrayList = new ArrayList(); StaticCollectionNodeDeserializer.DeserializeHelper(valueType, parser, nestedObjectDeserializer, arrayList, factory); Array array = factory.CreateArray(expectedType, arrayList.Count); arrayList.CopyTo(array, 0); value = array; return true; } } internal sealed class StaticCollectionNodeDeserializer : INodeDeserializer { private readonly StaticObjectFactory factory; public StaticCollectionNodeDeserializer(StaticObjectFactory factory) { this.factory = factory ?? throw new ArgumentNullException("factory"); } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { if (!factory.IsList(expectedType)) { value = null; return false; } DeserializeHelper(result: (IList)(value = factory.Create(expectedType) as IList), tItem: factory.GetValueType(expectedType), parser: parser, nestedObjectDeserializer: nestedObjectDeserializer, factory: factory); return true; } internal static void DeserializeHelper(Type tItem, IParser parser, Func nestedObjectDeserializer, IList result, IObjectFactory factory) { IList result2 = result; parser.Consume(); SequenceEnd @event; while (!parser.TryConsume(out @event)) { _ = parser.Current; object obj = nestedObjectDeserializer(parser, tItem); if (obj is IValuePromise valuePromise) { int index = result2.Add(factory.CreatePrimitive(tItem)); valuePromise.ValueAvailable += delegate(object? v) { result2[index] = v; }; } else { result2.Add(obj); } } } } internal class StaticDictionaryNodeDeserializer : DictionaryDeserializer, INodeDeserializer { private readonly StaticObjectFactory _objectFactory; public StaticDictionaryNodeDeserializer(StaticObjectFactory objectFactory, bool duplicateKeyChecking) : base(duplicateKeyChecking) { _objectFactory = objectFactory ?? throw new ArgumentNullException("objectFactory"); } public bool Deserialize(IParser reader, Type expectedType, Func nestedObjectDeserializer, out object? value) { if (_objectFactory.IsDictionary(expectedType)) { if (!(_objectFactory.Create(expectedType) is IDictionary dictionary)) { value = null; return false; } Type keyType = _objectFactory.GetKeyType(expectedType); Type valueType = _objectFactory.GetValueType(expectedType); value = dictionary; base.Deserialize(keyType, valueType, reader, nestedObjectDeserializer, dictionary); return true; } value = null; return false; } } internal sealed class TypeConverterNodeDeserializer : INodeDeserializer { private readonly IEnumerable converters; public TypeConverterNodeDeserializer(IEnumerable converters) { this.converters = converters ?? throw new ArgumentNullException("converters"); } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { Type expectedType2 = expectedType; IYamlTypeConverter yamlTypeConverter = converters.FirstOrDefault((IYamlTypeConverter c) => c.Accepts(expectedType2)); if (yamlTypeConverter == null) { value = null; return false; } value = yamlTypeConverter.ReadYaml(parser, expectedType2); return true; } } internal sealed class YamlConvertibleNodeDeserializer : INodeDeserializer { private readonly IObjectFactory objectFactory; public YamlConvertibleNodeDeserializer(IObjectFactory objectFactory) { this.objectFactory = objectFactory; } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { Func nestedObjectDeserializer2 = nestedObjectDeserializer; IParser parser2 = parser; if (typeof(IYamlConvertible).IsAssignableFrom(expectedType)) { IYamlConvertible yamlConvertible = (IYamlConvertible)objectFactory.Create(expectedType); yamlConvertible.Read(parser2, expectedType, (Type type) => nestedObjectDeserializer2(parser2, type)); value = yamlConvertible; return true; } value = null; return false; } } internal sealed class YamlSerializableNodeDeserializer : INodeDeserializer { private readonly IObjectFactory objectFactory; public YamlSerializableNodeDeserializer(IObjectFactory objectFactory) { this.objectFactory = objectFactory; } public bool Deserialize(IParser parser, Type expectedType, Func nestedObjectDeserializer, out object? value) { if (typeof(IYamlSerializable).IsAssignableFrom(expectedType)) { IYamlSerializable yamlSerializable = (IYamlSerializable)objectFactory.Create(expectedType); yamlSerializable.ReadYaml(parser); value = yamlSerializable; return true; } value = null; return false; } } } namespace YamlDotNet.Serialization.NamingConventions { internal sealed class CamelCaseNamingConvention : INamingConvention { public static readonly INamingConvention Instance = new CamelCaseNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public CamelCaseNamingConvention() { } public string Apply(string value) { return value.ToCamelCase(); } } internal sealed class HyphenatedNamingConvention : INamingConvention { public static readonly INamingConvention Instance = new HyphenatedNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public HyphenatedNamingConvention() { } public string Apply(string value) { return value.FromCamelCase("-"); } } internal sealed class LowerCaseNamingConvention : INamingConvention { public static readonly INamingConvention Instance = new LowerCaseNamingConvention(); private LowerCaseNamingConvention() { } public string Apply(string value) { return value.ToCamelCase().ToLower(); } } internal sealed class NullNamingConvention : INamingConvention { public static readonly INamingConvention Instance = new NullNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public NullNamingConvention() { } public string Apply(string value) { return value; } } internal sealed class PascalCaseNamingConvention : INamingConvention { public static readonly INamingConvention Instance = new PascalCaseNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public PascalCaseNamingConvention() { } public string Apply(string value) { return value.ToPascalCase(); } } internal sealed class UnderscoredNamingConvention : INamingConvention { public static readonly INamingConvention Instance = new UnderscoredNamingConvention(); [Obsolete("Use the Instance static field instead of creating new instances")] public UnderscoredNamingConvention() { } public string Apply(string value) { return value.FromCamelCase("_"); } } } namespace YamlDotNet.Serialization.EventEmitters { internal abstract class ChainedEventEmitter : IEventEmitter { protected readonly IEventEmitter nextEmitter; protected ChainedEventEmitter(IEventEmitter nextEmitter) { this.nextEmitter = nextEmitter ?? throw new ArgumentNullException("nextEmitter"); } public virtual void Emit(AliasEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } public virtual void Emit(ScalarEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } public virtual void Emit(MappingStartEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } public virtual void Emit(MappingEndEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } public virtual void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } public virtual void Emit(SequenceEndEventInfo eventInfo, IEmitter emitter) { nextEmitter.Emit(eventInfo, emitter); } } internal sealed class JsonEventEmitter : ChainedEventEmitter { public JsonEventEmitter(IEventEmitter nextEmitter) : base(nextEmitter) { } public override void Emit(AliasEventInfo eventInfo, IEmitter emitter) { eventInfo.NeedsExpansion = true; } public override void Emit(ScalarEventInfo eventInfo, IEmitter emitter) { eventInfo.IsPlainImplicit = true; eventInfo.Style = ScalarStyle.Plain; object value = eventInfo.Source.Value; if (value == null) { eventInfo.RenderedValue = "null"; } else { TypeCode typeCode = eventInfo.Source.Type.GetTypeCode(); switch (typeCode) { case TypeCode.Boolean: eventInfo.RenderedValue = YamlFormatter.FormatBoolean(value); break; case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: if (eventInfo.Source.Type.IsEnum()) { eventInfo.RenderedValue = value.ToString(); eventInfo.Style = ScalarStyle.DoubleQuoted; } else { eventInfo.RenderedValue = YamlFormatter.FormatNumber(value); } break; case TypeCode.Single: case TypeCode.Double: case TypeCode.Decimal: eventInfo.RenderedValue = YamlFormatter.FormatNumber(value); break; case TypeCode.Char: case TypeCode.String: eventInfo.RenderedValue = value.ToString(); eventInfo.Style = ScalarStyle.DoubleQuoted; break; case TypeCode.DateTime: eventInfo.RenderedValue = YamlFormatter.FormatDateTime(value); break; case TypeCode.Empty: eventInfo.RenderedValue = "null"; break; default: if (eventInfo.Source.Type == typeof(TimeSpan)) { eventInfo.RenderedValue = YamlFormatter.FormatTimeSpan(value); break; } throw new NotSupportedException($"TypeCode.{typeCode} is not supported."); } } base.Emit(eventInfo, emitter); } public override void Emit(MappingStartEventInfo eventInfo, IEmitter emitter) { eventInfo.Style = MappingStyle.Flow; base.Emit(eventInfo, emitter); } public override void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) { eventInfo.Style = SequenceStyle.Flow; base.Emit(eventInfo, emitter); } } internal sealed class TypeAssigningEventEmitter : ChainedEventEmitter { private readonly bool requireTagWhenStaticAndActualTypesAreDifferent; private readonly IDictionary tagMappings; private readonly bool quoteNecessaryStrings; private readonly Regex? isSpecialStringValue_Regex; private static readonly string SpecialStrings_Pattern = "^(null|Null|NULL|\\~|true|True|TRUE|false|False|FALSE|[-+]?[0-9]+|0o[0-7]+|0x[0-9a-fA-F]+|[-+]?(\\.[0-9]+|[0-9]+(\\.[0-9]*)?)([eE][-+]?[0-9]+)?|[-+]?(\\.inf|\\.Inf|\\.INF)|\\.nan|\\.NaN|\\.NAN)$"; private static readonly string CombinedYaml1_1SpecialStrings_Pattern = "^(null|Null|NULL|\\~|true|True|TRUE|false|False|FALSE|y|Y|yes|Yes|YES|n|N|no|No|NO|on|On|ON|off|Off|OFF|[-+]?0b[0-1_]+|[-+]?0o?[0-7_]+|[-+]?(0|[1-9][0-9_]*)|[-+]?0x[0-9a-fA-F_]+|[-+]?[1-9][0-9_]*(:[0-5]?[0-9])+|[-+]?([0-9][0-9_]*)?\\.[0-9_]*([eE][-+][0-9]+)?|[-+]?[0-9][0-9_]*(:[0-5]?[0-9])+\\.[0-9_]*|[-+]?\\.(inf|Inf|INF)|\\.(nan|NaN|NAN))$"; public TypeAssigningEventEmitter(IEventEmitter nextEmitter, bool requireTagWhenStaticAndActualTypesAreDifferent, IDictionary tagMappings, bool quoteNecessaryStrings, bool quoteYaml1_1Strings) : this(nextEmitter, requireTagWhenStaticAndActualTypesAreDifferent, tagMappings) { this.quoteNecessaryStrings = quoteNecessaryStrings; isSpecialStringValue_Regex = new Regex(quoteYaml1_1Strings ? CombinedYaml1_1SpecialStrings_Pattern : SpecialStrings_Pattern, RegexOptions.Compiled); } public TypeAssigningEventEmitter(IEventEmitter nextEmitter, bool requireTagWhenStaticAndActualTypesAreDifferent, IDictionary tagMappings, bool quoteNecessaryStrings) : this(nextEmitter, requireTagWhenStaticAndActualTypesAreDifferent, tagMappings) { this.quoteNecessaryStrings = quoteNecessaryStrings; isSpecialStringValue_Regex = new Regex(SpecialStrings_Pattern, RegexOptions.Compiled); } public TypeAssigningEventEmitter(IEventEmitter nextEmitter, bool requireTagWhenStaticAndActualTypesAreDifferent, IDictionary tagMappings) : base(nextEmitter) { this.requireTagWhenStaticAndActualTypesAreDifferent = requireTagWhenStaticAndActualTypesAreDifferent; this.tagMappings = tagMappings ?? throw new ArgumentNullException("tagMappings"); } public override void Emit(ScalarEventInfo eventInfo, IEmitter emitter) { ScalarStyle style = ScalarStyle.Plain; object value = eventInfo.Source.Value; if (value == null) { eventInfo.Tag = JsonSchema.Tags.Null; eventInfo.RenderedValue = ""; } else { TypeCode typeCode = eventInfo.Source.Type.GetTypeCode(); switch (typeCode) { case TypeCode.Boolean: eventInfo.Tag = JsonSchema.Tags.Bool; eventInfo.RenderedValue = YamlFormatter.FormatBoolean(value); break; case TypeCode.SByte: case TypeCode.Byte: case TypeCode.Int16: case TypeCode.UInt16: case TypeCode.Int32: case TypeCode.UInt32: case TypeCode.Int64: case TypeCode.UInt64: if (eventInfo.Source.Type.IsEnum) { eventInfo.Tag = FailsafeSchema.Tags.Str; eventInfo.RenderedValue = value.ToString(); style = ((quoteNecessaryStrings && IsSpecialStringValue(eventInfo.RenderedValue)) ? ScalarStyle.DoubleQuoted : ScalarStyle.Any); } else { eventInfo.Tag = JsonSchema.Tags.Int; eventInfo.RenderedValue = YamlFormatter.FormatNumber(value); } break; case TypeCode.Single: eventInfo.Tag = JsonSchema.Tags.Float; eventInfo.RenderedValue = YamlFormatter.FormatNumber((float)value); break; case TypeCode.Double: eventInfo.Tag = JsonSchema.Tags.Float; eventInfo.RenderedValue = YamlFormatter.FormatNumber((double)value); break; case TypeCode.Decimal: eventInfo.Tag = JsonSchema.Tags.Float; eventInfo.RenderedValue = YamlFormatter.FormatNumber(value); break; case TypeCode.Char: case TypeCode.String: eventInfo.Tag = FailsafeSchema.Tags.Str; eventInfo.RenderedValue = value.ToString(); style = ((quoteNecessaryStrings && IsSpecialStringValue(eventInfo.RenderedValue)) ? ScalarStyle.DoubleQuoted : ScalarStyle.Any); break; case TypeCode.DateTime: eventInfo.Tag = DefaultSchema.Tags.Timestamp; eventInfo.RenderedValue = YamlFormatter.FormatDateTime(value); break; case TypeCode.Empty: eventInfo.Tag = JsonSchema.Tags.Null; eventInfo.RenderedValue = ""; break; default: if (eventInfo.Source.Type == typeof(TimeSpan)) { eventInfo.RenderedValue = YamlFormatter.FormatTimeSpan(value); break; } throw new NotSupportedException($"TypeCode.{typeCode} is not supported."); } } eventInfo.IsPlainImplicit = true; if (eventInfo.Style == ScalarStyle.Any) { eventInfo.Style = style; } base.Emit(eventInfo, emitter); } public override void Emit(MappingStartEventInfo eventInfo, IEmitter emitter) { AssignTypeIfNeeded(eventInfo); base.Emit(eventInfo, emitter); } public override void Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) { AssignTypeIfNeeded(eventInfo); base.Emit(eventInfo, emitter); } private void AssignTypeIfNeeded(ObjectEventInfo eventInfo) { if (tagMappings.TryGetValue(eventInfo.Source.Type, out var value)) { eventInfo.Tag = value; } else if (requireTagWhenStaticAndActualTypesAreDifferent && eventInfo.Source.Value != null && eventInfo.Source.Type != eventInfo.Source.StaticType) { throw new YamlException("Cannot serialize type '" + eventInfo.Source.Type.FullName + "' where a '" + eventInfo.Source.StaticType.FullName + "' was expected because no tag mapping has been registered for '" + eventInfo.Source.Type.FullName + "', which means that it won't be possible to deserialize the document.\nRegister a tag mapping using the SerializerBuilder.WithTagMapping method.\n\nE.g: builder.WithTagMapping(\"!" + eventInfo.Source.Type.Name + "\", typeof(" + eventInfo.Source.Type.FullName + "));"); } } private bool IsSpecialStringValue(string value) { if (value.Trim() == string.Empty) { return true; } return isSpecialStringValue_Regex?.IsMatch(value) ?? false; } } internal sealed class WriterEventEmitter : IEventEmitter { void IEventEmitter.Emit(AliasEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new YamlDotNet.Core.Events.AnchorAlias(eventInfo.Alias)); } void IEventEmitter.Emit(ScalarEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new YamlDotNet.Core.Events.Scalar(eventInfo.Anchor, eventInfo.Tag, eventInfo.RenderedValue, eventInfo.Style, eventInfo.IsPlainImplicit, eventInfo.IsQuotedImplicit)); } void IEventEmitter.Emit(MappingStartEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new MappingStart(eventInfo.Anchor, eventInfo.Tag, eventInfo.IsImplicit, eventInfo.Style)); } void IEventEmitter.Emit(MappingEndEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new MappingEnd()); } void IEventEmitter.Emit(SequenceStartEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new SequenceStart(eventInfo.Anchor, eventInfo.Tag, eventInfo.IsImplicit, eventInfo.Style)); } void IEventEmitter.Emit(SequenceEndEventInfo eventInfo, IEmitter emitter) { emitter.Emit(new SequenceEnd()); } } } namespace YamlDotNet.Serialization.Converters { internal class DateTimeConverter : IYamlTypeConverter { private readonly DateTimeKind kind; private readonly IFormatProvider provider; private readonly bool doubleQuotes; private readonly string[] formats; public DateTimeConverter(DateTimeKind kind = DateTimeKind.Utc, IFormatProvider? provider = null, bool doubleQuotes = false, params string[] formats) { this.kind = ((kind == DateTimeKind.Unspecified) ? DateTimeKind.Utc : kind); this.provider = provider ?? CultureInfo.InvariantCulture; this.doubleQuotes = doubleQuotes; this.formats = formats.DefaultIfEmpty("G").ToArray(); } public bool Accepts(Type type) { return type == typeof(DateTime); } public object ReadYaml(IParser parser, Type type) { return EnsureDateTimeKind(DateTime.ParseExact(parser.Consume().Value, style: (kind == DateTimeKind.Local) ? DateTimeStyles.AssumeLocal : DateTimeStyles.AssumeUniversal, formats: formats, provider: provider), kind); } public void WriteYaml(IEmitter emitter, object? value, Type type) { DateTime dateTime = (DateTime)value; string value2 = ((kind == DateTimeKind.Local) ? dateTime.ToLocalTime() : dateTime.ToUniversalTime()).ToString(formats.First(), provider); emitter.Emit(new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, value2, doubleQuotes ? ScalarStyle.DoubleQuoted : ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: false)); } private static DateTime EnsureDateTimeKind(DateTime dt, DateTimeKind kind) { if (dt.Kind == DateTimeKind.Local && kind == DateTimeKind.Utc) { return dt.ToUniversalTime(); } if (dt.Kind == DateTimeKind.Utc && kind == DateTimeKind.Local) { return dt.ToLocalTime(); } return dt; } } internal class GuidConverter : IYamlTypeConverter { private readonly bool jsonCompatible; public GuidConverter(bool jsonCompatible) { this.jsonCompatible = jsonCompatible; } public bool Accepts(Type type) { return type == typeof(Guid); } public object ReadYaml(IParser parser, Type type) { return new Guid(parser.Consume().Value); } public void WriteYaml(IEmitter emitter, object? value, Type type) { Guid guid = (Guid)value; emitter.Emit(new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, guid.ToString("D"), jsonCompatible ? ScalarStyle.DoubleQuoted : ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: false)); } } internal class SystemTypeConverter : IYamlTypeConverter { public bool Accepts(Type type) { return typeof(Type).IsAssignableFrom(type); } public object ReadYaml(IParser parser, Type type) { return Type.GetType(parser.Consume().Value, throwOnError: true); } public void WriteYaml(IEmitter emitter, object? value, Type type) { Type type2 = (Type)value; emitter.Emit(new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, type2.AssemblyQualifiedName, ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: false)); } } } namespace YamlDotNet.Serialization.BufferedDeserialization { internal interface ITypeDiscriminatingNodeDeserializerOptions { void AddTypeDiscriminator(ITypeDiscriminator discriminator); void AddKeyValueTypeDiscriminator(string discriminatorKey, IDictionary valueTypeMapping); void AddUniqueKeyTypeDiscriminator(IDictionary uniqueKeyTypeMapping); } internal class ParserBuffer : IParser { private readonly LinkedList buffer; private LinkedListNode? current; public ParsingEvent? Current => current?.Value; public ParserBuffer(IParser parserToBuffer, int maxDepth, int maxLength) { buffer = new LinkedList(); buffer.AddLast(parserToBuffer.Consume()); int num = 0; do { ParsingEvent parsingEvent = parserToBuffer.Consume(); num += parsingEvent.NestingIncrease; buffer.AddLast(parsingEvent); if (maxDepth > -1 && num > maxDepth) { throw new ArgumentOutOfRangeException("parserToBuffer", "Parser buffer exceeded max depth"); } if (maxLength > -1 && buffer.Count > maxLength) { throw new ArgumentOutOfRangeException("parserToBuffer", "Parser buffer exceeded max length"); } } while (num >= 0); current = buffer.First; } public bool MoveNext() { current = current?.Next; return current != null; } public void Reset() { current = buffer.First; } } internal class TypeDiscriminatingNodeDeserializer : INodeDeserializer { private readonly IList innerDeserializers; private readonly IList typeDiscriminators; private readonly int maxDepthToBuffer; private readonly int maxLengthToBuffer; public TypeDiscriminatingNodeDeserializer(IList innerDeserializers, IList typeDiscriminators, int maxDepthToBuffer, int maxLengthToBuffer) { this.innerDeserializers = innerDeserializers; this.typeDiscriminators = typeDiscriminators; this.maxDepthToBuffer = maxDepthToBuffer; this.maxLengthToBuffer = maxLengthToBuffer; } public bool Deserialize(IParser reader, Type expectedType, Func nestedObjectDeserializer, out object? value) { Type expectedType2 = expectedType; if (!reader.Accept(out var _)) { value = null; return false; } IEnumerable enumerable = typeDiscriminators.Where((ITypeDiscriminator t) => t.BaseType.IsAssignableFrom(expectedType2)); if (!enumerable.Any()) { value = null; return false; } Mark start = reader.Current.Start; Type expectedType3 = expectedType2; ParserBuffer parserBuffer; try { parserBuffer = new ParserBuffer(reader, maxDepthToBuffer, maxLengthToBuffer); } catch (Exception innerException) { Mark end = reader.Current.End; throw new YamlException(in start, in end, "Failed to buffer yaml node", innerException); } try { foreach (ITypeDiscriminator item in enumerable) { parserBuffer.Reset(); if (item.TryDiscriminate(parserBuffer, out Type suggestedType)) { expectedType3 = suggestedType; break; } } } catch (Exception innerException2) { Mark end = reader.Current.End; throw new YamlException(in start, in end, "Failed to discriminate type", innerException2); } parserBuffer.Reset(); foreach (INodeDeserializer innerDeserializer in innerDeserializers) { if (innerDeserializer.Deserialize(parserBuffer, expectedType3, nestedObjectDeserializer, out value)) { return true; } } value = null; return false; } } internal class TypeDiscriminatingNodeDeserializerOptions : ITypeDiscriminatingNodeDeserializerOptions { internal readonly List discriminators = new List(); public void AddTypeDiscriminator(ITypeDiscriminator discriminator) { discriminators.Add(discriminator); } public void AddKeyValueTypeDiscriminator(string discriminatorKey, IDictionary valueTypeMapping) { discriminators.Add(new KeyValueTypeDiscriminator(typeof(T), discriminatorKey, valueTypeMapping)); } public void AddUniqueKeyTypeDiscriminator(IDictionary uniqueKeyTypeMapping) { discriminators.Add(new UniqueKeyTypeDiscriminator(typeof(T), uniqueKeyTypeMapping)); } } } namespace YamlDotNet.Serialization.BufferedDeserialization.TypeDiscriminators { internal interface ITypeDiscriminator { Type BaseType { get; } bool TryDiscriminate(IParser buffer, out Type? suggestedType); } internal class KeyValueTypeDiscriminator : ITypeDiscriminator { private readonly string targetKey; private readonly IDictionary typeMapping; public Type BaseType { get; private set; } public KeyValueTypeDiscriminator(Type baseType, string targetKey, IDictionary typeMapping) { foreach (KeyValuePair item in typeMapping) { if (!baseType.IsAssignableFrom(item.Value)) { throw new ArgumentOutOfRangeException("typeMapping", $"{item.Value} is not a assignable to {baseType}"); } } BaseType = baseType; this.targetKey = targetKey; this.typeMapping = typeMapping; } public bool TryDiscriminate(IParser parser, out Type? suggestedType) { if (parser.TryFindMappingEntry((YamlDotNet.Core.Events.Scalar scalar) => targetKey == scalar.Value, out YamlDotNet.Core.Events.Scalar _, out ParsingEvent value) && value is YamlDotNet.Core.Events.Scalar scalar2 && typeMapping.TryGetValue(scalar2.Value, out Type value2)) { suggestedType = value2; return true; } suggestedType = null; return false; } } internal class UniqueKeyTypeDiscriminator : ITypeDiscriminator { private readonly IDictionary typeMapping; public Type BaseType { get; private set; } public UniqueKeyTypeDiscriminator(Type baseType, IDictionary typeMapping) { foreach (KeyValuePair item in typeMapping) { if (!baseType.IsAssignableFrom(item.Value)) { throw new ArgumentOutOfRangeException("typeMapping", $"{item.Value} is not a assignable to {baseType}"); } } BaseType = baseType; this.typeMapping = typeMapping; } public bool TryDiscriminate(IParser parser, out Type? suggestedType) { if (parser.TryFindMappingEntry((YamlDotNet.Core.Events.Scalar scalar) => typeMapping.ContainsKey(scalar.Value), out YamlDotNet.Core.Events.Scalar key, out ParsingEvent _)) { suggestedType = typeMapping[key.Value]; return true; } suggestedType = null; return false; } } } namespace YamlDotNet.RepresentationModel { internal class DocumentLoadingState { private readonly IDictionary anchors = new Dictionary(); private readonly IList nodesWithUnresolvedAliases = new List(); public void AddAnchor(YamlNode node) { if (node.Anchor.IsEmpty) { throw new ArgumentException("The specified node does not have an anchor"); } if (anchors.ContainsKey(node.Anchor)) { anchors[node.Anchor] = node; } else { anchors.Add(node.Anchor, node); } } public YamlNode GetNode(AnchorName anchor, Mark start, Mark end) { if (anchors.TryGetValue(anchor, out YamlNode value)) { return value; } throw new AnchorNotFoundException(in start, in end, $"The anchor '{anchor}' does not exists"); } public bool TryGetNode(AnchorName anchor, [NotNullWhen(true)] out YamlNode? node) { return anchors.TryGetValue(anchor, out node); } public void AddNodeWithUnresolvedAliases(YamlNode node) { nodesWithUnresolvedAliases.Add(node); } public void ResolveAliases() { foreach (YamlNode nodesWithUnresolvedAlias in nodesWithUnresolvedAliases) { nodesWithUnresolvedAlias.ResolveAliases(this); } } } internal class EmitterState { public HashSet EmittedAnchors { get; } = new HashSet(); } internal interface IYamlVisitor { void Visit(YamlStream stream); void Visit(YamlDocument document); void Visit(YamlScalarNode scalar); void Visit(YamlSequenceNode sequence); void Visit(YamlMappingNode mapping); } internal class LibYamlEventStream { private readonly IParser parser; public LibYamlEventStream(IParser iParser) { parser = iParser ?? throw new ArgumentNullException("iParser"); } public void WriteTo(TextWriter textWriter) { while (parser.MoveNext()) { ParsingEvent current = parser.Current; if (!(current is YamlDotNet.Core.Events.AnchorAlias anchorAlias)) { if (!(current is YamlDotNet.Core.Events.DocumentEnd documentEnd)) { if (!(current is YamlDotNet.Core.Events.DocumentStart documentStart)) { if (!(current is MappingEnd)) { if (!(current is MappingStart nodeEvent)) { if (!(current is YamlDotNet.Core.Events.Scalar scalar)) { if (!(current is SequenceEnd)) { if (!(current is SequenceStart nodeEvent2)) { if (!(current is YamlDotNet.Core.Events.StreamEnd)) { if (current is YamlDotNet.Core.Events.StreamStart) { textWriter.Write("+STR"); } } else { textWriter.Write("-STR"); } } else { textWriter.Write("+SEQ"); WriteAnchorAndTag(textWriter, nodeEvent2); } } else { textWriter.Write("-SEQ"); } } else { textWriter.Write("=VAL"); WriteAnchorAndTag(textWriter, scalar); switch (scalar.Style) { case ScalarStyle.DoubleQuoted: textWriter.Write(" \""); break; case ScalarStyle.SingleQuoted: textWriter.Write(" '"); break; case ScalarStyle.Folded: textWriter.Write(" >"); break; case ScalarStyle.Literal: textWriter.Write(" |"); break; default: textWriter.Write(" :"); break; } string value = scalar.Value; foreach (char c in value) { switch (c) { case '\b': textWriter.Write("\\b"); break; case '\t': textWriter.Write("\\t"); break; case '\n': textWriter.Write("\\n"); break; case '\r': textWriter.Write("\\r"); break; case '\\': textWriter.Write("\\\\"); break; default: textWriter.Write(c); break; } } } } else { textWriter.Write("+MAP"); WriteAnchorAndTag(textWriter, nodeEvent); } } else { textWriter.Write("-MAP"); } } else { textWriter.Write("+DOC"); if (!documentStart.IsImplicit) { textWriter.Write(" ---"); } } } else { textWriter.Write("-DOC"); if (!documentEnd.IsImplicit) { textWriter.Write(" ..."); } } } else { textWriter.Write("=ALI *"); textWriter.Write(anchorAlias.Value); } textWriter.WriteLine(); } } private void WriteAnchorAndTag(TextWriter textWriter, NodeEvent nodeEvent) { if (!nodeEvent.Anchor.IsEmpty) { textWriter.Write(" &"); textWriter.Write(nodeEvent.Anchor); } if (!nodeEvent.Tag.IsEmpty) { textWriter.Write(" <"); textWriter.Write(nodeEvent.Tag.Value); textWriter.Write(">"); } } } internal class YamlAliasNode : YamlNode { public override YamlNodeType NodeType => YamlNodeType.Alias; internal YamlAliasNode(AnchorName anchor) { base.Anchor = anchor; } internal override void ResolveAliases(DocumentLoadingState state) { throw new NotSupportedException("Resolving an alias on an alias node does not make sense"); } internal override void Emit(IEmitter emitter, EmitterState state) { throw new NotSupportedException("A YamlAliasNode is an implementation detail and should never be saved."); } public override void Accept(IYamlVisitor visitor) { throw new NotSupportedException("A YamlAliasNode is an implementation detail and should never be visited."); } public override bool Equals(object? obj) { if (obj is YamlAliasNode yamlAliasNode && Equals(yamlAliasNode)) { return object.Equals(base.Anchor, yamlAliasNode.Anchor); } return false; } public override int GetHashCode() { return base.GetHashCode(); } internal override string ToString(RecursionLevel level) { return "*" + base.Anchor.ToString(); } internal override IEnumerable SafeAllNodes(RecursionLevel level) { yield return this; } } internal class YamlDocument { private class AnchorAssigningVisitor : YamlVisitorBase { private readonly HashSet existingAnchors = new HashSet(); private readonly Dictionary visitedNodes = new Dictionary(); public void AssignAnchors(YamlDocument document) { existingAnchors.Clear(); visitedNodes.Clear(); document.Accept(this); Random random = new Random(); foreach (KeyValuePair visitedNode in visitedNodes) { if (!visitedNode.Value) { continue; } AnchorName anchorName; if (!visitedNode.Key.Anchor.IsEmpty && !existingAnchors.Contains(visitedNode.Key.Anchor)) { anchorName = visitedNode.Key.Anchor; } else { do { anchorName = new AnchorName(random.Next().ToString(CultureInfo.InvariantCulture)); } while (existingAnchors.Contains(anchorName)); } existingAnchors.Add(anchorName); visitedNode.Key.Anchor = anchorName; } } private bool VisitNodeAndFindDuplicates(YamlNode node) { if (visitedNodes.TryGetValue(node, out var value)) { if (!value) { visitedNodes[node] = true; } return !value; } visitedNodes.Add(node, value: false); return false; } public override void Visit(YamlScalarNode scalar) { VisitNodeAndFindDuplicates(scalar); } public override void Visit(YamlMappingNode mapping) { if (!VisitNodeAndFindDuplicates(mapping)) { base.Visit(mapping); } } public override void Visit(YamlSequenceNode sequence) { if (!VisitNodeAndFindDuplicates(sequence)) { base.Visit(sequence); } } } public YamlNode RootNode { get; private set; } public IEnumerable AllNodes => RootNode.AllNodes; public YamlDocument(YamlNode rootNode) { RootNode = rootNode; } public YamlDocument(string rootNode) { RootNode = new YamlScalarNode(rootNode); } internal YamlDocument(IParser parser) { DocumentLoadingState documentLoadingState = new DocumentLoadingState(); parser.Consume(); YamlDotNet.Core.Events.DocumentEnd @event; while (!parser.TryConsume(out @event)) { RootNode = YamlNode.ParseNode(parser, documentLoadingState); if (RootNode is YamlAliasNode) { throw new YamlException("A document cannot contain only an alias"); } } documentLoadingState.ResolveAliases(); if (RootNode == null) { throw new ArgumentException("Atempted to parse an empty document"); } } private void AssignAnchors() { new AnchorAssigningVisitor().AssignAnchors(this); } internal void Save(IEmitter emitter, bool assignAnchors = true) { if (assignAnchors) { AssignAnchors(); } emitter.Emit(new YamlDotNet.Core.Events.DocumentStart()); RootNode.Save(emitter, new EmitterState()); emitter.Emit(new YamlDotNet.Core.Events.DocumentEnd(isImplicit: false)); } public void Accept(IYamlVisitor visitor) { visitor.Visit(this); } } internal sealed class YamlMappingNode : YamlNode, IEnumerable>, IEnumerable, IYamlConvertible { private readonly OrderedDictionary children = new OrderedDictionary(); public IOrderedDictionary Children => children; public MappingStyle Style { get; set; } public override YamlNodeType NodeType => YamlNodeType.Mapping; internal YamlMappingNode(IParser parser, DocumentLoadingState state) { Load(parser, state); } private void Load(IParser parser, DocumentLoadingState state) { MappingStart mappingStart = parser.Consume(); Load(mappingStart, state); Style = mappingStart.Style; bool flag = false; MappingEnd @event; while (!parser.TryConsume(out @event)) { YamlNode yamlNode = YamlNode.ParseNode(parser, state); YamlNode yamlNode2 = YamlNode.ParseNode(parser, state); try { children.Add(yamlNode, yamlNode2); } catch (ArgumentException innerException) { Mark start = yamlNode.Start; Mark end = yamlNode.End; throw new YamlException(in start, in end, "Duplicate key", innerException); } flag = flag || yamlNode is YamlAliasNode || yamlNode2 is YamlAliasNode; } if (flag) { state.AddNodeWithUnresolvedAliases(this); } } public YamlMappingNode() { } public YamlMappingNode(params KeyValuePair[] children) : this((IEnumerable>)children) { } public YamlMappingNode(IEnumerable> children) { foreach (KeyValuePair child in children) { this.children.Add(child); } } public YamlMappingNode(params YamlNode[] children) : this((IEnumerable)children) { } public YamlMappingNode(IEnumerable children) { using IEnumerator enumerator = children.GetEnumerator(); while (enumerator.MoveNext()) { YamlNode current = enumerator.Current; if (!enumerator.MoveNext()) { throw new ArgumentException("When constructing a mapping node with a sequence, the number of elements of the sequence must be even."); } Add(current, enumerator.Current); } } public void Add(YamlNode key, YamlNode value) { children.Add(key, value); } public void Add(string key, YamlNode value) { children.Add(new YamlScalarNode(key), value); } public void Add(YamlNode key, string value) { children.Add(key, new YamlScalarNode(value)); } public void Add(string key, string value) { children.Add(new YamlScalarNode(key), new YamlScalarNode(value)); } internal override void ResolveAliases(DocumentLoadingState state) { Dictionary dictionary = null; Dictionary dictionary2 = null; foreach (KeyValuePair child in children) { if (child.Key is YamlAliasNode) { if (dictionary == null) { dictionary = new Dictionary(); } dictionary.Add(child.Key, state.GetNode(child.Key.Anchor, child.Key.Start, child.Key.End)); } if (child.Value is YamlAliasNode) { if (dictionary2 == null) { dictionary2 = new Dictionary(); } dictionary2.Add(child.Key, state.GetNode(child.Value.Anchor, child.Value.Start, child.Value.End)); } } if (dictionary2 != null) { foreach (KeyValuePair item in dictionary2) { children[item.Key] = item.Value; } } if (dictionary == null) { return; } foreach (KeyValuePair item2 in dictionary) { YamlNode value = children[item2.Key]; children.Remove(item2.Key); children.Add(item2.Value, value); } } internal override void Emit(IEmitter emitter, EmitterState state) { emitter.Emit(new MappingStart(base.Anchor, base.Tag, isImplicit: true, Style)); foreach (KeyValuePair child in children) { child.Key.Save(emitter, state); child.Value.Save(emitter, state); } emitter.Emit(new MappingEnd()); } public override void Accept(IYamlVisitor visitor) { visitor.Visit(this); } public override bool Equals(object? obj) { if (!(obj is YamlMappingNode yamlMappingNode) || !object.Equals(base.Tag, yamlMappingNode.Tag) || children.Count != yamlMappingNode.children.Count) { return false; } foreach (KeyValuePair child in children) { if (!yamlMappingNode.children.TryGetValue(child.Key, out YamlNode value) || !object.Equals(child.Value, value)) { return false; } } return true; } public override int GetHashCode() { int num = base.GetHashCode(); foreach (KeyValuePair child in children) { num = YamlDotNet.Core.HashCode.CombineHashCodes(num, child.Key); num = YamlDotNet.Core.HashCode.CombineHashCodes(num, child.Value); } return num; } internal override IEnumerable SafeAllNodes(RecursionLevel level) { level.Increment(); yield return this; foreach (KeyValuePair child in children) { foreach (YamlNode item in child.Key.SafeAllNodes(level)) { yield return item; } foreach (YamlNode item2 in child.Value.SafeAllNodes(level)) { yield return item2; } } level.Decrement(); } internal override string ToString(RecursionLevel level) { if (!level.TryIncrement()) { return "WARNING! INFINITE RECURSION!"; } StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; builder.Append("{ "); foreach (KeyValuePair child in children) { if (builder.Length > 2) { builder.Append(", "); } builder.Append("{ ").Append(child.Key.ToString(level)).Append(", ") .Append(child.Value.ToString(level)) .Append(" }"); } builder.Append(" }"); level.Decrement(); return builder.ToString(); } finally { ((IDisposable)builderWrapper).Dispose(); } } public IEnumerator> GetEnumerator() { return children.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { Load(parser, new DocumentLoadingState()); } void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) { Emit(emitter, new EmitterState()); } public static YamlMappingNode FromObject(object mapping) { if (mapping == null) { throw new ArgumentNullException("mapping"); } YamlMappingNode yamlMappingNode = new YamlMappingNode(); foreach (PropertyInfo publicProperty in mapping.GetType().GetPublicProperties()) { if (publicProperty.CanRead && publicProperty.GetGetMethod(nonPublic: false).GetParameters().Length == 0) { object value = publicProperty.GetValue(mapping, null); YamlNode yamlNode = value as YamlNode; if (yamlNode == null) { yamlNode = Convert.ToString(value) ?? string.Empty; } yamlMappingNode.Add(publicProperty.Name, yamlNode); } } return yamlMappingNode; } } internal abstract class YamlNode { private const int MaximumRecursionLevel = 1000; internal const string MaximumRecursionLevelReachedToStringValue = "WARNING! INFINITE RECURSION!"; public AnchorName Anchor { get; set; } public TagName Tag { get; set; } public Mark Start { get; private set; } = Mark.Empty; public Mark End { get; private set; } = Mark.Empty; public IEnumerable AllNodes { get { RecursionLevel level = new RecursionLevel(1000); return SafeAllNodes(level); } } public abstract YamlNodeType NodeType { get; } public YamlNode this[int index] { get { if (!(this is YamlSequenceNode yamlSequenceNode)) { throw new ArgumentException($"Accessed '{NodeType}' with an invalid index: {index}. Only Sequences can be indexed by number."); } return yamlSequenceNode.Children[index]; } } public YamlNode this[YamlNode key] { get { if (!(this is YamlMappingNode yamlMappingNode)) { throw new ArgumentException($"Accessed '{NodeType}' with an invalid index: {key}. Only Mappings can be indexed by key."); } return yamlMappingNode.Children[key]; } } internal void Load(NodeEvent yamlEvent, DocumentLoadingState state) { Tag = yamlEvent.Tag; if (!yamlEvent.Anchor.IsEmpty) { Anchor = yamlEvent.Anchor; state.AddAnchor(this); } Start = yamlEvent.Start; End = yamlEvent.End; } internal static YamlNode ParseNode(IParser parser, DocumentLoadingState state) { if (parser.Accept(out var _)) { return new YamlScalarNode(parser, state); } if (parser.Accept(out var _)) { return new YamlSequenceNode(parser, state); } if (parser.Accept(out var _)) { return new YamlMappingNode(parser, state); } if (parser.TryConsume(out var event4)) { if (!state.TryGetNode(event4.Value, out YamlNode node)) { return new YamlAliasNode(event4.Value); } return node; } throw new ArgumentException("The current event is of an unsupported type.", "parser"); } internal abstract void ResolveAliases(DocumentLoadingState state); internal void Save(IEmitter emitter, EmitterState state) { if (!Anchor.IsEmpty && !state.EmittedAnchors.Add(Anchor)) { emitter.Emit(new YamlDotNet.Core.Events.AnchorAlias(Anchor)); } else { Emit(emitter, state); } } internal abstract void Emit(IEmitter emitter, EmitterState state); public abstract void Accept(IYamlVisitor visitor); public override string ToString() { RecursionLevel recursionLevel = new RecursionLevel(1000); return ToString(recursionLevel); } internal abstract string ToString(RecursionLevel level); internal abstract IEnumerable SafeAllNodes(RecursionLevel level); public static implicit operator YamlNode(string value) { return new YamlScalarNode(value); } public static implicit operator YamlNode(string[] sequence) { return new YamlSequenceNode(((IEnumerable)sequence).Select((Func)((string i) => i))); } public static explicit operator string?(YamlNode node) { if (!(node is YamlScalarNode yamlScalarNode)) { throw new ArgumentException($"Attempted to convert a '{node.NodeType}' to string. This conversion is valid only for Scalars."); } return yamlScalarNode.Value; } } internal sealed class YamlNodeIdentityEqualityComparer : IEqualityComparer { public bool Equals([AllowNull] YamlNode x, [AllowNull] YamlNode y) { return x == y; } public int GetHashCode(YamlNode obj) { return obj.GetHashCode(); } } internal enum YamlNodeType { Alias, Mapping, Scalar, Sequence } [DebuggerDisplay("{Value}")] internal sealed class YamlScalarNode : YamlNode, IYamlConvertible { public string? Value { get; set; } public ScalarStyle Style { get; set; } public override YamlNodeType NodeType => YamlNodeType.Scalar; internal YamlScalarNode(IParser parser, DocumentLoadingState state) { Load(parser, state); } private void Load(IParser parser, DocumentLoadingState state) { YamlDotNet.Core.Events.Scalar scalar = parser.Consume(); Load(scalar, state); Value = scalar.Value; Style = scalar.Style; } public YamlScalarNode() { } public YamlScalarNode(string? value) { Value = value; } internal override void ResolveAliases(DocumentLoadingState state) { throw new NotSupportedException("Resolving an alias on a scalar node does not make sense"); } internal override void Emit(IEmitter emitter, EmitterState state) { emitter.Emit(new YamlDotNet.Core.Events.Scalar(base.Anchor, base.Tag, Value ?? string.Empty, Style, base.Tag.IsEmpty, isQuotedImplicit: false)); } public override void Accept(IYamlVisitor visitor) { visitor.Visit(this); } public override bool Equals(object? obj) { if (obj is YamlScalarNode yamlScalarNode && object.Equals(base.Tag, yamlScalarNode.Tag)) { return object.Equals(Value, yamlScalarNode.Value); } return false; } public override int GetHashCode() { return YamlDotNet.Core.HashCode.CombineHashCodes(base.Tag.GetHashCode(), Value); } public static explicit operator string?(YamlScalarNode value) { return value.Value; } internal override string ToString(RecursionLevel level) { return Value ?? string.Empty; } internal override IEnumerable SafeAllNodes(RecursionLevel level) { yield return this; } void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { Load(parser, new DocumentLoadingState()); } void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) { Emit(emitter, new EmitterState()); } } [DebuggerDisplay("Count = {children.Count}")] internal sealed class YamlSequenceNode : YamlNode, IEnumerable, IEnumerable, IYamlConvertible { private readonly IList children = new List(); public IList Children => children; public SequenceStyle Style { get; set; } public override YamlNodeType NodeType => YamlNodeType.Sequence; internal YamlSequenceNode(IParser parser, DocumentLoadingState state) { Load(parser, state); } private void Load(IParser parser, DocumentLoadingState state) { SequenceStart sequenceStart = parser.Consume(); Load(sequenceStart, state); Style = sequenceStart.Style; bool flag = false; SequenceEnd @event; while (!parser.TryConsume(out @event)) { YamlNode yamlNode = YamlNode.ParseNode(parser, state); children.Add(yamlNode); flag = flag || yamlNode is YamlAliasNode; } if (flag) { state.AddNodeWithUnresolvedAliases(this); } } public YamlSequenceNode() { } public YamlSequenceNode(params YamlNode[] children) : this((IEnumerable)children) { } public YamlSequenceNode(IEnumerable children) { foreach (YamlNode child in children) { this.children.Add(child); } } public void Add(YamlNode child) { children.Add(child); } public void Add(string child) { children.Add(new YamlScalarNode(child)); } internal override void ResolveAliases(DocumentLoadingState state) { for (int i = 0; i < children.Count; i++) { if (children[i] is YamlAliasNode) { children[i] = state.GetNode(children[i].Anchor, children[i].Start, children[i].End); } } } internal override void Emit(IEmitter emitter, EmitterState state) { emitter.Emit(new SequenceStart(base.Anchor, base.Tag, base.Tag.IsEmpty, Style)); foreach (YamlNode child in children) { child.Save(emitter, state); } emitter.Emit(new SequenceEnd()); } public override void Accept(IYamlVisitor visitor) { visitor.Visit(this); } public override bool Equals(object? obj) { if (!(obj is YamlSequenceNode yamlSequenceNode) || !object.Equals(base.Tag, yamlSequenceNode.Tag) || children.Count != yamlSequenceNode.children.Count) { return false; } for (int i = 0; i < children.Count; i++) { if (!object.Equals(children[i], yamlSequenceNode.children[i])) { return false; } } return true; } public override int GetHashCode() { int h = 0; foreach (YamlNode child in children) { h = YamlDotNet.Core.HashCode.CombineHashCodes(h, child); } return YamlDotNet.Core.HashCode.CombineHashCodes(h, base.Tag); } internal override IEnumerable SafeAllNodes(RecursionLevel level) { level.Increment(); yield return this; foreach (YamlNode child in children) { foreach (YamlNode item in child.SafeAllNodes(level)) { yield return item; } } level.Decrement(); } internal override string ToString(RecursionLevel level) { if (!level.TryIncrement()) { return "WARNING! INFINITE RECURSION!"; } StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; builder.Append("[ "); foreach (YamlNode child in children) { if (builder.Length > 2) { builder.Append(", "); } builder.Append(child.ToString(level)); } builder.Append(" ]"); level.Decrement(); return builder.ToString(); } finally { ((IDisposable)builderWrapper).Dispose(); } } public IEnumerator GetEnumerator() { return Children.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } void IYamlConvertible.Read(IParser parser, Type expectedType, ObjectDeserializer nestedObjectDeserializer) { Load(parser, new DocumentLoadingState()); } void IYamlConvertible.Write(IEmitter emitter, ObjectSerializer nestedObjectSerializer) { Emit(emitter, new EmitterState()); } } internal class YamlStream : IEnumerable, IEnumerable { private readonly IList documents = new List(); public IList Documents => documents; public YamlStream() { } public YamlStream(params YamlDocument[] documents) : this((IEnumerable)documents) { } public YamlStream(IEnumerable documents) { foreach (YamlDocument document in documents) { this.documents.Add(document); } } public void Add(YamlDocument document) { documents.Add(document); } public void Load(TextReader input) { Load(new Parser(input)); } public void Load(IParser parser) { documents.Clear(); parser.Consume(); YamlDotNet.Core.Events.StreamEnd @event; while (!parser.TryConsume(out @event)) { YamlDocument item = new YamlDocument(parser); documents.Add(item); } } public void Save(TextWriter output) { Save(output, assignAnchors: true); } public void Save(TextWriter output, bool assignAnchors) { Save(new Emitter(output), assignAnchors); } public void Save(IEmitter emitter, bool assignAnchors) { emitter.Emit(new YamlDotNet.Core.Events.StreamStart()); foreach (YamlDocument document in documents) { document.Save(emitter, assignAnchors); } emitter.Emit(new YamlDotNet.Core.Events.StreamEnd()); } public void Accept(IYamlVisitor visitor) { visitor.Visit(this); } public IEnumerator GetEnumerator() { return documents.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [Obsolete("Use YamlVisitorBase")] internal abstract class YamlVisitor : IYamlVisitor { protected virtual void Visit(YamlStream stream) { } protected virtual void Visited(YamlStream stream) { } protected virtual void Visit(YamlDocument document) { } protected virtual void Visited(YamlDocument document) { } protected virtual void Visit(YamlScalarNode scalar) { } protected virtual void Visited(YamlScalarNode scalar) { } protected virtual void Visit(YamlSequenceNode sequence) { } protected virtual void Visited(YamlSequenceNode sequence) { } protected virtual void Visit(YamlMappingNode mapping) { } protected virtual void Visited(YamlMappingNode mapping) { } protected virtual void VisitChildren(YamlStream stream) { foreach (YamlDocument document in stream.Documents) { document.Accept(this); } } protected virtual void VisitChildren(YamlDocument document) { if (document.RootNode != null) { document.RootNode.Accept(this); } } protected virtual void VisitChildren(YamlSequenceNode sequence) { foreach (YamlNode child in sequence.Children) { child.Accept(this); } } protected virtual void VisitChildren(YamlMappingNode mapping) { foreach (KeyValuePair child in mapping.Children) { child.Key.Accept(this); child.Value.Accept(this); } } void IYamlVisitor.Visit(YamlStream stream) { Visit(stream); VisitChildren(stream); Visited(stream); } void IYamlVisitor.Visit(YamlDocument document) { Visit(document); VisitChildren(document); Visited(document); } void IYamlVisitor.Visit(YamlScalarNode scalar) { Visit(scalar); Visited(scalar); } void IYamlVisitor.Visit(YamlSequenceNode sequence) { Visit(sequence); VisitChildren(sequence); Visited(sequence); } void IYamlVisitor.Visit(YamlMappingNode mapping) { Visit(mapping); VisitChildren(mapping); Visited(mapping); } } internal abstract class YamlVisitorBase : IYamlVisitor { public virtual void Visit(YamlStream stream) { VisitChildren(stream); } public virtual void Visit(YamlDocument document) { VisitChildren(document); } public virtual void Visit(YamlScalarNode scalar) { } public virtual void Visit(YamlSequenceNode sequence) { VisitChildren(sequence); } public virtual void Visit(YamlMappingNode mapping) { VisitChildren(mapping); } protected virtual void VisitPair(YamlNode key, YamlNode value) { key.Accept(this); value.Accept(this); } protected virtual void VisitChildren(YamlStream stream) { foreach (YamlDocument document in stream.Documents) { document.Accept(this); } } protected virtual void VisitChildren(YamlDocument document) { if (document.RootNode != null) { document.RootNode.Accept(this); } } protected virtual void VisitChildren(YamlSequenceNode sequence) { foreach (YamlNode child in sequence.Children) { child.Accept(this); } } protected virtual void VisitChildren(YamlMappingNode mapping) { foreach (KeyValuePair child in mapping.Children) { VisitPair(child.Key, child.Value); } } } } namespace YamlDotNet.Helpers { [DebuggerStepThrough] internal sealed class ConcurrentObjectPool where T : class { [DebuggerDisplay("{value,nq}")] private struct Element { internal T? value; } internal delegate T Factory(); private T? firstItem; private readonly Element[] items; private readonly Factory factory; internal ConcurrentObjectPool(Factory factory) : this(factory, Environment.ProcessorCount * 2) { } internal ConcurrentObjectPool(Factory factory, int size) { this.factory = factory; items = new Element[size - 1]; } private T CreateInstance() { return factory(); } internal T Allocate() { T val = firstItem; if (val == null || val != Interlocked.CompareExchange(ref firstItem, null, val)) { val = AllocateSlow(); } return val; } private T AllocateSlow() { Element[] array = items; for (int i = 0; i < array.Length; i++) { T value = array[i].value; if (value != null && value == Interlocked.CompareExchange(ref array[i].value, null, value)) { return value; } } return CreateInstance(); } internal void Free(T obj) { if (firstItem == null) { firstItem = obj; } else { FreeSlow(obj); } } private void FreeSlow(T obj) { Element[] array = items; for (int i = 0; i < array.Length; i++) { if (array[i].value == null) { array[i].value = obj; break; } } } [Conditional("DEBUG")] private void Validate(object obj) { Element[] array = items; for (int i = 0; i < array.Length && array[i].value != null; i++) { } } } internal static class ExpressionExtensions { public static PropertyInfo AsProperty(this LambdaExpression propertyAccessor) { PropertyInfo propertyInfo = TryGetMemberExpression(propertyAccessor); if (propertyInfo == null) { throw new ArgumentException("Expected a lambda expression in the form: x => x.SomeProperty", "propertyAccessor"); } return propertyInfo; } [return: MaybeNull] private static TMemberInfo TryGetMemberExpression(LambdaExpression lambdaExpression) where TMemberInfo : MemberInfo { if (lambdaExpression.Parameters.Count != 1) { return null; } Expression expression = lambdaExpression.Body; if (expression is UnaryExpression unaryExpression) { if (unaryExpression.NodeType != ExpressionType.Convert) { return null; } expression = unaryExpression.Operand; } if (expression is MemberExpression memberExpression) { if (memberExpression.Expression != lambdaExpression.Parameters[0]) { return null; } return memberExpression.Member as TMemberInfo; } return null; } } internal sealed class GenericCollectionToNonGenericAdapter : IList, ICollection, IEnumerable { private readonly ICollection genericCollection; public bool IsFixedSize { get { throw new NotSupportedException(); } } public bool IsReadOnly { get { throw new NotSupportedException(); } } public object? this[int index] { get { throw new NotSupportedException(); } set { ((IList)genericCollection)[index] = (T)value; } } public int Count { get { throw new NotSupportedException(); } } public bool IsSynchronized { get { throw new NotSupportedException(); } } public object SyncRoot { get { throw new NotSupportedException(); } } public GenericCollectionToNonGenericAdapter(ICollection genericCollection) { this.genericCollection = genericCollection ?? throw new ArgumentNullException("genericCollection"); } public int Add(object? value) { int count = genericCollection.Count; genericCollection.Add((T)value); return count; } public void Clear() { genericCollection.Clear(); } public bool Contains(object? value) { throw new NotSupportedException(); } public int IndexOf(object? value) { throw new NotSupportedException(); } public void Insert(int index, object? value) { throw new NotSupportedException(); } public void Remove(object? value) { throw new NotSupportedException(); } public void RemoveAt(int index) { throw new NotSupportedException(); } public void CopyTo(Array array, int index) { throw new NotSupportedException(); } public IEnumerator GetEnumerator() { return genericCollection.GetEnumerator(); } } internal sealed class GenericDictionaryToNonGenericAdapter : IDictionary, ICollection, IEnumerable where TKey : notnull { private class DictionaryEnumerator : IDictionaryEnumerator, IEnumerator { private readonly IEnumerator> enumerator; public DictionaryEntry Entry => new DictionaryEntry(Key, Value); public object Key => enumerator.Current.Key; public object? Value => enumerator.Current.Value; public object Current => Entry; public DictionaryEnumerator(IEnumerator> enumerator) { this.enumerator = enumerator; } public bool MoveNext() { return enumerator.MoveNext(); } public void Reset() { enumerator.Reset(); } } private readonly IDictionary genericDictionary; public bool IsFixedSize { get { throw new NotSupportedException(); } } public bool IsReadOnly { get { throw new NotSupportedException(); } } public ICollection Keys { get { throw new NotSupportedException(); } } public ICollection Values { get { throw new NotSupportedException(); } } public object? this[object key] { get { throw new NotSupportedException(); } set { genericDictionary[(TKey)key] = (TValue)value; } } public int Count { get { throw new NotSupportedException(); } } public bool IsSynchronized { get { throw new NotSupportedException(); } } public object SyncRoot { get { throw new NotSupportedException(); } } public GenericDictionaryToNonGenericAdapter(IDictionary genericDictionary) { this.genericDictionary = genericDictionary ?? throw new ArgumentNullException("genericDictionary"); } public void Add(object key, object? value) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Contains(object key) { throw new NotSupportedException(); } public IDictionaryEnumerator GetEnumerator() { return new DictionaryEnumerator(genericDictionary.GetEnumerator()); } public void Remove(object key) { throw new NotSupportedException(); } public void CopyTo(Array array, int index) { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal interface IOrderedDictionary : IDictionary, ICollection>, IEnumerable>, IEnumerable where TKey : notnull { KeyValuePair this[int index] { get; set; } void Insert(int index, TKey key, TValue value); void RemoveAt(int index); } internal static class NumberExtensions { public static bool IsPowerOfTwo(this int value) { return (value & (value - 1)) == 0; } } [Serializable] internal sealed class OrderedDictionary : IOrderedDictionary, IDictionary, ICollection>, IEnumerable>, IEnumerable where TKey : notnull { private class KeyCollection : ICollection, IEnumerable, IEnumerable { private readonly OrderedDictionary orderedDictionary; public int Count => orderedDictionary.list.Count; public bool IsReadOnly => true; public void Add(TKey item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Contains(TKey item) { return orderedDictionary.dictionary.Keys.Contains(item); } public KeyCollection(OrderedDictionary orderedDictionary) { this.orderedDictionary = orderedDictionary; } public void CopyTo(TKey[] array, int arrayIndex) { for (int i = 0; i < orderedDictionary.list.Count; i++) { array[i] = orderedDictionary.list[i + arrayIndex].Key; } } public IEnumerator GetEnumerator() { return orderedDictionary.list.Select((KeyValuePair kvp) => kvp.Key).GetEnumerator(); } public bool Remove(TKey item) { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private class ValueCollection : ICollection, IEnumerable, IEnumerable { private readonly OrderedDictionary orderedDictionary; public int Count => orderedDictionary.list.Count; public bool IsReadOnly => true; public void Add(TValue item) { throw new NotSupportedException(); } public void Clear() { throw new NotSupportedException(); } public bool Contains(TValue item) { return orderedDictionary.dictionary.Values.Contains(item); } public ValueCollection(OrderedDictionary orderedDictionary) { this.orderedDictionary = orderedDictionary; } public void CopyTo(TValue[] array, int arrayIndex) { for (int i = 0; i < orderedDictionary.list.Count; i++) { array[i] = orderedDictionary.list[i + arrayIndex].Value; } } public IEnumerator GetEnumerator() { return orderedDictionary.list.Select((KeyValuePair kvp) => kvp.Value).GetEnumerator(); } public bool Remove(TValue item) { throw new NotSupportedException(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } [NonSerialized] private Dictionary dictionary; private readonly List> list; private readonly IEqualityComparer comparer; public TValue this[TKey key] { get { return dictionary[key]; } set { TKey key2 = key; if (dictionary.ContainsKey(key2)) { int index = list.FindIndex((KeyValuePair kvp) => comparer.Equals(kvp.Key, key2)); dictionary[key2] = value; list[index] = new KeyValuePair(key2, value); } else { Add(key2, value); } } } public ICollection Keys => new KeyCollection(this); public ICollection Values => new ValueCollection(this); public int Count => dictionary.Count; public bool IsReadOnly => false; public KeyValuePair this[int index] { get { return list[index]; } set { list[index] = value; } } public OrderedDictionary() : this((IEqualityComparer)EqualityComparer.Default) { } public OrderedDictionary(IEqualityComparer comparer) { list = new List>(); dictionary = new Dictionary(comparer); this.comparer = comparer; } public void Add(TKey key, TValue value) { Add(new KeyValuePair(key, value)); } public void Add(KeyValuePair item) { dictionary.Add(item.Key, item.Value); list.Add(item); } public void Clear() { dictionary.Clear(); list.Clear(); } public bool Contains(KeyValuePair item) { return dictionary.Contains(item); } public bool ContainsKey(TKey key) { return dictionary.ContainsKey(key); } public void CopyTo(KeyValuePair[] array, int arrayIndex) { list.CopyTo(array, arrayIndex); } public IEnumerator> GetEnumerator() { return list.GetEnumerator(); } public void Insert(int index, TKey key, TValue value) { dictionary.Add(key, value); list.Insert(index, new KeyValuePair(key, value)); } public bool Remove(TKey key) { TKey key2 = key; if (dictionary.ContainsKey(key2)) { int index = list.FindIndex((KeyValuePair kvp) => comparer.Equals(kvp.Key, key2)); list.RemoveAt(index); if (!dictionary.Remove(key2)) { throw new InvalidOperationException(); } return true; } return false; } public bool Remove(KeyValuePair item) { return Remove(item.Key); } public void RemoveAt(int index) { TKey key = list[index].Key; dictionary.Remove(key); list.RemoveAt(index); } public bool TryGetValue(TKey key, [MaybeNullWhen(false)] out TValue value) { return dictionary.TryGetValue(key, out value); } IEnumerator IEnumerable.GetEnumerator() { return list.GetEnumerator(); } [OnDeserialized] internal void OnDeserializedMethod(StreamingContext context) { dictionary = new Dictionary(); foreach (KeyValuePair item in list) { dictionary[item.Key] = item.Value; } } } [DebuggerStepThrough] internal static class StringBuilderPool { internal readonly struct BuilderWrapper : IDisposable { public readonly StringBuilder Builder; private readonly ConcurrentObjectPool _pool; public BuilderWrapper(StringBuilder builder, ConcurrentObjectPool pool) { Builder = builder; _pool = pool; } public override string ToString() { return Builder.ToString(); } public void Dispose() { StringBuilder builder = Builder; if (builder.Capacity <= 1024) { builder.Length = 0; _pool.Free(builder); } } } private static readonly ConcurrentObjectPool Pool; static StringBuilderPool() { Pool = new ConcurrentObjectPool(() => new StringBuilder()); } public static BuilderWrapper Rent() { return new BuilderWrapper(Pool.Allocate(), Pool); } } internal static class ThrowHelper { [MethodImpl(MethodImplOptions.NoInlining)] public static void ThrowArgumentOutOfRangeException(string paramName, string message) { throw new ArgumentOutOfRangeException(paramName, message); } } internal static class Lazy { public static Lazy FromValue(T value) { T value2 = value; Lazy lazy = new Lazy(() => value2, isThreadSafe: false); _ = lazy.Value; return lazy; } } internal static class ReadOnlyCollectionExtensions { public static IReadOnlyList AsReadonlyList(this List list) { return list; } public static IReadOnlyDictionary AsReadonlyDictionary(this Dictionary dictionary) where TKey : notnull { return dictionary; } } } namespace YamlDotNet.Core { internal struct AnchorName : IEquatable { public static readonly AnchorName Empty = default(AnchorName); private static readonly Regex AnchorPattern = new Regex("^[^\\[\\]\\{\\},]+$", RegexOptions.Compiled); private readonly string? value; public string Value => value ?? throw new InvalidOperationException("Cannot read the Value of an empty anchor"); public bool IsEmpty => value == null; public AnchorName(string value) { this.value = value ?? throw new ArgumentNullException("value"); if (!AnchorPattern.IsMatch(value)) { throw new ArgumentException("Anchor cannot be empty or contain disallowed characters: []{},\nThe value was '" + value + "'.", "value"); } } public override string ToString() { return value ?? "[empty]"; } public bool Equals(AnchorName other) { return object.Equals(value, other.value); } public override bool Equals(object? obj) { if (obj is AnchorName other) { return Equals(other); } return false; } public override int GetHashCode() { return value?.GetHashCode() ?? 0; } public static bool operator ==(AnchorName left, AnchorName right) { return left.Equals(right); } public static bool operator !=(AnchorName left, AnchorName right) { return !(left == right); } public static implicit operator AnchorName(string? value) { if (value != null) { return new AnchorName(value); } return Empty; } } internal class AnchorNotFoundException : YamlException { public AnchorNotFoundException(string message) : base(message) { } public AnchorNotFoundException(in Mark start, in Mark end, string message) : base(in start, in end, message) { } public AnchorNotFoundException(string message, Exception inner) : base(message, inner) { } } [DebuggerStepThrough] internal sealed class CharacterAnalyzer where TBuffer : class, ILookAheadBuffer { public TBuffer Buffer { get; } public bool EndOfInput => Buffer.EndOfInput; public CharacterAnalyzer(TBuffer buffer) { Buffer = buffer ?? throw new ArgumentNullException("buffer"); } public char Peek(int offset) { return Buffer.Peek(offset); } public void Skip(int length) { Buffer.Skip(length); } public bool IsAlphaNumericDashOrUnderscore(int offset = 0) { char c = Buffer.Peek(offset); if ((c < '0' || c > '9') && (c < 'A' || c > 'Z') && (c < 'a' || c > 'z') && c != '_') { return c == '-'; } return true; } public bool IsAscii(int offset = 0) { return Buffer.Peek(offset) <= '\u007f'; } public bool IsPrintable(int offset = 0) { char c = Buffer.Peek(offset); switch (c) { default: if (c != '\u0085' && (c < '\u00a0' || c > '\ud7ff')) { if (c >= '\ue000') { return c <= '\ufffd'; } return false; } break; case '\t': case '\n': case '\r': case ' ': case '!': case '"': case '#': case '$': case '%': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ':': case ';': case '<': case '=': case '>': case '?': case '@': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '[': case '\\': case ']': case '^': case '_': case '`': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '{': case '|': case '}': case '~': break; } return true; } public bool IsDigit(int offset = 0) { char c = Buffer.Peek(offset); if (c >= '0') { return c <= '9'; } return false; } public int AsDigit(int offset = 0) { return Buffer.Peek(offset) - 48; } public bool IsHex(int offset) { char c = Buffer.Peek(offset); if ((c < '0' || c > '9') && (c < 'A' || c > 'F')) { if (c >= 'a') { return c <= 'f'; } return false; } return true; } public int AsHex(int offset) { char c = Buffer.Peek(offset); if (c <= '9') { return c - 48; } if (c <= 'F') { return c - 65 + 10; } return c - 97 + 10; } public bool IsSpace(int offset = 0) { return Check(' ', offset); } public bool IsZero(int offset = 0) { return Check('\0', offset); } public bool IsTab(int offset = 0) { return Check('\t', offset); } public bool IsWhite(int offset = 0) { if (!IsSpace(offset)) { return IsTab(offset); } return true; } public bool IsBreak(int offset = 0) { return Check("\r\n\u0085\u2028\u2029", offset); } public bool IsCrLf(int offset = 0) { if (Check('\r', offset)) { return Check('\n', offset + 1); } return false; } public bool IsBreakOrZero(int offset = 0) { if (!IsBreak(offset)) { return IsZero(offset); } return true; } public bool IsWhiteBreakOrZero(int offset = 0) { if (!IsWhite(offset)) { return IsBreakOrZero(offset); } return true; } public bool Check(char expected, int offset = 0) { return Buffer.Peek(offset) == expected; } public bool Check(string expectedCharacters, int offset = 0) { char value = Buffer.Peek(offset); return expectedCharacters.IndexOf(value) != -1; } } internal static class Constants { public static readonly TagDirective[] DefaultTagDirectives = new TagDirective[2] { new TagDirective("!", "!"), new TagDirective("!!", "tag:yaml.org,2002:") }; public const int MajorVersion = 1; public const int MinorVersion = 3; } [DebuggerStepThrough] internal sealed class Cursor { public int Index { get; private set; } public int Line { get; private set; } public int LineOffset { get; private set; } public Cursor() { Line = 1; } public Cursor(Cursor cursor) { Index = cursor.Index; Line = cursor.Line; LineOffset = cursor.LineOffset; } public Mark Mark() { return new Mark(Index, Line, LineOffset + 1); } public void Skip() { Index++; LineOffset++; } public void SkipLineByOffset(int offset) { Index += offset; Line++; LineOffset = 0; } public void ForceSkipLineAfterNonBreak() { if (LineOffset != 0) { Line++; LineOffset = 0; } } } internal class Emitter : IEmitter { private class AnchorData { public AnchorName Anchor; public bool IsAlias; } private class TagData { public string? Handle; public string? Suffix; } private class ScalarData { public string Value = string.Empty; public bool IsMultiline; public bool IsFlowPlainAllowed; public bool IsBlockPlainAllowed; public bool IsSingleQuotedAllowed; public bool IsBlockAllowed; public bool HasSingleQuotes; public ScalarStyle Style; } private static readonly Regex UriReplacer = new Regex("[^0-9A-Za-z_\\-;?@=$~\\\\\\)\\]/:&+,\\.\\*\\(\\[!]", RegexOptions.Compiled | RegexOptions.Singleline); private static readonly string[] newLineSeparators = new string[3] { "\r\n", "\r", "\n" }; private readonly TextWriter output; private readonly bool outputUsesUnicodeEncoding; private readonly int maxSimpleKeyLength; private readonly bool isCanonical; private readonly bool skipAnchorName; private readonly int bestIndent; private readonly int bestWidth; private EmitterState state; private readonly Stack states = new Stack(); private readonly Queue events = new Queue(); private readonly Stack indents = new Stack(); private readonly TagDirectiveCollection tagDirectives = new TagDirectiveCollection(); private int indent; private int flowLevel; private bool isMappingContext; private bool isSimpleKeyContext; private int column; private bool isWhitespace; private bool isIndentation; private readonly bool forceIndentLess; private readonly string newLine; private bool isDocumentEndWritten; private readonly AnchorData anchorData = new AnchorData(); private readonly TagData tagData = new TagData(); private readonly ScalarData scalarData = new ScalarData(); public Emitter(TextWriter output) : this(output, EmitterSettings.Default) { } public Emitter(TextWriter output, int bestIndent) : this(output, bestIndent, int.MaxValue) { } public Emitter(TextWriter output, int bestIndent, int bestWidth) : this(output, bestIndent, bestWidth, isCanonical: false) { } public Emitter(TextWriter output, int bestIndent, int bestWidth, bool isCanonical) : this(output, new EmitterSettings(bestIndent, bestWidth, isCanonical, 1024)) { } public Emitter(TextWriter output, EmitterSettings settings) { bestIndent = settings.BestIndent; bestWidth = settings.BestWidth; isCanonical = settings.IsCanonical; maxSimpleKeyLength = settings.MaxSimpleKeyLength; skipAnchorName = settings.SkipAnchorName; forceIndentLess = !settings.IndentSequences; newLine = settings.NewLine; this.output = output; outputUsesUnicodeEncoding = IsUnicode(output.Encoding); } public void Emit(ParsingEvent @event) { events.Enqueue(@event); while (!NeedMoreEvents()) { ParsingEvent evt = events.Peek(); try { AnalyzeEvent(evt); StateMachine(evt); } finally { events.Dequeue(); } } } private bool NeedMoreEvents() { if (events.Count == 0) { return true; } int num; switch (events.Peek().Type) { case EventType.DocumentStart: num = 1; break; case EventType.SequenceStart: num = 2; break; case EventType.MappingStart: num = 3; break; default: return false; } if (events.Count > num) { return false; } int num2 = 0; using (Queue.Enumerator enumerator = events.GetEnumerator()) { while (enumerator.MoveNext()) { switch (enumerator.Current.Type) { case EventType.DocumentStart: case EventType.SequenceStart: case EventType.MappingStart: num2++; break; case EventType.DocumentEnd: case EventType.SequenceEnd: case EventType.MappingEnd: num2--; break; } if (num2 == 0) { return false; } } } return true; } private void AnalyzeEvent(ParsingEvent evt) { anchorData.Anchor = AnchorName.Empty; tagData.Handle = null; tagData.Suffix = null; if (evt is YamlDotNet.Core.Events.AnchorAlias anchorAlias) { AnalyzeAnchor(anchorAlias.Value, isAlias: true); } else if (evt is NodeEvent nodeEvent) { if (evt is YamlDotNet.Core.Events.Scalar scalar) { AnalyzeScalar(scalar); } AnalyzeAnchor(nodeEvent.Anchor, isAlias: false); if (!nodeEvent.Tag.IsEmpty && (isCanonical || nodeEvent.IsCanonical)) { AnalyzeTag(nodeEvent.Tag); } } } private void AnalyzeAnchor(AnchorName anchor, bool isAlias) { anchorData.Anchor = anchor; anchorData.IsAlias = isAlias; } private void AnalyzeScalar(YamlDotNet.Core.Events.Scalar scalar) { string value = scalar.Value; scalarData.Value = value; if (value.Length == 0) { if (scalar.Tag == "tag:yaml.org,2002:null") { scalarData.IsMultiline = false; scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = true; scalarData.IsSingleQuotedAllowed = false; scalarData.IsBlockAllowed = false; } else { scalarData.IsMultiline = false; scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = false; scalarData.IsSingleQuotedAllowed = true; scalarData.IsBlockAllowed = false; } return; } bool flag = false; bool flag2 = false; if (value.StartsWith("---", StringComparison.Ordinal) || value.StartsWith("...", StringComparison.Ordinal)) { flag = true; flag2 = true; } CharacterAnalyzer characterAnalyzer = new CharacterAnalyzer(new StringLookAheadBuffer(value)); bool flag3 = true; bool flag4 = characterAnalyzer.IsWhiteBreakOrZero(1); bool flag5 = false; bool flag6 = false; bool flag7 = false; bool flag8 = false; bool flag9 = false; bool flag10 = false; bool flag11 = false; bool flag12 = false; bool flag13 = false; bool flag14 = false; bool flag15 = false; bool flag16 = !ValueIsRepresentableInOutputEncoding(value); bool flag17 = false; bool flag18 = false; bool flag19 = true; while (!characterAnalyzer.EndOfInput) { if (flag19) { if (characterAnalyzer.Check("#,[]{}&*!|>\\\"%@`'")) { flag = true; flag2 = true; flag9 = characterAnalyzer.Check('\''); flag17 |= characterAnalyzer.Check('\''); } if (characterAnalyzer.Check("?:")) { flag = true; if (flag4) { flag2 = true; } } if (characterAnalyzer.Check('-') && flag4) { flag = true; flag2 = true; } } else { if (characterAnalyzer.Check(",?[]{}")) { flag = true; } if (characterAnalyzer.Check(':')) { flag = true; if (flag4) { flag2 = true; } } if (characterAnalyzer.Check('#') && flag3) { flag = true; flag2 = true; } flag17 |= characterAnalyzer.Check('\''); } if (!flag16 && !characterAnalyzer.IsPrintable()) { flag16 = true; } if (characterAnalyzer.IsBreak()) { flag15 = true; } if (characterAnalyzer.IsSpace()) { if (flag19) { flag5 = true; } if (characterAnalyzer.Buffer.Position >= characterAnalyzer.Buffer.Length - 1) { flag7 = true; } if (flag13) { flag10 = true; flag14 = true; } flag12 = true; flag13 = false; } else if (characterAnalyzer.IsBreak()) { if (flag19) { flag6 = true; } if (characterAnalyzer.Buffer.Position >= characterAnalyzer.Buffer.Length - 1) { flag8 = true; } if (flag12) { flag11 = true; } if (flag14) { flag18 = true; } flag12 = false; flag13 = true; } else { flag12 = false; flag13 = false; flag14 = false; } flag3 = characterAnalyzer.IsWhiteBreakOrZero(); characterAnalyzer.Skip(1); if (!characterAnalyzer.EndOfInput) { flag4 = characterAnalyzer.IsWhiteBreakOrZero(1); } flag19 = false; } scalarData.IsFlowPlainAllowed = true; scalarData.IsBlockPlainAllowed = true; scalarData.IsSingleQuotedAllowed = true; scalarData.IsBlockAllowed = true; if (flag5 || flag6 || flag7 || flag8 || flag9) { scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = false; } if (flag7) { scalarData.IsBlockAllowed = false; } if (flag10) { scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = false; scalarData.IsSingleQuotedAllowed = false; } if (flag11 || flag16) { scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = false; scalarData.IsSingleQuotedAllowed = false; } if (flag18) { scalarData.IsBlockAllowed = false; } scalarData.IsMultiline = flag15; if (flag15) { scalarData.IsFlowPlainAllowed = false; scalarData.IsBlockPlainAllowed = false; } if (flag) { scalarData.IsFlowPlainAllowed = false; } if (flag2) { scalarData.IsBlockPlainAllowed = false; } scalarData.HasSingleQuotes = flag17; } private bool ValueIsRepresentableInOutputEncoding(string value) { if (outputUsesUnicodeEncoding) { return true; } try { byte[] bytes = output.Encoding.GetBytes(value); return output.Encoding.GetString(bytes, 0, bytes.Length).Equals(value); } catch (EncoderFallbackException) { return false; } catch (ArgumentOutOfRangeException) { return false; } } private bool IsUnicode(Encoding encoding) { if (!(encoding is UTF8Encoding) && !(encoding is UnicodeEncoding)) { return encoding is UTF7Encoding; } return true; } private void AnalyzeTag(TagName tag) { tagData.Handle = tag.Value; foreach (TagDirective tagDirective in tagDirectives) { if (tag.Value.StartsWith(tagDirective.Prefix, StringComparison.Ordinal)) { tagData.Handle = tagDirective.Handle; tagData.Suffix = tag.Value.Substring(tagDirective.Prefix.Length); break; } } } private void StateMachine(ParsingEvent evt) { if (evt is YamlDotNet.Core.Events.Comment comment) { EmitComment(comment); return; } switch (state) { case EmitterState.StreamStart: EmitStreamStart(evt); break; case EmitterState.FirstDocumentStart: EmitDocumentStart(evt, isFirst: true); break; case EmitterState.DocumentStart: EmitDocumentStart(evt, isFirst: false); break; case EmitterState.DocumentContent: EmitDocumentContent(evt); break; case EmitterState.DocumentEnd: EmitDocumentEnd(evt); break; case EmitterState.FlowSequenceFirstItem: EmitFlowSequenceItem(evt, isFirst: true); break; case EmitterState.FlowSequenceItem: EmitFlowSequenceItem(evt, isFirst: false); break; case EmitterState.FlowMappingFirstKey: EmitFlowMappingKey(evt, isFirst: true); break; case EmitterState.FlowMappingKey: EmitFlowMappingKey(evt, isFirst: false); break; case EmitterState.FlowMappingSimpleValue: EmitFlowMappingValue(evt, isSimple: true); break; case EmitterState.FlowMappingValue: EmitFlowMappingValue(evt, isSimple: false); break; case EmitterState.BlockSequenceFirstItem: EmitBlockSequenceItem(evt, isFirst: true); break; case EmitterState.BlockSequenceItem: EmitBlockSequenceItem(evt, isFirst: false); break; case EmitterState.BlockMappingFirstKey: EmitBlockMappingKey(evt, isFirst: true); break; case EmitterState.BlockMappingKey: EmitBlockMappingKey(evt, isFirst: false); break; case EmitterState.BlockMappingSimpleValue: EmitBlockMappingValue(evt, isSimple: true); break; case EmitterState.BlockMappingValue: EmitBlockMappingValue(evt, isSimple: false); break; case EmitterState.StreamEnd: throw new YamlException("Expected nothing after STREAM-END"); default: throw new InvalidOperationException(); } } private void EmitComment(YamlDotNet.Core.Events.Comment comment) { if (flowLevel > 0 || state == EmitterState.FlowMappingFirstKey || state == EmitterState.FlowSequenceFirstItem) { return; } string[] array = comment.Value.Split(newLineSeparators, StringSplitOptions.None); if (comment.IsInline) { Write(" # "); Write(string.Join(" ", array)); } else { bool flag = state == EmitterState.BlockMappingFirstKey; if (flag) { IncreaseIndent(isFlow: false, isIndentless: false); } string[] array2 = array; foreach (string value in array2) { WriteIndent(); Write("# "); Write(value); WriteBreak(); } if (flag) { indent = indents.Pop(); } } isIndentation = true; } private void EmitStreamStart(ParsingEvent evt) { if (!(evt is YamlDotNet.Core.Events.StreamStart)) { throw new ArgumentException("Expected STREAM-START.", "evt"); } indent = -1; column = 0; isWhitespace = true; isIndentation = true; state = EmitterState.FirstDocumentStart; } private void EmitDocumentStart(ParsingEvent evt, bool isFirst) { if (evt is YamlDotNet.Core.Events.DocumentStart documentStart) { bool flag = documentStart.IsImplicit && isFirst && !isCanonical; TagDirectiveCollection tagDirectiveCollection = NonDefaultTagsAmong(documentStart.Tags); if (!isFirst && !isDocumentEndWritten && (documentStart.Version != null || tagDirectiveCollection.Count > 0)) { isDocumentEndWritten = false; WriteIndicator("...", needWhitespace: true, whitespace: false, indentation: false); WriteIndent(); } if (documentStart.Version != null) { AnalyzeVersionDirective(documentStart.Version); Version version = documentStart.Version.Version; flag = false; WriteIndicator("%YAML", needWhitespace: true, whitespace: false, indentation: false); WriteIndicator(string.Format(CultureInfo.InvariantCulture, "{0}.{1}", version.Major, version.Minor), needWhitespace: true, whitespace: false, indentation: false); WriteIndent(); } foreach (TagDirective item in tagDirectiveCollection) { AppendTagDirectiveTo(item, allowDuplicates: false, tagDirectives); } TagDirective[] defaultTagDirectives = Constants.DefaultTagDirectives; for (int i = 0; i < defaultTagDirectives.Length; i++) { AppendTagDirectiveTo(defaultTagDirectives[i], allowDuplicates: true, tagDirectives); } if (tagDirectiveCollection.Count > 0) { flag = false; defaultTagDirectives = Constants.DefaultTagDirectives; for (int i = 0; i < defaultTagDirectives.Length; i++) { AppendTagDirectiveTo(defaultTagDirectives[i], allowDuplicates: true, tagDirectiveCollection); } foreach (TagDirective item2 in tagDirectiveCollection) { WriteIndicator("%TAG", needWhitespace: true, whitespace: false, indentation: false); WriteTagHandle(item2.Handle); WriteTagContent(item2.Prefix, needsWhitespace: true); WriteIndent(); } } if (CheckEmptyDocument()) { flag = false; } if (!flag) { WriteIndent(); WriteIndicator("---", needWhitespace: true, whitespace: false, indentation: false); if (isCanonical) { WriteIndent(); } } state = EmitterState.DocumentContent; } else { if (!(evt is YamlDotNet.Core.Events.StreamEnd)) { throw new YamlException("Expected DOCUMENT-START or STREAM-END"); } state = EmitterState.StreamEnd; } } private TagDirectiveCollection NonDefaultTagsAmong(IEnumerable? tagCollection) { TagDirectiveCollection tagDirectiveCollection = new TagDirectiveCollection(); if (tagCollection == null) { return tagDirectiveCollection; } foreach (TagDirective item2 in tagCollection) { AppendTagDirectiveTo(item2, allowDuplicates: false, tagDirectiveCollection); } TagDirective[] defaultTagDirectives = Constants.DefaultTagDirectives; foreach (TagDirective item in defaultTagDirectives) { tagDirectiveCollection.Remove(item); } return tagDirectiveCollection; } private void AnalyzeVersionDirective(VersionDirective versionDirective) { if (versionDirective.Version.Major != 1 || versionDirective.Version.Minor > 3) { throw new YamlException("Incompatible %YAML directive"); } } private static void AppendTagDirectiveTo(TagDirective value, bool allowDuplicates, TagDirectiveCollection tagDirectives) { if (tagDirectives.Contains(value)) { if (!allowDuplicates) { throw new YamlException("Duplicate %TAG directive."); } } else { tagDirectives.Add(value); } } private void EmitDocumentContent(ParsingEvent evt) { states.Push(EmitterState.DocumentEnd); EmitNode(evt, isMapping: false, isSimpleKey: false); } private void EmitNode(ParsingEvent evt, bool isMapping, bool isSimpleKey) { isMappingContext = isMapping; isSimpleKeyContext = isSimpleKey; switch (evt.Type) { case EventType.Alias: EmitAlias(); break; case EventType.Scalar: EmitScalar(evt); break; case EventType.SequenceStart: EmitSequenceStart(evt); break; case EventType.MappingStart: EmitMappingStart(evt); break; default: throw new YamlException($"Expected SCALAR, SEQUENCE-START, MAPPING-START, or ALIAS, got {evt.Type}"); } } private void EmitAlias() { ProcessAnchor(); state = states.Pop(); } private void EmitScalar(ParsingEvent evt) { SelectScalarStyle(evt); ProcessAnchor(); ProcessTag(); IncreaseIndent(isFlow: true, isIndentless: false); ProcessScalar(); indent = indents.Pop(); state = states.Pop(); } private void SelectScalarStyle(ParsingEvent evt) { YamlDotNet.Core.Events.Scalar scalar = (YamlDotNet.Core.Events.Scalar)evt; ScalarStyle scalarStyle = scalar.Style; bool flag = tagData.Handle == null && tagData.Suffix == null; if (flag && !scalar.IsPlainImplicit && !scalar.IsQuotedImplicit) { throw new YamlException("Neither tag nor isImplicit flags are specified."); } if (scalarStyle == ScalarStyle.Any) { scalarStyle = ((!scalarData.IsMultiline) ? ScalarStyle.Plain : ScalarStyle.Folded); } if (isCanonical) { scalarStyle = ScalarStyle.DoubleQuoted; } if (isSimpleKeyContext && scalarData.IsMultiline) { scalarStyle = ScalarStyle.DoubleQuoted; } if (scalarStyle == ScalarStyle.Plain) { if ((flowLevel != 0 && !scalarData.IsFlowPlainAllowed) || (flowLevel == 0 && !scalarData.IsBlockPlainAllowed)) { scalarStyle = ((scalarData.IsSingleQuotedAllowed && !scalarData.HasSingleQuotes) ? ScalarStyle.SingleQuoted : ScalarStyle.DoubleQuoted); } if (string.IsNullOrEmpty(scalarData.Value) && (flowLevel != 0 || isSimpleKeyContext)) { scalarStyle = ScalarStyle.SingleQuoted; } if (flag && !scalar.IsPlainImplicit) { scalarStyle = ScalarStyle.SingleQuoted; } } if (scalarStyle == ScalarStyle.SingleQuoted && !scalarData.IsSingleQuotedAllowed) { scalarStyle = ScalarStyle.DoubleQuoted; } if ((scalarStyle == ScalarStyle.Literal || scalarStyle == ScalarStyle.Folded) && (!scalarData.IsBlockAllowed || flowLevel != 0 || isSimpleKeyContext)) { scalarStyle = ScalarStyle.DoubleQuoted; } scalarData.Style = scalarStyle; } private void ProcessScalar() { switch (scalarData.Style) { case ScalarStyle.Plain: WritePlainScalar(scalarData.Value, !isSimpleKeyContext); break; case ScalarStyle.SingleQuoted: WriteSingleQuotedScalar(scalarData.Value, !isSimpleKeyContext); break; case ScalarStyle.DoubleQuoted: WriteDoubleQuotedScalar(scalarData.Value, !isSimpleKeyContext); break; case ScalarStyle.Literal: WriteLiteralScalar(scalarData.Value); break; case ScalarStyle.Folded: WriteFoldedScalar(scalarData.Value); break; default: throw new InvalidOperationException(); } } private void WritePlainScalar(string value, bool allowBreaks) { if (!isWhitespace) { Write(' '); } bool flag = false; bool flag2 = false; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (IsSpace(c)) { if (allowBreaks && !flag && column > bestWidth && i + 1 < value.Length && value[i + 1] != ' ') { WriteIndent(); } else { Write(c); } flag = true; continue; } if (IsBreak(c, out var breakChar)) { if (!flag2 && c == '\n') { WriteBreak(); } WriteBreak(breakChar); isIndentation = true; flag2 = true; continue; } if (flag2) { WriteIndent(); } Write(c); isIndentation = false; flag = false; flag2 = false; } isWhitespace = false; isIndentation = false; } private void WriteSingleQuotedScalar(string value, bool allowBreaks) { WriteIndicator("'", needWhitespace: true, whitespace: false, indentation: false); bool flag = false; bool flag2 = false; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (c == ' ') { if (allowBreaks && !flag && column > bestWidth && i != 0 && i + 1 < value.Length && value[i + 1] != ' ') { WriteIndent(); } else { Write(c); } flag = true; continue; } if (IsBreak(c, out var breakChar)) { if (!flag2 && c == '\n') { WriteBreak(); } WriteBreak(breakChar); isIndentation = true; flag2 = true; continue; } if (flag2) { WriteIndent(); } if (c == '\'') { Write(c); } Write(c); isIndentation = false; flag = false; flag2 = false; } WriteIndicator("'", needWhitespace: false, whitespace: false, indentation: false); isWhitespace = false; isIndentation = false; } private void WriteDoubleQuotedScalar(string value, bool allowBreaks) { WriteIndicator("\"", needWhitespace: true, whitespace: false, indentation: false); bool flag = false; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (IsPrintable(c) && !IsBreak(c, out var _)) { switch (c) { case '"': case '\\': break; case ' ': if (allowBreaks && !flag && column > bestWidth && i > 0 && i + 1 < value.Length) { WriteIndent(); if (value[i + 1] == ' ') { Write('\\'); } } else { Write(c); } flag = true; continue; default: Write(c); flag = false; continue; } } Write('\\'); switch (c) { case '\0': Write('0'); break; case '\a': Write('a'); break; case '\b': Write('b'); break; case '\t': Write('t'); break; case '\n': Write('n'); break; case '\v': Write('v'); break; case '\f': Write('f'); break; case '\r': Write('r'); break; case '\u001b': Write('e'); break; case '"': Write('"'); break; case '\\': Write('\\'); break; case '\u0085': Write('N'); break; case '\u00a0': Write('_'); break; case '\u2028': Write('L'); break; case '\u2029': Write('P'); break; default: { ushort num = c; if (num <= 255) { Write('x'); Write(num.ToString("X02", CultureInfo.InvariantCulture)); } else if (IsHighSurrogate(c)) { if (i + 1 >= value.Length || !IsLowSurrogate(value[i + 1])) { throw new SyntaxErrorException("While writing a quoted scalar, found an orphaned high surrogate."); } Write('U'); Write(char.ConvertToUtf32(c, value[i + 1]).ToString("X08", CultureInfo.InvariantCulture)); i++; } else { Write('u'); Write(num.ToString("X04", CultureInfo.InvariantCulture)); } break; } } flag = false; } WriteIndicator("\"", needWhitespace: false, whitespace: false, indentation: false); isWhitespace = false; isIndentation = false; } private void WriteLiteralScalar(string value) { bool flag = true; WriteIndicator("|", needWhitespace: true, whitespace: false, indentation: false); WriteBlockScalarHints(value); WriteBreak(); isIndentation = true; isWhitespace = true; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (c == '\r' && i + 1 < value.Length && value[i + 1] == '\n') { continue; } if (IsBreak(c, out var breakChar)) { WriteBreak(breakChar); isIndentation = true; flag = true; continue; } if (flag) { WriteIndent(); } Write(c); isIndentation = false; flag = false; } } private void WriteFoldedScalar(string value) { bool flag = true; bool flag2 = true; WriteIndicator(">", needWhitespace: true, whitespace: false, indentation: false); WriteBlockScalarHints(value); WriteBreak(); isIndentation = true; isWhitespace = true; for (int i = 0; i < value.Length; i++) { char c = value[i]; if (IsBreak(c, out var breakChar)) { if (c == '\r' && i + 1 < value.Length && value[i + 1] == '\n') { continue; } if (!flag && !flag2 && breakChar == '\n') { int j; char breakChar2; for (j = 0; i + j < value.Length && IsBreak(value[i + j], out breakChar2); j++) { } if (i + j < value.Length && !IsBlank(value[i + j]) && !IsBreak(value[i + j], out breakChar2)) { WriteBreak(); } } WriteBreak(breakChar); isIndentation = true; flag = true; } else { if (flag) { WriteIndent(); flag2 = IsBlank(c); } if (!flag && c == ' ' && i + 1 < value.Length && value[i + 1] != ' ' && column > bestWidth) { WriteIndent(); } else { Write(c); } isIndentation = false; flag = false; } } } private static bool IsSpace(char character) { return character == ' '; } private static bool IsBreak(char character, out char breakChar) { switch (character) { case '\n': case '\r': case '\u0085': breakChar = '\n'; return true; case '\u2028': case '\u2029': breakChar = character; return true; default: breakChar = '\0'; return false; } } private static bool IsBlank(char character) { if (character != ' ') { return character == '\t'; } return true; } private static bool IsPrintable(char character) { switch (character) { default: if (character != '\u0085' && (character < '\u00a0' || character > '\ud7ff')) { if (character >= '\ue000') { return character <= '\ufffd'; } return false; } break; case '\t': case '\n': case '\r': case ' ': case '!': case '"': case '#': case '$': case '%': case '&': case '\'': case '(': case ')': case '*': case '+': case ',': case '-': case '.': case '/': case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': case ':': case ';': case '<': case '=': case '>': case '?': case '@': case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': case 'G': case 'H': case 'I': case 'J': case 'K': case 'L': case 'M': case 'N': case 'O': case 'P': case 'Q': case 'R': case 'S': case 'T': case 'U': case 'V': case 'W': case 'X': case 'Y': case 'Z': case '[': case '\\': case ']': case '^': case '_': case '`': case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': case 'g': case 'h': case 'i': case 'j': case 'k': case 'l': case 'm': case 'n': case 'o': case 'p': case 'q': case 'r': case 's': case 't': case 'u': case 'v': case 'w': case 'x': case 'y': case 'z': case '{': case '|': case '}': case '~': break; } return true; } private static bool IsHighSurrogate(char c) { if ('\ud800' <= c) { return c <= '\udbff'; } return false; } private static bool IsLowSurrogate(char c) { if ('\udc00' <= c) { return c <= '\udfff'; } return false; } private void EmitSequenceStart(ParsingEvent evt) { ProcessAnchor(); ProcessTag(); SequenceStart sequenceStart = (SequenceStart)evt; if (flowLevel != 0 || isCanonical || sequenceStart.Style == SequenceStyle.Flow || CheckEmptySequence()) { state = EmitterState.FlowSequenceFirstItem; } else { state = EmitterState.BlockSequenceFirstItem; } } private void EmitMappingStart(ParsingEvent evt) { ProcessAnchor(); ProcessTag(); MappingStart mappingStart = (MappingStart)evt; if (flowLevel != 0 || isCanonical || mappingStart.Style == MappingStyle.Flow || CheckEmptyMapping()) { state = EmitterState.FlowMappingFirstKey; } else { state = EmitterState.BlockMappingFirstKey; } } private void ProcessAnchor() { if (!anchorData.Anchor.IsEmpty && !skipAnchorName) { WriteIndicator(anchorData.IsAlias ? "*" : "&", needWhitespace: true, whitespace: false, indentation: false); WriteAnchor(anchorData.Anchor); } } private void ProcessTag() { if (tagData.Handle == null && tagData.Suffix == null) { return; } if (tagData.Handle != null) { WriteTagHandle(tagData.Handle); if (tagData.Suffix != null) { WriteTagContent(tagData.Suffix, needsWhitespace: false); } } else { WriteIndicator("!<", needWhitespace: true, whitespace: false, indentation: false); WriteTagContent(tagData.Suffix, needsWhitespace: false); WriteIndicator(">", needWhitespace: false, whitespace: false, indentation: false); } } private void EmitDocumentEnd(ParsingEvent evt) { if (evt is YamlDotNet.Core.Events.DocumentEnd documentEnd) { WriteIndent(); if (!documentEnd.IsImplicit) { WriteIndicator("...", needWhitespace: true, whitespace: false, indentation: false); WriteIndent(); isDocumentEndWritten = true; } state = EmitterState.DocumentStart; tagDirectives.Clear(); return; } throw new YamlException("Expected DOCUMENT-END."); } private void EmitFlowSequenceItem(ParsingEvent evt, bool isFirst) { if (isFirst) { WriteIndicator("[", needWhitespace: true, whitespace: true, indentation: false); IncreaseIndent(isFlow: true, isIndentless: false); flowLevel++; } if (evt is SequenceEnd) { flowLevel--; indent = indents.Pop(); if (isCanonical && !isFirst) { WriteIndicator(",", needWhitespace: false, whitespace: false, indentation: false); WriteIndent(); } WriteIndicator("]", needWhitespace: false, whitespace: false, indentation: false); state = states.Pop(); } else { if (!isFirst) { WriteIndicator(",", needWhitespace: false, whitespace: false, indentation: false); } if (isCanonical || column > bestWidth) { WriteIndent(); } states.Push(EmitterState.FlowSequenceItem); EmitNode(evt, isMapping: false, isSimpleKey: false); } } private void EmitFlowMappingKey(ParsingEvent evt, bool isFirst) { if (isFirst) { WriteIndicator("{", needWhitespace: true, whitespace: true, indentation: false); IncreaseIndent(isFlow: true, isIndentless: false); flowLevel++; } if (evt is MappingEnd) { flowLevel--; indent = indents.Pop(); if (isCanonical && !isFirst) { WriteIndicator(",", needWhitespace: false, whitespace: false, indentation: false); WriteIndent(); } WriteIndicator("}", needWhitespace: false, whitespace: false, indentation: false); state = states.Pop(); return; } if (!isFirst) { WriteIndicator(",", needWhitespace: false, whitespace: false, indentation: false); } if (isCanonical || column > bestWidth) { WriteIndent(); } if (!isCanonical && CheckSimpleKey()) { states.Push(EmitterState.FlowMappingSimpleValue); EmitNode(evt, isMapping: true, isSimpleKey: true); } else { WriteIndicator("?", needWhitespace: true, whitespace: false, indentation: false); states.Push(EmitterState.FlowMappingValue); EmitNode(evt, isMapping: true, isSimpleKey: false); } } private void EmitFlowMappingValue(ParsingEvent evt, bool isSimple) { if (isSimple) { WriteIndicator(":", needWhitespace: false, whitespace: false, indentation: false); } else { if (isCanonical || column > bestWidth) { WriteIndent(); } WriteIndicator(":", needWhitespace: true, whitespace: false, indentation: false); } states.Push(EmitterState.FlowMappingKey); EmitNode(evt, isMapping: true, isSimpleKey: false); } private void EmitBlockSequenceItem(ParsingEvent evt, bool isFirst) { if (isFirst) { IncreaseIndent(isFlow: false, isMappingContext && !isIndentation); } if (evt is SequenceEnd) { indent = indents.Pop(); state = states.Pop(); return; } WriteIndent(); WriteIndicator("-", needWhitespace: true, whitespace: false, indentation: true); states.Push(EmitterState.BlockSequenceItem); EmitNode(evt, isMapping: false, isSimpleKey: false); } private void EmitBlockMappingKey(ParsingEvent evt, bool isFirst) { if (isFirst) { IncreaseIndent(isFlow: false, isIndentless: false); } if (evt is MappingEnd) { indent = indents.Pop(); state = states.Pop(); return; } WriteIndent(); if (CheckSimpleKey()) { states.Push(EmitterState.BlockMappingSimpleValue); EmitNode(evt, isMapping: true, isSimpleKey: true); } else { WriteIndicator("?", needWhitespace: true, whitespace: false, indentation: true); states.Push(EmitterState.BlockMappingValue); EmitNode(evt, isMapping: true, isSimpleKey: false); } } private void EmitBlockMappingValue(ParsingEvent evt, bool isSimple) { if (isSimple) { WriteIndicator(":", needWhitespace: false, whitespace: false, indentation: false); } else { WriteIndent(); WriteIndicator(":", needWhitespace: true, whitespace: false, indentation: true); } states.Push(EmitterState.BlockMappingKey); EmitNode(evt, isMapping: true, isSimpleKey: false); } private void IncreaseIndent(bool isFlow, bool isIndentless) { indents.Push(indent); if (indent < 0) { indent = (isFlow ? bestIndent : 0); } else if (!isIndentless || !forceIndentLess) { indent += bestIndent; } } private bool CheckEmptyDocument() { int num = 0; foreach (ParsingEvent @event in events) { num++; if (num == 2) { if (@event is YamlDotNet.Core.Events.Scalar scalar) { return string.IsNullOrEmpty(scalar.Value); } break; } } return false; } private bool CheckSimpleKey() { if (events.Count < 1) { return false; } int num; switch (events.Peek().Type) { case EventType.Alias: num = AnchorNameLength(anchorData.Anchor); break; case EventType.Scalar: if (scalarData.IsMultiline) { return false; } num = AnchorNameLength(anchorData.Anchor) + SafeStringLength(tagData.Handle) + SafeStringLength(tagData.Suffix) + SafeStringLength(scalarData.Value); break; case EventType.SequenceStart: if (!CheckEmptySequence()) { return false; } num = AnchorNameLength(anchorData.Anchor) + SafeStringLength(tagData.Handle) + SafeStringLength(tagData.Suffix); break; case EventType.MappingStart: if (!CheckEmptySequence()) { return false; } num = AnchorNameLength(anchorData.Anchor) + SafeStringLength(tagData.Handle) + SafeStringLength(tagData.Suffix); break; default: return false; } return num <= maxSimpleKeyLength; } private int AnchorNameLength(AnchorName value) { if (!value.IsEmpty) { return value.Value.Length; } return 0; } private int SafeStringLength(string? value) { return value?.Length ?? 0; } private bool CheckEmptySequence() { return CheckEmptyStructure(); } private bool CheckEmptyMapping() { return CheckEmptyStructure(); } private bool CheckEmptyStructure() where TStart : NodeEvent where TEnd : ParsingEvent { if (events.Count < 2) { return false; } using Queue.Enumerator enumerator = events.GetEnumerator(); return enumerator.MoveNext() && enumerator.Current is TStart && enumerator.MoveNext() && enumerator.Current is TEnd; } private void WriteBlockScalarHints(string value) { CharacterAnalyzer characterAnalyzer = new CharacterAnalyzer(new StringLookAheadBuffer(value)); if (characterAnalyzer.IsSpace() || characterAnalyzer.IsBreak()) { int num = bestIndent; string indicator = num.ToString(CultureInfo.InvariantCulture); WriteIndicator(indicator, needWhitespace: false, whitespace: false, indentation: false); } string text = null; if (value.Length == 0 || !characterAnalyzer.IsBreak(value.Length - 1)) { text = "-"; } else if (value.Length >= 2 && characterAnalyzer.IsBreak(value.Length - 2)) { text = "+"; } if (text != null) { WriteIndicator(text, needWhitespace: false, whitespace: false, indentation: false); } } private void WriteIndicator(string indicator, bool needWhitespace, bool whitespace, bool indentation) { if (needWhitespace && !isWhitespace) { Write(' '); } Write(indicator); isWhitespace = whitespace; isIndentation &= indentation; } private void WriteIndent() { int num = Math.Max(indent, 0); if (!isIndentation || column > num || (column == num && !isWhitespace)) { WriteBreak(); } while (column < num) { Write(' '); } isWhitespace = true; isIndentation = true; } private void WriteAnchor(AnchorName value) { Write(value.Value); isWhitespace = false; isIndentation = false; } private void WriteTagHandle(string value) { if (!isWhitespace) { Write(' '); } Write(value); isWhitespace = false; isIndentation = false; } private void WriteTagContent(string value, bool needsWhitespace) { if (needsWhitespace && !isWhitespace) { Write(' '); } Write(UrlEncode(value)); isWhitespace = false; isIndentation = false; } private static string UrlEncode(string text) { return UriReplacer.Replace(text, delegate(Match match) { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; byte[] bytes = Encoding.UTF8.GetBytes(match.Value); foreach (byte b in bytes) { builder.AppendFormat("%{0:X02}", b); } return builder.ToString(); } finally { ((IDisposable)builderWrapper).Dispose(); } }); } private void Write(char value) { output.Write(value); column++; } private void Write(string value) { output.Write(value); column += value.Length; } private void WriteBreak(char breakCharacter = '\n') { if (breakCharacter == '\n') { output.Write(newLine); } else { output.Write(breakCharacter); } column = 0; } } internal sealed class EmitterSettings { public static readonly EmitterSettings Default = new EmitterSettings(); public int BestIndent { get; } = 2; public int BestWidth { get; } = int.MaxValue; public string NewLine { get; } = Environment.NewLine; public bool IsCanonical { get; } public bool SkipAnchorName { get; private set; } public int MaxSimpleKeyLength { get; } = 1024; public bool IndentSequences { get; } public EmitterSettings() { } public EmitterSettings(int bestIndent, int bestWidth, bool isCanonical, int maxSimpleKeyLength, bool skipAnchorName = false, bool indentSequences = false, string? newLine = null) { if (bestIndent < 2 || bestIndent > 9) { throw new ArgumentOutOfRangeException("bestIndent", "BestIndent must be between 2 and 9, inclusive"); } if (bestWidth <= bestIndent * 2) { throw new ArgumentOutOfRangeException("bestWidth", "BestWidth must be greater than BestIndent x 2."); } if (maxSimpleKeyLength < 0) { throw new ArgumentOutOfRangeException("maxSimpleKeyLength", "MaxSimpleKeyLength must be >= 0"); } BestIndent = bestIndent; BestWidth = bestWidth; IsCanonical = isCanonical; MaxSimpleKeyLength = maxSimpleKeyLength; SkipAnchorName = skipAnchorName; IndentSequences = indentSequences; NewLine = newLine ?? Environment.NewLine; } public EmitterSettings WithBestIndent(int bestIndent) { return new EmitterSettings(bestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, IndentSequences, NewLine); } public EmitterSettings WithBestWidth(int bestWidth) { return new EmitterSettings(BestIndent, bestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, IndentSequences, NewLine); } public EmitterSettings WithMaxSimpleKeyLength(int maxSimpleKeyLength) { return new EmitterSettings(BestIndent, BestWidth, IsCanonical, maxSimpleKeyLength, SkipAnchorName, IndentSequences, NewLine); } public EmitterSettings WithNewLine(string newLine) { return new EmitterSettings(BestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, IndentSequences, newLine); } public EmitterSettings Canonical() { return new EmitterSettings(BestIndent, BestWidth, isCanonical: true, MaxSimpleKeyLength, SkipAnchorName); } public EmitterSettings WithoutAnchorName() { return new EmitterSettings(BestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, skipAnchorName: true, IndentSequences, NewLine); } public EmitterSettings WithIndentedSequences() { return new EmitterSettings(BestIndent, BestWidth, IsCanonical, MaxSimpleKeyLength, SkipAnchorName, indentSequences: true, NewLine); } } internal enum EmitterState { StreamStart, StreamEnd, FirstDocumentStart, DocumentStart, DocumentContent, DocumentEnd, FlowSequenceFirstItem, FlowSequenceItem, FlowMappingFirstKey, FlowMappingKey, FlowMappingSimpleValue, FlowMappingValue, BlockSequenceFirstItem, BlockSequenceItem, BlockMappingFirstKey, BlockMappingKey, BlockMappingSimpleValue, BlockMappingValue } internal sealed class ForwardAnchorNotSupportedException : YamlException { public ForwardAnchorNotSupportedException(string message) : base(message) { } public ForwardAnchorNotSupportedException(in Mark start, in Mark end, string message) : base(in start, in end, message) { } public ForwardAnchorNotSupportedException(string message, Exception inner) : base(message, inner) { } } internal static class HashCode { public static int CombineHashCodes(int h1, int h2) { return ((h1 << 5) + h1) ^ h2; } public static int CombineHashCodes(int h1, object? o2) { return CombineHashCodes(h1, GetHashCode(o2)); } private static int GetHashCode(object? obj) { return obj?.GetHashCode() ?? 0; } } internal interface IEmitter { void Emit(ParsingEvent @event); } internal interface ILookAheadBuffer { bool EndOfInput { get; } char Peek(int offset); void Skip(int length); } internal sealed class InsertionQueue : IEnumerable, IEnumerable { private const int DefaultInitialCapacity = 128; private T[] items; private int readPtr; private int writePtr; private int mask; private int count; public int Count => count; public int Capacity => items.Length; public InsertionQueue(int initialCapacity = 128) { if (initialCapacity <= 0) { throw new ArgumentOutOfRangeException("initialCapacity", "The initial capacity must be a positive number."); } if (!initialCapacity.IsPowerOfTwo()) { throw new ArgumentException("The initial capacity must be a power of 2.", "initialCapacity"); } items = new T[initialCapacity]; readPtr = initialCapacity / 2; writePtr = initialCapacity / 2; mask = initialCapacity - 1; } public void Enqueue(T item) { ResizeIfNeeded(); items[writePtr] = item; writePtr = (writePtr - 1) & mask; count++; } public T Dequeue() { if (count == 0) { throw new InvalidOperationException("The queue is empty"); } T result = items[readPtr]; readPtr = (readPtr - 1) & mask; count--; return result; } public void Insert(int index, T item) { if (index > count) { throw new InvalidOperationException("Cannot insert outside of the bounds of the queue"); } ResizeIfNeeded(); CalculateInsertionParameters(mask, count, index, ref readPtr, ref writePtr, out var insertPtr, out var copyIndex, out var copyOffset, out var copyLength); if (copyLength != 0) { Array.Copy(items, copyIndex, items, copyIndex + copyOffset, copyLength); } items[insertPtr] = item; count++; } private void ResizeIfNeeded() { int num = items.Length; if (count == num) { T[] destinationArray = new T[num * 2]; int num2 = readPtr + 1; if (num2 > 0) { Array.Copy(items, 0, destinationArray, 0, num2); } writePtr += num; int num3 = num - num2; if (num3 > 0) { Array.Copy(items, readPtr + 1, destinationArray, writePtr + 1, num3); } items = destinationArray; mask = mask * 2 + 1; } } internal static void CalculateInsertionParameters(int mask, int count, int index, ref int readPtr, ref int writePtr, out int insertPtr, out int copyIndex, out int copyOffset, out int copyLength) { int num = (readPtr + 1) & mask; if (index == 0) { insertPtr = (readPtr = num); copyIndex = 0; copyOffset = 0; copyLength = 0; return; } insertPtr = (readPtr - index) & mask; if (index == count) { writePtr = (writePtr - 1) & mask; copyIndex = 0; copyOffset = 0; copyLength = 0; return; } int num2 = ((num >= insertPtr) ? (readPtr - insertPtr) : int.MaxValue); int num3 = ((writePtr <= insertPtr) ? (insertPtr - writePtr) : int.MaxValue); if (num2 <= num3) { insertPtr++; readPtr++; copyIndex = insertPtr; copyOffset = 1; copyLength = num2; } else { copyIndex = writePtr + 1; copyOffset = -1; copyLength = num3; writePtr = (writePtr - 1) & mask; } } public IEnumerator GetEnumerator() { int ptr = readPtr; for (int i = 0; i < Count; i++) { yield return items[ptr]; ptr = (ptr - 1) & mask; } } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } internal interface IParser { ParsingEvent? Current { get; } bool MoveNext(); } internal interface IScanner { Mark CurrentPosition { get; } Token? Current { get; } bool MoveNext(); bool MoveNextWithoutConsuming(); void ConsumeCurrent(); } [DebuggerStepThrough] internal sealed class LookAheadBuffer : ILookAheadBuffer { private readonly TextReader input; private readonly char[] buffer; private readonly int blockSize; private readonly int mask; private int firstIndex; private int writeOffset; private int count; private bool endOfInput; public bool EndOfInput { get { if (endOfInput) { return count == 0; } return false; } } public LookAheadBuffer(TextReader input, int capacity) { if (capacity < 1) { throw new ArgumentOutOfRangeException("capacity", "The capacity must be positive."); } if (!capacity.IsPowerOfTwo()) { throw new ArgumentException("The capacity must be a power of 2.", "capacity"); } this.input = input ?? throw new ArgumentNullException("input"); blockSize = capacity; buffer = new char[capacity * 2]; mask = capacity * 2 - 1; } private int GetIndexForOffset(int offset) { return (firstIndex + offset) & mask; } public char Peek(int offset) { if (offset >= count) { FillBuffer(); } if (offset < count) { return buffer[(firstIndex + offset) & mask]; } return '\0'; } public void Cache(int length) { if (length >= count) { FillBuffer(); } } private void FillBuffer() { if (endOfInput) { return; } int num = blockSize; do { int num2 = input.Read(buffer, writeOffset, num); if (num2 == 0) { endOfInput = true; return; } num -= num2; writeOffset += num2; count += num2; } while (num > 0); if (writeOffset == buffer.Length) { writeOffset = 0; } } public void Skip(int length) { if (length < 1 || length > blockSize) { throw new ArgumentOutOfRangeException("length", "The length must be between 1 and the number of characters in the buffer. Use the Peek() and / or Cache() methods to fill the buffer."); } firstIndex = GetIndexForOffset(length); count -= length; } } internal readonly struct Mark : IEquatable, IComparable, IComparable { public static readonly Mark Empty = new Mark(0, 1, 1); public int Index { get; } public int Line { get; } public int Column { get; } public Mark(int index, int line, int column) { if (index < 0) { ThrowHelper.ThrowArgumentOutOfRangeException("index", "Index must be greater than or equal to zero."); } if (line < 1) { ThrowHelper.ThrowArgumentOutOfRangeException("line", "Line must be greater than or equal to 1."); } if (column < 1) { ThrowHelper.ThrowArgumentOutOfRangeException("column", "Column must be greater than or equal to 1."); } Index = index; Line = line; Column = column; } public override string ToString() { return $"Line: {Line}, Col: {Column}, Idx: {Index}"; } public override bool Equals(object? obj) { return Equals((Mark)(obj ?? ((object)Empty))); } public bool Equals(Mark other) { if (Index == other.Index && Line == other.Line) { return Column == other.Column; } return false; } public override int GetHashCode() { return HashCode.CombineHashCodes(Index.GetHashCode(), HashCode.CombineHashCodes(Line.GetHashCode(), Column.GetHashCode())); } public int CompareTo(object? obj) { return CompareTo((Mark)(obj ?? ((object)Empty))); } public int CompareTo(Mark other) { int num = Line.CompareTo(other.Line); if (num == 0) { num = Column.CompareTo(other.Column); } return num; } } internal sealed class MaximumRecursionLevelReachedException : YamlException { public MaximumRecursionLevelReachedException(string message) : base(message) { } public MaximumRecursionLevelReachedException(in Mark start, in Mark end, string message) : base(in start, in end, message) { } public MaximumRecursionLevelReachedException(string message, Exception inner) : base(message, inner) { } } internal sealed class MergingParser : IParser { private sealed class ParsingEventCollection : IEnumerable>, IEnumerable { private readonly LinkedList events; private readonly HashSet> deleted; private readonly Dictionary> references; public ParsingEventCollection() { events = new LinkedList(); deleted = new HashSet>(); references = new Dictionary>(); } public void AddAfter(LinkedListNode node, IEnumerable items) { foreach (ParsingEvent item in items) { node = events.AddAfter(node, item); } } public void Add(ParsingEvent item) { LinkedListNode node = events.AddLast(item); AddReference(item, node); } public void MarkDeleted(LinkedListNode node) { deleted.Add(node); } public void CleanMarked() { foreach (LinkedListNode item in deleted) { events.Remove(item); } } public IEnumerable> FromAnchor(AnchorName anchor) { LinkedListNode next = references[anchor].Next; return Enumerate(next); } public IEnumerator> GetEnumerator() { return Enumerate(events.First).GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } private IEnumerable> Enumerate(LinkedListNode? node) { while (node != null) { yield return node; node = node.Next; } } private void AddReference(ParsingEvent item, LinkedListNode node) { if (item is MappingStart mappingStart) { AnchorName anchor = mappingStart.Anchor; if (!anchor.IsEmpty) { references[anchor] = node; } } } } private sealed class ParsingEventCloner : IParsingEventVisitor { private ParsingEvent? clonedEvent; public ParsingEvent Clone(ParsingEvent e) { e.Accept(this); if (clonedEvent == null) { throw new InvalidOperationException($"Could not clone event of type '{e.Type}'"); } return clonedEvent; } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.AnchorAlias e) { clonedEvent = new YamlDotNet.Core.Events.AnchorAlias(e.Value, e.Start, e.End); } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.StreamStart e) { throw new NotSupportedException(); } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.StreamEnd e) { throw new NotSupportedException(); } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.DocumentStart e) { throw new NotSupportedException(); } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.DocumentEnd e) { throw new NotSupportedException(); } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.Scalar e) { clonedEvent = new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, e.Tag, e.Value, e.Style, e.IsPlainImplicit, e.IsQuotedImplicit, e.Start, e.End); } void IParsingEventVisitor.Visit(SequenceStart e) { clonedEvent = new SequenceStart(AnchorName.Empty, e.Tag, e.IsImplicit, e.Style, e.Start, e.End); } void IParsingEventVisitor.Visit(SequenceEnd e) { Mark start = e.Start; Mark end = e.End; clonedEvent = new SequenceEnd(in start, in end); } void IParsingEventVisitor.Visit(MappingStart e) { clonedEvent = new MappingStart(AnchorName.Empty, e.Tag, e.IsImplicit, e.Style, e.Start, e.End); } void IParsingEventVisitor.Visit(MappingEnd e) { Mark start = e.Start; Mark end = e.End; clonedEvent = new MappingEnd(in start, in end); } void IParsingEventVisitor.Visit(YamlDotNet.Core.Events.Comment e) { throw new NotSupportedException(); } } private readonly ParsingEventCollection events; private readonly IParser innerParser; private IEnumerator> iterator; private bool merged; public ParsingEvent? Current => iterator.Current?.Value; public MergingParser(IParser innerParser) { events = new ParsingEventCollection(); merged = false; iterator = events.GetEnumerator(); this.innerParser = innerParser; } public bool MoveNext() { if (!merged) { Merge(); events.CleanMarked(); iterator = events.GetEnumerator(); merged = true; } return iterator.MoveNext(); } private void Merge() { while (innerParser.MoveNext()) { events.Add(innerParser.Current); } foreach (LinkedListNode @event in events) { if (IsMergeToken(@event)) { events.MarkDeleted(@event); if (!HandleMerge(@event.Next)) { Mark start = @event.Value.Start; Mark end = @event.Value.End; throw new SemanticErrorException(in start, in end, "Unrecognized merge key pattern"); } } } } private bool HandleMerge(LinkedListNode? node) { if (node == null) { return false; } if (node.Value is YamlDotNet.Core.Events.AnchorAlias anchorAlias) { return HandleAnchorAlias(node, node, anchorAlias); } if (node.Value is SequenceStart) { return HandleSequence(node); } return false; } private bool HandleMergeSequence(LinkedListNode sequenceStart, LinkedListNode? node) { if (node == null) { return false; } if (node.Value is YamlDotNet.Core.Events.AnchorAlias anchorAlias) { return HandleAnchorAlias(sequenceStart, node, anchorAlias); } if (node.Value is SequenceStart) { return HandleSequence(node); } return false; } private bool IsMergeToken(LinkedListNode node) { if (node.Value is YamlDotNet.Core.Events.Scalar scalar) { return scalar.Value == "<<"; } return false; } private bool HandleAnchorAlias(LinkedListNode node, LinkedListNode anchorNode, YamlDotNet.Core.Events.AnchorAlias anchorAlias) { IEnumerable mappingEvents = GetMappingEvents(anchorAlias.Value); events.AddAfter(node, mappingEvents); events.MarkDeleted(anchorNode); return true; } private bool HandleSequence(LinkedListNode node) { events.MarkDeleted(node); LinkedListNode linkedListNode = node; while (linkedListNode != null) { if (linkedListNode.Value is SequenceEnd && linkedListNode.Value.Start.Line >= node.Value.Start.Line) { events.MarkDeleted(linkedListNode); return true; } LinkedListNode next = linkedListNode.Next; HandleMergeSequence(node, next); linkedListNode = next; } return true; } private IEnumerable GetMappingEvents(AnchorName anchor) { ParsingEventCloner cloner = new ParsingEventCloner(); int nesting = 0; return from e in (from e in events.FromAnchor(anchor) select e.Value).TakeWhile((ParsingEvent e) => (nesting += e.NestingIncrease) >= 0) select cloner.Clone(e); } } internal class Parser : IParser { private class EventQueue { private readonly Queue highPriorityEvents = new Queue(); private readonly Queue normalPriorityEvents = new Queue(); public int Count => highPriorityEvents.Count + normalPriorityEvents.Count; public void Enqueue(ParsingEvent @event) { EventType type = @event.Type; if (type == EventType.StreamStart || type == EventType.DocumentStart) { highPriorityEvents.Enqueue(@event); } else { normalPriorityEvents.Enqueue(@event); } } public ParsingEvent Dequeue() { if (highPriorityEvents.Count <= 0) { return normalPriorityEvents.Dequeue(); } return highPriorityEvents.Dequeue(); } } private readonly Stack states = new Stack(); private readonly TagDirectiveCollection tagDirectives = new TagDirectiveCollection(); private ParserState state; private readonly IScanner scanner; private Token? currentToken; private VersionDirective? version; private readonly EventQueue pendingEvents = new EventQueue(); public ParsingEvent? Current { get; private set; } private Token? GetCurrentToken() { if (currentToken == null) { while (scanner.MoveNextWithoutConsuming()) { currentToken = scanner.Current; if (!(currentToken is YamlDotNet.Core.Tokens.Comment comment)) { break; } pendingEvents.Enqueue(new YamlDotNet.Core.Events.Comment(comment.Value, comment.IsInline, comment.Start, comment.End)); scanner.ConsumeCurrent(); } } return currentToken; } public Parser(TextReader input) : this(new Scanner(input)) { } public Parser(IScanner scanner) { this.scanner = scanner; } public bool MoveNext() { if (state == ParserState.StreamEnd) { Current = null; return false; } if (pendingEvents.Count == 0) { pendingEvents.Enqueue(StateMachine()); } Current = pendingEvents.Dequeue(); return true; } private ParsingEvent StateMachine() { return state switch { ParserState.StreamStart => ParseStreamStart(), ParserState.ImplicitDocumentStart => ParseDocumentStart(isImplicit: true), ParserState.DocumentStart => ParseDocumentStart(isImplicit: false), ParserState.DocumentContent => ParseDocumentContent(), ParserState.DocumentEnd => ParseDocumentEnd(), ParserState.BlockNode => ParseNode(isBlock: true, isIndentlessSequence: false), ParserState.BlockNodeOrIndentlessSequence => ParseNode(isBlock: true, isIndentlessSequence: true), ParserState.FlowNode => ParseNode(isBlock: false, isIndentlessSequence: false), ParserState.BlockSequenceFirstEntry => ParseBlockSequenceEntry(isFirst: true), ParserState.BlockSequenceEntry => ParseBlockSequenceEntry(isFirst: false), ParserState.IndentlessSequenceEntry => ParseIndentlessSequenceEntry(), ParserState.BlockMappingFirstKey => ParseBlockMappingKey(isFirst: true), ParserState.BlockMappingKey => ParseBlockMappingKey(isFirst: false), ParserState.BlockMappingValue => ParseBlockMappingValue(), ParserState.FlowSequenceFirstEntry => ParseFlowSequenceEntry(isFirst: true), ParserState.FlowSequenceEntry => ParseFlowSequenceEntry(isFirst: false), ParserState.FlowSequenceEntryMappingKey => ParseFlowSequenceEntryMappingKey(), ParserState.FlowSequenceEntryMappingValue => ParseFlowSequenceEntryMappingValue(), ParserState.FlowSequenceEntryMappingEnd => ParseFlowSequenceEntryMappingEnd(), ParserState.FlowMappingFirstKey => ParseFlowMappingKey(isFirst: true), ParserState.FlowMappingKey => ParseFlowMappingKey(isFirst: false), ParserState.FlowMappingValue => ParseFlowMappingValue(isEmpty: false), ParserState.FlowMappingEmptyValue => ParseFlowMappingValue(isEmpty: true), _ => throw new InvalidOperationException(), }; } private void Skip() { if (currentToken != null) { currentToken = null; scanner.ConsumeCurrent(); } } private ParsingEvent ParseStreamStart() { Token token = GetCurrentToken(); Mark start; Mark end; if (!(token is YamlDotNet.Core.Tokens.StreamStart streamStart)) { start = token?.Start ?? Mark.Empty; end = token?.End ?? Mark.Empty; throw new SemanticErrorException(in start, in end, "Did not find expected ."); } Skip(); state = ParserState.ImplicitDocumentStart; start = streamStart.Start; end = streamStart.End; return new YamlDotNet.Core.Events.StreamStart(in start, in end); } private ParsingEvent ParseDocumentStart(bool isImplicit) { if (currentToken is VersionDirective) { throw new SyntaxErrorException("While parsing a document start node, could not find document end marker before version directive."); } Token token = GetCurrentToken(); if (!isImplicit) { while (token is YamlDotNet.Core.Tokens.DocumentEnd) { Skip(); token = GetCurrentToken(); } } if (token == null) { throw new SyntaxErrorException("Reached the end of the stream while parsing a document start."); } if (token is YamlDotNet.Core.Tokens.Scalar && (state == ParserState.ImplicitDocumentStart || state == ParserState.DocumentStart)) { isImplicit = true; } if ((isImplicit && !(token is VersionDirective) && !(token is TagDirective) && !(token is YamlDotNet.Core.Tokens.DocumentStart) && !(token is YamlDotNet.Core.Tokens.StreamEnd) && !(token is YamlDotNet.Core.Tokens.DocumentEnd)) || token is BlockMappingStart) { TagDirectiveCollection tags = new TagDirectiveCollection(); ProcessDirectives(tags); states.Push(ParserState.DocumentEnd); state = ParserState.BlockNode; return new YamlDotNet.Core.Events.DocumentStart(null, tags, isImplicit: true, token.Start, token.End); } Mark start2; Mark end; if (!(token is YamlDotNet.Core.Tokens.StreamEnd) && !(token is YamlDotNet.Core.Tokens.DocumentEnd)) { Mark start = token.Start; TagDirectiveCollection tags2 = new TagDirectiveCollection(); VersionDirective? versionDirective = ProcessDirectives(tags2); token = GetCurrentToken() ?? throw new SemanticErrorException("Reached the end of the stream while parsing a document start"); if (!(token is YamlDotNet.Core.Tokens.DocumentStart)) { start2 = token.Start; end = token.End; throw new SemanticErrorException(in start2, in end, "Did not find expected ."); } states.Push(ParserState.DocumentEnd); state = ParserState.DocumentContent; Mark end2 = token.End; Skip(); return new YamlDotNet.Core.Events.DocumentStart(versionDirective, tags2, isImplicit: false, start, end2); } if (token is YamlDotNet.Core.Tokens.DocumentEnd) { Skip(); } state = ParserState.StreamEnd; token = GetCurrentToken() ?? throw new SemanticErrorException("Reached the end of the stream while parsing a document start"); start2 = token.Start; end = token.End; YamlDotNet.Core.Events.StreamEnd result = new YamlDotNet.Core.Events.StreamEnd(in start2, in end); if (scanner.MoveNextWithoutConsuming()) { throw new InvalidOperationException("The scanner should contain no more tokens."); } return result; } private VersionDirective? ProcessDirectives(TagDirectiveCollection tags) { bool flag = false; VersionDirective result = null; while (true) { if (GetCurrentToken() is VersionDirective versionDirective) { if (version != null) { Mark start = versionDirective.Start; Mark end = versionDirective.End; throw new SemanticErrorException(in start, in end, "Found duplicate %YAML directive."); } if (versionDirective.Version.Major != 1 || versionDirective.Version.Minor > 3) { Mark start = versionDirective.Start; Mark end = versionDirective.End; throw new SemanticErrorException(in start, in end, "Found incompatible YAML document."); } result = (version = versionDirective); flag = true; } else { if (!(GetCurrentToken() is TagDirective tagDirective)) { break; } if (tags.Contains(tagDirective.Handle)) { Mark start = tagDirective.Start; Mark end = tagDirective.End; throw new SemanticErrorException(in start, in end, "Found duplicate %TAG directive."); } tags.Add(tagDirective); flag = true; } Skip(); } if (GetCurrentToken() is YamlDotNet.Core.Tokens.DocumentStart && (version == null || (version.Version.Major == 1 && version.Version.Minor > 1))) { if (GetCurrentToken() is YamlDotNet.Core.Tokens.DocumentStart && version == null) { version = new VersionDirective(new Version(1, 2)); } flag = true; } AddTagDirectives(tags, Constants.DefaultTagDirectives); if (flag) { tagDirectives.Clear(); } AddTagDirectives(tagDirectives, tags); return result; } private static void AddTagDirectives(TagDirectiveCollection directives, IEnumerable source) { foreach (TagDirective item in source) { if (!directives.Contains(item)) { directives.Add(item); } } } private ParsingEvent ParseDocumentContent() { if (GetCurrentToken() is VersionDirective || GetCurrentToken() is TagDirective || GetCurrentToken() is YamlDotNet.Core.Tokens.DocumentStart || GetCurrentToken() is YamlDotNet.Core.Tokens.DocumentEnd || GetCurrentToken() is YamlDotNet.Core.Tokens.StreamEnd) { state = states.Pop(); Mark position = scanner.CurrentPosition; return ProcessEmptyScalar(in position); } return ParseNode(isBlock: true, isIndentlessSequence: false); } private static ParsingEvent ProcessEmptyScalar(in Mark position) { return new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, string.Empty, ScalarStyle.Plain, isPlainImplicit: true, isQuotedImplicit: false, position, position); } private ParsingEvent ParseNode(bool isBlock, bool isIndentlessSequence) { Mark start; Mark end; if (GetCurrentToken() is Error error) { start = error.Start; end = error.End; throw new SemanticErrorException(in start, in end, error.Value); } Token token = GetCurrentToken() ?? throw new SemanticErrorException("Reached the end of the stream while parsing a node"); if (token is YamlDotNet.Core.Tokens.AnchorAlias anchorAlias) { state = states.Pop(); YamlDotNet.Core.Events.AnchorAlias result = new YamlDotNet.Core.Events.AnchorAlias(anchorAlias.Value, anchorAlias.Start, anchorAlias.End); Skip(); return result; } Mark start2 = token.Start; AnchorName anchor = AnchorName.Empty; TagName tag = TagName.Empty; Anchor anchor2 = null; Tag tag2 = null; while (true) { if (anchor.IsEmpty && token is Anchor anchor3) { anchor2 = anchor3; anchor = anchor3.Value; Skip(); } else { if (!tag.IsEmpty || !(token is Tag tag3)) { if (token is Anchor anchor4) { start = anchor4.Start; end = anchor4.End; throw new SemanticErrorException(in start, in end, "While parsing a node, found more than one anchor."); } if (token is YamlDotNet.Core.Tokens.AnchorAlias anchorAlias2) { start = anchorAlias2.Start; end = anchorAlias2.End; throw new SemanticErrorException(in start, in end, "While parsing a node, did not find expected token."); } if (!(token is Error error2)) { break; } if (tag2 != null && anchor2 != null && !anchor.IsEmpty) { return new YamlDotNet.Core.Events.Scalar(anchor, default(TagName), string.Empty, ScalarStyle.Any, isPlainImplicit: false, isQuotedImplicit: false, anchor2.Start, anchor2.End); } start = error2.Start; end = error2.End; throw new SemanticErrorException(in start, in end, error2.Value); } tag2 = tag3; if (string.IsNullOrEmpty(tag3.Handle)) { tag = new TagName(tag3.Suffix); } else { if (!tagDirectives.Contains(tag3.Handle)) { start = tag3.Start; end = tag3.End; throw new SemanticErrorException(in start, in end, "While parsing a node, found undefined tag handle."); } tag = new TagName(tagDirectives[tag3.Handle].Prefix + tag3.Suffix); } Skip(); } token = GetCurrentToken() ?? throw new SemanticErrorException("Reached the end of the stream while parsing a node"); } bool isEmpty = tag.IsEmpty; if (isIndentlessSequence && GetCurrentToken() is BlockEntry) { state = ParserState.IndentlessSequenceEntry; return new SequenceStart(anchor, tag, isEmpty, SequenceStyle.Block, start2, token.End); } if (token is YamlDotNet.Core.Tokens.Scalar scalar) { bool isPlainImplicit = false; bool isQuotedImplicit = false; if ((scalar.Style == ScalarStyle.Plain && tag.IsEmpty) || tag.IsNonSpecific) { isPlainImplicit = true; } else if (tag.IsEmpty) { isQuotedImplicit = true; } state = states.Pop(); Skip(); YamlDotNet.Core.Events.Scalar result2 = new YamlDotNet.Core.Events.Scalar(anchor, tag, scalar.Value, scalar.Style, isPlainImplicit, isQuotedImplicit, start2, scalar.End, scalar.IsKey); if (!anchor.IsEmpty && scanner.MoveNextWithoutConsuming()) { currentToken = scanner.Current; if (currentToken is Error) { Error error3 = currentToken as Error; start = error3.Start; end = error3.End; throw new SemanticErrorException(in start, in end, error3.Value); } } if (state == ParserState.FlowMappingKey && scanner.MoveNextWithoutConsuming()) { currentToken = scanner.Current; if (currentToken != null && !(currentToken is FlowEntry) && !(currentToken is FlowMappingEnd)) { start = currentToken.Start; end = currentToken.End; throw new SemanticErrorException(in start, in end, "While parsing a flow mapping, did not find expected ',' or '}'."); } } return result2; } if (token is FlowSequenceStart flowSequenceStart) { state = ParserState.FlowSequenceFirstEntry; return new SequenceStart(anchor, tag, isEmpty, SequenceStyle.Flow, start2, flowSequenceStart.End); } if (token is FlowMappingStart flowMappingStart) { state = ParserState.FlowMappingFirstKey; return new MappingStart(anchor, tag, isEmpty, MappingStyle.Flow, start2, flowMappingStart.End); } if (isBlock) { if (token is BlockSequenceStart blockSequenceStart) { state = ParserState.BlockSequenceFirstEntry; return new SequenceStart(anchor, tag, isEmpty, SequenceStyle.Block, start2, blockSequenceStart.End); } if (token is BlockMappingStart blockMappingStart) { state = ParserState.BlockMappingFirstKey; return new MappingStart(anchor, tag, isEmpty, MappingStyle.Block, start2, blockMappingStart.End); } } if (!anchor.IsEmpty || !tag.IsEmpty) { state = states.Pop(); return new YamlDotNet.Core.Events.Scalar(anchor, tag, string.Empty, ScalarStyle.Plain, isEmpty, isQuotedImplicit: false, start2, token.End); } start = token.Start; end = token.End; throw new SemanticErrorException(in start, in end, "While parsing a node, did not find expected node content."); } private ParsingEvent ParseDocumentEnd() { Token token = GetCurrentToken() ?? throw new SemanticErrorException("Reached the end of the stream while parsing a document end"); bool isImplicit = true; Mark start = token.Start; Mark end = start; if (token is YamlDotNet.Core.Tokens.DocumentEnd) { end = token.End; Skip(); isImplicit = false; } else if (!(currentToken is YamlDotNet.Core.Tokens.StreamEnd) && !(currentToken is YamlDotNet.Core.Tokens.DocumentStart) && !(currentToken is FlowSequenceEnd) && !(currentToken is VersionDirective) && (!(Current is YamlDotNet.Core.Events.Scalar) || !(currentToken is Error))) { throw new SemanticErrorException(in start, in end, "Did not find expected ."); } if (version != null && version.Version.Major == 1 && version.Version.Minor > 1) { version = null; } state = ParserState.DocumentStart; return new YamlDotNet.Core.Events.DocumentEnd(isImplicit, start, end); } private ParsingEvent ParseBlockSequenceEntry(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } Token token = GetCurrentToken(); if (token is BlockEntry blockEntry) { Mark position = blockEntry.End; Skip(); token = GetCurrentToken(); if (!(token is BlockEntry) && !(token is BlockEnd)) { states.Push(ParserState.BlockSequenceEntry); return ParseNode(isBlock: true, isIndentlessSequence: false); } state = ParserState.BlockSequenceEntry; return ProcessEmptyScalar(in position); } Mark start; Mark end; if (token is BlockEnd blockEnd) { state = states.Pop(); start = blockEnd.Start; end = blockEnd.End; SequenceEnd result = new SequenceEnd(in start, in end); Skip(); return result; } start = token?.Start ?? Mark.Empty; end = token?.End ?? Mark.Empty; throw new SemanticErrorException(in start, in end, "While parsing a block collection, did not find expected '-' indicator."); } private ParsingEvent ParseIndentlessSequenceEntry() { Token token = GetCurrentToken(); if (token is BlockEntry blockEntry) { Mark position = blockEntry.End; Skip(); token = GetCurrentToken(); if (!(token is BlockEntry) && !(token is Key) && !(token is Value) && !(token is BlockEnd)) { states.Push(ParserState.IndentlessSequenceEntry); return ParseNode(isBlock: true, isIndentlessSequence: false); } state = ParserState.IndentlessSequenceEntry; return ProcessEmptyScalar(in position); } state = states.Pop(); Mark start = token?.Start ?? Mark.Empty; Mark end = token?.End ?? Mark.Empty; return new SequenceEnd(in start, in end); } private ParsingEvent ParseBlockMappingKey(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } Token token = GetCurrentToken(); if (token is Key key) { Mark position = key.End; Skip(); token = GetCurrentToken(); if (!(token is Key) && !(token is Value) && !(token is BlockEnd)) { states.Push(ParserState.BlockMappingValue); return ParseNode(isBlock: true, isIndentlessSequence: true); } state = ParserState.BlockMappingValue; return ProcessEmptyScalar(in position); } Mark position2; if (token is Value value) { Skip(); position2 = value.End; return ProcessEmptyScalar(in position2); } if (token is YamlDotNet.Core.Tokens.AnchorAlias anchorAlias) { Skip(); return new YamlDotNet.Core.Events.AnchorAlias(anchorAlias.Value, anchorAlias.Start, anchorAlias.End); } Mark end; if (token is BlockEnd blockEnd) { state = states.Pop(); position2 = blockEnd.Start; end = blockEnd.End; MappingEnd result = new MappingEnd(in position2, in end); Skip(); return result; } if (GetCurrentToken() is Error error) { position2 = error.Start; end = error.End; throw new SyntaxErrorException(in position2, in end, error.Value); } position2 = token?.Start ?? Mark.Empty; end = token?.End ?? Mark.Empty; throw new SemanticErrorException(in position2, in end, "While parsing a block mapping, did not find expected key."); } private ParsingEvent ParseBlockMappingValue() { Token token = GetCurrentToken(); if (token is Value value) { Mark position = value.End; Skip(); token = GetCurrentToken(); if (!(token is Key) && !(token is Value) && !(token is BlockEnd)) { states.Push(ParserState.BlockMappingKey); return ParseNode(isBlock: true, isIndentlessSequence: true); } state = ParserState.BlockMappingKey; return ProcessEmptyScalar(in position); } Mark start; if (token is Error error) { start = error.Start; Mark end = error.End; throw new SemanticErrorException(in start, in end, error.Value); } state = ParserState.BlockMappingKey; start = token?.Start ?? Mark.Empty; return ProcessEmptyScalar(in start); } private ParsingEvent ParseFlowSequenceEntry(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } Token token = GetCurrentToken(); Mark start; Mark end; if (!(token is FlowSequenceEnd)) { if (!isFirst) { if (!(token is FlowEntry)) { start = token?.Start ?? Mark.Empty; end = token?.End ?? Mark.Empty; throw new SemanticErrorException(in start, in end, "While parsing a flow sequence, did not find expected ',' or ']'."); } Skip(); token = GetCurrentToken(); } if (token is Key) { state = ParserState.FlowSequenceEntryMappingKey; MappingStart result = new MappingStart(AnchorName.Empty, TagName.Empty, isImplicit: true, MappingStyle.Flow); Skip(); return result; } if (!(token is FlowSequenceEnd)) { states.Push(ParserState.FlowSequenceEntry); return ParseNode(isBlock: false, isIndentlessSequence: false); } } state = states.Pop(); start = token?.Start ?? Mark.Empty; end = token?.End ?? Mark.Empty; SequenceEnd result2 = new SequenceEnd(in start, in end); Skip(); return result2; } private ParsingEvent ParseFlowSequenceEntryMappingKey() { Token token = GetCurrentToken(); if (!(token is Value) && !(token is FlowEntry) && !(token is FlowSequenceEnd)) { states.Push(ParserState.FlowSequenceEntryMappingValue); return ParseNode(isBlock: false, isIndentlessSequence: false); } Mark position = token?.End ?? Mark.Empty; Skip(); state = ParserState.FlowSequenceEntryMappingValue; return ProcessEmptyScalar(in position); } private ParsingEvent ParseFlowSequenceEntryMappingValue() { Token token = GetCurrentToken(); if (token is Value) { Skip(); token = GetCurrentToken(); if (!(token is FlowEntry) && !(token is FlowSequenceEnd)) { states.Push(ParserState.FlowSequenceEntryMappingEnd); return ParseNode(isBlock: false, isIndentlessSequence: false); } } state = ParserState.FlowSequenceEntryMappingEnd; Mark position = token?.Start ?? Mark.Empty; return ProcessEmptyScalar(in position); } private ParsingEvent ParseFlowSequenceEntryMappingEnd() { state = ParserState.FlowSequenceEntry; Token token = GetCurrentToken(); Mark start = token?.Start ?? Mark.Empty; Mark end = token?.End ?? Mark.Empty; return new MappingEnd(in start, in end); } private ParsingEvent ParseFlowMappingKey(bool isFirst) { if (isFirst) { GetCurrentToken(); Skip(); } Token token = GetCurrentToken(); Mark start; Mark end; if (!(token is FlowMappingEnd)) { if (!isFirst) { if (token is FlowEntry) { Skip(); token = GetCurrentToken(); } else if (!(token is YamlDotNet.Core.Tokens.Scalar)) { start = token?.Start ?? Mark.Empty; end = token?.End ?? Mark.Empty; throw new SemanticErrorException(in start, in end, "While parsing a flow mapping, did not find expected ',' or '}'."); } } if (token is Key) { Skip(); token = GetCurrentToken(); if (!(token is Value) && !(token is FlowEntry) && !(token is FlowMappingEnd)) { states.Push(ParserState.FlowMappingValue); return ParseNode(isBlock: false, isIndentlessSequence: false); } state = ParserState.FlowMappingValue; start = token?.Start ?? Mark.Empty; return ProcessEmptyScalar(in start); } if (token is YamlDotNet.Core.Tokens.Scalar) { states.Push(ParserState.FlowMappingValue); return ParseNode(isBlock: false, isIndentlessSequence: false); } if (!(token is FlowMappingEnd)) { states.Push(ParserState.FlowMappingEmptyValue); return ParseNode(isBlock: false, isIndentlessSequence: false); } } state = states.Pop(); Skip(); start = token?.Start ?? Mark.Empty; end = token?.End ?? Mark.Empty; return new MappingEnd(in start, in end); } private ParsingEvent ParseFlowMappingValue(bool isEmpty) { Token token = GetCurrentToken(); if (!isEmpty && token is Value) { Skip(); token = GetCurrentToken(); if (!(token is FlowEntry) && !(token is FlowMappingEnd)) { states.Push(ParserState.FlowMappingKey); return ParseNode(isBlock: false, isIndentlessSequence: false); } } state = ParserState.FlowMappingKey; if (!isEmpty && token is YamlDotNet.Core.Tokens.Scalar scalar) { Skip(); return new YamlDotNet.Core.Events.Scalar(AnchorName.Empty, TagName.Empty, scalar.Value, scalar.Style, isPlainImplicit: false, isQuotedImplicit: false, token.Start, scalar.End); } Mark position = token?.Start ?? Mark.Empty; return ProcessEmptyScalar(in position); } } internal static class ParserExtensions { public static T Consume(this IParser parser) where T : ParsingEvent { T result = parser.Require(); parser.MoveNext(); return result; } public static bool TryConsume(this IParser parser, [MaybeNullWhen(false)] out T @event) where T : ParsingEvent { if (parser.Accept(out @event)) { parser.MoveNext(); return true; } return false; } public static T Require(this IParser parser) where T : ParsingEvent { if (!parser.Accept(out var @event)) { ParsingEvent current = parser.Current; if (current == null) { throw new YamlException("Expected '" + typeof(T).Name + "', got nothing."); } Mark start = current.Start; Mark end = current.End; throw new YamlException(in start, in end, $"Expected '{typeof(T).Name}', got '{current.GetType().Name}' (at {current.Start})."); } return @event; } public static bool Accept(this IParser parser, [MaybeNullWhen(false)] out T @event) where T : ParsingEvent { if (parser.Current == null && !parser.MoveNext()) { throw new EndOfStreamException(); } if (parser.Current is T val) { @event = val; return true; } @event = null; return false; } public static void SkipThisAndNestedEvents(this IParser parser) { int num = 0; do { ParsingEvent parsingEvent = parser.Consume(); num += parsingEvent.NestingIncrease; } while (num > 0); } [Obsolete("Please use Consume() instead")] public static T Expect(this IParser parser) where T : ParsingEvent { return parser.Consume(); } [Obsolete("Please use TryConsume(out var evt) instead")] [return: MaybeNull] public static T? Allow(this IParser parser) where T : ParsingEvent { if (!parser.TryConsume(out var @event)) { return null; } return @event; } [Obsolete("Please use Accept(out var evt) instead")] [return: MaybeNull] public static T? Peek(this IParser parser) where T : ParsingEvent { if (!parser.Accept(out var @event)) { return null; } return @event; } [Obsolete("Please use TryConsume(out var evt) or Accept(out var evt) instead")] public static bool Accept(this IParser parser) where T : ParsingEvent { T @event; return parser.Accept(out @event); } public static bool TryFindMappingEntry(this IParser parser, Func selector, [MaybeNullWhen(false)] out YamlDotNet.Core.Events.Scalar? key, [MaybeNullWhen(false)] out ParsingEvent? value) { if (parser.TryConsume(out var _)) { while (parser.Current != null) { ParsingEvent current = parser.Current; if (!(current is YamlDotNet.Core.Events.Scalar scalar)) { if (current is MappingStart || current is SequenceStart) { parser.SkipThisAndNestedEvents(); } else { parser.MoveNext(); } continue; } bool num = selector(scalar); parser.MoveNext(); if (num) { value = parser.Current; key = scalar; return true; } parser.SkipThisAndNestedEvents(); } } key = null; value = null; return false; } } internal enum ParserState { StreamStart, StreamEnd, ImplicitDocumentStart, DocumentStart, DocumentContent, DocumentEnd, BlockNode, BlockNodeOrIndentlessSequence, FlowNode, BlockSequenceFirstEntry, BlockSequenceEntry, IndentlessSequenceEntry, BlockMappingFirstKey, BlockMappingKey, BlockMappingValue, FlowSequenceFirstEntry, FlowSequenceEntry, FlowSequenceEntryMappingKey, FlowSequenceEntryMappingValue, FlowSequenceEntryMappingEnd, FlowMappingFirstKey, FlowMappingKey, FlowMappingValue, FlowMappingEmptyValue } internal sealed class RecursionLevel { private int current; public int Maximum { get; } public RecursionLevel(int maximum) { Maximum = maximum; } public void Increment() { if (!TryIncrement()) { throw new MaximumRecursionLevelReachedException("Maximum level of recursion reached"); } } public bool TryIncrement() { if (current < Maximum) { current++; return true; } return false; } public void Decrement() { if (current == 0) { throw new InvalidOperationException("Attempted to decrement RecursionLevel to a negative value"); } current--; } } internal enum ScalarStyle { Any, Plain, SingleQuoted, DoubleQuoted, Literal, Folded } internal class Scanner : IScanner { private const int MaxVersionNumberLength = 9; private static readonly SortedDictionary SimpleEscapeCodes = new SortedDictionary { { '0', '\0' }, { 'a', '\a' }, { 'b', '\b' }, { 't', '\t' }, { '\t', '\t' }, { 'n', '\n' }, { 'v', '\v' }, { 'f', '\f' }, { 'r', '\r' }, { 'e', '\u001b' }, { ' ', ' ' }, { '"', '"' }, { '\\', '\\' }, { '/', '/' }, { 'N', '\u0085' }, { '_', '\u00a0' }, { 'L', '\u2028' }, { 'P', '\u2029' } }; private readonly Stack indents = new Stack(); private readonly InsertionQueue tokens = new InsertionQueue(); private readonly Stack simpleKeys = new Stack(); private readonly CharacterAnalyzer analyzer; private readonly Cursor cursor; private bool streamStartProduced; private bool streamEndProduced; private bool plainScalarFollowedByComment; private int flowSequenceStartLine; private bool flowCollectionFetched; private bool startFlowCollectionFetched; private int indent = -1; private bool flowScalarFetched; private bool simpleKeyAllowed; private int flowLevel; private int tokensParsed; private bool tokenAvailable; private Token? previous; private Anchor? previousAnchor; private YamlDotNet.Core.Tokens.Scalar? lastScalar; private static readonly byte[] EmptyBytes = new byte[0]; public bool SkipComments { get; private set; } public Token? Current { get; private set; } public Mark CurrentPosition => cursor.Mark(); private bool IsDocumentStart() { if (!analyzer.EndOfInput && cursor.LineOffset == 0 && analyzer.Check('-') && analyzer.Check('-', 1) && analyzer.Check('-', 2)) { return analyzer.IsWhiteBreakOrZero(3); } return false; } private bool IsDocumentEnd() { if (!analyzer.EndOfInput && cursor.LineOffset == 0 && analyzer.Check('.') && analyzer.Check('.', 1) && analyzer.Check('.', 2)) { return analyzer.IsWhiteBreakOrZero(3); } return false; } private bool IsDocumentIndicator() { if (!IsDocumentStart()) { return IsDocumentEnd(); } return true; } public Scanner(TextReader input, bool skipComments = true) { analyzer = new CharacterAnalyzer(new LookAheadBuffer(input, 1024)); cursor = new Cursor(); SkipComments = skipComments; } public bool MoveNext() { if (Current != null) { ConsumeCurrent(); } return MoveNextWithoutConsuming(); } public bool MoveNextWithoutConsuming() { if (!tokenAvailable && !streamEndProduced) { FetchMoreTokens(); } if (tokens.Count > 0) { Current = tokens.Dequeue(); tokenAvailable = false; return true; } Current = null; return false; } public void ConsumeCurrent() { tokensParsed++; tokenAvailable = false; previous = Current; Current = null; } private char ReadCurrentCharacter() { char result = analyzer.Peek(0); Skip(); return result; } private char ReadLine() { if (analyzer.Check("\r\n\u0085")) { SkipLine(); return '\n'; } char result = analyzer.Peek(0); SkipLine(); return result; } private void FetchMoreTokens() { while (true) { bool flag = false; if (tokens.Count == 0) { flag = true; } else { foreach (SimpleKey simpleKey in simpleKeys) { if (simpleKey.IsPossible && simpleKey.TokenNumber == tokensParsed) { flag = true; break; } } } if (!flag) { break; } FetchNextToken(); } tokenAvailable = true; } private static bool StartsWith(StringBuilder what, char start) { if (what.Length > 0) { return what[0] == start; } return false; } private void StaleSimpleKeys() { foreach (SimpleKey simpleKey in simpleKeys) { if (simpleKey.IsPossible && (simpleKey.Line < cursor.Line || simpleKey.Index + 1024 < cursor.Index)) { if (simpleKey.IsRequired) { Mark mark = cursor.Mark(); tokens.Enqueue(new Error("While scanning a simple key, could not find expected ':'.", mark, mark)); } simpleKey.MarkAsImpossible(); } } } private void FetchNextToken() { if (!streamStartProduced) { FetchStreamStart(); return; } ScanToNextToken(); StaleSimpleKeys(); UnrollIndent(cursor.LineOffset); analyzer.Buffer.Cache(4); if (analyzer.Buffer.EndOfInput) { lastScalar = null; FetchStreamEnd(); } if (cursor.LineOffset == 0 && analyzer.Check('%')) { lastScalar = null; FetchDirective(); return; } if (IsDocumentStart()) { lastScalar = null; FetchDocumentIndicator(isStartToken: true); return; } if (IsDocumentEnd()) { lastScalar = null; FetchDocumentIndicator(isStartToken: false); return; } if (analyzer.Check('[')) { lastScalar = null; FetchFlowCollectionStart(isSequenceToken: true); return; } if (analyzer.Check('{')) { lastScalar = null; FetchFlowCollectionStart(isSequenceToken: false); return; } if (analyzer.Check(']')) { lastScalar = null; FetchFlowCollectionEnd(isSequenceToken: true); return; } if (analyzer.Check('}')) { lastScalar = null; FetchFlowCollectionEnd(isSequenceToken: false); return; } if (analyzer.Check(',')) { lastScalar = null; FetchFlowEntry(); return; } if (analyzer.Check('-')) { if (analyzer.IsWhiteBreakOrZero(1)) { FetchBlockEntry(); return; } if (flowLevel > 0 && analyzer.Check(",[]{}", 1)) { tokens.Enqueue(new Error("Invalid key indicator format.", cursor.Mark(), cursor.Mark())); } } if (analyzer.Check('?') && (flowLevel > 0 || analyzer.IsWhiteBreakOrZero(1)) && analyzer.IsWhiteBreakOrZero(1)) { FetchKey(); } else if (analyzer.Check(':') && (flowLevel > 0 || analyzer.IsWhiteBreakOrZero(1)) && (!simpleKeyAllowed || flowLevel <= 0) && (!flowScalarFetched || !analyzer.Check(':', 1)) && (analyzer.IsWhiteBreakOrZero(1) || analyzer.Check(',', 1) || flowScalarFetched || flowCollectionFetched || startFlowCollectionFetched)) { if (lastScalar != null) { lastScalar.IsKey = true; lastScalar = null; } FetchValue(); } else if (analyzer.Check('*')) { FetchAnchor(isAlias: true); } else if (analyzer.Check('&')) { FetchAnchor(isAlias: false); } else if (analyzer.Check('!')) { FetchTag(); } else if (analyzer.Check('|') && flowLevel == 0) { FetchBlockScalar(isLiteral: true); } else if (analyzer.Check('>') && flowLevel == 0) { FetchBlockScalar(isLiteral: false); } else if (analyzer.Check('\'')) { FetchFlowScalar(isSingleQuoted: true); } else if (analyzer.Check('"')) { FetchFlowScalar(isSingleQuoted: false); } else if ((!analyzer.IsWhiteBreakOrZero() && !analyzer.Check("-?:,[]{}#&*!|>'\"%@`")) || (analyzer.Check('-') && !analyzer.IsWhite(1)) || (analyzer.Check("?:") && !analyzer.IsWhiteBreakOrZero(1)) || (simpleKeyAllowed && flowLevel > 0)) { if (plainScalarFollowedByComment) { Mark mark = cursor.Mark(); tokens.Enqueue(new Error("While scanning plain scalar, found a comment between adjacent scalars.", mark, mark)); } if ((flowScalarFetched || (flowCollectionFetched && !startFlowCollectionFetched)) && analyzer.Check(':')) { Skip(); } flowScalarFetched = false; flowCollectionFetched = false; startFlowCollectionFetched = false; plainScalarFollowedByComment = false; FetchPlainScalar(); } else { if (simpleKeyAllowed && indent >= cursor.LineOffset && analyzer.IsTab()) { throw new SyntaxErrorException("While scanning a mapping, found invalid tab as indentation."); } if (!analyzer.IsWhiteBreakOrZero()) { Mark start = cursor.Mark(); Skip(); Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning for the next token, found character that cannot start any token."); } Skip(); } } private bool CheckWhiteSpace() { if (!analyzer.Check(' ')) { if (flowLevel > 0 || !simpleKeyAllowed) { return analyzer.Check('\t'); } return false; } return true; } private void Skip() { cursor.Skip(); analyzer.Buffer.Skip(1); } private void SkipLine() { if (analyzer.IsCrLf()) { cursor.SkipLineByOffset(2); analyzer.Buffer.Skip(2); } else if (analyzer.IsBreak()) { cursor.SkipLineByOffset(1); analyzer.Buffer.Skip(1); } else if (!analyzer.IsZero()) { throw new InvalidOperationException("Not at a break."); } } private void ScanToNextToken() { while (true) { if (CheckWhiteSpace()) { Skip(); continue; } ProcessComment(); if (analyzer.IsBreak()) { SkipLine(); if (flowLevel == 0) { simpleKeyAllowed = true; } continue; } break; } } private void ProcessComment() { if (!analyzer.Check('#')) { return; } Mark start = cursor.Mark(); Skip(); while (analyzer.IsSpace()) { Skip(); } StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; while (!analyzer.IsBreakOrZero()) { builder.Append(ReadCurrentCharacter()); } if (!SkipComments) { bool isInline = previous != null && previous.End.Line == start.Line && previous.End.Column != 1 && !(previous is YamlDotNet.Core.Tokens.StreamStart); tokens.Enqueue(new YamlDotNet.Core.Tokens.Comment(builder.ToString(), isInline, start, cursor.Mark())); } } finally { ((IDisposable)builderWrapper).Dispose(); } } private void FetchStreamStart() { simpleKeys.Push(new SimpleKey()); simpleKeyAllowed = true; streamStartProduced = true; Mark start = cursor.Mark(); tokens.Enqueue(new YamlDotNet.Core.Tokens.StreamStart(in start, in start)); } private void UnrollIndent(int column) { if (flowLevel == 0) { while (indent > column) { Mark start = cursor.Mark(); tokens.Enqueue(new BlockEnd(in start, in start)); indent = indents.Pop(); } } } private void FetchStreamEnd() { cursor.ForceSkipLineAfterNonBreak(); UnrollIndent(-1); RemoveSimpleKey(); simpleKeyAllowed = false; streamEndProduced = true; Mark start = cursor.Mark(); tokens.Enqueue(new YamlDotNet.Core.Tokens.StreamEnd(in start, in start)); } private void FetchDirective() { UnrollIndent(-1); RemoveSimpleKey(); simpleKeyAllowed = false; Token token = ScanDirective(); if (token != null) { tokens.Enqueue(token); } } private Token? ScanDirective() { Mark start = cursor.Mark(); Skip(); string text = ScanDirectiveName(in start); Token result; if (!(text == "YAML")) { if (!(text == "TAG")) { while (!analyzer.EndOfInput && !analyzer.Check('#') && !analyzer.IsBreak()) { Skip(); } return null; } result = ScanTagDirectiveValue(in start); } else { if (!(previous is YamlDotNet.Core.Tokens.DocumentStart) && !(previous is YamlDotNet.Core.Tokens.StreamStart) && !(previous is YamlDotNet.Core.Tokens.DocumentEnd)) { Mark end = cursor.Mark(); throw new SemanticErrorException(in start, in end, "While scanning a version directive, did not find preceding ."); } result = ScanVersionDirectiveValue(in start); } while (analyzer.IsWhite()) { Skip(); } ProcessComment(); if (!analyzer.IsBreakOrZero()) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a directive, did not find expected comment or line break."); } if (analyzer.IsBreak()) { SkipLine(); } return result; } private void FetchDocumentIndicator(bool isStartToken) { UnrollIndent(-1); RemoveSimpleKey(); simpleKeyAllowed = false; Mark end = cursor.Mark(); Skip(); Skip(); Skip(); if (isStartToken) { InsertionQueue insertionQueue = tokens; Mark end2 = cursor.Mark(); insertionQueue.Enqueue(new YamlDotNet.Core.Tokens.DocumentStart(in end, in end2)); return; } Token token = null; while (!analyzer.EndOfInput && !analyzer.IsBreak() && !analyzer.Check('#')) { if (!analyzer.IsWhite()) { token = new Error("While scanning a document end, found invalid content after '...' marker.", end, cursor.Mark()); break; } Skip(); } tokens.Enqueue(new YamlDotNet.Core.Tokens.DocumentEnd(in end, in end)); if (token != null) { tokens.Enqueue(token); } } private void FetchFlowCollectionStart(bool isSequenceToken) { SaveSimpleKey(); IncreaseFlowLevel(); simpleKeyAllowed = true; Mark start = cursor.Mark(); Skip(); Token token; if (isSequenceToken) { token = new FlowSequenceStart(in start, in start); flowSequenceStartLine = token.Start.Line; } else { token = new FlowMappingStart(in start, in start); } tokens.Enqueue(token); startFlowCollectionFetched = true; } private void IncreaseFlowLevel() { simpleKeys.Push(new SimpleKey()); flowLevel++; } private void FetchFlowCollectionEnd(bool isSequenceToken) { RemoveSimpleKey(); DecreaseFlowLevel(); simpleKeyAllowed = false; Mark start = cursor.Mark(); Skip(); Token token = null; Token item; if (isSequenceToken) { if (analyzer.Check('#')) { token = new Error("While scanning a flow sequence end, found invalid comment after ']'.", start, start); } item = new FlowSequenceEnd(in start, in start); } else { item = new FlowMappingEnd(in start, in start); } tokens.Enqueue(item); if (token != null) { tokens.Enqueue(token); } flowCollectionFetched = true; } private void DecreaseFlowLevel() { if (flowLevel > 0) { flowLevel--; simpleKeys.Pop(); } } private void FetchFlowEntry() { RemoveSimpleKey(); simpleKeyAllowed = true; Mark start = cursor.Mark(); Skip(); Mark end = cursor.Mark(); if (analyzer.Check('#')) { tokens.Enqueue(new Error("While scanning a flow entry, found invalid comment after comma.", start, end)); } else { tokens.Enqueue(new FlowEntry(in start, in end)); } } private void FetchBlockEntry() { Mark start; if (flowLevel == 0) { if (!simpleKeyAllowed) { if (previousAnchor != null && previousAnchor.End.Line == cursor.Line) { start = previousAnchor.Start; Mark end = previousAnchor.End; throw new SemanticErrorException(in start, in end, "Anchor before sequence entry on same line is not allowed."); } Mark mark = cursor.Mark(); tokens.Enqueue(new Error("Block sequence entries are not allowed in this context.", mark, mark)); } RollIndent(cursor.LineOffset, -1, isSequence: true, cursor.Mark()); } RemoveSimpleKey(); simpleKeyAllowed = true; Mark start2 = cursor.Mark(); Skip(); InsertionQueue insertionQueue = tokens; start = cursor.Mark(); insertionQueue.Enqueue(new BlockEntry(in start2, in start)); } private void FetchKey() { if (flowLevel == 0) { if (!simpleKeyAllowed) { Mark start = cursor.Mark(); throw new SyntaxErrorException(in start, in start, "Mapping keys are not allowed in this context."); } RollIndent(cursor.LineOffset, -1, isSequence: false, cursor.Mark()); } RemoveSimpleKey(); simpleKeyAllowed = flowLevel == 0; Mark start2 = cursor.Mark(); Skip(); InsertionQueue insertionQueue = tokens; Mark end = cursor.Mark(); insertionQueue.Enqueue(new Key(in start2, in end)); } private void FetchValue() { SimpleKey simpleKey = simpleKeys.Peek(); Mark start; if (simpleKey.IsPossible) { InsertionQueue insertionQueue = tokens; int index = simpleKey.TokenNumber - tokensParsed; start = simpleKey.Mark; Mark end = simpleKey.Mark; insertionQueue.Insert(index, new Key(in start, in end)); RollIndent(simpleKey.LineOffset, simpleKey.TokenNumber, isSequence: false, simpleKey.Mark); simpleKey.MarkAsImpossible(); simpleKeyAllowed = false; } else { bool flag = flowLevel == 0; if (flag) { if (!simpleKeyAllowed) { Mark mark = cursor.Mark(); tokens.Enqueue(new Error("Mapping values are not allowed in this context.", mark, mark)); return; } RollIndent(cursor.LineOffset, -1, isSequence: false, cursor.Mark()); if (cursor.LineOffset == 0 && simpleKey.LineOffset == 0) { InsertionQueue insertionQueue2 = tokens; int count = tokens.Count; start = simpleKey.Mark; Mark end = simpleKey.Mark; insertionQueue2.Insert(count, new Key(in start, in end)); flag = false; } } simpleKeyAllowed = flag; } Mark start2 = cursor.Mark(); Skip(); InsertionQueue insertionQueue3 = tokens; start = cursor.Mark(); insertionQueue3.Enqueue(new Value(in start2, in start)); } private void RollIndent(int column, int number, bool isSequence, Mark position) { if (flowLevel <= 0 && indent < column) { indents.Push(indent); indent = column; Token item = ((!isSequence) ? ((Token)new BlockMappingStart(in position, in position)) : ((Token)new BlockSequenceStart(in position, in position))); if (number == -1) { tokens.Enqueue(item); } else { tokens.Insert(number - tokensParsed, item); } } } private void FetchAnchor(bool isAlias) { SaveSimpleKey(); simpleKeyAllowed = false; tokens.Enqueue(ScanAnchor(isAlias)); } private Token ScanAnchor(bool isAlias) { Mark start = cursor.Mark(); Skip(); bool flag = false; if (isAlias) { SimpleKey simpleKey = simpleKeys.Peek(); flag = simpleKey.IsRequired && simpleKey.IsPossible; } StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; while (!analyzer.IsWhiteBreakOrZero() && !analyzer.Check("[]{},") && (!flag || !analyzer.Check(':') || !analyzer.IsWhiteBreakOrZero(1))) { builder.Append(ReadCurrentCharacter()); } if (builder.Length == 0 || (!analyzer.IsWhiteBreakOrZero() && !analyzer.Check("?:,]}%@`"))) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning an anchor or alias, found value containing disallowed: []{},"); } AnchorName value = new AnchorName(builder.ToString()); if (isAlias) { return new YamlDotNet.Core.Tokens.AnchorAlias(value, start, cursor.Mark()); } return previousAnchor = new Anchor(value, start, cursor.Mark()); } finally { ((IDisposable)builderWrapper).Dispose(); } } private void FetchTag() { SaveSimpleKey(); simpleKeyAllowed = false; tokens.Enqueue(ScanTag()); } private Token ScanTag() { Mark start = cursor.Mark(); string text; string text2; if (analyzer.Check('<', 1)) { text = string.Empty; Skip(); Skip(); text2 = ScanTagUri(null, start); if (!analyzer.Check('>')) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a tag, did not find the expected '>'."); } Skip(); } else { string text3 = ScanTagHandle(isDirective: false, start); if (text3.Length > 1 && text3[0] == '!' && text3[text3.Length - 1] == '!') { text = text3; text2 = ScanTagUri(null, start); } else { text2 = ScanTagUri(text3, start); text = "!"; if (text2.Length == 0) { text2 = text; text = string.Empty; } } } if (!analyzer.IsWhiteBreakOrZero() && !analyzer.Check(',')) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a tag, did not find expected whitespace, comma or line break."); } return new Tag(text, text2, start, cursor.Mark()); } private void FetchBlockScalar(bool isLiteral) { SaveSimpleKey(); simpleKeyAllowed = true; tokens.Enqueue(ScanBlockScalar(isLiteral)); } private Token ScanBlockScalar(bool isLiteral) { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; StringBuilderPool.BuilderWrapper builderWrapper2 = StringBuilderPool.Rent(); try { StringBuilder builder2 = builderWrapper2.Builder; StringBuilderPool.BuilderWrapper builderWrapper3 = StringBuilderPool.Rent(); try { StringBuilder builder3 = builderWrapper3.Builder; int num = 0; int num2 = 0; int currentIndent = 0; bool flag = false; bool? isFirstLine = null; Mark start = cursor.Mark(); Skip(); if (analyzer.Check("+-")) { num = (analyzer.Check('+') ? 1 : (-1)); Skip(); if (analyzer.IsDigit()) { if (analyzer.Check('0')) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a block scalar, found an indentation indicator equal to 0."); } num2 = analyzer.AsDigit(); Skip(); } } else if (analyzer.IsDigit()) { if (analyzer.Check('0')) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a block scalar, found an indentation indicator equal to 0."); } num2 = analyzer.AsDigit(); Skip(); if (analyzer.Check("+-")) { num = (analyzer.Check('+') ? 1 : (-1)); Skip(); } } if (analyzer.Check('#')) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a block scalar, found a comment without whtespace after '>' indicator."); } while (analyzer.IsWhite()) { Skip(); } ProcessComment(); if (!analyzer.IsBreakOrZero()) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a block scalar, did not find expected comment or line break."); } if (analyzer.IsBreak()) { SkipLine(); if (!isFirstLine.HasValue) { isFirstLine = true; } else if (isFirstLine == true) { isFirstLine = false; } } Mark end2 = cursor.Mark(); if (num2 != 0) { currentIndent = ((indent >= 0) ? (indent + num2) : num2); } currentIndent = ScanBlockScalarBreaks(currentIndent, builder3, isLiteral, ref end2, ref isFirstLine); isFirstLine = false; while (cursor.LineOffset == currentIndent && !analyzer.IsZero() && !IsDocumentEnd()) { bool flag2 = analyzer.IsWhite(); if (!isLiteral && StartsWith(builder2, '\n') && !flag && !flag2) { if (builder3.Length == 0) { builder.Append(' '); } builder2.Length = 0; } else { builder.Append(builder2.ToString()); builder2.Length = 0; } builder.Append(builder3.ToString()); builder3.Length = 0; flag = analyzer.IsWhite(); while (!analyzer.IsBreakOrZero()) { builder.Append(ReadCurrentCharacter()); } char c = ReadLine(); if (c != 0) { builder2.Append(c); } currentIndent = ScanBlockScalarBreaks(currentIndent, builder3, isLiteral, ref end2, ref isFirstLine); } if (num != -1) { builder.Append((object?)builder2); } if (num == 1) { builder.Append((object?)builder3); } ScalarStyle style = (isLiteral ? ScalarStyle.Literal : ScalarStyle.Folded); return new YamlDotNet.Core.Tokens.Scalar(builder.ToString(), style, start, end2); } finally { ((IDisposable)builderWrapper3).Dispose(); } } finally { ((IDisposable)builderWrapper2).Dispose(); } } finally { ((IDisposable)builderWrapper).Dispose(); } } private int ScanBlockScalarBreaks(int currentIndent, StringBuilder breaks, bool isLiteral, ref Mark end, ref bool? isFirstLine) { int num = 0; int num2 = -1; end = cursor.Mark(); while (true) { if ((currentIndent == 0 || cursor.LineOffset < currentIndent) && analyzer.IsSpace()) { Skip(); continue; } if (cursor.LineOffset > num) { num = cursor.LineOffset; } if (!analyzer.IsBreak()) { break; } if (isFirstLine == true) { isFirstLine = false; num2 = cursor.LineOffset; } breaks.Append(ReadLine()); end = cursor.Mark(); } if (isLiteral && isFirstLine == true) { int num3 = cursor.LineOffset; int num4 = 0; while (!analyzer.IsBreak(num4) && analyzer.IsSpace(num4)) { num4++; num3++; } if (analyzer.IsBreak(num4) && num3 > cursor.LineOffset) { isFirstLine = false; num2 = num3; } } if (isLiteral && num2 > 1 && currentIndent < num2 - 1) { Mark end2 = cursor.Mark(); throw new SemanticErrorException(in end, in end2, "While scanning a literal block scalar, found extra spaces in first line."); } if (!isLiteral && num > cursor.LineOffset && num2 > -1) { Mark end2 = cursor.Mark(); throw new SemanticErrorException(in end, in end2, "While scanning a literal block scalar, found more spaces in lines above first content line."); } if (currentIndent == 0 && (cursor.LineOffset > 0 || indent > -1)) { currentIndent = Math.Max(num, Math.Max(indent + 1, 1)); } return currentIndent; } private void FetchFlowScalar(bool isSingleQuoted) { SaveSimpleKey(); simpleKeyAllowed = false; flowScalarFetched = true; tokens.Enqueue(ScanFlowScalar(isSingleQuoted)); if (!isSingleQuoted && analyzer.Check('#')) { Mark mark = cursor.Mark(); tokens.Enqueue(new Error("While scanning a flow sequence end, found invalid comment after double-quoted scalar.", mark, mark)); } } private Token ScanFlowScalar(bool isSingleQuoted) { Mark start = cursor.Mark(); Skip(); StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; StringBuilderPool.BuilderWrapper builderWrapper2 = StringBuilderPool.Rent(); try { StringBuilder builder2 = builderWrapper2.Builder; StringBuilderPool.BuilderWrapper builderWrapper3 = StringBuilderPool.Rent(); try { StringBuilder builder3 = builderWrapper3.Builder; StringBuilderPool.BuilderWrapper builderWrapper4 = StringBuilderPool.Rent(); try { StringBuilder builder4 = builderWrapper4.Builder; bool flag = false; while (true) { if (IsDocumentIndicator()) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a quoted scalar, found unexpected document indicator."); } if (analyzer.IsZero()) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a quoted scalar, found unexpected end of stream."); } if (flag && !isSingleQuoted && indent >= cursor.LineOffset) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a multi-line double-quoted scalar, found wrong indentation."); } flag = false; while (!analyzer.IsWhiteBreakOrZero()) { if (isSingleQuoted && analyzer.Check('\'') && analyzer.Check('\'', 1)) { builder.Append('\''); Skip(); Skip(); continue; } if (analyzer.Check(isSingleQuoted ? '\'' : '"')) { break; } if (!isSingleQuoted && analyzer.Check('\\') && analyzer.IsBreak(1)) { Skip(); SkipLine(); flag = true; break; } if (!isSingleQuoted && analyzer.Check('\\')) { int num = 0; char c = analyzer.Peek(1); switch (c) { case 'x': num = 2; break; case 'u': num = 4; break; case 'U': num = 8; break; default: { if (SimpleEscapeCodes.TryGetValue(c, out var value)) { builder.Append(value); break; } Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a quoted scalar, found unknown escape character."); } } Skip(); Skip(); if (num <= 0) { continue; } int num2 = 0; for (int i = 0; i < num; i++) { if (!analyzer.IsHex(i)) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a quoted scalar, did not find expected hexadecimal number."); } num2 = (num2 << 4) + analyzer.AsHex(i); } if ((num2 >= 55296 && num2 <= 57343) || num2 > 1114111) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a quoted scalar, found invalid Unicode character escape code."); } builder.Append(char.ConvertFromUtf32(num2)); for (int j = 0; j < num; j++) { Skip(); } } else { builder.Append(ReadCurrentCharacter()); } } if (analyzer.Check(isSingleQuoted ? '\'' : '"')) { break; } while (analyzer.IsWhite() || analyzer.IsBreak()) { if (analyzer.IsWhite()) { if (!flag) { builder2.Append(ReadCurrentCharacter()); } else { Skip(); } } else if (!flag) { builder2.Length = 0; builder3.Append(ReadLine()); flag = true; } else { builder4.Append(ReadLine()); } } if (flag) { if (StartsWith(builder3, '\n')) { if (builder4.Length == 0) { builder.Append(' '); } else { builder.Append(builder4.ToString()); } } else { builder.Append(builder3.ToString()); builder.Append(builder4.ToString()); } builder3.Length = 0; builder4.Length = 0; } else { builder.Append(builder2.ToString()); builder2.Length = 0; } } Skip(); return new YamlDotNet.Core.Tokens.Scalar(builder.ToString(), isSingleQuoted ? ScalarStyle.SingleQuoted : ScalarStyle.DoubleQuoted, start, cursor.Mark()); } finally { ((IDisposable)builderWrapper4).Dispose(); } } finally { ((IDisposable)builderWrapper3).Dispose(); } } finally { ((IDisposable)builderWrapper2).Dispose(); } } finally { ((IDisposable)builderWrapper).Dispose(); } } private void FetchPlainScalar() { SaveSimpleKey(); simpleKeyAllowed = false; bool isMultiline = false; YamlDotNet.Core.Tokens.Scalar item = (lastScalar = ScanPlainScalar(ref isMultiline)); if (isMultiline && analyzer.Check(':') && flowLevel == 0 && indent < cursor.LineOffset) { tokens.Enqueue(new Error("While scanning a multiline plain scalar, found invalid mapping.", cursor.Mark(), cursor.Mark())); } tokens.Enqueue(item); } private YamlDotNet.Core.Tokens.Scalar ScanPlainScalar(ref bool isMultiline) { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; StringBuilderPool.BuilderWrapper builderWrapper2 = StringBuilderPool.Rent(); try { StringBuilder builder2 = builderWrapper2.Builder; StringBuilderPool.BuilderWrapper builderWrapper3 = StringBuilderPool.Rent(); try { StringBuilder builder3 = builderWrapper3.Builder; StringBuilderPool.BuilderWrapper builderWrapper4 = StringBuilderPool.Rent(); try { StringBuilder builder4 = builderWrapper4.Builder; bool flag = false; int num = indent + 1; Mark start = cursor.Mark(); Mark end = start; SimpleKey simpleKey = simpleKeys.Peek(); while (!IsDocumentIndicator()) { if (analyzer.Check('#')) { if (indent < 0 && flowLevel == 0) { plainScalarFollowedByComment = true; } break; } bool flag2 = analyzer.Check('*') && (!simpleKey.IsPossible || !simpleKey.IsRequired); while (!analyzer.IsWhiteBreakOrZero()) { if ((analyzer.Check(':') && !flag2 && (analyzer.IsWhiteBreakOrZero(1) || (flowLevel > 0 && analyzer.Check(',', 1)))) || (flowLevel > 0 && analyzer.Check(",[]{}"))) { if (flowLevel == 0 && !simpleKey.IsPossible) { tokens.Enqueue(new Error("While scanning a plain scalar value, found invalid mapping.", cursor.Mark(), cursor.Mark())); } break; } if (flag || builder2.Length > 0) { if (flag) { if (StartsWith(builder3, '\n')) { if (builder4.Length == 0) { builder.Append(' '); } else { builder.Append((object?)builder4); } } else { builder.Append((object?)builder3); builder.Append((object?)builder4); } builder3.Length = 0; builder4.Length = 0; flag = false; } else { builder.Append((object?)builder2); builder2.Length = 0; } } if (flowLevel > 0 && cursor.LineOffset < num) { throw new Exception(); } builder.Append(ReadCurrentCharacter()); end = cursor.Mark(); } if (!analyzer.IsWhite() && !analyzer.IsBreak()) { break; } while (analyzer.IsWhite() || analyzer.IsBreak()) { if (analyzer.IsWhite()) { if (flag && cursor.LineOffset < num && analyzer.IsTab()) { Mark end2 = cursor.Mark(); throw new SyntaxErrorException(in start, in end2, "While scanning a plain scalar, found a tab character that violate indentation."); } if (!flag) { builder2.Append(ReadCurrentCharacter()); } else { Skip(); } } else { isMultiline = true; if (!flag) { builder2.Length = 0; builder3.Append(ReadLine()); flag = true; } else { builder4.Append(ReadLine()); } } } if (flowLevel == 0 && cursor.LineOffset < num) { break; } } if (flag) { simpleKeyAllowed = true; } return new YamlDotNet.Core.Tokens.Scalar(builder.ToString(), ScalarStyle.Plain, start, end); } finally { ((IDisposable)builderWrapper4).Dispose(); } } finally { ((IDisposable)builderWrapper3).Dispose(); } } finally { ((IDisposable)builderWrapper2).Dispose(); } } finally { ((IDisposable)builderWrapper).Dispose(); } } private void RemoveSimpleKey() { SimpleKey simpleKey = simpleKeys.Peek(); if (simpleKey.IsPossible && simpleKey.IsRequired) { Mark start = simpleKey.Mark; Mark end = simpleKey.Mark; throw new SyntaxErrorException(in start, in end, "While scanning a simple key, could not find expected ':'."); } simpleKey.MarkAsImpossible(); } private string ScanDirectiveName(in Mark start) { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; while (analyzer.IsAlphaNumericDashOrUnderscore()) { builder.Append(ReadCurrentCharacter()); } if (builder.Length == 0) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a directive, could not find expected directive name."); } if (analyzer.EndOfInput) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a directive, found unexpected end of stream."); } if (!analyzer.IsWhiteBreakOrZero()) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a directive, found unexpected non-alphabetical character."); } return builder.ToString(); } finally { ((IDisposable)builderWrapper).Dispose(); } } private void SkipWhitespaces() { while (analyzer.IsWhite()) { Skip(); } } private Token ScanVersionDirectiveValue(in Mark start) { SkipWhitespaces(); int major = ScanVersionDirectiveNumber(in start); if (!analyzer.Check('.')) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a %YAML directive, did not find expected digit or '.' character."); } Skip(); int minor = ScanVersionDirectiveNumber(in start); return new VersionDirective(new Version(major, minor), start, start); } private Token ScanTagDirectiveValue(in Mark start) { SkipWhitespaces(); string handle = ScanTagHandle(isDirective: true, start); if (!analyzer.IsWhite()) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a %TAG directive, did not find expected whitespace."); } SkipWhitespaces(); string prefix = ScanTagUri(null, start); if (!analyzer.IsWhiteBreakOrZero()) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a %TAG directive, did not find expected whitespace or line break."); } return new TagDirective(handle, prefix, start, start); } private string ScanTagUri(string? head, Mark start) { StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; if (head != null && head.Length > 1) { builder.Append(head.Substring(1)); } while (analyzer.IsAlphaNumericDashOrUnderscore() || analyzer.Check(";/?:@&=+$.!~*'()[]%") || (analyzer.Check(',') && !analyzer.IsBreak(1))) { if (analyzer.Check('%')) { builder.Append(ScanUriEscapes(in start)); } else if (analyzer.Check('+')) { builder.Append(' '); Skip(); } else { builder.Append(ReadCurrentCharacter()); } } if (builder.Length == 0) { return string.Empty; } string text = builder.ToString(); if (text.EndsWith(",")) { Mark start2 = cursor.Mark(); Mark end = cursor.Mark(); throw new SyntaxErrorException(in start2, in end, "Unexpected comma at end of tag"); } return text; } finally { ((IDisposable)builderWrapper).Dispose(); } } private string ScanUriEscapes(in Mark start) { byte[] array = EmptyBytes; int count = 0; int num = 0; do { if (!analyzer.Check('%') || !analyzer.IsHex(1) || !analyzer.IsHex(2)) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a tag, did not find URI escaped octet."); } int num2 = (analyzer.AsHex(1) << 4) + analyzer.AsHex(2); if (num == 0) { num = (((num2 & 0x80) == 0) ? 1 : (((num2 & 0xE0) == 192) ? 2 : (((num2 & 0xF0) == 224) ? 3 : (((num2 & 0xF8) == 240) ? 4 : 0)))); if (num == 0) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a tag, found an incorrect leading UTF-8 octet."); } array = new byte[num]; } else if ((num2 & 0xC0) != 128) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a tag, found an incorrect trailing UTF-8 octet."); } array[count++] = (byte)num2; Skip(); Skip(); Skip(); } while (--num > 0); string @string = Encoding.UTF8.GetString(array, 0, count); if (@string.Length == 0 || @string.Length > 2) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a tag, found an incorrect UTF-8 sequence."); } return @string; } private string ScanTagHandle(bool isDirective, Mark start) { if (!analyzer.Check('!')) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a tag, did not find expected '!'."); } StringBuilderPool.BuilderWrapper builderWrapper = StringBuilderPool.Rent(); try { StringBuilder builder = builderWrapper.Builder; builder.Append(ReadCurrentCharacter()); while (analyzer.IsAlphaNumericDashOrUnderscore()) { builder.Append(ReadCurrentCharacter()); } if (analyzer.Check('!')) { builder.Append(ReadCurrentCharacter()); } else if (isDirective && (builder.Length != 1 || builder[0] != '!')) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a tag directive, did not find expected '!'."); } return builder.ToString(); } finally { ((IDisposable)builderWrapper).Dispose(); } } private int ScanVersionDirectiveNumber(in Mark start) { int num = 0; int num2 = 0; while (analyzer.IsDigit()) { if (++num2 > 9) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a %YAML directive, found extremely long version number."); } num = num * 10 + analyzer.AsDigit(); Skip(); } if (num2 == 0) { Mark end = cursor.Mark(); throw new SyntaxErrorException(in start, in end, "While scanning a %YAML directive, did not find expected version number."); } return num; } private void SaveSimpleKey() { bool isRequired = flowLevel == 0 && indent == cursor.LineOffset; if (simpleKeyAllowed) { SimpleKey item = new SimpleKey(isRequired, tokensParsed + tokens.Count, cursor); RemoveSimpleKey(); simpleKeys.Pop(); simpleKeys.Push(item); } } } internal class SemanticErrorException : YamlException { public SemanticErrorException(string message) : base(message) { } public SemanticErrorException(in Mark start, in Mark end, string message) : base(in start, in end, message) { } public SemanticErrorException(string message, Exception inner) : base(message, inner) { } } internal sealed class SimpleKey { private readonly Cursor cursor; public bool IsPossible { get; private set; } public bool IsRequired { get; } public int TokenNumber { get; } public int Index => cursor.Index; public int Line => cursor.Line; public int LineOffset => cursor.LineOffset; public Mark Mark => cursor.Mark(); public void MarkAsImpossible() { IsPossible = false; } public SimpleKey() { cursor = new Cursor(); } public SimpleKey(bool isRequired, int tokenNumber, Cursor cursor) { IsPossible = true; IsRequired = isRequired; TokenNumber = tokenNumber; this.cursor = new Cursor(cursor); } } internal sealed class StringLookAheadBuffer : ILookAheadBuffer { private readonly string value; public int Position { get; private set; } public int Length => value.Length; public bool EndOfInput => IsOutside(Position); public StringLookAheadBuffer(string value) { this.value = value; } public char Peek(int offset) { int index = Position + offset; if (!IsOutside(index)) { return value[index]; } return '\0'; } private bool IsOutside(int index) { return index >= value.Length; } public void Skip(int length) { if (length < 0) { throw new ArgumentOutOfRangeException("length", "The length must be positive."); } Position += length; } } internal sealed class SyntaxErrorException : YamlException { public SyntaxErrorException(string message) : base(message) { } public SyntaxErrorException(in Mark start, in Mark end, string message) : base(in start, in end, message) { } public SyntaxErrorException(string message, Exception inner) : base(message, inner) { } } internal sealed class TagDirectiveCollection : KeyedCollection { public TagDirectiveCollection() { } public TagDirectiveCollection(IEnumerable tagDirectives) { foreach (TagDirective tagDirective in tagDirectives) { Add(tagDirective); } } protected override string GetKeyForItem(TagDirective item) { return item.Handle; } public new bool Contains(TagDirective directive) { return Contains(GetKeyForItem(directive)); } } internal readonly struct TagName : IEquatable { public static readonly TagName Empty; private readonly string? value; public string Value => value ?? throw new InvalidOperationException("Cannot read the Value of a non-specific tag"); public bool IsEmpty => value == null; public bool IsNonSpecific { get { if (!IsEmpty) { if (!(value == "!")) { return value == "?"; } return true; } return false; } } public bool IsLocal { get { if (!IsEmpty) { return Value[0] == '!'; } return false; } } public bool IsGlobal { get { if (!IsEmpty) { return !IsLocal; } return false; } } public TagName(string value) { this.value = value ?? throw new ArgumentNullException("value"); if (value.Length == 0) { throw new ArgumentException("Tag value must not be empty.", "value"); } if (IsGlobal && !Uri.IsWellFormedUriString(value, UriKind.RelativeOrAbsolute)) { throw new ArgumentException("Global tags must be valid URIs.", "value"); } } public override string ToString() { return value ?? "?"; } public bool Equals(TagName other) { return object.Equals(value, other.value); } public override bool Equals(object? obj) { if (obj is TagName other) { return Equals(other); } return false; } public override int GetHashCode() { return value?.GetHashCode() ?? 0; } public static bool operator ==(TagName left, TagName right) { return left.Equals(right); } public static bool operator !=(TagName left, TagName right) { return !(left == right); } public static bool operator ==(TagName left, string right) { return object.Equals(left.value, right); } public static bool operator !=(TagName left, string right) { return !(left == right); } public static implicit operator TagName(string? value) { if (value != null) { return new TagName(value); } return Empty; } } internal sealed class Version { public int Major { get; } public int Minor { get; } public Version(int major, int minor) { if (major < 0) { throw new ArgumentOutOfRangeException("major", $"{major} should be >= 0"); } Major = major; if (minor < 0) { throw new ArgumentOutOfRangeException("minor", $"{minor} should be >= 0"); } Minor = minor; } public override bool Equals(object? obj) { if (obj is Version version && Major == version.Major) { return Minor == version.Minor; } return false; } public override int GetHashCode() { return HashCode.CombineHashCodes(Major.GetHashCode(), Minor.GetHashCode()); } } internal class YamlException : Exception { public Mark Start { get; } public Mark End { get; } public YamlException(string message) : this(in Mark.Empty, in Mark.Empty, message) { } public YamlException(in Mark start, in Mark end, string message) : this(in start, in end, message, null) { } public YamlException(in Mark start, in Mark end, string message, Exception? innerException) : base(message, innerException) { Start = start; End = end; } public YamlException(string message, Exception inner) : this(in Mark.Empty, in Mark.Empty, message, inner) { } public override string ToString() { return $"({Start}) - ({End}): {Message}"; } } } namespace YamlDotNet.Core.Tokens { internal class Anchor : Token { public AnchorName Value { get; } public Anchor(AnchorName value) : this(value, Mark.Empty, Mark.Empty) { } public Anchor(AnchorName value, Mark start, Mark end) : base(in start, in end) { if (value.IsEmpty) { throw new ArgumentNullException("value"); } Value = value; } } internal sealed class AnchorAlias : Token { public AnchorName Value { get; } public AnchorAlias(AnchorName value) : this(value, Mark.Empty, Mark.Empty) { } public AnchorAlias(AnchorName value, Mark start, Mark end) : base(in start, in end) { if (value.IsEmpty) { throw new ArgumentNullException("value"); } Value = value; } } internal sealed class BlockEnd : Token { public BlockEnd() : this(in Mark.Empty, in Mark.Empty) { } public BlockEnd(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class BlockEntry : Token { public BlockEntry() : this(in Mark.Empty, in Mark.Empty) { } public BlockEntry(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class BlockMappingStart : Token { public BlockMappingStart() : this(in Mark.Empty, in Mark.Empty) { } public BlockMappingStart(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class BlockSequenceStart : Token { public BlockSequenceStart() : this(in Mark.Empty, in Mark.Empty) { } public BlockSequenceStart(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class Comment : Token { public string Value { get; } public bool IsInline { get; } public Comment(string value, bool isInline) : this(value, isInline, Mark.Empty, Mark.Empty) { } public Comment(string value, bool isInline, Mark start, Mark end) : base(in start, in end) { Value = value ?? throw new ArgumentNullException("value"); IsInline = isInline; } } internal sealed class DocumentEnd : Token { public DocumentEnd() : this(in Mark.Empty, in Mark.Empty) { } public DocumentEnd(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class DocumentStart : Token { public DocumentStart() : this(in Mark.Empty, in Mark.Empty) { } public DocumentStart(in Mark start, in Mark end) : base(in start, in end) { } } internal class Error : Token { public string Value { get; } public Error(string value, Mark start, Mark end) : base(in start, in end) { Value = value; } } internal sealed class FlowEntry : Token { public FlowEntry() : this(in Mark.Empty, in Mark.Empty) { } public FlowEntry(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class FlowMappingEnd : Token { public FlowMappingEnd() : this(in Mark.Empty, in Mark.Empty) { } public FlowMappingEnd(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class FlowMappingStart : Token { public FlowMappingStart() : this(in Mark.Empty, in Mark.Empty) { } public FlowMappingStart(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class FlowSequenceEnd : Token { public FlowSequenceEnd() : this(in Mark.Empty, in Mark.Empty) { } public FlowSequenceEnd(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class FlowSequenceStart : Token { public FlowSequenceStart() : this(in Mark.Empty, in Mark.Empty) { } public FlowSequenceStart(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class Key : Token { public Key() : this(in Mark.Empty, in Mark.Empty) { } public Key(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class Scalar : Token { public bool IsKey { get; set; } public string Value { get; } public ScalarStyle Style { get; } public Scalar(string value) : this(value, ScalarStyle.Any) { } public Scalar(string value, ScalarStyle style) : this(value, style, Mark.Empty, Mark.Empty) { } public Scalar(string value, ScalarStyle style, Mark start, Mark end) : base(in start, in end) { Value = value ?? throw new ArgumentNullException("value"); Style = style; } } internal sealed class StreamEnd : Token { public StreamEnd() : this(in Mark.Empty, in Mark.Empty) { } public StreamEnd(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class StreamStart : Token { public StreamStart() : this(in Mark.Empty, in Mark.Empty) { } public StreamStart(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class Tag : Token { public string Handle { get; } public string Suffix { get; } public Tag(string handle, string suffix) : this(handle, suffix, Mark.Empty, Mark.Empty) { } public Tag(string handle, string suffix, Mark start, Mark end) : base(in start, in end) { Handle = handle ?? throw new ArgumentNullException("handle"); Suffix = suffix ?? throw new ArgumentNullException("suffix"); } } internal class TagDirective : Token { private static readonly Regex TagHandlePattern = new Regex("^!([0-9A-Za-z_\\-]*!)?$", RegexOptions.Compiled); public string Handle { get; } public string Prefix { get; } public TagDirective(string handle, string prefix) : this(handle, prefix, Mark.Empty, Mark.Empty) { } public TagDirective(string handle, string prefix, Mark start, Mark end) : base(in start, in end) { if (string.IsNullOrEmpty(handle)) { throw new ArgumentNullException("handle", "Tag handle must not be empty."); } if (!TagHandlePattern.IsMatch(handle)) { throw new ArgumentException("Tag handle must start and end with '!' and contain alphanumerical characters only.", "handle"); } Handle = handle; if (string.IsNullOrEmpty(prefix)) { throw new ArgumentNullException("prefix", "Tag prefix must not be empty."); } Prefix = prefix; } public override bool Equals(object? obj) { if (obj is TagDirective tagDirective && Handle.Equals(tagDirective.Handle)) { return Prefix.Equals(tagDirective.Prefix); } return false; } public override int GetHashCode() { return Handle.GetHashCode() ^ Prefix.GetHashCode(); } public override string ToString() { return Handle + " => " + Prefix; } } internal abstract class Token { public Mark Start { get; } public Mark End { get; } protected Token(in Mark start, in Mark end) { Start = start; End = end; } } internal sealed class Value : Token { public Value() : this(in Mark.Empty, in Mark.Empty) { } public Value(in Mark start, in Mark end) : base(in start, in end) { } } internal sealed class VersionDirective : Token { public Version Version { get; } public VersionDirective(Version version) : this(version, Mark.Empty, Mark.Empty) { } public VersionDirective(Version version, Mark start, Mark end) : base(in start, in end) { Version = version; } public override bool Equals(object? obj) { if (obj is VersionDirective versionDirective) { return Version.Equals(versionDirective.Version); } return false; } public override int GetHashCode() { return Version.GetHashCode(); } } } namespace YamlDotNet.Core.Events { internal sealed class AnchorAlias : ParsingEvent { internal override EventType Type => EventType.Alias; public AnchorName Value { get; } public AnchorAlias(AnchorName value, Mark start, Mark end) : base(in start, in end) { if (value.IsEmpty) { throw new YamlException(in start, in end, "Anchor value must not be empty."); } Value = value; } public AnchorAlias(AnchorName value) : this(value, Mark.Empty, Mark.Empty) { } public override string ToString() { return $"Alias [value = {Value}]"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal sealed class Comment : ParsingEvent { public string Value { get; } public bool IsInline { get; } internal override EventType Type => EventType.Comment; public Comment(string value, bool isInline) : this(value, isInline, Mark.Empty, Mark.Empty) { } public Comment(string value, bool isInline, Mark start, Mark end) : base(in start, in end) { Value = value; IsInline = isInline; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } public override string ToString() { return (IsInline ? "Inline" : "Block") + " Comment [" + Value + "]"; } } internal sealed class DocumentEnd : ParsingEvent { public override int NestingIncrease => -1; internal override EventType Type => EventType.DocumentEnd; public bool IsImplicit { get; } public DocumentEnd(bool isImplicit, Mark start, Mark end) : base(in start, in end) { IsImplicit = isImplicit; } public DocumentEnd(bool isImplicit) : this(isImplicit, Mark.Empty, Mark.Empty) { } public override string ToString() { return $"Document end [isImplicit = {IsImplicit}]"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal sealed class DocumentStart : ParsingEvent { public override int NestingIncrease => 1; internal override EventType Type => EventType.DocumentStart; public TagDirectiveCollection? Tags { get; } public VersionDirective? Version { get; } public bool IsImplicit { get; } public DocumentStart(VersionDirective? version, TagDirectiveCollection? tags, bool isImplicit, Mark start, Mark end) : base(in start, in end) { Version = version; Tags = tags; IsImplicit = isImplicit; } public DocumentStart(VersionDirective? version, TagDirectiveCollection? tags, bool isImplicit) : this(version, tags, isImplicit, Mark.Empty, Mark.Empty) { } public DocumentStart(in Mark start, in Mark end) : this(null, null, isImplicit: true, start, end) { } public DocumentStart() : this(null, null, isImplicit: true, Mark.Empty, Mark.Empty) { } public override string ToString() { return $"Document start [isImplicit = {IsImplicit}]"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal enum EventType { None, StreamStart, StreamEnd, DocumentStart, DocumentEnd, Alias, Scalar, SequenceStart, SequenceEnd, MappingStart, MappingEnd, Comment } internal interface IParsingEventVisitor { void Visit(AnchorAlias e); void Visit(StreamStart e); void Visit(StreamEnd e); void Visit(DocumentStart e); void Visit(DocumentEnd e); void Visit(Scalar e); void Visit(SequenceStart e); void Visit(SequenceEnd e); void Visit(MappingStart e); void Visit(MappingEnd e); void Visit(Comment e); } internal class MappingEnd : ParsingEvent { public override int NestingIncrease => -1; internal override EventType Type => EventType.MappingEnd; public MappingEnd(in Mark start, in Mark end) : base(in start, in end) { } public MappingEnd() : this(in Mark.Empty, in Mark.Empty) { } public override string ToString() { return "Mapping end"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal sealed class MappingStart : NodeEvent { public override int NestingIncrease => 1; internal override EventType Type => EventType.MappingStart; public bool IsImplicit { get; } public override bool IsCanonical => !IsImplicit; public MappingStyle Style { get; } public MappingStart(AnchorName anchor, TagName tag, bool isImplicit, MappingStyle style, Mark start, Mark end) : base(anchor, tag, start, end) { IsImplicit = isImplicit; Style = style; } public MappingStart(AnchorName anchor, TagName tag, bool isImplicit, MappingStyle style) : this(anchor, tag, isImplicit, style, Mark.Empty, Mark.Empty) { } public MappingStart() : this(AnchorName.Empty, TagName.Empty, isImplicit: true, MappingStyle.Any, Mark.Empty, Mark.Empty) { } public override string ToString() { return $"Mapping start [anchor = {base.Anchor}, tag = {base.Tag}, isImplicit = {IsImplicit}, style = {Style}]"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal enum MappingStyle { Any, Block, Flow } internal abstract class NodeEvent : ParsingEvent { public AnchorName Anchor { get; } public TagName Tag { get; } public abstract bool IsCanonical { get; } protected NodeEvent(AnchorName anchor, TagName tag, Mark start, Mark end) : base(in start, in end) { Anchor = anchor; Tag = tag; } protected NodeEvent(AnchorName anchor, TagName tag) : this(anchor, tag, Mark.Empty, Mark.Empty) { } } internal abstract class ParsingEvent { public virtual int NestingIncrease => 0; internal abstract EventType Type { get; } public Mark Start { get; } public Mark End { get; } public abstract void Accept(IParsingEventVisitor visitor); internal ParsingEvent(in Mark start, in Mark end) { Start = start; End = end; } } internal sealed class Scalar : NodeEvent { internal override EventType Type => EventType.Scalar; public string Value { get; } public ScalarStyle Style { get; } public bool IsPlainImplicit { get; } public bool IsQuotedImplicit { get; } public override bool IsCanonical { get { if (!IsPlainImplicit) { return !IsQuotedImplicit; } return false; } } public bool IsKey { get; } public Scalar(AnchorName anchor, TagName tag, string value, ScalarStyle style, bool isPlainImplicit, bool isQuotedImplicit, Mark start, Mark end, bool isKey = false) : base(anchor, tag, start, end) { Value = value; Style = style; IsPlainImplicit = isPlainImplicit; IsQuotedImplicit = isQuotedImplicit; IsKey = isKey; } public Scalar(AnchorName anchor, TagName tag, string value, ScalarStyle style, bool isPlainImplicit, bool isQuotedImplicit) : this(anchor, tag, value, style, isPlainImplicit, isQuotedImplicit, Mark.Empty, Mark.Empty) { } public Scalar(string value) : this(AnchorName.Empty, TagName.Empty, value, ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: true, Mark.Empty, Mark.Empty) { } public Scalar(TagName tag, string value) : this(AnchorName.Empty, tag, value, ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: true, Mark.Empty, Mark.Empty) { } public Scalar(AnchorName anchor, TagName tag, string value) : this(anchor, tag, value, ScalarStyle.Any, isPlainImplicit: true, isQuotedImplicit: true, Mark.Empty, Mark.Empty) { } public override string ToString() { return $"Scalar [anchor = {base.Anchor}, tag = {base.Tag}, value = {Value}, style = {Style}, isPlainImplicit = {IsPlainImplicit}, isQuotedImplicit = {IsQuotedImplicit}]"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal sealed class SequenceEnd : ParsingEvent { public override int NestingIncrease => -1; internal override EventType Type => EventType.SequenceEnd; public SequenceEnd(in Mark start, in Mark end) : base(in start, in end) { } public SequenceEnd() : this(in Mark.Empty, in Mark.Empty) { } public override string ToString() { return "Sequence end"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal sealed class SequenceStart : NodeEvent { public override int NestingIncrease => 1; internal override EventType Type => EventType.SequenceStart; public bool IsImplicit { get; } public override bool IsCanonical => !IsImplicit; public SequenceStyle Style { get; } public SequenceStart(AnchorName anchor, TagName tag, bool isImplicit, SequenceStyle style, Mark start, Mark end) : base(anchor, tag, start, end) { IsImplicit = isImplicit; Style = style; } public SequenceStart(AnchorName anchor, TagName tag, bool isImplicit, SequenceStyle style) : this(anchor, tag, isImplicit, style, Mark.Empty, Mark.Empty) { } public override string ToString() { return $"Sequence start [anchor = {base.Anchor}, tag = {base.Tag}, isImplicit = {IsImplicit}, style = {Style}]"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal enum SequenceStyle { Any, Block, Flow } internal sealed class StreamEnd : ParsingEvent { public override int NestingIncrease => -1; internal override EventType Type => EventType.StreamEnd; public StreamEnd(in Mark start, in Mark end) : base(in start, in end) { } public StreamEnd() : this(in Mark.Empty, in Mark.Empty) { } public override string ToString() { return "Stream end"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } internal sealed class StreamStart : ParsingEvent { public override int NestingIncrease => 1; internal override EventType Type => EventType.StreamStart; public StreamStart() : this(in Mark.Empty, in Mark.Empty) { } public StreamStart(in Mark start, in Mark end) : base(in start, in end) { } public override string ToString() { return "Stream start"; } public override void Accept(IParsingEventVisitor visitor) { visitor.Visit(this); } } } namespace System.Collections.Generic { internal static class DeconstructionExtensions { public static void Deconstruct(this KeyValuePair pair, out TKey key, out TValue value) { key = pair.Key; value = pair.Value; } } } namespace System.Diagnostics.CodeAnalysis { [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class AllowNullAttribute : Attribute { } [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, Inherited = false)] internal sealed class DisallowNullAttribute : Attribute { } [DebuggerNonUserCode] [ExcludeFromCodeCoverage] [AttributeUsage(AttributeTargets.Method, Inherited = false)] internal sealed class DoesNotReturnAttribute : Attribute { } [ExcludeFromCodeCoverage] [DebuggerNonUserCode] [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] internal sealed class DoesNotReturnIfAttribute : Attribute { public bool ParameterValue { get; } public DoesNotReturnIfAttribute(bool parameterValue) { ParameterValue = parameterValue; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal sealed class MaybeNullAttribute : Attribute { } [ExcludeFromCodeCoverage] [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [DebuggerNonUserCode] internal sealed class MaybeNullWhenAttribute : Attribute { public bool ReturnValue { get; } public MaybeNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } [ExcludeFromCodeCoverage] [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [DebuggerNonUserCode] internal sealed class MemberNotNullAttribute : Attribute { public string[] Members { get; } public MemberNotNullAttribute(string member) { Members = new string[1] { member }; } public MemberNotNullAttribute(params string[] members) { Members = members; } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal sealed class MemberNotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public string[] Members { get; } public MemberNotNullWhenAttribute(bool returnValue, string member) { ReturnValue = returnValue; Members = new string[1] { member }; } public MemberNotNullWhenAttribute(bool returnValue, params string[] members) { ReturnValue = returnValue; Members = members; } } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter | AttributeTargets.ReturnValue, Inherited = false)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal sealed class NotNullAttribute : Attribute { } [AttributeUsage(AttributeTargets.Property | AttributeTargets.Parameter | AttributeTargets.ReturnValue, AllowMultiple = true, Inherited = false)] [DebuggerNonUserCode] [ExcludeFromCodeCoverage] internal sealed class NotNullIfNotNullAttribute : Attribute { public string ParameterName { get; } public NotNullIfNotNullAttribute(string parameterName) { ParameterName = parameterName; } } [AttributeUsage(AttributeTargets.Parameter, Inherited = false)] [ExcludeFromCodeCoverage] [DebuggerNonUserCode] internal sealed class NotNullWhenAttribute : Attribute { public bool ReturnValue { get; } public NotNullWhenAttribute(bool returnValue) { ReturnValue = returnValue; } } }