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.Drawing; using System.Globalization; using System.IO; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using HarmonyLib; using Microsoft.CodeAnalysis; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Collections.Generic; using MonoMod.Cil; using MonoMod.Utils; using SoftReferenceableAssets; using UnityEngine; using Valheim.ServersideQoL.CodeAnalysis; using Valheim.ServersideQoL.HarmonyPatches; using Valheim.ServersideQoL.Processors; using YamlDotNet.Serialization; using YamlDotNet.Serialization.TypeInspectors; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("Valheim.ServersideQoL")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.8.1.0")] [assembly: AssemblyInformationalVersion("1.8.1-beta.0.30+d2c324ae03da43f3657ad33447faf467152a1eb9")] [assembly: AssemblyProduct("Valheim.ServersideQoL")] [assembly: AssemblyTitle("Valheim.ServersideQoL")] [assembly: AssemblyVersion("1.0.0.0")] [module: RefSafetyRules(11)] [CompilerGenerated] internal sealed class <>z__ReadOnlyArray : IEnumerable, ICollection, IList, IEnumerable, IReadOnlyCollection, IReadOnlyList, ICollection, IList { int ICollection.Count => _items.Length; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; object IList.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; int IReadOnlyCollection.Count => _items.Length; T IReadOnlyList.this[int index] => _items[index]; int ICollection.Count => _items.Length; bool ICollection.IsReadOnly => true; T IList.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } public <>z__ReadOnlyArray(T[] items) { _items = items; } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_items).GetEnumerator(); } void ICollection.CopyTo(Array array, int index) { ((ICollection)_items).CopyTo(array, index); } int IList.Add(object value) { throw new NotSupportedException(); } void IList.Clear() { throw new NotSupportedException(); } bool IList.Contains(object value) { return ((IList)_items).Contains(value); } int IList.IndexOf(object value) { return ((IList)_items).IndexOf(value); } 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(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_items).GetEnumerator(); } void ICollection.Add(T item) { throw new NotSupportedException(); } void ICollection.Clear() { throw new NotSupportedException(); } bool ICollection.Contains(T item) { return ((ICollection)_items).Contains(item); } void ICollection.CopyTo(T[] array, int arrayIndex) { ((ICollection)_items).CopyTo(array, arrayIndex); } bool ICollection.Remove(T item) { throw new NotSupportedException(); } int IList.IndexOf(T item) { return ((IList)_items).IndexOf(item); } void IList.Insert(int index, T item) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } } [CompilerGenerated] internal sealed class <>z__ReadOnlyList : IEnumerable, ICollection, IList, IEnumerable, IReadOnlyCollection, IReadOnlyList, ICollection, IList { int ICollection.Count => _items.Count; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; object IList.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; int IReadOnlyCollection.Count => _items.Count; T IReadOnlyList.this[int index] => _items[index]; int ICollection.Count => _items.Count; bool ICollection.IsReadOnly => true; T IList.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } public <>z__ReadOnlyList(List items) { _items = items; } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_items).GetEnumerator(); } void ICollection.CopyTo(Array array, int index) { ((ICollection)_items).CopyTo(array, index); } int IList.Add(object value) { throw new NotSupportedException(); } void IList.Clear() { throw new NotSupportedException(); } bool IList.Contains(object value) { return ((IList)_items).Contains(value); } int IList.IndexOf(object value) { return ((IList)_items).IndexOf(value); } 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(); } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_items).GetEnumerator(); } void ICollection.Add(T item) { throw new NotSupportedException(); } void ICollection.Clear() { throw new NotSupportedException(); } bool ICollection.Contains(T item) { return _items.Contains(item); } void ICollection.CopyTo(T[] array, int arrayIndex) { _items.CopyTo(array, arrayIndex); } bool ICollection.Remove(T item) { throw new NotSupportedException(); } int IList.IndexOf(T item) { return _items.IndexOf(item); } void IList.Insert(int index, T item) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } } [CompilerGenerated] internal sealed class <>z__ReadOnlySingleElementList : IEnumerable, ICollection, IList, IEnumerable, IReadOnlyCollection, IReadOnlyList, ICollection, IList { private sealed class Enumerator : IDisposable, IEnumerator, IEnumerator { object IEnumerator.Current => _item; T IEnumerator.Current => _item; public Enumerator(T item) { _item = item; } bool IEnumerator.MoveNext() { if (!_moveNextCalled) { return _moveNextCalled = true; } return false; } void IEnumerator.Reset() { _moveNextCalled = false; } void IDisposable.Dispose() { } } int ICollection.Count => 1; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; object IList.this[int index] { get { if (index != 0) { throw new IndexOutOfRangeException(); } return _item; } set { throw new NotSupportedException(); } } bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; int IReadOnlyCollection.Count => 1; T IReadOnlyList.this[int index] { get { if (index != 0) { throw new IndexOutOfRangeException(); } return _item; } } int ICollection.Count => 1; bool ICollection.IsReadOnly => true; T IList.this[int index] { get { if (index != 0) { throw new IndexOutOfRangeException(); } return _item; } set { throw new NotSupportedException(); } } public <>z__ReadOnlySingleElementList(T item) { _item = item; } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(_item); } void ICollection.CopyTo(Array array, int index) { array.SetValue(_item, index); } int IList.Add(object value) { throw new NotSupportedException(); } void IList.Clear() { throw new NotSupportedException(); } bool IList.Contains(object value) { return EqualityComparer.Default.Equals(_item, (T)value); } int IList.IndexOf(object value) { if (!EqualityComparer.Default.Equals(_item, (T)value)) { return -1; } return 0; } 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(); } IEnumerator IEnumerable.GetEnumerator() { return new Enumerator(_item); } void ICollection.Add(T item) { throw new NotSupportedException(); } void ICollection.Clear() { throw new NotSupportedException(); } bool ICollection.Contains(T item) { return EqualityComparer.Default.Equals(_item, item); } void ICollection.CopyTo(T[] array, int arrayIndex) { array[arrayIndex] = _item; } bool ICollection.Remove(T item) { throw new NotSupportedException(); } int IList.IndexOf(T item) { if (!EqualityComparer.Default.Equals(_item, item)) { return -1; } return 0; } void IList.Insert(int index, T item) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class IsUnmanagedAttribute : 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; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace Valheim.ServersideQoL { internal sealed class ConcurrentHashSet : ICollection, IEnumerable, IEnumerable, IReadOnlyCollection where T : notnull { private readonly ConcurrentDictionary _dict = new ConcurrentDictionary(); public int Count => _dict.Count; bool ICollection.IsReadOnly => false; public bool Add(T value) { return _dict.TryAdd(value, null); } public bool Remove(T value) { object value2; return _dict.TryRemove(value, out value2); } void ICollection.Add(T item) { if (!Add(item)) { throw new InvalidOperationException(); } } public void Clear() { _dict.Clear(); } public bool Contains(T item) { return _dict.ContainsKey(item); } void ICollection.CopyTo(T[] array, int arrayIndex) { throw new NotImplementedException(); } IEnumerator IEnumerable.GetEnumerator() { return _dict.Keys.GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return _dict.Keys.GetEnumerator(); } } internal static class ReadOnlyDictionary { public static IReadOnlyDictionary Empty { get; } = new System.Collections.ObjectModel.ReadOnlyDictionary(new Dictionary(0)); } internal static class EnumUtils { private static class Generic where T : unmanaged, Enum { public static bool IsBitSet { get; } = OfType(typeof(T)).IsBitSet; public static Func EnumToUInt64 { get; } public static Func UInt64ToEnum { get; } public static Func EnumToInt64 { get; } public static Func Int64ToEnum { get; } static Generic() { ParameterExpression parameterExpression = Expression.Parameter(typeof(T)); EnumToUInt64 = Expression.Lambda>(Expression.ConvertChecked(parameterExpression, typeof(ulong)), new ParameterExpression[1] { parameterExpression }).Compile(); ParameterExpression parameterExpression2 = Expression.Parameter(typeof(ulong)); UInt64ToEnum = Expression.Lambda>(Expression.ConvertChecked(parameterExpression2, typeof(T)), new ParameterExpression[1] { parameterExpression2 }).Compile(); ParameterExpression parameterExpression3 = Expression.Parameter(typeof(T)); EnumToInt64 = Expression.Lambda>(Expression.ConvertChecked(parameterExpression3, typeof(long)), new ParameterExpression[1] { parameterExpression3 }).Compile(); ParameterExpression parameterExpression4 = Expression.Parameter(typeof(long)); Int64ToEnum = Expression.Lambda>(Expression.ConvertChecked(parameterExpression4, typeof(T)), new ParameterExpression[1] { parameterExpression4 }).Compile(); } } public sealed class ObjectEnumUtils { public bool IsBitSet { get; } = enumType.GetCustomAttribute() != null; public Func EnumToUInt64 { get; } public Func UInt64ToEnum { get; } public Func EnumToInt64 { get; } public Func Int64ToEnum { get; } public ObjectEnumUtils(Type enumType) { ParameterExpression parameterExpression = Expression.Parameter(typeof(object)); EnumToUInt64 = Expression.Lambda>(Expression.ConvertChecked(Expression.Convert(parameterExpression, enumType), typeof(ulong)), new ParameterExpression[1] { parameterExpression }).Compile(); ParameterExpression parameterExpression2 = Expression.Parameter(typeof(ulong)); UInt64ToEnum = Expression.Lambda>(Expression.Convert(Expression.ConvertChecked(parameterExpression2, enumType), typeof(object)), new ParameterExpression[1] { parameterExpression2 }).Compile(); ParameterExpression parameterExpression3 = Expression.Parameter(typeof(object)); EnumToInt64 = Expression.Lambda>(Expression.ConvertChecked(Expression.Convert(parameterExpression3, enumType), typeof(long)), new ParameterExpression[1] { parameterExpression3 }).Compile(); ParameterExpression parameterExpression4 = Expression.Parameter(typeof(long)); Int64ToEnum = Expression.Lambda>(Expression.Convert(Expression.ConvertChecked(parameterExpression4, enumType), typeof(object)), new ParameterExpression[1] { parameterExpression4 }).Compile(); base..ctor(); } } private static readonly ConcurrentDictionary __isBitSet = new ConcurrentDictionary(); public static ObjectEnumUtils OfType(Type type) { return __isBitSet.GetOrAdd(type, (Type t) => new ObjectEnumUtils(t)); } public static bool IsBitSet() where T : unmanaged, Enum { return Generic.IsBitSet; } public static ulong ToUInt64(this T value) where T : unmanaged, Enum { return Generic.EnumToUInt64(value); } public static T ToEnum(ulong value) where T : unmanaged, Enum { return Generic.UInt64ToEnum(value); } public static long ToInt64(this T value) where T : unmanaged, Enum { return Generic.EnumToInt64(value); } public static T ToEnum(long value) where T : unmanaged, Enum { return Generic.Int64ToEnum(value); } public static bool ExactlyOneBitSet(this T value) where T : unmanaged, Enum { bool flag = false; for (ulong num = value.ToUInt64(); num != 0L; num &= num - 1) { if (flag) { return false; } flag = true; } return flag; } } internal sealed class ExtendedZDO : ZDO { private sealed class AdditionalData { [CompilerGenerated] private IReadOnlyList k__BackingField; private static readonly Dictionary> _processors = new Dictionary>(); public bool HasProcessors { get; private set; } = true; public IReadOnlyList Processors { get { return k__BackingField ?? (k__BackingField = Processor.DefaultProcessors); } private set { k__BackingField = value; HasProcessors = value.Count > 0; } } public PrefabInfo PrefabInfo { get; } public ConcurrentDictionary? ComponentFieldAccessors { get; set; } public Dictionary? ProcessorDataRevisions { get; set; } public ZDOInventory? Inventory { get; set; } public bool? HasFields { get; set; } public RecreateHandler? Recreated { get; set; } public Action? Destroyed { get; set; } public static AdditionalData Dummy { get; } = new AdditionalData(Valheim.ServersideQoL.PrefabInfo.Dummy) { Processors = Array.Empty() }; public AdditionalData(PrefabInfo prefabInfo) { PrefabInfo = prefabInfo; base..ctor(); } public void Ungregister(IReadOnlyList processors) { int num = 0; foreach (Processor item in Processors.AsEnumerable()) { bool flag = true; foreach (Processor item2 in processors.AsEnumerable()) { if (item == item2) { flag = false; break; } } if (flag) { num = (num, item.GetType()).GetHashCode(); } } if (!_processors.TryGetValue(num, out IReadOnlyList value)) { List list = new List(); _processors.Add(num, value = list); foreach (Processor item3 in Processors.AsEnumerable()) { bool flag2 = true; foreach (Processor item4 in processors.AsEnumerable()) { if (item3 == item4) { flag2 = false; break; } } if (flag2) { list.Add(item3); } } } Processors = value; if (ProcessorDataRevisions == null) { return; } foreach (Processor item5 in processors.AsEnumerable()) { ProcessorDataRevisions.Remove(item5); } } public void UnregisterAllExcept(Processor keep) { int hashCode = (0, keep.GetType()).GetHashCode(); if (!_processors.TryGetValue(hashCode, out IReadOnlyList value)) { _processors.Add(hashCode, value = new <>z__ReadOnlySingleElementList(keep)); } if (ProcessorDataRevisions != null) { foreach (Processor item in Processors.AsEnumerable()) { if (item != keep) { ProcessorDataRevisions.Remove(item); } } } Processors = value; } public void UnregisterAll() { Processors = Array.Empty(); } public void ReregisterAll() { Processors = Processor.DefaultProcessors; } } private sealed class UnityObjectEqualityComparer : EqualityComparer where T : Object { public static UnityObjectEqualityComparer Instance { get; } = new UnityObjectEqualityComparer(); public override bool Equals(T x, T y) { object obj = x; string obj2 = ((obj != null) ? ((Object)obj).name : null); object obj3 = y; return obj2 == ((obj3 != null) ? ((Object)obj3).name : null); } public override int GetHashCode(T obj) { return ((Object)obj).name.GetHashCode(); } } private delegate T GetHandler(ZDO zdo, int hash, T defaultValue) where T : notnull; private delegate void SetHandler(ZDO zdo, int hash, T value) where T : notnull; private delegate bool RemoveHandler(ZDO zdo, int hash) where T : notnull; public sealed class ComponentFieldAccessor { private static class ExpressionCache where T : notnull { private static readonly Dictionary<(string, int), Expression>> __cache = new Dictionary<(string, int), Expression>>(); public static Expression> Get(Func>> factory, string callerFilePath, int callerLineNo) { if (!__cache.TryGetValue((callerFilePath, callerLineNo), out Expression> value)) { __cache.Add((callerFilePath, callerLineNo), value = factory()); } return value; } } private sealed class FieldReference where T : notnull { private readonly int _hash; private readonly Func _getFieldValue; private static readonly Dictionary> __cacheByFieldName = new Dictionary>(); private static readonly Dictionary<(string, int), FieldReference> __cacheByLocation = new Dictionary<(string, int), FieldReference>(); private static readonly (GetHandler Getter, SetHandler Setter, RemoveHandler? Remover, IEqualityComparer EqualityComparer) Accessors = ((Func<(GetHandler, SetHandler, RemoveHandler, IEqualityComparer)>)delegate { if (typeof(T) == typeof(bool)) { return ((GetHandler)(object)(GetHandler)((ZDO zdo, int hash, bool defaultValue) => zdo.GetBool(hash, defaultValue)), (SetHandler)(object)(SetHandler)delegate(ZDO zdo, int hash, bool value) { zdo.Set(hash, value); }, (RemoveHandler)(object)(RemoveHandler)((ZDO zdo, int hash) => zdo.RemoveInt(hash)), (IEqualityComparer)EqualityComparer.Default); } if (typeof(T) == typeof(int)) { return ((GetHandler)(object)(GetHandler)((ZDO zdo, int hash, int defaultValue) => zdo.GetInt(hash, defaultValue)), (SetHandler)(object)(SetHandler)delegate(ZDO zdo, int hash, int value) { zdo.Set(hash, value, false); }, (RemoveHandler)(object)(RemoveHandler)((ZDO zdo, int hash) => zdo.RemoveInt(hash)), (IEqualityComparer)EqualityComparer.Default); } if (typeof(T) == typeof(float)) { return ((GetHandler)(object)(GetHandler)((ZDO zdo, int hash, float defaultValue) => zdo.GetFloat(hash, defaultValue)), (SetHandler)(object)(SetHandler)delegate(ZDO zdo, int hash, float value) { zdo.Set(hash, value); }, (RemoveHandler)(object)(RemoveHandler)((ZDO zdo, int hash) => zdo.RemoveFloat(hash)), (IEqualityComparer)EqualityComparer.Default); } if (typeof(T) == typeof(string)) { return ((GetHandler)(object)(GetHandler)((ZDO zdo, int hash, string defaultValue) => zdo.GetString(hash, defaultValue)), (SetHandler)(object)(SetHandler)delegate(ZDO zdo, int hash, string value) { zdo.Set(hash, value); }, null, (IEqualityComparer)EqualityComparer.Default); } if (typeof(T) == typeof(Vector3)) { return ((GetHandler)(object)(GetHandler)((ZDO zdo, int hash, Vector3 defaultValue) => zdo.GetVec3(hash, defaultValue)), (SetHandler)(object)(SetHandler)delegate(ZDO zdo, int hash, Vector3 value) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) zdo.Set(hash, value); }, (RemoveHandler)(object)(RemoveHandler)((ZDO zdo, int hash) => zdo.RemoveVec3(hash)), (IEqualityComparer)EqualityComparer.Default); } if (typeof(T) == typeof(GameObject)) { return ((GetHandler)(object)new GetHandler(GetGameObject), (SetHandler)(object)(SetHandler)delegate(ZDO zdo, int hash, GameObject value) { zdo.Set(hash, ((Object)value).name); }, null, (IEqualityComparer)(object)UnityObjectEqualityComparer.Instance); } if (typeof(T) == typeof(ItemDrop)) { return ((GetHandler)(object)new GetHandler(GetItemDrop), (SetHandler)(object)(SetHandler)delegate(ZDO zdo, int hash, ItemDrop value) { zdo.Set(hash, ((Object)value).name); }, null, (IEqualityComparer)(object)UnityObjectEqualityComparer.Instance); } throw new NotSupportedException(); static GameObject GetGameObject(ZDO zdo, int hash, GameObject defaultValue) { string string2 = zdo.GetString(hash, ""); if (string.IsNullOrEmpty(string2)) { return defaultValue; } return ZNetScene.instance.GetPrefab(string2) ?? defaultValue; } static ItemDrop GetItemDrop(ZDO zdo, int hash, ItemDrop defaultValue) { string @string = zdo.GetString(hash, ""); if (!string.IsNullOrEmpty(@string)) { GameObject prefab = ZNetScene.instance.GetPrefab(@string); return ((prefab != null) ? prefab.GetComponent() : null) ?? defaultValue; } return defaultValue; } })(); private FieldReference(FieldInfo field) { _hash = StringExtensionMethods.GetStableHashCode(FormattableString.Invariant($"{typeof(TComponent).Name}.{field.Name}"), true); ParameterExpression parameterExpression = Expression.Parameter(typeof(TComponent)); _getFieldValue = Expression.Lambda>(Expression.Field(parameterExpression, field), new ParameterExpression[1] { parameterExpression }).Compile(); } public static FieldReference Get(Func>> factory, string callerFilePath, int callerLineNo) { if (!__cacheByLocation.TryGetValue((callerFilePath, callerLineNo), out FieldReference value)) { Expression> expression = ExpressionCache.Get(factory, callerFilePath, callerLineNo); MemberExpression memberExpression = (MemberExpression)expression.Body; FieldInfo fieldInfo = (FieldInfo)memberExpression.Member; if (!__cacheByFieldName.TryGetValue(fieldInfo.Name, out value)) { __cacheByFieldName.Add(fieldInfo.Name, value = new FieldReference(fieldInfo)); } __cacheByLocation.Add((callerFilePath, callerLineNo), value); } return value; } public T GetValue(ComponentFieldAccessor componentFieldAccessor) { T val = _getFieldValue(componentFieldAccessor._component); if (!componentFieldAccessor.HasFields) { return val; } return Accessors.Getter((ZDO)(object)componentFieldAccessor._zdo, _hash, val); } public ComponentFieldAccessor SetValue(ComponentFieldAccessor componentFieldAccessor, T value) { if (Accessors.Remover != null && Accessors.EqualityComparer.Equals(value, _getFieldValue(componentFieldAccessor._component))) { Accessors.Remover((ZDO)(object)componentFieldAccessor._zdo, _hash); } else { if (!componentFieldAccessor.HasFields) { componentFieldAccessor.SetHasFields(value: true); } Accessors.Setter((ZDO)(object)componentFieldAccessor._zdo, _hash, value); } return componentFieldAccessor; } public bool UpdateValue(ComponentFieldAccessor componentFieldAccessor, T value) { T val = _getFieldValue(componentFieldAccessor._component); if (Accessors.EqualityComparer.Equals(value, Accessors.Getter((ZDO)(object)componentFieldAccessor._zdo, _hash, val))) { return false; } bool flag = Accessors.EqualityComparer.Equals(value, val); if (Accessors.Remover != null && flag) { Accessors.Remover((ZDO)(object)componentFieldAccessor._zdo, _hash); } else { if (!componentFieldAccessor.HasFields && !flag) { componentFieldAccessor.SetHasFields(value: true); } Accessors.Setter((ZDO)(object)componentFieldAccessor._zdo, _hash, value); } return true; } public ComponentFieldAccessor ResetValue(ComponentFieldAccessor componentFieldAccessor) { if (!componentFieldAccessor.HasFields) { return componentFieldAccessor; } if (Accessors.Remover != null) { Accessors.Remover((ZDO)(object)componentFieldAccessor._zdo, _hash); } else { Accessors.Setter((ZDO)(object)componentFieldAccessor._zdo, _hash, _getFieldValue(componentFieldAccessor._component)); } return componentFieldAccessor; } public bool UpdateResetValue(ComponentFieldAccessor componentFieldAccessor) { if (!componentFieldAccessor.HasFields) { return false; } if (Accessors.Remover != null) { return Accessors.Remover((ZDO)(object)componentFieldAccessor._zdo, _hash); } T val = _getFieldValue(componentFieldAccessor._component); if (Accessors.EqualityComparer.Equals(Accessors.Getter((ZDO)(object)componentFieldAccessor._zdo, _hash, val), val)) { return false; } Accessors.Setter((ZDO)(object)componentFieldAccessor._zdo, _hash, val); return true; } } private readonly ExtendedZDO _zdo; private readonly TComponent _component; private bool? _hasComponentFields; private static readonly int __hasComponentFieldsHash = StringExtensionMethods.GetStableHashCode(FormattableString.Invariant(FormattableStringFactory.Create("{0}{1}", "HasFields", typeof(TComponent).Name)), true); public bool HasFields { get { if (_zdo.HasFields) { bool valueOrDefault = _hasComponentFields.GetValueOrDefault(); if (!_hasComponentFields.HasValue) { valueOrDefault = ((ZDO)_zdo).GetBool(__hasComponentFieldsHash, false); _hasComponentFields = valueOrDefault; return valueOrDefault; } return valueOrDefault; } return false; } } public ComponentFieldAccessor(ExtendedZDO zdo, TComponent component) { _zdo = zdo; _component = component; base..ctor(); } private void SetHasFields(bool value) { if (value && !_zdo.HasFields) { _zdo.SetHasFields(); } if (_hasComponentFields != value) { ExtendedZDO zdo = _zdo; int _hasComponentFieldsHash = __hasComponentFieldsHash; bool? flag = (_hasComponentFields = value); ((ZDO)zdo).Set(_hasComponentFieldsHash, flag.Value); } } [MustBeOnUniqueLine] public bool GetBool(Func>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).GetValue(this); } [MustBeOnUniqueLine] public float GetFloat(Func>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).GetValue(this); } [MustBeOnUniqueLine] public int GetInt(Func>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).GetValue(this); } [MustBeOnUniqueLine] public string GetString(Func>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).GetValue(this); } [MustBeOnUniqueLine] public ComponentFieldAccessor Set(Func>> fieldExpressionFactory, bool value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).SetValue(this, value); } [MustBeOnUniqueLine] public ComponentFieldAccessor Set(Func>> fieldExpressionFactory, float value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).SetValue(this, value); } [MustBeOnUniqueLine] public ComponentFieldAccessor Set(Func>> fieldExpressionFactory, int value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).SetValue(this, value); } [MustBeOnUniqueLine] public ComponentFieldAccessor Set(Func>> fieldExpressionFactory, Vector3 value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).SetValue(this, value); } [MustBeOnUniqueLine] public ComponentFieldAccessor Set(Func>> fieldExpressionFactory, string value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).SetValue(this, value); } [MustBeOnUniqueLine] public ComponentFieldAccessor Set(Func>> fieldExpressionFactory, GameObject value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).SetValue(this, value); } [MustBeOnUniqueLine] public ComponentFieldAccessor Set(Func>> fieldExpressionFactory, ItemDrop value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).SetValue(this, value); } [MustBeOnUniqueLine] public bool UpdateValue(Func>> fieldExpressionFactory, bool value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateValue(this, value); } [MustBeOnUniqueLine] public bool UpdateValue(Func>> fieldExpressionFactory, float value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateValue(this, value); } [MustBeOnUniqueLine] public bool UpdateValue(Func>> fieldExpressionFactory, int value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateValue(this, value); } [MustBeOnUniqueLine] public bool UpdateValue(Func>> fieldExpressionFactory, string value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateValue(this, value); } [MustBeOnUniqueLine] public bool UpdateValue(Func>> fieldExpressionFactory, GameObject value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateValue(this, value); } [MustBeOnUniqueLine] public bool UpdateValue(Func>> fieldExpressionFactory, ItemDrop value, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateValue(this, value); } [MustBeOnUniqueLine] public ComponentFieldAccessor Reset(Func>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).ResetValue(this); } [MustBeOnUniqueLine] public ComponentFieldAccessor Reset(Func>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).ResetValue(this); } [MustBeOnUniqueLine] public ComponentFieldAccessor Reset(Func>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).ResetValue(this); } [MustBeOnUniqueLine] public ComponentFieldAccessor Reset(Func>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).ResetValue(this); } [MustBeOnUniqueLine] public ComponentFieldAccessor Reset(Func>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).ResetValue(this); } [MustBeOnUniqueLine] public ComponentFieldAccessor Reset(Func>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).ResetValue(this); } [MustBeOnUniqueLine] public bool UpdateResetValue(Func>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateResetValue(this); } [MustBeOnUniqueLine] public bool UpdateResetValue(Func>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateResetValue(this); } [MustBeOnUniqueLine] public bool UpdateResetValue(Func>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateResetValue(this); } [MustBeOnUniqueLine] public bool UpdateResetValue(Func>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateResetValue(this); } [MustBeOnUniqueLine] public bool UpdateResetValue(Func>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateResetValue(this); } [MustBeOnUniqueLine] public bool UpdateResetValue(Func>> fieldExpressionFactory, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateResetValue(this); } [MustBeOnUniqueLine] public bool SetOrReset(Func>> fieldExpressionFactory, bool set, bool setValue, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { if (!set) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateResetValue(this); } return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateValue(this, setValue); } [MustBeOnUniqueLine] public bool SetOrReset(Func>> fieldExpressionFactory, bool set, float setValue, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { if (!set) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateResetValue(this); } return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateValue(this, setValue); } [MustBeOnUniqueLine] public bool SetOrReset(Func>> fieldExpressionFactory, bool set, int setValue, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { if (!set) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateResetValue(this); } return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateValue(this, setValue); } [MustBeOnUniqueLine] public bool SetOrReset(Func>> fieldExpressionFactory, bool set, string setValue, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { if (!set) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateResetValue(this); } return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateValue(this, setValue); } [MustBeOnUniqueLine] public bool SetOrReset(Func>> fieldExpressionFactory, bool set, GameObject setValue, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { if (!set) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateResetValue(this); } return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateValue(this, setValue); } [MustBeOnUniqueLine] public bool SetOrReset(Func>> fieldExpressionFactory, bool set, ItemDrop setValue, [CallerFilePath] string callerFilePath = null, [CallerLineNumber] int callerLineNo = -1) { if (!set) { return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateResetValue(this); } return FieldReference.Get(fieldExpressionFactory, callerFilePath, callerLineNo).UpdateValue(this, setValue); } } public delegate void RecreateHandler(ExtendedZDO oldZdo, ExtendedZDO newZdo); private sealed class ZDOInventory : IZDOInventory, IZDOInventoryReadOnly { private List? _items; private uint _dataRevision; public Inventory Inventory { get; private set; } public ExtendedZDO ZDO { get; private set; } public int? PickupRange { get; set; } public int? FeedRange { get; set; } private List Items { get { if (_items == null) { _items = Inventory.GetAllItems(); } else if (_items != Inventory.GetAllItems()) { throw new Exception("Assumption violated"); } return _items; } } public float TotalWeight => Inventory.GetTotalWeight(); IList IZDOInventory.Items => Items; IReadOnlyList IZDOInventoryReadOnly.Items => Items; public ZDOInventory(ExtendedZDO zdo) { ZDO = zdo; _dataRevision = uint.MaxValue; base..ctor(); } public ZDOInventory Update() { //IL_00ff: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Expected O, but got Unknown //IL_0120: Unknown result type (might be due to invalid IL or missing references) //IL_012a: Expected O, but got Unknown if (_dataRevision == ((ZDO)ZDO).DataRevision) { return this; } byte[] items = ZDO.Vars.GetItems(); ComponentFieldAccessor componentFieldAccessor = ZDO.Fields(getUnknownComponent: false); int @int = componentFieldAccessor.GetInt(() => (Container x) => x.m_width, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\ExtendedZDO.ZDOInventory.cs", 44); int int2 = componentFieldAccessor.GetInt(() => (Container x) => x.m_height, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\ExtendedZDO.ZDOInventory.cs", 45); if (Inventory == null || Inventory.GetWidth() != @int || Inventory.GetHeight() != int2) { Inventory = new Inventory(ZDO.PrefabInfo.Container.Value.Container.m_name, ZDO.PrefabInfo.Container.Value.Container.m_bkg, @int, int2); _items = null; } if (items != null && items.Length > 0) { Inventory.Load(new ZPackage(items)); } else { Items.Clear(); } _dataRevision = ((ZDO)ZDO).DataRevision; return this; } public void UpdateZDO(ExtendedZDO zdo) { ZDO = zdo; _items = null; _dataRevision = 0u; Update(); } public void Save() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_009f: Unknown result type (might be due to invalid IL or missing references) ZPackage val = new ZPackage(); Inventory.Save(val); uint dataRevision = ((ZDO)ZDO).DataRevision; byte[] array = val.GetArray(); ZDO.Vars.SetItems(array, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\ExtendedZDO.ZDOInventory.cs", 75); if (dataRevision != ((ZDO)ZDO).DataRevision) { (Container, PrefabInfo.Optional, PrefabInfo.Optional, PrefabInfo.Optional, PrefabInfo.Optional)? container = ZDO.PrefabInfo.Container; if (container.HasValue) { PrefabInfo.Optional item = container.GetValueOrDefault().Item5; if (item.Value != null) { ExtendedZDO zDO = ZDO; ((ZDO)zDO).DataRevision = ((ZDO)zDO).DataRevision + 120; } } ZDOMan.instance.ForceSendZDO(((ZDO)ZDO).m_uid); } _dataRevision = ((ZDO)ZDO).DataRevision; } } public readonly struct ZDOVars_ { private readonly ExtendedZDO _zdo; private static readonly int _animationCraftingHash = ZSyncAnimation.GetHash("crafting"); private static int __isBackpack = StringExtensionMethods.GetStableHashCode("argusmagnus.ServersideQoL.IsBackpack", true); private static int __processorId = StringExtensionMethods.GetStableHashCode("argusmagnus.ServersideQoL.ProcessorId", true); private static int __intTag = StringExtensionMethods.GetStableHashCode("argusmagnus.ServersideQoL.IntTag", true); private static int __lastSpawnedTime = StringExtensionMethods.GetStableHashCode("argusmagnus.ServersideQoL.LastSpawnedTime", true); private static int __spawnedByTrophy = StringExtensionMethods.GetStableHashCode("argusmagnus.ServersideQoL.SpawnedByTrophy", true); private static int __portalHubId = StringExtensionMethods.GetStableHashCode("argusmagnus.ServersideQoL.PortalHubId", true); private static int __returnContentToCreator = StringExtensionMethods.GetStableHashCode("argusmagnus.ServersideQoL.ReturnContentToCreator", true); private static int __initialLevel = StringExtensionMethods.GetStableHashCode("argusmagnus.ServersideQoL.InitialLevel", true); private static int __beaconFound = StringExtensionMethods.GetStableHashCode("argusmagnus.ServersideQoL.BeaconState", true); private static int __adminBuildModifiers = StringExtensionMethods.GetStableHashCode("argusmagnus.ServersideQoL.AdminBuildModifiers", true); public ZDOVars_(ExtendedZDO zdo) { _zdo = zdo; } private void ValidateOwnership(string filePath, int lineNo) { if (Main.Instance.Config.General.DiagnosticLogs.Value && _zdo.PrefabInfo.Container.HasValue && !_zdo.IsOwnerOrUnassigned() && !_zdo.IsModCreator()) { Main.Instance.Logger.LogWarning($"{Path.GetFileName(filePath)} L{lineNo}: Container was modified while it is owned by a client, which can lead to the loss of items."); } } public int GetState(int defaultValue = 0) { return ((ZDO)_zdo).GetInt(ZDOVars.s_state, defaultValue); } public void SetState(int value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_state, value, false); } public long GetCreator(long defaultValue = 0L) { return ((ZDO)_zdo).GetLong(ZDOVars.s_creator, defaultValue); } public void SetCreator(long value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_creator, value); } public bool GetInUse(bool defaultValue = false) { return ((ZDO)_zdo).GetBool(ZDOVars.s_inUse, defaultValue); } public void SetInUse(bool value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_inUse, value); } public float GetFuel(float defaultValue = 0f) { return ((ZDO)_zdo).GetFloat(ZDOVars.s_fuel, defaultValue); } public void SetFuel(float value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_fuel, value); } public bool GetPiece(bool defaultValue = false) { return ((ZDO)_zdo).GetBool(ZDOVars.s_piece, defaultValue); } public void SetPiece(bool value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_piece, value); } public byte[]? GetItems(byte[]? defaultValue = null) { return ((ZDO)_zdo).GetByteArray(ZDOVars.s_items, defaultValue); } public void SetItems(byte[]? value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_items, value); } public string GetTag(string defaultValue = "") { return ((ZDO)_zdo).GetString(ZDOVars.s_tag, defaultValue); } public void SetTag(string value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_tag, value); } public byte[]? GetData(byte[]? defaultValue = null) { return ((ZDO)_zdo).GetByteArray(ZDOVars.s_data, defaultValue); } public void SetData(byte[]? value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_data, value); } public float GetStamina(float defaultValue = 0f) { return ((ZDO)_zdo).GetFloat(ZDOVars.s_stamina, defaultValue); } public float GetEitr(float defaultValue = 0f) { return ((ZDO)_zdo).GetFloat(ZDOVars.s_eitr, defaultValue); } public long GetPlayerID(long defaultValue = 0L) { return ((ZDO)_zdo).GetLong(ZDOVars.s_playerID, defaultValue); } public void SetPlayerID(long value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_playerID, value); } public string GetPlayerName(string defaultValue = "") { return ((ZDO)_zdo).GetString(ZDOVars.s_playerName, defaultValue); } public void SetPlayerName(string value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_playerName, value); } public string GetFollow(string defaultValue = "") { return ((ZDO)_zdo).GetString(ZDOVars.s_follow, defaultValue); } public void SetFollow(string value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_follow, value); } public int GetRightItem(int defaultValue = 0) { return ((ZDO)_zdo).GetInt(ZDOVars.s_rightItem, defaultValue); } public int GetLeftItem(int defaultValue = 0) { return ((ZDO)_zdo).GetInt(ZDOVars.s_leftItem, defaultValue); } public string GetText(string defaultValue = "") { return ((ZDO)_zdo).GetString(ZDOVars.s_text, defaultValue); } public void SetText(string value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_text, value); } public string GetItem(string defaultValue = "") { return ((ZDO)_zdo).GetString(ZDOVars.s_item, defaultValue); } public void SetItem(string value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_item, value); } public string GetItem(int idx, string defaultValue = "") { return ((ZDO)_zdo).GetString(FormattableString.Invariant($"item{idx}"), defaultValue); } public void SetItem(int idx, string value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(FormattableString.Invariant($"item{idx}"), value); } public int GetQueued(int defaultValue = 0) { return ((ZDO)_zdo).GetInt(ZDOVars.s_queued, defaultValue); } public void SetQueued(int value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_queued, value, false); } public bool GetTamed(bool defaultValue = false) { return ((ZDO)_zdo).GetBool(ZDOVars.s_tamed, defaultValue); } public void SetTamed(bool value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_tamed, value); } public float GetTameTimeLeft(float defaultValue = 0f) { return ((ZDO)_zdo).GetFloat(ZDOVars.s_tameTimeLeft, defaultValue); } public void SetTameTimeLeft(float value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_tameTimeLeft, value); } public int GetAmmo(int defaultValue = 0) { return ((ZDO)_zdo).GetInt(ZDOVars.s_ammo, defaultValue); } public void SetAmmo(int value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_ammo, value, false); } public string GetAmmoType(string defaultValue = "") { return ((ZDO)_zdo).GetString(ZDOVars.s_ammoType, defaultValue); } public void SetAmmoType(string value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_ammoType, value); } public float GetGrowStart(float defaultValue = 0f) { return ((ZDO)_zdo).GetFloat(ZDOVars.s_growStart, defaultValue); } public void SetGrowStart(float value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_growStart, value); } public DateTime GetSpawnTime(DateTime defaultValue = default(DateTime)) { return new DateTime(((ZDO)_zdo).GetLong(ZDOVars.s_spawnTime, defaultValue.Ticks)); } public void SetSpawnTime(DateTime value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_spawnTime, value.Ticks); } public float GetHealth(float defaultValue = 0f) { return ((ZDO)_zdo).GetFloat(ZDOVars.s_health, defaultValue); } public void SetHealth(float value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_health, value); } public string GetHealthString(string defaultValue = "") { return ((ZDO)_zdo).GetString(ZDOVars.s_health, defaultValue); } public void SetHealth(string value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_health, value); } public void RemoveHealth([CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).RemoveFloat(ZDOVars.s_health); } public int GetPermitted(int defaultValue = 0) { return ((ZDO)_zdo).GetInt(ZDOVars.s_permitted, defaultValue); } public void SetPermitted(int value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_permitted, value, false); } public int GetLevel(int defaultValue = 1) { return ((ZDO)_zdo).GetInt(ZDOVars.s_level, defaultValue); } public void SetLevel(int value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_level, value, false); } public bool GetPatrol(bool defaultValue = false) { return ((ZDO)_zdo).GetBool(ZDOVars.s_patrol, defaultValue); } public void SetPatrol(bool value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_patrol, value); } public Vector3 GetPatrolPoint(Vector3 defaultValue = default(Vector3)) { //IL_000b: 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) return ((ZDO)_zdo).GetVec3(ZDOVars.s_patrolPoint, defaultValue); } public void SetPatrolPoint(Vector3 value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_patrolPoint, value); } public Vector3 GetSpawnPoint(Vector3 defaultValue = default(Vector3)) { //IL_000b: 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) return ((ZDO)_zdo).GetVec3(ZDOVars.s_spawnPoint, defaultValue); } public void SetSpawnPoint(Vector3 value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_spawnPoint, value); } public int GetEmoteID(int defaultValue = 0) { return ((ZDO)_zdo).GetInt(ZDOVars.s_emoteID, defaultValue); } public Emotes GetEmote(Emotes defaultValue = -1) { //IL_0021: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) if (!Enum.TryParse(((ZDO)_zdo).GetString(ZDOVars.s_emote, ""), ignoreCase: true, out Emotes result)) { return defaultValue; } return result; } public bool GetAnimationIsEncumbered(bool defaultValue = false) { return ((ZDO)_zdo).GetBool(PrivateAccessor.ZSyncAnimationZDOSalt + PrivateAccessor.CharacterAnimationHashEncumbered, defaultValue); } public bool GetAnimationInWater(bool defaultValue = false) { return ((ZDO)_zdo).GetBool(PrivateAccessor.ZSyncAnimationZDOSalt + PrivateAccessor.CharacterAnimationHashInWater, defaultValue); } public bool GetAnimationIsCrouching(bool defaultValue = false) { return ((ZDO)_zdo).GetBool(PrivateAccessor.ZSyncAnimationZDOSalt + PrivateAccessor.PlayerAnimationHashCrouching, defaultValue); } public int GetAnimationCrafting(int defaultValue = 0) { return ((ZDO)_zdo).GetInt(PrivateAccessor.ZSyncAnimationZDOSalt + _animationCraftingHash, defaultValue); } public DateTime GetTameLastFeeding(DateTime defaultValue = default(DateTime)) { return new DateTime(((ZDO)_zdo).GetLong(ZDOVars.s_tameLastFeeding, defaultValue.Ticks)); } public void SetTameLastFeeding(DateTime value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_tameLastFeeding, value.Ticks); } public bool GetEventCreature(bool defaultValue = false) { return ((ZDO)_zdo).GetBool(ZDOVars.s_eventCreature, defaultValue); } public bool GetInBed(bool defaultValue = false) { return ((ZDO)_zdo).GetBool(ZDOVars.s_inBed, defaultValue); } public int GetLocation(int defaultValue = 0) { return ((ZDO)_zdo).GetInt(ZDOVars.s_location, defaultValue); } public int GetSeed(int defaultValue = 0) { return ((ZDO)_zdo).GetInt(ZDOVars.s_seed, defaultValue); } public bool GetAttachJoint(bool defaultValue = false) { return ((ZDO)_zdo).GetBool(ZDOVars.s_attachJointHash, defaultValue); } public long GetUser(long defaultValue = 0L) { return ((ZDO)_zdo).GetLong(ZDOVars.s_user, defaultValue); } public bool GetIsDead(bool defaultValue = false) { return ((ZDO)_zdo).GetBool(ZDOVars.s_dead, defaultValue); } public long GetOwner(long defaultValue = 0L) { return ((ZDO)_zdo).GetLong(ZDOVars.s_owner, defaultValue); } public void SetOwner(long value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_owner, value); } public string GetOwnerName(string defaultValue = "") { return ((ZDO)_zdo).GetString(ZDOVars.s_ownerName, defaultValue); } public void SetOwnerName(string value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(ZDOVars.s_ownerName, value); } public bool GetIsBackpack(bool defaultValue = false) { return ((ZDO)_zdo).GetBool(__isBackpack, defaultValue); } public void SetIsBackpack(bool value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(__isBackpack, value); } public Guid GetProcessorId(Guid defaultValue = default(Guid)) { byte[] byteArray = ((ZDO)_zdo).GetByteArray(__processorId, Array.Empty()); if (byteArray == null || byteArray.Length <= 0) { return defaultValue; } return new Guid(byteArray); } public void SetProcessorId(Guid value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(__processorId, (value == default(Guid)) ? Array.Empty() : value.ToByteArray()); } public int GetIntTag(int defaultValue = 0) { return ((ZDO)_zdo).GetInt(__intTag, defaultValue); } public void SetIntTag(int value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(__intTag, value, false); } public void RemoveIntTag([CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).RemoveInt(__intTag); } public DateTimeOffset GetLastSpawnedTime(DateTimeOffset defaultValue = default(DateTimeOffset)) { return new DateTimeOffset(((ZDO)_zdo).GetLong(__lastSpawnedTime, defaultValue.Ticks), default(TimeSpan)); } public void SetLastSpawnedTime(DateTimeOffset value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(__lastSpawnedTime, value.Ticks - value.Offset.Ticks); } public bool GetSpawnedByTrophy(bool defaultValue = false) { return ((ZDO)_zdo).GetBool(__spawnedByTrophy, defaultValue); } public void SetSpawnedByTrophy(bool value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(__spawnedByTrophy, value); } public int GetPortalHubId(int defaultValue = 0) { return ((ZDO)_zdo).GetInt(__portalHubId, defaultValue); } public void SetPortalHubId(int value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(__portalHubId, value, false); } public bool GetReturnContentToCreator(bool defaultValue = false) { return ((ZDO)_zdo).GetBool(__returnContentToCreator, defaultValue); } public void SetReturnContentToCreator(bool value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(__returnContentToCreator, value); } public int GetInitialLevel(int defaultValue = 0) { return ((ZDO)_zdo).GetInt(__initialLevel, defaultValue); } public void SetInitialLevel(int value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(__initialLevel, value, false); } public void RemoveInitialLevel([CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).RemoveInt(__initialLevel); } public bool GetBeaconFound(bool defaultValue = false) { return ((ZDO)_zdo).GetBool(__beaconFound, defaultValue); } public void SetBeaconFound(bool value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(__beaconFound, value); } public bool GetSacrifiedMegingjord(long playerID, bool defaultValue = false) { return ((ZDO)_zdo).GetBool($"player{playerID}_SacrifiedMegingjord", defaultValue); } public void SetSacrifiedMegingjord(long playerID, bool value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set($"player{playerID}_SacrifiedMegingjord", value); } public bool GetSacrifiedCryptKey(long playerID, bool defaultValue = false) { return ((ZDO)_zdo).GetBool($"player{playerID}_SacrifiedCryptKey", defaultValue); } public void SetSacrifiedCryptKey(long playerID, bool value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set($"player{playerID}_SacrifiedCryptKey", value); } public bool GetSacrifiedWishbone(long playerID, bool defaultValue = false) { return ((ZDO)_zdo).GetBool($"player{playerID}_SacrifiedWishbone", defaultValue); } public void SetSacrifiedWishbone(long playerID, bool value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set($"player{playerID}_SacrifiedWishbone", value); } public bool GetSacrifiedTornSpirit(long playerID, bool defaultValue = false) { return ((ZDO)_zdo).GetBool($"player{playerID}_SacrifiedTornSpirit", defaultValue); } public void SetSacrifiedTornSpirit(long playerID, bool value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set($"player{playerID}_SacrifiedTornSpirit", value); } public float GetEstimatedSkillLevel(long playerID, SkillType skill, float defaultValue = 0f) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) return ((ZDO)_zdo).GetFloat($"player{playerID}_EstimatedSkillLevel_{skill}", defaultValue); } public void SetEstimatedSkillLevel(long playerID, SkillType skill, float value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set($"player{playerID}_EstimatedSkillLevel_{skill}", value); } public PlayerProcessor.BuildModifiers GetAdminBuildModifiers(PlayerProcessor.BuildModifiers defaultValue = PlayerProcessor.BuildModifiers.None) { return (PlayerProcessor.BuildModifiers)((ZDO)_zdo).GetInt(__adminBuildModifiers, (int)defaultValue); } public void SetAdminBuildModifiers(PlayerProcessor.BuildModifiers value, [CallerFilePath] string filePath = "", [CallerLineNumber] int lineNo = 0) { ValidateOwnership(filePath, lineNo); ((ZDO)_zdo).Set(__adminBuildModifiers, (int)value, false); } } private ZDOID _lastId = ZDOID.None; private AdditionalData? _addData; private static readonly int __hasFieldsHash = StringExtensionMethods.GetStableHashCode("HasFields", true); private static bool _onZdoDestroyedRegistered; [CompilerGenerated] private IPeerInfo? k__BackingField; private AdditionalData AddData { get { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) if (_lastId != base.m_uid || _addData == null) { _lastId = base.m_uid; if (base.m_uid != ZDOID.None) { PrefabInfo prefabInfo = SharedProcessorState.GetPrefabInfo(((ZDO)this).GetPrefab()); if ((object)prefabInfo != null) { _addData = new AdditionalData(prefabInfo); goto IL_0061; } } _addData = AdditionalData.Dummy; } goto IL_0061; IL_0061: return _addData; } } public PrefabInfo PrefabInfo => AddData.PrefabInfo; public IZDOInventory Inventory { get { AdditionalData addData = AddData; ZDOInventory zDOInventory = addData.Inventory; if (zDOInventory == null) { if (!PrefabInfo.Container.HasValue) { throw new InvalidOperationException(); } ZDOInventory zDOInventory3 = (addData.Inventory = new ZDOInventory(this)); zDOInventory = zDOInventory3; } return zDOInventory.Update(); } } public IZDOInventoryReadOnly InventoryReadOnly { get { AdditionalData addData = AddData; ZDOInventory zDOInventory = addData.Inventory; if (zDOInventory == null) { if (!PrefabInfo.Container.HasValue) { throw new InvalidOperationException(); } ZDOInventory zDOInventory3 = (addData.Inventory = new ZDOInventory(this)); zDOInventory = zDOInventory3; } return zDOInventory; } } public bool HasFields { get { AdditionalData addData = AddData; bool? hasFields = addData.HasFields; bool valueOrDefault = hasFields.GetValueOrDefault(); if (!hasFields.HasValue) { valueOrDefault = ((ZDO)this).GetBool(__hasFieldsHash, false); bool? hasFields2 = valueOrDefault; addData.HasFields = hasFields2; return valueOrDefault; } return valueOrDefault; } } public ZDOVars_ Vars => new ZDOVars_(this); public bool HasProcessors => AddData.HasProcessors; public IReadOnlyList Processors => AddData.Processors; public DateTimeOffset OwnerTimestamp { get; private set; } public IPeerInfo? OwnerPeerInfo { get { if (!((ZDO)this).HasOwner()) { return null; } long owner = ((ZDO)this).GetOwner(); IPeerInfo? peerInfo = k__BackingField; if (peerInfo == null || peerInfo.Owner != owner) { IPeerInfo? peerInfo2 = k__BackingField; if (peerInfo2 != null) { peerInfo2.PlayerZDO.Destroyed -= OnOwnerPlayerZdoDestroyed; } k__BackingField = Processor.Instance().GetPeerInfo(owner); IPeerInfo? peerInfo3 = k__BackingField; if (peerInfo3 != null) { peerInfo3.PlayerZDO.Destroyed += OnOwnerPlayerZdoDestroyed; } } return k__BackingField; void OnOwnerPlayerZdoDestroyed(ZDO zdo) { k__BackingField = null; } } } public event RecreateHandler? Recreated { add { AdditionalData addData = AddData; addData.Recreated = (RecreateHandler)Delegate.Combine(addData.Recreated, value); } remove { AdditionalData addData = AddData; addData.Recreated = (RecreateHandler)Delegate.Remove(addData.Recreated, value); } } public event Action? Destroyed { add { if (!_onZdoDestroyedRegistered) { ZDOMan instance = ZDOMan.instance; instance.m_onZDODestroyed = (Action)Delegate.Combine(instance.m_onZDODestroyed, new Action(OnZdoDestroyed)); _onZdoDestroyedRegistered = true; } AdditionalData addData = AddData; addData.Destroyed = (Action)Delegate.Combine(addData.Destroyed, value); } remove { AdditionalData addData = AddData; addData.Destroyed = (Action)Delegate.Remove(addData.Destroyed, value); } } public void SetModAsCreator(Processor.CreatorMarkers marker = Processor.CreatorMarkers.None) { Vars.SetCreator((long)Main.PluginGuidHash | (long)((ulong)marker << 32), "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\ExtendedZDO.cs", 45); } public bool IsModCreator(out Processor.CreatorMarkers marker) { marker = Processor.CreatorMarkers.None; if ((int)Vars.GetCreator(0L) != Main.PluginGuidHash) { return false; } marker = (Processor.CreatorMarkers)((ulong)Vars.GetCreator(0L) >> 32); return true; } public bool IsModCreator() { Processor.CreatorMarkers marker; return IsModCreator(out marker); } private static void OnZdoDestroyed(ZDO zdo) { ExtendedZDO extendedZDO = (ExtendedZDO)(object)zdo; extendedZDO._addData?.Destroyed?.Invoke(extendedZDO); extendedZDO._addData = null; } private void SetHasFields() { if ((!AddData.HasFields) ?? true) { ((ZDO)this).Set(__hasFieldsHash, true); AddData.HasFields = true; } } public void UnregisterProcessors(IReadOnlyList processors) { AddData.Ungregister(processors); } public void UnregisterAllExcept(Processor processor) { AddData.UnregisterAllExcept(processor); } public void UnregisterAllProcessors() { AddData.UnregisterAll(); } public void ReregisterAllProcessors() { _addData?.ReregisterAll(); } public void UpdateProcessorDataRevision(Processor processor) { AdditionalData addData = AddData; (addData.ProcessorDataRevisions ?? (addData.ProcessorDataRevisions = new Dictionary()))[processor] = (((ZDO)this).DataRevision, ((ZDO)this).OwnerRevision); } public void ResetProcessorDataRevision(Processor processor) { AddData.ProcessorDataRevisions?.Remove(processor); } public bool CheckProcessorDataRevisionChanged(Processor processor) { if (AddData.ProcessorDataRevisions != null && AddData.ProcessorDataRevisions.TryGetValue(processor, out (uint, uint) value)) { (uint, uint) tuple = value; uint dataRevision = ((ZDO)this).DataRevision; ushort ownerRevision = ((ZDO)this).OwnerRevision; if (tuple.Item1 == dataRevision && tuple.Item2 == ownerRevision) { return false; } } return true; } public void Destroy() { ClaimOwnershipInternal(); ZDOMan.instance.DestroyZDO((ZDO)(object)this); } public ExtendedZDO CreateClone() { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_000d: 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_001b: Expected O, but got Unknown //IL_0027: Unknown result type (might be due to invalid IL or missing references) //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Expected O, but got Unknown int prefab = ((ZDO)this).GetPrefab(); Vector3 position = ((ZDO)this).GetPosition(); long owner = ((ZDO)this).GetOwner(); ZPackage val = new ZPackage(); ((ZDO)this).Serialize(val); ExtendedZDO extendedZDO = (ExtendedZDO)(object)ZDOMan.instance.CreateNewZDO(position, prefab); ((ZDO)extendedZDO).Deserialize(new ZPackage(val.GetArray())); extendedZDO.SetOwnerInternal(owner); return extendedZDO; } public ExtendedZDO Recreate() { ExtendedZDO extendedZDO = CreateClone(); _addData?.Recreated?.Invoke(this, extendedZDO); Destroy(); return extendedZDO; } public void SetOwner(long uid) { OwnerTimestamp = DateTimeOffset.UtcNow; ((ZDO)this).SetOwner(uid); } public void SetOwnerInternal(long uid) { OwnerTimestamp = DateTimeOffset.UtcNow; ((ZDO)this).SetOwnerInternal(uid); } public void ClaimOwnership() { SetOwner(ZDOMan.GetSessionID()); } public void ClaimOwnershipInternal() { SetOwnerInternal(ZDOMan.GetSessionID()); } public void ReleaseOwnership() { SetOwner(0L); } public void ReleaseOwnershipInternal() { SetOwnerInternal(0L); } public bool IsOwnerOrUnassigned() { if (((ZDO)this).HasOwner()) { return ((ZDO)this).IsOwner(); } return true; } public TimeSpan GetTimeSinceSpawned() { return ZNet.instance.GetTime() - Vars.GetSpawnTime(); } public ComponentFieldAccessor Fields(bool getUnknownComponent = false) where TComponent : MonoBehaviour { if (AddData != AdditionalData.Dummy) { AdditionalData addData = AddData; return (ComponentFieldAccessor)(addData.ComponentFieldAccessors ?? (addData.ComponentFieldAccessors = new ConcurrentDictionary())).GetOrAdd(typeof(TComponent), delegate(Type key) { if (!PrefabInfo.Components.TryGetValue(key, out MonoBehaviour value) && getUnknownComponent) { value = (MonoBehaviour)(object)PrefabInfo.Prefab.GetComponentInChildren(); } if (value == null) { throw new KeyNotFoundException(); } return new ComponentFieldAccessor(this, (TComponent)(object)value); }); } if (getUnknownComponent) { GameObject prefab = ZNetScene.instance.GetPrefab(((ZDO)this).GetPrefab()); TComponent val = ((prefab != null) ? prefab.GetComponentInChildren() : default(TComponent)); if (val == null) { throw new KeyNotFoundException(); } return new ComponentFieldAccessor(this, val); } throw new InvalidOperationException(); } } internal interface IZDOInventoryReadOnly { IReadOnlyList Items { get; } float TotalWeight { get; } } internal interface IZDOInventory { Inventory Inventory { get; } IList Items { get; } float TotalWeight { get; } int? PickupRange { get; set; } int? FeedRange { get; set; } void Save(); } internal static class ExtensionMethods { public readonly struct ListEnumerable { public struct Enumerator : IEnumerator, IEnumerator, IDisposable { private readonly IReadOnlyList _list; private readonly int _count; private int _index; public T Current { get; private set; } readonly object? IEnumerator.Current => Current; public Enumerator(IReadOnlyList list) { _list = list; _count = list.Count; _index = -1; Current = default(T); } public void Dispose() { Current = default(T); } public bool MoveNext() { if (++_index < _count) { Current = _list[_index]; return true; } Current = default(T); return false; } public void Reset() { _index = -1; } } private readonly IReadOnlyList _list; public ListEnumerable(IReadOnlyList list) { _list = list; } public Enumerator GetEnumerator() { return new Enumerator(_list); } } public static ExtendedZDO? GetExtendedZDO(this ZDOMan instance, ZDOID id) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return (ExtendedZDO)(object)instance.GetZDO(id); } public static int GetActiveArea(this ZoneSystem instance) { return instance.m_activeArea - 1; } public static int GetLoadedArea(this ZoneSystem instance) { return instance.m_activeArea; } public static float GetHeight(this Heightmap hmap, Vector3 pos) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) int num = default(int); int num2 = default(int); hmap.WorldToVertex(pos, ref num, ref num2); return hmap.GetHeight(num, num2); } public static ConfigEntry BindEx(this ConfigFile config, string section, T defaultValue, string description, AcceptableValueBase? acceptableValues = null, ModConfigBase.Deprecated? deprecated = null, [CallerMemberName] string key = null) { return ModConfigBase.BindEx(config, section, defaultValue, description, acceptableValues, deprecated, key); } public static bool IsDeprecated(this ConfigEntryBase entry) { return ModConfigBase.IsDeprecated(entry); } [Conditional("DEBUG")] public static void AssertIs(this ExtendedZDO zdo) where T : MonoBehaviour { } [Conditional("DEBUG")] public static void AssertIsAll(this ExtendedZDO zdo) where T1 : MonoBehaviour where T2 : MonoBehaviour { } public static void InsertSorted(this List list, T item) where T : IComparable { int num = list.BinarySearch(item); if (num < 0) { num = ~num; } list.Insert(num, item); } public static ListEnumerable AsEnumerable(this IReadOnlyList list) { return new ListEnumerable(list); } public static ListEnumerable AsEnumerable(this IList list) { return new ListEnumerable((IReadOnlyList)list); } public static IEnumerable AsBoxedEnumerable(this IReadOnlyList list) { return Enumerable.AsEnumerable(list); } } internal readonly record struct GlobalKey(string Key) { public GlobalKey(string Key) { this.Key = Key; } public GlobalKey(GlobalKeys key) : this(((object)(GlobalKeys)(ref key)).ToString().ToLower()) { } public static implicit operator string(in GlobalKey key) { return key.Key; } } internal interface IPeerInfo { long Owner { get; } ExtendedZDO PlayerZDO { get; } long PlayerID { get; } string PlayerName { get; } bool IsAdmin { get; } float ConnectionQuality { get; } ItemDrop? LastUsedItem { get; } PlayerProcessor.BuildModifiers BuildModifiers { get; } PlayerProcessor.LevelGroundModes LevelGroundMode { get; } IReadOnlyDictionary GlobalKeyModifications { get; } float GetEstimatedSkillLevel(SkillType skillType); void AddGlobalKeyModification(GlobalKey key, bool add); void RemoveGlobalKeyModification(GlobalKey key); } internal sealed class Logger : ILogSource, IDisposable { private readonly ManualLogSource _logger = Logger.CreateLogSource(sourceName); public string SourceName => _logger.SourceName; public event EventHandler LogEvent { add { _logger.LogEvent += value; } remove { _logger.LogEvent -= value; } } public Logger(string sourceName) { } public void Dispose() { _logger.Dispose(); } public void Log(LogLevel level, object data) { //IL_003d: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) double realtimeSinceStartupAsDouble = Time.realtimeSinceStartupAsDouble; TimeSpan timeSpan = TimeSpan.FromSeconds(realtimeSinceStartupAsDouble); if (realtimeSinceStartupAsDouble < 86400.0) { _logger.Log(level, (object)$"[{timeSpan:hh\\:mm\\:ss\\.fff}] {data}"); } else { _logger.Log(level, (object)$"[{timeSpan:d\\.hh\\:mm\\:ss\\.fff}] {data}"); } } public void LogFatal(object data) { Log((LogLevel)1, data); } public void LogError(object data) { Log((LogLevel)2, data); } public void LogWarning(object data) { Log((LogLevel)4, data); } public void LogMessage(object data) { Log((LogLevel)8, data); } public void LogInfo(object data) { Log((LogLevel)16, data); } public void LogDebug(object data) { Log((LogLevel)32, data); } [Conditional("DEBUG")] public void DevLog(string text, LogLevel logLevel = 4) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) Log(logLevel, text); } } [BepInPlugin("argusmagnus.ServersideQoL", "ServersideQoL", "1.8.1")] public sealed class Main : BaseUnityPlugin { private record SectorInfo(List Peers, List ZDOs) { public int ZdoIndex { get; set; } public int InverseWeight { get; set; } } private sealed class PeersEnumerable : IEnumerable, IEnumerable { public struct Enumerator : IEnumerator, IEnumerator, IDisposable { private readonly PeersEnumerable _enumerable; private int _index; public Peer Current { get; private set; } readonly object IEnumerator.Current => Current; public Enumerator(PeersEnumerable enumerable) { _enumerable = enumerable; _index = -2; Current = null; } public void Dispose() { Current = null; } [MethodImpl(MethodImplOptions.AggressiveInlining)] public bool MoveNext() { if (++_index < 0) { if (_enumerable._localPeer != null) { Current = Peer.Get(_enumerable._localPeer); return true; } _index++; } if (_index < _enumerable._peers.Count) { Current = Peer.Get(_enumerable._peers[_index]); return true; } Current = null; return false; } public void Reset() { _index = -2; } } private readonly ZNetPeer? _localPeer; private List _peers; public int Count => _peers.Count + ((_localPeer != null) ? 1 : 0); public PeersEnumerable(ZNetPeer? localPeer) { _localPeer = localPeer; _peers = new List(); base..ctor(); } public void Update() { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) if (_localPeer != null) { _localPeer.m_refPos = ZNet.instance.GetReferencePosition(); } _peers = ZNet.instance.GetPeers(); } [MethodImpl(MethodImplOptions.AggressiveInlining)] public Enumerator GetEnumerator() { return new Enumerator(this); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } IEnumerator IEnumerable.GetEnumerator() { return GetEnumerator(); } } private sealed class MyTerminal : Terminal { private sealed class MyConsoleEventArgs : ConsoleEventArgs { public MyConsoleEventArgs(string command, params string[] args) : base("", (Terminal)null) { int num = 0; string[] array = new string[1 + args.Length]; array[num] = command; num++; ReadOnlySpan readOnlySpan = new ReadOnlySpan(args); readOnlySpan.CopyTo(new Span(array).Slice(num, readOnlySpan.Length)); num += readOnlySpan.Length; base.Args = array; } } protected override Terminal m_terminalInstance { get { throw new NotImplementedException(); } } public static void ExecuteCommand(string command, params string[] args) { ConsoleCommand command2 = Terminal.commands[command]; ConsoleEvent action = command2.GetAction(); if (action != null) { action.Invoke((ConsoleEventArgs)(object)new MyConsoleEventArgs(command, args)); return; } ConsoleEventFailable actionFailable = command2.GetActionFailable(); if (actionFailable != null) { object obj = actionFailable.Invoke((ConsoleEventArgs)(object)new MyConsoleEventArgs(command, args)); if (obj is bool && (bool)obj) { return; } throw new Exception(obj.ToString()); } throw new ArgumentException("command"); } } private sealed class DummySocket : ISocket { public ISocket Accept() { throw new NotImplementedException(); } public void Close() { } public void Dispose() { } public bool Flush() { throw new NotImplementedException(); } public void GetAndResetStats(out int totalSent, out int totalRecv) { throw new NotImplementedException(); } public void GetConnectionQuality(out float localQuality, out float remoteQuality, out int ping, out float outByteSec, out float inByteSec) { throw new NotImplementedException(); } public int GetCurrentSendRate() { throw new NotImplementedException(); } public string GetEndPointString() { throw new NotImplementedException(); } public string GetHostName() { return ""; } public int GetHostPort() { throw new NotImplementedException(); } public int GetSendQueueSize() { throw new NotImplementedException(); } public bool GotNewData() { throw new NotImplementedException(); } public bool IsConnected() { return true; } public bool IsHost() { throw new NotImplementedException(); } public ZPackage Recv() { throw new NotImplementedException(); } public void Send(ZPackage pkg) { throw new NotImplementedException(); } public void VersionMatch() { throw new NotImplementedException(); } } [CompilerGenerated] private sealed class <g__CallExecute|31_0>d : IEnumerator, IEnumerator, IDisposable { private int <>1__state; private YieldInstruction? <>2__current; public Main <>4__this; private PeersEnumerable 5__2; YieldInstruction IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public <g__CallExecute|31_0>d(int <>1__state) { this.<>1__state = <>1__state; } [DebuggerHidden] void IDisposable.Dispose() { 5__2 = null; <>1__state = -2; } private bool MoveNext() { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Expected O, but got Unknown //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00b0: Expected O, but got Unknown //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_0122: Expected O, but got Unknown //IL_013f: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_014f: Unknown result type (might be due to invalid IL or missing references) //IL_0155: 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_015f: Unknown result type (might be due to invalid IL or missing references) //IL_0167: Expected O, but got Unknown //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Expected O, but got Unknown //IL_00e3: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Expected O, but got Unknown int num = <>1__state; Main main = <>4__this; ZNetPeer localPeer; switch (num) { default: return false; case 0: <>1__state = -1; goto IL_005b; case 1: <>1__state = -1; goto IL_005b; case 2: <>1__state = -1; goto IL_005b; case 3: <>1__state = -1; goto IL_00c0; case 4: <>1__state = -1; goto IL_005b; case 5: <>1__state = -1; goto IL_0132; case 6: { <>1__state = -1; if (ZNet.instance != null) { int num2 = (ZNet.instance.IsDedicated() ? 10 : 30); int num3 = ((Application.targetFrameRate < 0) ? (2 * num2) : Application.targetFrameRate); double num4 = 1.0 / (double)num2; double num5 = 1.0 / (double)Time.unscaledDeltaTime; if ((double)Time.unscaledDeltaTime > num4) { if (main.Config.General.DiagnosticLogs.Value) { main.Logger.LogInfo($"No time budget available, actual FPS: {num5}, min FPS: {num2}, target FPS: {num3}"); } break; } double num6 = Math.Min(1.0, (num5 - (double)num2) / (double)(num3 - num2)); double timeBudgetSeconds = (num4 - (double)Time.unscaledDeltaTime) * num6; try { main.Execute(5__2, timeBudgetSeconds); } catch (OperationCanceledException) { return false; } catch (Exception data) { main.Logger.LogError(data); return false; } break; } 5__2 = null; goto IL_005b; } IL_005b: if (ZNet.instance == null) { <>2__current = (YieldInstruction?)new WaitForSeconds(0.2f); <>1__state = 1; return true; } if (!ZNet.instance.IsServer()) { main.Logger.LogWarning("Mod should only be installed on the host"); <>2__current = (YieldInstruction?)new WaitForSeconds(5f); <>1__state = 2; return true; } goto IL_00c0; IL_0167: 5__2 = new PeersEnumerable(localPeer); break; IL_0132: if (Player.m_localPlayer == null) { <>2__current = (YieldInstruction?)new WaitForSeconds(0.2f); <>1__state = 5; return true; } localPeer = new ZNetPeer((ISocket)(object)new DummySocket(), true) { m_uid = ZDOMan.GetSessionID(), m_characterID = ((Character)Player.m_localPlayer).GetZDOID(), m_server = true }; goto IL_0167; IL_00c0: if (ZDOMan.instance == null || ZNetScene.instance == null || ZNet.World == null) { <>2__current = (YieldInstruction?)new WaitForSeconds(0.2f); <>1__state = 3; return true; } if (!main.Initialize()) { <>2__current = (YieldInstruction?)new WaitForSeconds(5f); <>1__state = 4; return true; } localPeer = null; if (!ZNet.instance.IsDedicated()) { goto IL_0132; } goto IL_0167; } <>2__current = null; <>1__state = 6; return true; } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } } internal const string PluginName = "ServersideQoL"; internal const string PluginGuid = "argusmagnus.ServersideQoL"; private ModConfig? _mainConfig; private ModConfig? _worldConfig; private ulong _executeCounter; private uint _unfinishedProcessingInRow; private readonly Stack _sectorInfoPool = new Stack(); private Dictionary _playerSectors = new Dictionary(); private Dictionary _playerSectorsOld = new Dictionary(); private List<(Processor, double)>? _processingTimes; private readonly List _unregister = new List(); private bool _configChanged = true; internal const string DummyConfigSection = "Z - Dummy"; private const string PluginVersion = "1.8.1"; internal const string PluginInformationalVersion = "1.8.1-beta.0.30"; internal static int PluginGuidHash { get; } = StringExtensionMethods.GetStableHashCode("argusmagnus.ServersideQoL", true); internal static Main Instance { get; private set; } = null; internal static Harmony HarmonyInstance { get; } = new Harmony("argusmagnus.ServersideQoL"); internal Logger Logger { get; } = new Logger("ServersideQoL"); internal ModConfig Config => _worldConfig ?? _mainConfig ?? (_mainConfig = new ModConfig(((BaseUnityPlugin)this).Config)); internal DateTimeOffset BuildTimestamp { get; } = new DateTimeOffset(639144194935416681L, default(TimeSpan)); public Main() { Instance = this; } private void Awake() { Logger.LogWarning(string.Format("You are running a pre-release version: {0} ({1})", "1.8.1-beta.0.30", BuildTimestamp.LocalDateTime)); HarmonyInstance.PatchAll(Assembly.GetExecutingAssembly()); } private void Start() { ((MonoBehaviour)this).StartCoroutine((IEnumerator)CallExecute()); [IteratorStateMachine(typeof(<g__CallExecute|31_0>d))] IEnumerator CallExecute() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new <g__CallExecute|31_0>d(0) { <>4__this = this }; } } private bool Initialize() { //IL_017b: Unknown result type (might be due to invalid IL or missing references) //IL_0185: Expected O, but got Unknown //IL_0180: Unknown result type (might be due to invalid IL or missing references) //IL_018a: Expected O, but got Unknown //IL_02f3: Unknown result type (might be due to invalid IL or missing references) //IL_02f8: Unknown result type (might be due to invalid IL or missing references) //IL_0314: 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_0370: Unknown result type (might be due to invalid IL or missing references) //IL_0374: Invalid comparison between Unknown and I4 //IL_03db: Unknown result type (might be due to invalid IL or missing references) //IL_03df: Invalid comparison between Unknown and I4 //IL_0389: Unknown result type (might be due to invalid IL or missing references) //IL_0393: Unknown result type (might be due to invalid IL or missing references) //IL_03f4: Unknown result type (might be due to invalid IL or missing references) //IL_03fe: Unknown result type (might be due to invalid IL or missing references) if ((object)_mainConfig != null) { _mainConfig.ConfigFile.SettingChanged -= OnConfigChanged; } if ((object)_worldConfig != null) { _worldConfig.ConfigFile.SettingChanged -= OnConfigChanged; } _worldConfig = null; _executeCounter = 0uL; if (Config.General.ConfigPerWorld.Value) { string saveDirectory = ZNet.World.GetSaveDirectory((FileSource)2); saveDirectory = Path.Combine(saveDirectory, "ServersideQoL.cfg"); if (!File.Exists(saveDirectory) && File.Exists(((BaseUnityPlugin)this).Config.ConfigFilePath)) { File.Copy(((BaseUnityPlugin)this).Config.ConfigFilePath, saveDirectory); } string path = Path.Combine(Path.GetDirectoryName(((BaseUnityPlugin)this).Config.ConfigFilePath), Path.GetFileNameWithoutExtension(((BaseUnityPlugin)this).Config.ConfigFilePath)); if (Directory.Exists(path)) { string text = Path.Combine(Path.GetDirectoryName(saveDirectory), Path.GetFileNameWithoutExtension(saveDirectory)); Directory.CreateDirectory(text); foreach (string item in Directory.EnumerateFiles(path)) { string text2 = Path.Combine(text, Path.GetFileName(item)); if (!File.Exists(text2)) { File.Copy(item, text2); } } } Logger.LogInfo("Using world config file"); _worldConfig = new ModConfig(new ConfigFile(saveDirectory, false, new BepInPlugin("argusmagnus.ServersideQoL", "ServersideQoL", "1.8.1"))); } Logger.LogInfo(FormattableString.Invariant($"Enabled: {Config.General.Enabled.Value}, DiagnosticLogs: {Config.General.DiagnosticLogs.Value}")); if (!Config.General.Enabled.Value) { return false; } if (Chainloader.PluginInfos.TryGetValue("org.bepinex.plugins.dedicatedserver", out var value)) { Logger.LogWarning("Many features are incompatible with " + value.Metadata.Name); } if (Config.General.DiagnosticLogs.Value) { Logger logger = Logger; string separator = Environment.NewLine + " "; List list = new List(); list.Add("Config:"); list.AddRange(((IEnumerable>)Config.ConfigFile).Select((KeyValuePair x) => FormattableString.Invariant($"[{x.Key.Section}].[{x.Key.Key}] = {x.Value.BoxedValue}"))); logger.LogInfo(string.Join(separator, list.ToArray())); } bool flag = false; bool flag2 = false; uint num = (uint)typeof(Version).GetField("c_networkVersion").GetValue(null); Item val = (Item)typeof(Version).GetField("c_ItemDataVersion").GetValue(null); World val2 = (World)typeof(Version).GetField("c_WorldVersion").GetValue(null); if (num != 37) { Logger.LogWarning(FormattableString.Invariant($"Unsupported network version: {num}, expected: {37u}")); flag = true; flag2 |= !Config.General.IgnoreNetworkVersionCheck.Value; } if ((int)val != 108) { Logger.LogWarning(FormattableString.Invariant($"Unsupported item data version: {val:D} [{val}], expected: {(object)(Item)108:D} [{(object)(Item)108}]")); flag = true; flag2 |= !Config.General.IgnoreItemDataVersionCheck.Value; } if ((int)val2 != 40) { Logger.LogWarning(FormattableString.Invariant($"Unsupported world version: {val2:D} [{val2}], expected: {(object)(World)40:D} [{(object)(World)40}]")); flag = true; flag2 |= !Config.General.IgnoreWorldVersionCheck.Value; } if (flag) { if (flag2) { Logger.LogError("Version checks failed. Mod execution is stopped"); return false; } Logger.LogWarning("Version checks failed, but you chose to ignore the checks (config). Continuing..."); } return true; } private void OnConfigChanged(object sender, SettingChangedEventArgs e) { _configChanged = true; if (Config.General.DiagnosticLogs.Value || e.ChangedSetting == Config.General.DiagnosticLogs) { Logger.LogInfo($"Config changed: [{e.ChangedSetting.Definition.Section}].[{e.ChangedSetting.Definition.Key}] = {e.ChangedSetting.BoxedValue}"); } if (e.ChangedSetting == Config.General.DiagnosticLogs && Config.General.DiagnosticLogs.Value) { Logger logger = Logger; string separator = Environment.NewLine + " "; List list = new List(); list.Add("Config:"); list.AddRange(((IEnumerable>)Config.ConfigFile).Select((KeyValuePair x) => FormattableString.Invariant($"[{x.Key.Section}].[{x.Key.Key}] = {x.Value.BoxedValue}"))); logger.LogInfo(string.Join(separator, list.ToArray())); } } private void Execute(PeersEnumerable peers, double timeBudgetSeconds) { //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_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_0217: 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_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_0164: 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_0243: 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_03ea: Unknown result type (might be due to invalid IL or missing references) //IL_03ef: Unknown result type (might be due to invalid IL or missing references) //IL_03f1: Unknown result type (might be due to invalid IL or missing references) //IL_0290: Unknown result type (might be due to invalid IL or missing references) //IL_04e7: Unknown result type (might be due to invalid IL or missing references) //IL_0401: 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_0422: Unknown result type (might be due to invalid IL or missing references) //IL_0466: Unknown result type (might be due to invalid IL or missing references) //IL_0433: Unknown result type (might be due to invalid IL or missing references) //IL_04c0: Unknown result type (might be due to invalid IL or missing references) //IL_05f9: 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_0633: Unknown result type (might be due to invalid IL or missing references) //IL_091c: Unknown result type (might be due to invalid IL or missing references) //IL_0937: Unknown result type (might be due to invalid IL or missing references) //IL_09b7: Unknown result type (might be due to invalid IL or missing references) //IL_09bb: Invalid comparison between Unknown and I4 //IL_09bd: Unknown result type (might be due to invalid IL or missing references) //IL_071f: Unknown result type (might be due to invalid IL or missing references) //IL_0aa8: Unknown result type (might be due to invalid IL or missing references) double realtimeSinceStartupAsDouble = Time.realtimeSinceStartupAsDouble; double num = realtimeSinceStartupAsDouble + timeBudgetSeconds; _executeCounter++; if (_configChanged) { _configChanged = false; if (Config.GlobalsKeys.SetGlobalKeysFromConfig.Value) { ZoneSystem.instance.ResetWorldKeys(); } if (Config.WorldModifiers.SetPresetFromConfig.Value) { try { MyTerminal.ExecuteCommand("setworldpreset", FormattableString.Invariant($"{Config.WorldModifiers.Preset.Value}")); } catch (Exception data) { Logger.LogError(data); } } if (Config.WorldModifiers.SetModifiersFromConfig.Value) { foreach (var (val, val2) in Config.WorldModifiers.Modifiers.Select>, (WorldModifiers, WorldModifierOption)>((KeyValuePair> x) => (x.Key, x.Value.Value))) { try { MyTerminal.ExecuteCommand("setworldmodifier", FormattableString.Invariant($"{val}"), FormattableString.Invariant($"{val2}")); } catch (Exception data2) { Logger.LogError(data2); } } } if (Config.GlobalsKeys.SetGlobalKeysFromConfig.Value) { foreach (KeyValuePair item in Config.GlobalsKeys.KeyConfigs.Where>((KeyValuePair x) => !object.Equals(x.Value.BoxedValue, x.Value.DefaultValue))) { item.Deconstruct(out var key, out var value); GlobalKeys val3 = key; ConfigEntryBase val4 = value; object boxedValue = val4.BoxedValue; if (boxedValue is bool) { if ((bool)boxedValue) { ZoneSystem.instance.SetGlobalKey(val3); } else { ZoneSystem.instance.RemoveGlobalKey(val3); } continue; } float num2; try { num2 = (float)Convert.ChangeType(val4.BoxedValue, typeof(float)); } catch (Exception data3) { Logger.LogError(data3); continue; } ZoneSystem.instance.SetGlobalKey(val3, num2); } } foreach (Processor item2 in Processor.DefaultProcessors.AsEnumerable()) { item2.Initialize(_executeCounter == 1); } if (_executeCounter == 1) { Config.ConfigFile.SettingChanged -= OnConfigChanged; Config.ConfigFile.SettingChanged += OnConfigChanged; return; } { foreach (ExtendedZDO @object in ZDOMan.instance.GetObjects()) { @object.ReregisterAllProcessors(); } return; } } peers.Update(); SharedProcessorState.CleanUp(peers); if (peers.Count == 0) { return; } Dictionary playerSectorsOld = _playerSectorsOld; Dictionary playerSectors = _playerSectors; _playerSectors = playerSectorsOld; _playerSectorsOld = playerSectors; int value2 = Config.General.ZonesAroundPlayers.Value; Vector2s key2 = default(Vector2s); foreach (Peer peer in peers) { Vector2s zone = ZoneSystem.GetZone(peer.m_refPos); for (int i = zone.x - value2; i <= zone.x + value2; i++) { for (int j = zone.y - value2; j <= zone.y + value2; j++) { ((Vector2s)(ref key2))..ctor(i, j); if (_playerSectorsOld.Remove(key2, out SectorInfo value3)) { _playerSectors.Add(key2, value3); value3.InverseWeight = 0; value3.Peers.Clear(); value3.Peers.Add(peer); continue; } if (_playerSectors.TryGetValue(key2, out value3)) { value3.Peers.Add(peer); continue; } if (_sectorInfoPool.TryPop(out value3)) { value3.Peers.Add(peer); } else { value3 = new SectorInfo(new List(1) { peer }, new List()); } _playerSectors.Add(key2, value3); } } } foreach (SectorInfo value4 in _playerSectorsOld.Values) { value4.ZdoIndex = 0; value4.InverseWeight = 0; value4.Peers.Clear(); value4.ZDOs.Clear(); _sectorInfoPool.Push(value4); } _playerSectorsOld.Clear(); Dictionary playerSectors2 = _playerSectors; foreach (Processor item3 in Processor.DefaultProcessors.AsEnumerable()) { item3.PreProcess(peers); } int num3 = 0; int num4 = 0; int num5 = 0; foreach (var (val6, sectorInfo2) in playerSectors2) { if (Time.realtimeSinceStartupAsDouble > num) { break; } num3++; if ((object)sectorInfo2 != null) { List zDOs = sectorInfo2.ZDOs; if (zDOs != null && zDOs.Count == 0) { ZDOMan.instance.FindSectorObjects(val6, 0, 0, sectorInfo2.ZDOs, (List)null); } } num5 += sectorInfo2.ZDOs.Count; while (sectorInfo2.ZdoIndex < sectorInfo2.ZDOs.Count && (num4 % 10 != 0 || !(Time.realtimeSinceStartupAsDouble >= num))) { num4++; ExtendedZDO extendedZDO2 = (ExtendedZDO)(object)sectorInfo2.ZDOs[sectorInfo2.ZdoIndex]; if (((ZDO)extendedZDO2).IsValid() && extendedZDO2.HasProcessors) { if (extendedZDO2.Processors.Count > 1) { Processor processor = null; foreach (Processor item4 in extendedZDO2.Processors.AsEnumerable()) { if (item4.ClaimExclusive(extendedZDO2)) { if (processor == null) { processor = item4; } else if (Config.General.DiagnosticLogs.Value) { Logger.LogError(FormattableString.Invariant($"ZDO {((ZDO)extendedZDO2).m_uid} claimed exclusive by {item4.GetType().Name} while already claimed by {processor.GetType().Name}")); } } } if (processor != null) { extendedZDO2.UnregisterAllExcept(processor); } } bool flag = false; bool flag2 = false; _unregister.Clear(); foreach (Processor item5 in extendedZDO2.Processors.AsEnumerable()) { if (extendedZDO2.CheckProcessorDataRevisionChanged(item5)) { if (item5.Process(extendedZDO2, sectorInfo2.Peers)) { extendedZDO2.UpdateProcessorDataRevision(item5); } if (flag = item5.DestroyZdo) { extendedZDO2.Destroy(); break; } if (item5.UnregisterZdoProcessor) { _unregister.Add(item5); } flag2 = flag2 || item5.RecreateZdo; } } if (!flag) { if (flag2) { extendedZDO2.Recreate(); } else if (_unregister.Count > 0) { extendedZDO2.UnregisterProcessors(_unregister); } } } sectorInfo2.ZdoIndex++; } if (sectorInfo2.ZdoIndex >= sectorInfo2.ZDOs.Count) { sectorInfo2.ZDOs.Clear(); sectorInfo2.ZdoIndex = 0; } } if (num3 < _playerSectors.Count || num4 < num5) { _unfinishedProcessingInRow++; } else { _unfinishedProcessingInRow = 0u; } if (!Config.General.DiagnosticLogs.Value) { return; } LogLevel val7 = (LogLevel)((_unfinishedProcessingInRow == 0) ? 32 : 16); double num6 = (Time.realtimeSinceStartupAsDouble - realtimeSinceStartupAsDouble) * 1000.0; Logger.Log(val7, FormattableString.Invariant(FormattableStringFactory.Create("{0} took {1:F2} ms (budget: {2:F2} ms) to process {3} of {4} ZDOs in {5} of {6} zones. Incomplete runs in row: {7}", "Execute", num6, timeBudgetSeconds * 1000.0, num4, num5, num3, _playerSectors.Count, _unfinishedProcessingInRow))); if (((int)val7 > 16 || (int)val7 == 0) ? true : false) { return; } (_processingTimes ?? (_processingTimes = new List<(Processor, double)>(Processor.DefaultProcessors.Count))).Clear(); foreach (Processor item6 in Processor.DefaultProcessors.AsEnumerable()) { double num7 = Math.Round(item6.ProcessingTimeSeconds * 1000.0, 2); if (!(num7 <= 0.0)) { _processingTimes.Add((item6, num7)); } } if (_processingTimes.Count != 0) { _processingTimes.Sort(((Processor, double) a, (Processor, double) b) => Math.Sign(b.Item2 - a.Item2)); Logger.Log(val7, FormattableString.Invariant(FormattableStringFactory.Create("Processing Time: {0}", string.Join(", ", _processingTimes.Select<(Processor, double), string>(((Processor, double) x) => FormattableString.Invariant($"{x.Item1.GetType().Name}: {x.Item2}ms")))))); } } } public enum MessageTypes { None, TopLeftNear, TopLeftFar, CenterNear, CenterFar, InWorld } internal record ModConfigBase(ConfigFile ConfigFile) { internal sealed class AcceptableEnum : AcceptableValueBase where T : unmanaged, Enum { [CompilerGenerated] private sealed class d__7 : IEnumerable, IEnumerable, IEnumerator, IEnumerator, IDisposable { private int <>1__state; private T <>2__current; private int <>l__initialThreadId; private HashSet 5__2; private T[] <>7__wrap2; private int <>7__wrap3; T IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public d__7(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { 5__2 = null; <>7__wrap2 = null; <>1__state = -2; } private bool MoveNext() { int num = <>1__state; if (num != 0) { if (num != 1) { return false; } <>1__state = -1; goto IL_007c; } <>1__state = -1; 5__2 = new HashSet(); <>7__wrap2 = (T[])Enum.GetValues(typeof(T)); <>7__wrap3 = 0; goto IL_008a; IL_007c: <>7__wrap3++; goto IL_008a; IL_008a: if (<>7__wrap3 < <>7__wrap2.Length) { T item = <>7__wrap2[<>7__wrap3]; if (5__2.Add(item)) { <>2__current = item; <>1__state = 1; return true; } goto IL_007c; } <>7__wrap2 = null; 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(); } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; return this; } return new d__7(0); } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)this).GetEnumerator(); } } private readonly T _default; public static AcceptableEnum Default { get; } = new AcceptableEnum(GetDefaultValues()); public IReadOnlyList AcceptableValues { get; } [IteratorStateMachine(typeof(AcceptableEnum<>.d__7))] private static IEnumerable GetDefaultValues() { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__7(-2); } public AcceptableEnum(IEnumerable values) : base(typeof(T)) { if (EnumUtils.IsBitSet()) { List list = new List(); list.AddRange(values.Where((T x) => x.ExactlyOneBitSet())); AcceptableValues = new <>z__ReadOnlyList(list); _default = default(T); return; } object obj = values as IReadOnlyList; if (obj == null) { List list2 = new List(); list2.AddRange(values); obj = new <>z__ReadOnlyList(list2); } AcceptableValues = (IReadOnlyList)obj; _default = AcceptableValues.FirstOrDefault(); } public override object Clamp(object value) { if (value is T) { T e = (T)value; if (EnumUtils.IsBitSet()) { ulong val = e.ToUInt64(); ulong num = 0uL; foreach (ulong item in from x in AcceptableValues select x.ToUInt64() into x where (val & x) == x select x) { num |= item; } return EnumUtils.ToEnum(num); } if (!AcceptableValues.Any((T x) => x.Equals(e))) { return _default; } return e; } return _default; } public override bool IsValid(object value) { return object.Equals(value, ((AcceptableValueBase)this).Clamp(value)); } public override string ToDescriptionString() { if (EnumUtils.IsBitSet()) { return FormattableString.Invariant(FormattableStringFactory.Create("# Acceptable values: {0} or combination of {1}", _default, string.Join(", ", AcceptableValues.Where((T x) => !x.Equals(_default))))); } return FormattableString.Invariant(FormattableStringFactory.Create("# Acceptable values: {0}", string.Join(", ", AcceptableValues))); } } private sealed class AcceptableFormatString : AcceptableValueBase { [CompilerGenerated] private object[] P; public AcceptableFormatString(object[] testArgs) { P = testArgs; ((AcceptableValueBase)this)..ctor(typeof(string)); } public override bool IsValid(object value) { if (!(value is string format)) { return false; } try { string.Format(format, P); } catch (FormatException) { return false; } return true; } public override object Clamp(object value) { return value; } public override string ToDescriptionString() { return FormattableString.Invariant(FormattableStringFactory.Create("# Acceptable values: .NET Format strings for {0} arguments ({1}): https://learn.microsoft.com/en-us/dotnet/fundamentals/runtime-libraries/system-string-format#get-started-with-the-stringformat-method", P.Length, string.Join(", ", P.Select((object x) => x.GetType().Name)))); } } public sealed class AdminsConfig { public ConfigEntry ToggleDisableRainDamageEmote { get; } public ConfigEntry ToggleDisableSupportRequirements { get; } public ConfigEntry ToggleMakeIndestructible { get; } public ConfigEntry ToggleNoWorkbench { get; } public ConfigEntry ToggleDungeonBuild { get; } public ConfigEntry ToggleNoBuildCost { get; } public ConfigEntry ToggleAllPiecesUnlocked { get; } public ConfigEntry CycleLevelGroundMode { get; } public AdminsConfig(ConfigFile cfg, string section) { string description = $"Emote admins can use to toggle disabling rain damage for newly built pieces.\r\n{(object)(Emotes)(-1)} to disable this feature, {(object)(Emotes)(-2)} to use any emote as trigger.\r\nIf you use emotes exclusively for this feature, it is recommended to set the value to {(object)(Emotes)(-2)} as it is more reliably detected than specific emotes, especially on bad connection/with crossplay."; List list = new List(); list.Add((Emotes)(-1)); list.Add((Emotes)(-2)); list.AddRange(Enum.GetValues(typeof(Emotes)).Cast()); ToggleDisableRainDamageEmote = cfg.BindEx(section, (Emotes)(-1), description, (AcceptableValueBase?)(object)new AcceptableEnum(new <>z__ReadOnlyList(list)), null, "ToggleDisableRainDamageEmote"); string description2 = $"Emote admins can use to toggle disabling support requirements for newly built pieces.\r\n{(object)(Emotes)(-1)} to disable this feature, {(object)(Emotes)(-2)} to use any emote as trigger.\r\nIf you use emotes exclusively for this feature, it is recommended to set the value to {(object)(Emotes)(-2)} as it is more reliably detected than specific emotes, especially on bad connection/with crossplay."; list = new List(); list.Add((Emotes)(-1)); list.Add((Emotes)(-2)); list.AddRange(Enum.GetValues(typeof(Emotes)).Cast()); ToggleDisableSupportRequirements = cfg.BindEx(section, (Emotes)(-1), description2, (AcceptableValueBase?)(object)new AcceptableEnum(new <>z__ReadOnlyList(list)), null, "ToggleDisableSupportRequirements"); string description3 = $"Emote admins can use to toggle making newly built pieces indestructible.\r\n{(object)(Emotes)(-1)} to disable this feature, {(object)(Emotes)(-2)} to use any emote as trigger.\r\nIf you use emotes exclusively for this feature, it is recommended to set the value to {(object)(Emotes)(-2)} as it is more reliably detected than specific emotes, especially on bad connection/with crossplay."; list = new List(); list.Add((Emotes)(-1)); list.Add((Emotes)(-2)); list.AddRange(Enum.GetValues(typeof(Emotes)).Cast()); ToggleMakeIndestructible = cfg.BindEx(section, (Emotes)(-1), description3, (AcceptableValueBase?)(object)new AcceptableEnum(new <>z__ReadOnlyList(list)), null, "ToggleMakeIndestructible"); string description4 = $"Emote admins can use to toggle the workbench requirement for building.\r\n{(object)(Emotes)(-1)} to disable this feature, {(object)(Emotes)(-2)} to use any emote as trigger.\r\nIf you use emotes exclusively for this feature, it is recommended to set the value to {(object)(Emotes)(-2)} as it is more reliably detected than specific emotes, especially on bad connection/with crossplay."; list = new List(); list.Add((Emotes)(-1)); list.Add((Emotes)(-2)); list.AddRange(Enum.GetValues(typeof(Emotes)).Cast()); ToggleNoWorkbench = cfg.BindEx(section, (Emotes)(-1), description4, (AcceptableValueBase?)(object)new AcceptableEnum(new <>z__ReadOnlyList(list)), null, "ToggleNoWorkbench"); string description5 = $"Emote admins can use to toggle building in dungeons.\r\n{(object)(Emotes)(-1)} to disable this feature, {(object)(Emotes)(-2)} to use any emote as trigger.\r\nIf you use emotes exclusively for this feature, it is recommended to set the value to {(object)(Emotes)(-2)} as it is more reliably detected than specific emotes, especially on bad connection/with crossplay."; list = new List(); list.Add((Emotes)(-1)); list.Add((Emotes)(-2)); list.AddRange(Enum.GetValues(typeof(Emotes)).Cast()); ToggleDungeonBuild = cfg.BindEx(section, (Emotes)(-1), description5, (AcceptableValueBase?)(object)new AcceptableEnum(new <>z__ReadOnlyList(list)), null, "ToggleDungeonBuild"); string description6 = $"Emote admins can use to toggle no build cost.\r\n{(object)(Emotes)(-1)} to disable this feature, {(object)(Emotes)(-2)} to use any emote as trigger.\r\nIf you use emotes exclusively for this feature, it is recommended to set the value to {(object)(Emotes)(-2)} as it is more reliably detected than specific emotes, especially on bad connection/with crossplay."; list = new List(); list.Add((Emotes)(-1)); list.Add((Emotes)(-2)); list.AddRange(Enum.GetValues(typeof(Emotes)).Cast()); ToggleNoBuildCost = cfg.BindEx(section, (Emotes)(-1), description6, (AcceptableValueBase?)(object)new AcceptableEnum(new <>z__ReadOnlyList(list)), null, "ToggleNoBuildCost"); string description7 = $"Emote admins can use to toggle unlocking all building pieces.\r\n{(object)(Emotes)(-1)} to disable this feature, {(object)(Emotes)(-2)} to use any emote as trigger.\r\nIf you use emotes exclusively for this feature, it is recommended to set the value to {(object)(Emotes)(-2)} as it is more reliably detected than specific emotes, especially on bad connection/with crossplay."; list = new List(); list.Add((Emotes)(-1)); list.Add((Emotes)(-2)); list.AddRange(Enum.GetValues(typeof(Emotes)).Cast()); ToggleAllPiecesUnlocked = cfg.BindEx(section, (Emotes)(-1), description7, (AcceptableValueBase?)(object)new AcceptableEnum(new <>z__ReadOnlyList(list)), null, "ToggleAllPiecesUnlocked"); string description8 = $"Emote admins can use to cycle between different modes when using the Hoe's \"Level Ground\" option.\r\n{(object)(Emotes)(-1)} to disable this feature, {(object)(Emotes)(-2)} to use any emote as trigger.\r\nIf you use emotes exclusively for this feature, it is recommended to set the value to {(object)(Emotes)(-2)} as it is more reliably detected than specific emotes, especially on bad connection/with crossplay."; list = new List(); list.Add((Emotes)(-1)); list.Add((Emotes)(-2)); list.AddRange(Enum.GetValues(typeof(Emotes)).Cast()); CycleLevelGroundMode = cfg.BindEx(section, (Emotes)(-1), description8, (AcceptableValueBase?)(object)new AcceptableEnum(new <>z__ReadOnlyList(list)), null, "CycleLevelGroundMode"); base..ctor(); } } public sealed class AdvancedConfig { public sealed class TamesConfig { public sealed record TeleportFollowPositioningConfig(float MinDistXZ, float MaxDistXZ, float MinOffsetY, float MaxOffsetY, float HalfArcXZ) { private TeleportFollowPositioningConfig() : this(0f, 0f, 0f, 0f, 0f) { } } [CompilerGenerated] private IReadOnlyList k__BackingField; [CompilerGenerated] private IReadOnlyList k__BackingField; public TeleportFollowPositioningConfig TeleportFollowPositioning { get; init; } = new TeleportFollowPositioningConfig(2f, 4f, 0f, 1f, 45f); private Dictionary TeleportFollow { get; init; } = new Dictionary(); [YamlIgnore] public IReadOnlyList TeleportFollowExcluded { get { IReadOnlyList readOnlyList = k__BackingField; if (readOnlyList == null) { List list = new List(); list.AddRange(from x in TeleportFollow where !x.Value select StringExtensionMethods.GetStableHashCode(x.Key, true)); readOnlyList = (k__BackingField = new <>z__ReadOnlyList(list)); } return readOnlyList; } } private Dictionary TakeIntoDungeon { get; init; } = new Dictionary(); [YamlIgnore] public IReadOnlyList TakeIntoDungeonExcluded { get { IReadOnlyList readOnlyList = k__BackingField; if (readOnlyList == null) { List list = new List(); list.AddRange(from x in TakeIntoDungeon where !x.Value select StringExtensionMethods.GetStableHashCode(x.Key, true)); readOnlyList = (k__BackingField = new <>z__ReadOnlyList(list)); } return readOnlyList; } } public TamesConfig() { foreach (GameObject prefab in ZNetScene.instance.m_prefabs) { if (prefab.GetComponent() != null && prefab.GetComponent() != null) { TeleportFollow.Add(((Object)prefab).name, value: true); TakeIntoDungeon.Add(((Object)prefab).name, value: true); } } } } public sealed class HostileSummonsConfig { public sealed record FollowSummonerConfig(float MoveInterval, float MaxDistance) { private FollowSummonerConfig() : this(0f, 0f) { } } public FollowSummonerConfig FollowSummoners { get; init; } = new FollowSummonerConfig(4f, 20f); } public sealed class ContainerConfig { public sealed record ChestSignOffset(float Left, float Right, float Front, float Back, float Top) { private ChestSignOffset() : this(float.NaN, float.NaN, float.NaN, float.NaN, float.NaN) { } } [CompilerGenerated] private IReadOnlyDictionary k__BackingField; [YamlMember(Alias = "ChestSignOffsets")] private Dictionary ChestSignOffsetsYaml { get; init; } = new Dictionary { ["piece_chest_wood"] = new ChestSignOffset(0.8f, 0.8f, 0.4f, 0.4f, 0.8f), ["piece_chest"] = new ChestSignOffset(0.85f, 0.85f, 0.5f, 0.5f, 1.1f), ["piece_chest_blackmetal"] = new ChestSignOffset(0.95f, 0.95f, 0.7f, 0.7f, 0.95f), ["piece_chest_barrel"] = new ChestSignOffset(0.4f, 0.4f, 0.4f, 0.4f, 0.9f), ["incinerator"] = new ChestSignOffset(float.NaN, float.NaN, 0.1f, float.NaN, 3f) }; [YamlIgnore] public IReadOnlyDictionary ChestSignOffsets => k__BackingField ?? (k__BackingField = ChestSignOffsetsYaml.ToDictionary, int, ChestSignOffset>((KeyValuePair x) => StringExtensionMethods.GetStableHashCode(x.Key, true), (KeyValuePair x) => x.Value)); } public sealed class PlayersConfig { public sealed record BackpackOnDeathDropTombStoneConfig(float VerticalOffset, float AutoCollectDistance) { private BackpackOnDeathDropTombStoneConfig() : this(0f, 0f) { } } public sealed record BackpackOnDeathDropItemsConfig(float ScatterRadius, float VerticalOffset, bool PreventAutoDestroy, bool PreventAutoPickup) { private BackpackOnDeathDropItemsConfig() : this(0f, 0f, PreventAutoDestroy: false, PreventAutoPickup: false) { } } public BackpackOnDeathDropTombStoneConfig BackpackOnDeathDropTombStone { get; init; } = new BackpackOnDeathDropTombStoneConfig(2f, 2f); public BackpackOnDeathDropItemsConfig BackpackOnDeathDropItems { get; init; } = new BackpackOnDeathDropItemsConfig(2f, 1f, PreventAutoDestroy: true, PreventAutoPickup: false); } public sealed class AdminsConfig { public float ResetTerrainRadius { get; init; } = 3f; } public TamesConfig Tames { get; init; } = new TamesConfig(); public HostileSummonsConfig HostileSummons { get; init; } = new HostileSummonsConfig(); public ContainerConfig Containers { get; init; } = new ContainerConfig(); public PlayersConfig Players { get; init; } = new PlayersConfig(); public AdminsConfig Admins { get; init; } = new AdminsConfig(); } private sealed class MyTypeInspector : TypeInspectorSkeleton { [CompilerGenerated] private sealed class d__4 : IEnumerable, IEnumerable, IEnumerator, IEnumerator, IDisposable { private int <>1__state; private IPropertyDescriptor <>2__current; private int <>l__initialThreadId; public MyTypeInspector <>4__this; private Type type; public Type <>3__type; private object container; public object <>3__container; private IEnumerator <>7__wrap1; IPropertyDescriptor IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public d__4(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { int num = <>1__state; if (num == -3 || num == 1) { try { } finally { <>m__Finally1(); } } <>7__wrap1 = null; <>1__state = -2; } private bool MoveNext() { try { int num = <>1__state; MyTypeInspector myTypeInspector = <>4__this; switch (num) { default: return false; case 0: <>1__state = -1; <>7__wrap1 = myTypeInspector._inner.GetProperties(type, container).GetEnumerator(); <>1__state = -3; break; case 1: <>1__state = -3; break; } while (<>7__wrap1.MoveNext()) { IPropertyDescriptor current = <>7__wrap1.Current; if (!(current.Type == typeof(Type)) || !(current.Name == "EqualityContract")) { <>2__current = current; <>1__state = 1; 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] IEnumerator IEnumerable.GetEnumerator() { d__4 d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; d__ = this; } else { d__ = new d__4(0) { <>4__this = <>4__this }; } d__.type = <>3__type; d__.container = <>3__container; return d__; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)this).GetEnumerator(); } } private readonly ITypeInspector _inner; public MyTypeInspector(ITypeInspector inner) { _inner = inner; ((TypeInspectorSkeleton)this)..ctor(); } public override string GetEnumName(Type enumType, string name) { return _inner.GetEnumName(enumType, name); } public override string GetEnumValue(object enumValue) { return _inner.GetEnumValue(enumValue); } [IteratorStateMachine(typeof(d__4))] public override IEnumerable GetProperties(Type type, object? container) { //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__4(-2) { <>4__this = this, <>3__type = type, <>3__container = container }; } } public sealed class CartsConfig { public ConfigEntry ContentMassMultiplier { get; } = cfg.BindEx(section, 1f, "Multiplier for a carts content weight. E.g. set to 0 to ignore a cart's content weight", (AcceptableValueBase?)(object)new AcceptableValueRange(0f, float.PositiveInfinity), null, "ContentMassMultiplier"); public ConfigEntry DeconstructWithHammer { get; } = cfg.BindEx(section, defaultValue: false, "If enabled, carts can be deconstructed with the build hammer", null, null, "DeconstructWithHammer"); public CartsConfig(ConfigFile cfg, string section) { } } public sealed class ContainersConfig { public enum ObliteratorItemTeleporterOptions { Disabled = 0, Enabled = 1, EnabledAllItems = 2, [Obsolete] False = 0, [Obsolete] True = 1 } [Flags] public enum SignOptions { None = 0, Left = 1, Right = 2, Front = 4, Back = 8, TopLongitudinal = 0x10, TopLateral = 0x20 } private const string ChestSignItemNamesFileName = "ChestSignItemNames.yml"; private const string DefaultPlaceholderString = "•"; public ConfigEntry AutoSort { get; } public ConfigEntry SortedMessageType { get; } public ConfigEntry AutoPickup { get; } public ConfigEntry AutoPickupRange { get; } public ConfigEntry AutoPickupMaxRange { get; } public ConfigEntry AutoPickupMinPlayerDistance { get; } public ConfigEntry AutoPickupExcludeFodder { get; } public ConfigEntry AutoPickupRequestOwnership { get; } public ConfigEntry PickedUpMessageType { get; } public ConfigEntry ChestSignsDefaultText { get; } public ConfigEntry ChestSignsContentListPlaceholder { get; } public ConfigEntry ChestSignsContentListMaxCount { get; } public ConfigEntry ChestSignsContentListSeparator { get; } public ConfigEntry ChestSignsContentListNameRest { get; } public ConfigEntry ChestSignsContentListEntryFormat { get; } public ConfigEntry WoodChestSigns { get; } public ConfigEntry ReinforcedChestSigns { get; } public ConfigEntry BlackmetalChestSigns { get; } public ConfigEntry BarrelSigns { get; } public ConfigEntry ObliteratorSigns { get; } public ConfigEntry ObliteratorItemTeleporter { get; } public ConfigEntry ObliteratorItemTeleporterMessageType { get; } public IReadOnlyDictionary> ContainerSizes { get; } public IReadOnlyDictionary ItemNames { get; } public ContainersConfig(ConfigFile cfg, string section) { ConfigFile cfg2 = cfg; string section2 = section; AutoSort = cfg2.BindEx(section2, defaultValue: false, "True to auto sort container inventories", null, null, "AutoSort"); SortedMessageType = cfg2.BindEx(section2, MessageTypes.None, "Type of message to show when a container was sorted", (AcceptableValueBase?)(object)AcceptableEnum.Default, null, "SortedMessageType"); AutoPickup = cfg2.BindEx(section2, defaultValue: false, "True to automatically put dropped items into containers if they already contain said item", null, null, "AutoPickup"); AutoPickupRange = cfg2.BindEx(section2, 64f, "Required proximity of a container to a dropped item to be considered as auto pickup target. Can be overridden per chest by putting '\ud83e\uddf2' on a chest sign", null, null, "AutoPickupRange"); AutoPickupMaxRange = cfg2.BindEx(section2, 64, "Max auto pickup range players can set per chest (by putting '\ud83e\uddf2' on a chest sign)", null, null, "AutoPickupMaxRange"); AutoPickupMinPlayerDistance = cfg2.BindEx(section2, 4f, "Min distance all player must have to a dropped item for it to be picked up", null, null, "AutoPickupMinPlayerDistance"); AutoPickupExcludeFodder = cfg2.BindEx(section2, defaultValue: true, "True to exclude food items for tames when tames are within search range", null, null, "AutoPickupExcludeFodder"); AutoPickupRequestOwnership = cfg2.BindEx(section2, defaultValue: true, "True to make the server request (and receive) ownership of dropped items from the clients before they are picked up. This will reduce the risk of data conflicts (e.g. item duplication) but will drastically decrease performance", null, null, "AutoPickupRequestOwnership"); PickedUpMessageType = cfg2.BindEx(section2, MessageTypes.None, "Type of message to show when a dropped item is added to a container", (AcceptableValueBase?)(object)AcceptableEnum.Default, null, "PickedUpMessageType"); ChestSignsDefaultText = cfg2.BindEx(section2, "•", "Default text for chest signs", null, null, "ChestSignsDefaultText"); ChestSignsContentListPlaceholder = cfg2.BindEx(section2, "•", "If this value is found in the text of a chest sign, it will be replaced by a list of contained items in that chest", null, null, "ChestSignsContentListPlaceholder"); ChestSignsContentListMaxCount = cfg2.BindEx(section2, 3, "Max number of entries to show in the content list on chest signs.", null, null, "ChestSignsContentListMaxCount"); ChestSignsContentListSeparator = cfg2.BindEx(section2, "
", "Separator to use for content lists on chest signs", null, null, "ChestSignsContentListSeparator"); ChestSignsContentListNameRest = cfg2.BindEx(section2, "Other", "Text to show for the entry summarizing the rest of the items", null, null, "ChestSignsContentListNameRest"); ChestSignsContentListEntryFormat = cfg2.BindEx(section2, "{0} {1}", "Format string for entries in the content list, the first argument is the name of the item, the second is the total number of per item. The item names can be configured further by editing ChestSignItemNames.yml", (AcceptableValueBase?)(object)new AcceptableFormatString(new object[2] { "Test", 0 }), null, "ChestSignsContentListEntryFormat"); WoodChestSigns = cfg2.BindEx(section2, SignOptions.None, "Options to automatically put signs on wood chests", (AcceptableValueBase?)(object)AcceptableEnum.Default, null, "WoodChestSigns"); ReinforcedChestSigns = cfg2.BindEx(section2, SignOptions.None, "Options to automatically put signs on reinforced chests", (AcceptableValueBase?)(object)AcceptableEnum.Default, null, "ReinforcedChestSigns"); BlackmetalChestSigns = cfg2.BindEx(section2, SignOptions.None, "Options to automatically put signs on blackmetal chests", (AcceptableValueBase?)(object)AcceptableEnum.Default, null, "BlackmetalChestSigns"); BarrelSigns = cfg2.BindEx(section2, SignOptions.None, "Options to automatically put signs on barrels", (AcceptableValueBase?)(object)AcceptableEnum.Default, null, "BarrelSigns"); ObliteratorSigns = cfg2.BindEx(section2, SignOptions.None, "Options to automatically put signs on obliterators", (AcceptableValueBase?)(object)new AcceptableEnum(new <>z__ReadOnlySingleElementList(SignOptions.Front)), null, "ObliteratorSigns"); ObliteratorItemTeleporter = cfg2.BindEx(section2, ObliteratorItemTeleporterOptions.Disabled, "Options to enable obliterators to teleport items instead of obliterating them when the lever is pulled. Requires 'ObliteratorSigns' and two obliterators with matching tags. The tag is set by putting '\ud83d\udd17' on the sign", (AcceptableValueBase?)(object)AcceptableEnum.Default, null, "ObliteratorItemTeleporter"); ObliteratorItemTeleporterMessageType = cfg2.BindEx(section2, MessageTypes.InWorld, "Type of message to show for obliterator item teleporters", (AcceptableValueBase?)(object)AcceptableEnum.Default, null, "ObliteratorItemTeleporterMessageType"); ContainerSizes = (from x in ZNetScene.instance.m_prefabs where SharedProcessorState.PieceTablesByPiece.ContainsKey(((Object)x).name) select (((Object)x).name, x.GetComponentInChildren(), x.GetComponent()) into x where x.Container != null && x.Piece != null select x).ToDictionary<(string, Container, Piece), int, ConfigEntry>(((string Name, Container Container, Piece Piece) x) => StringExtensionMethods.GetStableHashCode(x.Name, true), ((string Name, Container Container, Piece Piece) x) => cfg2.Bind(section2, FormattableString.Invariant($"InventorySize_{x.Name}"), FormattableString.Invariant($"{x.Container.m_width}x{x.Container.m_height}"), FormattableString.Invariant($"Inventory size for '{Localization.instance.Localize(x.Piece.m_name)}'.\r\nIf you append '+' to the end (e.g. '{x.Container.m_width}x{x.Container.m_height}+'),\r\nthe inventory size will keep expanding as long as only one type of item is stored inside."))); ItemNames = ((Func>)delegate { //IL_005e: Unknown result type (might be due to invalid IL or missing references) //IL_0183: Unknown result type (might be due to invalid IL or missing references) string text = Path.Combine(Path.GetDirectoryName(cfg2.ConfigFilePath), Path.GetFileNameWithoutExtension(cfg2.ConfigFilePath)); string path = Path.Combine(text, "ChestSignItemNames.yml"); Dictionary dictionary; if (!File.Exists(path)) { dictionary = new Dictionary(ObjectDB.instance.m_items.Count); } else { try { using StreamReader streamReader = new StreamReader(File.OpenRead(path)); dictionary = new DeserializerBuilder().Build().Deserialize>((TextReader)streamReader); } catch (Exception arg) { Main.Instance.Logger.LogWarning(string.Format("{0}: {1}", "ChestSignItemNames.yml", arg)); dictionary = new Dictionary(ObjectDB.instance.m_items.Count); } } foreach (GameObject item in ObjectDB.instance.m_items) { ItemDrop component = item.GetComponent(); if (component != null) { ItemData itemData = component.m_itemData; if (itemData != null) { SharedData shared = itemData.m_shared; if (shared != null) { Sprite[] icons = shared.m_icons; if (icons != null && icons.Length > 0 && !dictionary.ContainsKey(((Object)component).name)) { dictionary.Add(((Object)component).name, Localization.instance.Localize(component.m_itemData.m_shared.m_name)); } } } } } if (!File.Exists(path)) { Directory.CreateDirectory(text); using StreamWriter streamWriter = new StreamWriter(File.OpenWrite(path)); WriteYamlHeader(streamWriter); new SerializerBuilder().Build().Serialize((TextWriter)streamWriter, (object)dictionary); } return dictionary; })(); base..ctor(); } } public sealed class CraftingStationsConfig { public sealed class StationCfg { public ConfigEntry? BuildRange { get; } = (station.m_areaMarker == null) ? null : cfg.Bind(section, prefix + "BuildRange", station.m_rangeBuild, "Build range of " + Localization.instance.Localize(station.m_name)); public ConfigEntry? ExtraBuildRangePerLevel { get; } = (station.m_areaMarker == null || !hasExtensions) ? null : cfg.Bind(section, prefix + "ExtraBuildRangePerLevel", station.m_extraRangePerLevel, "Additional build range per level of " + Localization.instance.Localize(station.m_name)); public ConfigEntry? MaxExtensionDistance { get; } = (!hasExtensions) ? null : cfg.Bind(section, prefix + "MaxExtensionDistance", float.NaN, FormattableString.Invariant($"Max distance an extension can have to the corresponding {Localization.instance.Localize(station.m_name)} to increase its level.\r\nIncreasing this range will only increase the range for already built extensions, you may need to temporarily place additional {Localization.instance.Localize(station.m_name)} to be able to place the extension.\r\n{float.NaN} to use the game's default range. ")); public StationCfg(ConfigFile cfg, string section, string prefix, CraftingStation station, bool hasExtensions) { } } public ConfigEntry OpenClosestContainerRange { get; } public IReadOnlyDictionary StationConfig { get; } public CraftingStationsConfig(ConfigFile cfg, string section) { ConfigFile cfg2 = cfg; string section2 = section; OpenClosestContainerRange = cfg2.BindEx(section2, 0f, "The closest container within this range is automatically opened when a player interacts with a crafting station.\r\nOpening a container this way refocuses the player's inventory as a side effect, so the player has to\r\nmanually switch to the crafting menu again to craft or repair items.", null, null, "OpenClosestContainerRange"); StationConfig = ((Func>)delegate { Dictionary dictionary = new Dictionary(); foreach (GameObject prefab in ZNetScene.instance.m_prefabs) { CraftingStation component = prefab.GetComponent(); if (component != null) { if (component.m_areaMarker != null && !dictionary.ContainsKey(component)) { dictionary.Add(component, value: false); } } else { StationExtension component2 = prefab.GetComponent(); if (component2 != null) { component = component2.m_craftingStation; dictionary[component] = true; } } } return dictionary.ToDictionary((KeyValuePair x) => x.Key, (KeyValuePair x) => new StationCfg(cfg2, section2, NormalizeName(((Object)x.Key).name), x.Key, x.Value)); })(); base..ctor(); } private static string NormalizeName(string name) { if (char.IsUpper(name[0])) { return name; } name = name.Replace("piece_", ""); object arg = char.ToUpperInvariant(name[0]); string text = name; return $"{arg}{text.Substring(1, text.Length - 1)}"; } } public sealed class CreaturesConfig { [Flags] public enum ShowHigherLevelAuraOptions { Never = 0, Wild = 1, Tamed = 2 } public enum RespawnOneTimeSpawnsConditions { Never, Always, AfterBossDefeated } public ConfigEntry ShowHigherLevelStars { get; } = cfg.BindEx(section, defaultValue: false, "True to show stars for higher level creatures (> 2 stars)", null, null, "ShowHigherLevelStars"); public ConfigEntry ShowHigherLevelAura { get; } = cfg.BindEx(section, ShowHigherLevelAuraOptions.Never, "Show an aura for higher level creatures (> 2 stars)", (AcceptableValueBase?)(object)AcceptableEnum.Default, null, "ShowHigherLevelAura"); public ConfigEntry MaxLevelIncrease { get; } = cfg.BindEx(section, 0, "Amount the max level of creatures is incremented throughout the world.\r\nThe level up chance increases with the max level.\r\nExample: if this value is set to 2, a creature will spawn with 4 stars with the same probability as it would spawn with 2 stars without this setting.", null, null, "MaxLevelIncrease"); public ConfigEntry MaxLevelIncreasePerDefeatedBoss { get; } = cfg.BindEx(section, 0, "Amount the max level of creatures is incremented per defeated boss.\r\nThe respective boss's biome and previous biomes are affected and the level up chance increases with the max level.\r\nExample: If this value is set to 1 and Eikthyr and the Elder is defeated, the max creature level in the Black Forest will be raised by 1 and in the Meadows by 2.", null, null, "MaxLevelIncreasePerDefeatedBoss"); public ConfigEntry TreatOceanAs { get; } = cfg.BindEx(section, (Biome)8, "Biome to treat the ocean as for the purpose of leveling up creatures", (AcceptableValueBase?)(object)new AcceptableEnum(AcceptableEnum.Default.AcceptableValues.Where((Biome x) => (int)x != 256)), null, "TreatOceanAs"); public ConfigEntry LevelUpBosses { get; } = cfg.BindEx(section, defaultValue: false, "True to also level up bosses", null, null, "LevelUpBosses"); public ConfigEntry RespawnOneTimeSpawnsCondition { get; } = cfg.BindEx(section, RespawnOneTimeSpawnsConditions.Never, "Condition for one-time spawns to respawn", null, null, "RespawnOneTimeSpawnsCondition"); public ConfigEntry RespawnOneTimeSpawnsAfter { get; } = cfg.BindEx(section, 240f, "Time after one-time spawns are respawned in minutes", null, null, "RespawnOneTimeSpawnsAfter"); public CreaturesConfig(ConfigFile cfg, string section) { } } public sealed record Deprecated(string Reason, Action AdjustConfig); public sealed class DoorsConfig { public ConfigEntry AutoCloseMinPlayerDistance { get; } = cfg.BindEx(section, float.NaN, FormattableString.Invariant($"Min distance all players must have to the door before it is closed. {float.NaN} to disable this feature"), null, null, "AutoCloseMinPlayerDistance"); public DoorsConfig(ConfigFile cfg, string section) { } } public sealed class FermentersConfig { public ConfigEntry FermentationDurationMultiplier { get; } = cfg.BindEx(section, 1f, "Multiply the time fermentation takes by this factor.", null, null, "FermentationDurationMultiplier"); public FermentersConfig(ConfigFile cfg, string section) { } } public sealed class FireplacesConfig { public enum IgnoreRainOptions { Never, Always, InsideShield } public ConfigEntry MakeToggleable { get; } = cfg.BindEx(section, defaultValue: false, "True to make all fireplaces (including torches, braziers, etc.) toggleable", null, null, "MakeToggleable"); public ConfigEntry InfiniteFuel { get; } = cfg.BindEx(section, defaultValue: false, "True to make all fireplaces have infinite fuel", null, null, "InfiniteFuel"); public ConfigEntry IgnoreRain { get; } = cfg.BindEx(section, IgnoreRainOptions.Never, "Options to make all fireplaces ignore rain", (AcceptableValueBase?)(object)AcceptableEnum.Default, null, "IgnoreRain"); public FireplacesConfig(ConfigFile cfg, string section) { } } public sealed class GeneralConfig { public ConfigEntry Enabled { get; } = cfg.BindEx(section, defaultValue: true, "Enables/disables the entire mod", null, null, "Enabled"); public ConfigEntry ConfigPerWorld { get; } = cfg.BindEx(section, defaultValue: false, "Use one config file per world. The file is saved next to the world file", null, null, "ConfigPerWorld"); public ConfigEntry InWorldConfigRoom { get; } = cfg.BindEx(section, defaultValue: false, "True to generate an in-world room which admins can enter to configure this mod by editing signs. A portal is placed at the start location", null, null, "InWorldConfigRoom"); public ConfigEntry FarMessageRange { get; } = cfg.BindEx(section, 64f, $"Max distance a player can have to a modified object to receive messages of type {MessageTypes.TopLeftFar} or {MessageTypes.CenterFar}", null, null, "FarMessageRange"); public ConfigEntry DiagnosticLogs { get; } = cfg.BindEx(section, defaultValue: false, "Enables/disables diagnostic logs", null, null, "DiagnosticLogs"); public ConfigEntry ZonesAroundPlayers { get; } = cfg.BindEx(section, ZoneSystem.instance.GetActiveArea(), "Zones to process around each player", null, null, "ZonesAroundPlayers"); public ConfigEntry MinPlayerDistance { get; } = cfg.BindEx(section, 4f, "Min distance all players must have to a ZDO for it to be modified", null, null, "MinPlayerDistance"); public ConfigEntry IgnoreGameVersionCheck { get; } = cfg.BindEx(section, defaultValue: true, "True to ignore the game version check. Turning this off may lead to the mod being run in an untested version and may lead to data loss/world corruption", null, null, "IgnoreGameVersionCheck"); public ConfigEntry IgnoreNetworkVersionCheck { get; } = cfg.BindEx(section, defaultValue: false, "True to ignore the network version check. Turning this off may lead to the mod being run in an untested version and may lead to data loss/world corruption", null, null, "IgnoreNetworkVersionCheck"); public ConfigEntry IgnoreItemDataVersionCheck { get; } = cfg.BindEx(section, defaultValue: false, "True to ignore the item data version check. Turning this off may lead to the mod being run in an untested version and may lead to data loss/world corruption", null, null, "IgnoreItemDataVersionCheck"); public ConfigEntry IgnoreWorldVersionCheck { get; } = cfg.BindEx(section, defaultValue: false, "True to ignore the world version check. Turning this off may lead to the mod being run in an untested version and may lead to data loss/world corruption", null, null, "IgnoreWorldVersionCheck"); public GeneralConfig(ConfigFile cfg, string section) { } } public sealed class GlobalsKeysConfig { public ConfigEntry SetGlobalKeysFromConfig { get; } = cfg.BindEx(section, defaultValue: false, "True to set global keys according to the following configuration entries", null, null, "SetGlobalKeysFromConfig"); public IReadOnlyDictionary KeyConfigs { get; } = ((GlobalKeyConfigFinder)(tmp ?? (tmp = new GlobalKeyConfigFinder()))).Get((GlobalKeys?)(GlobalKeys)31, cfg, section, FormattableString.Invariant(FormattableStringFactory.Create("Sets the value for the '{{0}}' global key. Enable '{0}' for this to have an effect", "SetGlobalKeysFromConfig"))); public ConfigEntry NoPortalsPreventsContruction { get; } = cfg.BindEx(section, defaultValue: true, FormattableString.Invariant($"True to change the effect of the '{(object)(GlobalKeys)27}' global key, to prevent the construction of new portals but leave existing portals functional"), null, null, "NoPortalsPreventsContruction"); public GlobalsKeysConfig(ConfigFile cfg, string section, object? tmp = null) { } } private sealed class GlobalKeyConfigFinder { private sealed record FieldInfoEx(FieldInfo Field, object? RestoreValueObject, double RestoreValue) { public double ComparisonValue { get; set; } = double.NaN; } public IReadOnlyDictionary Get(TKey? maxEclusive, ConfigFile cfg, string section, string descriptionFormat) where TKey : unmanaged, Enum { //IL_04aa: Unknown result type (might be due to invalid IL or missing references) //IL_04b1: Expected O, but got Unknown //IL_0514: Unknown result type (might be due to invalid IL or missing references) //IL_051b: Expected O, but got Unknown //IL_0493: Unknown result type (might be due to invalid IL or missing references) //IL_049a: Expected O, but got Unknown List<(double, double)> list = new List<(double, double)>(); List list2 = new List(); list2.Add(-3.4028234663852886E+38); list2.Add(-2147483648.0); list2.AddRange(Enumerable.Range(-100, 100).Select((Func)((int x) => x))); list2.Add(2147483647.0); list2.Add(3.4028234663852886E+38); IEnumerable enumerable = new <>z__ReadOnlyList(list2); Dictionary dictionary = new Dictionary(); List list3 = (from x in typeof(Game).GetFields(BindingFlags.Static | BindingFlags.Public) where !x.IsLiteral && !x.IsInitOnly select new FieldInfoEx(x, x.GetValue(null), TryGetAsDouble(x)) into x where !double.IsNaN(x.RestoreValue) select x).ToList(); MethodInfo methodInfo = null; try { Game.UpdateWorldRates(new HashSet(), dictionary); } catch (NullReferenceException) { } foreach (FieldInfoEx item in list3) { item.ComparisonValue = TryGetAsDouble(item.Field); } Dictionary dictionary2 = new Dictionary(); foreach (TKey value3 in Enum.GetValues(typeof(TKey))) { if (maxEclusive.HasValue && value3.ToInt64() >= maxEclusive.Value.ToInt64()) { continue; } string text = value3.ToString(); string key = text.ToLower(); FieldInfo fieldInfo = null; object value = null; double num = double.NaN; list.Clear(); foreach (double item2 in enumerable) { dictionary.Clear(); dictionary.Add(key, FormattableString.Invariant($"{item2}")); try { Game.UpdateWorldRates(new HashSet(), dictionary); } catch (NullReferenceException) { } double num2 = double.NaN; if ((object)fieldInfo == null) { int index; (fieldInfo, value, num, num2, index) = list3.Select((FieldInfoEx x, int i) => (x.Field, x.RestoreValueObject, x.ComparisonValue, TryGetAsDouble(x.Field), i)).FirstOrDefault<(FieldInfo, object, double, double, int)>(((FieldInfo Field, object RestoreValueObject, double ComparisonValue, double Value, int i) x) => x.ComparisonValue != x.Value); if ((object)fieldInfo != null) { list3.RemoveAt(index); } } else { num2 = TryGetAsDouble(fieldInfo); if (num2 == num) { num2 = double.NaN; } } if (!double.IsNaN(num2)) { list.Add((item2, num2)); } } if (list != null && list.Count > 0 && (object)fieldInfo != null) { double min = list.Min<(double, double)>(((double TestValue, double Value) x) => x.Value); double max = list.Max<(double, double)>(((double TestValue, double Value) x) => x.Value); IEnumerable<(double, double)> source = list.Where<(double, double)>(((double TestValue, double Value) x) => x.Value != 0.0 && x.Value > min && x.Value < max); double num3 = (source.Any() ? source.Average<(double, double)>(((double TestValue, double Value) x) => x.TestValue / x.Value) : 1.0); min *= num3; max *= num3; num *= num3; AcceptableValueBase val2 = null; if (min > -3.4028234663852886E+38 && max < 3.4028234663852886E+38 && min < max) { val2 = (AcceptableValueBase)Activator.CreateInstance(typeof(AcceptableValueRange<>).MakeGenericType(fieldInfo.FieldType), Convert.ChangeType(min, fieldInfo.FieldType), Convert.ChangeType(max, fieldInfo.FieldType)); } ConfigDescription val3 = new ConfigDescription(string.Format(descriptionFormat, text), val2, Array.Empty()); if ((object)methodInfo == null) { methodInfo = new Func>(cfg.Bind).Method.GetGenericMethodDefinition(); } ConfigEntryBase value2 = (ConfigEntryBase)methodInfo.MakeGenericMethod(fieldInfo.FieldType).Invoke(cfg, new object[4] { section, text, Convert.ChangeType(num, fieldInfo.FieldType), val3 }); dictionary2.Add(value3, value2); } else { dictionary2.Add(value3, (ConfigEntryBase)(object)cfg.Bind(section, text, false, string.Format(descriptionFormat, text))); } fieldInfo?.SetValue(null, value); } foreach (FieldInfoEx item3 in list3) { item3.Field.SetValue(null, item3.RestoreValueObject); } return dictionary2; } private static double TryGetAsDouble(FieldInfo field) { object value = field.GetValue(null); try { return (double)Convert.ChangeType(value, typeof(double)); } catch { return double.NaN; } } } public sealed class HostileSummonsConfig { public ConfigEntry AllowReplacementSummon { get; } = cfg.BindEx(section, defaultValue: false, "True to allow the summoning of new hostile summons (such as summoned trolls) to replace older ones when the limit exceeded", null, null, "AllowReplacementSummon"); public ConfigEntry MakeFriendly { get; } = cfg.BindEx(section, defaultValue: false, "True to make all hostile summons (such as summoned trolls) friendly", null, null, "MakeFriendly"); public ConfigEntry FollowSummoner { get; } = cfg.BindEx(section, defaultValue: false, "True to make summoned creatures follow the summoner", null, null, "FollowSummoner"); public HostileSummonsConfig(ConfigFile cfg, string section) { } } public sealed class LocalizationConfig { public sealed class NonTeleportableItemsConfig { public string ItemsReturned { get; init; } = "Portal returned your items"; private string ItemsTaken { get; init; } = "Portal took {0} items"; public string FormatItemsTaken(int count) { return string.Format(ItemsTaken, count); } } public sealed class PlayersConfig { public sealed class BackpackConfig { public string Name { get; init; } = "Backpack"; public string ForbiddenItems { get; init; } = "Backpack cannot contain non-teleportable items"; private string WeightLimitExceeded { get; init; } = "Backpack weight limit ({0}) exceeded"; public string FormatWeightLimitExceeded(int maxWeight) { return string.Format(WeightLimitExceeded, maxWeight); } } public string SacrificedMegingjord { get; init; } = "You were permanently granted increased carrying weight"; public string SacrificedCryptKey { get; init; } = "You were permanently granted the ability to open sunken crypt doors"; public string SacrificedWishbone { get; init; } = "You were permanently granted the ability to sense hidden objects"; public string SacrificedTornSpirit { get; init; } = "You were permanently granted a wisp companion"; public BackpackConfig Backpack { get; init; } = new BackpackConfig(); } public sealed class SleepingConfig { private string Prompt { get; init; } = "{0} of {1} players want to sleep.
Sit down if you want to sleep as well"; public string FormatPrompt(int sleepingPlayers, int totalPlayers) { return string.Format(Prompt, sleepingPlayers, totalPlayers); } } public sealed class ContainersConfig { public sealed class ObliteratorItemTeleporterConfig { public string TargetNotFound { get; init; } = "No target with corresponding tag found"; public string ForbiddenItem { get; init; } = "An item prevents the teleportation"; public string ItemsTeleported { get; init; } = "Items teleported"; } private string ContainerSorted { get; init; } = "{0} sorted"; private string AutoPickup { get; init; } = "{0}: $msg_added {1} {2}x"; public ObliteratorItemTeleporterConfig ObliteratorItemTeleporter { get; init; } = new ObliteratorItemTeleporterConfig(); public string FormatContainerSorted(string containerName) { return string.Format(ContainerSorted, containerName); } public string FormatAutoPickup(string containerName, string itemName, int stack) { return string.Format(AutoPickup, containerName, itemName, stack); } } public sealed class TamesConfig { private string Growing { get; init; } = "$caption_growing {0}%"; private string Taming { get; init; } = "$hud_tameness {0:P0}"; private string TamingHungry { get; init; } = "$hud_tameness {0:P0}, $hud_tamehungry"; public string FormatGrowing(int percent) { return string.Format(Growing, percent); } public string FormatTaming(float tameness, bool isHungry) { if (!isHungry) { return string.Format(Taming, tameness); } return string.Format(TamingHungry, tameness); } } public sealed class MapTableConfig { public string Updated { get; init; } = "$msg_mapsaved"; } public sealed class SmeltersConfig { private string FuelAdded { get; init; } = "{0}: $msg_added {1} {2}x"; private string OreAdded { get; init; } = "{0}: $msg_added {1} {2}x"; public string FormatFuelAdded(string smelterName, string itemName, int stack) { return string.Format(FuelAdded, smelterName, itemName, stack); } public string FormatOreAdded(string smelterName, string itemName, int stack) { return string.Format(OreAdded, smelterName, itemName, stack); } } public sealed class TrophySpawnerConfig { private string AttractingProgress { get; init; } = "Attracting {0}... {1:P0}"; private string Attracting { get; init; } = "Attracting {0}"; public string FormatAttractingProgress(string creatureName, double progress) { return string.Format(AttractingProgress, creatureName, progress); } public string FormatAttracting(string creatureName) { return string.Format(Attracting, creatureName); } } public sealed class TurretsConfig { private string AmmoAdded { get; init; } = "{0}: $msg_added {1} {2}x"; public string NoAmmoFound { get; init; } = "$msg_noturretammo"; public string FormatAmmoAdded(string turretName, string itemName, int count) { return string.Format(AmmoAdded, turretName, itemName, count); } } public ContainersConfig Containers { get; init; } = new ContainersConfig(); public MapTableConfig MapTable { get; init; } = new MapTableConfig(); public NonTeleportableItemsConfig NonTeleportableItems { get; init; } = new NonTeleportableItemsConfig(); public PlayersConfig Players { get; init; } = new PlayersConfig(); public SleepingConfig Sleeping { get; init; } = new SleepingConfig(); public SmeltersConfig Smelters { get; init; } = new SmeltersConfig(); public TamesConfig Tames { get; init; } = new TamesConfig(); public TrophySpawnerConfig TrophySpawner { get; init; } = new TrophySpawnerConfig(); public TurretsConfig Turrets { get; init; } = new TurretsConfig(); } public sealed class MapTableConfig { public ConfigEntry AutoUpdatePortals { get; } = cfg.BindEx(section, defaultValue: false, "True to update map tables with portal pins", null, null, "AutoUpdatePortals"); public ConfigEntry AutoUpdatePortalsExclude { get; } = cfg.BindEx(section, "", "Portals with a tag that matches this filter are not added to map tables", null, null, "AutoUpdatePortalsExclude"); public ConfigEntry AutoUpdatePortalsInclude { get; } = cfg.BindEx(section, "*", "Only portals with a tag that matches this filter are added to map tables", null, null, "AutoUpdatePortalsInclude"); public ConfigEntry AutoUpdateShips { get; } = cfg.BindEx(section, defaultValue: false, "True to update map tables with ship pins", null, null, "AutoUpdateShips"); public ConfigEntry UpdatedMessageType { get; } = cfg.BindEx(section, MessageTypes.None, "Type of message to show when a map table is updated", (AcceptableValueBase?)(object)AcceptableEnum.Default, null, "UpdatedMessageType"); public ConfigEntry? MapViewDistance { get; } = (ZNet.instance.IsServer() && ZNet.instance.IsDedicated()) ? cfg.BindEx(section, 0f, $"Max distance to a map table at which players can view their map.\r\nHas no effect unless the {(object)(GlobalKeys)26} global key is set.\r\n0 to disable this feature.", null, null, "MapViewDistance") : null; public MapTableConfig(ConfigFile cfg, string section) { } } public sealed class NetworkingConfig { public ConfigEntry MeasurePing { get; } = cfg.BindEx(section, defaultValue: false, "True to measure player ping", null, null, "MeasurePing"); public ConfigEntry PingStatisticsWindow { get; } = cfg.BindEx(section, 60, "Number of measurements to include for statistic calculations like mean and standard deviation", (AcceptableValueBase?)(object)new AcceptableValueRange(1, 100000), null, "PingStatisticsWindow"); public ConfigEntry LogPingThreshold { get; } = cfg.BindEx(section, 0, "A player's ping value to the server is logged if it exceeds this threshold", null, null, "LogPingThreshold"); public ConfigEntry ShowPingThreshold { get; } = cfg.BindEx(section, 0, "A player's ping value to the server is shown to the player if it exceeds this threshold", null, null, "ShowPingThreshold"); public ConfigEntry LogZoneOwnerPingThreshold { get; } = cfg.BindEx(section, 0, "A player's ping value to the zone owner is logged if it exceeds this threshold", null, null, "LogZoneOwnerPingThreshold"); public ConfigEntry ShowZoneOwnerPingThreshold { get; } = cfg.BindEx(section, 0, "A player's ping value to the zone owner is shown to the player if it exceeds this threshold", null, null, "ShowZoneOwnerPingThreshold"); public ConfigEntry LogPingFormat { get; } = cfg.BindEx(section, "Ping ({0}): {1:F0} ms (ema: {6:F0} ms, av: {2:F0} ± {3:F0} ms, jitter: {4:F0} ms)", "Format string for logging player ping.\r\nArguments:\r\n 0: Player name\r\n 1: Ping value in milliseconds\r\n 2: Mean of ping value in milliseconds\r\n 3: Standard deviation of ping value in milliseconds\r\n 4: Jitter in milliseconds\r\n 5: Connection quality\r\n 6: Exponential moving average of ping value in milliseconds", (AcceptableValueBase?)(object)new AcceptableFormatString(new object[7] { "", 0.0, 0.0, 0.0, 0.0, 0f, 0.0 }), null, "LogPingFormat"); public ConfigEntry ShowPingFormat { get; } = cfg.BindEx(section, "Ping: {0:F0} ms (ema: {5:F0} ms, av: {1:F0} ± {2:F0} ms, jitter: {3:F0} ms)", "Format string for player ping messages.\r\nArguments:\r\n 0: Ping value in milliseconds\r\n 1: Mean ping of value in milliseconds\r\n 2: Standard deviation of ping value in milliseconds\r\n 3: Jitter in milliseconds\r\n 4: Connection quality\r\n 5: Exponential moving average of ping value in milliseconds", (AcceptableValueBase?)(object)new AcceptableFormatString(new object[5] { 0.0, 0.0, 0.0, 0.0, 0f }), null, "ShowPingFormat"); public ConfigEntry LogZoneOwnerPingFormat { get; } = cfg.BindEx(section, "Ping ({0}): {1:F0} ms (ema: {12:F0} ms, av: {2:F0} ± {3:F0} ms, jitter: {4:F0} ms) + ZoneOwner ({6}): {7:F0} ms (ema: {13:F0} ms, av: {8:F0} ± {9:F0} ms, jitter: {10:F0} ms)", "Format string for logging player ping.\r\nArguments:\r\n 0: Player name\r\n 1: Ping value in milliseconds\r\n 2: Mean ping of value in milliseconds\r\n 3: Standard deviation of ping value in milliseconds\r\n 4: Jitter in milliseconds\r\n 5: Connection quality\r\n 6: Zone owner player name\r\n 7: Zone owner ping value in milliseconds\r\n 8: Mean ping of zone owner ping in milliseconds\r\n 9: Standard deviation of zone owner ping value in milliseconds\r\n 10: Zone owner jitter in milliseconds\r\n 11: Zone owner connection quality\r\n 12: Exponential moving average of ping value in milliseconds\r\n 13: Zone owner exponential moving average of ping value in milliseconds", (AcceptableValueBase?)(object)new AcceptableFormatString(new object[12] { "", 0.0, 0.0, 0.0, 0.0, 0f, "", 0.0, 0.0, 0.0, 0.0, 0f }), null, "LogZoneOwnerPingFormat"); public ConfigEntry ShowZoneOwnerPingFormat { get; } = cfg.BindEx(section, "Ping: {0:F0} ms (ema: {11:F0} ms, av: {1:F0} ± {2:F0} ms, jitter: {3:F0} ms) + {5}: {6:F0} ms (ema: {12:F0} ms, av: {7:F0} ± {8:F0} ms, jitter: {9:F0} ms)", "Format string for player ping messages.\r\nArguments:\r\n 0: Ping value in milliseconds\r\n 1: Mean ping of value in milliseconds\r\n 2: Standard deviation of ping value in milliseconds\r\n 3: Jitter in milliseconds\r\n 4: Connection quality\r\n 5: Zone owner player name\r\n 6: Zone owner ping value in milliseconds\r\n 7: Mean ping of zone owner ping in milliseconds\r\n 8: Standard deviation of zone owner ping value in milliseconds\r\n 9: Zone owner jitter in milliseconds\r\n 10: Zone owner connection quality\r\n 11: Exponential moving average of ping value in milliseconds\r\n 12: Zone owner exponential moving average of ping value in milliseconds", (AcceptableValueBase?)(object)new AcceptableFormatString(new object[11] { 0.0, 0.0, 0.0, 0.0, 0f, "", 0.0, 0.0, 0.0, 0.0, 0f }), null, "ShowZoneOwnerPingFormat"); public ConfigEntry ReassignOwnershipBasedOnConnectionQuality { get; } = cfg.BindEx(section, defaultValue: false, "True to (re)assign zone ownership to the player with the best connection.\r\nRequires 'MeasurePing' to be enabled.\r\nThe connection with the lowest connection quality value (lower = better) is chosen as the best connection,\r\nwhere connection quality = ping mean * ConnectionQualityPingMeanWeight + ping stddev * ConnectionQualityPingStdDevWeight + ping jitter * ConnectionQualityPingJitterWeight + ping EMA * ConnectionQualityPingEMAWeight\r\nWARNING: This feature is highly experimental and is likely to cause issues/interfere with other features of this mod and other mods", null, null, "ReassignOwnershipBasedOnConnectionQuality"); public ConfigEntry ReassignOwnershipConnectionQualityHysteresis { get; } = cfg.BindEx(section, 0.15f, "Minimum difference in connection quality required to reassign ownership.\r\nIf this value is smaller than 1, it's interpreted as relative difference (e.g. 0.15 means 15% difference),\r\notherwise as absolute value difference in connection quality.", null, null, "ReassignOwnershipConnectionQualityHysteresis"); public ConfigEntry ConnectionQualityPingMeanWeight { get; } = cfg.BindEx(section, 0f, "Weight of ping mean when calculating connection quality", null, null, "ConnectionQualityPingMeanWeight"); public ConfigEntry ConnectionQualityPingStdDevWeight { get; } = cfg.BindEx(section, 0f, "Weight of ping standard deviation when calculating connection quality", null, null, "ConnectionQualityPingStdDevWeight"); public ConfigEntry ConnectionQualityPingJitterWeight { get; } = cfg.BindEx(section, 0f, "Weight of ping jitter when calculating connection quality", null, null, "ConnectionQualityPingJitterWeight"); public ConfigEntry ConnectionQualityPingEMAWeight { get; } = cfg.BindEx(section, 1f, "Weight of ping exponential moving average when calculating connection quality", null, null, "ConnectionQualityPingEMAWeight"); public ConfigEntry PingEMAHalfLife { get; } = cfg.BindEx(section, 2.5f, "Half-life time in seconds for the exponential moving average of the ping value", null, null, "PingEMAHalfLife"); public ConfigEntry AssignInteractablesToClosestPlayer { get; } = cfg.BindEx(section, defaultValue: false, "True to assign ownership of some interactable objects (such as smelters or cooking stations) to the closest player.\r\nThis should help avoiding the loss of ore, etc. due to networking issues.", null, null, "AssignInteractablesToClosestPlayer"); public ConfigEntry AssignMobsToClosestPlayer { get; } = cfg.BindEx(section, defaultValue: false, "True to assign ownership of hostile mobs to the closest player.\r\nThis should help reduce issues with dodging/parrying due to networking issues.", null, null, "AssignMobsToClosestPlayer"); public ConfigEntry AssignShipsToCaptain { get; } = cfg.BindEx(section, defaultValue: false, "True to assign ownership of ships to the player controlling the ship.\r\nThis should help reduce issues with ship control due to networking issues.", null, null, "AssignShipsToCaptain"); public NetworkingConfig(ConfigFile cfg, string section) { } } public sealed class NonTeleportableItemsConfig { public sealed record Entry(ItemDrop ItemDrop, ConfigEntry Config); public ConfigEntry Enable { get; } public ConfigEntry PortalRange { get; } public ConfigEntry MessageType { get; } public IReadOnlyList Entries { get; } public NonTeleportableItemsConfig(ConfigFile cfg, string section) { ConfigFile cfg2 = cfg; string section2 = section; Enable = cfg2.BindEx(section2, defaultValue: false, "True to enable the non-teleportable items feature.\r\nItems which are not teleportable by default (e.g. ores, metals, etc.) will be temporarily taken from a player's inventory when they enter a certain range around a portal so that they can travel through, according to the settings below.\r\nWhen the player leaves the range (e.g. by travelling through the portal), the items will be returned to their inventory.", null, null, "Enable"); PortalRange = cfg2.BindEx(section2, 4f, "The range around a portal in which items will be taken from a player's inventory.\r\nDecreasing this value will lead to a longer delay before players with non-teleportable items in their inventory can use the portal.\r\nIncreasing this value will leave players unable to have certain items in their inventory in a larger range around portals.", null, null, "PortalRange"); MessageType = cfg2.BindEx(section2, MessageTypes.None, "Type of message to show when a non-teleportable item is taken from/returned to a player's inventory", (AcceptableValueBase?)(object)AcceptableEnum.Default, null, "MessageType"); Entries = ((Func>)delegate { //IL_01fd: Unknown result type (might be due to invalid IL or missing references) //IL_0207: Expected O, but got Unknown AcceptableValueList val = new AcceptableValueList((from x in SharedProcessorState.BossesByBiome.Values orderby x.m_health select x.m_defeatSetGlobalKey).ToArray()); List list = new List(); foreach (GameObject item in ObjectDB.instance.m_items) { ItemDrop component = item.GetComponent(); if (component != null) { ItemData itemData = component.m_itemData; if (itemData != null) { SharedData shared = itemData.m_shared; if (shared != null && !shared.m_teleportable) { string text = ""; if (Regex.IsMatch(((Object)item).name, "copper|tin|bronze", RegexOptions.IgnoreCase)) { text = SharedProcessorState.BossesByBiome[(Biome)8].m_defeatSetGlobalKey; } else if (((Object)item).name.Contains("iron", StringComparison.OrdinalIgnoreCase)) { text = SharedProcessorState.BossesByBiome[(Biome)2].m_defeatSetGlobalKey; } else if (Regex.IsMatch(((Object)item).name, "silver|DragonEgg", RegexOptions.IgnoreCase)) { text = SharedProcessorState.BossesByBiome[(Biome)4].m_defeatSetGlobalKey; } else if (((Object)item).name.Contains("blackmetal", StringComparison.OrdinalIgnoreCase)) { text = SharedProcessorState.BossesByBiome[(Biome)16].m_defeatSetGlobalKey; } else if (Regex.IsMatch(((Object)item).name, "DvergrNeedle|MechanicalSpring", RegexOptions.IgnoreCase)) { text = SharedProcessorState.BossesByBiome[(Biome)512].m_defeatSetGlobalKey; } else if (Regex.IsMatch(((Object)item).name, "flametal|CharredCogwheel", RegexOptions.IgnoreCase)) { text = SharedProcessorState.BossesByBiome[(Biome)32].m_defeatSetGlobalKey; } list.Add(new Entry(component, cfg2.Bind(section2, ((Object)item).name, text, new ConfigDescription("Key of the boss that will allow '" + Localization.instance.Localize(component.m_itemData.m_shared.m_name) + "' to be teleported when defeated", (AcceptableValueBase)(object)val, Array.Empty())))); } } } } return list; })(); base..ctor(); } } public sealed class PlantsConfig { public ConfigEntry GrowTimeMultiplier { get; } = cfg.BindEx(section, 1f, "Multiply plant grow time by this factor. 0 to make them grow almost instantly.", (AcceptableValueBase?)(object)new AcceptableValueRange(0f, float.PositiveInfinity), null, "GrowTimeMultiplier"); public ConfigEntry SpaceRequirementMultiplier { get; } = cfg.BindEx(section, 1f, "Multiply plant space requirement by this factor. 0 to disable space requirements.", (AcceptableValueBase?)(object)new AcceptableValueRange(0f, float.PositiveInfinity), null, "SpaceRequirementMultiplier"); public ConfigEntry DontDestroyIfCantGrow { get; } = cfg.BindEx(section, defaultValue: false, "True to keep plants that can't grow alive", null, null, "DontDestroyIfCantGrow"); public PlantsConfig(ConfigFile cfg, string section) { } } public sealed class PlayersConfig { public enum BackPackOnDeathOptions { SameAsInventory, Keep, Destroy, DropTombStone, DropItems } public ConfigEntry InfiniteBuildingStamina { get; } = cfg.BindEx(section, defaultValue: false, GetInfiniteXDescription("building"), null, null, "InfiniteBuildingStamina"); public ConfigEntry InfiniteFarmingStamina { get; } = cfg.BindEx(section, defaultValue: false, GetInfiniteXDescription("farming"), null, null, "InfiniteFarmingStamina"); public ConfigEntry InfiniteMiningStamina { get; } = cfg.BindEx(section, defaultValue: false, GetInfiniteXDescription("mining"), null, null, "InfiniteMiningStamina"); public ConfigEntry InfiniteWoodCuttingStamina { get; } = cfg.BindEx(section, defaultValue: false, GetInfiniteXDescription("cutting wood"), null, null, "InfiniteWoodCuttingStamina"); public ConfigEntry InfiniteEncumberedStamina { get; } = cfg.BindEx(section, defaultValue: false, GetInfiniteXDescription("encumbered"), null, null, "InfiniteEncumberedStamina"); public ConfigEntry InfiniteSneakingStamina { get; } = cfg.BindEx(section, defaultValue: false, GetInfiniteXDescription("sneaking"), null, null, "InfiniteSneakingStamina"); public ConfigEntry InfiniteSwimmingStamina { get; } = cfg.BindEx(section, defaultValue: false, GetInfiniteXDescription("swimming"), null, null, "InfiniteSwimmingStamina"); public ConfigEntry StackInventoryIntoContainersEmote { get; } public ConfigEntry StackInventoryIntoContainersReturnDelay { get; } public ConfigEntry OpenCartEmote { get; } public ConfigEntry OpenBackpackEmote { get; } public ConfigEntry InitialBackpackSlots { get; } public ConfigEntry AdditionalBackpackSlotsPerDefeatedBoss { get; } public ConfigEntry MaxBackpackWeight { get; } public ConfigEntry BackpackOnDeath { get; } public ConfigEntry CanSacrificeMegingjord { get; } public ConfigEntry CanSacrificeCryptKey { get; } public ConfigEntry CanSacrificeWishbone { get; } public ConfigEntry CanSacrificeTornSpirit { get; } public PlayersConfig(ConfigFile cfg, string section) { string description = $"Emote to stack inventory into containers.\r\nIf a player uses this emote, their inventory will be automatically stacked into nearby containers.\r\nThe rules for which containers are used are the same as for auto pickup.\r\n{(object)(Emotes)(-1)} to disable this feature, {(object)(Emotes)(-2)} to use any emote as trigger.\r\nFor example, on xbox you can use D-Pad down to execute the {(object)(Emotes)1} emote.\r\nIf you use emotes exclusively for this feature, it is recommended to set the value to {(object)(Emotes)(-2)} as it is more reliably detected than specific emotes, especially on bad connection/with crossplay."; List list = new List(); list.Add((Emotes)(-1)); list.Add((Emotes)(-2)); list.AddRange(Enum.GetValues(typeof(Emotes)).Cast()); StackInventoryIntoContainersEmote = cfg.BindEx(section, (Emotes)(-1), description, (AcceptableValueBase?)(object)new AcceptableEnum(new <>z__ReadOnlyList(list)), null, "StackInventoryIntoContainersEmote"); StackInventoryIntoContainersReturnDelay = cfg.BindEx(section, 1f, "Time in seconds after which items which could not be stacked into containers are returned to the player.\r\nIncreasing this value can help with bad connections.", (AcceptableValueBase?)(object)new AcceptableValueRange(1f, 10f), null, "StackInventoryIntoContainersReturnDelay"); string description2 = $"Emote to open the inventory of an attached cart.\r\n{(object)(Emotes)(-1)} to disable this feature, {(object)(Emotes)(-2)} to use any emote as trigger.\r\nYou can bind emotes to buttons with chat commands.\r\nFor example, on xbox you can bind the Y-Button to the wave-emote by entering \"/bind JoystickButton3 {(object)(Emotes)0}\" in the in-game chat.\r\nIf you use emotes exclusively for this feature, it is recommended to set the value to {(object)(Emotes)(-2)} as it is more reliably detected than specific emotes, especially on bad connection/with crossplay."; list = new List(); list.Add((Emotes)(-1)); list.Add((Emotes)(-2)); list.AddRange(Enum.GetValues(typeof(Emotes)).Cast()); OpenCartEmote = cfg.BindEx(section, (Emotes)(-1), description2, (AcceptableValueBase?)(object)new AcceptableEnum(new <>z__ReadOnlyList(list)), null, "OpenCartEmote"); string description3 = $"Emote to open the backpack.\r\nIf a player uses this emote, a virtual container acting as their backpack will open.\r\n{(object)(Emotes)(-1)} to disable this feature, {(object)(Emotes)(-2)} to use any emote as trigger.\r\nYou can bind emotes to buttons with chat commands.\r\nFor example, on xbox you can bind the Y-Button to the wave-emote by entering \"/bind JoystickButton3 {(object)(Emotes)0}\" in the in-game chat.\r\nIf you use emotes exclusively for this feature, it is recommended to set the value to {(object)(Emotes)(-2)} as it is more reliably detected than specific emotes, especially on bad connection/with crossplay."; list = new List(); list.Add((Emotes)(-1)); list.Add((Emotes)(-2)); list.AddRange(Enum.GetValues(typeof(Emotes)).Cast()); OpenBackpackEmote = cfg.BindEx(section, (Emotes)(-1), description3, (AcceptableValueBase?)(object)new AcceptableEnum(new <>z__ReadOnlyList(list)), null, "OpenBackpackEmote"); InitialBackpackSlots = cfg.BindEx(section, 4, "Initial available slots in the backpack", null, null, "InitialBackpackSlots"); AdditionalBackpackSlotsPerDefeatedBoss = cfg.BindEx(section, 4, "Additional backpack slots per defeated boss", null, null, "AdditionalBackpackSlotsPerDefeatedBoss"); MaxBackpackWeight = cfg.BindEx(section, 0, "Maximum backpack weight. 0 for no limit.", null, null, "MaxBackpackWeight"); BackpackOnDeath = cfg.BindEx(section, BackPackOnDeathOptions.SameAsInventory, "What happens to backpack contents on player death", null, null, "BackpackOnDeath"); CanSacrificeMegingjord = cfg.BindEx(section, defaultValue: false, "If true, players can permanently unlock increased carrying weight by sacrificing a megingjord in an obliterator", null, null, "CanSacrificeMegingjord"); CanSacrificeCryptKey = cfg.BindEx(section, defaultValue: false, "If true, players can permanently unlock the ability to open sunken crypt doors by sacrificing a crypt key in an obliterator", null, null, "CanSacrificeCryptKey"); CanSacrificeWishbone = cfg.BindEx(section, defaultValue: false, "If true, players can permanently unlock the ability to sense hidden objects by sacrificing a wishbone in an obliterator", null, null, "CanSacrificeWishbone"); CanSacrificeTornSpirit = cfg.BindEx(section, defaultValue: false, "If true, players can permanently unlock a wisp companion by sacrificing a torn spirit in an obliterator. WARNING: Wisp companion cannot be unsummoned and will stay as long as this setting is enabled.", null, null, "CanSacrificeTornSpirit"); base..ctor(); } private static string GetInfiniteXDescription(string action) { return FormattableString.Invariant(FormattableStringFactory.Create("True to give players infinite stamina when {0}.\r\nPlayer stamina will still be drained, but when nearly depleted, just enough stamina will be restored to continue indefinitely.\r\nIf you want infinite stamina in general, set the global key '{1}' to 0.", action, "StaminaRate")); } } public sealed class PortalHubConfig { public ConfigEntry Enable { get; } = cfg.BindEx(section, defaultValue: false, "True to automatically generate a portal hub.\r\nPlaced portals which don't have a paired portal in the world will be connected to the portal hub.", null, null, "Enable"); public ConfigEntry Exclude { get; } = cfg.BindEx(section, "", "Portals with a tag that matches this filter are not connected to the portal hub", null, null, "Exclude"); public ConfigEntry Include { get; } = cfg.BindEx(section, "*", "Only portals with a tag that matches this filter are connected to the portal hub", null, null, "Include"); public ConfigEntry AutoNameNewPortals { get; } = cfg.BindEx(section, defaultValue: false, "True to automatically name new portals. Has no effect if 'Enable' is false", null, null, "AutoNameNewPortals"); public ConfigEntry AutoNameNewPortalsFormat { get; } = cfg.BindEx(section, "{0} {1:D2}", "Format string for auto-naming portals, the first argument is the biome name, the second is an automatically incremented integer", (AcceptableValueBase?)(object)new AcceptableFormatString(new object[2] { "Test", 0 }), null, "AutoNameNewPortalsFormat"); public PortalHubConfig(ConfigFile cfg, string section) { } } public sealed class ShipsConfig { public ConfigEntry DeconstructWithHammer { get; } = cfg.BindEx(section, defaultValue: false, "If enabled, ships can be deconstructed with the build hammer", null, null, "DeconstructWithHammer"); public ShipsConfig(ConfigFile cfg, string section) { } } public sealed class SignsConfig { public ConfigEntry DefaultColor { get; } = cfg.BindEx(section, "", "Default color for signs. Can be a color name or hex code (e.g. #FF0000 for red)", null, null, "DefaultColor"); public ConfigEntry TimeSigns { get; } = cfg.BindEx(section, defaultValue: false, FormattableString.Invariant($"True to update sign texts which contain time emojis (any of {string.Concat(SignProcessor.ClockEmojis)}) with the in-game time"), null, null, "TimeSigns"); public SignsConfig(ConfigFile cfg, string section) { } } public sealed class SkillsConfig { [Obsolete(null, true)] public ConfigEntry PickaxeAffectsRockDestruction { get; } = cfg.BindEx(section, defaultValue: false, "True to make the pickaxe skill affect the destruction of rocks and ore deposits.\r\nIf true, rocks and ore deposits will be completely destroyed once more than (100 - Pickaxe Skill Level)%\r\nof their parts have been destroyed.\r\nE.g. at skill level 10, 90% of the parts need to be destroyed while at skill level 80, 20% destroyed parts are enough\r\nto destroy the whole rock/ore deposit", null, new Deprecated("Use PickaxeRockCollapseThresholdAtMinSkill/PickaxeRockCollapseThresholdAtMaxSkill instead", delegate(ModConfig cfg) { cfg.Skills.PickaxeRockCollapseThresholdAtMinSkill.Value = 100; cfg.Skills.PickaxeRockCollapseThresholdAtMaxSkill.Value = 0; }), "PickaxeAffectsRockDestruction"); public ConfigEntry PickaxeRockCollapseThresholdAtMinSkill { get; } = cfg.BindEx(section, -1, "The percentage of destroyed parts required to collapse a rock or ore deposit at pickaxe skill level 0.\r\nThe actual required percentage scales linearly between this value and PickaxeRockCollapseThresholdAtMaxSkill with skill level.\r\nSet both of these values to -1 to disable this feature.", null, null, "PickaxeRockCollapseThresholdAtMinSkill"); public ConfigEntry PickaxeRockCollapseThresholdAtMaxSkill { get; } = cfg.BindEx(section, -1, "The percentage of destroyed parts required to collapse a rock or ore deposit at pickaxe skill level 100.\r\nThe actual required percentage scales linearly between this value and PickaxeRockCollapseThresholdAtMinSkill with skill level.\r\nSet both of these values to -1 to disable this feature.", null, null, "PickaxeRockCollapseThresholdAtMaxSkill"); public bool PickaxeRockCollapseEnabled => Math.Max(PickaxeRockCollapseThresholdAtMinSkill.Value, PickaxeRockCollapseThresholdAtMaxSkill.Value) > 0; public ConfigEntry BloodmagicSummonsLevelUpChanceAtMinSkill { get; } = cfg.BindEx(section, -1, "The chance (in percent) at skill level 0 to summon a creature with an increased level.\r\nThe actual chance scales linearly between this value and BloodmagicSummonsLevelUpChanceAtMaxSkill with skill level.\r\nSet both of these values to -1 to disable this feature.", null, null, "BloodmagicSummonsLevelUpChanceAtMinSkill"); public ConfigEntry BloodmagicSummonsLevelUpChanceAtMaxSkill { get; } = cfg.BindEx(section, -1, "The chance (in percent) at skill level 100 to summon a creature with an increased level.\r\nThe actual chance scales linearly between this value and BloodmagicSummonsLevelUpChanceAtMinSkill with skill level.\r\nSet both of these values to -1 to disable this feature.", null, null, "BloodmagicSummonsLevelUpChanceAtMaxSkill"); public bool BloodmagicSummonsLevelUpEnabled => Math.Max(BloodmagicSummonsLevelUpChanceAtMinSkill.Value, BloodmagicSummonsLevelUpChanceAtMaxSkill.Value) > 0; public ConfigEntry BloodmagicSummonsMaxLevel { get; } = cfg.BindEx(section, 3, "The maximum level a summoned creature can reach.", (AcceptableValueBase?)(object)new AcceptableValueRange(2, 9), null, "BloodmagicSummonsMaxLevel"); public ConfigEntry BloodmagicMakeSummonsFriendlyChanceAtMinSkill { get; } = cfg.BindEx(section, -1, "The chance (in percent) at skill level 0 for hostile summons to be made friendly.\r\nThe actual chance scales linearly between this value and BloodmagicMakeSummonsFriendlyChanceAtMaxSkill with skill level.\r\nSet both of these values to -1 to disable this feature.\r\nThis will not affect summons that are already friendly by default.", null, null, "BloodmagicMakeSummonsFriendlyChanceAtMinSkill"); public ConfigEntry BloodmagicMakeSummonsFriendlyChanceAtMaxSkill { get; } = cfg.BindEx(section, -1, "The chance (in percent) at skill level 100 for hostile summons to be made friendly.\r\nThe actual chance scales linearly between this value and BloodmagicMakeSummonsFriendlyChanceAtMinSkill with skill level.\r\nSet both of these values to -1 to disable this feature.\r\nThis will not affect summons that are already friendly by default.", null, null, "BloodmagicMakeSummonsFriendlyChanceAtMaxSkill"); public bool BloodmagicMakeSummonsFriendlyEnabled => Math.Max(BloodmagicMakeSummonsFriendlyChanceAtMinSkill.Value, BloodmagicMakeSummonsFriendlyChanceAtMaxSkill.Value) > 0; public ConfigEntry BloodmagicMakeSummonsTolerateLavaChanceAtMinSkill { get; } = cfg.BindEx(section, -1, "The chance (in percent) at skill level 0 for a summoned creature to tolerate lava.\r\nThe actual chance scales linearly between this value and BloodmagicMakeSummonsTolerateLavaChanceAtMaxSkill with skill level.\r\nSet both of these values to -1 to disable this feature.\r\nThis will not affect summons that already tolerate lava by default.", null, null, "BloodmagicMakeSummonsTolerateLavaChanceAtMinSkill"); public ConfigEntry BloodmagicMakeSummonsTolerateLavaChanceAtMaxSkill { get; } = cfg.BindEx(section, -1, "The chance (in percent) at skill level 0 for a summoned creature to tolerate lava.\r\nThe actual chance scales linearly between this value and BloodmagicMakeSummonsTolerateLavaChanceAtMinSkill with skill level.\r\nSet both of these values to -1 to disable this feature.\r\nThis will not affect summons that already tolerate lava by default.", null, null, "BloodmagicMakeSummonsTolerateLavaChanceAtMaxSkill"); public bool BloodmagicMakeSummonsTolerateLavaEnabled => Math.Max(BloodmagicMakeSummonsTolerateLavaChanceAtMinSkill.Value, BloodmagicMakeSummonsTolerateLavaChanceAtMaxSkill.Value) > 0; public ConfigEntry BloodmagicSummonsHPRegenMultiplierAtMinSkill { get; } = cfg.BindEx(section, 1f, "The time it takes for a summoned creature to fully regenerate its health at skill level 0 is multiplied by this factor.\r\nThe actual chance scales linearly between this value and BloodmagicSummonsHPRegenMultiplierAtMaxSkill with skill level.\r\nSet both of these values to 1 to disable this feature.", null, null, "BloodmagicSummonsHPRegenMultiplierAtMinSkill"); public ConfigEntry BloodmagicSummonsHPRegenMultiplierAtMaxSkill { get; } = cfg.BindEx(section, 1f, "The time it takes for a summoned creature to fully regenerate its health at skill level 100 is multiplied by this factor.\r\nThe actual chance scales linearly between this value and BloodmagicSummonsHPRegenMultiplierAtMinSkill with skill level.\r\nSet both of these values to 1 to disable this feature.", null, null, "BloodmagicSummonsHPRegenMultiplierAtMaxSkill"); public bool BloodmagicSummonsHPRegenMultiplierEnabled { get { float value = BloodmagicSummonsHPRegenMultiplierAtMinSkill.Value; float value2 = BloodmagicSummonsHPRegenMultiplierAtMaxSkill.Value; if (value > 0f && value2 > 0f && (value != 1f || value2 != 1f)) { return true; } return false; } } public ConfigEntry BloodmagicSummonsSpeedMultiplierAtMinSkill { get; } = cfg.BindEx(section, 1f, "The movement speed of a summoned creature at skill level 0 is multiplied by this factor.\r\nThe actual chance scales linearly between this value and BloodmagicSummonsSpeedMultiplierAtMaxSkill with skill level.\r\nSet both of these values to 1 to disable this feature.", null, null, "BloodmagicSummonsSpeedMultiplierAtMinSkill"); public ConfigEntry BloodmagicSummonsSpeedMultiplierAtMaxSkill { get; } = cfg.BindEx(section, 1f, "The movement speed of a summoned creature at skill level 0 is multiplied by this factor.\r\nThe actual chance scales linearly between this value and BloodmagicSummonsSpeedMultiplierAtMinSkill with skill level.\r\nSet both of these values to 1 to disable this feature.", null, null, "BloodmagicSummonsSpeedMultiplierAtMaxSkill"); public bool BloodmagicSummonsSpeedMultiplierEnabled { get { float value = BloodmagicSummonsSpeedMultiplierAtMinSkill.Value; float value2 = BloodmagicSummonsSpeedMultiplierAtMaxSkill.Value; if (value > 0f && value2 > 0f && (value != 1f || value2 != 1f)) { return true; } return false; } } public bool AnyEnbaled { get { if (!PickaxeRockCollapseEnabled && !BloodmagicSummonsLevelUpEnabled && !BloodmagicMakeSummonsFriendlyEnabled && !BloodmagicMakeSummonsTolerateLavaEnabled && !BloodmagicSummonsHPRegenMultiplierEnabled) { return BloodmagicSummonsSpeedMultiplierEnabled; } return true; } } public SkillsConfig(ConfigFile cfg, string section) { } } public sealed class SleepingConfig { public ConfigEntry MinPlayersInBed { get; } = cfg.BindEx(section, 0, "Minimum number of players in bed to show the sleep prompt to the other players. 0 to require all players to be in bed (default behavior)", null, null, "MinPlayersInBed"); public ConfigEntry RequiredPlayerPercentage { get; } = cfg.BindEx(section, 100, "Percentage of players that must be in bed or sitting to skip the night", (AcceptableValueBase?)(object)new AcceptableValueRange(0, 100), null, "RequiredPlayerPercentage"); public ConfigEntry SleepPromptMessageType { get; } = cfg.BindEx(section, (MessageType)2, "Type of message to show for the sleep prompt", (AcceptableValueBase?)(object)AcceptableEnum.Default, null, "SleepPromptMessageType"); public SleepingConfig(ConfigFile cfg, string section) { } } public sealed class SmeltersConfig { public ConfigEntry FeedFromContainers { get; } = cfg.BindEx(section, defaultValue: false, "True to automatically feed smelters from nearby containers", null, null, "FeedFromContainers"); public ConfigEntry FeedFromContainersRange { get; } = cfg.BindEx(section, 4f, "Required proximity of a container to a smelter to be used as feeding source.\r\nCan be overridden per chest by putting '↔\ufe0f' on a chest sign.", null, null, "FeedFromContainersRange"); public ConfigEntry FeedFromContainersMaxRange { get; } = cfg.BindEx(section, 64, "Max feeding range players can set per chest (by putting '↔\ufe0f' on a chest sign)", null, null, "FeedFromContainersMaxRange"); public ConfigEntry FeedFromContainersLeaveAtLeastFuel { get; } = cfg.BindEx(section, 1, "Minimum amount of fuel to leave in a container", null, null, "FeedFromContainersLeaveAtLeastFuel"); public ConfigEntry FeedFromContainersLeaveAtLeastOre { get; } = cfg.BindEx(section, 1, "Minimum amount of ore to leave in a container", null, null, "FeedFromContainersLeaveAtLeastOre"); public ConfigEntry OreOrFuelAddedMessageType { get; } = cfg.BindEx(section, MessageTypes.None, "Type of message to show when ore or fuel is added to a smelter", (AcceptableValueBase?)(object)AcceptableEnum.Default, null, "OreOrFuelAddedMessageType"); public ConfigEntry CapacityMultiplier { get; } = cfg.BindEx(section, 1f, "Multiply a smelter's ore/fuel capacity by this factor", null, null, "CapacityMultiplier"); public ConfigEntry TimePerProductMultiplier { get; } = cfg.BindEx(section, 1f, "Multiply the time it takes to produce one product by this factor (will not go below 1 second per product).", null, null, "TimePerProductMultiplier"); public SmeltersConfig(ConfigFile cfg, string section) { } } public sealed class SummonsConfig { public ConfigEntry UnsummonDistanceMultiplier { get; } = cfg.BindEx(section, 1f, "Multiply unsummon distance by this factor. 0 to disable distance-based unsummoning", (AcceptableValueBase?)(object)new AcceptableValueRange(0f, float.PositiveInfinity), null, "UnsummonDistanceMultiplier"); public ConfigEntry UnsummonLogoutTimeMultiplier { get; } = cfg.BindEx(section, 1f, "Multiply the time after which summons are unsummoned when the player logs out. 0 to disable logout-based unsummoning", (AcceptableValueBase?)(object)new AcceptableValueRange(0f, float.PositiveInfinity), null, "UnsummonLogoutTimeMultiplier"); public SummonsConfig(ConfigFile cfg, string section) { } } public sealed class TamesConfig { public ConfigEntry MakeCommandable { get; } = cfg.BindEx(section, defaultValue: false, "True to make all tames commandable (like wolves)", null, null, "MakeCommandable"); public ConfigEntry TamingProgressMessageType { get; } = cfg.BindEx(section, MessageTypes.None, "Type of taming progress messages to show", (AcceptableValueBase?)(object)AcceptableEnum.Default, null, "TamingProgressMessageType"); public ConfigEntry GrowingProgressMessageType { get; } = cfg.BindEx(section, MessageTypes.None, "Type of growing progress messages to show", (AcceptableValueBase?)(object)AcceptableEnum.Default, null, "GrowingProgressMessageType"); public ConfigEntry FedDurationMultiplier { get; } = cfg.BindEx(section, 1f, FormattableString.Invariant($"Multiply the time tames stay fed after they have eaten by this factor. {float.PositiveInfinity} to keep them fed indefinitely"), null, null, "FedDurationMultiplier"); public ConfigEntry TamingTimeMultiplier { get; } = cfg.BindEx(section, 1f, "Multiply the time it takes to tame a tameable creature by this factor.\r\nE.g. a value of 0.5 means that the taming time is halved.", null, null, "TamingTimeMultiplier"); public ConfigEntry PotionTamingBoostMultiplier { get; } = cfg.BindEx(section, 1f, "Multiply the taming boost from the animal whispers potion by this factor.\r\nE.g. a value of 2 means that the effect of the potion is doubled and the resulting taming time is reduced by a factor of 4 per player.", null, null, "PotionTamingBoostMultiplier"); public ConfigEntry TeleportFollow { get; } = cfg.BindEx(section, defaultValue: false, "True to teleport following tames to the players location if the player gets too far away from them", null, null, "TeleportFollow"); public ConfigEntry TeleportFollowMinDistance { get; } = cfg.BindEx(section, 64f, "Minimum distance from the player at which following tames will be teleported to the player's location", null, null, "TeleportFollowMinDistance"); public ConfigEntry TakeIntoDungeons { get; } = cfg.BindEx(section, defaultValue: false, "True to take following tames into (and out of) dungeons with you", null, null, "TakeIntoDungeons"); public TamesConfig(ConfigFile cfg, string section) { } } public sealed class TradersConfig { public IReadOnlyDictionary ConfigEntry)>> AlwaysUnlock { get; } = GetAlwaysUnlock(cfg, section); public TradersConfig(ConfigFile cfg, string section) { } private static IReadOnlyDictionary ConfigEntry)>> GetAlwaysUnlock(ConfigFile cfg, string section) { ConfigFile cfg2 = cfg; string section2 = section; if (!ZNet.instance.IsServer() || !ZNet.instance.IsDedicated()) { return new Dictionary)>>(); } return (from x in (from x in ZNetScene.instance.m_prefabs select x.GetComponent() into x where x != null select x).Select((Func)>)>)delegate(Trader trader) { Trader item2 = trader; List<(string, ConfigEntry)> list = new List<(string, ConfigEntry)>(); list.AddRange(from x in trader.m_items where !string.IsNullOrEmpty(x.m_requiredGlobalKey) select x into item select (item.m_requiredGlobalKey, cfg2.Bind(section2, FormattableString.Invariant(FormattableStringFactory.Create("{0}{1}{2}", "AlwaysUnlock", ((Object)trader).name, ((Object)item.m_prefab).name)), false, FormattableString.Invariant($"Remove the progression requirements for buying {Localization.instance.Localize(item.m_prefab.m_itemData.m_shared.m_name)} from {Localization.instance.Localize(trader.m_name)}")))); return (item2, new <>z__ReadOnlyList<(string, ConfigEntry)>(list)); }) where x.Entries.Any() select x).ToDictionary<(Trader, IReadOnlyList<(string, ConfigEntry)>), Trader, IReadOnlyList<(string, ConfigEntry)>>(((Trader Trader, IReadOnlyList<(string GlobalKey, ConfigEntry ConfigEntry)> Entries) x) => x.Trader, ((Trader Trader, IReadOnlyList<(string GlobalKey, ConfigEntry ConfigEntry)> Entries) x) => x.Entries); } } public sealed class TrapsConfig { public ConfigEntry DisableTriggeredByPlayers { get; } = cfg.BindEx(section, defaultValue: false, "True to stop traps from being triggered by players", null, null, "DisableTriggeredByPlayers"); public ConfigEntry DisableFriendlyFire { get; } = cfg.BindEx(section, defaultValue: false, "True to stop traps from damaging players and tames. Does not work reliably (yet).", null, null, "DisableFriendlyFire"); public ConfigEntry SelfDamageMultiplier { get; } = cfg.BindEx(section, 1f, "Multiply the damage the trap takes when it is triggered by this factor. 0 to make the trap take no damage", (AcceptableValueBase?)(object)new AcceptableValueRange(0f, float.PositiveInfinity), null, "SelfDamageMultiplier"); public ConfigEntry AutoRearm { get; } = cfg.BindEx(section, defaultValue: false, "True to automatically rearm traps when they are triggered", null, null, "AutoRearm"); public TrapsConfig(ConfigFile cfg, string section) { } } public sealed class TrophySpawnerConfig { public ConfigEntry Enable { get; } = cfg.BindEx(section, defaultValue: false, "True to make dropped trophies attract mobs.", null, null, "Enable"); public ConfigEntry ActivationDelay { get; } = cfg.BindEx(section, 3600, "Time in seconds before trophies start attracting mobs", null, null, "ActivationDelay"); public ConfigEntry RespawnDelay { get; } = cfg.BindEx(section, 12, "Respawn delay in seconds", null, null, "RespawnDelay"); private static float MaxDistance => Mathf.Round(Mathf.Sqrt(2f) * (float)ZoneSystem.instance.m_activeArea * 64f); public ConfigEntry MinSpawnDistance { get; } = cfg.BindEx(section, MaxDistance, "Min distance from the trophy mobs can spawn", (AcceptableValueBase?)(object)new AcceptableValueRange(0f, MaxDistance), null, "MinSpawnDistance"); public ConfigEntry MaxSpawnDistance { get; } = cfg.BindEx(section, MaxDistance, "Max distance from the trophy mobs can spawn", (AcceptableValueBase?)(object)new AcceptableValueRange(0f, MaxDistance), null, "MaxSpawnDistance"); public ConfigEntry MaxLevel { get; } = cfg.BindEx(section, 3, "Maximum level of spawned mobs", (AcceptableValueBase?)(object)new AcceptableValueRange(1, 9), null, "MaxLevel"); public ConfigEntry LevelUpChanceOverride { get; } = cfg.BindEx(section, -1, "Level up chance override for spawned mobs. If < 0, world default is used", (AcceptableValueBase?)(object)new AcceptableValueRange(-1, 100), null, "LevelUpChanceOverride"); public ConfigEntry SpawnLimit { get; } = cfg.BindEx(section, 20, "Maximum number of mobs of the trophy's type in the active area", (AcceptableValueBase?)(object)new AcceptableValueRange(1, 10000), null, "SpawnLimit"); public ConfigEntry SuppressDrops { get; } = cfg.BindEx(section, defaultValue: true, "True to suppress drops from mobs spawned by trophies. Does not work reliably (yet)", null, null, "SuppressDrops"); public ConfigEntry MessageType { get; } = cfg.BindEx(section, MessageTypes.InWorld, "Type of message to show when a trophy is attracting mobs", (AcceptableValueBase?)(object)AcceptableEnum.Default, null, "MessageType"); public TrophySpawnerConfig(ConfigFile cfg, string section) { } } public sealed class TurretsConfig { public ConfigEntry DontTargetPlayers { get; } = cfg.BindEx(section, defaultValue: false, "True to stop ballistas from targeting players", null, null, "DontTargetPlayers"); public ConfigEntry DontTargetTames { get; } = cfg.BindEx(section, defaultValue: false, "True to stop ballistas from targeting tames", null, null, "DontTargetTames"); public ConfigEntry LoadFromContainers { get; } = cfg.BindEx(section, defaultValue: false, "True to automatically load ballistas from containers", null, null, "LoadFromContainers"); public ConfigEntry LoadFromContainersRange { get; } = cfg.BindEx(section, 4f, "Required proximity of a container to a ballista to be used as ammo source", null, null, "LoadFromContainersRange"); public ConfigEntry AmmoAddedMessageType { get; } = cfg.BindEx(section, MessageTypes.None, "Type of message to show when ammo is added to a turret", (AcceptableValueBase?)(object)AcceptableEnum.Default, null, "AmmoAddedMessageType"); public ConfigEntry NoAmmoMessageType { get; } = cfg.BindEx(section, MessageTypes.None, "Type of message to show when there is no ammo to add to a turret", (AcceptableValueBase?)(object)AcceptableEnum.Default, null, "NoAmmoMessageType"); public TurretsConfig(ConfigFile cfg, string section) { } } public sealed class WearNTearConfig { [Flags] public enum DisableSupportRequirementsOptions { None = 0, PlayerBuilt = 1, World = 2 } public ConfigEntry DisableRainDamage { get; } = cfg.BindEx(section, defaultValue: false, "True to prevent rain from damaging build pieces", null, null, "DisableRainDamage"); public ConfigEntry DisableSupportRequirements { get; } = cfg.BindEx(section, DisableSupportRequirementsOptions.None, "Ignore support requirements on build pieces", (AcceptableValueBase?)(object)AcceptableEnum.Default, null, "DisableSupportRequirements"); public ConfigEntry MakeIndestructible { get; } = cfg.BindEx(section, defaultValue: false, "True to make player-built pieces indestructible", null, null, "MakeIndestructible"); public WearNTearConfig(ConfigFile cfg, string section) { } } public sealed class WindmillsConfig { public ConfigEntry IgnoreWind { get; } = cfg.BindEx(section, defaultValue: false, "True to make windmills ignore wind (Cover still decreases operating efficiency though)", null, null, "IgnoreWind"); public WindmillsConfig(ConfigFile cfg, string section) { } } public sealed class WishboneConfig { public ConfigEntry FindDungeons { get; } = cfg.BindEx(section, defaultValue: false, "True to make the wishbone find dungeons", null, null, "FindDungeons"); public ConfigEntry FindVegvisir { get; } = cfg.BindEx(section, defaultValue: false, "True to make the wishbone find vegvisirs", null, null, "FindVegvisir"); public ConfigEntry FindLocationObjectRegex { get; } = cfg.BindEx(section, "", "The wishbone will find locations which contain an object whose (prefab) name matches this regular expression.\r\nExample: Beehive|goblin_totempole|giant_brain|dvergrprops_crate\\w*", null, null, "FindLocationObjectRegex"); public ConfigEntry Range { get; } = cfg.BindEx(section, Mathf.Max(Minimap.instance.m_exploreRadius, 64f), "Radius in which the wishbone will react to dungeons/locations", (AcceptableValueBase?)(object)new AcceptableValueRange(0f, 128f * Mathf.Sqrt(2f)), null, "Range"); public WishboneConfig(ConfigFile cfg, string section) { } } public sealed class WorldConfig { public enum RemoveMistlandsMistOptions { Never, Always, AfterQueenKilled, InsideShield } public ConfigEntry RemoveMistlandsMist { get; } = cfg.BindEx(section, RemoveMistlandsMistOptions.Never, "Condition to remove the mist from the mistlands.\r\nBeware that there are a few cases of mist (namely mist around POIs like ancient bones/skulls)\r\nthat cannot be removed by this mod and will remain regardless of this setting.", (AcceptableValueBase?)(object)AcceptableEnum.Default, null, "RemoveMistlandsMist"); public ConfigEntry MakeAllItemsFloat { get; } = cfg.BindEx(section, defaultValue: false, "True to make all items float.\r\nNon-floating items will be put in a floating cargo crate if they sink 2m below water level.", null, null, "MakeAllItemsFloat"); public WorldConfig(ConfigFile cfg, string section) { } } public sealed class WorldModifiersConfig { public ConfigEntry SetPresetFromConfig { get; } = cfg.BindEx(section, defaultValue: false, FormattableString.Invariant(FormattableStringFactory.Create("True to set the world preset according to the '{0}' config entry", "Preset")), null, null, "SetPresetFromConfig"); public ConfigEntry Preset { get; } = GetPreset(cfg, section); public ConfigEntry SetModifiersFromConfig { get; } = cfg.BindEx(section, defaultValue: false, "True to set world modifiers according to the following configuration entries", null, null, "SetModifiersFromConfig"); public IReadOnlyDictionary> Modifiers { get; } = GetModifiers(cfg, section); public WorldModifiersConfig(ConfigFile cfg, string section) { } private static ConfigEntry GetPreset(ConfigFile cfg, string section) { //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Expected O, but got Unknown IReadOnlyList source = PrivateAccessor.GetServerOptionsGUIPresets(); return cfg.Bind(section, "Preset", (WorldPresets)0, new ConfigDescription(FormattableString.Invariant(FormattableStringFactory.Create("World preset. Enable '{0}' for this to have an effect", "SetPresetFromConfig")), (AcceptableValueBase)(object)new AcceptableEnum(source.Select((KeyButton x) => x.m_preset)), Array.Empty())); } private static IReadOnlyDictionary> GetModifiers(ConfigFile cfg, string section) { ConfigFile cfg2 = cfg; string section2 = section; return (from keySlider in PrivateAccessor.GetServerOptionsGUIModifiers().OfType() select (keySlider.m_modifier, cfg2.Bind(section2, FormattableString.Invariant($"{keySlider.m_modifier}"), (WorldModifierOption)0, new ConfigDescription(FormattableString.Invariant(FormattableStringFactory.Create("World modifier '{0}'. Enable '{1}' for this to have an effect", keySlider.m_modifier, "SetModifiersFromConfig")), (AcceptableValueBase)(object)new AcceptableEnum(keySlider.m_settings.Select((SliderSetting x) => x.m_modifierValue)), Array.Empty())))).ToDictionary<(WorldModifiers, ConfigEntry), WorldModifiers, ConfigEntry>(((WorldModifiers Key, ConfigEntry Cfg) x) => x.Key, ((WorldModifiers Key, ConfigEntry Cfg) x) => x.Cfg); } } public GeneralConfig General { get; } = new GeneralConfig(ConfigFile, "A - General"); public AdminsConfig Admins { get; } = new AdminsConfig(ConfigFile, "B - Admins"); public SignsConfig Signs { get; } = new SignsConfig(ConfigFile, "B - Signs"); public MapTableConfig MapTables { get; } = new MapTableConfig(ConfigFile, "B - Map Tables"); public TamesConfig Tames { get; } = new TamesConfig(ConfigFile, "B - Tames"); public CreaturesConfig Creatures { get; } = new CreaturesConfig(ConfigFile, "B - Creatures"); public SummonsConfig Summons { get; } = new SummonsConfig(ConfigFile, "B - Summons"); public HostileSummonsConfig HostileSummons { get; } = new HostileSummonsConfig(ConfigFile, "B - Hostile Summons"); public FireplacesConfig Fireplaces { get; } = new FireplacesConfig(ConfigFile, "B - Fireplaces"); public ContainersConfig Containers { get; } = new ContainersConfig(ConfigFile, "B - Containers"); public SmeltersConfig Smelters { get; } = new SmeltersConfig(ConfigFile, "B - Smelters"); public WindmillsConfig Windmills { get; } = new WindmillsConfig(ConfigFile, "B - Windmills"); public CartsConfig Carts { get; } = new CartsConfig(ConfigFile, "B - Carts"); public ShipsConfig Ships { get; } = new ShipsConfig(ConfigFile, "B - Ships"); public DoorsConfig Doors { get; } = new DoorsConfig(ConfigFile, "B - Doors"); public PlayersConfig Players { get; } = new PlayersConfig(ConfigFile, "B - Players"); public TurretsConfig Turrets { get; } = new TurretsConfig(ConfigFile, "B - Turrets"); public WearNTearConfig WearNTear { get; } = new WearNTearConfig(ConfigFile, "B - Build Pieces"); public CraftingStationsConfig CraftingStations { get; } = new CraftingStationsConfig(ConfigFile, "B - Crafting Stations"); public TradersConfig Traders { get; } = new TradersConfig(ConfigFile, "B - Traders"); public PlantsConfig Plants { get; } = new PlantsConfig(ConfigFile, "B - Plants"); public TrapsConfig Traps { get; } = new TrapsConfig(ConfigFile, "B - Traps"); public PortalHubConfig PortalHub { get; } = new PortalHubConfig(ConfigFile, "B - Portal Hub"); public WorldConfig World { get; } = new WorldConfig(ConfigFile, "B - World"); public TrophySpawnerConfig TrophySpawner { get; } = new TrophySpawnerConfig(ConfigFile, "B - Trophy Spawner"); public NonTeleportableItemsConfig NonTeleportableItems { get; } = new NonTeleportableItemsConfig(ConfigFile, "B - Non-teleportable Items"); public SleepingConfig Sleeping { get; } = new SleepingConfig(ConfigFile, "B - Sleeping"); public FermentersConfig Fermenters { get; } = new FermentersConfig(ConfigFile, "B - Fermenters"); public NetworkingConfig Networking { get; } = new NetworkingConfig(ConfigFile, "B - Networking"); public WishboneConfig Wishbone { get; } = new WishboneConfig(ConfigFile, "B - Wishbone"); public SkillsConfig Skills { get; } = new SkillsConfig(ConfigFile, "B - Skills"); public WorldModifiersConfig WorldModifiers { get; } = new WorldModifiersConfig(ConfigFile, "C - World Modifiers"); public GlobalsKeysConfig GlobalsKeys { get; } = new GlobalsKeysConfig(ConfigFile, "D - Global Keys"); public AdvancedConfig Advanced { get; } = InitializeAdvancedConfig(ConfigFile, "Advanced.yml"); public LocalizationConfig Localization { get; } = InitializeAdvancedConfig(ConfigFile, "Localization.yml"); private static readonly HashSet __deprecatedEntries = new HashSet(); public const Emotes DisabledEmote = -1; public const Emotes AnyEmote = -2; private static T InitializeAdvancedConfig(ConfigFile cfg, string filename) where T : class, new() { //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Expected O, but got Unknown //IL_00f2: Unknown result type (might be due to invalid IL or missing references) //IL_00fc: Expected O, but got Unknown string text = Path.Combine(Path.GetDirectoryName(cfg.ConfigFilePath), Path.GetFileNameWithoutExtension(cfg.ConfigFilePath)); string path = Path.Combine(text, filename); T val = new T(); ISerializer val2 = ((BuilderSkeleton)(object)((BuilderSkeleton)new SerializerBuilder()).IncludeNonPublicProperties()).WithTypeInspector((Func)((ITypeInspector x) => new MyTypeInspector(x))).Build(); Directory.CreateDirectory(text); string path2 = Path.ChangeExtension(path, "default.yml"); using (StreamWriter streamWriter = new StreamWriter(path2, append: false)) { streamWriter.WriteLine("# " + Path.GetFileName(path2) + " contains the default values and is overwritten regularly."); streamWriter.WriteLine("# Rename it to " + Path.GetFileName(path) + " if you want to change values."); streamWriter.WriteLine(); WriteYamlHeader(streamWriter); val2.Serialize((TextWriter)streamWriter, (object)val); } if (File.Exists(path)) { try { using StreamReader streamReader = new StreamReader(path); val = ((BuilderSkeleton)(object)((BuilderSkeleton)(object)((BuilderSkeleton)new DeserializerBuilder()).IncludeNonPublicProperties()).EnablePrivateConstructors()).WithTypeInspector((Func)((ITypeInspector x) => new MyTypeInspector(x))).Build().Deserialize((TextReader)streamReader); Main.Instance.Logger.LogInfo("Advanced config loaded from " + Path.GetFileName(path) + ":" + Environment.NewLine + val2.Serialize((object)val)); } catch (Exception arg) { Main.Instance.Logger.LogWarning($"{Path.GetFileName(path)}: {arg}"); } } return val; } private static void WriteYamlHeader(StreamWriter writer) { writer.WriteLine("# IMPORTANT:"); writer.WriteLine("# This file is for advanced tweaks. You are expected to be familiar with YAML and its pitfalls if you decide to edit it."); writer.WriteLine("# Check the log for warnings related to this file and DO NOT open issues asking for help on how to format this file."); writer.WriteLine(); } public static bool IsDeprecated(ConfigEntryBase entry) { return __deprecatedEntries.Contains(entry); } public static ConfigEntry BindEx(ConfigFile config, string section, T defaultValue, string description, AcceptableValueBase? acceptableValues, Deprecated? deprecated, string key) { //IL_0052: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Expected O, but got Unknown Deprecated deprecated2 = deprecated; if ((object)deprecated2 != null) { description = string.Join(Environment.NewLine, "DEPRECATED: " + deprecated2.Reason, description); } ConfigEntry cfg2 = config.Bind(section, key, defaultValue, new ConfigDescription(description, acceptableValues, Array.Empty())); if ((object)deprecated2 != null) { __deprecatedEntries.Add((ConfigEntryBase)(object)cfg2); ModConfig.Initialized += OnInitialized; } return cfg2; void OnInitialized(ConfigFile cfgFile, ModConfig modConfig) { ModConfig modConfig2 = modConfig; if (cfgFile == ((ConfigEntryBase)cfg2).ConfigFile) { ModConfig.Initialized -= OnInitialized; cfg2.SettingChanged += delegate { OnSettingChanged(deprecated2, cfg2, modConfig2); }; OnSettingChanged(deprecated2, cfg2, modConfig2); } } static void OnSettingChanged(Deprecated deprecated, ConfigEntry cfg, ModConfig modCfg) { if (!EqualityComparer.Default.Equals(cfg.Value, (T)((ConfigEntryBase)cfg).DefaultValue)) { deprecated.AdjustConfig(modCfg); Main.Instance.Logger.LogWarning("[" + ((ConfigEntryBase)cfg).Definition.Section + "].[" + ((ConfigEntryBase)cfg).Definition.Key + "] is deprecated: " + deprecated.Reason); } } } [CompilerGenerated] protected ModConfigBase(ModConfigBase original) { ConfigFile = original.ConfigFile; General = original.General; Admins = original.Admins; Signs = original.Signs; MapTables = original.MapTables; Tames = original.Tames; Creatures = original.Creatures; Summons = original.Summons; HostileSummons = original.HostileSummons; Fireplaces = original.Fireplaces; Containers = original.Containers; Smelters = original.Smelters; Windmills = original.Windmills; Carts = original.Carts; Ships = original.Ships; Doors = original.Doors; Players = original.Players; Turrets = original.Turrets; WearNTear = original.WearNTear; CraftingStations = original.CraftingStations; Traders = original.Traders; Plants = original.Plants; Traps = original.Traps; PortalHub = original.PortalHub; World = original.World; TrophySpawner = original.TrophySpawner; NonTeleportableItems = original.NonTeleportableItems; Sleeping = original.Sleeping; Fermenters = original.Fermenters; Networking = original.Networking; Wishbone = original.Wishbone; Skills = original.Skills; WorldModifiers = original.WorldModifiers; GlobalsKeys = original.GlobalsKeys; Advanced = original.Advanced; Localization = original.Localization; } } internal sealed record ModConfig : ModConfigBase { public static event Action? Initialized; public ModConfig(ConfigFile configFile) : base(configFile) { ModConfig.Initialized?.Invoke(configFile, this); } [CompilerGenerated] private ModConfig(ModConfig original) : base((ModConfigBase)original) { } } internal sealed class Peer { private readonly ZNetPeer _peer; [CompilerGenerated] private IPeerInfo? k__BackingField; private static readonly ConditionalWeakTable _cache = new ConditionalWeakTable(); public long m_uid => _peer.m_uid; public Vector3 m_refPos { get { //IL_001b: 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) IPeerInfo? info = Info; if (info == null) { return _peer.m_refPos; } return ((ZDO)info.PlayerZDO).GetPosition(); } } public ZDOID m_characterID => _peer.m_characterID; public bool IsServer => _peer.m_server; public IReadOnlyDictionary m_serverSyncedPlayerData { get { ZNetPeer peer = _peer; if (peer == null || peer.m_server) { return ZNet.instance.m_serverSyncedPlayerData; } return _peer.m_serverSyncedPlayerData; } } public IPeerInfo? Info { get { if (k__BackingField == null) { k__BackingField = Processor.Instance().GetPeerInfo(_peer.m_uid); IPeerInfo? peerInfo = k__BackingField; if (peerInfo != null) { peerInfo.PlayerZDO.Destroyed += delegate { k__BackingField = null; }; } } return k__BackingField; } } public string GetHostName() { return _peer.m_socket.GetHostName() ?? ""; } public override bool Equals(object obj) { return object.Equals(_peer, obj); } public override int GetHashCode() { return ((object)_peer).GetHashCode(); } private Peer(ZNetPeer peer) { _peer = peer; } public static Peer Get(ZNetPeer peer) { return _cache.GetValue(peer, (ZNetPeer x) => new Peer(x)); } } internal sealed record PrefabInfo(GameObject Prefab, IReadOnlyDictionary Components) { public record struct Optional(T? Value) where T : MonoBehaviour; public string PrefabName { get { GameObject prefab = Prefab; return ((prefab != null) ? ((Object)prefab).name : null) ?? ""; } } public Sign? Sign { get; } = Get(Components); public MapTable? MapTable { get; } = Get(Components); public (Tameable Tameable, MonsterAI MonsterAI)? Tameable { get; } = GetTuple<(Tameable, MonsterAI)>(Components); public Fireplace? Fireplace { get; } = Get(Components); public (Container Container, Optional Piece, Optional PieceTable, Optional Incinerator, Optional ZSyncTransform)? Container { get; } = GetTuple<(Container, Optional, Optional, Optional, Optional)>(Components); public (Ship Ship, Piece Piece, ShipControlls ShipControls)? Ship { get; } = GetTuple<(Ship, Piece, ShipControlls)>(Components); public (ItemDrop ItemDrop, Optional ZSyncTransform, Optional Piece, Optional Floating, Optional Fish)? ItemDrop { get; } = GetTuple<(ItemDrop, Optional, Optional, Optional, Optional)>(Components); public Smelter? Smelter { get; } = Get(Components); public ShieldGenerator? ShieldGenerator { get; } = Get(Components); public Windmill? Windmill { get; } = Get(Components); public (Vagon Vagon, Piece Piece)? Vagon { get; } = GetTuple<(Vagon, Piece)>(Components); public Player? Player { get; } = Get(Components); public TeleportWorld? TeleportWorld { get; } = Get(Components); public Door? Door { get; } = Get(Components); public (Turret Turret, Piece Piece, PieceTable PieceTable)? Turret { get; } = GetTuple<(Turret, Piece, PieceTable)>(Components); public (WearNTear WearNTear, Optional Piece, Optional PieceTable)? WearNTear { get; } = GetTuple<(WearNTear, Optional, Optional)>(Components); public CraftingStation? CraftingStation { get; } = Get(Components); public StationExtension? StationExtension { get; } = Get(Components); public Trader? Trader { get; } = Get(Components); public Plant? Plant { get; } = Get(Components); public Pickable? Pickable { get; } = Get(Components); public EggGrow? EggGrow { get; } = Get(Components); public Growup? Growup { get; } = Get(Components); public (Aoe Aoe, Piece Piece, PieceTable PieceTable, Optional Trap)? Trap { get; } = GetTuple<(Aoe, Piece, PieceTable, Optional)>(Components); public Mister? Mister { get; } = Get(Components); public CreatureSpawner? CreatureSpawner { get; } = Get(Components); public SpawnArea? SpawnArea { get; } = Get(Components); public (Humanoid Humanoid, Optional MonsterAI, Optional CharacterDrop)? Humanoid { get; } = GetTuple<(Humanoid, Optional, Optional)>(Components); public (Character Character, Optional CharacterDrop)? Character { get; } = GetTuple<(Character, Optional)>(Components); public EffectArea? EffectArea { get; } = Get(Components); public CookingStation? CookingStation { get; } = Get(Components); public Fermenter? Fermenter { get; } = Get(Components); public SpawnSystem? SpawnSystem { get; } = Get(Components); public LocationProxy? LocationProxy { get; } = Get(Components); public MineRock5? MineRock5 { get; } = Get(Components); public TerrainComp? TerrainComp { get; } = Get(Components); public static PrefabInfo Dummy { get; } = new PrefabInfo(null, ReadOnlyDictionary.Empty); private static T? Get(IReadOnlyDictionary prefabs) where T : MonoBehaviour { if (!prefabs.TryGetValue(typeof(T), out MonoBehaviour value)) { return default(T); } return (T)(object)value; } private static T? GetTuple(IReadOnlyDictionary prefabs) where T : struct, ITuple { Type[] genericTypeArguments = typeof(T).GenericTypeArguments; object[] array = new object[genericTypeArguments.Length]; for (int i = 0; i < genericTypeArguments.Length; i++) { Type type = genericTypeArguments[i]; if (!type.IsGenericType || type.GetGenericTypeDefinition() != typeof(Optional<>)) { if (!prefabs.TryGetValue(type, out MonoBehaviour value)) { return null; } array[i] = value; } else { prefabs.TryGetValue(type.GenericTypeArguments[0], out MonoBehaviour value2); array[i] = Activator.CreateInstance(type, value2); } } return (T)Activator.CreateInstance(typeof(T), array); } [CompilerGenerated] private PrefabInfo(PrefabInfo original) { Prefab = original.Prefab; Components = original.Components; Sign = original.Sign; MapTable = original.MapTable; Tameable = original.Tameable; Fireplace = original.Fireplace; Container = original.Container; Ship = original.Ship; ItemDrop = original.ItemDrop; Smelter = original.Smelter; ShieldGenerator = original.ShieldGenerator; Windmill = original.Windmill; Vagon = original.Vagon; Player = original.Player; TeleportWorld = original.TeleportWorld; Door = original.Door; Turret = original.Turret; WearNTear = original.WearNTear; CraftingStation = original.CraftingStation; StationExtension = original.StationExtension; Trader = original.Trader; Plant = original.Plant; Pickable = original.Pickable; EggGrow = original.EggGrow; Growup = original.Growup; Trap = original.Trap; Mister = original.Mister; CreatureSpawner = original.CreatureSpawner; SpawnArea = original.SpawnArea; Humanoid = original.Humanoid; Character = original.Character; EffectArea = original.EffectArea; CookingStation = original.CookingStation; Fermenter = original.Fermenter; SpawnSystem = original.SpawnSystem; LocationProxy = original.LocationProxy; MineRock5 = original.MineRock5; TerrainComp = original.TerrainComp; } } internal static class PrivateAccessor { private const BindingFlags AccessFlags = BindingFlags.Public | BindingFlags.NonPublic; [CompilerGenerated] private static Func k__BackingField; [CompilerGenerated] private static Func k__BackingField; [CompilerGenerated] private static Func> k__BackingField; [CompilerGenerated] private static Func> k__BackingField; [CompilerGenerated] private static Func> k__BackingField; [CompilerGenerated] private static Func> k__BackingField; [CompilerGenerated] private static Func k__BackingField; [CompilerGenerated] private static Func> k__BackingField; [CompilerGenerated] private static Func, GameObject> k__BackingField; [CompilerGenerated] private static Action k__BackingField; private static Func GetCommandAction { get { Func func = k__BackingField; if (func == null) { ParameterExpression parameterExpression = Expression.Parameter(typeof(ConsoleCommand)); func = (k__BackingField = Expression.Lambda>(Expression.Field(parameterExpression, typeof(ConsoleCommand).GetField("action", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)), new ParameterExpression[1] { parameterExpression }).Compile()); } return func; } } private static Func GetCommandActionFailable { get { Func func = k__BackingField; if (func == null) { ParameterExpression parameterExpression = Expression.Parameter(typeof(ConsoleCommand)); func = (k__BackingField = Expression.Lambda>(Expression.Field(parameterExpression, typeof(ConsoleCommand).GetField("actionFailable", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)), new ParameterExpression[1] { parameterExpression }).Compile()); } return func; } } public static Func> GetServerOptionsGUIPresets => k__BackingField ?? (k__BackingField = Expression.Lambda>>(Expression.Field(null, typeof(ServerOptionsGUI).GetField("m_presets", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)), Array.Empty()).Compile()); public static Func> GetServerOptionsGUIModifiers => k__BackingField ?? (k__BackingField = Expression.Lambda>>(Expression.Field(null, typeof(ServerOptionsGUI).GetField("m_modifiers", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic)), Array.Empty()).Compile()); private static Func> GetZDOManObjectsByID { get { Func> func = k__BackingField; if (func == null) { ParameterExpression parameterExpression = Expression.Parameter(typeof(ZDOMan)); func = (k__BackingField = Expression.Lambda>>(Expression.Field(parameterExpression, typeof(ZDOMan).GetField("m_objectsByID", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)), new ParameterExpression[1] { parameterExpression }).Compile()); } return func; } } private static Func> GetLocalizationStrings { get { Func> func = k__BackingField; if (func == null) { ParameterExpression parameterExpression = Expression.Parameter(typeof(Localization)); func = (k__BackingField = Expression.Lambda>>(Expression.Field(parameterExpression, typeof(Localization).GetField("m_translations", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)), new ParameterExpression[1] { parameterExpression }).Compile()); } return func; } } private static Func GetCurrentEventFunc { get { Func func = k__BackingField; if (func == null) { ParameterExpression parameterExpression = Expression.Parameter(typeof(RandEventSystem)); func = (k__BackingField = Expression.Lambda>(Expression.Field(parameterExpression, typeof(RandEventSystem).GetField("m_randomEvent", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)), new ParameterExpression[1] { parameterExpression }).Compile()); } return func; } } private static Func> GetLocationsByHashFunc { get { Func> func = k__BackingField; if (func == null) { ParameterExpression parameterExpression = Expression.Parameter(typeof(ZoneSystem)); func = (k__BackingField = Expression.Lambda>>(Expression.Field(parameterExpression, typeof(ZoneSystem).GetField("m_locationsByHash", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic)), new ParameterExpression[1] { parameterExpression }).Compile()); } return func; } } private static Func, GameObject> SpawnLocationFunc { get { Func, GameObject> func = k__BackingField; if (func == null) { ParameterExpression parameterExpression = Expression.Parameter(typeof(ZoneSystem)); MethodInfo? method = typeof(ZoneSystem).GetMethod("SpawnLocation", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); Expression[] array = new Expression[6]; ParameterExpression parameterExpression2 = (ParameterExpression)(array[0] = Expression.Parameter(typeof(ZoneLocation))); ParameterExpression parameterExpression3 = (ParameterExpression)(array[1] = Expression.Parameter(typeof(int))); ParameterExpression parameterExpression4 = (ParameterExpression)(array[2] = Expression.Parameter(typeof(Vector3))); ParameterExpression parameterExpression5 = (ParameterExpression)(array[3] = Expression.Parameter(typeof(Quaternion))); ParameterExpression parameterExpression6 = (ParameterExpression)(array[4] = Expression.Parameter(typeof(SpawnMode))); ParameterExpression parameterExpression7 = (ParameterExpression)(array[5] = Expression.Parameter(typeof(List))); func = (k__BackingField = Expression.Lambda, GameObject>>(Expression.Call(parameterExpression, method, array), new ParameterExpression[7] { parameterExpression, parameterExpression2, parameterExpression3, parameterExpression4, parameterExpression5, parameterExpression6, parameterExpression7 }).Compile()); } return func; } } private static Action SendGlobalKeysAction { get { Action action = k__BackingField; if (action == null) { ParameterExpression parameterExpression = Expression.Parameter(typeof(ZoneSystem)); MethodInfo? method = typeof(ZoneSystem).GetMethod("SendGlobalKeys", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); Expression[] array = new Expression[1]; ParameterExpression parameterExpression2 = (ParameterExpression)(array[0] = Expression.Parameter(typeof(long))); action = (k__BackingField = Expression.Lambda>(Expression.Call(parameterExpression, method, array), new ParameterExpression[2] { parameterExpression, parameterExpression2 }).Compile()); } return action; } } public static int ZSyncAnimationZDOSalt { get; } = (int)typeof(ZSyncAnimation).GetField("c_ZDOSalt", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).GetRawConstantValue(); public static int CharacterAnimationHashEncumbered { get; } = (int)typeof(Character).GetField("s_encumbered", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).GetValue(null); public static int CharacterAnimationHashInWater { get; } = (int)typeof(Character).GetField("s_inWater", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).GetValue(null); public static int PlayerAnimationHashCrouching { get; } = (int)typeof(Player).GetField("s_crouching", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).GetValue(null); public static ConsoleEvent? GetAction(this ConsoleCommand command) { return GetCommandAction(command); } public static ConsoleEventFailable? GetActionFailable(this ConsoleCommand command) { return GetCommandActionFailable(command); } private static Dictionary GetObjectsByIDCore(this ZDOMan instance) { return GetZDOManObjectsByID(instance); } public static Dictionary.ValueCollection GetObjects(this ZDOMan instance) { return instance.GetObjectsByIDCore().Values; } public static IReadOnlyDictionary GetStrings(this Localization instance) { return GetLocalizationStrings(instance); } public static RandomEvent? GetCurrentEvent(this RandEventSystem instance) { return GetCurrentEventFunc(instance); } public static IReadOnlyDictionary GetLocationsByHash(this ZoneSystem instance) { return GetLocationsByHashFunc(instance); } public static GameObject SpawnLocation(this ZoneSystem instance, ZoneLocation location, int seed, Vector3 pos, Quaternion rot, SpawnMode mode, List? spawnedGhostObjects = null) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000b: Unknown result type (might be due to invalid IL or missing references) return SpawnLocationFunc(instance, location, seed, pos, rot, mode, spawnedGhostObjects ?? new List()); } public static void SendGlobalKeys(this ZoneSystem instance, long peerID) { SendGlobalKeysAction(instance, peerID); } } } namespace Valheim.ServersideQoL.Processors { internal sealed class ContainerProcessor : Processor { private readonly record struct ContainerSizeConfig(int Width, int Height, bool Growing); private sealed class ContainerState { public HashSet Items { get; } = new HashSet(); public DateTimeOffset LastOwnershipRequest { get; set; } public bool WaitingForResponse { get; set; } public long PreviousOwner { get; set; } public SwapContentRequest? SwapContentRequest { get; set; } } private sealed record SwapContentRequest(long SenderPeerID, ExtendedZDO From, ExtendedZDO? To) { public required DateTimeOffset SwapAfter { get; set; } public IReadOnlyList FromItems { get; } = new <>z__ReadOnlyArray(From.Inventory.Items.ToArray()); [CompilerGenerated] [SetsRequiredMembers] private SwapContentRequest(SwapContentRequest original) { SenderPeerID = original.SenderPeerID; From = original.From; To = original.To; SwapAfter = original.SwapAfter; FromItems = original.FromItems; } } private readonly Dictionary _stackPerItem = new Dictionary(); private readonly Dictionary> _signsByChests = new Dictionary>(); private readonly Dictionary _chestsBySigns = new Dictionary(); private readonly Dictionary _containerSizes = new Dictionary(); private readonly Dictionary _containers = new Dictionary(); private bool _openResponseRegistered; private readonly List _swapContentRequests = new List(); protected override Guid Id { get; } = Guid.Parse("2e74d73e-d1e4-46e2-9885-d608730bd0da"); public IReadOnlyCollection Containers => _containers.Keys; public ConcurrentDictionary> ContainersByItemName { get; } = new ConcurrentDictionary>(); public IReadOnlyDictionary ChestsBySigns => _chestsBySigns; public IReadOnlyDictionary> SignsByChests => _signsByChests; public event Action? ContainerChanged; public override void Initialize(bool firstTime) { base.Initialize(firstTime); foreach (ExtendedZDO key3 in _chestsBySigns.Keys) { key3.Destroy(); } foreach (ExtendedZDO key4 in _signsByChests.Keys) { key4.ResetProcessorDataRevision(this); } _signsByChests.Clear(); _chestsBySigns.Clear(); Processor.UpdateRpcSubscription("OpenRespons", new Func(RPC_OpenResponse), subscribe: false); Processor.UpdateRpcSubscription("RPC_AnimateLever", new Action(RPC_AnimateLever), base.Config.Containers.ObliteratorItemTeleporter.Value != ModConfigBase.ContainersConfig.ObliteratorItemTeleporterOptions.Disabled); Processor.UpdateRpcSubscription("RPC_AnimateLeverReturn", new Action(RPC_AnimateLeverReturn), base.Config.Containers.ObliteratorItemTeleporter.Value != ModConfigBase.ContainersConfig.ObliteratorItemTeleporterOptions.Disabled); _openResponseRegistered = false; _containerSizes.Clear(); foreach (KeyValuePair> containerSize in base.Config.Containers.ContainerSizes) { containerSize.Deconstruct(out var key, out var value); int key2 = key; ConfigEntry val = value; Match match = Regex.Match(val.Value, "^(?\\d+)x(?\\d+)(?\\+)?$"); if (match == null || !match.Success) { base.Logger.LogWarning("Invalid container size config value: " + val.Value); } else { _containerSizes.Add(key2, new ContainerSizeConfig(int.Parse(match.Groups["w"].Value, CultureInfo.InvariantCulture), int.Parse(match.Groups["h"].Value, CultureInfo.InvariantCulture), match.Groups["g"].Success)); } } if (!firstTime) { return; } _stackPerItem.Clear(); _containers.Clear(); ContainersByItemName.Clear(); _swapContentRequests.Clear(); if (base.Config.Containers.ObliteratorItemTeleporter.Value == ModConfigBase.ContainersConfig.ObliteratorItemTeleporterOptions.Disabled) { return; } foreach (ExtendedZDO @object in ZDOMan.instance.GetObjects()) { if (((ZDO)@object).GetPrefab() == Prefabs.Incinerator && @object.Vars.GetCreator(0L) != 0L) { _containers.Add(@object, new ContainerState()); @object.Destroyed += OnChestDestroyed; } } } private void OnChestDestroyed(ExtendedZDO zdo) { if (_containers.Remove(zdo, out ContainerState value)) { foreach (SharedItemDataKey item in value.Items) { if (ContainersByItemName.TryGetValue(item, out ConcurrentHashSet value2)) { value2.Remove(zdo); if (value2.Count == 0) { ContainersByItemName.TryRemove(item, out ConcurrentHashSet _); } } } } if (!_signsByChests.Remove(zdo, out List value4)) { return; } foreach (ExtendedZDO item2 in value4) { _chestsBySigns.Remove(item2); item2.Destroy(); } } private ModConfigBase.ContainersConfig.SignOptions GetSignOptions(int prefab) { if (prefab == Prefabs.WoodChest) { return base.Config.Containers.WoodChestSigns.Value; } if (prefab == Prefabs.ReinforcedChest) { return base.Config.Containers.ReinforcedChestSigns.Value; } if (prefab == Prefabs.BlackmetalChest) { return base.Config.Containers.BlackmetalChestSigns.Value; } if (prefab == Prefabs.Barrel) { return base.Config.Containers.BarrelSigns.Value; } if (prefab == Prefabs.Incinerator) { return base.Config.Containers.ObliteratorSigns.Value; } return ModConfigBase.ContainersConfig.SignOptions.None; } public override bool ClaimExclusive(ExtendedZDO zdo) { return false; } public void RequestOwnership(ExtendedZDO zdo, long playerID, [CallerFilePath] string caller = null, [CallerLineNumber] int callerLineNo = 0) { RequestOwnership(zdo, playerID, _containers[zdo], caller, callerLineNo); } private void RequestOwnership(ExtendedZDO zdo, long playerID, ContainerState state, [CallerFilePath] string caller = null, [CallerLineNumber] int callerLineNo = 0) { if (!zdo.IsOwnerOrUnassigned() && !(DateTimeOffset.UtcNow - state.LastOwnershipRequest < TimeSpan.FromSeconds(1.0))) { if (!_openResponseRegistered && Player.m_localPlayer != null) { _openResponseRegistered = true; Processor.UpdateRpcSubscription("OpenRespons", new Func(RPC_OpenResponse), subscribe: true); } state.LastOwnershipRequest = DateTimeOffset.UtcNow; state.WaitingForResponse = true; state.PreviousOwner = ((ZDO)zdo).GetOwner(); RPC.RequestOpen(zdo, playerID); } } private bool RPC_OpenResponse(ExtendedZDO? zdo, bool granted) { if (zdo == null || !_containers.TryGetValue(zdo, out ContainerState value) || !value.WaitingForResponse) { return true; } value.WaitingForResponse = false; return false; } private void RPC_AnimateLever(ExtendedZDO zdo, RoutedRPCData data) { ExtendedZDO zdo2 = zdo; if (zdo2 == null) { return; } PrefabInfo prefabInfo = zdo2.PrefabInfo; if ((object)prefabInfo == null) { return; } (Container, PrefabInfo.Optional, PrefabInfo.Optional, PrefabInfo.Optional, PrefabInfo.Optional)? container = prefabInfo.Container; if (!container.HasValue) { return; } PrefabInfo.Optional item = container.GetValueOrDefault().Item4; if (item.Value == null) { return; } int tag = zdo2.Vars.GetIntTag(); if (tag != 0 && zdo2.Inventory.Items.Count != 0) { if (!_containers.TryGetValue(zdo2, out ContainerState value)) { _containers.Add(zdo2, value = new ContainerState()); zdo2.Destroyed += OnChestDestroyed; } var (extendedZDO2, containerState2) = (KeyValuePair)(ref _containers.FirstOrDefault>((KeyValuePair x) => x.Key != zdo2 && x.Key.Vars.GetIntTag() == tag)); zdo2.ReleaseOwnership(); extendedZDO2?.ReleaseOwnership(); SwapContentRequest swapContentRequest = new SwapContentRequest(data.m_senderPeerID, zdo2, extendedZDO2) { SwapAfter = DateTimeOffset.UtcNow + TimeSpan.FromSeconds((double)zdo2.PrefabInfo.Container.Value.Incinerator.Value.m_effectDelayMax + 0.2) }; _swapContentRequests.Add(swapContentRequest); value.SwapContentRequest = swapContentRequest; if (containerState2 != null) { containerState2.SwapContentRequest = swapContentRequest; } } } private void RPC_AnimateLeverReturn(ExtendedZDO zdo) { for (int i = 0; i < _swapContentRequests.Count; i++) { SwapContentRequest swapContentRequest = _swapContentRequests[i]; if (swapContentRequest.From == zdo) { swapContentRequest.SwapAfter = DateTimeOffset.UtcNow.AddMilliseconds(200.0); } } } private bool CheckForbiddenItems(IEnumerable from, IEnumerable to) { switch (base.Config.Containers.ObliteratorItemTeleporter.Value) { case ModConfigBase.ContainersConfig.ObliteratorItemTeleporterOptions.EnabledAllItems: return false; case ModConfigBase.ContainersConfig.ObliteratorItemTeleporterOptions.Enabled: if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)30)) { return false; } break; } if (!HasNonTeleportableItem(from)) { return HasNonTeleportableItem(to); } return true; } protected override void PreProcessCore(IEnumerable peers) { for (int num = _swapContentRequests.Count - 1; num >= 0; num--) { SwapContentRequest swapContentRequest = _swapContentRequests[num]; if (((ZDO)swapContentRequest.From).GetOwner() == 0L) { ExtendedZDO? to = swapContentRequest.To; long? num2 = ((to != null) ? new long?(((ZDO)to).GetOwner()) : null); if (!num2.HasValue || num2.GetValueOrDefault() == 0L) { if (!(swapContentRequest.SwapAfter <= DateTimeOffset.UtcNow)) { continue; } if (swapContentRequest.To == null) { Processor.ShowMessage(peers, swapContentRequest.From, base.Config.Localization.Containers.ObliteratorItemTeleporter.TargetNotFound, base.Config.Containers.ObliteratorItemTeleporterMessageType.Value, (TextType)7); } else if (CheckForbiddenItems(swapContentRequest.FromItems, swapContentRequest.To.Inventory.Items)) { Processor.ShowMessage(peers, swapContentRequest.From, base.Config.Localization.Containers.ObliteratorItemTeleporter.ForbiddenItem, base.Config.Containers.ObliteratorItemTeleporterMessageType.Value, (TextType)7); } else { List list = swapContentRequest.To.Inventory.Items.ToList(); swapContentRequest.From.Inventory.Items.Clear(); swapContentRequest.To.Inventory.Items.Clear(); foreach (ItemData fromItem in swapContentRequest.FromItems) { swapContentRequest.To.Inventory.Items.Add(fromItem); } foreach (ItemData item in list) { swapContentRequest.From.Inventory.Items.Add(item); } swapContentRequest.To.Inventory.Save(); swapContentRequest.From.Inventory.Save(); Processor.ShowMessage(peers, swapContentRequest.From, base.Config.Localization.Containers.ObliteratorItemTeleporter.ItemsTeleported, base.Config.Containers.ObliteratorItemTeleporterMessageType.Value, (TextType)2); Processor.ShowMessage(peers, swapContentRequest.To, base.Config.Localization.Containers.ObliteratorItemTeleporter.ItemsTeleported, base.Config.Containers.ObliteratorItemTeleporterMessageType.Value, (TextType)2); } swapContentRequest.From.SetOwner(swapContentRequest.SenderPeerID); _swapContentRequests.RemoveAt(num); continue; } } swapContentRequest.From.ReleaseOwnership(); swapContentRequest.To?.ReleaseOwnership(); } } protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { //IL_0378: Unknown result type (might be due to invalid IL or missing references) //IL_037d: Unknown result type (might be due to invalid IL or missing references) //IL_0380: Unknown result type (might be due to invalid IL or missing references) //IL_0385: Unknown result type (might be due to invalid IL or missing references) //IL_0389: 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_03d3: Unknown result type (might be due to invalid IL or missing references) //IL_03d5: Unknown result type (might be due to invalid IL or missing references) //IL_03da: Unknown result type (might be due to invalid IL or missing references) //IL_03e6: Unknown result type (might be due to invalid IL or missing references) //IL_03eb: Unknown result type (might be due to invalid IL or missing references) //IL_0419: 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_041d: Unknown result type (might be due to invalid IL or missing references) //IL_0422: Unknown result type (might be due to invalid IL or missing references) //IL_042e: Unknown result type (might be due to invalid IL or missing references) //IL_0433: 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_0469: Unknown result type (might be due to invalid IL or missing references) //IL_046b: Unknown result type (might be due to invalid IL or missing references) //IL_0470: Unknown result type (might be due to invalid IL or missing references) //IL_047c: Unknown result type (might be due to invalid IL or missing references) //IL_0481: Unknown result type (might be due to invalid IL or missing references) //IL_04ed: Unknown result type (might be due to invalid IL or missing references) //IL_04f2: Unknown result type (might be due to invalid IL or missing references) //IL_04b5: Unknown result type (might be due to invalid IL or missing references) //IL_04b7: 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_04ca: Unknown result type (might be due to invalid IL or missing references) //IL_04cf: Unknown result type (might be due to invalid IL or missing references) //IL_051e: 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_055f: Unknown result type (might be due to invalid IL or missing references) //IL_0572: Unknown result type (might be due to invalid IL or missing references) //IL_0958: Unknown result type (might be due to invalid IL or missing references) //IL_0e92: Unknown result type (might be due to invalid IL or missing references) //IL_0e97: 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_0c32: Unknown result type (might be due to invalid IL or missing references) //IL_0da1: Unknown result type (might be due to invalid IL or missing references) //IL_0da6: Unknown result type (might be due to invalid IL or missing references) (Container, PrefabInfo.Optional, PrefabInfo.Optional, PrefabInfo.Optional, PrefabInfo.Optional)? container = zdo.PrefabInfo.Container; ContainerState value2; ExtendedZDO.ComponentFieldAccessor componentFieldAccessor; IZDOInventory inventory; int width; int height; ContainerSizeConfig value3; if (container.HasValue) { (Container, PrefabInfo.Optional, PrefabInfo.Optional, PrefabInfo.Optional, PrefabInfo.Optional) valueOrDefault = container.GetValueOrDefault(); PrefabInfo.Optional item = valueOrDefault.Item2; if (item.Value != null) { PrefabInfo.Optional item2 = valueOrDefault.Item3; if (item2.Value != null) { long? num = zdo.Vars.GetCreator(0L); long? num2 = num; if (!num2.HasValue || num2.GetValueOrDefault() != 0L) { if (zdo.Vars.GetReturnContentToCreator()) { if (Processor.Instance().PlayersByID.TryGetValue(num.Value, out ExtendedZDO value)) { if (zdo.Inventory.Items.Count == 0) { base.DestroyZdo = true; } else if (((ZDO)zdo).GetOwner() != ((ZDO)value).GetOwner()) { zdo.SetOwner(((ZDO)value).GetOwner()); } else { RPC.TakeAllResponse(zdo, granted: true); } } return false; } if (!_containers.TryGetValue(zdo, out value2)) { _containers.Add(zdo, value2 = new ContainerState()); zdo.Destroyed += OnChestDestroyed; } if ((object)value2.SwapContentRequest != null) { if (!(value2.SwapContentRequest.SwapAfter < DateTimeOffset.UtcNow)) { return false; } value2.SwapContentRequest = null; } componentFieldAccessor = zdo.Fields(getUnknownComponent: false); inventory = zdo.Inventory; width = inventory.Inventory.GetWidth(); height = inventory.Inventory.GetHeight(); int height2; int num3; int num4; if (!_containerSizes.TryGetValue(((ZDO)zdo).GetPrefab(), out value3)) { value3 = new ContainerSizeConfig(width, height, Growing: false); } else { int width2 = value3.Width; height2 = value3.Height; num3 = width; num4 = height; if (width2 != num3 || height2 != num4) { IZDOInventory inventory2 = zdo.Inventory; if (inventory2 != null) { IList items = inventory2.Items; if (items != null && items.Count == 0) { componentFieldAccessor.Set(() => (Container x) => x.m_width, width = value3.Width, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\ContainerProcessor.cs", 307); componentFieldAccessor.Set(() => (Container x) => x.m_height, height = value3.Height, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\ContainerProcessor.cs", 308); base.RecreateZdo = true; container = zdo.PrefabInfo.Container; if (container.HasValue) { PrefabInfo.Optional item3 = container.GetValueOrDefault().Item5; if (item3.Value != null) { zdo.ReleaseOwnershipInternal(); } } return false; } } } } ModConfigBase.ContainersConfig.SignOptions signOptions = GetSignOptions(((ZDO)zdo).GetPrefab()); if (signOptions != 0 && !_signsByChests.ContainsKey(zdo) && base.Config.Advanced.Containers.ChestSignOffsets.TryGetValue(((ZDO)zdo).GetPrefab(), out ModConfigBase.AdvancedConfig.ContainerConfig.ChestSignOffset value4)) { string text = zdo.Vars.GetText(null); if (text == null) { if (!zdo.IsOwnerOrUnassigned()) { RequestOwnership(zdo, 0L, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\ContainerProcessor.cs", 324); return false; } zdo.Vars.SetText(text = base.Config.Containers.ChestSignsDefaultText.Value, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\ContainerProcessor.cs", 327); } Vector3 position = ((ZDO)zdo).GetPosition(); Quaternion rotation = ((ZDO)zdo).GetRotation(); float num5 = ((Quaternion)(ref rotation)).eulerAngles.y + 90f; List list = new List(); position.y += value4.Top / 2f; if (signOptions.HasFlag(ModConfigBase.ContainersConfig.SignOptions.Left)) { list.Add(PlacePiece(position + rotation * Vector3.right * value4.Left, Prefabs.Sign, num5)); } if (signOptions.HasFlag(ModConfigBase.ContainersConfig.SignOptions.Right)) { list.Add(PlacePiece(position + rotation * Vector3.left * value4.Right, Prefabs.Sign, num5 + 180f)); } if (signOptions.HasFlag(ModConfigBase.ContainersConfig.SignOptions.Front)) { list.Add(PlacePiece(position + rotation * Vector3.forward * value4.Front, Prefabs.Sign, num5 + 270f)); } if (signOptions.HasFlag(ModConfigBase.ContainersConfig.SignOptions.Back)) { list.Add(PlacePiece(position + rotation * Vector3.back * value4.Back, Prefabs.Sign, num5 + 90f)); } position = ((ZDO)zdo).GetPosition(); position.y += value4.Top; if (signOptions.HasFlag(ModConfigBase.ContainersConfig.SignOptions.TopLongitudinal)) { list.Add(PlacePiece(position, Prefabs.Sign, Quaternion.Euler(-90f, num5 - 90f, 0f))); } if (signOptions.HasFlag(ModConfigBase.ContainersConfig.SignOptions.TopLateral)) { list.Add(PlacePiece(position, Prefabs.Sign, Quaternion.Euler(-90f, num5, 0f))); } _signsByChests.Add(zdo, list); foreach (ExtendedZDO item4 in list) { _chestsBySigns.Add(item4, zdo); item4.Vars.SetText(text, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\ContainerProcessor.cs", 352); item4.Fields(getUnknownComponent: false).Set(() => (WearNTear x) => x.m_supports, value: false, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\ContainerProcessor.cs", 353); } } if (zdo.Vars.GetInUse()) { return true; } if (inventory != null) { IList items = inventory.Items; if (items != null && items.Count == 0) { this.ContainerChanged?.Invoke(zdo); return true; } } bool flag = true; if (value3.Growing) { flag = false; ItemDataKey itemDataKey = new ItemDataKey(inventory.Items[0]); int num6 = 1; while (!flag && num6 < inventory.Items.Count) { flag = itemDataKey != new ItemDataKey(inventory.Items[num6]); num6++; } if (!flag) { value3 = value3 with { Height = Math.Max(value3.Height, Mathf.CeilToInt((float)inventory.Items.Count / (float)value3.Width) + 1) }; } } int num7 = width; num4 = height; num3 = value3.Width; height2 = value3.Height; if (num7 != num3 || num4 != height2) { base.RecreateZdo = true; if (flag && inventory.Items.Count > value3.Width * value3.Height) { bool flag2 = false; int num8 = value3.Height; while (!flag2 && num8 <= height) { int num9 = value3.Width; while (!flag2 && num9 <= width) { if (inventory.Items.Count <= num9 * num8) { flag2 = true; value3 = value3 with { Width = num9, Height = num8 }; } num9++; } num8++; } if (flag2) { int num10 = width; height2 = height; num3 = value3.Width; num4 = value3.Height; if (num10 != num3 || height2 != num4) { goto IL_07ff; } } base.RecreateZdo = false; } goto IL_07ff; } goto IL_088e; } } } } base.UnregisterZdoProcessor = true; return false; IL_07ff: if (base.RecreateZdo) { componentFieldAccessor.Set(() => (Container x) => x.m_width, width = value3.Width, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\ContainerProcessor.cs", 408); componentFieldAccessor.Set(() => (Container x) => x.m_height, height = value3.Height, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\ContainerProcessor.cs", 409); } goto IL_088e; IL_088e: bool flag3 = false; ItemData val = null; _stackPerItem.Clear(); foreach (ItemData item5 in from x in inventory.Items orderby (!x.IsEquipable()) ? 1 : 0, x.m_shared.m_name, x.m_stack descending select x) { value2.Items.Add(item5.m_shared); if ((int)zdo.PrefabInfo.Container.Value.Container.m_privacy != 0) { ConcurrentHashSet orAdd = ContainersByItemName.GetOrAdd(item5.m_shared, (SharedItemDataKey _) => new ConcurrentHashSet()); orAdd.Add(zdo); } if (!base.Config.Containers.AutoSort.Value && !base.RecreateZdo) { continue; } if (val != null && new ItemDataKey(item5) == val) { flag3 = true; if (!zdo.IsOwnerOrUnassigned()) { break; } int num11 = Math.Min(item5.m_stack, val.m_shared.m_maxStackSize - val.m_stack); ItemData obj = val; obj.m_stack += num11; item5.m_stack -= num11; } if (item5.m_stack != 0) { if (!_stackPerItem.TryGetValue(item5, out var value5)) { value5 = 0; } _stackPerItem[item5] = value5 + 1; if (item5.m_stack < item5.m_shared.m_maxStackSize) { val = item5; } } } if (flag3 && zdo.IsOwnerOrUnassigned()) { for (int num12 = inventory.Items.Count - 1; num12 >= 0; num12--) { if (inventory.Items[num12].m_stack == 0) { inventory.Items.RemoveAt(num12); } } } if (_stackPerItem.Count > 0) { if (_stackPerItem.Values.Sum((int x) => (int)Math.Ceiling((double)x / (double)width)) <= height) { int num13 = -1; int num14 = 0; ItemDataKey? itemDataKey2 = null; foreach (ItemData item6 in from x in inventory.Items orderby (!x.IsEquipable()) ? 1 : 0, x.m_shared.m_name, x.m_stack descending select x) { if (++num13 >= width || (itemDataKey2.HasValue && itemDataKey2 != item6)) { num13 = 0; num14++; } if (item6.m_gridPos.x != num13 || item6.m_gridPos.y != num14) { flag3 = true; if (zdo.IsOwnerOrUnassigned()) { item6.m_gridPos = new Vector2i(num13, num14); } } itemDataKey2 = item6; } } else if (_stackPerItem.Values.Sum((int x) => (int)Math.Ceiling((double)x / (double)height)) <= width) { int num15 = 0; int num16 = height; ItemDataKey? itemDataKey3 = null; foreach (ItemData item7 in from x in inventory.Items orderby (!x.IsEquipable()) ? 1 : 0, x.m_shared.m_name, x.m_stack descending select x) { if (--num16 < 0 || (itemDataKey3.HasValue && itemDataKey3 != item7)) { num16 = height - 1; num15++; } if (item7.m_gridPos.x != num15 || item7.m_gridPos.y != num16) { flag3 = true; if (zdo.IsOwnerOrUnassigned()) { item7.m_gridPos = new Vector2i(num15, num16); } } itemDataKey3 = item7; } } else { int num17 = 0; int num18 = 0; foreach (ItemData item8 in from x in inventory.Items orderby (!x.IsEquipable()) ? 1 : 0, x.m_shared.m_name, x.m_stack descending select x) { if (item8.m_gridPos.x != num17 || item8.m_gridPos.y != num18) { flag3 = true; if (zdo.IsOwnerOrUnassigned()) { item8.m_gridPos = new Vector2i(num17, num18); } } if (++num17 >= width) { num17 = 0; num18++; } } } } if (flag3 || base.RecreateZdo) { if (!zdo.IsOwnerOrUnassigned()) { base.RecreateZdo = false; RequestOwnership(zdo, zdo.Vars.GetCreator(0L), value2, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\ContainerProcessor.cs", 542); } else if (flag3) { inventory.Save(); Processor.ShowMessage(peers, zdo, base.Config.Localization.Containers.FormatContainerSorted(zdo.PrefabInfo.Container.Value.Container.m_name), base.Config.Containers.SortedMessageType.Value, (TextType)0); } } if (!base.RecreateZdo) { this.ContainerChanged?.Invoke(zdo); } else { container = zdo.PrefabInfo.Container; if (container.HasValue) { PrefabInfo.Optional item3 = container.GetValueOrDefault().Item5; if (item3.Value != null) { zdo.ReleaseOwnership(); } } } return true; } public ExtendedZDO? GetClosestContainer(Vector3 pos, float maxDist = float.PositiveInfinity, long playerID = 0L) { //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_0058: Unknown result type (might be due to invalid IL or missing references) if (maxDist <= 0f) { return null; } float num = maxDist * maxDist; ExtendedZDO result = null; foreach (ExtendedZDO key in _containers.Keys) { if (playerID != 0L) { (Container, PrefabInfo.Optional, PrefabInfo.Optional, PrefabInfo.Optional, PrefabInfo.Optional)? container = key.PrefabInfo.Container; if (container.HasValue) { Container item = container.GetValueOrDefault().Item1; if (item != null && (int)item.m_privacy == 0 && key.Vars.GetCreator(0L) != playerID) { continue; } } } float num2 = Utils.DistanceSqr(((ZDO)key).GetPosition(), pos); if (!(num2 >= num)) { result = key; num = num2; } } return result; } } internal sealed class CraftingStationProcessor : Processor { protected override Guid Id { get; } = Guid.Parse("a04a766c-a580-470a-9e6c-758a6ae7ccdb"); protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { base.UnregisterZdoProcessor = true; if (zdo.PrefabInfo.CraftingStation != null) { if (!base.Config.CraftingStations.StationConfig.TryGetValue(zdo.PrefabInfo.CraftingStation, out ModConfigBase.CraftingStationsConfig.StationCfg value)) { return false; } ExtendedZDO.ComponentFieldAccessor componentFieldAccessor = zdo.Fields(getUnknownComponent: false); if (value.BuildRange != null && componentFieldAccessor.UpdateValue(() => (CraftingStation x) => x.m_rangeBuild, value.BuildRange.Value, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\CraftingStationProcessor.cs", 16)) { base.RecreateZdo = true; } if (value.ExtraBuildRangePerLevel != null && componentFieldAccessor.UpdateValue(() => (CraftingStation x) => x.m_extraRangePerLevel, value.ExtraBuildRangePerLevel.Value, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\CraftingStationProcessor.cs", 18)) { base.RecreateZdo = true; } } else if (zdo.PrefabInfo.StationExtension != null) { if (!base.Config.CraftingStations.StationConfig.TryGetValue(zdo.PrefabInfo.StationExtension.m_craftingStation, out ModConfigBase.CraftingStationsConfig.StationCfg value2) || value2.MaxExtensionDistance == null) { return false; } ExtendedZDO.ComponentFieldAccessor componentFieldAccessor2 = zdo.Fields(getUnknownComponent: false); if (float.IsNaN(value2.MaxExtensionDistance.Value)) { componentFieldAccessor2.Reset(() => (StationExtension x) => x.m_maxStationDistance, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\CraftingStationProcessor.cs", 27); } else if (componentFieldAccessor2.UpdateValue(() => (StationExtension x) => x.m_maxStationDistance, value2.MaxExtensionDistance.Value, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\CraftingStationProcessor.cs", 28)) { base.RecreateZdo = true; } } return false; } } [Processor(Priority = 1)] internal sealed class CreatureLevelUpProcessor : Processor { private record SpawnData(int Prefab, int MinLevel, int MaxLevel, float LevelUpChance); private sealed record SpawnSystemData(SpawnData Data, Biome? BiomeOverwrite) : SpawnData(StringExtensionMethods.GetStableHashCode(((Object)Data.m_prefab).name, true), Data.m_minLevel, Data.m_maxLevel, Data.m_overrideLevelupChance); private sealed class SectorState { public sealed record SpawnAreaData : SpawnData { public ZDOID ID { get; init; } public Vector3 Position { get; init; } public Biome Biome { get; init; } public float Radius { get; init; } public SpawnAreaData(ZDOID ID, Vector3 Position, Biome Biome, float Radius, int Prefab, int MinLevel, int MaxLevel, float LevelUpChance) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: 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) this.ID = ID; this.Position = Position; this.Biome = Biome; this.Radius = Radius; base..ctor(Prefab, MinLevel, MaxLevel, LevelUpChance); } [CompilerGenerated] protected override bool PrintMembers(StringBuilder builder) { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_0028: 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_004f: 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_0076: Unknown result type (might be due to invalid IL or missing references) if (base.PrintMembers(builder)) { builder.Append(", "); } builder.Append("ID = "); ZDOID iD = ID; builder.Append(((object)(ZDOID)(ref iD)).ToString()); builder.Append(", Position = "); Vector3 position = Position; builder.Append(((object)(Vector3)(ref position)).ToString()); builder.Append(", Biome = "); Biome biome = Biome; builder.Append(((object)(Biome)(ref biome)).ToString()); builder.Append(", Radius = "); builder.Append(Radius.ToString()); return true; } [CompilerGenerated] public void Deconstruct(out ZDOID ID, out Vector3 Position, out Biome Biome, out float Radius, out int Prefab, out int MinLevel, out int MaxLevel, out float LevelUpChance) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000e: 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_001a: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected I4, but got Unknown ID = this.ID; Position = this.Position; Biome = (Biome)(int)this.Biome; Radius = this.Radius; Prefab = base.Prefab; MinLevel = base.MinLevel; MaxLevel = base.MaxLevel; LevelUpChance = base.LevelUpChance; } } public Dictionary> CreatureSpawnersBySpawned { get; } = new Dictionary>(); public Dictionary> SpawnAreasBySpawned { get; } = new Dictionary>(); } private sealed record EventInfo(Biome Biome) { public Dictionary SpawnData { get; } = new Dictionary(); public HashSet SpawnAreas { get; } = new HashSet(); [CompilerGenerated] private bool PrintMembers(StringBuilder builder) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0018: Unknown result type (might be due to invalid IL or missing references) RuntimeHelpers.EnsureSufficientExecutionStack(); builder.Append("Biome = "); Biome biome = Biome; builder.Append(((object)(Biome)(ref biome)).ToString()); builder.Append(", SpawnData = "); builder.Append(SpawnData); builder.Append(", SpawnAreas = "); builder.Append(SpawnAreas); return true; } [CompilerGenerated] public void Deconstruct(out Biome Biome) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Expected I4, but got Unknown Biome = (Biome)(int)this.Biome; } } private readonly Dictionary _levelIncreasePerBiome = new Dictionary(); private readonly Dictionary _sectorStates = new Dictionary(); private readonly Dictionary<(Biome, int Prefab), List> _spawnData = new Dictionary<(Biome, int), List>(); private readonly Dictionary _spawnDataByEvent = new Dictionary(); protected override Guid Id { get; } = Guid.Parse("26c57b62-c9be-458a-8d2f-18b140f483fb"); public override void Initialize(bool firstTime) { base.Initialize(firstTime); if (firstTime) { _sectorStates.Clear(); _spawnData.Clear(); } ZoneSystemSendGlobalKeys.GlobalKeysChanged -= InitializeData; if (base.Config.Creatures.MaxLevelIncrease.Value > 0 || base.Config.Creatures.MaxLevelIncreasePerDefeatedBoss.Value > 0) { InitializeData(); ZoneSystemSendGlobalKeys.GlobalKeysChanged += InitializeData; } } private void InitializeData() { //IL_0072: 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_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00ec: Unknown result type (might be due to invalid IL or missing references) //IL_01bc: 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_01c5: Unknown result type (might be due to invalid IL or missing references) //IL_01cf: 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_0212: Unknown result type (might be due to invalid IL or missing references) //IL_0252: Unknown result type (might be due to invalid IL or missing references) _levelIncreasePerBiome.Clear(); Dictionary dictionary = new Dictionary(); if (base.Config.Creatures.MaxLevelIncreasePerDefeatedBoss.Value > 0) { int num = 0; foreach (var (val3, val4) in SharedProcessorState.BossesByBiome.OrderByDescending, float>((KeyValuePair x) => x.Value.m_health)) { if (ZoneSystem.instance.GetGlobalKey(val4.m_defeatSetGlobalKey)) { num += base.Config.Creatures.MaxLevelIncreasePerDefeatedBoss.Value; } _levelIncreasePerBiome.Add(val3, num); dictionary.Add(val4.m_defeatSetGlobalKey, val3); } if (_levelIncreasePerBiome.TryGetValue(base.Config.Creatures.TreatOceanAs.Value, out var value)) { _levelIncreasePerBiome.Add((Biome)256, value); } } _spawnData.Clear(); foreach (SpawnData item in ZoneSystem.instance.m_zoneCtrlPrefab.GetComponent().m_spawnLists.SelectMany((SpawnSystemList x) => x.m_spawners)) { if (!item.m_enabled || item.m_prefab.GetComponent() == null || (!string.IsNullOrEmpty(item.m_requiredGlobalKey) && !ZoneSystem.instance.GetGlobalKey(item.m_requiredGlobalKey))) { continue; } foreach (Biome acceptableValue in ModConfigBase.AcceptableEnum.Default.AcceptableValues) { if (((Enum)item.m_biome).HasFlag((Enum)(object)acceptableValue)) { int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)item.m_prefab).name, true); if (!_spawnData.TryGetValue((acceptableValue, stableHashCode), out List value2)) { _spawnData.Add((acceptableValue, stableHashCode), value2 = new List()); } value2.Add(new SpawnSystemData(item, dictionary.TryGetValue(item.m_requiredGlobalKey ?? "", out var value3) ? new Biome?(value3) : null)); } } } foreach (List value4 in _spawnData.Values) { value4.Sort((SpawnSystemData a, SpawnSystemData b) => b.MaxLevel - a.MaxLevel); } } protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: 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_01ab: Unknown result type (might be due to invalid IL or missing references) //IL_01b0: Unknown result type (might be due to invalid IL or missing references) //IL_01b5: Unknown result type (might be due to invalid IL or missing references) //IL_01ba: Unknown result type (might be due to invalid IL or missing references) //IL_01bc: 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_01eb: Unknown result type (might be due to invalid IL or missing references) //IL_01f0: Unknown result type (might be due to invalid IL or missing references) //IL_01f5: Unknown result type (might be due to invalid IL or missing references) //IL_0206: Unknown result type (might be due to invalid IL or missing references) //IL_0207: 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_032a: Unknown result type (might be due to invalid IL or missing references) //IL_020e: 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_0218: Unknown result type (might be due to invalid IL or missing references) //IL_0485: 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_0060: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Unknown result type (might be due to invalid IL or missing references) //IL_0066: Invalid comparison between Unknown and I4 //IL_0337: 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_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Invalid comparison between Unknown and I4 //IL_0471: Unknown result type (might be due to invalid IL or missing references) //IL_0254: Unknown result type (might be due to invalid IL or missing references) //IL_026c: Unknown result type (might be due to invalid IL or missing references) //IL_0271: Unknown result type (might be due to invalid IL or missing references) //IL_0276: Unknown result type (might be due to invalid IL or missing references) //IL_027d: Unknown result type (might be due to invalid IL or missing references) //IL_0282: Unknown result type (might be due to invalid IL or missing references) //IL_0287: Unknown result type (might be due to invalid IL or missing references) //IL_028b: Unknown result type (might be due to invalid IL or missing references) //IL_02a3: 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_02b4: Unknown result type (might be due to invalid IL or missing references) //IL_02b9: Unknown result type (might be due to invalid IL or missing references) //IL_02be: Unknown result type (might be due to invalid IL or missing references) //IL_02c1: Unknown result type (might be due to invalid IL or missing references) //IL_02c6: Unknown result type (might be due to invalid IL or missing references) //IL_02c8: Unknown result type (might be due to invalid IL or missing references) //IL_02cf: Unknown result type (might be due to invalid IL or missing references) //IL_0355: Unknown result type (might be due to invalid IL or missing references) //IL_02d8: Unknown result type (might be due to invalid IL or missing references) //IL_02df: 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_02e8: Unknown result type (might be due to invalid IL or missing references) //IL_02ef: Unknown result type (might be due to invalid IL or missing references) //IL_02f8: Unknown result type (might be due to invalid IL or missing references) //IL_02ff: Unknown result type (might be due to invalid IL or missing references) //IL_030a: Unknown result type (might be due to invalid IL or missing references) //IL_030f: Unknown result type (might be due to invalid IL or missing references) //IL_031a: Unknown result type (might be due to invalid IL or missing references) //IL_032a: Expected I4, but got Unknown //IL_03f3: Unknown result type (might be due to invalid IL or missing references) //IL_03f9: Unknown result type (might be due to invalid IL or missing references) //IL_03fe: Unknown result type (might be due to invalid IL or missing references) base.UnregisterZdoProcessor = true; PrefabInfo prefabInfo = zdo.PrefabInfo; if ((object)prefabInfo != null) { CreatureSpawner creatureSpawner = prefabInfo.CreatureSpawner; if (creatureSpawner == null) { SpawnArea spawnArea = prefabInfo.SpawnArea; if (spawnArea == null) { (Humanoid, PrefabInfo.Optional, PrefabInfo.Optional)? humanoid = prefabInfo.Humanoid; if (humanoid.HasValue) { var (val, _, _) = humanoid.GetValueOrDefault(); if (val != null) { Faction faction = ((Character)val).m_faction; if ((int)faction != 11) { LevelUpCharacter(zdo); goto IL_04a2; } } } (Character, PrefabInfo.Optional)? character = prefabInfo.Character; if (character.HasValue) { var (val2, _) = character.GetValueOrDefault(); if (val2 != null) { Faction faction2 = val2.m_faction; if ((int)faction2 != 11) { LevelUpCharacter(zdo); } } } } else { Vector2s zone = ZoneSystem.GetZone(((ZDO)zdo).GetPosition() - new Vector3(zdo.PrefabInfo.SpawnArea.m_spawnRadius, 0f, zdo.PrefabInfo.SpawnArea.m_spawnRadius)); Vector2s zone2 = ZoneSystem.GetZone(((ZDO)zdo).GetPosition() + new Vector3(zdo.PrefabInfo.SpawnArea.m_spawnRadius, 0f, zdo.PrefabInfo.SpawnArea.m_spawnRadius)); Biome val3 = (Biome)zdo.Vars.GetLevel(0); if ((int)val3 == 0) { val3 = Processor.GetBiome(((ZDO)zdo).GetPosition()); RandomEvent currentEvent = RandEventSystem.instance.GetCurrentEvent(); if (currentEvent != null && GetEventInfo(currentEvent, out EventInfo eventInfo) && eventInfo.SpawnAreas.Contains(((ZDO)zdo).GetPrefab())) { Vector2s val4 = ZoneSystem.GetZone(currentEvent.m_pos - new Vector3(currentEvent.m_eventRange, 0f, currentEvent.m_eventRange)) - new Vector2s(1, 1); Vector2s val5 = ZoneSystem.GetZone(currentEvent.m_pos + new Vector3(currentEvent.m_eventRange, 0f, currentEvent.m_eventRange)) + new Vector2s(1, 1); Vector2s sector = ((ZDO)zdo).GetSector(); if (sector.x >= val4.x && sector.x <= val5.x && sector.y >= val4.y && sector.y <= val5.y) { val3 = eventInfo.Biome; zdo.Vars.SetLevel((int)val3, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\CreatureLevelUpProcessor.cs", 144); } } } Vector2s key = default(Vector2s); for (short num = zone.x; num <= zone2.x; num++) { for (short num2 = zone.y; num2 <= zone2.y; num2++) { ((Vector2s)(ref key))..ctor(num, num2); if (!_sectorStates.TryGetValue(key, out SectorState value)) { _sectorStates.Add(key, value = new SectorState()); } foreach (SpawnData prefab in zdo.PrefabInfo.SpawnArea.m_prefabs) { int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)prefab.m_prefab).name, true); if (!value.SpawnAreasBySpawned.TryGetValue(stableHashCode, out List list2)) { value.SpawnAreasBySpawned.Add(stableHashCode, list2 = new List()); } list2.Add(new SectorState.SpawnAreaData(((ZDO)zdo).m_uid, ((ZDO)zdo).GetPosition(), val3, zdo.PrefabInfo.SpawnArea.m_spawnRadius, stableHashCode, prefab.m_minLevel, prefab.m_maxLevel, zdo.PrefabInfo.SpawnArea.m_levelupChance)); zdo.Destroyed += delegate(ExtendedZDO x) { ExtendedZDO x2 = x; list2.RemoveAll((SectorState.SpawnAreaData y) => y.ID == ((ZDO)x2).m_uid); }; } } } } } else { LevelUpSpawner(zdo); if (!base.RecreateZdo) { Vector2s sector2 = ((ZDO)zdo).GetSector(); if (!_sectorStates.TryGetValue(sector2, out SectorState value2)) { _sectorStates.Add(sector2, value2 = new SectorState()); } int stableHashCode2 = StringExtensionMethods.GetStableHashCode(((Object)zdo.PrefabInfo.CreatureSpawner.m_creaturePrefab).name, true); if (!value2.CreatureSpawnersBySpawned.TryGetValue(stableHashCode2, out List list)) { value2.CreatureSpawnersBySpawned.Add(stableHashCode2, list = new List()); } if (!list.Contains(zdo)) { list.Add(zdo); zdo.Destroyed += delegate(ExtendedZDO x) { list.Remove(x); }; } } } } goto IL_04a2; IL_04a2: return false; } private void LevelUpSpawner(ExtendedZDO zdo) { //IL_0146: 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_0174: 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_015c: 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_0165: Unknown result type (might be due to invalid IL or missing references) //IL_0087: Unknown result type (might be due to invalid IL or missing references) //IL_008c: 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_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_00a2: 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) Biome? val = null; ExtendedZDO.ComponentFieldAccessor componentFieldAccessor = zdo.Fields(getUnknownComponent: false); if (zdo.PrefabInfo.CreatureSpawner.m_respawnTimeMinuts <= 0f) { float num = base.Config.Creatures.RespawnOneTimeSpawnsAfter.Value; if (num > 0f) { if (base.Config.Creatures.RespawnOneTimeSpawnsCondition.Value == ModConfigBase.CreaturesConfig.RespawnOneTimeSpawnsConditions.Never) { num = 0f; } else if (base.Config.Creatures.RespawnOneTimeSpawnsCondition.Value == ModConfigBase.CreaturesConfig.RespawnOneTimeSpawnsConditions.AfterBossDefeated) { Biome valueOrDefault = val.GetValueOrDefault(); if (!val.HasValue) { valueOrDefault = Processor.GetBiome(((ZDO)zdo).GetPosition()); val = valueOrDefault; } if (!SharedProcessorState.BossesByBiome.TryGetValue(val.Value, out Character value) || !ZoneSystem.instance.GetGlobalKey(value.m_defeatSetGlobalKey)) { num = 0f; } } } if (componentFieldAccessor.UpdateValue(() => (CreatureSpawner x) => x.m_respawnTimeMinuts, num, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\CreatureLevelUpProcessor.cs", 202)) { base.RecreateZdo = true; } } int num2 = base.Config.Creatures.MaxLevelIncrease.Value; if (base.Config.Creatures.MaxLevelIncreasePerDefeatedBoss.Value > 0) { Biome valueOrDefault = val.GetValueOrDefault(); if (!val.HasValue) { valueOrDefault = Processor.GetBiome(((ZDO)zdo).GetPosition()); val = valueOrDefault; } if (_levelIncreasePerBiome.TryGetValue(val.Value, out var value2)) { num2 += value2; } } int num3 = zdo.PrefabInfo.CreatureSpawner.m_maxLevel + num2; if (componentFieldAccessor.UpdateValue(() => (CreatureSpawner x) => x.m_maxLevel, num3, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\CreatureLevelUpProcessor.cs", 215)) { base.RecreateZdo = true; } float levelupChance = zdo.PrefabInfo.CreatureSpawner.m_levelupChance; int num4 = num3 - zdo.PrefabInfo.CreatureSpawner.m_minLevel; if (num4 > 0) { levelupChance /= 100f; if (zdo.PrefabInfo.CreatureSpawner.m_maxLevel > zdo.PrefabInfo.CreatureSpawner.m_minLevel) { levelupChance = Mathf.Pow(levelupChance, (float)(zdo.PrefabInfo.CreatureSpawner.m_maxLevel - zdo.PrefabInfo.CreatureSpawner.m_minLevel)); } levelupChance = Mathf.Pow(levelupChance, 1f / (float)num4) * 100f; if (componentFieldAccessor.UpdateValue(() => (CreatureSpawner x) => x.m_levelupChance, levelupChance, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\CreatureLevelUpProcessor.cs", 226)) { base.RecreateZdo = true; } } } private void LevelUpCharacter(ExtendedZDO zdo) where T : Character { //IL_0100: Unknown result type (might be due to invalid IL or missing references) //IL_0190: Unknown result type (might be due to invalid IL or missing references) //IL_0195: Unknown result type (might be due to invalid IL or missing references) //IL_019a: Unknown result type (might be due to invalid IL or missing references) //IL_0392: Unknown result type (might be due to invalid IL or missing references) //IL_0397: Unknown result type (might be due to invalid IL or missing references) //IL_039c: Unknown result type (might be due to invalid IL or missing references) //IL_03b1: Unknown result type (might be due to invalid IL or missing references) //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_022e: Unknown result type (might be due to invalid IL or missing references) //IL_022f: Unknown result type (might be due to invalid IL or missing references) //IL_035c: Unknown result type (might be due to invalid IL or missing references) //IL_0361: Unknown result type (might be due to invalid IL or missing references) //IL_0362: 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_02ff: Unknown result type (might be due to invalid IL or missing references) //IL_0300: Unknown result type (might be due to invalid IL or missing references) //IL_0485: Unknown result type (might be due to invalid IL or missing references) //IL_04e5: Unknown result type (might be due to invalid IL or missing references) //IL_04d8: Unknown result type (might be due to invalid IL or missing references) //IL_04dd: Unknown result type (might be due to invalid IL or missing references) ExtendedZDO zdo2 = zdo; int initialLevel = zdo2.Vars.GetInitialLevel(); if (initialLevel != 0) { if (initialLevel > 0 && base.Config.Creatures.MaxLevelIncrease.Value == 0 && base.Config.Creatures.MaxLevelIncreasePerDefeatedBoss.Value == 0) { zdo2.Vars.SetLevel(initialLevel, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\CreatureLevelUpProcessor.cs", 240); zdo2.Vars.RemoveInitialLevel("D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\CreatureLevelUpProcessor.cs", 241); } return; } if ((base.Config.Creatures.MaxLevelIncrease.Value == 0 && base.Config.Creatures.MaxLevelIncreasePerDefeatedBoss.Value == 0) || zdo2.Vars.GetTamed() || zdo2.Vars.GetSpawnedByTrophy()) { return; } initialLevel = ((!_sectorStates.TryGetValue(((ZDO)zdo2).GetSector(), out SectorState value) || !value.CreatureSpawnersBySpawned.TryGetValue(((ZDO)zdo2).GetPrefab(), out List value2) || !value2.Any((ExtendedZDO x) => ((ZDO)x).GetConnectionZDOID((ConnectionType)3) == ((ZDO)zdo2).m_uid)) ? zdo2.Vars.GetLevel() : (-1)); zdo2.Vars.SetInitialLevel(initialLevel, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\CreatureLevelUpProcessor.cs", 263); if (initialLevel <= 0) { return; } Vector3 pos = zdo2.Vars.GetSpawnPoint(((ZDO)zdo2).GetPosition()); int num = base.Config.Creatures.MaxLevelIncrease.Value; (Humanoid, PrefabInfo.Optional, PrefabInfo.Optional)? humanoid = zdo2.PrefabInfo.Humanoid; SpawnData spawnData; Biome biome; if (humanoid.HasValue) { Humanoid item = humanoid.GetValueOrDefault().Item1; if (item != null && ((Character)item).m_boss) { if (!base.Config.Creatures.LevelUpBosses.Value) { return; } spawnData = new SpawnData(((ZDO)zdo2).GetPrefab(), 1, 1, 0f); if (_levelIncreasePerBiome.TryGetValue(biome = Processor.GetBiome(pos), out var value3)) { num += value3; } goto IL_04f7; } } if (zdo2.Vars.GetEventCreature()) { RandomEvent currentEvent = RandEventSystem.instance.GetCurrentEvent(); if (currentEvent == null) { base.Logger.LogWarning(zdo2.PrefabInfo.PrefabName + " is an event creature, but no active event was found"); return; } if (!GetEventInfo(currentEvent, out EventInfo eventInfo)) { return; } if (!eventInfo.SpawnData.TryGetValue(((ZDO)zdo2).GetPrefab(), out SpawnSystemData value4)) { base.Logger.LogWarning(zdo2.PrefabInfo.PrefabName + ": Spawn source not found in event " + currentEvent.m_name); return; } spawnData = value4; if (_levelIncreasePerBiome.TryGetValue(biome = eventInfo.Biome, out var value5)) { num += value5; } goto IL_04f7; } if (value != null && value.SpawnAreasBySpawned.TryGetValue(((ZDO)zdo2).GetPrefab(), out List value6)) { SectorState.SpawnAreaData spawnAreaData = value6.FirstOrDefault((SectorState.SpawnAreaData x) => Vector3.Distance(x.Position, pos) <= x.Radius); if ((object)spawnAreaData != null) { spawnData = spawnAreaData; if (_levelIncreasePerBiome.TryGetValue(biome = spawnAreaData.Biome, out var value7)) { num += value7; } goto IL_04f7; } } biome = Processor.GetBiome(pos); float? distanceFromCenter = null; if (_spawnData.TryGetValue((biome, ((ZDO)zdo2).GetPrefab()), out List value8)) { SpawnSystemData spawnSystemData = value8.FirstOrDefault(delegate(SpawnSystemData x) { //IL_0020: Unknown result type (might be due to invalid IL or missing references) float valueOrDefault = distanceFromCenter.GetValueOrDefault(); float distanceFromCenter2; if (!distanceFromCenter.HasValue) { valueOrDefault = Utils.LengthXZ(pos); distanceFromCenter = valueOrDefault; distanceFromCenter2 = valueOrDefault; } else { distanceFromCenter2 = valueOrDefault; } return IsValidSpawnData(x, distanceFromCenter2); }); if ((object)spawnSystemData != null) { spawnData = spawnSystemData; if (spawnSystemData.BiomeOverwrite.HasValue) { biome = spawnSystemData.BiomeOverwrite.Value; } if (_levelIncreasePerBiome.TryGetValue(biome, out var value9)) { num += value9; } goto IL_04f7; } } string text = ((value8 == null) ? "" : string.Join(Environment.NewLine + " ", value8.Select((SpawnSystemData x) => $"{((Object)x.Data.m_prefab).name} ({x.Prefab}): {x.Data.m_biome}, day: {x.Data.m_spawnAtDay}, night: {x.Data.m_spawnAtNight}").Prepend(""))); base.Logger.LogWarning($"{zdo2.PrefabInfo.PrefabName} ({((ZDO)zdo2).GetPrefab()}): Spawn source not found in {biome}, day: {EnvMan.IsDay()}, night: {EnvMan.IsNight()}{text}"); return; IL_04f7: if (num <= 0) { return; } int num2 = spawnData.MaxLevel + num; float num3 = SpawnSystem.GetLevelUpChance(spawnData.LevelUpChance); int num4 = num2 - spawnData.MinLevel; if (num4 != 0) { num3 /= 100f; if (spawnData.MaxLevel > spawnData.MinLevel) { num3 = Mathf.Pow(num3, (float)(spawnData.MaxLevel - spawnData.MinLevel)); } num3 = Mathf.Pow(num3, 1f / (float)num4) * 100f; } int i; for (i = Math.Min(spawnData.MinLevel, spawnData.MaxLevel); i < num2; i++) { if (!(Random.Range(0f, 100f) <= num3)) { break; } } if (i != initialLevel) { zdo2.Vars.SetLevel(i, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\CreatureLevelUpProcessor.cs", 352); base.RecreateZdo = true; } } private static bool IsValidSpawnData(SpawnSystemData data, float distanceFromCenter) { if (!data.Data.m_spawnAtDay && EnvMan.IsDay()) { return false; } if (!data.Data.m_spawnAtNight && EnvMan.IsNight()) { return false; } if (data.Data.m_minDistanceFromCenter > 0f && data.Data.m_minDistanceFromCenter > distanceFromCenter) { return false; } if (data.Data.m_maxDistanceFromCenter > 0f && data.Data.m_maxDistanceFromCenter < distanceFromCenter) { return false; } return true; } private bool GetEventInfo(RandomEvent currentEvent, [NotNullWhen(true)] out EventInfo? eventInfo) { //IL_0018: 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_005f: 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_007d: 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_0095: 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_007a: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_0116: Unknown result type (might be due to invalid IL or missing references) if (!_spawnDataByEvent.TryGetValue(currentEvent.m_name, out eventInfo)) { Biome val = (Biome)0; foreach (var (val4, val5) in SharedProcessorState.BossesByBiome.OrderBy, float>((KeyValuePair x) => x.Value.m_health)) { if ((int)val == 0) { if (currentEvent.m_requiredGlobalKeys.Contains(val5.m_defeatSetGlobalKey)) { val = val4; } continue; } val = val4; break; } if ((int)val == 0) { base.Logger.LogWarning("Associated boss for event " + currentEvent.m_name + " not found"); return false; } eventInfo = new EventInfo(val); _spawnDataByEvent.Add(currentEvent.m_name, eventInfo); foreach (SpawnData item in currentEvent.m_spawn) { if (item.m_prefab.GetComponent() != null) { eventInfo.SpawnData.Add(StringExtensionMethods.GetStableHashCode(((Object)item.m_prefab).name, true), new SpawnSystemData(item, val)); } else if (item.m_prefab.GetComponent() != null) { eventInfo.SpawnAreas.Add(StringExtensionMethods.GetStableHashCode(((Object)item.m_prefab).name, true)); } } } return true; } } internal sealed class DoorProcessor : Processor { private readonly Dictionary _openSince = new Dictionary(); private readonly List _allowedPlayers = new List(); private readonly Dictionary _keyItemWeightByHash = new Dictionary(); private readonly IEnumerable _visEquipmentVars = new <>z__ReadOnlyArray(new int[9] { ZDOVars.s_helmetItem, ZDOVars.s_chestItem, ZDOVars.s_legItem, ZDOVars.s_shoulderItem, ZDOVars.s_utilityItem, ZDOVars.s_leftItem, ZDOVars.s_rightItem, ZDOVars.s_leftBackItem, ZDOVars.s_rightBackItem }); protected override Guid Id { get; } = Guid.Parse("9cf1003b-a30e-4844-9522-aad3c51f5a1e"); public override void Initialize(bool firstTime) { base.Initialize(firstTime); if (firstTime) { _openSince.Clear(); _allowedPlayers.Clear(); _keyItemWeightByHash.Clear(); } } private void OnDoorDestroyed(ExtendedZDO zdo) { _openSince.Remove(zdo); } protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { //IL_00df: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_0102: Unknown result type (might be due to invalid IL or missing references) base.UnregisterZdoProcessor = true; if (zdo.PrefabInfo.Door == null) { return false; } ItemDrop keyItem = zdo.PrefabInfo.Door.m_keyItem; if (keyItem != null && ((Object)keyItem).name == "CryptKey" && zdo.Vars.GetState() == 0) { ExtendedZDO.ComponentFieldAccessor componentFieldAccessor = zdo.Fields(getUnknownComponent: false); if (!base.Config.Players.CanSacrificeCryptKey.Value) { componentFieldAccessor.Reset(() => (Door x) => x.m_keyItem, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\DoorProcessor.cs", 46); } else { base.UnregisterZdoProcessor = false; _allowedPlayers.Clear(); if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)36)) { foreach (Peer peer in peers) { if (!(Vector3.Distance(peer.m_refPos, ((ZDO)zdo).GetPosition()) > 16f) && Processor.Instance().Players.TryGetValue(peer.m_characterID, out ExtendedZDO value) && Processor.DataZDO.Vars.GetSacrifiedCryptKey(value.Vars.GetPlayerID(0L))) { _allowedPlayers.Add(value); } } } if (_allowedPlayers.Count == 0) { if (componentFieldAccessor.UpdateResetValue(() => (Door x) => x.m_keyItem, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\DoorProcessor.cs", 66)) { base.RecreateZdo = true; } } else { int num = 0; int num2 = 0; foreach (int visEquipmentVar in _visEquipmentVars) { foreach (ExtendedZDO allowedPlayer in _allowedPlayers) { int @int = ((ZDO)allowedPlayer).GetInt(visEquipmentVar, 0); if (@int != 0) { int value2 = ((!_keyItemWeightByHash.TryGetValue(@int, out value2)) ? 1 : (value2 + 1)); _keyItemWeightByHash[@int] = value2; if (value2 > num) { num = value2; num2 = @int; } } } } _keyItemWeightByHash.Clear(); if (num2 != 0) { GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(num2); ItemDrop val = ((itemPrefab != null) ? itemPrefab.GetComponent() : null); if (val != null) { if (componentFieldAccessor.UpdateValue(() => (Door x) => x.m_keyItem, val, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\DoorProcessor.cs", 96)) { base.RecreateZdo = true; } goto IL_02dc; } } base.Logger.LogWarning($"Item {num2} was chosen as key, but it's not a valid ItemDrop"); } } } goto IL_02dc; IL_02dc: if (float.IsNaN(base.Config.Doors.AutoCloseMinPlayerDistance.Value)) { return false; } if (zdo.PrefabInfo.Door.m_keyItem != null || zdo.PrefabInfo.Door.m_canNotBeClosed || zdo.Vars.GetCreator(0L) == 0L) { return false; } base.UnregisterZdoProcessor = false; if (!Processor.CheckMinDistance(peers, (ZDO)(object)zdo, base.Config.Doors.AutoCloseMinPlayerDistance.Value)) { return false; } if (zdo.Vars.GetState() == 0) { if (_openSince.Remove(zdo)) { zdo.Destroyed -= OnDoorDestroyed; } return true; } if (!_openSince.TryGetValue(zdo, out var value3)) { _openSince.Add(zdo, value3 = DateTimeOffset.UtcNow); zdo.Destroyed += OnDoorDestroyed; } if (DateTimeOffset.UtcNow - value3 < TimeSpan.FromSeconds(2.0)) { return false; } zdo.Vars.SetState(0, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\DoorProcessor.cs", 130); if (_openSince.Remove(zdo)) { zdo.Destroyed -= OnDoorDestroyed; } return true; } } internal sealed class FermenterProcessor : Processor { protected override Guid Id { get; } = Guid.Parse("19367679-d46d-45e6-be8a-505d638cc133"); protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { base.UnregisterZdoProcessor = true; if (zdo.PrefabInfo.Fermenter == null) { return false; } ExtendedZDO.ComponentFieldAccessor componentFieldAccessor = zdo.Fields(getUnknownComponent: false); if (base.Config.Fermenters.FermentationDurationMultiplier.Value == 1f) { componentFieldAccessor.Reset(() => (Fermenter x) => x.m_fermentationDuration, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\FermenterProcessor.cs", 15); } else if (componentFieldAccessor.UpdateValue(() => (Fermenter x) => x.m_fermentationDuration, zdo.PrefabInfo.Fermenter.m_fermentationDuration * base.Config.Fermenters.FermentationDurationMultiplier.Value, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\FermenterProcessor.cs", 16)) { base.RecreateZdo = true; } return false; } } internal sealed class FireplaceProcessor : Processor { [CompilerGenerated] private sealed class d__9 : IEnumerable, IEnumerable, IEnumerator, IEnumerator, IDisposable { private int <>1__state; private ExtendedZDO <>2__current; private int <>l__initialThreadId; private Vector3 pos; public Vector3 <>3__pos; private float offset; public float <>3__offset; private float coverCheckOffset; public float <>3__coverCheckOffset; public FireplaceProcessor <>4__this; private float 5__2; ExtendedZDO IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } [DebuggerHidden] public d__9(int <>1__state) { this.<>1__state = <>1__state; <>l__initialThreadId = Environment.CurrentManagedThreadId; } [DebuggerHidden] void IDisposable.Dispose() { <>1__state = -2; } private bool MoveNext() { //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_007c: Unknown result type (might be due to invalid IL or missing references) //IL_008a: 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_00ca: 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) //IL_0119: Unknown result type (might be due to invalid IL or missing references) //IL_011e: Unknown result type (might be due to invalid IL or missing references) //IL_0144: Unknown result type (might be due to invalid IL or missing references) //IL_016d: Unknown result type (might be due to invalid IL or missing references) //IL_0172: Unknown result type (might be due to invalid IL or missing references) //IL_0198: Unknown result type (might be due to invalid IL or missing references) //IL_01c1: Unknown result type (might be due to invalid IL or missing references) //IL_01c6: 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_0280: Unknown result type (might be due to invalid IL or missing references) //IL_0285: Unknown result type (might be due to invalid IL or missing references) //IL_02ab: Unknown result type (might be due to invalid IL or missing references) //IL_02d4: Unknown result type (might be due to invalid IL or missing references) //IL_02d9: Unknown result type (might be due to invalid IL or missing references) //IL_02ff: Unknown result type (might be due to invalid IL or missing references) //IL_0328: Unknown result type (might be due to invalid IL or missing references) //IL_032d: Unknown result type (might be due to invalid IL or missing references) //IL_0353: Unknown result type (might be due to invalid IL or missing references) //IL_022c: 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_0257: Unknown result type (might be due to invalid IL or missing references) //IL_03a5: Unknown result type (might be due to invalid IL or missing references) //IL_03aa: 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) int num = <>1__state; FireplaceProcessor fireplaceProcessor = <>4__this; Vector3 val; switch (num) { default: return false; case 0: <>1__state = -1; 5__2 = pos.y + offset + coverCheckOffset + 0.5f + 0.5f; val = pos; val.y = 5__2; <>2__current = fireplaceProcessor.PlacePiece(val, Prefabs.GraustenFloor4x4, 0f); <>1__state = 1; return true; case 1: <>1__state = -1; 5__2 -= 2.25f; val = pos; val.z = pos.z - 2f; val.y = 5__2; <>2__current = fireplaceProcessor.PlacePiece(val, Prefabs.GraustenWall4x2, 0f); <>1__state = 2; return true; case 2: <>1__state = -1; val = pos; val.x = pos.x - 2f; val.y = 5__2; <>2__current = fireplaceProcessor.PlacePiece(val, Prefabs.GraustenWall4x2, 90f); <>1__state = 3; return true; case 3: <>1__state = -1; val = pos; val.z = pos.z + 2f; val.y = 5__2; <>2__current = fireplaceProcessor.PlacePiece(val, Prefabs.GraustenWall4x2, 0f); <>1__state = 4; return true; case 4: <>1__state = -1; val = pos; val.x = pos.x + 2f; val.y = 5__2; <>2__current = fireplaceProcessor.PlacePiece(val, Prefabs.GraustenWall4x2, 90f); <>1__state = 5; return true; case 5: <>1__state = -1; goto IL_037a; case 6: <>1__state = -1; val = pos; val.x = pos.x - 2f; val.y = 5__2; <>2__current = fireplaceProcessor.PlacePiece(val, Prefabs.GraustenWall4x2, 90f); <>1__state = 7; return true; case 7: <>1__state = -1; val = pos; val.z = pos.z + 2f; val.y = 5__2; <>2__current = fireplaceProcessor.PlacePiece(val, Prefabs.GraustenWall4x2, 0f); <>1__state = 8; return true; case 8: <>1__state = -1; val = pos; val.x = pos.x + 2f; val.y = 5__2; <>2__current = fireplaceProcessor.PlacePiece(val, Prefabs.GraustenWall4x2, 90f); <>1__state = 9; return true; case 9: <>1__state = -1; goto IL_037a; case 10: { <>1__state = -1; return false; } IL_037a: if (5__2 > pos.y) { 5__2 -= 2f; val = pos; val.z = pos.z - 2f; val.y = 5__2; <>2__current = fireplaceProcessor.PlacePiece(val, Prefabs.GraustenWall4x2, 0f); <>1__state = 6; return true; } 5__2 -= 0.25f; val = pos; val.y = 5__2; <>2__current = fireplaceProcessor.PlacePiece(val, Prefabs.GraustenFloor4x4, 0f); <>1__state = 10; return true; } } bool IEnumerator.MoveNext() { //ILSpy generated this explicit interface implementation from .override directive in MoveNext return this.MoveNext(); } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { //IL_0037: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) d__9 d__; if (<>1__state == -2 && <>l__initialThreadId == Environment.CurrentManagedThreadId) { <>1__state = 0; d__ = this; } else { d__ = new d__9(0) { <>4__this = <>4__this }; } d__.pos = <>3__pos; d__.offset = <>3__offset; d__.coverCheckOffset = <>3__coverCheckOffset; return d__; } [DebuggerHidden] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)this).GetEnumerator(); } } private readonly Dictionary> _enclosure = new Dictionary>(); private readonly List _fireplaces = new List(); protected override Guid Id { get; } = Guid.Parse("a805afd0-ecd0-4c85-8d8a-6f2f14957b0a"); public override void Initialize(bool firstTime) { base.Initialize(firstTime); if (firstTime) { _enclosure.Clear(); _fireplaces.Clear(); Processor.Instance().ShieldGeneratorChanged -= OnShieldGeneratorChanged; Processor.Instance().ShieldGeneratorChanged += OnShieldGeneratorChanged; } } private void OnShieldGeneratorChanged(ExtendedZDO shieldGenerator, bool hasFuel) { //IL_0017: 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) foreach (ExtendedZDO fireplace in _fireplaces) { if (Vector3.Distance(((ZDO)shieldGenerator).GetPosition(), ((ZDO)fireplace).GetPosition()) < shieldGenerator.PrefabInfo.ShieldGenerator.m_maxShieldRadius) { fireplace.ResetProcessorDataRevision(this); } } } private void OnFireplaceDestroyed(ExtendedZDO zdo) { if (!_enclosure.Remove(zdo, out IEnumerable value)) { return; } foreach (ExtendedZDO item in value) { DestroyObject(item); } } protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { //IL_0324: Unknown result type (might be due to invalid IL or missing references) ExtendedZDO zdo2 = zdo; base.UnregisterZdoProcessor = true; if (zdo2.PrefabInfo.Fireplace == null) { return false; } ExtendedZDO.ComponentFieldAccessor componentFieldAccessor = zdo2.Fields(getUnknownComponent: false); if (!base.Config.Fireplaces.MakeToggleable.Value) { componentFieldAccessor.Reset(() => (Fireplace x) => x.m_canTurnOff, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\FireplaceProcessor.cs", 52); } else if (componentFieldAccessor.UpdateValue(() => (Fireplace x) => x.m_canTurnOff, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\FireplaceProcessor.cs", 53)) { base.RecreateZdo = true; } if (!base.Config.Fireplaces.InfiniteFuel.Value) { componentFieldAccessor.Reset(() => (Fireplace x) => x.m_secPerFuel, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\FireplaceProcessor.cs", 57).Reset(() => (Fireplace x) => x.m_canRefill, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\FireplaceProcessor.cs", 57); } else { if (componentFieldAccessor.UpdateValue(() => (Fireplace x) => x.m_secPerFuel, 0f, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\FireplaceProcessor.cs", 60)) { base.RecreateZdo = true; } if (componentFieldAccessor.UpdateValue(() => (Fireplace x) => x.m_canRefill, value: false, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\FireplaceProcessor.cs", 62)) { base.RecreateZdo = true; } zdo2.Vars.SetFuel(componentFieldAccessor.GetFloat(() => (Fireplace x) => x.m_maxFuel, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\FireplaceProcessor.cs", 64), "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\FireplaceProcessor.cs", 64); } Fireplace fireplace = zdo2.PrefabInfo.Fireplace; if (fireplace == null) { goto IL_0210; } GameObject enabledObjectLow = fireplace.m_enabledObjectLow; if (enabledObjectLow != null) { GameObject enabledObjectHigh = fireplace.m_enabledObjectHigh; if (enabledObjectHigh != null) { goto IL_0210; } } bool flag = true; goto IL_0213; IL_0210: flag = false; goto IL_0213; IL_0213: if (flag) { return false; } if (base.Config.Fireplaces.IgnoreRain.Value switch { ModConfigBase.FireplacesConfig.IgnoreRainOptions.Never => false, ModConfigBase.FireplacesConfig.IgnoreRainOptions.Always => true, ModConfigBase.FireplacesConfig.IgnoreRainOptions.InsideShield => Processor.Instance().ShieldGenerators.Any((ShieldGeneratorProcessor.ShieldGeneratorInfo x) => x.HasFuel && Vector3.Distance(((ZDO)x.ShieldGenerator).GetPosition(), ((ZDO)zdo2).GetPosition()) < x.ShieldGenerator.PrefabInfo.ShieldGenerator.m_maxShieldRadius), _ => false, }) { if (componentFieldAccessor.UpdateValue(() => (Fireplace x) => x.m_coverCheckOffset, -100f, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\FireplaceProcessor.cs", 84)) { base.RecreateZdo = true; } if (componentFieldAccessor.UpdateValue(() => (Fireplace x) => x.m_disableCoverCheck, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\FireplaceProcessor.cs", 86)) { base.RecreateZdo = true; } if (!base.RecreateZdo && !_enclosure.ContainsKey(zdo2)) { Dictionary> enclosure = _enclosure; ExtendedZDO key = zdo2; List list = new List(); list.AddRange(PlaceEnclosure(((ZDO)zdo2).GetPosition(), -100f, zdo2.PrefabInfo.Fireplace.m_coverCheckOffset)); enclosure.Add(key, new <>z__ReadOnlyList(list)); zdo2.Destroyed += OnFireplaceDestroyed; } } else { if (componentFieldAccessor.UpdateResetValue(() => (Fireplace x) => x.m_coverCheckOffset, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\FireplaceProcessor.cs", 96)) { base.RecreateZdo = true; } if (componentFieldAccessor.UpdateResetValue(() => (Fireplace x) => x.m_disableCoverCheck, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\FireplaceProcessor.cs", 98)) { base.RecreateZdo = true; } if (_enclosure.Remove(zdo2, out IEnumerable value)) { foreach (ExtendedZDO item in value) { DestroyObject(item); } zdo2.Destroyed -= OnFireplaceDestroyed; } } if (base.Config.Fireplaces.IgnoreRain.Value == ModConfigBase.FireplacesConfig.IgnoreRainOptions.InsideShield) { base.UnregisterZdoProcessor = false; if (!_fireplaces.Contains(zdo2)) { _fireplaces.Add(zdo2); } return true; } return false; } [IteratorStateMachine(typeof(d__9))] private IEnumerable PlaceEnclosure(Vector3 pos, float offset, float coverCheckOffset) { //IL_000f: 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) //yield-return decompiler failed: Unexpected instruction in Iterator.Dispose() return new d__9(-2) { <>4__this = this, <>3__pos = pos, <>3__offset = offset, <>3__coverCheckOffset = coverCheckOffset }; } } internal sealed class GlobalPlayerKeysProcessor : Processor { private readonly record struct GlobalKeyModification(GlobalKey Key, bool Add); private readonly Dictionary> _globalKeyModifications = new Dictionary>(); private readonly Dictionary _reset = new Dictionary(); [CompilerGenerated] private IReadOnlyList <_mapTableModifications>k__BackingField; private float _mapTableRangeSqr; private readonly List _modifications = new List(); protected override Guid Id { get; } = Guid.Parse("f21976ad-a2b6-4aaf-94d1-8f9e65510704"); private IReadOnlyList _mapTableModifications => <_mapTableModifications>k__BackingField ?? (<_mapTableModifications>k__BackingField = new <>z__ReadOnlySingleElementList(new GlobalKeyModification(new GlobalKey((GlobalKeys)26), Add: false))); public override void Initialize(bool firstTime) { base.Initialize(firstTime); _globalKeyModifications.Clear(); foreach (var item3 in base.Config.Traders.AlwaysUnlock.Select)>>, (Trader, IReadOnlyList<(string, ConfigEntry)>)>((KeyValuePair ConfigEntry)>> x) => (x.Key, x.Value))) { Trader item = item3.Item1; IReadOnlyList<(string, ConfigEntry)> item2 = item3.Item2; List list = (from x in (from x in item2 where x.ConfigEntry.Value select x.GlobalKey).Distinct() select new GlobalKeyModification(new GlobalKey(x), Add: true)).ToList(); if (list.Count > 0) { _globalKeyModifications.Add(item, list); } } _mapTableRangeSqr = 0f; if (base.Config.MapTables.MapViewDistance != null) { _mapTableRangeSqr = base.Config.MapTables.MapViewDistance.Value * base.Config.MapTables.MapViewDistance.Value; if (_mapTableRangeSqr > 0f && !ZoneSystem.instance.GetGlobalKey((GlobalKeys)26)) { _mapTableRangeSqr = 0f; base.Logger.LogWarning($"[{((ConfigEntryBase)base.Config.MapTables.MapViewDistance).Definition.Section}].[{((ConfigEntryBase)base.Config.MapTables.MapViewDistance).Definition.Key}] has no effect unless the {(object)(GlobalKeys)26} global key is set"); } } if (firstTime) { _reset.Clear(); Processor.Instance().PlayerDestroyed -= OnPlayerDestroyed; Processor.Instance().PlayerDestroyed += OnPlayerDestroyed; } } private void OnPlayerDestroyed(ExtendedZDO zdo) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) _reset.Remove(((ZDO)zdo).m_uid); } protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { //IL_00ad: Unknown result type (might be due to invalid IL or missing references) //IL_00b3: Unknown result type (might be due to invalid IL or missing references) float num; if (zdo.PrefabInfo.Trader != null && _globalKeyModifications.TryGetValue(zdo.PrefabInfo.Trader, out IReadOnlyList value)) { num = zdo.PrefabInfo.Trader.m_standRange * zdo.PrefabInfo.Trader.m_standRange; } else { if (!(_mapTableRangeSqr > 0f) || zdo.PrefabInfo.MapTable == null) { base.UnregisterZdoProcessor = true; return false; } num = _mapTableRangeSqr; value = _mapTableModifications; } foreach (Peer item in peers.AsEnumerable()) { IPeerInfo info = item.Info; if (info == null) { continue; } GlobalKey Key; bool Add; if (Utils.DistanceSqr(item.m_refPos, ((ZDO)zdo).GetPosition()) < num) { foreach (GlobalKeyModification item2 in value) { item2.Deconstruct(out Key, out Add); GlobalKey key = Key; bool add = Add; item.Info.AddGlobalKeyModification(key, add); } continue; } foreach (GlobalKeyModification item3 in value) { item3.Deconstruct(out Key, out Add); GlobalKey key2 = Key; item.Info.RemoveGlobalKeyModification(key2); } } return false; } } internal sealed class GrowProcessor : Processor { private sealed class LastMessage { public DateTimeOffset Timestamp { get; set; } public int Progress { get; set; } } private readonly Dictionary _lastMessage = new Dictionary(); protected override Guid Id { get; } = Guid.Parse("c41992d5-60b0-4628-a578-f897ecb102a7"); public override void Initialize(bool firstTime) { base.Initialize(firstTime); if (firstTime) { _lastMessage.Clear(); } } protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { PrefabInfo prefabInfo = zdo.PrefabInfo; if ((object)prefabInfo == null) { goto IL_0026; } EggGrow eggGrow = prefabInfo.EggGrow; if (eggGrow == null) { Growup growup = prefabInfo.Growup; if (growup == null) { goto IL_0026; } } bool flag = false; goto IL_002e; IL_0026: flag = true; goto IL_002e; IL_002e: if (flag || base.Config.Tames.GrowingProgressMessageType.Value == MessageTypes.None) { base.UnregisterZdoProcessor = true; return false; } if (_lastMessage.TryGetValue(zdo, out LastMessage value) && DateTimeOffset.UtcNow - value.Timestamp < TimeSpan.FromSeconds(DamageText.instance.m_textDuration)) { return false; } double num = ((zdo.PrefabInfo.EggGrow != null) ? ((double)zdo.Vars.GetGrowStart()) : new TimeSpan(zdo.Vars.GetSpawnTime().Ticks).TotalSeconds); if (num == 0.0) { return false; } float num2 = zdo.PrefabInfo.EggGrow?.m_growTime ?? zdo.PrefabInfo.Growup.m_growTime; float num3 = (float)(ZNet.instance.GetTimeSeconds() - num); int num4 = (int)(100f * Mathf.Clamp01(num3 / num2)); if (value != null && value.Progress == num4) { return false; } if (value == null) { _lastMessage.Add(zdo, value = new LastMessage()); zdo.Destroyed += delegate(ExtendedZDO x) { _lastMessage.Remove(x); }; } value.Timestamp = DateTimeOffset.UtcNow; value.Progress = num4; Processor.ShowMessage(peers, zdo, base.Config.Localization.Tames.FormatGrowing(num4), base.Config.Tames.GrowingProgressMessageType.Value, (TextType)0); return false; } } internal sealed class HumanoidLevelProcessor : Processor { private sealed class HumanoidState { public int StatusEffect { get; } public TimeSpan Duration { get; } public DateTimeOffset LastApplied { get; set; } public HumanoidState(int statusEffect) { StatusEffect = statusEffect; Duration = TimeSpan.FromSeconds(ObjectDB.instance.GetStatusEffect(statusEffect).m_ttl - 0.2f); base..ctor(); } } private readonly IReadOnlyList _statusEffects = new <>z__ReadOnlySingleElementList(SEMan.s_statusEffectSpirit); private readonly Dictionary _states = new Dictionary(); protected override Guid Id { get; } = Guid.Parse("e579ea6d-86ca-4fbf-bd61-539bae01cf1d"); public override void Initialize(bool firstTime) { base.Initialize(firstTime); _states.Clear(); } protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { base.UnregisterZdoProcessor = true; PrefabInfo prefabInfo = zdo.PrefabInfo; if ((object)prefabInfo != null && !prefabInfo.Humanoid.HasValue && !prefabInfo.Character.HasValue) { return false; } int level = zdo.Vars.GetLevel(); if (level <= 3) { return false; } base.UnregisterZdoProcessor = false; if (!_states.TryGetValue(zdo, out HumanoidState value)) { if (zdo.PrefabInfo.Humanoid.HasValue) { SetFields(zdo, level); } else { SetFields(zdo, level); } if (!base.RecreateZdo) { bool tamed = zdo.Vars.GetTamed(); if ((tamed && base.Config.Creatures.ShowHigherLevelAura.Value.HasFlag(ModConfigBase.CreaturesConfig.ShowHigherLevelAuraOptions.Tamed)) || (!tamed && base.Config.Creatures.ShowHigherLevelAura.Value.HasFlag(ModConfigBase.CreaturesConfig.ShowHigherLevelAuraOptions.Wild))) { _states.Add(zdo, value = new HumanoidState(_statusEffects[Random.Range(0, _statusEffects.Count)])); zdo.Destroyed += delegate(ExtendedZDO x) { _states.Remove(x); }; } } } if (value == null) { base.UnregisterZdoProcessor = true; return false; } if (DateTimeOffset.UtcNow - value.LastApplied > value.Duration) { value.LastApplied = DateTimeOffset.UtcNow; RPC.AddStatusEffect(zdo, value.StatusEffect, resetTime: true); } return false; } private void SetFields(ExtendedZDO zdo, int level) where T : Character { ExtendedZDO.ComponentFieldAccessor componentFieldAccessor = zdo.Fields(getUnknownComponent: false); if (!base.Config.Creatures.ShowHigherLevelStars.Value) { componentFieldAccessor.Reset(() => (T x) => ((Character)x).m_name, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\HumanoidLevelProcessor.cs", 75); } else if (componentFieldAccessor.UpdateValue(() => (T x) => ((Character)x).m_name, string.Concat("", ((Character)(((object)zdo.PrefabInfo.Humanoid?.Humanoid) ?? ((object)zdo.PrefabInfo.Character.Value.Character))).m_name, "
", string.Concat(Enumerable.Repeat("⭐", level - 1)), ""), "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\HumanoidLevelProcessor.cs", 76)) { base.RecreateZdo = true; } } } internal sealed class InGameConfigProcessor : Processor { private sealed record ConfigState(ConfigEntryBase Entry, object? Value, ExtendedZDO Sign) { public bool CandleState { get; set; } } private const string SignFormatWhite = ""; private const string SignFormatGreen = ""; private const string MainPortalTag = "ServersideQoL Config-Room"; internal const string PortalHubTag = "ServersideQoL Portal Hub"; private const float FloorOffset = 5f; private readonly List<(ExtendedZDO Sign, string Text, IReadOnlyList Entries)> _portalSigns = new List<(ExtendedZDO, string, IReadOnlyList)>(); private readonly Dictionary _candleToggles = new Dictionary(); private readonly Dictionary _configBySign = new Dictionary(); private readonly Regex _removeFormatRegex = new Regex("<[^>]+ x>"); private readonly (Vector3 WorldSpawn, Vector3 Room) _offset = ((Func<(Vector3, Vector3)>)delegate { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_001a: 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_0024: 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_0026: 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_0041: 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) Vector3 val = default(Vector3); Vector3 val2 = (Vector3)(ZoneSystem.instance.GetLocationIcon(Game.instance.m_StartLocation, ref val) ? val : default(Vector3)); Vector3 val3 = val2; while (!Character.InInterior(val3)) { val3.y += 1000f; } return (val2, val3); })(); protected override Guid Id { get; } = Guid.Parse("81185723-7387-4b8c-ac26-e78fe1e659a6"); private static string GetSignText(object? value, Type type, Color c) { return FormattableString.Invariant($"{TomlTypeConverter.ConvertToString(value, type)}"); } private static string GetSignText(ConfigEntryBase entry, Color? color = null) { return GetSignText(entry.BoxedValue, entry.SettingType, color ?? (object.Equals(entry.BoxedValue, entry.DefaultValue) ? Color.White : Color.Lime)); } public override void Initialize(bool firstTime) { //IL_004a: 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_0057: 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_008b: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) //IL_0833: Unknown result type (might be due to invalid IL or missing references) //IL_0838: Unknown result type (might be due to invalid IL or missing references) //IL_0901: Unknown result type (might be due to invalid IL or missing references) //IL_0885: Unknown result type (might be due to invalid IL or missing references) //IL_025c: Unknown result type (might be due to invalid IL or missing references) //IL_0261: Unknown result type (might be due to invalid IL or missing references) //IL_027e: Unknown result type (might be due to invalid IL or missing references) //IL_02a2: Unknown result type (might be due to invalid IL or missing references) //IL_0b8a: 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_0b99: Unknown result type (might be due to invalid IL or missing references) //IL_0b9b: Unknown result type (might be due to invalid IL or missing references) //IL_0bbe: Unknown result type (might be due to invalid IL or missing references) //IL_0a0e: Unknown result type (might be due to invalid IL or missing references) //IL_0a13: Unknown result type (might be due to invalid IL or missing references) //IL_0a1d: Unknown result type (might be due to invalid IL or missing references) //IL_0a1f: Unknown result type (might be due to invalid IL or missing references) //IL_0a3c: Unknown result type (might be due to invalid IL or missing references) //IL_0a60: Unknown result type (might be due to invalid IL or missing references) //IL_0581: Unknown result type (might be due to invalid IL or missing references) //IL_0586: Unknown result type (might be due to invalid IL or missing references) //IL_0407: Unknown result type (might be due to invalid IL or missing references) //IL_06c6: Unknown result type (might be due to invalid IL or missing references) //IL_06cb: Unknown result type (might be due to invalid IL or missing references) //IL_0ad0: Unknown result type (might be due to invalid IL or missing references) //IL_0b19: Unknown result type (might be due to invalid IL or missing references) //IL_05de: 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_051c: Unknown result type (might be due to invalid IL or missing references) //IL_0722: Unknown result type (might be due to invalid IL or missing references) //IL_0743: Unknown result type (might be due to invalid IL or missing references) //IL_0645: Unknown result type (might be due to invalid IL or missing references) //IL_0789: Unknown result type (might be due to invalid IL or missing references) base.Initialize(firstTime); if (!firstTime) { return; } _portalSigns.Clear(); _candleToggles.Clear(); _configBySign.Clear(); if (!base.Config.General.InWorldConfigRoom.Value) { return; } if (_offset.WorldSpawn == default(Vector3)) { base.Logger.LogWarning(Game.instance.m_StartLocation + " not found, skipping generation of config room"); return; } Vector3 item = _offset.WorldSpawn; item.z -= 3f; PlacePiece(item, Prefabs.PortalWood, 0f).Vars.SetTag("ServersideQoL Config-Room", "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 70); item.y -= 3f; PlacePiece(item, Prefabs.DvergerGuardstone, 0f).Fields(getUnknownComponent: true).Set(() => (PrivateArea x) => x.m_radius, 3f, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 73).Set(() => (PrivateArea x) => x.m_enabledByDefault, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 73); List> list = (from x in (IEnumerable>)base.Config.ConfigFile where x.Key.Section != "Z - Dummy" && !x.Key.Section.StartsWith("A - ") group x.Value by x.Key.Section into x orderby x.Key select x).ToList(); List>.Enumerator enumerator = list.GetEnumerator(); int num = (int)Math.Ceiling((float)list.Count / 4f + 1f); for (int i = 0; i < num; i++) { bool flag = i == 0 || i == num - 1; float num2 = ((float)i - (float)num / 2f) * 4f; for (int j = 0; j < num; j++) { float num3 = ((float)j - (float)num / 2f) * 4f; Vector3 item2 = _offset.Room; item2.x += num2; item2.z += num3; PlacePiece(item2, Prefabs.GraustenFloor4x4, 0f); item2.y += 4.5f; PlacePiece(item2, Prefabs.GraustenFloor4x4, 0f); item2.y -= 4.5f; bool flag2 = j == 0 || j == num - 1; if (!flag && !flag2) { continue; } float num4 = 0f; if (flag && flag2) { num4 = ((j == 0 && i == 0) ? 45f : ((j == 0 && i != 0) ? 315f : ((j == 0 || i != 0) ? 225f : 135f))); } else if (flag) { num4 = ((i != 0) ? (num4 + 270f) : (num4 + 90f)); } else if (flag2 && j != 0) { num4 += 180f; } if (!flag) { item2.z += ((j == 0) ? (-1.5f) : 1.5f); } else if (!flag2) { item2.x += ((i == 0) ? (-1.5f) : 1.5f); } if (enumerator.MoveNext()) { string text = Regex.Replace(enumerator.Current.Key, "^[A-Z] - ", ""); List list2 = new List(); list2.AddRange(enumerator.Current); IReadOnlyList readOnlyList = new <>z__ReadOnlyList(list2); bool flag3 = readOnlyList.Any((ConfigEntryBase x) => !object.Equals(x.BoxedValue, x.DefaultValue)); ExtendedZDO extendedZDO = PlacePiece(item2, Prefabs.PortalWood, num4); extendedZDO.Fields(getUnknownComponent: false).Set(() => (TeleportWorld x) => x.m_allowAllItems, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 142); extendedZDO.Vars.SetTag("Config: " + text, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 143); if (flag && flag2) { item2.z += ((j == 0) ? (-0.25f) : 0.25f) * Mathf.Sqrt(2f); item2.x += ((i == 0) ? (-0.25f) : 0.25f) * Mathf.Sqrt(2f); } else if (!flag) { item2.z += ((j == 0) ? (-0.25f) : 0.25f); } else if (!flag2) { item2.x += ((i == 0) ? (-0.25f) : 0.25f); } item2.y += 2f; ExtendedZDO extendedZDO2 = PlacePiece(item2, Prefabs.Sign, num4); extendedZDO2.Vars.SetText((flag3 ? "" : "") + text, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 156); _portalSigns.Add((extendedZDO2, text, readOnlyList)); } if (flag) { item2 = _offset.Room; item2.x += num2; item2.z += num3; item2.y += 0.25f; num4 = ((i == 0) ? 90 : 270); item2.x += ((i == 0) ? (-2f) : 2f); PlacePiece(item2, Prefabs.GraustenWall4x2, num4); item2.y += 2f; PlacePiece(item2, Prefabs.GraustenWall4x2, num4); num4 -= 90f; item2.x += ((i == 0) ? 0.25f : (-0.25f)); item2.y += 0.5f; PlacePiece(item2, Prefabs.Sconce, num4).Fields(getUnknownComponent: false).Set(() => (Fireplace x) => x.m_infiniteFuel, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 176).Set(() => (Fireplace x) => x.m_disableCoverCheck, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 177); } if (!flag2) { continue; } item2 = _offset.Room; item2.x += num2; item2.z += num3; item2.y += 0.25f; num4 = ((j != 0) ? 180 : 0); item2.z += ((j == 0) ? (-2f) : 2f); PlacePiece(item2, Prefabs.GraustenWall4x2, num4); item2.y += 2f; PlacePiece(item2, Prefabs.GraustenWall4x2, num4); num4 -= 90f; item2.z += ((j == 0) ? 0.25f : (-0.25f)); item2.y += 0.5f; PlacePiece(item2, Prefabs.Sconce, num4).Fields(getUnknownComponent: false).Set(() => (Fireplace x) => x.m_infiniteFuel, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 195).Set(() => (Fireplace x) => x.m_disableCoverCheck, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 196); } } if (enumerator.MoveNext()) { throw new Exception("Algorithm failed to place all portals"); } Vector3 item3 = _offset.Room; item3.x -= 2f; item3.z -= 2f; if (base.Config.PortalHub.Enable.Value) { item3.z -= 0.5f; ExtendedZDO extendedZDO3 = PlacePiece(item3, Prefabs.PortalWood, 180f); extendedZDO3.Fields(getUnknownComponent: false).Set(() => (TeleportWorld x) => x.m_allowAllItems, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 213); extendedZDO3.Vars.SetTag("ServersideQoL Portal Hub", "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 214); item3.z += 1f; } ExtendedZDO extendedZDO4 = PlacePiece(item3, Prefabs.PortalWood, 0f); extendedZDO4.Fields(getUnknownComponent: false).Set(() => (TeleportWorld x) => x.m_allowAllItems, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 220); extendedZDO4.Vars.SetTag("ServersideQoL Config-Room", "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 221); float num5 = _offset.Room.y; foreach (IGrouping item5 in list) { num5 += 5f; IEnumerator enumerator3 = item5.GetEnumerator(); num = Math.Max(3, (int)Math.Ceiling((float)item5.Count() / 4f)); Vector3 item4; for (int k = 0; k < num; k++) { bool flag4 = k == 0 || k == num - 1; float num6 = ((float)k - (float)num / 2f) * 4f; for (int l = 0; l < num; l++) { float num7 = ((float)l - (float)num / 2f) * 4f; item4 = _offset.Room; item4.y = num5; Vector3 pos = item4; pos.x += num6; pos.z += num7; PlacePiece(pos, Prefabs.GraustenFloor4x4, 0f); pos.y += 4.5f; PlacePiece(pos, Prefabs.GraustenFloor4x4, 0f); pos.y -= 4.5f; bool flag5 = l == 0 || l == num - 1; if (flag4 || flag5) { if (flag4) { PlaceConfigWall(new Vector3(_offset.Room.x + num6, num5 + 0.25f, _offset.Room.z + num7), alongX: false, k == 0, 90f, enumerator3); } if (flag5) { PlaceConfigWall(new Vector3(_offset.Room.x + num6, num5 + 0.25f, _offset.Room.z + num7), alongX: true, l == 0, 0f, enumerator3); } } } } if (enumerator3.MoveNext()) { throw new Exception("Algorithm failed to place all signs in config section " + item5.Key); } string text2 = Regex.Replace(item5.Key, "^[A-Z] - ", ""); item4 = _offset.Room; item4.y = num5; Vector3 pos2 = item4; pos2.x -= 2f; pos2.z -= 2f; ExtendedZDO extendedZDO5 = PlacePiece(pos2, Prefabs.PortalWood, 0f); extendedZDO5.Fields(getUnknownComponent: false).Set(() => (TeleportWorld x) => x.m_allowAllItems, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 269); extendedZDO5.Vars.SetTag("Config: " + text2, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 270); } base.Config.ConfigFile.SettingChanged -= OnSettingsChanged; base.Config.ConfigFile.SettingChanged += OnSettingsChanged; } private void OnSettingsChanged(object sender, EventArgs args) { foreach (var portalSign in _portalSigns) { ExtendedZDO item = portalSign.Sign; string item2 = portalSign.Text; IReadOnlyList item3 = portalSign.Entries; bool flag = item3.Any((ConfigEntryBase x) => !object.Equals(x.BoxedValue, x.DefaultValue)); item.Vars.SetText((flag ? "" : "") + item2, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 284); } } private void PlaceConfigWall(Vector3 pos, bool alongX, bool isStart, float rot, IEnumerator entryEnumerator) { //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: 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_016e: 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_069a: Unknown result type (might be due to invalid IL or missing references) //IL_0732: Unknown result type (might be due to invalid IL or missing references) //IL_06f9: Unknown result type (might be due to invalid IL or missing references) //IL_0443: Unknown result type (might be due to invalid IL or missing references) //IL_0865: 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_0662: Unknown result type (might be due to invalid IL or missing references) ref float reference = ref alongX ? ref pos.x : ref pos.z; ref float reference2 = ref alongX ? ref pos.z : ref pos.x; rot += (float)((!isStart) ? 180 : 0); reference2 += (isStart ? (-2f) : 2f); PlacePiece(pos, Prefabs.GraustenWall4x2, rot); pos.y += 2f; PlacePiece(pos, Prefabs.GraustenWall4x2, rot); if (!entryEnumerator.MoveNext()) { return; } ConfigEntryBase current = entryEnumerator.Current; rot -= 90f; reference2 += (isStart ? 0.25f : (-0.25f)); pos.y += 1.35f; PlacePiece(pos, Prefabs.Sign, rot + 90f).Vars.SetText("" + current.Definition.Key, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 306); pos.y -= 0.6f; PlacePiece(pos, Prefabs.Sign, rot + 90f).Vars.SetText("" + current.Description.Description, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 309); pos.y -= 0.25f; reference -= 1f; PlacePiece(pos, Prefabs.Sconce, rot).Fields(getUnknownComponent: false).Set(() => (Fireplace x) => x.m_infiniteFuel, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 315).Set(() => (Fireplace x) => x.m_disableCoverCheck, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 316); reference += 2f; PlacePiece(pos, Prefabs.Sconce, rot).Fields(getUnknownComponent: false).Set(() => (Fireplace x) => x.m_infiniteFuel, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 319).Set(() => (Fireplace x) => x.m_disableCoverCheck, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 320); reference -= 1f; pos.y += 0.25f; pos.y -= 1f; IReadOnlyList readOnlyList = null; Type type = ((object)current.Description.AcceptableValues)?.GetType(); if ((object)type != null && type.IsConstructedGenericType) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(AcceptableValueList<>)) { List list = new List(); foreach (object item in (IEnumerable)type.GetProperty("AcceptableValues", BindingFlags.Instance | BindingFlags.Public).GetValue(current.Description.AcceptableValues)) { list.Add(item); } readOnlyList = new <>z__ReadOnlyList(list); } else if (genericTypeDefinition == typeof(ModConfigBase.AcceptableEnum<>)) { List list2 = new List(); foreach (object item2 in (IEnumerable)type.GetProperty("AcceptableValues", BindingFlags.Instance | BindingFlags.Public).GetValue(current.Description.AcceptableValues)) { list2.Add(item2); } readOnlyList = new <>z__ReadOnlyList(list2); } } if (readOnlyList != null) { int count = readOnlyList.Count; if (count > 0 && count <= 8) { int num = Math.Max(2, (readOnlyList.Count + 1) / 2); float num2 = 1f; float num3 = reference - num2 * (float)(num - 1) / 2f; pos.y += 1f; ExtendedZDO extendedZDO; ConfigState configState; Color silver; ExtendedZDO extendedZDO2; for (int i = 0; i < readOnlyList.Count; extendedZDO.Vars.SetText(GetSignText(readOnlyList[i], current.SettingType, silver), "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 370), pos.y -= 0.55f, extendedZDO2 = PlacePiece(pos, Prefabs.Sconce, rot), extendedZDO2.Fields(getUnknownComponent: false).Set(() => (Fireplace x) => x.m_secPerFuel, 0f, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 375).Set(() => (Fireplace x) => x.m_canRefill, value: false, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 376) .Set(() => (Fireplace x) => x.m_canTurnOff, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 377) .Set(() => (Fireplace x) => x.m_disableCoverCheck, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 378), extendedZDO2.Vars.SetFuel(extendedZDO2.PrefabInfo.Fireplace.m_maxFuel, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 379), extendedZDO2.Vars.SetState(configState.CandleState ? 1 : 2, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 380), _candleToggles.Add(((ZDO)extendedZDO2).m_uid, configState), pos.y += 0.55f, reference += num2, i++) { if (i % num == 0) { reference = num3; pos.y -= 1f; } extendedZDO = PlacePiece(pos, Prefabs.Sign, rot + 90f); configState = new ConfigState(current, readOnlyList[i], extendedZDO); silver = Color.Silver; if (current.SettingType.IsEnum) { EnumUtils.ObjectEnumUtils objectEnumUtils = EnumUtils.OfType(current.SettingType); if (objectEnumUtils != null && objectEnumUtils.IsBitSet) { ulong num4 = objectEnumUtils.EnumToUInt64(current.BoxedValue); ulong num5 = objectEnumUtils.EnumToUInt64(readOnlyList[i]); configState.CandleState = (num4 & num5) == num5; continue; } } configState.CandleState = object.Equals(current.BoxedValue, readOnlyList[i]); } return; } } ExtendedZDO extendedZDO3 = PlacePiece(pos, Prefabs.Sign, rot + 90f); extendedZDO3.Vars.SetText(GetSignText(current), "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 390); if (current.SettingType != typeof(bool)) { _configBySign.Add(((ZDO)extendedZDO3).m_uid, current); return; } ConfigState configState2 = new ConfigState(current, null, extendedZDO3) { CandleState = (bool)current.BoxedValue }; pos.y -= 0.55f; ExtendedZDO extendedZDO4 = PlacePiece(pos, Prefabs.Sconce, rot); extendedZDO4.Fields(getUnknownComponent: false).Set(() => (Fireplace x) => x.m_secPerFuel, 0f, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 400).Set(() => (Fireplace x) => x.m_canRefill, value: false, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 401) .Set(() => (Fireplace x) => x.m_canTurnOff, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 402) .Set(() => (Fireplace x) => x.m_disableCoverCheck, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 403); extendedZDO4.Vars.SetState(configState2.CandleState ? 1 : 2, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 404); extendedZDO4.Vars.SetFuel(extendedZDO4.PrefabInfo.Fireplace.m_maxFuel, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 405); _candleToggles.Add(((ZDO)extendedZDO4).m_uid, configState2); pos.y += 0.55f; } protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { //IL_0058: 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_0070: Unknown result type (might be due to invalid IL or missing references) //IL_0075: 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_0087: 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_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a0: 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_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_0551: Unknown result type (might be due to invalid IL or missing references) if (!base.Config.General.InWorldConfigRoom.Value) { base.UnregisterZdoProcessor = true; return false; } if (zdo.PrefabInfo.Player != null) { IPeerInfo peerInfo = Processor.Instance().GetPeerInfo(((ZDO)zdo).GetOwner()); if (peerInfo == null) { return false; } if (peerInfo.IsAdmin) { base.UnregisterZdoProcessor = true; return false; } if (Character.InInterior(((ZDO)zdo).GetPosition()) && ((ZDO)zdo).GetSector() == ZoneSystem.GetZone(_offset.WorldSpawn)) { Vector3 pos = _offset.WorldSpawn + Vector3.up * 2f; RPC.TeleportPlayer(zdo, pos, ((ZDO)zdo).GetRotation(), distantTeleport: false); RPC.ShowMessage(((ZDO)zdo).GetOwner(), (MessageType)2, "$piece_noaccess"); } return false; } if (!base.PlacedObjects.Contains(zdo)) { base.UnregisterZdoProcessor = true; return false; } float num = peers.Max((Peer x) => x.m_refPos.y); ConfigState value; bool flag; string text; if (num > _offset.Room.y) { if (zdo.PrefabInfo.Fireplace != null && _candleToggles.TryGetValue(((ZDO)zdo).m_uid, out value)) { flag = zdo.Vars.GetState(1) == 1; text = null; if (flag != value.CandleState && num > _offset.Room.y + 5f) { value.CandleState = flag; if (value.Entry.SettingType == typeof(bool)) { value.Entry.BoxedValue = flag; text = GetSignText(value.Entry); } else { if (value.Value != null && value.Entry.SettingType.IsEnum) { EnumUtils.ObjectEnumUtils objectEnumUtils = EnumUtils.OfType(value.Entry.SettingType); if (objectEnumUtils != null && objectEnumUtils.IsBitSet) { ulong num2 = objectEnumUtils.EnumToUInt64(value.Entry.BoxedValue); ulong num3 = objectEnumUtils.EnumToUInt64(value.Value); Color c; if (flag) { num2 |= num3; ulong num4 = objectEnumUtils.EnumToUInt64(value.Entry.DefaultValue); c = (((num4 & num3) == num3) ? Color.White : Color.Lime); } else { num2 &= ~num3; c = Color.Silver; } value.Entry.BoxedValue = objectEnumUtils.UInt64ToEnum(num2); text = GetSignText(value.Value, value.Entry.SettingType, c); goto IL_0514; } } value.Entry.BoxedValue = value.Value; Color c2 = (object.Equals(value.Value, value.Entry.DefaultValue) ? Color.White : Color.Lime); text = GetSignText(value.Value, value.Entry.SettingType, c2); } goto IL_0514; } if (value.Entry.SettingType == typeof(bool)) { bool flag2 = (bool)value.Entry.BoxedValue; if (value.CandleState != flag2) { value.CandleState = flag2; text = GetSignText(value.Entry); } } else { if (value.Value != null && value.Entry.SettingType.IsEnum) { EnumUtils.ObjectEnumUtils objectEnumUtils2 = EnumUtils.OfType(value.Entry.SettingType); if (objectEnumUtils2 != null && objectEnumUtils2.IsBitSet) { ulong num5 = objectEnumUtils2.EnumToUInt64(value.Entry.BoxedValue); ulong num6 = objectEnumUtils2.EnumToUInt64(value.Value); bool flag3 = (num5 & num6) == num6; if (value.CandleState != flag3) { value.CandleState = flag3; Color c3; if (!value.CandleState) { c3 = Color.Silver; } else { ulong num7 = objectEnumUtils2.EnumToUInt64(value.Entry.DefaultValue); c3 = (((num7 & num6) == num6) ? Color.White : Color.Lime); } text = GetSignText(value.Value, value.Entry.SettingType, c3); } goto IL_04e5; } } bool flag4 = object.Equals(value.Value, value.Entry.BoxedValue); if (value.CandleState != flag4) { value.CandleState = flag4; text = GetSignText(c: (!value.CandleState) ? Color.Silver : (object.Equals(value.Value, value.Entry.DefaultValue) ? Color.White : Color.Lime), value: value.Value, type: value.Entry.SettingType); } } goto IL_04e5; } if (zdo.PrefabInfo.Sign != null && _configBySign.TryGetValue(((ZDO)zdo).m_uid, out ConfigEntryBase value2)) { string text2 = _removeFormatRegex.Replace(zdo.Vars.GetText(), ""); try { value2.BoxedValue = TomlTypeConverter.ConvertToValue(text2, value2.SettingType); } catch (Exception) { RPC.ShowMessage(peers.Where((Peer x) => x.Info?.IsAdmin ?? false), (MessageType)2, "$invalid_keybind_header"); } zdo.Vars.SetText(GetSignText(value2), "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 560); return true; } base.UnregisterZdoProcessor = true; } return false; IL_0514: if (text != null) { value.Sign.Vars.SetText(text, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 545); } return false; IL_04e5: if (value.CandleState != flag) { zdo.Vars.SetState(value.CandleState ? 1 : 2, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 541); } goto IL_0514; } private static void AddAdmin(ExtendedZDO guardStone, long playerId, string playerName) { int permitted = guardStone.Vars.GetPermitted(); guardStone.Vars.SetPermitted(permitted + 1, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\InGameConfigProcessor.cs", 580); ((ZDO)guardStone).Set(FormattableString.Invariant($"pu_id{permitted}"), playerId); ((ZDO)guardStone).Set(FormattableString.Invariant($"pu_name{permitted}"), playerName); } } internal sealed class ItemDropProcessor : Processor { private readonly Dictionary _eggDropTime = new Dictionary(); private readonly List _itemDrops = new List(); private readonly Dictionary _crates = new Dictionary(); protected override Guid Id { get; } = Guid.Parse("0c2236b3-e371-4bb9-9724-e1eb83a9679e"); public override void Initialize(bool firstTime) { base.Initialize(firstTime); if (firstTime) { _eggDropTime.Clear(); _itemDrops.Clear(); Processor.Instance().ContainerChanged -= OnContainerChanged; Processor.Instance().ContainerChanged += OnContainerChanged; } } private void OnContainerChanged(ExtendedZDO containerZdo) { //IL_002a: 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) if (containerZdo.Inventory.Items.Count == 0) { return; } foreach (ExtendedZDO itemDrop in _itemDrops) { if (Vector3.Distance(((ZDO)itemDrop).GetPosition(), ((ZDO)containerZdo).GetPosition()) <= base.Config.Containers.AutoPickupRange.Value) { itemDrop.ResetProcessorDataRevision(this); } } } protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { //IL_08fe: Unknown result type (might be due to invalid IL or missing references) //IL_0913: Unknown result type (might be due to invalid IL or missing references) //IL_0928: Unknown result type (might be due to invalid IL or missing references) //IL_092d: Unknown result type (might be due to invalid IL or missing references) //IL_0940: Unknown result type (might be due to invalid IL or missing references) //IL_0943: Unknown result type (might be due to invalid IL or missing references) //IL_0282: Unknown result type (might be due to invalid IL or missing references) //IL_028e: Unknown result type (might be due to invalid IL or missing references) //IL_0952: Unknown result type (might be due to invalid IL or missing references) //IL_0957: Unknown result type (might be due to invalid IL or missing references) //IL_0964: Expected O, but got Unknown //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_0461: Unknown result type (might be due to invalid IL or missing references) //IL_0466: Unknown result type (might be due to invalid IL or missing references) //IL_0473: Expected O, but got Unknown //IL_04c0: Unknown result type (might be due to invalid IL or missing references) //IL_0b0f: Unknown result type (might be due to invalid IL or missing references) //IL_0b14: Unknown result type (might be due to invalid IL or missing references) //IL_064d: Unknown result type (might be due to invalid IL or missing references) if (!zdo.PrefabInfo.ItemDrop.HasValue || !base.Config.Containers.AutoPickup.Value || (base.Config.TrophySpawner.Enable.Value && Processor.Instance().IsAttracting(zdo))) { base.UnregisterZdoProcessor = true; return false; } if (zdo.PrefabInfo.ItemDrop.Value.Piece.Value != null && zdo.Vars.GetPiece()) { base.UnregisterZdoProcessor = true; return false; } if (zdo.PrefabInfo.EggGrow != null) { if (zdo.Vars.GetGrowStart() > 0f) { return true; } if (!_eggDropTime.TryGetValue(zdo, out var value)) { _eggDropTime.Add(zdo, DateTimeOffset.UtcNow); zdo.Destroyed += delegate(ExtendedZDO x) { _eggDropTime.Remove(x); }; return false; } if (DateTimeOffset.UtcNow - value < TimeSpan.FromSeconds(2f * zdo.PrefabInfo.EggGrow.m_updateInterval + 2f)) { return false; } } if (!Processor.CheckMinDistance(peers, (ZDO)(object)zdo, base.Config.Containers.AutoPickupMinPlayerDistance.Value)) { return false; } SharedData shared = zdo.PrefabInfo.ItemDrop.Value.ItemDrop.m_itemData.m_shared; ItemData val = null; bool flag = false; (ItemDrop, PrefabInfo.Optional, PrefabInfo.Optional, PrefabInfo.Optional, PrefabInfo.Optional)? itemDrop; if (Processor.Instance().ContainersByItemName.TryGetValue(shared, out ConcurrentHashSet value2)) { if (base.Config.Containers.AutoPickupExcludeFodder.Value) { foreach (TameableProcessor.ITameableState tame in Processor.Instance().Tames) { if (!tame.ZDO.PrefabInfo.Tameable.HasValue || !tame.ZDO.PrefabInfo.Tameable.Value.MonsterAI.m_consumeItems.Any((ItemDrop x) => x.m_itemData.m_shared.m_name == shared.m_name)) { continue; } float consumeSearchRange = tame.ZDO.PrefabInfo.Tameable.Value.MonsterAI.m_consumeSearchRange; consumeSearchRange *= consumeSearchRange; if (!(Utils.DistanceSqr(((ZDO)zdo).GetPosition(), ((ZDO)tame.ZDO).GetPosition()) < consumeSearchRange)) { continue; } itemDrop = zdo.PrefabInfo.ItemDrop; if (itemDrop.HasValue) { PrefabInfo.Optional item = itemDrop.GetValueOrDefault().Item2; if (item.Value != null && zdo.GetTimeSinceSpawned() < TimeSpan.FromSeconds(10.0)) { return false; } } base.UnregisterZdoProcessor = true; ExtendedZDO.ComponentFieldAccessor componentFieldAccessor = zdo.Fields(getUnknownComponent: false); if (componentFieldAccessor.UpdateValue(() => (ItemDrop x) => x.m_autoPickup, value: false, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\ItemDropProcessor.cs", 94)) { base.RecreateZdo = true; } if (componentFieldAccessor.UpdateValue(() => (ItemDrop x) => x.m_autoDestroy, value: false, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\ItemDropProcessor.cs", 96)) { base.RecreateZdo = true; } if (base.RecreateZdo) { zdo.ReleaseOwnershipInternal(); } return false; } } HashSet hashSet = null; foreach (ExtendedZDO item6 in (IEnumerable)value2) { if (!((ZDO)item6).IsValid() || !item6.PrefabInfo.Container.HasValue) { value2.Remove(item6); } else { if (item6.Vars.GetInUse()) { continue; } float num = ((float?)item6.Inventory.PickupRange) ?? base.Config.Containers.AutoPickupRange.Value; num *= num; if (num == 0f || Utils.DistanceSqr(((ZDO)zdo).GetPosition(), ((ZDO)item6).GetPosition()) > num) { continue; } if (val == null) { val = new ItemData { m_shared = shared }; ItemDrop.LoadFromZDO(val, (ZDO)(object)zdo, -1); } int num2 = val.m_stack; if (hashSet == null) { hashSet = new HashSet(); } hashSet.Clear(); bool flag2 = false; ItemData val2 = null; foreach (ItemData item7 in item6.Inventory.Items) { hashSet.Add(item7.m_gridPos); if (new ItemDataKey(val) != item7) { continue; } if (val2 == null) { val2 = item7; } int num3 = item7.m_shared.m_maxStackSize - item7.m_stack; if (num3 > 0) { if (base.Config.Containers.AutoPickupRequestOwnership.Value && !zdo.IsOwnerOrUnassigned()) { flag = true; } if (!item6.IsOwnerOrUnassigned()) { flag2 = true; } if (flag || flag2) { break; } int num4 = Math.Min(num2, num3); item7.m_stack += num4; num2 -= num4; if (num2 == 0) { break; } } } if (val2 == null) { value2.Remove(item6); if (value2 != null && value2.Count == 0) { Processor.Instance().ContainersByItemName.TryRemove(val.m_shared, out ConcurrentHashSet _); } continue; } int num5 = item6.Inventory.Inventory.GetEmptySlots(); while (num2 > 0 && num5 > 0) { if (base.Config.Containers.AutoPickupRequestOwnership.Value && !zdo.IsOwnerOrUnassigned()) { flag = true; } if (!item6.IsOwnerOrUnassigned()) { flag2 = true; } if (flag || flag2) { break; } int num6 = Math.Min(num2, val.m_shared.m_maxStackSize); ItemData val3 = val2.Clone(); val3.m_stack = num6; val3.m_gridPos.x = -1; for (int i = 0; i < item6.Inventory.Inventory.GetWidth(); i++) { if (val3.m_gridPos.x >= 0) { break; } for (int j = 0; j < item6.Inventory.Inventory.GetHeight(); j++) { if (hashSet.Add(new Vector2i(i, j))) { ref int x2 = ref val3.m_gridPos.x; ref int y = ref val3.m_gridPos.y; int num7 = i; int num8 = j; x2 = num7; y = num8; break; } } } item6.Inventory.Items.Add(val3); num2 -= num6; num5--; } if (flag || flag2) { if (flag2) { Processor.Instance().RequestOwnership(item6, 0L, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\ItemDropProcessor.cs", 203); } continue; } if (num2 != val.m_stack) { item6.Inventory.Save(); ItemData val4 = val; int num8 = num2; int stack = val.m_stack; val4.m_stack = num8; num2 = stack; ItemDrop.SaveToZDO(val, (ZDO)(object)zdo, -1); Processor.ShowMessage(peers, item6, base.Config.Localization.Containers.FormatAutoPickup(item6.PrefabInfo.Container.Value.Container.m_name, val.m_shared.m_name, num2), base.Config.Containers.PickedUpMessageType.Value, (TextType)0); } if (val.m_stack == 0) { break; } } } int? num9 = val?.m_stack; if (num9.HasValue && num9.GetValueOrDefault() == 0) { base.DestroyZdo = true; return false; } if (!_itemDrops.Contains(zdo)) { _itemDrops.Add(zdo); zdo.Destroyed += delegate(ExtendedZDO x) { _itemDrops.Remove(x); }; } if (flag) { RPC.RequestOwn(zdo, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\ItemDropProcessor.cs", 235); return true; } } itemDrop = zdo.PrefabInfo.ItemDrop; if (itemDrop.HasValue) { (ItemDrop, PrefabInfo.Optional, PrefabInfo.Optional, PrefabInfo.Optional, PrefabInfo.Optional) valueOrDefault = itemDrop.GetValueOrDefault(); PrefabInfo.Optional item2 = valueOrDefault.Item4; if (item2.Value == null) { PrefabInfo.Optional item3 = valueOrDefault.Item5; if (item3.Value == null && base.Config.World.MakeAllItemsFloat.Value && zdo.Vars.GetSpawnTime() < ZNet.instance.GetTime().AddSeconds(-2.0) && Processor.GetHeight(((ZDO)zdo).GetPosition()) < 28f && ((ZDO)zdo).GetPosition().y < 30f) { Vector3 position = ((ZDO)zdo).GetPosition(); position.y += 1f; ExtendedZDO crate = GetCrate(position, ((ZDO)zdo).GetRotation()); if (val == null) { val = new ItemData { m_shared = shared }; ItemDrop.LoadFromZDO(val, (ZDO)(object)zdo, -1); } val.m_dropPrefab = ((Component)zdo.PrefabInfo.ItemDrop.Value.ItemDrop).gameObject; foreach (ItemData item8 in crate.Inventory.Items) { if (ItemDataKeyComparer.Instance.Equals(item8, val)) { int num10 = Math.Min(val.m_stack, item8.m_shared.m_maxStackSize - item8.m_stack); item8.m_stack += num10; ItemData obj = val; obj.m_stack -= num10; if (val.m_stack == 0) { break; } } } if (val.m_stack > 0) { crate.Inventory.Items.Add(val); (int Width, int Height) backpackSize = PlayerProcessor.GetBackpackSize(crate.Inventory.Items.Count); int item4 = backpackSize.Width; int item5 = backpackSize.Height; ExtendedZDO.ComponentFieldAccessor componentFieldAccessor2 = crate.Fields(getUnknownComponent: false); bool num11 = componentFieldAccessor2.UpdateValue(() => (Container x) => x.m_width, item4, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\ItemDropProcessor.cs", 275); bool flag3 = componentFieldAccessor2.UpdateValue(() => (Container x) => x.m_height, item5, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\ItemDropProcessor.cs", 276); if (num11 || flag3) { using IEnumerator enumerator5 = crate.Inventory.Items.GetEnumerator(); for (int k = 0; k < item5; k++) { for (int l = 0; l < item4; l++) { if (!enumerator5.MoveNext()) { break; } enumerator5.Current.m_gridPos = new Vector2i(l, k); } } } } crate.Inventory.Save(); base.DestroyZdo = true; return false; } } } return true; } private ExtendedZDO GetCrate(Vector3 pos, Quaternion rot) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0035: Unknown result type (might be due to invalid IL or missing references) //IL_0041: 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_0079: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0061: Unknown result type (might be due to invalid IL or missing references) Vector2i key = new Vector2i(Mathf.FloorToInt(pos.x / 4f), Mathf.FloorToInt(pos.z / 4f)); if (!_crates.TryGetValue(key, out ExtendedZDO value) || !value.IsOwnerOrUnassigned()) { if (value != null) { _crates.Remove(key); } _crates.Add(key, value = PlaceObject(pos, Prefabs.CargoCrate, rot)); base.PlacedObjects.Remove(value); value.Destroyed += delegate { //IL_000c: Unknown result type (might be due to invalid IL or missing references) _crates.Remove(key); }; value.Vars.SetCreator(0L, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\ItemDropProcessor.cs", 312); } return value; } } internal sealed class LocationProcessor : Processor { private readonly Dictionary _zdosByBeacon = new Dictionary(); private Regex? _regex; protected override Guid Id { get; } = Guid.Parse("fbacfa56-3fd4-408c-aac7-cd39663d4ea2"); public override void Initialize(bool firstTime) { base.Initialize(firstTime); _regex = null; string text = base.Config.Wishbone.FindLocationObjectRegex.Value.Trim(); if (!string.IsNullOrEmpty(text)) { try { _regex = new Regex(text); } catch (Exception data) { base.Logger.LogError("Invalid regex pattern: " + text); base.Logger.LogError(data); } } } protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { //IL_0181: Unknown result type (might be due to invalid IL or missing references) //IL_0186: Unknown result type (might be due to invalid IL or missing references) //IL_0194: 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_01a7: Unknown result type (might be due to invalid IL or missing references) //IL_01bd: Unknown result type (might be due to invalid IL or missing references) //IL_0321: Unknown result type (might be due to invalid IL or missing references) //IL_0334: Unknown result type (might be due to invalid IL or missing references) //IL_035b: Unknown result type (might be due to invalid IL or missing references) //IL_0360: Unknown result type (might be due to invalid IL or missing references) //IL_0362: Unknown result type (might be due to invalid IL or missing references) //IL_0364: Unknown result type (might be due to invalid IL or missing references) //IL_0377: Unknown result type (might be due to invalid IL or missing references) ExtendedZDO zdo2 = zdo; if (_zdosByBeacon.TryGetValue(zdo2, out ExtendedZDO value)) { if (peers.Any((Peer x) => Utils.DistanceXZ(x.m_refPos, ((ZDO)zdo2).GetPosition()) < 2f)) { DestroyObject(zdo2); _zdosByBeacon.Remove(zdo2); value.Vars.SetBeaconFound(value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\LocationProcessor.cs", 37); } return false; } base.UnregisterZdoProcessor = true; if (zdo2.PrefabInfo.LocationProxy == null || base.Config.Wishbone.Range.Value <= 0f) { return false; } if (!base.Config.Wishbone.FindDungeons.Value && !base.Config.Wishbone.FindVegvisir.Value && _regex == null) { return false; } if (zdo2.Vars.GetBeaconFound()) { return false; } int location2 = zdo2.Vars.GetLocation(); if (location2 == 0) { base.UnregisterZdoProcessor = false; return true; } if (!ZoneSystem.instance.GetLocationsByHash().TryGetValue(location2, out ZoneLocation value2) || !value2.m_prefab.IsValid) { return false; } if (!value2.m_prefab.IsLoaded) { if (!value2.m_prefab.IsLoading) { value2.m_prefab.LoadAsync(); } base.UnregisterZdoProcessor = false; return false; } GameObject asset = value2.m_prefab.Asset; Vector3 position = asset.gameObject.transform.position; Quaternion rotation = asset.gameObject.transform.rotation; asset.gameObject.transform.position = Vector3.zero; asset.gameObject.transform.rotation = Quaternion.identity; List activeRandomSpawns2 = null; List positions2 = null; HashSet hashSet = null; if (base.Config.Wishbone.FindDungeons.Value) { Teleport[] componentsInChildren = asset.GetComponentsInChildren(); foreach (Teleport val in componentsInChildren) { if ((hashSet ?? (hashSet = new HashSet())).Add(((Component)val).gameObject)) { AddBeaconPosition(ref positions2, (Component?)(object)val, ref activeRandomSpawns2, asset, zdo2); } } } if (base.Config.Wishbone.FindVegvisir.Value) { Vegvisir[] componentsInChildren2 = asset.GetComponentsInChildren(); foreach (Vegvisir val2 in componentsInChildren2) { if ((hashSet ?? (hashSet = new HashSet())).Add(((Component)val2).gameObject)) { AddBeaconPosition(ref positions2, (Component?)(object)val2, ref activeRandomSpawns2, asset, zdo2); } } } if (_regex != null) { Component[] componentsInChildren3 = asset.GetComponentsInChildren(); foreach (Component val3 in componentsInChildren3) { if ((hashSet ?? (hashSet = new HashSet())).Add(val3.gameObject) && _regex.IsMatch(Utils.GetPrefabName(val3.gameObject))) { AddBeaconPosition(ref positions2, val3, ref activeRandomSpawns2, asset, zdo2); } } } asset.gameObject.transform.position = position; asset.gameObject.transform.rotation = rotation; if (positions2 == null || positions2.Count <= 0) { return false; } foreach (Vector3 item3 in positions2) { Vector3 pos = item3; pos.y -= 4f; ExtendedZDO extendedZDO = PlaceObject(pos, Prefabs.MountainRemainsBuried, 0f); extendedZDO.Fields(getUnknownComponent: true).Set(() => (Beacon x) => x.m_range, base.Config.Wishbone.Range.Value, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\LocationProcessor.cs", 115); _zdosByBeacon.Add(extendedZDO, zdo2); } return false; static void AddBeaconPosition(ref List? positions, Component? component, ref List? activeRandomSpawns, GameObject location, ExtendedZDO zdo) { //IL_0010: 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: 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_0031: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) //IL_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_0047: 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_0145: Unknown result type (might be due to invalid IL or missing references) //IL_0155: 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_015f: Unknown result type (might be due to invalid IL or missing references) //IL_0164: 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_00a1: 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_00aa: Unknown result type (might be due to invalid IL or missing references) //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00b8: 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) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_012b: Unknown result type (might be due to invalid IL or missing references) if (component != null) { RandomSpawn component2 = component.GetComponent(); if (component2 == null) { Vector3 item = ((ZDO)zdo).GetPosition() + ((ZDO)zdo).GetRotation() * component.gameObject.transform.position; (positions ?? (positions = new List())).Add(item); } else { if (activeRandomSpawns == null) { activeRandomSpawns = new List(); RandomSpawn[] enabledComponentsInChildren = Utils.GetEnabledComponentsInChildren(location); State state = Random.state; Random.InitState(zdo.Vars.GetSeed()); Location val4 = null; RandomSpawn[] array = enabledComponentsInChildren; foreach (RandomSpawn val5 in array) { Vector3 position2 = ((Component)val5).gameObject.transform.position; position2 = ((ZDO)zdo).GetPosition() + ((ZDO)zdo).GetRotation() * position2; val5.Prepare(); val5.Randomize(position2, val4 ?? (val4 = location.GetComponent()), (DungeonGenerator)null); if (((Component)val5).gameObject.activeSelf) { activeRandomSpawns.Add(val5); } val5.Reset(); ZNetView component3 = ((Component)val5).GetComponent(); if (component3 != null) { ((Component)component3).gameObject.SetActive(true); } } Random.state = state; } if (activeRandomSpawns.Contains(component2)) { Vector3 item2 = ((ZDO)zdo).GetPosition() + ((ZDO)zdo).GetRotation() * ((Component)component2).gameObject.transform.position; (positions ?? (positions = new List())).Add(item2); } } } } } } [Processor(Priority = int.MaxValue)] internal sealed class ManageOwnerProcessor : Processor { private readonly Dictionary ValidOwners)> _zoneData = new Dictionary)>(); private readonly Stack> _hashsetCache = new Stack>(); private readonly MethodInfo _releaseNearbyZDOSMethod = typeof(ZDOMan).GetMethod("ReleaseNearbyZDOS", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); private readonly MethodInfo _releaseNearbyZDOSPrefix = new Func(ReleaseNearbyZDOSPrefix).Method; private DateTimeOffset _maxOwnerTimestamp; protected override Guid Id { get; } = Guid.Parse("9178b9fe-ef1a-4e75-b492-ae392aa6b557"); public override void Initialize(bool firstTime) { //IL_010a: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Expected O, but got Unknown base.Initialize(firstTime); Main.HarmonyInstance.Unpatch((MethodBase)_releaseNearbyZDOSMethod, _releaseNearbyZDOSPrefix); if (base.Config.Networking.ReassignOwnershipBasedOnConnectionQuality.Value && !base.Config.Networking.MeasurePing.Value) { ConfigDefinition definition = ((ConfigEntryBase)base.Config.Networking.ReassignOwnershipBasedOnConnectionQuality).Definition; ConfigDefinition definition2 = ((ConfigEntryBase)base.Config.Networking.MeasurePing).Definition; base.Logger.LogWarning("Config option [" + definition.Section + "].[" + definition.Key + "] requires [" + definition.Section + "].[" + definition.Key + "] to be true, it does nothing otherwhise"); } else if (base.Config.Networking.ReassignOwnershipBasedOnConnectionQuality.Value) { Main.HarmonyInstance.Patch((MethodBase)_releaseNearbyZDOSMethod, new HarmonyMethod(_releaseNearbyZDOSPrefix), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } private static bool ReleaseNearbyZDOSPrefix() { return false; } protected override void PreProcessCore(IEnumerable peers) { foreach (var value in _zoneData.Values) { HashSet item = value.ValidOwners; item.Clear(); _hashsetCache.Push(item); } _zoneData.Clear(); _maxOwnerTimestamp = DateTimeOffset.UtcNow.AddSeconds(-2.0); } protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { //IL_01d1: Unknown result type (might be due to invalid IL or missing references) //IL_0126: Unknown result type (might be due to invalid IL or missing references) //IL_0132: 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) if (!((ZDO)zdo).Persistent) { return false; } base.UnregisterZdoProcessor = true; IPeerInfo peerInfo = null; IPeerInfo peerInfo2 = null; int count = peers.Count; if (zdo.PrefabInfo.Ship.HasValue && base.Config.Networking.AssignShipsToCaptain.Value) { base.UnregisterZdoProcessor = false; long user = zdo.Vars.GetUser(0L); if (user != 0L && count > 1) { foreach (Peer item in peers.AsEnumerable()) { IPeerInfo info = item.Info; if (info != null && info.PlayerID == user) { peerInfo2 = info; break; } } } } if (peerInfo2 == null && ShouldAssignToClosestPlayer(zdo)) { base.UnregisterZdoProcessor = false; if (count > 1 && zdo.OwnerTimestamp < _maxOwnerTimestamp) { IPeerInfo peerInfo3 = null; float num = float.MaxValue; foreach (Peer item2 in peers.AsEnumerable()) { IPeerInfo info2 = item2.Info; if (info2 != null) { float num2 = Utils.DistanceSqr(((ZDO)zdo).GetPosition(), ((ZDO)info2.PlayerZDO).GetPosition()); if (num2 < num) { num = num2; peerInfo3 = info2; } } } if (peerInfo3 != null) { peerInfo2 = peerInfo3; } } } if (peerInfo2 == null && base.Config.Networking.MeasurePing.Value && base.Config.Networking.ReassignOwnershipBasedOnConnectionQuality.Value) { base.UnregisterZdoProcessor = false; if (zdo.OwnerTimestamp < _maxOwnerTimestamp) { peerInfo = zdo.OwnerPeerInfo; if (!_zoneData.TryGetValue(((ZDO)zdo).GetSector(), out (IPeerInfo, HashSet) value)) { if (!_hashsetCache.TryPop(out value.Item2)) { value.Item2 = new HashSet(); } float num3 = float.MaxValue; foreach (Peer item3 in peers.AsEnumerable()) { value.Item2.Add(item3.m_uid); IPeerInfo info3 = item3.Info; if (info3 != null && info3.ConnectionQuality < num3) { num3 = info3.ConnectionQuality; value.Item1 = info3; } } _zoneData.Add(((ZDO)zdo).GetSector(), value); } if (value.Item1 != null && (peerInfo == null || !value.Item2.Contains(peerInfo.Owner) || SwitchOwner(peerInfo, value.Item1))) { (peerInfo2, _) = value; } } } if (peerInfo2 != null && (peerInfo ?? (peerInfo = zdo.OwnerPeerInfo)) != peerInfo2) { zdo.SetOwner(peerInfo2.Owner); } return false; } private bool ShouldAssignToClosestPlayer(ExtendedZDO zdo) { if (base.Config.Networking.AssignInteractablesToClosestPlayer.Value) { PrefabInfo prefabInfo = zdo.PrefabInfo; if ((object)prefabInfo == null || prefabInfo.Smelter != null || prefabInfo.CookingStation != null) { return true; } } if (base.Config.Networking.AssignMobsToClosestPlayer.Value) { (Humanoid, PrefabInfo.Optional, PrefabInfo.Optional)? humanoid = zdo.PrefabInfo.Humanoid; if (humanoid.HasValue) { PrefabInfo.Optional item = humanoid.GetValueOrDefault().Item2; if (item.Value != null) { return !zdo.Vars.GetTamed(); } } } return false; } private bool SwitchOwner(IPeerInfo currentOwner, IPeerInfo bestCandidate) { float num = base.Config.Networking.ReassignOwnershipConnectionQualityHysteresis.Value; if (num <= 0f) { return true; } if (num < 1f) { num = currentOwner.ConnectionQuality * num; } return currentOwner.ConnectionQuality - bestCandidate.ConnectionQuality >= num; } } internal sealed class MapTableProcessor : Processor { private record Pin(long OwnerId, string Tag, Vector3 Pos, PinType Type, bool IsChecked, string Author) { [CompilerGenerated] protected virtual bool PrintMembers(StringBuilder builder) { //IL_0053: 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_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) RuntimeHelpers.EnsureSufficientExecutionStack(); builder.Append("OwnerId = "); builder.Append(OwnerId.ToString()); builder.Append(", Tag = "); builder.Append((object?)Tag); builder.Append(", Pos = "); Vector3 pos = Pos; builder.Append(((object)(Vector3)(ref pos)).ToString()); builder.Append(", Type = "); PinType type = Type; builder.Append(((object)(PinType)(ref type)).ToString()); builder.Append(", IsChecked = "); builder.Append(IsChecked.ToString()); builder.Append(", Author = "); builder.Append((object?)Author); return true; } [CompilerGenerated] public void Deconstruct(out long OwnerId, out string Tag, out Vector3 Pos, out PinType Type, out bool IsChecked, out string Author) { //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_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0025: Expected I4, but got Unknown OwnerId = this.OwnerId; Tag = this.Tag; Pos = this.Pos; Type = (PinType)(int)this.Type; IsChecked = this.IsChecked; Author = this.Author; } } private readonly List _pins = new List(); private readonly List _existingPins = new List(); private byte[]? _emptyExplored; private int _pinsHash; private int _oldPinsHash; private Regex? _includePortalRegex; private Regex? _excludePortalRegex; private DateTimeOffset _nextUpdate; protected override Guid Id { get; } = Guid.Parse("7d16d783-e298-43ee-b621-11022e4b392a"); public override void Initialize(bool firstTime) { base.Initialize(firstTime); string text = base.Config.MapTables.AutoUpdatePortalsInclude.Value.Trim(); _includePortalRegex = (string.IsNullOrEmpty(text.Trim(new char[1] { '*' })) ? null : new Regex(Processor.ConvertToRegexPattern(text))); text = base.Config.MapTables.AutoUpdatePortalsExclude.Value.Trim(); _excludePortalRegex = (string.IsNullOrEmpty(text) ? null : new Regex(Processor.ConvertToRegexPattern(text))); if (firstTime) { _pins.Clear(); _existingPins.Clear(); } } protected override void PreProcessCore(IEnumerable peers) { _pins.Clear(); _oldPinsHash = 0; } protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { //IL_044e: Unknown result type (might be due to invalid IL or missing references) //IL_0454: Expected O, but got Unknown //IL_0336: Unknown result type (might be due to invalid IL or missing references) //IL_033c: Expected O, but got Unknown //IL_0342: Unknown result type (might be due to invalid IL or missing references) //IL_0344: Unknown result type (might be due to invalid IL or missing references) //IL_0347: Invalid comparison between Unknown and I4 //IL_035c: 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_04f2: Unknown result type (might be due to invalid IL or missing references) //IL_04ff: Unknown result type (might be due to invalid IL or missing references) //IL_0509: Expected I4, but got Unknown //IL_0222: Unknown result type (might be due to invalid IL or missing references) //IL_0227: Unknown result type (might be due to invalid IL or missing references) //IL_022b: 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_0243: Unknown result type (might be due to invalid IL or missing references) //IL_0282: 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_018b: Unknown result type (might be due to invalid IL or missing references) if (zdo.PrefabInfo.MapTable == null || (!base.Config.MapTables.AutoUpdatePortals.Value && !base.Config.MapTables.AutoUpdateShips.Value)) { base.UnregisterZdoProcessor = true; return false; } DateTimeOffset utcNow = DateTimeOffset.UtcNow; if (utcNow < _nextUpdate) { return false; } _nextUpdate = utcNow.AddSeconds(2.0); List pins = _pins; if (pins != null && pins.Count == 0) { if (base.Config.MapTables.AutoUpdatePortals.Value) { foreach (ExtendedZDO item in ZDOMan.instance.GetPortals().Values.SelectMany((List x) => x)) { if (!item.IsModCreator()) { string tag = item.Vars.GetTag(); if ((_includePortalRegex?.IsMatch(tag) ?? true) && ((!(_excludePortalRegex?.IsMatch(tag))) ?? true)) { Pin pin = new Pin(Main.PluginGuidHash, tag, ((ZDO)item).GetPosition(), (PinType)6, IsChecked: false, "argusmagnus.ServersideQoL"); _pins.Add(pin); _oldPinsHash = (_oldPinsHash, pin).GetHashCode(); } } } } if (base.Config.MapTables.AutoUpdateShips.Value) { foreach (ExtendedZDO ship in Processor.Instance().Ships) { Vector3 position = ((ZDO)ship).GetPosition(); ((Vector3)(ref position))..ctor(RoundToMultipleOf5(position.x), RoundToMultipleOf5(position.y), RoundToMultipleOf5(position.z)); Pin pin2 = new Pin(Main.PluginGuidHash, ship.PrefabInfo.Ship.Value.Piece.m_name ?? "", position, (PinType)10, IsChecked: false, "argusmagnus.ServersideQoL"); _pins.Add(pin2); _oldPinsHash = (_oldPinsHash, pin2).GetHashCode(); } } int oldPinsHash = _oldPinsHash; int pinsHash = _pinsHash; _pinsHash = oldPinsHash; _oldPinsHash = pinsHash; } if (_pinsHash == _oldPinsHash) { return false; } _existingPins.Clear(); byte[] array = zdo.Vars.GetData(); ZPackage val; if (array != null) { array = Utils.Decompress(array); val = new ZPackage(array); SharedMap val2 = (SharedMap)val.ReadInt(); if ((int)val2 != 3) { base.Logger.LogWarning(FormattableString.Invariant($"MapTable data version {val2:D} [{val2}] is not supported")); return false; } array = val.ReadByteArray(); if (array.Length != Minimap.instance.m_textureSize * Minimap.instance.m_textureSize) { base.Logger.LogWarning("Invalid explored map data length"); array = null; } int num = val.ReadInt(); if (_existingPins.Capacity < num) { _existingPins.Capacity = num; } foreach (int item2 in Enumerable.Range(0, num)) { Pin pin3 = new Pin(val.ReadLong(), val.ReadString(), val.ReadVector3(), (PinType)val.ReadInt(), val.ReadBool(), val.ReadString()); if (pin3.OwnerId != Main.PluginGuidHash) { _existingPins.Add(pin3); } } } val = new ZPackage(); val.Write(3); val.Write(array ?? _emptyExplored ?? (_emptyExplored = new byte[Minimap.instance.m_textureSize * Minimap.instance.m_textureSize])); val.Write(_pins.Count + _existingPins.Count); foreach (Pin item3 in _pins.Concat(_existingPins)) { val.Write(item3.OwnerId); val.Write(item3.Tag); val.Write(item3.Pos); val.Write((int)item3.Type); val.Write(item3.IsChecked); val.Write(item3.Author); } zdo.Vars.SetData(Utils.Compress(val.GetArray()), "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\MapTableProcessor.cs", 142); Processor.ShowMessage(peers, zdo, base.Config.Localization.MapTable.Updated, base.Config.MapTables.UpdatedMessageType.Value, (TextType)0); return false; static float RoundToMultipleOf5(float value) { return Mathf.Round(value / 5f) * 5f; } } } internal sealed class MineRockProcessor : Processor { private readonly ZPackage _pkg = new ZPackage(); private readonly List<(int Idx, float Health)> _notDestroyedIndices = new List<(int, float)>(); private bool _canCollapseBasedOnSkill; protected override Guid Id { get; } = Guid.Parse("12157bfa-d940-45b9-b6c8-eb0460c3c053"); public override void Initialize(bool firstTime) { base.Initialize(firstTime); _canCollapseBasedOnSkill = base.Config.Skills.PickaxeRockCollapseEnabled; } protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { //IL_0094: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Invalid comparison between Unknown and I4 //IL_00b6: 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_01e3: Unknown result type (might be due to invalid IL or missing references) //IL_01ea: Expected O, but got Unknown //IL_022d: Unknown result type (might be due to invalid IL or missing references) if (zdo.PrefabInfo.MineRock5 == null || !_canCollapseBasedOnSkill) { base.UnregisterZdoProcessor = true; return false; } string healthString = zdo.Vars.GetHealthString(); if (healthString == null || healthString.Length <= 0) { return true; } float num = 32f; IPeerInfo peerInfo = null; float num2 = float.NaN; foreach (IPeerInfo peerInfo2 in Processor.Instance().PeerInfos) { ItemDrop lastUsedItem = peerInfo2.LastUsedItem; if (lastUsedItem == null) { continue; } ItemData itemData = lastUsedItem.m_itemData; if (itemData == null) { continue; } SharedData shared = itemData.m_shared; if (shared != null && (int)shared.m_skillType == 12 && !float.IsNaN(num2 = peerInfo2.GetEstimatedSkillLevel((SkillType)12))) { float num3 = Vector3.Distance(((ZDO)peerInfo2.PlayerZDO).GetPosition(), ((ZDO)zdo).GetPosition()); if (!(num3 >= num)) { peerInfo = peerInfo2; num = num3; } } } if (peerInfo == null) { return true; } if (float.IsNaN(num2)) { num2 = 0f; } float num4 = Utils.Lerp((float)base.Config.Skills.PickaxeRockCollapseThresholdAtMinSkill.Value, (float)base.Config.Skills.PickaxeRockCollapseThresholdAtMaxSkill.Value, num2); num4 /= 100f; if (num4 >= 1f) { return true; } bool flag = num4 <= 0f; if (!flag) { _pkg.Load(Convert.FromBase64String(healthString)); int num5 = _pkg.ReadInt(); _notDestroyedIndices.Clear(); for (int i = 0; i < num5; i++) { float num6 = _pkg.ReadSingle(); if (num6 > 0f) { _notDestroyedIndices.Add((i, num6)); } } float num7 = (float)(num5 - _notDestroyedIndices.Count) / (float)num5; flag = num7 >= num4; } if (flag) { HitData val = new HitData(); foreach (var notDestroyedIndex in _notDestroyedIndices) { int item = notDestroyedIndex.Idx; float item2 = notDestroyedIndex.Health; val.m_damage.m_damage = item2; val.m_toolTier = short.MaxValue; val.m_hitType = (HitType)15; RPC.DamageMineRock5(zdo, val, item); } } return true; } } internal sealed class MisterProcessor : Processor { protected override Guid Id { get; } = Guid.Parse("bc1174a9-43c5-4594-8754-bc059bbee284"); protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { //IL_01c1: Unknown result type (might be due to invalid IL or missing references) //IL_01c7: Unknown result type (might be due to invalid IL or missing references) base.UnregisterZdoProcessor = true; if (zdo.PrefabInfo.Mister == null) { return false; } ExtendedZDO.ComponentFieldAccessor componentFieldAccessor = zdo.Fields(getUnknownComponent: false); switch (base.Config.World.RemoveMistlandsMist.Value) { case ModConfigBase.WorldConfig.RemoveMistlandsMistOptions.Never: if (componentFieldAccessor.UpdateResetValue(() => (Mister x) => x.m_radius, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\MisterProcessor.cs", 20)) { base.RecreateZdo = true; } break; case ModConfigBase.WorldConfig.RemoveMistlandsMistOptions.Always: if (componentFieldAccessor.UpdateValue(() => (Mister x) => x.m_radius, float.MinValue, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\MisterProcessor.cs", 25)) { base.RecreateZdo = true; } break; case ModConfigBase.WorldConfig.RemoveMistlandsMistOptions.AfterQueenKilled: if (ZoneSystem.instance.GetGlobalKey("defeated_queen")) { if (componentFieldAccessor.UpdateValue(() => (Mister x) => x.m_radius, float.MinValue, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\MisterProcessor.cs", 32)) { base.RecreateZdo = true; } break; } base.UnregisterZdoProcessor = false; if (componentFieldAccessor.UpdateResetValue(() => (Mister x) => x.m_radius, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\MisterProcessor.cs", 38)) { base.RecreateZdo = true; } break; case ModConfigBase.WorldConfig.RemoveMistlandsMistOptions.InsideShield: { base.UnregisterZdoProcessor = false; float num = float.PositiveInfinity; float num2 = Mathf.Max(ParticleMist.instance.m_localRange, ParticleMist.instance.m_distantMaxRange); foreach (var (extendedZDO2, flag2) in Processor.Instance().ShieldGenerators) { if (flag2) { float num3 = Vector3.Distance(((ZDO)extendedZDO2).GetPosition(), ((ZDO)zdo).GetPosition()); num = Mathf.Min(num, num3 - extendedZDO2.PrefabInfo.ShieldGenerator.m_maxShieldRadius - num2); } } if (zdo.PrefabInfo.Mister.m_radius > num) { if (componentFieldAccessor.UpdateValue(() => (Mister x) => x.m_radius, num, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\MisterProcessor.cs", 57)) { base.RecreateZdo = true; } } else if (componentFieldAccessor.UpdateResetValue(() => (Mister x) => x.m_radius, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\MisterProcessor.cs", 62)) { base.RecreateZdo = true; } break; } } return false; } } internal sealed class PlantProcessor : Processor { protected override Guid Id { get; } = Guid.Parse("6b337a7f-e751-454e-ac84-b6c3b4679535"); protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { base.UnregisterZdoProcessor = true; if (zdo.PrefabInfo.Plant != null && (base.Config.Plants.GrowTimeMultiplier.Value != 1f || base.Config.Plants.SpaceRequirementMultiplier.Value != 1f)) { ExtendedZDO.ComponentFieldAccessor componentFieldAccessor = zdo.Fields(getUnknownComponent: false); if (base.Config.Plants.GrowTimeMultiplier.Value != 1f) { if (componentFieldAccessor.UpdateValue(() => (Plant x) => x.m_growTime, zdo.PrefabInfo.Plant.m_growTime * base.Config.Plants.GrowTimeMultiplier.Value, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlantProcessor.cs", 34)) { base.RecreateZdo = true; } if (componentFieldAccessor.UpdateValue(() => (Plant x) => x.m_growTimeMax, zdo.PrefabInfo.Plant.m_growTimeMax * base.Config.Plants.GrowTimeMultiplier.Value, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlantProcessor.cs", 36)) { base.RecreateZdo = true; } } if (base.Config.Plants.SpaceRequirementMultiplier.Value != 1f && componentFieldAccessor.UpdateValue(() => (Plant x) => x.m_growRadius, zdo.PrefabInfo.Plant.m_growRadius * base.Config.Plants.SpaceRequirementMultiplier.Value, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlantProcessor.cs", 41)) { base.RecreateZdo = true; } if (!base.Config.Plants.DontDestroyIfCantGrow.Value) { componentFieldAccessor.Reset(() => (Plant x) => x.m_destroyIfCantGrow, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlantProcessor.cs", 48); } else if (componentFieldAccessor.UpdateValue(() => (Plant x) => x.m_destroyIfCantGrow, value: false, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlantProcessor.cs", 49)) { base.RecreateZdo = true; } } return false; } } internal sealed class PlayerProcessor : Processor { [Flags] public enum BuildModifiers : uint { None = 0u, DisableRainDamage = 1u, DisableSupportRequirements = 2u, MakeIndestructible = 4u, NoWorkbench = 8u, DungeonBuild = 0x10u, NoBuildCost = 0x20u, AllPiecesUnlocked = 0x40u } public enum LevelGroundModes { Default, FlattenMedium, FlattenLarge, Reset } private sealed record StackContainerState(ExtendedZDO PlayerZDO) { public DateTimeOffset RemoveAfter { get; set; } = DateTimeOffset.UtcNow.AddSeconds(20.0); public bool Stacked { get; set; } } private sealed class TerrainCompData { private const int TerrainCompVersion = 1; private readonly ExtendedZDO _zdo; private readonly Heightmap _hmap; private bool[]? _modifiedHeight; private float[] _levelDelta; private float[] _smoothDelta; private bool[] _modifiedPaint; private Color[] _paintMask; private int _operations; private Vector3 _lastOpPoint; private float _lastOpRadius; public bool? HasModifications { get; private set; } public static TerrainCompData? Load(ExtendedZDO zdo) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) Heightmap heightmap = Processor.GetHeightmap(((ZDO)zdo).GetPosition()); if (heightmap == null) { Main.Instance.Logger.LogWarning($"Heightmap not found at {((ZDO)zdo).GetPosition()}"); return null; } return new TerrainCompData(zdo, heightmap); } private TerrainCompData(ExtendedZDO zdo, Heightmap hmap) { _zdo = zdo; _hmap = hmap; } [MemberNotNullWhen(true, "_modifiedHeight")] private bool Load() { //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Expected O, but got Unknown //IL_006c: 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_01ec: 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_0189: Unknown result type (might be due to invalid IL or missing references) //IL_01c3: Unknown result type (might be due to invalid IL or missing references) //IL_01c5: Unknown result type (might be due to invalid IL or missing references) //IL_01cf: Unknown result type (might be due to invalid IL or missing references) //IL_01d1: Unknown result type (might be due to invalid IL or missing references) //IL_02e9: Unknown result type (might be due to invalid IL or missing references) //IL_02ee: Unknown result type (might be due to invalid IL or missing references) if (_modifiedHeight != null) { return true; } byte[] byteArray = ((ZDO)_zdo).GetByteArray(ZDOVars.s_TCData, (byte[])null); if (byteArray == null) { return false; } int num = _hmap.m_width + 1; num *= num; ZPackage val = new ZPackage(Utils.Decompress(byteArray)); if (val.ReadInt() != 1) { Main.Instance.Logger.LogWarning("Terrain data load error, version missmatch"); return false; } _operations = val.ReadInt(); _lastOpPoint = val.ReadVector3(); _lastOpRadius = val.ReadSingle(); int num2 = val.ReadInt(); if (num2 != num) { Main.Instance.Logger.LogWarning("Terrain data load error, height array missmatch"); return false; } _modifiedHeight = new bool[num]; _levelDelta = new float[num]; _smoothDelta = new float[num]; _modifiedPaint = new bool[num]; _paintMask = (Color[])(object)new Color[num]; HasModifications = false; for (int i = 0; i < num2; i++) { _modifiedHeight[i] = val.ReadBool(); if (_modifiedHeight[i]) { _levelDelta[i] = val.ReadSingle(); _smoothDelta[i] = val.ReadSingle(); HasModifications = true; } else { _levelDelta[i] = 0f; _smoothDelta[i] = 0f; } } int num3 = val.ReadInt(); for (int j = 0; j < num3; j++) { _modifiedPaint[j] = val.ReadBool(); if (_modifiedPaint[j]) { Color val2 = default(Color); val2.r = val.ReadSingle(); val2.g = val.ReadSingle(); val2.b = val.ReadSingle(); val2.a = val.ReadSingle(); Color val3 = val2; _paintMask[j] = val3; HasModifications = true; } else { _paintMask[j] = Color.black; } } if (num3 == _hmap.m_width * _hmap.m_width) { Color[] array = (Color[])(object)new Color[_paintMask.Length]; _paintMask.CopyTo(array, 0); bool[] array2 = new bool[_modifiedPaint.Length]; _modifiedPaint.CopyTo(array2, 0); int num4 = _hmap.m_width + 1; for (int k = 0; k < _paintMask.Length; k++) { int num5 = k / num4; int num6 = (k + 1) / num4; int num7 = k - num5; if (num5 == _hmap.m_width) { num7 -= _hmap.m_width; } if (k > 0 && (k - num5) % _hmap.m_width == 0 && (k + 1 - num6) % _hmap.m_width == 0) { num7--; } _paintMask[k] = array[num7]; _modifiedPaint[k] = array2[num7]; } } return true; } private void Save() { //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //IL_0030: Unknown result type (might be due to invalid IL or missing references) if (_modifiedHeight == null) { return; } HasModifications = false; ZPackage val = new ZPackage(); val.Write(1); val.Write(_operations); val.Write(_lastOpPoint); val.Write(_lastOpRadius); val.Write(_modifiedHeight.Length); for (int i = 0; i < _modifiedHeight.Length; i++) { val.Write(_modifiedHeight[i]); if (_modifiedHeight[i]) { val.Write(_levelDelta[i]); val.Write(_smoothDelta[i]); HasModifications = true; } } val.Write(_modifiedPaint.Length); for (int j = 0; j < _modifiedPaint.Length; j++) { val.Write(_modifiedPaint[j]); if (_modifiedPaint[j]) { val.Write(_paintMask[j].r); val.Write(_paintMask[j].g); val.Write(_paintMask[j].b); val.Write(_paintMask[j].a); HasModifications = true; } } byte[] array = Utils.Compress(val.GetArray()); ((ZDO)_zdo).Set(ZDOVars.s_TCData, array); } public void ResetTerrain(Vector3 pos, float radius) { //IL_0006: 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_001c: 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: 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) //IL_00f0: Unknown result type (might be due to invalid IL or missing references) int num = default(int); int num2 = default(int); _hmap.WorldToVertex(pos, ref num, ref num2); float num3 = pos.y - ((ZDO)_zdo).GetPosition().y; float num4 = radius / _hmap.m_scale; int num5 = Mathf.CeilToInt(num4); Vector2 val = default(Vector2); ((Vector2)(ref val))..ctor((float)num, (float)num2); int num6 = _hmap.m_width + 1; bool flag = false; for (int i = num2 - num5; i <= num2 + num5; i++) { for (int j = num - num5; j <= num + num5; j++) { float num7 = Vector2.Distance(val, new Vector2((float)j, (float)i)); if (!(num7 > num4) && j >= 0 && i >= 0 && j < num6 && i < num6) { if (!Load()) { return; } int num8 = i * num6 + j; _modifiedHeight[num8] = false; _smoothDelta[num8] = 0f; _levelDelta[num8] = 0f; _modifiedPaint[num8] = false; _paintMask[num8] = Color.black; flag = true; } } } if (flag) { Save(); } } } private sealed class PlayerState : IPeerInfo { private readonly PlayerProcessor _processor; private readonly ZNetPeer? _peer; private long? _playerID; private string? _playerName; private bool? _isAdmin; private ExtendedZDO? _backpackContainer; [CompilerGenerated] private Dictionary k__BackingField; [CompilerGenerated] private Dictionary Queue, List List)> k__BackingField; [CompilerGenerated] private ExtendedZDO? k__BackingField; private bool _hasChangedGlobalKeyModifications; private Dictionary? _globalKeyModifications; private readonly Queue _pingHistory; private DateTimeOffset _pingStart; public long Owner { get; } public ExtendedZDO PlayerZDO { get; } public ZRpc? Rpc => _peer?.m_rpc; public long PlayerID { get { long valueOrDefault = _playerID.GetValueOrDefault(); if (!_playerID.HasValue) { valueOrDefault = PlayerZDO.Vars.GetPlayerID(0L); _playerID = valueOrDefault; return valueOrDefault; } return valueOrDefault; } } public string PlayerName => _playerName ?? (_playerName = PlayerZDO.Vars.GetPlayerName()); public bool IsAdmin { get { //IL_0030: 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_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Unknown result type (might be due to invalid IL or missing references) bool valueOrDefault = _isAdmin.GetValueOrDefault(); if (!_isAdmin.HasValue) { Player localPlayer = Player.m_localPlayer; ZDOID? val = ((localPlayer != null) ? new ZDOID?(((Character)localPlayer).GetZDOID()) : null); ZDOID uid = ((ZDO)PlayerZDO).m_uid; int num; if (!val.HasValue || !(val.GetValueOrDefault() == uid)) { ZNet instance = ZNet.instance; ZNetPeer? peer = _peer; num = (instance.IsAdmin(((peer != null) ? peer.m_socket.GetHostName() : null) ?? "") ? 1 : 0); } else { num = 1; } valueOrDefault = (byte)num != 0; _isAdmin = valueOrDefault; return valueOrDefault; } return valueOrDefault; } } public int LastEmoteId { get; set; } public int LastCraftingAnimation { get; set; } public Vector3? InitialInInteriorPosition { get; set; } public DateTimeOffset NextStaminaCheck { get; set; } public int Stamina { get; set; } public DateTimeOffset StaminaTimestamp { get; set; } public int Eitr { get; set; } public DateTimeOffset EitrTimestamp { get; set; } public ExtendedZDO? BackpackContainer { get { return _backpackContainer; } set { if (_backpackContainer != null) { _processor._backpacks.Remove(_backpackContainer); } _backpackContainer = value; if (_backpackContainer != null) { _processor._backpacks.Add(_backpackContainer, this); _backpackContainer.Destroyed += OnBackpackDestroyed; } } } public DateTimeOffset? OpenBackpackAfter { get; set; } public BuildModifiers BuildModifiers { get; set; } public LevelGroundModes LevelGroundMode { get; set; } public DateTimeOffset NextBuildModifierMessage { get; set; } public DateTimeOffset NextLevelGroundModeMessage { get; set; } public ItemDrop? LastUsedItem { get; set; } public ItemDrop? CheckSkillItem { get; set; } public float CheckSkillStaminaEitr { get; set; } public Dictionary EstimatedSkillLevels => k__BackingField ?? (k__BackingField = new Dictionary()); public Dictionary Queue, List List)> EstimatedSkillLevelHistories => k__BackingField ?? (k__BackingField = new Dictionary, List)>()); public ExtendedZDO? AttachedCart { get { return k__BackingField; } set { } } public IReadOnlyDictionary GlobalKeyModifications { get { IReadOnlyDictionary globalKeyModifications = _globalKeyModifications; return globalKeyModifications ?? ReadOnlyDictionary.Empty; } } public TimeSpan? LastPing { get; private set; } public DateTimeOffset? LastPingTimestamp { get; private set; } public TimeSpan? PingMean { get; private set; } public TimeSpan? PingStdDev { get; private set; } public TimeSpan? PingJitter { get; private set; } public TimeSpan? PingEMA { get; private set; } public float ConnectionQuality { get; private set; } public PlayerState(ExtendedZDO playerZDO, PlayerProcessor processor) { _processor = processor; Owner = ((ZDO)playerZDO).GetOwner(); PlayerZDO = playerZDO; _peer = ZNet.instance.GetPeer(((ZDO)playerZDO).GetOwner()); StaminaTimestamp = DateTimeOffset.UtcNow; EitrTimestamp = DateTimeOffset.UtcNow; NextBuildModifierMessage = DateTimeOffset.MaxValue; NextLevelGroundModeMessage = DateTimeOffset.MaxValue; _pingHistory = new Queue(); base..ctor(); } private void OnBackpackDestroyed(ExtendedZDO backpack) { _processor._backpacks.Remove(backpack); if (backpack == _backpackContainer) { _backpackContainer = null; } } [MemberNotNull("BackpackContainer")] public bool EnsureBackpackExists() { //IL_000c: 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_0174: 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_00bb: 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) int privateChest = Prefabs.PrivateChest; Vector3 position = ((ZDO)PlayerZDO).GetPosition(); position.y -= 0.6f; if (BackpackContainer == null) { BackpackContainer = _processor.PlacedObjects.FirstOrDefault((ExtendedZDO x) => x.PrefabInfo.Container.HasValue && x.IsModCreator(out var marker) && marker == CreatorMarkers.ProcessorOwned && x.Vars.GetPlayerID(0L) == PlayerID); BackpackContainer?.Fields(getUnknownComponent: false).Set(() => (Container x) => x.m_name, _processor.Config.Localization.Players.Backpack.Name, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerProcessor.PlayerState.cs", 95); } if (BackpackContainer == null) { BackpackContainer = _processor.PlacePiece(position, privateChest, 0f, CreatorMarkers.ProcessorOwned); BackpackContainer.Vars.SetPlayerID(PlayerID, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerProcessor.PlayerState.cs", 108); BackpackContainer.Fields(getUnknownComponent: false).Set(() => (Container x) => x.m_name, _processor.Config.Localization.Players.Backpack.Name, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerProcessor.PlayerState.cs", 109); AdjustSize(BackpackContainer, _processor._backpackSlots); BackpackContainer.SetOwnerInternal(Owner); } else { if (!(Vector3.Distance(((ZDO)PlayerZDO).GetPosition(), ((ZDO)BackpackContainer).GetPosition()) > InventoryGui.instance.m_autoCloseDistance) && !AdjustSize(BackpackContainer, _processor._backpackSlots)) { return true; } ((ZDO)BackpackContainer).SetPosition(position); BackpackContainer.SetOwnerInternal(Owner); BackpackContainer = _processor.RecreatePiece(BackpackContainer); } return false; static bool AdjustSize(ExtendedZDO zdo, int slots) { //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00e1: Unknown result type (might be due to invalid IL or missing references) ExtendedZDO.ComponentFieldAccessor componentFieldAccessor = zdo.Fields(getUnknownComponent: false); int slots2 = Math.Max(slots, zdo.Inventory.Items.Count); (int Width, int Height) backpackSize = GetBackpackSize(slots2); int item = backpackSize.Width; int item2 = backpackSize.Height; bool num = componentFieldAccessor.UpdateValue(() => (Container x) => x.m_width, item, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerProcessor.PlayerState.cs", 70); bool flag = componentFieldAccessor.UpdateValue(() => (Container x) => x.m_height, item2, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerProcessor.PlayerState.cs", 71); if (!num && !flag) { return false; } using (IEnumerator enumerator = zdo.Inventory.Items.GetEnumerator()) { int num2 = 0; while (true) { if (num2 >= item2) { flag = true; break; } int num3 = 0; while (true) { if (num3 >= item) { num2++; break; } if (!enumerator.MoveNext()) { zdo.ClaimOwnershipInternal(); zdo.Inventory.Save(); flag = true; goto end_IL_00f7; } enumerator.Current.m_gridPos = new Vector2i(num3, num2); num3++; } continue; end_IL_00f7: break; } } return flag; } } public float GetEstimatedSkillLevel(SkillType skillType) { //IL_0006: 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_002a: Unknown result type (might be due to invalid IL or missing references) if (!EstimatedSkillLevels.TryGetValue(skillType, out var value)) { EstimatedSkillLevels.Add(skillType, value = Processor.DataZDO.Vars.GetEstimatedSkillLevel(PlayerID, skillType, float.NaN)); } return value; } public void AddGlobalKeyModification(GlobalKey key, bool add) { if (_globalKeyModifications == null) { _globalKeyModifications = new Dictionary(); } if (_globalKeyModifications.TryAdd(key, add)) { _hasChangedGlobalKeyModifications = true; } } public void RemoveGlobalKeyModification(GlobalKey key) { if (_globalKeyModifications?.Remove(key) ?? false) { _hasChangedGlobalKeyModifications = true; } } public void SendGlobalKeyModifications() { if (_hasChangedGlobalKeyModifications) { ZoneSystem.instance.SendGlobalKeys(Owner); _hasChangedGlobalKeyModifications = false; } } public static void ReceivePingPrefix(ZRpc __instance, ZPackage package) { int pos = package.GetPos(); bool flag = !package.ReadBool(); package.SetPos(pos); if (flag && Processor.Instance()._statesByRpc.TryGetValue(__instance, out PlayerState value)) { value.ReceivePingPrefix(); } } public static bool SendPackagePrefix(ZRpc __instance, ZPackage pkg) { int pos = pkg.GetPos(); pkg.SetPos(0); bool flag = pkg.ReadInt() == 0 && pkg.ReadBool(); pkg.SetPos(pos); if (!flag || !Processor.Instance()._statesByRpc.TryGetValue(__instance, out PlayerState value)) { return true; } return value.SendPingPrefix(); } private void ReceivePingPrefix() { //IL_03dc: Unknown result type (might be due to invalid IL or missing references) DateTimeOffset utcNow = DateTimeOffset.UtcNow; LastPing = utcNow - _pingStart; _pingStart = default(DateTimeOffset); if (!PingEMA.HasValue || !LastPingTimestamp.HasValue) { PingEMA = LastPing; } else { double totalSeconds = (utcNow - LastPingTimestamp.Value).TotalSeconds; double num = 1.0 - Math.Exp((0.0 - totalSeconds) / _processor._emaTau); PingEMA = num * LastPing.Value + (1.0 - num) * PingEMA.Value; } LastPingTimestamp = utcNow; ModConfigBase.NetworkingConfig networking = _processor.Config.Networking; while (_pingHistory.Count >= networking.PingStatisticsWindow.Value) { _pingHistory.Dequeue(); } _pingHistory.Enqueue(LastPing.GetValueOrDefault()); (TimeSpan?, TimeSpan?, TimeSpan?) tuple = CalculateStats(_pingHistory); PingMean = tuple.Item1; PingStdDev = tuple.Item2; PingJitter = tuple.Item3; double? num2 = PingMean?.TotalMilliseconds * (double)networking.ConnectionQualityPingMeanWeight.Value + PingStdDev?.TotalMilliseconds * (double)networking.ConnectionQualityPingStdDevWeight.Value + PingJitter?.TotalMilliseconds * (double)networking.ConnectionQualityPingJitterWeight.Value + PingEMA?.TotalMilliseconds * (double)networking.ConnectionQualityPingEMAWeight.Value; ConnectionQuality = ((!num2.HasValue) ? float.NaN : ((float)num2.Value)); PlayerState value = null; if (_processor._zoneControls.TryGetValue(((ZDO)PlayerZDO).GetSector(), out ExtendedZDO value2) && ((ZDO)value2).GetOwner() != ((ZDO)PlayerZDO).GetOwner()) { _processor._playerStates.TryGetValue(((ZDO)value2).GetOwner(), out value); } if (LastPing > TimeSpan.FromMilliseconds(networking.LogPingThreshold.Value) || value?.LastPing > TimeSpan.FromMilliseconds(networking.LogZoneOwnerPingThreshold.Value)) { if (value == null) { _processor.Logger.LogInfo(string.Format(networking.LogPingFormat.Value, PlayerName, LastPing?.TotalMilliseconds, PingMean?.TotalMilliseconds, PingStdDev?.TotalMilliseconds, PingJitter?.TotalMilliseconds, ConnectionQuality, PingEMA?.TotalMilliseconds)); } else { _processor.Logger.LogInfo(string.Format(networking.LogZoneOwnerPingFormat.Value, PlayerName, LastPing?.TotalMilliseconds, PingMean?.TotalMilliseconds, PingStdDev?.TotalMilliseconds, PingJitter?.TotalMilliseconds, ConnectionQuality, value.PlayerName, value.LastPing?.TotalMilliseconds, value.PingMean?.TotalMilliseconds, value.PingStdDev?.TotalMilliseconds, value.PingJitter?.TotalMilliseconds, value.ConnectionQuality, PingEMA?.TotalMilliseconds, value.PingEMA?.TotalMilliseconds)); } } if (LastPing > TimeSpan.FromMilliseconds(networking.ShowPingThreshold.Value) || value?.LastPing > TimeSpan.FromMilliseconds(networking.ShowZoneOwnerPingThreshold.Value)) { if (value == null) { RPC.ShowMessage(((ZDO)PlayerZDO).GetOwner(), (MessageType)1, string.Format(networking.ShowPingFormat.Value, LastPing?.TotalMilliseconds, PingMean?.TotalMilliseconds, PingStdDev?.TotalMilliseconds, PingJitter?.TotalMilliseconds, ConnectionQuality, PingEMA?.TotalMilliseconds)); return; } RPC.ShowMessage(((ZDO)PlayerZDO).GetOwner(), (MessageType)1, string.Format(networking.ShowZoneOwnerPingFormat.Value, LastPing?.TotalMilliseconds, PingMean?.TotalMilliseconds, PingStdDev?.TotalMilliseconds, PingJitter?.TotalMilliseconds, ConnectionQuality, value.PlayerName, value.LastPing?.TotalMilliseconds, value.PingMean?.TotalMilliseconds, value.PingStdDev?.TotalMilliseconds, value.PingJitter?.TotalMilliseconds, value.ConnectionQuality, PingEMA?.TotalMilliseconds, value.PingEMA?.TotalMilliseconds)); } static (TimeSpan? Mean, TimeSpan? StdDev, TimeSpan? Jitter) CalculateStats(Queue pingHistory) { if (pingHistory.Count < 2) { return default((TimeSpan?, TimeSpan?, TimeSpan?)); } double num3 = 0.0; double num4 = 0.0; long ticks = pingHistory.FirstOrDefault().Ticks; long num5 = 0L; int num6 = 0; foreach (TimeSpan item in pingHistory) { if (item == default(TimeSpan)) { return default((TimeSpan?, TimeSpan?, TimeSpan?)); } double totalMilliseconds = item.TotalMilliseconds; double num7 = totalMilliseconds - num3; num3 += num7 / (double)(++num6); num4 += num7 * (totalMilliseconds - num3); num5 += Math.Abs(item.Ticks - ticks); ticks = item.Ticks; } num6--; num4 /= (double)num6; num5 /= num6; return (double.IsNaN(num3) ? null : new TimeSpan?(TimeSpan.FromMilliseconds(num3)), double.IsNaN(num4) ? null : new TimeSpan?(TimeSpan.FromMilliseconds(Math.Sqrt(num4))), (num5 == 0L) ? null : new TimeSpan?(new TimeSpan(num5))); } } private bool SendPingPrefix() { if (_pingStart != default(DateTimeOffset) && Rpc != null && Rpc.GetTimeSinceLastPing() < ZNet.instance.m_badConnectionPing) { return false; } if (_pingStart == default(DateTimeOffset)) { _pingStart = DateTimeOffset.UtcNow; } return true; } } private readonly Dictionary _playerStates = new Dictionary(); private readonly Dictionary _statesByRpc = new Dictionary(); private readonly Dictionary _players = new Dictionary(); private readonly Dictionary _playersByID = new Dictionary(); private readonly Dictionary _zoneControls = new Dictionary(); private readonly Dictionary _backpacks = new Dictionary(); private int _backpackSlots; private bool _estimateSkillLevels; private double _emaTau; private readonly int _numberOfLevelGroundModes = Enum.GetValues(typeof(LevelGroundModes)).Length; private readonly int _mudRoadPrefab = StringExtensionMethods.GetStableHashCode("vfx_Place_mud_road", true); [CompilerGenerated] private ZoneLocation k__BackingField; [CompilerGenerated] private ZoneLocation k__BackingField; private readonly Dictionary _stackContainers = new Dictionary(); private readonly MethodInfo _everybodyIsTryingToSleepMethod = typeof(Game).GetMethod("EverybodyIsTryingToSleep", BindingFlags.Instance | BindingFlags.NonPublic); private readonly MethodInfo _everybodyIsTryingToSleepPrefix = new <>F{00000001}(EverybodyIsTryingToSleepPrefix).Method; private readonly MethodInfo _receivePingMethod = typeof(ZRpc).GetMethod("ReceivePing", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); private readonly MethodInfo _receivePingPefix = new Action(PlayerState.ReceivePingPrefix).Method; private readonly MethodInfo _sendPackageMethod = typeof(ZRpc).GetMethod("SendPackage", BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic); private readonly MethodInfo _sendPackagePrefix = new Func(PlayerState.SendPackagePrefix).Method; protected override Guid Id { get; } = Guid.Parse("159d939c-cb85-4314-ac30-f473d043fdc2"); public BuildModifiers PossibleBuildModifiers { get; private set; } public IReadOnlyDictionary Players => _players; public IReadOnlyDictionary PlayersByID => _playersByID; private static TimeSpan OpenBackpackDelay => TimeSpan.FromMilliseconds(200.0); private ZoneLocation DevGround1 => k__BackingField ?? (k__BackingField = GetZoneLocation("DevGround1")); private ZoneLocation DevGround2 => k__BackingField ?? (k__BackingField = GetZoneLocation("DevGround2")); public IReadOnlyCollection PeerInfos => _playerStates.Values; private static int BackpackTombstonePrefab => Prefabs.TombStone; public event Action? PlayerDestroyed; private static ZoneLocation GetZoneLocation([CallerMemberName] string name = null) { return ZoneSystem.instance.GetLocationsByHash()[StringExtensionMethods.GetStableHashCode(name, true)]; } public ExtendedZDO? GetPeerCharacter(long peerID) { if (!_playerStates.TryGetValue(peerID, out PlayerState value)) { return null; } return value.PlayerZDO; } public IPeerInfo? GetPeerInfo(long peerID) { if (!_playerStates.TryGetValue(peerID, out PlayerState value)) { return null; } return value; } public IPeerInfo? GetPeerInfoFromPlayerID(long playerID) { if (!_playersByID.TryGetValue(playerID, out ExtendedZDO value) || !_playerStates.TryGetValue(((ZDO)value).GetOwner(), out PlayerState value2)) { return null; } return value2; } public override void Initialize(bool firstTime) { //IL_01b6: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Expected O, but got Unknown //IL_0269: Unknown result type (might be due to invalid IL or missing references) //IL_026f: Invalid comparison between Unknown and I4 //IL_0219: Unknown result type (might be due to invalid IL or missing references) //IL_0227: Expected O, but got Unknown //IL_0239: Unknown result type (might be due to invalid IL or missing references) //IL_0247: Expected O, but got Unknown //IL_02bf: Unknown result type (might be due to invalid IL or missing references) //IL_02c5: Invalid comparison between Unknown and I4 //IL_02e5: Unknown result type (might be due to invalid IL or missing references) //IL_02eb: Invalid comparison between Unknown and I4 //IL_030b: Unknown result type (might be due to invalid IL or missing references) //IL_0311: Invalid comparison between Unknown and I4 //IL_0331: Unknown result type (might be due to invalid IL or missing references) //IL_0337: Invalid comparison between Unknown and I4 //IL_0357: Unknown result type (might be due to invalid IL or missing references) //IL_035d: Invalid comparison between Unknown and I4 //IL_037e: Unknown result type (might be due to invalid IL or missing references) //IL_0384: Invalid comparison between Unknown and I4 //IL_03a5: Unknown result type (might be due to invalid IL or missing references) //IL_03ab: Invalid comparison between Unknown and I4 base.Initialize(firstTime); _estimateSkillLevels = base.Config.Skills.AnyEnbaled; _emaTau = (double)base.Config.Networking.PingEMAHalfLife.Value / Math.Log(2.0); bool flag = _estimateSkillLevels; if (!flag && Game.m_staminaRate > 0f) { flag = base.Config.Players.InfiniteBuildingStamina.Value || base.Config.Players.InfiniteFarmingStamina.Value || base.Config.Players.InfiniteMiningStamina.Value || base.Config.Players.InfiniteWoodCuttingStamina.Value; } Processor.UpdateRpcSubscription("SetTrigger", new Action(OnZSyncAnimationSetTrigger), flag); Processor.UpdateRpcSubscription("OnDeath", new Action(RPC_OnDeath), base.Config.Players.BackpackOnDeath.Value != ModConfigBase.PlayersConfig.BackPackOnDeathOptions.Keep); Processor.UpdateRpcSubscription("RPC_AnimateLever", new Action(RPC_AnimateLever), base.Config.Players.CanSacrificeMegingjord.Value || base.Config.Players.CanSacrificeCryptKey.Value || base.Config.Players.CanSacrificeWishbone.Value || base.Config.Players.CanSacrificeTornSpirit.Value); Main.HarmonyInstance.Unpatch((MethodBase)_everybodyIsTryingToSleepMethod, _everybodyIsTryingToSleepPrefix); if (base.Config.Sleeping.MinPlayersInBed.Value > 0) { Main.HarmonyInstance.Patch((MethodBase)_everybodyIsTryingToSleepMethod, new HarmonyMethod(_everybodyIsTryingToSleepPrefix), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } Main.HarmonyInstance.Unpatch((MethodBase)_receivePingMethod, _receivePingPefix); Main.HarmonyInstance.Unpatch((MethodBase)_sendPackageMethod, _sendPackagePrefix); if (base.Config.Networking.MeasurePing.Value) { Main.HarmonyInstance.Patch((MethodBase)_receivePingMethod, new HarmonyMethod(_receivePingPefix), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); Main.HarmonyInstance.Patch((MethodBase)_sendPackageMethod, new HarmonyMethod(_sendPackagePrefix), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } ZoneSystemSendGlobalKeys.GlobalKeysChanged -= UpdateBackpackSlots; if ((int)base.Config.Players.OpenBackpackEmote.Value == -1) { _backpackSlots = 0; } else { UpdateBackpackSlots(); if (base.Config.Players.AdditionalBackpackSlotsPerDefeatedBoss.Value != 0) { ZoneSystemSendGlobalKeys.GlobalKeysChanged += UpdateBackpackSlots; } } PossibleBuildModifiers = BuildModifiers.None; if ((int)base.Config.Admins.ToggleDisableRainDamageEmote.Value != -1) { PossibleBuildModifiers |= BuildModifiers.DisableRainDamage; } if ((int)base.Config.Admins.ToggleDisableSupportRequirements.Value != -1) { PossibleBuildModifiers |= BuildModifiers.DisableSupportRequirements; } if ((int)base.Config.Admins.ToggleMakeIndestructible.Value != -1) { PossibleBuildModifiers |= BuildModifiers.MakeIndestructible; } if ((int)base.Config.Admins.ToggleNoWorkbench.Value != -1) { PossibleBuildModifiers |= BuildModifiers.NoWorkbench; } if ((int)base.Config.Admins.ToggleDungeonBuild.Value != -1) { PossibleBuildModifiers |= BuildModifiers.DungeonBuild; } if ((int)base.Config.Admins.ToggleNoBuildCost.Value != -1) { PossibleBuildModifiers |= BuildModifiers.NoBuildCost; } if ((int)base.Config.Admins.ToggleAllPiecesUnlocked.Value != -1) { PossibleBuildModifiers |= BuildModifiers.AllPiecesUnlocked; } if (firstTime) { _players.Clear(); _playersByID.Clear(); _playerStates.Clear(); _statesByRpc.Clear(); _zoneControls.Clear(); _backpacks.Clear(); } void UpdateBackpackSlots() { _backpackSlots = base.Config.Players.InitialBackpackSlots.Value; if (base.Config.Players.AdditionalBackpackSlotsPerDefeatedBoss.Value != 0) { _backpackSlots += base.Config.Players.AdditionalBackpackSlotsPerDefeatedBoss.Value * SharedProcessorState.BossesByBiome.Values.Count((Character x) => ZoneSystem.instance.GetGlobalKey(x.m_defeatSetGlobalKey)); } } } private void OnZdoDestroyed(ExtendedZDO zdo) { //IL_0056: Unknown result type (might be due to invalid IL or missing references) if (_playerStates.Remove(((ZDOID)(ref ((ZDO)zdo).m_uid)).UserID, out PlayerState value)) { if (value.Rpc != null) { _statesByRpc.Remove(value.Rpc); } if (value.BackpackContainer != null) { _backpacks.Remove(value.BackpackContainer); } _players.Remove(((ZDO)zdo).m_uid); if (_playersByID.Remove(value.PlayerID, out ExtendedZDO value2) && value2 != zdo) { _playersByID.Add(value.PlayerID, value2); } this.PlayerDestroyed?.Invoke(zdo); } } private void OnZSyncAnimationSetTrigger(RoutedRPCData data, string name) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_01f0: Unknown result type (might be due to invalid IL or missing references) //IL_01f5: Unknown result type (might be due to invalid IL or missing references) //IL_01f7: Unknown result type (might be due to invalid IL or missing references) //IL_01fa: Invalid comparison between Unknown and I4 //IL_01fe: Unknown result type (might be due to invalid IL or missing references) //IL_0203: Unknown result type (might be due to invalid IL or missing references) //IL_0205: Unknown result type (might be due to invalid IL or missing references) if (!_players.TryGetValue(data.m_targetZDO, out ExtendedZDO value) || !_playerStates.TryGetValue(((ZDO)value).GetOwner(), out PlayerState value2)) { return; } ItemDrop val = null; int rightItem = value.Vars.GetRightItem(); if (rightItem != 0) { GameObject itemPrefab = ObjectDB.instance.GetItemPrefab(rightItem); val = ((itemPrefab != null) ? itemPrefab.GetComponent() : null); if (val == null) { base.Logger.LogWarning($"Player {value2.PlayerName}: SetTrigger({name}): Right item prefab '{rightItem}' not found"); } } ItemDrop val2 = null; if (val == null && (rightItem = value.Vars.GetLeftItem()) != 0) { GameObject itemPrefab2 = ObjectDB.instance.GetItemPrefab(rightItem); val2 = ((itemPrefab2 != null) ? itemPrefab2.GetComponent() : null); if (val2 == null) { base.Logger.LogWarning($"Player {value2.PlayerName}: SetTrigger({name}): Left item prefab '{rightItem}' not found"); } } ItemDrop val3 = val ?? val2; Attack val4 = val3?.m_itemData.m_shared.m_attack; if (val4 == null) { return; } if (val4.m_attackChainLevels > 1 || val4.m_attackRandomAnimations >= 2) { if (Regex.IsMatch(name, "^" + Regex.Escape(val4.m_attackAnimation) + "\\d+$")) { value2.LastUsedItem = val3; } } else if (name == val4.m_attackAnimation) { value2.LastUsedItem = val3; } if (val != null && CheckStamina(name, base.Config.Players)) { float attackStamina = val.m_itemData.m_shared.m_attack.m_attackStamina; if (value.Vars.GetStamina() < 2f * attackStamina) { RPC.UseStamina(value, 0f - attackStamina); } } if (!_estimateSkillLevels) { return; } value2.CheckSkillItem = null; SharedData shared = val3.m_itemData.m_shared; bool flag; if (shared != null) { Attack attack = shared.m_attack; if (attack != null) { float attackStamina2 = attack.m_attackStamina; if (attackStamina2 > 0f) { SkillType skillType = shared.m_skillType; if ((int)skillType == 1) { DamageTypes damages = shared.m_damages; float slash = damages.m_slash; if (!(slash > 0f)) { goto IL_021c; } } flag = true; goto IL_021f; } } } goto IL_021c; IL_021c: flag = false; goto IL_021f; IL_021f: if (flag) { if (val3 == value2.LastUsedItem && value2.StaminaTimestamp < DateTimeOffset.UtcNow.AddSeconds(-1.5f * value.PrefabInfo.Player.m_staminaRegenDelay)) { float stamina = value.Vars.GetStamina(); int num = Mathf.FloorToInt(stamina); if (num != value2.Stamina) { value2.Stamina = num; value2.StaminaTimestamp = DateTimeOffset.UtcNow; } else if (stamina >= 2f * val3.m_itemData.m_shared.m_attack.m_attackStamina) { value2.CheckSkillStaminaEitr = stamina; value2.CheckSkillItem = val3; } } } else if (val3.m_itemData.m_shared.m_attack.m_attackEitr > 0f && val3 == value2.LastUsedItem && value2.EitrTimestamp < DateTimeOffset.UtcNow.AddSeconds(-1.5f * value.PrefabInfo.Player.m_eitrRegenDelay)) { float eitr = value.Vars.GetEitr(); int num2 = Mathf.FloorToInt(eitr); if (num2 != value2.Eitr) { value2.Eitr = num2; value2.EitrTimestamp = DateTimeOffset.UtcNow; } else { value2.CheckSkillStaminaEitr = eitr; value2.CheckSkillItem = val3; } } static bool CheckStamina(string triggerName, ModConfigBase.PlayersConfig cfg) { switch (triggerName) { case "swing_pickaxe": return cfg.InfiniteMiningStamina.Value; case "swing_hammer": return cfg.InfiniteBuildingStamina.Value; case "swing_hoe": case "scything": return cfg.InfiniteFarmingStamina.Value; case "dualaxes0": case "swing_axe0": case "battleaxe_attack0": return cfg.InfiniteWoodCuttingStamina.Value; default: return false; } } } private void DestroyBackpack(long peerID) { if (_playerStates.TryGetValue(peerID, out PlayerState value)) { ExtendedZDO backpackContainer = value.BackpackContainer; if (backpackContainer != null) { DestroyObject(backpackContainer); base.Logger.LogInfo("Backpack of player '" + value.PlayerName + "' destroyed on death"); } } } private void DropBackpackItem(ItemData item, ExtendedZDO refPosZdo) { //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_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Unknown result type (might be due to invalid IL or missing references) //IL_0037: 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_0063: 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) ModConfigBase.AdvancedConfig.PlayersConfig.BackpackOnDeathDropItemsConfig backpackOnDeathDropItems = base.Config.Advanced.Players.BackpackOnDeathDropItems; Vector3 position = ((ZDO)refPosZdo).GetPosition(); Vector2 val = Random.insideUnitCircle * backpackOnDeathDropItems.ScatterRadius; position.x += val.x; position.y += backpackOnDeathDropItems.VerticalOffset; position.z += val.y; ExtendedZDO extendedZDO = (ExtendedZDO)(object)((Component)ItemDrop.DropItem(item, 0, position, ((ZDO)refPosZdo).GetRotation())).GetComponent().GetZDO(); extendedZDO.Fields(getUnknownComponent: false).Set(() => (ItemDrop x) => x.m_autoDestroy, !backpackOnDeathDropItems.PreventAutoDestroy, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerProcessor.cs", 320).Set(() => (ItemDrop x) => x.m_autoPickup, !backpackOnDeathDropItems.PreventAutoPickup, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerProcessor.cs", 321); } private void DropBackpackItems(long peerID) { if (!_playerStates.TryGetValue(peerID, out PlayerState value)) { return; } ExtendedZDO backpackContainer = value.BackpackContainer; if (backpackContainer == null) { return; } foreach (ItemData item in backpackContainer.Inventory.Items.AsEnumerable()) { DropBackpackItem(item, value.PlayerZDO); } DestroyObject(backpackContainer); base.Logger.LogInfo("Backpack items of player '" + value.PlayerName + "' dropped at death location."); } private void DropBackback(long peerID) { //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_0074: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Unknown result type (might be due to invalid IL or missing references) if (!_playerStates.TryGetValue(peerID, out PlayerState value)) { return; } ExtendedZDO backpackContainer = value.BackpackContainer; if (backpackContainer == null) { return; } IZDOInventory inventory = backpackContainer.Inventory; if (inventory == null) { return; } IList items = inventory.Items; if (items == null || items.Count <= 0) { return; } Vector3 position = ((ZDO)value.PlayerZDO).GetPosition(); position.y += base.Config.Advanced.Players.BackpackOnDeathDropTombStone.VerticalOffset; ExtendedZDO extendedZDO = Processor.Spawn(BackpackTombstonePrefab, position, ((ZDO)value.PlayerZDO).GetRotation()); extendedZDO.Vars.SetIsBackpack(value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerProcessor.cs", 345); extendedZDO.Vars.SetOwner(value.PlayerID, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerProcessor.cs", 347); extendedZDO.Vars.SetOwnerName(value.PlayerName + " - " + base.Config.Localization.Players.Backpack.Name, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerProcessor.cs", 348); extendedZDO.Fields(getUnknownComponent: false).Set(() => (Container x) => x.m_width, backpackContainer.Inventory.Inventory.GetWidth(), "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerProcessor.cs", 351).Set(() => (Container x) => x.m_height, backpackContainer.Inventory.Inventory.GetHeight(), "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerProcessor.cs", 352); foreach (ItemData item in backpackContainer.Inventory.Items) { extendedZDO.Inventory.Items.Add(item); } extendedZDO.Inventory.Save(); DestroyObject(backpackContainer); base.Logger.LogInfo("Backpack of player '" + value.PlayerName + "' dropped at death location."); } private void RPC_OnDeath(RoutedRPCData data) { switch (base.Config.Players.BackpackOnDeath.Value) { case ModConfigBase.PlayersConfig.BackPackOnDeathOptions.SameAsInventory: if (ZoneSystem.instance.GetGlobalKey((GlobalKeys)16) || ZoneSystem.instance.GetGlobalKey((GlobalKeys)17)) { DestroyBackpack(data.m_senderPeerID); } else { DropBackback(data.m_senderPeerID); } break; case ModConfigBase.PlayersConfig.BackPackOnDeathOptions.Destroy: DestroyBackpack(data.m_senderPeerID); break; case ModConfigBase.PlayersConfig.BackPackOnDeathOptions.DropTombStone: DropBackback(data.m_senderPeerID); break; case ModConfigBase.PlayersConfig.BackPackOnDeathOptions.DropItems: DropBackpackItems(data.m_senderPeerID); break; case ModConfigBase.PlayersConfig.BackPackOnDeathOptions.Keep: break; } } private void RPC_AnimateLever(ExtendedZDO zdo, RoutedRPCData data) { (Container, PrefabInfo.Optional, PrefabInfo.Optional, PrefabInfo.Optional, PrefabInfo.Optional)? container = zdo.PrefabInfo.Container; if (!container.HasValue) { return; } PrefabInfo.Optional item = container.GetValueOrDefault().Item4; if (item.Value == null || zdo.Vars.GetIntTag() != 0) { return; } IPeerInfo peerInfo = null; if (base.Config.Players.CanSacrificeMegingjord.Value && zdo.Inventory.Items.Any(delegate(ItemData x) { GameObject dropPrefab4 = x.m_dropPrefab; return ((dropPrefab4 != null) ? ((Object)dropPrefab4).name : null) == "BeltStrength"; })) { if (peerInfo == null) { peerInfo = GetPeerInfo(data.m_senderPeerID); } if (peerInfo == null) { base.Logger.LogError($"Player ZDO with peer ID {data.m_senderPeerID} not found"); } else { Processor.DataZDO.Vars.SetSacrifiedMegingjord(peerInfo.PlayerID, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerProcessor.cs", 400); RPC.AddStatusEffect(peerInfo.PlayerZDO, StatusEffects.Megingjord); RPC.ShowMessage(data.m_senderPeerID, (MessageType)2, base.Config.Localization.Players.SacrificedMegingjord); } } if (base.Config.Players.CanSacrificeCryptKey.Value && zdo.Inventory.Items.Any(delegate(ItemData x) { GameObject dropPrefab3 = x.m_dropPrefab; return ((dropPrefab3 != null) ? ((Object)dropPrefab3).name : null) == "CryptKey"; })) { if (peerInfo == null) { peerInfo = GetPeerInfo(data.m_senderPeerID); } if (peerInfo == null) { base.Logger.LogError($"Player ZDO with peer ID {data.m_senderPeerID} not found"); } else { Processor.DataZDO.Vars.SetSacrifiedCryptKey(peerInfo.PlayerID, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerProcessor.cs", 412); RPC.ShowMessage(data.m_senderPeerID, (MessageType)2, base.Config.Localization.Players.SacrificedCryptKey); } } if (base.Config.Players.CanSacrificeWishbone.Value && zdo.Inventory.Items.Any(delegate(ItemData x) { GameObject dropPrefab2 = x.m_dropPrefab; return ((dropPrefab2 != null) ? ((Object)dropPrefab2).name : null) == "Wishbone"; })) { if (peerInfo == null) { peerInfo = GetPeerInfo(data.m_senderPeerID); } if (peerInfo == null) { base.Logger.LogError($"Player ZDO with peer ID {data.m_senderPeerID} not found"); } else { Processor.DataZDO.Vars.SetSacrifiedWishbone(peerInfo.PlayerID, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerProcessor.cs", 423); RPC.AddStatusEffect(peerInfo.PlayerZDO, StatusEffects.Wishbone); RPC.ShowMessage(data.m_senderPeerID, (MessageType)2, base.Config.Localization.Players.SacrificedWishbone); } } if (base.Config.Players.CanSacrificeTornSpirit.Value && zdo.Inventory.Items.Any(delegate(ItemData x) { GameObject dropPrefab = x.m_dropPrefab; return ((dropPrefab != null) ? ((Object)dropPrefab).name : null) == "YagluthDrop"; })) { if (peerInfo == null) { peerInfo = GetPeerInfo(data.m_senderPeerID); } if (peerInfo == null) { base.Logger.LogError($"Player ZDO with peer ID {data.m_senderPeerID} not found"); return; } Processor.DataZDO.Vars.SetSacrifiedTornSpirit(peerInfo.PlayerID, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerProcessor.cs", 435); RPC.AddStatusEffect(peerInfo.PlayerZDO, StatusEffects.Demister); RPC.ShowMessage(data.m_senderPeerID, (MessageType)2, base.Config.Localization.Players.SacrificedTornSpirit); } } private bool MoveItems(ExtendedZDO zdo, StackContainerState state, IEnumerable peers) { //IL_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_0155: 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) bool flag = false; HashSet hashSet = null; for (int num = zdo.Inventory.Items.Count - 1; num >= 0; num--) { ItemData val = zdo.Inventory.Items[num]; if (Processor.Instance().ContainersByItemName.TryGetValue(val.m_shared, out ConcurrentHashSet value)) { foreach (ExtendedZDO item in (IEnumerable)value) { if (!((ZDO)item).IsValid() || !item.PrefabInfo.Container.HasValue) { value.Remove(item); } else { if (item.Vars.GetInUse()) { continue; } float num2 = ((float?)item.Inventory.PickupRange) ?? base.Config.Containers.AutoPickupRange.Value; num2 *= num2; if (num2 == 0f || Utils.DistanceSqr(((ZDO)state.PlayerZDO).GetPosition(), ((ZDO)item).GetPosition()) > num2) { continue; } int num3 = val.m_stack; if (hashSet == null) { hashSet = new HashSet(); } hashSet.Clear(); bool flag2 = false; ItemData val2 = null; foreach (ItemData item2 in item.Inventory.Items) { hashSet.Add(item2.m_gridPos); if (new ItemDataKey(val) != item2) { continue; } if (val2 == null) { val2 = item2; } int num4 = item2.m_shared.m_maxStackSize - item2.m_stack; if (num4 > 0) { if (!item.IsOwnerOrUnassigned()) { flag2 = true; break; } int num5 = Math.Min(num3, num4); item2.m_stack += num5; num3 -= num5; if (num3 == 0) { break; } } } if (val2 == null) { value.Remove(item); if (value != null && value.Count == 0) { Processor.Instance().ContainersByItemName.TryRemove(val.m_shared, out ConcurrentHashSet _); } continue; } int num6 = item.Inventory.Inventory.GetEmptySlots(); while (num3 > 0 && num6 > 0) { if (!item.IsOwnerOrUnassigned()) { flag2 = true; } if (flag2) { break; } int num7 = Math.Min(num3, val.m_shared.m_maxStackSize); ItemData val3 = val2.Clone(); val3.m_stack = num7; val3.m_gridPos.x = -1; for (int i = 0; i < item.Inventory.Inventory.GetWidth(); i++) { if (val3.m_gridPos.x >= 0) { break; } for (int j = 0; j < item.Inventory.Inventory.GetHeight(); j++) { if (hashSet.Add(new Vector2i(i, j))) { ref int x = ref val3.m_gridPos.x; ref int y = ref val3.m_gridPos.y; int num8 = i; int num9 = j; x = num8; y = num9; break; } } } item.Inventory.Items.Add(val3); num3 -= num7; num6--; } if (flag2) { Processor.Instance().RequestOwnership(item, state.PlayerZDO.Vars.GetPlayerID(0L), "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerProcessor.cs", 538); continue; } if (num3 != val.m_stack) { item.Inventory.Save(); ItemData val4 = val; int num9 = num3; int stack = val.m_stack; val4.m_stack = num9; num3 = stack; flag = true; Processor.ShowMessage(peers, item, base.Config.Localization.Containers.FormatAutoPickup(item.PrefabInfo.Container.Value.Container.m_name, val.m_shared.m_name, num3), base.Config.Containers.PickedUpMessageType.Value, (TextType)0); } if (val.m_stack == 0) { zdo.Inventory.Items.RemoveAt(num); break; } } } } } if (flag) { zdo.Inventory.Save(); } return flag; } private void OnStackContainerDestroyed(ExtendedZDO zdo) { _stackContainers.Remove(zdo); } internal static (int Width, int Height) GetBackpackSize(int slots) { int num = ((slots < 16) ? ((slots < 4) ? 1 : ((slots >= 9) ? 3 : 2)) : ((slots <= 32) ? 4 : 0)); int num2 = num; int num3 = 0; if (num2 > 0) { num3 = (slots + num2 - 1) / num2; } else { num3 = 8; num2 = (slots + num3 - 1) / num3; } return (num3, num2); } protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { //IL_023d: Unknown result type (might be due to invalid IL or missing references) //IL_0242: Unknown result type (might be due to invalid IL or missing references) //IL_03df: Unknown result type (might be due to invalid IL or missing references) //IL_0939: Unknown result type (might be due to invalid IL or missing references) //IL_0604: Unknown result type (might be due to invalid IL or missing references) //IL_060a: Invalid comparison between Unknown and I4 //IL_042f: Unknown result type (might be due to invalid IL or missing references) //IL_0435: Invalid comparison between Unknown and I4 //IL_02da: 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_0fb5: Unknown result type (might be due to invalid IL or missing references) //IL_0fbb: Invalid comparison between Unknown and I4 //IL_0fcd: Unknown result type (might be due to invalid IL or missing references) //IL_0fd3: Invalid comparison between Unknown and I4 //IL_0f72: Unknown result type (might be due to invalid IL or missing references) //IL_0c28: Unknown result type (might be due to invalid IL or missing references) //IL_04d8: Unknown result type (might be due to invalid IL or missing references) //IL_04de: Unknown result type (might be due to invalid IL or missing references) //IL_1041: Unknown result type (might be due to invalid IL or missing references) //IL_0c3a: Unknown result type (might be due to invalid IL or missing references) //IL_0c45: Unknown result type (might be due to invalid IL or missing references) //IL_12fe: Unknown result type (might be due to invalid IL or missing references) //IL_0c67: Unknown result type (might be due to invalid IL or missing references) //IL_0c6c: Unknown result type (might be due to invalid IL or missing references) //IL_0c7a: Unknown result type (might be due to invalid IL or missing references) //IL_0ffe: Unknown result type (might be due to invalid IL or missing references) //IL_1004: Invalid comparison between Unknown and I4 //IL_1367: Unknown result type (might be due to invalid IL or missing references) //IL_13d1: Unknown result type (might be due to invalid IL or missing references) //IL_065b: Unknown result type (might be due to invalid IL or missing references) //IL_0661: Unknown result type (might be due to invalid IL or missing references) //IL_16f0: Unknown result type (might be due to invalid IL or missing references) //IL_140c: Unknown result type (might be due to invalid IL or missing references) //IL_0d75: Unknown result type (might be due to invalid IL or missing references) //IL_0d89: Unknown result type (might be due to invalid IL or missing references) //IL_06c3: Unknown result type (might be due to invalid IL or missing references) //IL_1447: Unknown result type (might be due to invalid IL or missing references) //IL_1196: Unknown result type (might be due to invalid IL or missing references) //IL_119b: Unknown result type (might be due to invalid IL or missing references) //IL_11a9: Unknown result type (might be due to invalid IL or missing references) //IL_0d9f: Unknown result type (might be due to invalid IL or missing references) //IL_1747: Unknown result type (might be due to invalid IL or missing references) //IL_174c: Unknown result type (might be due to invalid IL or missing references) //IL_1721: Unknown result type (might be due to invalid IL or missing references) //IL_1482: Unknown result type (might be due to invalid IL or missing references) //IL_10be: Unknown result type (might be due to invalid IL or missing references) //IL_10c5: Unknown result type (might be due to invalid IL or missing references) //IL_0e5d: Unknown result type (might be due to invalid IL or missing references) //IL_0e7f: Unknown result type (might be due to invalid IL or missing references) //IL_14c6: Unknown result type (might be due to invalid IL or missing references) //IL_10f0: Unknown result type (might be due to invalid IL or missing references) //IL_0829: Unknown result type (might be due to invalid IL or missing references) //IL_082f: Unknown result type (might be due to invalid IL or missing references) //IL_0849: Unknown result type (might be due to invalid IL or missing references) //IL_150c: Unknown result type (might be due to invalid IL or missing references) //IL_071d: Unknown result type (might be due to invalid IL or missing references) //IL_1552: Unknown result type (might be due to invalid IL or missing references) //IL_0ee8: Unknown result type (might be due to invalid IL or missing references) //IL_0734: Unknown result type (might be due to invalid IL or missing references) //IL_1598: Unknown result type (might be due to invalid IL or missing references) //IL_126b: Unknown result type (might be due to invalid IL or missing references) //IL_1270: Unknown result type (might be due to invalid IL or missing references) //IL_0768: Unknown result type (might be due to invalid IL or missing references) //IL_17a6: Unknown result type (might be due to invalid IL or missing references) //IL_17ab: Unknown result type (might be due to invalid IL or missing references) //IL_17c6: Unknown result type (might be due to invalid IL or missing references) //IL_17cb: Unknown result type (might be due to invalid IL or missing references) //IL_17ce: Unknown result type (might be due to invalid IL or missing references) //IL_17d3: Unknown result type (might be due to invalid IL or missing references) //IL_17d8: Unknown result type (might be due to invalid IL or missing references) //IL_17dd: Unknown result type (might be due to invalid IL or missing references) //IL_17f6: Unknown result type (might be due to invalid IL or missing references) //IL_1816: Unknown result type (might be due to invalid IL or missing references) //IL_181b: Unknown result type (might be due to invalid IL or missing references) //IL_181d: Unknown result type (might be due to invalid IL or missing references) //IL_1835: Unknown result type (might be due to invalid IL or missing references) //IL_183a: Unknown result type (might be due to invalid IL or missing references) //IL_183f: Unknown result type (might be due to invalid IL or missing references) //IL_1866: Unknown result type (might be due to invalid IL or missing references) //IL_0898: Unknown result type (might be due to invalid IL or missing references) if (_stackContainers.TryGetValue(zdo, out StackContainerState value)) { if (zdo.Inventory.Items.Count == 0) { DestroyObject(zdo); } else { if (value.Stacked) { if (value.RemoveAfter < DateTimeOffset.UtcNow) { RPC.TakeAllResponse(zdo, granted: true); } else if (MoveItems(zdo, value, peers)) { zdo.Destroyed -= OnStackContainerDestroyed; _stackContainers.Remove(zdo); if (zdo.Inventory.Items.Count == 0) { DestroyObject(zdo); } else { _stackContainers.Add(zdo = RecreatePiece(zdo), value); zdo.Destroyed += OnStackContainerDestroyed; } } return false; } if (zdo.Inventory.Items.Any(delegate(ItemData x) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) if (x != null) { Vector2i gridPos = x.m_gridPos; int x2 = gridPos.x; if (x2 <= 0) { int stack = x.m_stack; if (stack <= 1) { goto IL_0024; } } return true; } goto IL_0024; IL_0024: return false; })) { for (int num = zdo.Inventory.Items.Count - 1; num >= 0; num--) { ItemData val = zdo.Inventory.Items[num]; if (val.m_gridPos.x == 0) { if (--val.m_stack == 0) { zdo.Inventory.Items.RemoveAt(num); } } } zdo.Inventory.Save(); value.Stacked = true; value.RemoveAfter = DateTimeOffset.UtcNow.AddSeconds(base.Config.Players.StackInventoryIntoContainersReturnDelay.Value); zdo.Destroyed -= OnStackContainerDestroyed; _stackContainers.Remove(zdo); _stackContainers.Add(zdo = RecreatePiece(zdo), value); zdo.Destroyed += OnStackContainerDestroyed; } else if (value.RemoveAfter < DateTimeOffset.UtcNow) { DestroyObject(zdo); } else { RPC.StackResponse(zdo, granted: true); } } return true; } if (_backpacks.TryGetValue(zdo, out PlayerState value2)) { bool flag = false; bool flag2 = false; float num2 = 0f; IZDOInventory inventory = zdo.Inventory; Vector3 position = ((ZDO)value2.PlayerZDO).GetPosition(); position.y += 2f; for (int num3 = inventory.Items.Count - 1; num3 >= 0; num3--) { ItemData val2 = inventory.Items[num3]; bool flag3 = false; if (!IsItemTeleportable(val2)) { flag = true; flag3 = true; } else { num2 += val2.GetWeight(-1); if (base.Config.Players.MaxBackpackWeight.Value > 0 && num2 > (float)base.Config.Players.MaxBackpackWeight.Value) { flag2 = true; flag3 = true; } } if (flag3) { ItemDrop.DropItem(val2, 0, position, ((ZDO)value2.PlayerZDO).GetRotation()); inventory.Items.RemoveAt(num3); } } if (flag || flag2) { long owner = ((ZDO)zdo).GetOwner(); zdo.ClaimOwnershipInternal(); zdo.Inventory.Save(); zdo.SetOwnerInternal(owner); value2.BackpackContainer = RecreatePiece(zdo); RPC.ShowMessage(owner, (MessageType)2, flag ? base.Config.Localization.Players.Backpack.ForbiddenItems : base.Config.Localization.Players.Backpack.FormatWeightLimitExceeded(base.Config.Players.MaxBackpackWeight.Value)); value2.OpenBackpackAfter = DateTimeOffset.UtcNow + OpenBackpackDelay; } return true; } ZoneLocation val3; if (zdo.PrefabInfo.Player == null) { base.UnregisterZdoProcessor = true; if (zdo.PrefabInfo.SpawnSystem != null) { _zoneControls[((ZDO)zdo).GetSector()] = zdo; } else { PrefabInfo prefabInfo = zdo.PrefabInfo; if ((object)prefabInfo != null && prefabInfo.Vagon.HasValue && prefabInfo.Container.HasValue && (int)base.Config.Players.OpenCartEmote.Value != -1) { base.UnregisterZdoProcessor = false; if (_playerStates.TryGetValue(((ZDO)zdo).GetOwner(), out value2)) { value2.AttachedCart = (zdo.Vars.GetAttachJoint() ? zdo : null); } return true; } if (((ZDO)zdo).GetPrefab() == BackpackTombstonePrefab && zdo.Vars.GetIsBackpack()) { base.UnregisterZdoProcessor = false; if (_playersByID.TryGetValue(zdo.Vars.GetOwner(0L), out ExtendedZDO value3) && !value3.Vars.GetIsDead() && Vector3.Distance(((ZDO)value3).GetPosition(), ((ZDO)zdo).GetPosition()) < base.Config.Advanced.Players.BackpackOnDeathDropTombStone.AutoCollectDistance && _playerStates.TryGetValue(((ZDO)value3).GetOwner(), out value2)) { value2.EnsureBackpackExists(); foreach (ItemData item in zdo.Inventory.Items.AsEnumerable()) { if (!value2.BackpackContainer.Inventory.Inventory.AddItem(item)) { DropBackpackItem(item, zdo); } } value2.BackpackContainer.ClaimOwnershipInternal(); value2.BackpackContainer.Inventory.Save(); RPC.ShowMessage(value2.Owner, (MessageType)2, "$piece_tombstone_recovered (" + base.Config.Localization.Players.Backpack.Name + ")"); zdo.Destroy(); } } else if (((ZDO)zdo).GetPrefab() == _mudRoadPrefab && (int)base.Config.Admins.CycleLevelGroundMode.Value != -1) { float num4 = float.PositiveInfinity; Peer peer = null; foreach (Peer peer2 in peers) { IPeerInfo info = peer2.Info; if (info == null) { continue; } ItemDrop lastUsedItem = info.LastUsedItem; if (lastUsedItem != null && ((Object)lastUsedItem).name == "Hoe") { float num5 = Utils.DistanceSqr(peer2.m_refPos, ((ZDO)zdo).GetPosition()); if (num5 < num4) { num4 = num5; peer = peer2; } } } if (peer != null) { IPeerInfo info = peer.Info; if (info != null && info.LevelGroundMode == LevelGroundModes.Reset) { List list = new List(); ZDOMan.instance.FindSectorObjects(((ZDO)zdo).GetSector(), ZoneSystem.instance.GetActiveArea(), 0, list, (List)null); foreach (ExtendedZDO item2 in list) { if (item2.PrefabInfo.LocationProxy != null) { int location2 = item2.Vars.GetLocation(); if (Remove(item2, location2, ((ZDO)zdo).GetPosition(), DevGround1)) { _ = 1; } else Remove(item2, location2, ((ZDO)zdo).GetPosition(), DevGround2); } else { if (item2.PrefabInfo.TerrainComp == null) { continue; } TerrainCompData terrainCompData = TerrainCompData.Load(item2); if (terrainCompData != null) { terrainCompData.ResetTerrain(((ZDO)zdo).GetPosition(), base.Config.Advanced.Admins.ResetTerrainRadius); if ((!terrainCompData.HasModifications) ?? false) { item2.Destroy(); } } } } goto IL_08e4; } } IPeerInfo peerInfo = peer?.Info; if (peerInfo == null || !peerInfo.IsAdmin) { goto IL_0812; } LevelGroundModes levelGroundMode = peerInfo.LevelGroundMode; if (levelGroundMode != LevelGroundModes.FlattenMedium) { if (levelGroundMode != LevelGroundModes.FlattenLarge) { goto IL_0812; } val3 = DevGround2; } else { val3 = DevGround1; } goto IL_0815; } } goto IL_08e4; } if (!_playerStates.TryGetValue(((ZDO)zdo).GetOwner(), out value2)) { _playerStates.Add(((ZDO)zdo).GetOwner(), value2 = new PlayerState(zdo, this)); if (value2.Rpc != null) { _statesByRpc[value2.Rpc] = value2; } _players[((ZDO)zdo).m_uid] = zdo; _playersByID[value2.PlayerID] = zdo; zdo.Destroyed += OnZdoDestroyed; if (base.Config.Players.CanSacrificeMegingjord.Value && Processor.DataZDO.Vars.GetSacrifiedMegingjord(value2.PlayerID)) { RPC.AddStatusEffect(zdo, StatusEffects.Megingjord); } if (base.Config.Players.CanSacrificeWishbone.Value && Processor.DataZDO.Vars.GetSacrifiedWishbone(value2.PlayerID)) { RPC.AddStatusEffect(zdo, StatusEffects.Wishbone); } if (base.Config.Players.CanSacrificeTornSpirit.Value && Processor.DataZDO.Vars.GetSacrifiedTornSpirit(value2.PlayerID)) { RPC.AddStatusEffect(zdo, StatusEffects.Demister); } } DateTimeOffset utcNow = DateTimeOffset.UtcNow; if (value2.NextStaminaCheck < utcNow) { value2.NextStaminaCheck = utcNow.AddSeconds(0.2); int num6 = Mathf.FloorToInt(zdo.Vars.GetStamina()); if (value2.Stamina != num6) { value2.StaminaTimestamp = utcNow; value2.Stamina = num6; } if ((float)num6 < zdo.PrefabInfo.Player.m_encumberedStaminaDrain && base.Config.Players.InfiniteEncumberedStamina.Value && zdo.Vars.GetAnimationIsEncumbered()) { RPC.UseStamina(zdo, 0f - zdo.PrefabInfo.Player.m_encumberedStaminaDrain); } else if ((float)num6 < zdo.PrefabInfo.Player.m_sneakStaminaDrain && base.Config.Players.InfiniteSneakingStamina.Value && zdo.Vars.GetAnimationIsCrouching()) { RPC.UseStamina(zdo, 0f - zdo.PrefabInfo.Player.m_sneakStaminaDrain); } else if ((float)num6 < zdo.PrefabInfo.Player.m_swimStaminaDrainMinSkill && base.Config.Players.InfiniteSwimmingStamina.Value && zdo.Vars.GetAnimationInWater()) { RPC.UseStamina(zdo, 0f - zdo.PrefabInfo.Player.m_swimStaminaDrainMinSkill); } int num7 = Mathf.FloorToInt(zdo.Vars.GetEitr()); if (value2.Eitr != num7) { value2.EitrTimestamp = utcNow; value2.Eitr = num7; } } if (value2.BackpackContainer != null) { if (value2.OpenBackpackAfter < utcNow) { value2.OpenBackpackAfter = null; RPC.OpenResponse(value2.BackpackContainer, granted: true); } else if (((ZDO)value2.BackpackContainer).GetPosition().y > -1000f && Vector3.Distance(((ZDO)zdo).GetPosition(), ((ZDO)value2.BackpackContainer).GetPosition()) > InventoryGui.instance.m_autoCloseDistance) { ExtendedZDO? backpackContainer = value2.BackpackContainer; Vector3 position2 = ((ZDO)value2.BackpackContainer).GetPosition(); position2.y = -1000f; ((ZDO)backpackContainer).SetPosition(position2); value2.BackpackContainer = RecreatePiece(value2.BackpackContainer); } } if (_estimateSkillLevels && value2.CheckSkillItem != null) { bool flag4 = value2.CheckSkillItem.m_itemData.m_shared.m_attack.m_attackEitr > 0f; float num8 = (flag4 ? zdo.Vars.GetEitr() : zdo.Vars.GetStamina()); if (num8 < value2.CheckSkillStaminaEitr) { SharedData shared = value2.CheckSkillItem.m_itemData.m_shared; float num9 = (flag4 ? shared.m_attack.m_attackEitr : shared.m_attack.m_attackStamina); float num10 = value2.CheckSkillStaminaEitr - num8; float num11 = num9 - num10; float num12 = num11 / (num9 * 0.33f); if (num12 >= 0f && num12 <= 1f) { float estimatedSkillLevel = value2.GetEstimatedSkillLevel(shared.m_skillType); if (!value2.EstimatedSkillLevelHistories.TryGetValue(shared.m_skillType, out (Queue, List) value4)) { Dictionary Queue, List List)> estimatedSkillLevelHistories = value2.EstimatedSkillLevelHistories; SkillType skillType = shared.m_skillType; value4 = (new Queue(7), new List(7)); estimatedSkillLevelHistories.Add(skillType, value4); if (!float.IsNaN(estimatedSkillLevel)) { for (int i = 0; i < 7; i++) { value4.Item1.Enqueue(estimatedSkillLevel); value4.Item2.Add(estimatedSkillLevel); } } } while (value4.Item1.Count >= 7) { value4.Item2.Remove(value4.Item1.Dequeue()); } value4.Item1.Enqueue(num12); value4.Item2.InsertSorted(num12); num12 = value4.Item2[value4.Item2.Count / 2]; value2.EstimatedSkillLevels[shared.m_skillType] = num12; Processor.DataZDO.Vars.SetEstimatedSkillLevel(value2.PlayerID, shared.m_skillType, num12, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerProcessor.cs", 896); float num13 = Mathf.Floor(num12 * 100f); float num14 = Mathf.Floor(estimatedSkillLevel * 100f); if (num13 != num14) { base.Logger.Log((LogLevel)((num13 - num14 > 1f) ? 4 : 16), $"Player {value2.PlayerName}: Estimated {shared.m_skillType} skill level: {num13}, Previous estimate: {num14} (Item: {((Object)value2.CheckSkillItem).name}, max stamina: {num9}, used stamina: {num10})"); } } value2.CheckSkillItem = null; } } PlayerState playerState = value2; int lastCraftingAnimation = value2.LastCraftingAnimation; int animationCrafting = zdo.Vars.GetAnimationCrafting(); int num15 = lastCraftingAnimation; playerState.LastCraftingAnimation = animationCrafting; if (num15 != value2.LastCraftingAnimation && value2.LastCraftingAnimation != 0) { ExtendedZDO closestContainer = Processor.Instance().GetClosestContainer(((ZDO)zdo).GetPosition(), base.Config.CraftingStations.OpenClosestContainerRange.Value, value2.PlayerID); if (closestContainer != null) { RPC.RequestOpenFor(zdo, closestContainer); } } if ((int)base.Config.Players.StackInventoryIntoContainersEmote.Value != -1 || (int)base.Config.Players.OpenCartEmote.Value != -1 || _backpackSlots > 0 || (PossibleBuildModifiers != 0 && value2.IsAdmin) || (int)base.Config.Admins.CycleLevelGroundMode.Value != -1) { int emoteID = zdo.Vars.GetEmoteID(); if (emoteID != value2.LastEmoteId) { value2.LastEmoteId = emoteID; if (CheckEmote(zdo, base.Config.Players.StackInventoryIntoContainersEmote.Value)) { Dictionary dictionary = null; foreach (ExtendedZDO container in Processor.Instance().Containers) { float num16 = ((float?)container.Inventory.PickupRange) ?? base.Config.Containers.AutoPickupRange.Value; num16 *= num16; if (num16 == 0f || Utils.DistanceSqr(((ZDO)zdo).GetPosition(), ((ZDO)container).GetPosition()) > num16 || ((int)container.PrefabInfo.Container.Value.Container.m_privacy == 0 && container.Vars.GetCreator(0L) != zdo.Vars.GetPlayerID(0L))) { continue; } foreach (ItemData item3 in container.Inventory.Items) { (dictionary ?? (dictionary = new Dictionary())).TryAdd(item3.m_shared, item3); } } if (dictionary != null) { Vector3 position2 = ((ZDO)zdo).GetPosition(); position2.y = -1000f; ExtendedZDO extendedZDO2 = PlacePiece(position2, Prefabs.WoodChest, 0f); int value5 = Math.Max(4, dictionary.Count); extendedZDO2.Fields(getUnknownComponent: false).Set(() => (Container x) => x.m_width, 8, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerProcessor.cs", 953).Set(() => (Container x) => x.m_height, value5, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerProcessor.cs", 954); int num17 = 0; foreach (ItemData value6 in dictionary.Values) { ItemData val4 = value6.Clone(); val4.m_stack = 1; val4.m_gridPos = new Vector2i(0, num17++); extendedZDO2.Inventory.Items.Add(val4); } extendedZDO2.Inventory.Save(); extendedZDO2.SetOwner(((ZDO)zdo).GetOwner()); _stackContainers.Add(extendedZDO2, new StackContainerState(zdo)); extendedZDO2.Destroyed += OnStackContainerDestroyed; RPC.StackResponse(extendedZDO2, granted: true); } } else if (CheckEmote(zdo, base.Config.Players.OpenCartEmote.Value) && value2.AttachedCart != null && ((ZDO)value2.AttachedCart).GetOwner() == value2.Owner && value2.AttachedCart.Vars.GetAttachJoint()) { RPC.OpenResponse(value2.AttachedCart, granted: true); } else if (_backpackSlots > 0 && CheckEmote(zdo, base.Config.Players.OpenBackpackEmote.Value)) { value2.OpenBackpackAfter = utcNow + OpenBackpackDelay; if (value2.EnsureBackpackExists()) { value2.OpenBackpackAfter = null; RPC.OpenResponse(value2.BackpackContainer, granted: true); } } else if (value2.IsAdmin) { if (CheckEmote(zdo, base.Config.Admins.ToggleDisableRainDamageEmote.Value)) { value2.BuildModifiers ^= BuildModifiers.DisableRainDamage; value2.NextBuildModifierMessage = default(DateTimeOffset); } if (CheckEmote(zdo, base.Config.Admins.ToggleDisableSupportRequirements.Value)) { value2.BuildModifiers ^= BuildModifiers.DisableSupportRequirements; value2.NextBuildModifierMessage = default(DateTimeOffset); } if (CheckEmote(zdo, base.Config.Admins.ToggleMakeIndestructible.Value)) { value2.BuildModifiers ^= BuildModifiers.MakeIndestructible; value2.NextBuildModifierMessage = default(DateTimeOffset); } if (CheckEmote(zdo, base.Config.Admins.ToggleNoWorkbench.Value)) { value2.BuildModifiers ^= BuildModifiers.NoWorkbench; value2.NextBuildModifierMessage = default(DateTimeOffset); UpdateGlobalKeyModification(value2, BuildModifiers.NoWorkbench, (GlobalKeys)22); } if (CheckEmote(zdo, base.Config.Admins.ToggleDungeonBuild.Value)) { value2.BuildModifiers ^= BuildModifiers.DungeonBuild; value2.NextBuildModifierMessage = default(DateTimeOffset); UpdateGlobalKeyModification(value2, BuildModifiers.DungeonBuild, (GlobalKeys)29); } if (CheckEmote(zdo, base.Config.Admins.ToggleNoBuildCost.Value)) { value2.BuildModifiers ^= BuildModifiers.NoBuildCost; value2.NextBuildModifierMessage = default(DateTimeOffset); UpdateGlobalKeyModification(value2, BuildModifiers.NoBuildCost, (GlobalKeys)19); } if (CheckEmote(zdo, base.Config.Admins.ToggleAllPiecesUnlocked.Value)) { value2.BuildModifiers ^= BuildModifiers.AllPiecesUnlocked; value2.NextBuildModifierMessage = default(DateTimeOffset); UpdateGlobalKeyModification(value2, BuildModifiers.AllPiecesUnlocked, (GlobalKeys)21); } if (CheckEmote(zdo, base.Config.Admins.CycleLevelGroundMode.Value)) { value2.LevelGroundMode = (LevelGroundModes)((int)(value2.LevelGroundMode + 1) % _numberOfLevelGroundModes); value2.NextLevelGroundModeMessage = default(DateTimeOffset); } } } } if (value2.NextBuildModifierMessage == default(DateTimeOffset) || (value2.BuildModifiers != 0 && value2.NextBuildModifierMessage < utcNow && zdo.Vars.GetRightItem() == Prefabs.Hammer)) { value2.NextBuildModifierMessage = utcNow.AddSeconds(4.0); RPC.ShowMessage(value2.Owner, (MessageType)1, $"Build modifiers: {value2.BuildModifiers}"); } if (value2.NextLevelGroundModeMessage == default(DateTimeOffset) || (value2.LevelGroundMode != 0 && value2.NextLevelGroundModeMessage < utcNow && zdo.Vars.GetRightItem() == Prefabs.Hoe)) { value2.NextLevelGroundModeMessage = utcNow.AddSeconds(4.0); RPC.ShowMessage(value2.Owner, (MessageType)1, $"Level ground mode: {value2.LevelGroundMode}"); } if (!base.Config.Tames.TeleportFollow.Value && !base.Config.Tames.TakeIntoDungeons.Value) { return false; } if (!Character.InInterior(((ZDO)zdo).GetPosition())) { value2.InitialInInteriorPosition = null; } else if (!value2.InitialInInteriorPosition.HasValue) { value2.InitialInInteriorPosition = ((ZDO)zdo).GetPosition(); } string playerName = zdo.Vars.GetPlayerName(); Vector2s playerZone = ((ZDO)zdo).GetSector(); foreach (TameableProcessor.ITameableState tame in Processor.Instance().Tames) { if (tame.IsTamed && !(tame.ZDO.Vars.GetFollow() != playerName)) { Vector2s tameZone = ((ZDO)tame.ZDO).GetSector(); if (ShouldTeleport(in playerZone, in tameZone, zdo, tame.ZDO, value2)) { Vector3 position3 = ((ZDO)zdo).GetPosition(); Vector3 val5 = ((ZDO)zdo).GetRotation() * Vector3.forward; ModConfigBase.AdvancedConfig.TamesConfig.TeleportFollowPositioningConfig teleportFollowPositioning = base.Config.Advanced.Tames.TeleportFollowPositioning; position3 += Quaternion.Euler(0f, Random.Range(0f - teleportFollowPositioning.HalfArcXZ, teleportFollowPositioning.HalfArcXZ), 0f) * val5 * Random.Range(teleportFollowPositioning.MinDistXZ, teleportFollowPositioning.MaxDistXZ); position3.y += Random.Range(teleportFollowPositioning.MinOffsetY, teleportFollowPositioning.MaxOffsetY); ((ZDO)tame.ZDO).SetPosition(position3); tame.ZDO.Recreate(); } } } value2.SendGlobalKeyModifications(); return false; IL_0815: ZoneLocation val6 = val3; if (val6 != null) { ZoneSystem.instance.SpawnLocation(val6, 0, ((ZDO)zdo).GetPosition(), ((ZDO)zdo).GetRotation(), (SpawnMode)0); List list2 = new List(); ZDOMan.instance.FindSectorObjects(((ZDO)zdo).GetSector(), ZoneSystem.instance.GetActiveArea(), 0, list2, (List)null); foreach (ExtendedZDO item4 in list2) { if (item4.PrefabInfo.TerrainComp == null) { continue; } TerrainCompData terrainCompData2 = TerrainCompData.Load(item4); if (terrainCompData2 != null) { terrainCompData2.ResetTerrain(((ZDO)zdo).GetPosition(), val6.m_exteriorRadius); if ((!terrainCompData2.HasModifications) ?? false) { item4.Destroy(); } } } } goto IL_08e4; IL_08e4: return false; IL_0812: val3 = null; goto IL_0815; static bool CheckEmote(ExtendedZDO player, Emotes emote) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0002: Invalid comparison between Unknown and I4 //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Invalid comparison between Unknown and I4 //IL_0009: 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) if ((int)emote != -1) { if ((int)emote != -2) { return emote == player.Vars.GetEmote((Emotes)(-1)); } return true; } return false; } static bool Remove(ExtendedZDO zdo, int hash, Vector3 pos, ZoneLocation location) { //IL_0009: 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 (hash != location.Hash || Utils.DistanceXZ(pos, ((ZDO)zdo).GetPosition()) > location.m_exteriorRadius) { return false; } zdo.Destroy(); return true; } static void UpdateGlobalKeyModification(PlayerState state, BuildModifiers modifier, GlobalKeys key) { //IL_0018: 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 ((state.BuildModifiers & modifier) == 0) { state.RemoveGlobalKeyModification(new GlobalKey(key)); } else { state.AddGlobalKeyModification(new GlobalKey(key), add: true); } } } private bool ShouldTeleport(in Vector2s playerZone, in Vector2s tameZone, ExtendedZDO player, ExtendedZDO tame, PlayerState state) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_00a5: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) if (base.Config.Tames.TakeIntoDungeons.Value && Character.InInterior(((ZDO)player).GetPosition()) != Character.InInterior(((ZDO)tame).GetPosition())) { if (base.Config.Advanced.Tames.TakeIntoDungeonExcluded.Contains(((ZDO)tame).GetPrefab())) { return false; } if (!state.InitialInInteriorPosition.HasValue) { return true; } if (Utils.DistanceXZ(state.InitialInInteriorPosition.Value, ((ZDO)player).GetPosition()) > 0.5f) { return true; } return false; } if (base.Config.Tames.TeleportFollow.Value && !Character.InInterior(((ZDO)player).GetPosition())) { if (base.Config.Advanced.Tames.TeleportFollowExcluded.Contains(((ZDO)tame).GetPrefab())) { return false; } if (Utils.DistanceXZ(((ZDO)player).GetPosition(), ((ZDO)tame).GetPosition()) >= base.Config.Tames.TeleportFollowMinDistance.Value) { return true; } return false; } return false; } private static bool EverybodyIsTryingToSleepPrefix(ref bool __result) { PlayerProcessor playerProcessor = Processor.Instance(); __result = playerProcessor.EverybodyIsTryingToSleep(); return false; } private bool EverybodyIsTryingToSleep() { //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_005a: Invalid comparison between Unknown and I4 //IL_00e5: Unknown result type (might be due to invalid IL or missing references) if (_playerStates.Count == 0) { return false; } int num = 0; int num2 = 0; foreach (ExtendedZDO value in _players.Values) { if (value.Vars.GetInBed()) { num++; } else if ((int)value.Vars.GetEmote((Emotes)(-1)) == 1) { num2++; } } if (num == _playerStates.Count) { return true; } if (num < base.Config.Sleeping.MinPlayersInBed.Value) { return false; } int num3 = num + num2; if (num3 * 100 / _playerStates.Count >= base.Config.Sleeping.RequiredPlayerPercentage.Value) { return true; } RPC.ShowMessage(ZRoutedRpc.Everybody, base.Config.Sleeping.SleepPromptMessageType.Value, base.Config.Localization.Sleeping.FormatPrompt(num3, _playerStates.Count)); return false; } } internal sealed class PlayerSpawnedProcessor : Processor { private sealed record SpawnInfo(int MaxSpawned, string MaxSummonReached, Dictionary> SpawnedByPrefab); private sealed class SpawnedState { public IPeerInfo? Summoner { get; set; } public DateTimeOffset NextPatrolPointUpdate { get; set; } public bool ChancesEvaluated { get; set; } } private readonly Dictionary _spawnInfo = new Dictionary(); private readonly Dictionary> _spawnedByPrefab = new Dictionary>(); private readonly Dictionary _spawnedStates = new Dictionary(); private IPeerInfo? _lastSummoningPlayer; private bool _canMakeFriendly; private bool _canLevelUp; private bool _canTolerateLava; private bool _modifyHpRegen; private bool _modifySpeed; protected override Guid Id { get; } = Guid.Parse("7766ee34-0ade-4f71-8e6e-5931419cc303"); public bool SetsFedDuration => _modifyHpRegen; public override void Initialize(bool firstTime) { //IL_0197: Unknown result type (might be due to invalid IL or missing references) //IL_019c: 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_01a2: Unknown result type (might be due to invalid IL or missing references) //IL_01a6: Invalid comparison between Unknown and I4 base.Initialize(firstTime); if (firstTime) { foreach (List value2 in _spawnedByPrefab.Values) { value2.Clear(); } } _canMakeFriendly = base.Config.HostileSummons.MakeFriendly.Value || base.Config.Skills.BloodmagicMakeSummonsFriendlyEnabled; _canLevelUp = base.Config.Skills.BloodmagicSummonsLevelUpEnabled; _canTolerateLava = base.Config.Skills.BloodmagicMakeSummonsTolerateLavaEnabled; _modifyHpRegen = base.Config.Skills.BloodmagicSummonsHPRegenMultiplierEnabled; _modifySpeed = base.Config.Skills.BloodmagicSummonsSpeedMultiplierEnabled; if (_spawnInfo.Count == 0 && (base.Config.HostileSummons.AllowReplacementSummon.Value || _canMakeFriendly)) { foreach (ItemDrop item in ObjectDB.instance.m_items.Select((GameObject x) => x.GetComponent())) { Attack attack = item.m_itemData.m_shared.m_attack; GameObject attackProjectile = attack.m_attackProjectile; SpawnAbility val = ((attackProjectile != null) ? attackProjectile.GetComponent() : null); if (val == null) { continue; } Dictionary> dictionary = new Dictionary>(); GameObject[] spawnPrefab = val.m_spawnPrefab; foreach (GameObject val2 in spawnPrefab) { Humanoid component = val2.GetComponent(); bool flag; if (component != null) { Faction faction = ((Character)component).m_faction; if ((int)faction == 0 || (int)faction == 11) { flag = true; goto IL_01b0; } } flag = false; goto IL_01b0; IL_01b0: if (flag) { int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)val2).name, true); if (!_spawnedByPrefab.TryGetValue(stableHashCode, out List value)) { _spawnedByPrefab.Add(stableHashCode, value = new List()); } dictionary.Add(stableHashCode, value); } } if (dictionary.Count > 0) { _spawnInfo.Add(attack.m_attackAnimation, new SpawnInfo(val.m_maxSpawned, val.m_maxSummonReached, dictionary)); } } foreach (ExtendedZDO @object in ZDOMan.instance.GetObjects()) { if (_spawnedByPrefab.TryGetValue(((ZDO)@object).GetPrefab(), out List list) && !list.Contains(@object)) { list.Add(@object); @object.Destroyed += delegate(ExtendedZDO x) { list.Remove(x); }; } } foreach (List value3 in _spawnedByPrefab.Values) { SortBySpawnTime(value3); } } Processor.UpdateRpcSubscription("SetTrigger", new Action(OnZSyncAnimationSetTrigger), base.Config.HostileSummons.AllowReplacementSummon.Value || _canMakeFriendly); if (firstTime) { _spawnedStates.Clear(); _lastSummoningPlayer = null; } } private static void SortBySpawnTime(List list) { list.Sort((ExtendedZDO a, ExtendedZDO b) => Math.Sign(a.Vars.GetSpawnTime().Ticks - b.Vars.GetSpawnTime().Ticks)); } private void EvaluateChances(ExtendedZDO zdo, SpawnedState state, bool tamed) { //IL_06e8: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) if (state.ChancesEvaluated) { return; } state.ChancesEvaluated = true; if (state.Summoner == null) { return; } State state2 = Random.state; Random.InitState(zdo.Vars.GetSeed()); try { float? num = null; if (!tamed) { int num2 = -1; if (base.Config.HostileSummons.MakeFriendly.Value) { num2 = 100; } else if (_canMakeFriendly) { if (!num.HasValue) { num = state.Summoner.GetEstimatedSkillLevel((SkillType)10); if (float.IsNaN(num.Value)) { num = 0f; } } num2 = Mathf.RoundToInt(Utils.Lerp((float)base.Config.Skills.BloodmagicMakeSummonsFriendlyChanceAtMinSkill.Value, (float)base.Config.Skills.BloodmagicMakeSummonsFriendlyChanceAtMaxSkill.Value, num.Value)); } if (num2 >= 0 && Random.Range(0, 100) <= num2) { base.UnregisterZdoProcessor = false; RPC.SetTamed(zdo, tamed: true); zdo.Vars.SetTamed(value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerSpawnedProcessor.cs", 134); } } if (_canLevelUp) { if (!num.HasValue) { num = state.Summoner.GetEstimatedSkillLevel((SkillType)10); if (float.IsNaN(num.Value)) { num = 0f; } } int num3 = Mathf.RoundToInt(Utils.Lerp((float)base.Config.Skills.BloodmagicSummonsLevelUpChanceAtMinSkill.Value, (float)base.Config.Skills.BloodmagicSummonsLevelUpChanceAtMaxSkill.Value, num.Value)); int i; for (i = 1; i < base.Config.Skills.BloodmagicSummonsMaxLevel.Value; i++) { if (!(Random.Range(0f, 100f) <= (float)num3)) { break; } } if (i != zdo.Vars.GetLevel()) { zdo.Vars.SetLevel(i, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerSpawnedProcessor.cs", 153); base.RecreateZdo = true; } } if (_canTolerateLava) { if (!num.HasValue) { num = state.Summoner.GetEstimatedSkillLevel((SkillType)10); if (float.IsNaN(num.Value)) { num = 0f; } } int num4 = Mathf.RoundToInt(Utils.Lerp((float)base.Config.Skills.BloodmagicMakeSummonsTolerateLavaChanceAtMinSkill.Value, (float)base.Config.Skills.BloodmagicMakeSummonsTolerateLavaChanceAtMaxSkill.Value, num.Value)); (Humanoid, PrefabInfo.Optional, PrefabInfo.Optional)? humanoid = zdo.PrefabInfo.Humanoid; if (humanoid.HasValue) { Humanoid item = humanoid.GetValueOrDefault().Item1; if (item != null && !((Character)item).m_tolerateFire && zdo.Fields(getUnknownComponent: false).UpdateValue(() => (Humanoid x) => ((Character)x).m_tolerateFire, Random.Range(0, 100) <= num4, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerSpawnedProcessor.cs", 169)) { base.RecreateZdo = true; } } } if (_modifyHpRegen) { if (!num.HasValue) { num = state.Summoner.GetEstimatedSkillLevel((SkillType)10); if (float.IsNaN(num.Value)) { num = 0f; } } float num5 = Utils.Lerp(base.Config.Skills.BloodmagicSummonsHPRegenMultiplierAtMinSkill.Value, base.Config.Skills.BloodmagicSummonsHPRegenMultiplierAtMaxSkill.Value, num.Value); if (zdo.Fields(getUnknownComponent: false).UpdateValue(() => (Humanoid x) => ((Character)x).m_regenAllHPTime, ((Character)zdo.PrefabInfo.Humanoid.Value.Humanoid).m_regenAllHPTime / num5, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerSpawnedProcessor.cs", 185)) { base.RecreateZdo = true; } if (zdo.PrefabInfo.Tameable.HasValue && zdo.Fields(getUnknownComponent: false).UpdateValue(() => (Tameable x) => x.m_fedDuration, float.PositiveInfinity, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerSpawnedProcessor.cs", 187)) { base.RecreateZdo = true; } } if (!_modifySpeed) { return; } if (!num.HasValue) { num = state.Summoner.GetEstimatedSkillLevel((SkillType)10); if (float.IsNaN(num.Value)) { num = 0f; } } float num6 = Utils.Lerp(base.Config.Skills.BloodmagicSummonsSpeedMultiplierAtMinSkill.Value, base.Config.Skills.BloodmagicSummonsSpeedMultiplierAtMaxSkill.Value, num.Value); ExtendedZDO.ComponentFieldAccessor componentFieldAccessor = zdo.Fields(getUnknownComponent: false); Humanoid item2 = zdo.PrefabInfo.Humanoid.Value.Humanoid; if (componentFieldAccessor.UpdateValue(() => (Humanoid x) => ((Character)x).m_speed, ((Character)item2).m_speed * num6, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerSpawnedProcessor.cs", 202)) { base.RecreateZdo = true; } if (componentFieldAccessor.UpdateValue(() => (Humanoid x) => ((Character)x).m_crouchSpeed, ((Character)item2).m_crouchSpeed * num6, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerSpawnedProcessor.cs", 204)) { base.RecreateZdo = true; } if (componentFieldAccessor.UpdateValue(() => (Humanoid x) => ((Character)x).m_flyFastSpeed, ((Character)item2).m_flyFastSpeed * num6, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerSpawnedProcessor.cs", 206)) { base.RecreateZdo = true; } if (componentFieldAccessor.UpdateValue(() => (Humanoid x) => ((Character)x).m_flySlowSpeed, ((Character)item2).m_flySlowSpeed * num6, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerSpawnedProcessor.cs", 208)) { base.RecreateZdo = true; } if (componentFieldAccessor.UpdateValue(() => (Humanoid x) => ((Character)x).m_groundTiltSpeed, ((Character)item2).m_groundTiltSpeed * num6, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerSpawnedProcessor.cs", 212)) { base.RecreateZdo = true; } if (componentFieldAccessor.UpdateValue(() => (Humanoid x) => ((Character)x).m_runSpeed, ((Character)item2).m_runSpeed * num6, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerSpawnedProcessor.cs", 214)) { base.RecreateZdo = true; } if (componentFieldAccessor.UpdateValue(() => (Humanoid x) => ((Character)x).m_swimSpeed, ((Character)item2).m_swimSpeed * num6, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerSpawnedProcessor.cs", 218)) { base.RecreateZdo = true; } if (componentFieldAccessor.UpdateValue(() => (Humanoid x) => ((Character)x).m_walkSpeed, ((Character)item2).m_walkSpeed * num6, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerSpawnedProcessor.cs", 224)) { base.RecreateZdo = true; } } finally { Random.state = state2; } } private void OnZSyncAnimationSetTrigger(RoutedRPCData data, string name) { //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Unknown result type (might be due to invalid IL or missing references) //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_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_00d6: Expected O, but got Unknown if (!_spawnInfo.TryGetValue(name, out SpawnInfo value) || (_lastSummoningPlayer = Processor.Instance().GetPeerInfo(data.m_senderPeerID)) == null || !base.Config.HostileSummons.AllowReplacementSummon.Value) { return; } foreach (List value2 in value.SpawnedByPrefab.Values) { if (value2.Count >= value.MaxSpawned) { if (((ZDO)value2[0]).GetOwner() == data.m_senderPeerID && ZNetScene.InActiveArea(((ZDO)value2[0]).GetSector(), ((ZDO)_lastSummoningPlayer.PlayerZDO).GetSector())) { RPC.Damage(value2[0], new HitData(float.MaxValue) { m_attacker = ((ZDO)_lastSummoningPlayer.PlayerZDO).m_uid }); } else { value2[0].Destroy(); } RPC.ShowMessage(data.m_senderPeerID, (MessageType)2, value.MaxSummonReached); } } } protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { //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_003b: 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_0043: Invalid comparison between Unknown and I4 //IL_0310: Unknown result type (might be due to invalid IL or missing references) //IL_0320: Unknown result type (might be due to invalid IL or missing references) //IL_0374: Unknown result type (might be due to invalid IL or missing references) //IL_03b7: Unknown result type (might be due to invalid IL or missing references) base.UnregisterZdoProcessor = true; (Humanoid, PrefabInfo.Optional, PrefabInfo.Optional)? humanoid = zdo.PrefabInfo.Humanoid; bool flag; if (humanoid.HasValue) { var (val, _, _) = humanoid.GetValueOrDefault(); if (val != null) { Faction faction = ((Character)val).m_faction; if ((int)faction == 0 || (int)faction == 11) { flag = true; goto IL_004d; } } } flag = false; goto IL_004d; IL_004d: if (!flag) { return false; } if (!_spawnedStates.TryGetValue(zdo, out SpawnedState value)) { _spawnedStates.Add(zdo, value = new SpawnedState()); zdo.Destroyed += delegate(ExtendedZDO x) { _spawnedStates.Remove(x); }; if (!zdo.PrefabInfo.Tameable.HasValue) { if (!_spawnedByPrefab.TryGetValue(((ZDO)zdo).GetPrefab(), out List list)) { _spawnedByPrefab.Add(((ZDO)zdo).GetPrefab(), list = new List()); } if (!list.Contains(zdo)) { list.Add(zdo); SortBySpawnTime(list); zdo.Destroyed += delegate(ExtendedZDO x) { list.Remove(x); }; } } } if (value.Summoner == null) { string playerName = zdo.Vars.GetFollow(); if (!string.IsNullOrEmpty(playerName)) { value.Summoner = Processor.Instance().PeerInfos.FirstOrDefault((IPeerInfo x) => x.PlayerName == playerName); } SpawnedState spawnedState = value; if (spawnedState.Summoner == null) { IPeerInfo peerInfo = (spawnedState.Summoner = _lastSummoningPlayer); } if (value.Summoner != null && string.IsNullOrEmpty(playerName)) { zdo.Vars.SetFollow(playerName = value.Summoner.PlayerName, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerSpawnedProcessor.cs", 289); } } bool tamed = zdo.Vars.GetTamed(); EvaluateChances(zdo, value, tamed); if ((base.Config.HostileSummons.FollowSummoner.Value || (_canMakeFriendly && tamed)) && !zdo.PrefabInfo.Tameable.HasValue) { ModConfigBase.AdvancedConfig.HostileSummonsConfig.FollowSummonerConfig followSummoners = base.Config.Advanced.HostileSummons.FollowSummoners; ExtendedZDO.ComponentFieldAccessor componentFieldAccessor = zdo.Fields(getUnknownComponent: false); if (componentFieldAccessor.UpdateValue(() => (MonsterAI x) => ((BaseAI)x).m_randomMoveInterval, followSummoners.MoveInterval, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerSpawnedProcessor.cs", 301)) { base.RecreateZdo = true; } if (componentFieldAccessor.UpdateValue(() => (MonsterAI x) => ((BaseAI)x).m_randomMoveRange, followSummoners.MaxDistance, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerSpawnedProcessor.cs", 303)) { base.RecreateZdo = true; } if (base.RecreateZdo) { return false; } base.UnregisterZdoProcessor = false; if (value.Summoner != null) { DateTimeOffset utcNow = DateTimeOffset.UtcNow; if (utcNow > value.NextPatrolPointUpdate && Utils.DistanceXZ(((ZDO)zdo).GetPosition(), ((ZDO)value.Summoner.PlayerZDO).GetPosition()) > followSummoners.MaxDistance / 2f) { value.NextPatrolPointUpdate = utcNow.AddSeconds(followSummoners.MoveInterval / 2f); uint dataRevision = ((ZDO)zdo).DataRevision; zdo.Vars.SetSpawnPoint(((ZDO)value.Summoner.PlayerZDO).GetPosition(), "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerSpawnedProcessor.cs", 315); zdo.Vars.SetPatrol(value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerSpawnedProcessor.cs", 316); zdo.Vars.SetPatrolPoint(((ZDO)value.Summoner.PlayerZDO).GetPosition(), "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PlayerSpawnedProcessor.cs", 317); if (dataRevision != ((ZDO)zdo).DataRevision) { ((ZDO)zdo).DataRevision = ((ZDO)zdo).DataRevision + 100; } } } } return false; } } internal sealed class PortalHubProcessor : Processor { private sealed class PortalState { public required string Tag { get; set; } public required int HubId { get; set; } public required bool AllowAllItems { get; init; } public ExtendedZDO? HubPortal { get; set; } public ExtendedZDO? HubSign { get; set; } } private readonly Dictionary _knownPortals = new Dictionary(); private readonly IReadOnlyList _torchPrefabs = new <>z__ReadOnlyArray(new int[3] { Prefabs.StandingIronTorch, Prefabs.StandingIronTorchBlue, Prefabs.StandingIronTorchGreen }); private bool _hubEnabled; private float _hubRadius; private bool _updateHub; private int _lastHubWidth; private Regex? _includeRegex; private Regex? _excludeRegex; private bool _autoTag; private readonly Vector3 _offset = ((Func)delegate { //IL_0028: 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) Vector3 val = default(Vector3); ((Vector3)(ref val))..ctor(10820f, 0f, 0f); while (!Character.InInterior(val)) { val.y += 1000f; } return val; })(); protected override Guid Id { get; } = Guid.Parse("1523cbb8-ed88-4608-84c5-8526937020f7"); public override void Initialize(bool firstTime) { base.Initialize(firstTime); bool flag = _hubEnabled != base.Config.PortalHub.Enable.Value; _hubEnabled = base.Config.PortalHub.Enable.Value; _autoTag = _hubEnabled && base.Config.PortalHub.AutoNameNewPortals.Value; _knownPortals.Clear(); if (_hubEnabled) { string text = base.Config.PortalHub.Include.Value.Trim(); _includeRegex = (string.IsNullOrEmpty(text.Trim(new char[1] { '*' })) ? null : new Regex(Processor.ConvertToRegexPattern(text))); text = base.Config.PortalHub.Exclude.Value.Trim(); _excludeRegex = (string.IsNullOrEmpty(text) ? null : new Regex(Processor.ConvertToRegexPattern(text))); foreach (ExtendedZDO item in ZDOMan.instance.GetPortals().Values.SelectMany((List x) => x)) { string text2 = null; if (item.IsModCreator() || !CheckFilter(item, text2 = item.Vars.GetTag())) { continue; } _knownPortals.Add(item, new PortalState { Tag = text2, HubId = item.Vars.GetPortalHubId(), AllowAllItems = item.Fields(getUnknownComponent: false).GetBool(() => (TeleportWorld x) => x.m_allowAllItems, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PortalHubProcessor.cs", 59) }); item.Destroyed += OnKnownPortalDestroyed; } HashSet hashSet = (from x in _knownPortals.Values where !x.AllowAllItems select x.HubId).ToHashSet(); HashSet hashSet2 = (from x in _knownPortals.Values where x.AllowAllItems select x.HubId).ToHashSet(); int num = 0; foreach (KeyValuePair item2 in from x in _knownPortals where x.Value.HubId == 0 orderby x.Value.Tag select x) { item2.Deconstruct(out var key, out var value); ExtendedZDO extendedZDO2 = key; PortalState portalState = value; HashSet hashSet3 = (portalState.AllowAllItems ? hashSet2 : hashSet); while (!hashSet3.Add(++num)) { } ExtendedZDO.ZDOVars_ vars = extendedZDO2.Vars; int value2 = (portalState.HubId = num); vars.SetPortalHubId(value2, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PortalHubProcessor.cs", 70); } } if (flag || !_hubEnabled) { UpdatePortalHub(); } } private void OnKnownPortalDestroyed(ExtendedZDO zdo) { if (_knownPortals.Remove(zdo) && _hubEnabled) { _updateHub = true; } } private bool CheckFilter(ExtendedZDO zdo, string tag) { if ((_includeRegex ?? _excludeRegex) == null) { return true; } if (_includeRegex?.IsMatch(tag) ?? true) { return !(_excludeRegex?.IsMatch(tag) ?? false); } return false; } protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { //IL_02d1: 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_02db: Unknown result type (might be due to invalid IL or missing references) ExtendedZDO zdo2 = zdo; if (!_hubEnabled) { base.UnregisterZdoProcessor = true; return false; } if (zdo2.PrefabInfo.Player != null) { if (_updateHub && !peers.Any((Peer x) => Utils.DistanceXZ(x.m_refPos, _offset) < _hubRadius)) { _updateHub = false; UpdatePortalHub(); } return false; } ExtendedZDO key; PortalState value; if (zdo2.PrefabInfo.Sign != null && base.PlacedObjects.Contains(zdo2)) { _knownPortals.FirstOrDefault>((KeyValuePair x) => x.Value.HubSign == zdo2).Deconstruct(out key, out value); ExtendedZDO extendedZDO = key; PortalState portalState = value; if (portalState != null) { string text = StringExtensionMethods.RemoveRichTextTags(zdo2.Vars.GetText()); if (text != null && portalState.Tag != text) { portalState.Tag = text; extendedZDO.Vars.SetTag(text, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PortalHubProcessor.cs", 114); portalState.HubPortal?.Vars.SetTag(text, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PortalHubProcessor.cs", 115); portalState.HubSign?.Vars.SetText("" + text, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PortalHubProcessor.cs", 116); _updateHub = true; } } return true; } if (zdo2.PrefabInfo.TeleportWorld == null) { base.UnregisterZdoProcessor = true; return false; } if (base.PlacedObjects.Contains(zdo2)) { _knownPortals.FirstOrDefault>((KeyValuePair x) => x.Value.HubPortal == zdo2).Deconstruct(out key, out value); ExtendedZDO extendedZDO2 = key; PortalState portalState2 = value; if (portalState2 != null) { string tag = zdo2.Vars.GetTag(); if (tag != null && portalState2.Tag != tag) { portalState2.Tag = tag; extendedZDO2.Vars.SetTag(tag, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PortalHubProcessor.cs", 132); portalState2.HubSign?.Vars.SetText("" + tag, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PortalHubProcessor.cs", 133); _updateHub = true; } } return true; } if (zdo2.IsModCreator()) { base.UnregisterZdoProcessor = true; return false; } string text2 = zdo2.Vars.GetTag(); _knownPortals.TryGetValue(zdo2, out PortalState state); if (_autoTag && state == null && string.IsNullOrEmpty(text2)) { Biome biome = Processor.GetBiome(((ZDO)zdo2).GetPosition()); string arg = Localization.instance.Localize("$biome_" + ((object)(Biome)(ref biome)).ToString().ToLowerInvariant()); HashSet hashSet = (from x in ZDOMan.instance.GetPortals().Values.SelectMany((List x) => x) select ((ExtendedZDO)(object)x).Vars.GetTag()).ToHashSet(); foreach (int item in Enumerable.Range(1, 1000)) { string text3 = string.Format(base.Config.PortalHub.AutoNameNewPortalsFormat.Value, arg, item); if (!hashSet.Contains(text3)) { zdo2.Vars.SetTag(text2 = text3, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PortalHubProcessor.cs", 158); break; } } } if (!CheckFilter(zdo2, text2)) { if (_knownPortals.Remove(zdo2)) { _updateHub = true; } zdo2.Destroyed -= OnKnownPortalDestroyed; } else if (state?.Tag != text2) { if (state != null) { state.Tag = text2; } else { Dictionary knownPortals = _knownPortals; ExtendedZDO key2 = zdo2; PortalState obj = new PortalState { Tag = text2, HubId = zdo2.Vars.GetPortalHubId(), AllowAllItems = zdo2.Fields(getUnknownComponent: false).GetBool(() => (TeleportWorld x) => x.m_allowAllItems, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PortalHubProcessor.cs", 176) }; value = obj; state = obj; knownPortals.Add(key2, value); zdo2.Destroyed += OnKnownPortalDestroyed; if (state.HubId == 0) { HashSet hashSet2 = (from x in _knownPortals.Values where x.AllowAllItems == state.AllowAllItems select x.HubId).ToHashSet(); int num = 0; while (!hashSet2.Add(++num)) { } ExtendedZDO.ZDOVars_ vars = zdo2.Vars; int value2 = (state.HubId = num); vars.SetPortalHubId(value2, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PortalHubProcessor.cs", 184); } } _updateHub = true; } return true; } private void UpdatePortalHub() { //IL_02ce: Unknown result type (might be due to invalid IL or missing references) //IL_02d3: Unknown result type (might be due to invalid IL or missing references) //IL_02f0: Unknown result type (might be due to invalid IL or missing references) //IL_0314: Unknown result type (might be due to invalid IL or missing references) IReadOnlyList readOnlyList = Array.Empty(); if (_hubEnabled && _knownPortals.Count > 0) { List list = new List(); IEnumerable first = from x in _knownPortals.Values group x by x.Tag into x where x.Count() % 2 != 0 select x.First(); IEnumerable second; if (!base.Config.General.InWorldConfigRoom.Value) { IEnumerable enumerable = Array.Empty(); second = enumerable; } else { IEnumerable enumerable = new <>z__ReadOnlySingleElementList(new PortalState { Tag = "ServersideQoL Portal Hub", HubId = 0, AllowAllItems = true }); second = enumerable; } list.AddRange(from x in first.Concat(second) orderby x.Tag select x); readOnlyList = new <>z__ReadOnlyList(list); } if (readOnlyList.Count == 0) { foreach (ExtendedZDO placedObject in base.PlacedObjects) { placedObject.Destroy(); } base.PlacedObjects.Clear(); return; } int width = Math.Max(3, (int)Math.Ceiling((float)readOnlyList.Count / 4f + 1f)); _hubRadius = (float)(width + 1) * 4f * Mathf.Sqrt(2f); bool flag = width == _lastHubWidth; _lastHubWidth = width; if (flag) { List list2 = base.PlacedObjects.Where((ExtendedZDO x) => ((ZDO)x).GetPrefab() != Prefabs.GraustenFloor4x4 && ((ZDO)x).GetPrefab() != Prefabs.GraustenWall4x2 && ((ZDO)x).GetPrefab() != Prefabs.DvergerGuardstone).ToList(); foreach (ExtendedZDO item in list2) { item.Destroy(); base.PlacedObjects.Remove(item); } } else { foreach (ExtendedZDO placedObject2 in base.PlacedObjects) { placedObject2.Destroy(); } base.PlacedObjects.Clear(); for (int j = 0; j < width; j++) { float num = ((float)j - (float)width / 2f) * 4f; for (int l = 0; l < width; l++) { float num2 = ((float)l - (float)width / 2f) * 4f; Vector3 offset = _offset; offset.x += num; offset.z += num2; PlacePiece(offset, Prefabs.GraustenFloor4x4, 0f); offset.y += 4.5f; PlacePiece(offset, Prefabs.GraustenFloor4x4, 0f); offset.y -= 4.5f; } } } IEnumerator enumerator4 = readOnlyList.GetEnumerator(); for (int m = 0; m < width; m++) { PlacePortalAndWalls(0, m, width, flag, enumerator4, (int _, int k) => k < width - 1); } for (int n = 0; n < width; n++) { PlacePortalAndWalls(n, width - 1, width, flag, enumerator4, (int i, int _) => i < width - 1); } for (int num3 = width - 1; num3 >= 0; num3--) { PlacePortalAndWalls(width - 1, num3, width, flag, enumerator4, (int _, int k) => k > 0); } for (int num4 = width - 1; num4 >= 0; num4--) { PlacePortalAndWalls(num4, 0, width, flag, enumerator4, (int i, int _) => i > 0); } if (!enumerator4.MoveNext()) { return; } throw new Exception("Algorithm failed to place all portals"); } private IReadOnlyList GetTorches(int hubId) { if (hubId == 0) { return Array.Empty(); } List list = new List(1) { 0 }; for (int i = 0; i < hubId; i++) { list[0]++; for (int j = 0; j < list.Count; j++) { if (list[j] >= 3) { list[j] = 0; if (j == list.Count - 1) { list.Add(1); } else { list[j + 1]++; } } } } for (int k = 0; k < list.Count; k++) { list[k] = _torchPrefabs[list[k]]; } return list; } private void PlacePortalAndWalls(int i, int k, int width, bool dontUpdateFloorAndWalls, IEnumerator statesEnumerator, Func placePortal) { //IL_0025: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_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_04e6: Unknown result type (might be due to invalid IL or missing references) //IL_04eb: 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_04af: Unknown result type (might be due to invalid IL or missing references) //IL_04cf: Unknown result type (might be due to invalid IL or missing references) //IL_053d: 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_029e: Unknown result type (might be due to invalid IL or missing references) //IL_0314: 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_033e: 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_03c0: Unknown result type (might be due to invalid IL or missing references) float num = ((float)i - (float)width / 2f) * 4f; float num2 = ((float)k - (float)width / 2f) * 4f; Vector3 offset = _offset; offset.x += num; offset.z += num2; bool flag = i == 0 || i == width - 1; bool flag2 = k == 0 || k == width - 1; if (!flag && !flag2) { throw new Exception("Unexpected values"); } float num3 = 0f; if (flag && flag2) { num3 = ((k == 0 && i == 0) ? 45f : ((k == 0 && i != 0) ? 315f : ((k == 0 || i != 0) ? 225f : 135f))); } else if (flag) { num3 = ((i != 0) ? (num3 + 270f) : (num3 + 90f)); } else if (flag2 && k != 0) { num3 += 180f; } if (!flag) { offset.z += ((k == 0) ? (-1.5f) : 1.5f); } else if (!flag2) { offset.x += ((i == 0) ? (-1.5f) : 1.5f); } if (placePortal(i, k) && statesEnumerator.MoveNext()) { PortalState current = statesEnumerator.Current; float num4 = (current.AllowAllItems ? (-0.25f) : 0f); offset.y += num4; current.HubPortal = PlacePiece(offset, current.AllowAllItems ? Prefabs.Portal : Prefabs.PortalWood, num3); offset.y -= num4; current.HubPortal.Fields(getUnknownComponent: false).Set(() => (TeleportWorld x) => x.m_allowAllItems, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PortalHubProcessor.cs", 349); current.HubPortal.Vars.SetTag(current.Tag, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PortalHubProcessor.cs", 350); if (flag && flag2) { offset.z += ((k == 0) ? (-0.25f) : 0.25f) * Mathf.Sqrt(2f); offset.x += ((i == 0) ? (-0.25f) : 0.25f) * Mathf.Sqrt(2f); } else if (!flag) { offset.z += ((k == 0) ? (-0.25f) : 0.25f); } else if (!flag2) { offset.x += ((i == 0) ? (-0.25f) : 0.25f); } offset.y += 2f; current.HubSign = PlacePiece(offset, Prefabs.Sign, num3); current.HubSign.Vars.SetText("" + current.Tag, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PortalHubProcessor.cs", 364); IReadOnlyList torches = GetTorches(current.HubId); if (torches != null && torches.Count > 0) { offset.y -= 1.5f; Vector3 val = offset; float num5 = ((flag && flag2) ? (0.25f / Mathf.Sqrt(2f)) : 0.25f); for (int j = 0; j < torches.Count; j++) { offset = val; float num6 = ((float)j - (float)(torches.Count - 1) / 2f) * num5; if (flag && flag2) { offset.x += ((k == 0) ? num6 : (0f - num6)); offset.z += ((i == 0) ? (0f - num6) : num6); } else if (!flag) { offset.x += ((k == 0) ? num6 : (0f - num6)); } else if (!flag2) { offset.z += ((i == 0) ? (0f - num6) : num6); } PlacePiece(offset, torches[j], num3).Fields(getUnknownComponent: false).Set(() => (Fireplace x) => x.m_infiniteFuel, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PortalHubProcessor.cs", 385).Set(() => (Fireplace x) => x.m_disableCoverCheck, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PortalHubProcessor.cs", 386); } } } if (!dontUpdateFloorAndWalls) { if (flag) { offset = _offset; offset.x += num; offset.z += num2; offset.y += 0.25f; num3 = ((i == 0) ? 90 : 270); offset.x += ((i == 0) ? (-2f) : 2f); PlacePiece(offset, Prefabs.GraustenWall4x2, num3); offset.y += 2f; PlacePiece(offset, Prefabs.GraustenWall4x2, num3); } if (flag2) { offset = _offset; offset.x += num; offset.z += num2; offset.y += 0.25f; num3 = ((k != 0) ? 180 : 0); offset.z += ((k == 0) ? (-2f) : 2f); PlacePiece(offset, Prefabs.GraustenWall4x2, num3); offset.y += 2f; PlacePiece(offset, Prefabs.GraustenWall4x2, num3); } } } } internal sealed class PortalProcessor : Processor { private sealed class ContainerState { [CompilerGenerated] private DateTimeOffset k__BackingField; public Peer Peer { get; } public ExtendedZDO Container { get; set; } public ExtendedZDO Player { get; } public Vector3 InitialPosition { get; } public long PlayerID { get; } public Vector3 PortalPosition { get; } public bool Stacked { get; set; } public DateTimeOffset NextRequest { get { return k__BackingField; } set { k__BackingField = value; DestroyAfter = value.AddSeconds(5.0); } } public DateTimeOffset DestroyAfter { get; private set; } public ContainerState(ExtendedZDO container, Peer peer, ExtendedZDO player, ExtendedZDO portal) { //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_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) Peer = peer; Container = container; Player = player; InitialPosition = ((ZDO)player).GetPosition(); PlayerID = player.Vars.GetPlayerID(0L); PortalPosition = ((ZDO)portal).GetPosition(); base..ctor(); } } private bool _destroyNewPortals; private float _rangeSqr; private readonly HashSet _initialPortals = new HashSet(); private readonly List _containers = new List(); protected override Guid Id { get; } = Guid.Parse("a59669f7-3573-4ece-9ec3-d42e67a772c1"); public override void Initialize(bool firstTime) { base.Initialize(firstTime); foreach (ExtendedZDO initialPortal in _initialPortals) { initialPortal.Destroyed -= OnInitialPortalDestroyed; } _initialPortals.Clear(); _destroyNewPortals = base.Config.GlobalsKeys.NoPortalsPreventsContruction.Value && ZoneSystem.instance.GetGlobalKey((GlobalKeys)27); if (_destroyNewPortals) { ZoneSystem.instance.RemoveGlobalKey((GlobalKeys)27); foreach (ExtendedZDO item in ZDOMan.instance.GetPortals().Values.SelectMany((List x) => x)) { _initialPortals.Add(item); item.Destroyed += OnInitialPortalDestroyed; } } _rangeSqr = base.Config.NonTeleportableItems.PortalRange.Value; _rangeSqr *= _rangeSqr; if (firstTime) { _containers.Clear(); } } private void OnInitialPortalDestroyed(ExtendedZDO zdo) { _initialPortals.Remove(zdo); } private void OnContainerDestroyed(ExtendedZDO zdo) { for (int i = 0; i < _containers.Count; i++) { ContainerState containerState = _containers[i]; if (containerState.Container == zdo) { containerState.Player.Destroyed -= OnPlayerDestroyed; _containers.RemoveAt(i); break; } } } private void OnPlayerDestroyed(ExtendedZDO zdo) { //IL_005f: Unknown result type (might be due to invalid IL or missing references) //IL_0064: 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) for (int i = 0; i < _containers.Count; i++) { ContainerState containerState = _containers[i]; if (containerState.Player != zdo) { continue; } containerState.Container.Destroyed -= OnContainerDestroyed; if (!containerState.Stacked) { DestroyObject(containerState.Container); } else { containerState.Container.ReleaseOwnershipInternal(); ExtendedZDO container = containerState.Container; Vector3 initialPosition = containerState.InitialPosition; initialPosition.y = -1000f; ((ZDO)container).SetPosition(initialPosition); containerState.Container.Fields(getUnknownComponent: false).Set(() => (Container x) => x.m_autoDestroyEmpty, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PortalProcessor.cs", 89); containerState.Container.CreateClone(); DestroyObject(containerState.Container); } _containers.RemoveAt(i); break; } } protected override void PreProcessCore(IEnumerable peers) { //IL_0054: 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_0383: Unknown result type (might be due to invalid IL or missing references) //IL_038e: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Unknown result type (might be due to invalid IL or missing references) //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_015f: Unknown result type (might be due to invalid IL or missing references) //IL_0095: 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_0329: Unknown result type (might be due to invalid IL or missing references) //IL_00f1: Unknown result type (might be due to invalid IL or missing references) //IL_042c: Unknown result type (might be due to invalid IL or missing references) //IL_0431: Unknown result type (might be due to invalid IL or missing references) //IL_043e: Unknown result type (might be due to invalid IL or missing references) //IL_03f0: Unknown result type (might be due to invalid IL or missing references) //IL_03fb: Unknown result type (might be due to invalid IL or missing references) for (int num = _containers.Count - 1; num >= 0; num--) { ContainerState containerState = _containers[num]; if (containerState.Container.Inventory.Items.Count == 0) { DestroyObject(containerState.Container); } else if (containerState.Stacked) { if (Utils.DistanceSqr(containerState.PortalPosition, ((ZDO)containerState.Player).GetPosition()) > _rangeSqr) { if (((ZDO)containerState.Container).GetOwner() == ((ZDO)containerState.Player).GetOwner() && ZNetScene.InActiveArea(((ZDO)containerState.Container).GetSector(), ((ZDO)containerState.Player).GetSector())) { DateTimeOffset utcNow = DateTimeOffset.UtcNow; if (utcNow > containerState.NextRequest) { containerState.NextRequest = utcNow.AddMilliseconds(200.0); RPC.TakeAllResponse(containerState.Container, granted: true); Processor.ShowMessage(new <>z__ReadOnlySingleElementList(containerState.Peer), containerState.PortalPosition, base.Config.Localization.NonTeleportableItems.ItemsReturned, base.Config.NonTeleportableItems.MessageType.Value, (TextType)0); } } else { containerState.Container.SetOwnerInternal(((ZDO)containerState.Player).GetOwner()); ExtendedZDO container = containerState.Container; Vector3 position = ((ZDO)containerState.Player).GetPosition(); position.y = -1000f; ((ZDO)container).SetPosition(position); containerState.Container.Destroyed -= OnContainerDestroyed; containerState.Container = RecreatePiece(containerState.Container); containerState.Container.UnregisterAllProcessors(); containerState.Container.Destroyed += OnContainerDestroyed; } } } else if (containerState.Container.Inventory.Items.Any(delegate(ItemData x) { //IL_0004: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) if (x != null) { Vector2i gridPos = x.m_gridPos; int x2 = gridPos.x; if (x2 <= 0) { int stack = x.m_stack; if (stack <= 1) { goto IL_0024; } } return true; } goto IL_0024; IL_0024: return false; })) { int num2 = 0; for (int num3 = containerState.Container.Inventory.Items.Count - 1; num3 >= 0; num3--) { ItemData val = containerState.Container.Inventory.Items[num3]; if (val.m_gridPos.x == 0) { if (--val.m_stack == 0) { containerState.Container.Inventory.Items.RemoveAt(num3); } num2 += val.m_stack; } } containerState.Container.Inventory.Save(); containerState.Container.Vars.SetReturnContentToCreator(value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PortalProcessor.cs", 146); containerState.Container.Vars.SetCreator(containerState.PlayerID, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PortalProcessor.cs", 147); containerState.Stacked = true; containerState.Container.Destroyed -= OnContainerDestroyed; containerState.Container = RecreatePiece(containerState.Container); containerState.Container.UnregisterAllProcessors(); containerState.Container.Destroyed += OnContainerDestroyed; Processor.ShowMessage(new <>z__ReadOnlySingleElementList(containerState.Peer), containerState.PortalPosition, base.Config.Localization.NonTeleportableItems.FormatItemsTaken(num2), base.Config.NonTeleportableItems.MessageType.Value, (TextType)0); containerState.NextRequest = DateTimeOffset.UtcNow.AddSeconds(1.0); } else if (Utils.DistanceSqr(containerState.PortalPosition, ((ZDO)containerState.Player).GetPosition()) <= _rangeSqr) { DateTimeOffset utcNow2 = DateTimeOffset.UtcNow; if (utcNow2 > containerState.NextRequest) { containerState.NextRequest = utcNow2.AddMilliseconds(200.0); if (((ZDO)containerState.Container).GetOwner() != ((ZDO)containerState.Player).GetOwner() || !ZNetScene.InActiveArea(((ZDO)containerState.Container).GetSector(), ((ZDO)containerState.Player).GetSector())) { containerState.Container.SetOwnerInternal(((ZDO)containerState.Player).GetOwner()); ExtendedZDO container2 = containerState.Container; Vector3 position = ((ZDO)containerState.Player).GetPosition(); position.y = -1000f; ((ZDO)container2).SetPosition(position); containerState.Container.Destroyed -= OnContainerDestroyed; containerState.Container = RecreatePiece(containerState.Container); containerState.Container.UnregisterAllProcessors(); containerState.Container.Destroyed += OnContainerDestroyed; } RPC.StackResponse(containerState.Container, granted: true); RPC.ShowMessage(((ZDO)containerState.Player).GetOwner(), (MessageType)2, ""); } } else if (DateTimeOffset.UtcNow > containerState.DestroyAfter) { DestroyObject(containerState.Container); } } } protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_012f: Unknown result type (might be due to invalid IL or missing references) //IL_0134: Unknown result type (might be due to invalid IL or missing references) //IL_0142: Unknown result type (might be due to invalid IL or missing references) //IL_022a: Unknown result type (might be due to invalid IL or missing references) //IL_022f: Unknown result type (might be due to invalid IL or missing references) if (zdo.PrefabInfo.TeleportWorld == null) { base.UnregisterZdoProcessor = true; return false; } if (_destroyNewPortals && !_initialPortals.Contains(zdo) && !zdo.IsModCreator()) { RPC.Remove(zdo); long owner = ((ZDO)zdo).GetOwner(); if (owner != 0L) { RPC.ShowMessage(owner, (MessageType)2, "$msg_nobuildzone"); } return false; } if (zdo.Fields(getUnknownComponent: false).GetBool(() => (TeleportWorld x) => x.m_allowAllItems, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PortalProcessor.cs", 205)) { base.UnregisterZdoProcessor = true; return false; } if (base.TeleportableItems.Count == 0) { return false; } foreach (Peer item in peers.AsEnumerable()) { ExtendedZDO player = Processor.Instance().GetPeerCharacter(item.m_uid); if (player == null || Utils.DistanceSqr(((ZDO)zdo).GetPosition(), ((ZDO)player).GetPosition()) > _rangeSqr || _containers.Any((ContainerState x) => x.Player == player)) { continue; } Vector3 position = ((ZDO)player).GetPosition(); position.y = -1000f; ExtendedZDO extendedZDO = PlacePiece(position, Prefabs.PrivateChest, 0f); extendedZDO.UnregisterAllProcessors(); int value = Math.Max(4, base.TeleportableItems.Count); extendedZDO.Fields(getUnknownComponent: false).Set(() => (Container x) => x.m_width, 8, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PortalProcessor.cs", 227).Set(() => (Container x) => x.m_height, value, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\PortalProcessor.cs", 228); int num = 0; foreach (KeyValuePair teleportableItem in base.TeleportableItems) { teleportableItem.Deconstruct(out var key, out var value2); ItemData val = key; GameObject dropPrefab = value2; ItemData val2 = val.Clone(); val2.m_dropPrefab = dropPrefab; val2.m_stack = 1; val2.m_gridPos = new Vector2i(0, num++); extendedZDO.Inventory.Items.Add(val2); } extendedZDO.Inventory.Save(); extendedZDO.SetOwner(item.m_uid); _containers.Add(new ContainerState(extendedZDO, item, player, zdo) { NextRequest = DateTimeOffset.UtcNow.AddMilliseconds(200.0) }); extendedZDO.Destroyed += OnContainerDestroyed; if (!item.IsServer) { player.Destroyed += OnPlayerDestroyed; } RPC.StackResponse(extendedZDO, granted: true); RPC.ShowMessage(((ZDO)player).GetOwner(), (MessageType)2, ""); } return false; } } internal abstract class Processor { [AttributeUsage(AttributeTargets.Class)] public sealed class ProcessorAttribute : Attribute { public required int Priority { get; init; } } private static class InstanceCache where T : Processor, new() { public static T Instance { get; } = DefaultProcessors.OfType().First(); } private sealed class RpcDelegate { public Delegate Delegate { get; } public ParameterInfo[] Parameters { get; } public int DataParameterIndex { get; } public int ZdoParameterIndex { get; } public RpcDelegate(Delegate del) { Delegate = del; Parameters = del.Method.GetParameters(); List list = Parameters.Select((ParameterInfo x) => x.ParameterType).ToList(); DataParameterIndex = list.IndexOf(typeof(RoutedRPCData)); ZdoParameterIndex = list.IndexOf(typeof(ExtendedZDO)); } } private sealed record RpcMethod(string Name, List Delegates); [Flags] public enum CreatorMarkers : uint { None = 0u, DataZDO = 1u, ProcessorOwned = 2u } public static class PrefabNames { public const string Megingjord = "BeltStrength"; public const string CryptKey = "CryptKey"; public const string Wishbone = "Wishbone"; public const string TornSpirit = "YagluthDrop"; public const string BlackmetalChest = "piece_chest_blackmetal"; public const string ReinforcedChest = "piece_chest"; public const string WoodChest = "piece_chest_wood"; public const string Barrel = "piece_chest_barrel"; public const string Incinerator = "incinerator"; public const string GiantBrain = "giant_brain"; public const string Hoe = "Hoe"; } public static class Prefabs { public static int Hammer { get; } = StringExtensionMethods.GetStableHashCode("Hammer", true); public static int Hoe { get; } = StringExtensionMethods.GetStableHashCode("Hoe", true); public static int GraustenFloor4x4 { get; } = StringExtensionMethods.GetStableHashCode("Piece_grausten_floor_4x4", true); public static int GraustenWall4x2 { get; } = StringExtensionMethods.GetStableHashCode("Piece_grausten_wall_4x2", true); public static int PortalWood { get; } = StringExtensionMethods.GetStableHashCode("portal_wood", true); public static int Portal { get; } = StringExtensionMethods.GetStableHashCode("portal", true); public static int Sconce { get; } = StringExtensionMethods.GetStableHashCode("piece_walltorch", true); public static int DvergerGuardstone { get; } = StringExtensionMethods.GetStableHashCode("dverger_guardstone", true); public static int Sign { get; } = StringExtensionMethods.GetStableHashCode("sign", true); public static int Candle { get; } = StringExtensionMethods.GetStableHashCode("Candle_resin", true); public static int BlackmetalChest { get; } = StringExtensionMethods.GetStableHashCode("piece_chest_blackmetal", true); public static int ReinforcedChest { get; } = StringExtensionMethods.GetStableHashCode("piece_chest", true); public static int Barrel { get; } = StringExtensionMethods.GetStableHashCode("piece_chest_barrel", true); public static int WoodChest { get; } = StringExtensionMethods.GetStableHashCode("piece_chest_wood", true); public static int Incinerator { get; } = StringExtensionMethods.GetStableHashCode("incinerator", true); public static int CargoCrate { get; } = StringExtensionMethods.GetStableHashCode("CargoCrate", true); public static int PrivateChest { get; } = StringExtensionMethods.GetStableHashCode("piece_chest_private", true); public static int StandingIronTorch { get; } = StringExtensionMethods.GetStableHashCode("piece_groundtorch", true); public static int StandingIronTorchGreen { get; } = StringExtensionMethods.GetStableHashCode("piece_groundtorch_green", true); public static int StandingIronTorchBlue { get; } = StringExtensionMethods.GetStableHashCode("piece_groundtorch_blue", true); public static int MountainRemainsBuried { get; } = StringExtensionMethods.GetStableHashCode("Pickable_MountainRemains01_buried", true); public static int TombStone { get; } = StringExtensionMethods.GetStableHashCode("Player_tombstone", true); } protected static class StatusEffects { public static int Wishbone { get; } = StringExtensionMethods.GetStableHashCode("Wishbone", true); public static int Demister { get; } = StringExtensionMethods.GetStableHashCode("Demister", true); public static int Megingjord { get; } = StringExtensionMethods.GetStableHashCode("BeltStrength", true); } protected static class RPC { private static readonly Dictionary __invokeCounters = new Dictionary(); private static readonly Dictionary __invokeAsSenderCounters = new Dictionary(); private static int __invokeTotalCounter; private static Action? __invokeRouteRPCAsSender; public static void ShowMessage(long targetPeerId, MessageType type, string message) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Expected I4, but got Unknown InvokeRoutedRPC(targetPeerId, "ShowMessage", new object[2] { (int)type, message }); } public static void ShowMessage(Peer peer, MessageType type, string message) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) ShowMessage(peer.m_uid, type, message); } public static void ShowMessage(IEnumerable peers, MessageType type, string message) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) foreach (Peer peer in peers) { ShowMessage(peer, type, message); } } public static void UseStamina(ExtendedZDO playerZdo, float value) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) InvokeRoutedRPC(((ZDO)playerZdo).GetOwner(), ((ZDO)playerZdo).m_uid, "UseStamina", new object[1] { value }); } public static void SendGlobalKeys(Peer peer, List keys) { InvokeRoutedRPC(peer.m_uid, "GlobalKeys", new object[1] { keys }); } public static void ShowInWorldText(IEnumerable targetPeerIds, TextType type, Vector3 pos, string text) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Expected O, but got Unknown //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Expected I4, but got Unknown //IL_000e: Unknown result type (might be due to invalid IL or missing references) ZPackage val = new ZPackage(); val.Write((int)type); val.Write(pos); val.Write(text); val.Write(false); foreach (long targetPeerId in targetPeerIds) { InvokeRoutedRPC(targetPeerId, "RPC_DamageText", new object[1] { val }); } } private static void TeleportPlayer(long targetPeerID, Vector3 pos, Quaternion rot, bool distantTeleport) { //IL_000e: 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) InvokeRoutedRPC(targetPeerID, "RPC_TeleportPlayer", new object[3] { pos, rot, distantTeleport }); } public static void TeleportPlayer(Peer peer, Vector3 pos, Quaternion rot, bool distantTeleport) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0007: Unknown result type (might be due to invalid IL or missing references) TeleportPlayer(peer.m_uid, pos, rot, distantTeleport); } public static void TeleportPlayer(ExtendedZDO player, Vector3 pos, Quaternion rot, bool distantTeleport) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Unknown result type (might be due to invalid IL or missing references) //IL_0022: Unknown result type (might be due to invalid IL or missing references) InvokeRoutedRPC(((ZDO)player).GetOwner(), ((ZDO)player).m_uid, "RPC_TeleportTo", new object[3] { pos, rot, distantTeleport }); } public static void Remove(ExtendedZDO piece, bool blockDrop = false) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) InvokeRoutedRPC(((ZDO)piece).GetOwner(), ((ZDO)piece).m_uid, "RPC_Remove", new object[1] { false }); } public static void AddStatusEffect(ExtendedZDO character, int nameHash, bool resetTime = false, int itemLevel = 0, float skillLevel = 0f) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) InvokeRoutedRPC(((ZDO)character).GetOwner(), ((ZDO)character).m_uid, "RPC_AddStatusEffect", new object[4] { nameHash, resetTime, itemLevel, skillLevel }); } public static void RequestStack(ExtendedZDO container, ExtendedZDO player, long playerID = 0L) { //IL_0022: Unknown result type (might be due to invalid IL or missing references) if (playerID == 0L) { playerID = player.Vars.GetPlayerID(0L); } InvokeRoutedRPCAsSender(((ZDO)player).GetOwner(), ((ZDO)container).GetOwner(), ((ZDO)container).m_uid, "RPC_RequestStack", new object[1] { playerID }); } public static void StackResponse(ExtendedZDO container, bool granted) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) InvokeRoutedRPC(((ZDO)container).GetOwner(), ((ZDO)container).m_uid, "RPC_StackResponse", new object[1] { granted }); } public static void TakeAllResponse(ExtendedZDO container, bool granted) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) InvokeRoutedRPC(((ZDO)container).GetOwner(), ((ZDO)container).m_uid, "TakeAllRespons", new object[1] { granted }); } public static void RequestStateChange(ExtendedZDO trap, int state) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) InvokeRoutedRPC(((ZDO)trap).GetOwner(), ((ZDO)trap).m_uid, "RPC_RequestStateChange", new object[1] { state }); } public static void SetTamed(ExtendedZDO character, bool tamed) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) InvokeRoutedRPC(((ZDO)character).GetOwner(), ((ZDO)character).m_uid, "RPC_SetTamed", new object[1] { tamed }); } public static void Damage(ExtendedZDO character, HitData hitData) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) InvokeRoutedRPC(((ZDO)character).GetOwner(), ((ZDO)character).m_uid, "RPC_Damage", new object[1] { hitData }); } public static void RequestOwn(ExtendedZDO itemDrop, [CallerFilePath] string callerFile = null, [CallerLineNumber] int callerLineNo = 0) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) InvokeRoutedRPC(((ZDO)itemDrop).GetOwner(), ((ZDO)itemDrop).m_uid, "RPC_RequestOwn"); } public static void RequestOpen(ExtendedZDO container, long playerID) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) InvokeRoutedRPC(((ZDO)container).GetOwner(), ((ZDO)container).m_uid, "RequestOpen", new object[1] { playerID }); } public static void RequestOpenFor(ExtendedZDO player, ExtendedZDO container) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) InvokeRoutedRPCAsSender(((ZDO)player).GetOwner(), ((ZDO)container).GetOwner(), ((ZDO)container).m_uid, "RequestOpen", new object[1] { player.Vars.GetPlayerID(0L) }); } public static void OpenResponse(ExtendedZDO container, bool granted) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) InvokeRoutedRPC(((ZDO)container).GetOwner(), ((ZDO)container).m_uid, "OpenRespons", new object[1] { granted }); } public static void DamageMineRock5(ExtendedZDO minerock5, HitData hit, int hitAreaIndex) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) InvokeRoutedRPC(((ZDO)minerock5).GetOwner(), ((ZDO)minerock5).m_uid, "RPC_Damage", new object[2] { hit, hitAreaIndex }); } private static void InvokeRoutedRPC(long targetPeerId, string methodName, object[]? parameters = null) { if (Main.Instance.Config.General.DiagnosticLogs.Value) { __invokeCounters.TryGetValue(methodName, out var value); value = (__invokeCounters[methodName] = value + 1); __invokeTotalCounter++; if (value % 10 == 0) { Main.Instance.Logger.LogInfo(string.Format("{0}: {1}: {2} of {3} ({4:P0})", "InvokeRoutedRPC", methodName, value, __invokeTotalCounter, (float)value / (float)__invokeTotalCounter)); } } ZRoutedRpc.instance.InvokeRoutedRPC(targetPeerId, methodName, parameters ?? Array.Empty()); } private static void InvokeRoutedRPC(long targetPeerId, ZDOID targetZDO, string methodName, object[]? parameters = null) { //IL_00a6: Unknown result type (might be due to invalid IL or missing references) if (Main.Instance.Config.General.DiagnosticLogs.Value) { __invokeCounters.TryGetValue(methodName, out var value); value = (__invokeCounters[methodName] = value + 1); __invokeTotalCounter++; if (value % 10 == 0) { Main.Instance.Logger.LogInfo(string.Format("{0}: {1}: {2} of {3} ({4:P0})", "InvokeRoutedRPC", methodName, value, __invokeTotalCounter, (float)value / (float)__invokeTotalCounter)); } } ZRoutedRpc.instance.InvokeRoutedRPC(targetPeerId, targetZDO, methodName, parameters ?? Array.Empty()); } private static void InvokeRoutedRPCAsSender(long senderPeerId, long targetPeerID, ZDOID targetZDO, string methodName, object[] parameters) { //IL_00bc: Unknown result type (might be due to invalid IL or missing references) if (Main.Instance.Config.General.DiagnosticLogs.Value) { __invokeAsSenderCounters.TryGetValue(methodName, out var value); value = (__invokeAsSenderCounters[methodName] = value + 1); __invokeTotalCounter++; if (value % 10 == 0) { Main.Instance.Logger.LogInfo(string.Format("{0}: {1}: {2} of {3} ({4:P0})", "InvokeRoutedRPCAsSender", methodName, value, __invokeTotalCounter, (float)value / (float)__invokeTotalCounter)); } } if (__invokeRouteRPCAsSender == null) { __invokeRouteRPCAsSender = GetDelegate(); } __invokeRouteRPCAsSender(ZRoutedRpc.instance, targetPeerID, targetZDO, methodName, parameters, senderPeerId); static Action GetDelegate() { //IL_006b: 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_007c: Expected O, but got Unknown //IL_00bd: Unknown result type (might be due to invalid IL or missing references) //IL_00c7: Expected O, but got Unknown //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_0118: Unknown result type (might be due to invalid IL or missing references) //IL_0130: Unknown result type (might be due to invalid IL or missing references) FieldInfo field = GetField((RoutedRPCData x) => x.m_senderPeerID); FieldInfo field2 = typeof(ZRoutedRpc).GetField("m_id", BindingFlags.Instance | BindingFlags.NonPublic); MethodInfo method = new Action(ZRoutedRpc.instance.InvokeRoutedRPC).Method; DynamicMethodDefinition val = new DynamicMethodDefinition((MethodBase)method) { Name = "InvokeRoutedRPC_InjectSender" }; typeof(DynamicMethodDefinition).GetProperty("OriginalMethod").SetValue(val, null); ((MethodReference)val.Definition).Parameters.Add(new ParameterDefinition("senderPeerID", (ParameterAttributes)0, val.Module.ImportReference(typeof(long)))); Collection instructions = val.Definition.Body.Instructions; bool flag = false; for (int i = 2; i < instructions.Count; i++) { if (ILPatternMatchingExt.MatchStfld(instructions[i], field) && ILPatternMatchingExt.MatchLdfld(instructions[i - 1], field2) && instructions[i - 2].OpCode == OpCodes.Ldarg_0) { instructions[i - 1] = val.GetILProcessor().Create(OpCodes.Ldarg, ((MethodReference)val.Definition).Parameters.Count - 1); instructions.RemoveAt(i - 2); flag = true; break; } } if (!flag) { throw new Exception("Failed"); } MethodInfo methodInfo = val.Generate(); return Extensions.CreateDelegate>((MethodBase)methodInfo); } static FieldInfo GetField(Expression> expression) where T : notnull where TField : notnull { if (expression.Body is MemberExpression memberExpression) { return (FieldInfo)memberExpression.Member; } throw new ArgumentException(); } } } private static IReadOnlyList? _defaultProcessors; private static bool __initialized; private static ExtendedZDO? _dataZDO; private static bool __enableProcessingTimeMonitoring; private static IReadOnlyDictionary? __teleportableItems; private static List __args = new List(); private static readonly Dictionary __argArrays = new Dictionary(); private static int __loopCounter; private static readonly Dictionary __methods = new Dictionary(); private static readonly MethodInfo __handleRoutedRPCMethod = typeof(ZRoutedRpc).GetMethod("HandleRoutedRPC", BindingFlags.Instance | BindingFlags.NonPublic); private static readonly MethodInfo __handleRoutedRPCPrefix = new Func(HandleRoutedRPCPrefix).Method; public static IReadOnlyList DefaultProcessors { get { IReadOnlyList? readOnlyList = _defaultProcessors; if (readOnlyList == null) { List list = new List(); list.AddRange(from x in typeof(Processor).Assembly.GetTypes() where (object)x != null && x.IsClass && !x.IsAbstract && x.IsSubclassOf(typeof(Processor)) orderby x.GetCustomAttribute()?.Priority ?? 0 descending select (Processor)Activator.CreateInstance(x)); readOnlyList = (_defaultProcessors = new <>z__ReadOnlyList(list)); } return readOnlyList; } } protected Logger Logger => Main.Instance.Logger; protected ModConfig Config => Main.Instance.Config; protected abstract Guid Id { get; } public bool DestroyZdo { get; protected set; } public bool RecreateZdo { get; protected set; } public bool UnregisterZdoProcessor { get; protected set; } protected HashSet PlacedObjects { get; } = new HashSet(); public double ProcessingTimeSeconds { get; private set; } public double TotalProcessingTimeSeconds { get; private set; } protected static ExtendedZDO DataZDO { get { //IL_001e: Unknown result type (might be due to invalid IL or missing references) if (_dataZDO == null) { _dataZDO = (ExtendedZDO)(object)ZDOMan.instance.CreateNewZDO(new Vector3(105000f, -1000f, 105000f), Prefabs.Sconce); ((ZDO)_dataZDO).SetPrefab(Prefabs.Sconce); ((ZDO)_dataZDO).Persistent = true; ((ZDO)_dataZDO).Distant = false; ((ZDO)_dataZDO).Type = (ObjectType)0; _dataZDO.SetModAsCreator(CreatorMarkers.DataZDO); _dataZDO.Vars.SetHealth(-1f, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\Processor.cs", 133); _dataZDO.Fields(getUnknownComponent: false).Set(() => (Piece x) => x.m_canBeRemoved, value: false, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\Processor.cs", 134); _dataZDO.Fields(getUnknownComponent: false).Set(() => (WearNTear x) => x.m_noRoofWear, value: false, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\Processor.cs", 135).Set(() => (WearNTear x) => x.m_noSupportWear, value: false, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\Processor.cs", 135) .Set(() => (WearNTear x) => x.m_health, -1f, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\Processor.cs", 135); _dataZDO.UnregisterAllProcessors(); } return _dataZDO; } } protected IReadOnlyDictionary TeleportableItems { get { if (__teleportableItems == null) { UpdateTeleportableItems(); } return __teleportableItems; } } public static T Instance() where T : Processor, new() { return InstanceCache.Instance; } public virtual void Initialize(bool firstTime) { __enableProcessingTimeMonitoring = Config.General.DiagnosticLogs.Value; __teleportableItems = null; ZoneSystemSendGlobalKeys.GlobalKeysChanged -= UpdateTeleportableItems; if (!firstTime) { __initialized = false; } else { if (__initialized) { return; } __initialized = true; _dataZDO = null; foreach (ExtendedZDO @object in ZDOMan.instance.GetObjects()) { if (!@object.IsModCreator(out var marker)) { continue; } if (marker == CreatorMarkers.None) { @object.Destroy(); continue; } if ((marker & CreatorMarkers.DataZDO) != 0) { if (_dataZDO == null) { _dataZDO = @object; } else { Logger.LogError("More then one DataZDO found, destroying the second one"); @object.Destroy(); } } if ((marker & CreatorMarkers.ProcessorOwned) == 0) { continue; } Guid processorId = @object.Vars.GetProcessorId(); foreach (Processor defaultProcessor in DefaultProcessors) { if (defaultProcessor.Id == processorId) { defaultProcessor.PlacedObjects.Add(@object); break; } } } } } public void PreProcess(IEnumerable peers) { if (!__enableProcessingTimeMonitoring) { PreProcessCore(peers); return; } TotalProcessingTimeSeconds += ProcessingTimeSeconds; double realtimeSinceStartupAsDouble = Time.realtimeSinceStartupAsDouble; PreProcessCore(peers); ProcessingTimeSeconds = Time.realtimeSinceStartupAsDouble - realtimeSinceStartupAsDouble; } protected virtual void PreProcessCore(IEnumerable peers) { } public virtual bool ClaimExclusive(ExtendedZDO zdo) { return PlacedObjects.Contains(zdo); } protected abstract bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers); public bool Process(ExtendedZDO zdo, IReadOnlyList peers) { DestroyZdo = false; RecreateZdo = false; UnregisterZdoProcessor = false; bool result; if (!__enableProcessingTimeMonitoring) { result = ProcessCore(zdo, peers); } else { double realtimeSinceStartupAsDouble = Time.realtimeSinceStartupAsDouble; result = ProcessCore(zdo, peers); ProcessingTimeSeconds += Time.realtimeSinceStartupAsDouble - realtimeSinceStartupAsDouble; } return result; } protected bool CheckMinDistance(IReadOnlyList peers, ZDO zdo) { return CheckMinDistance(peers, zdo, Config.General.MinPlayerDistance.Value); } protected static bool CheckMinDistance(IReadOnlyList peers, ZDO zdo, float minDistance) { //IL_001f: 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) minDistance *= minDistance; foreach (Peer item in peers.AsEnumerable()) { if (Utils.DistanceSqr(item.m_refPos, zdo.GetPosition()) < minDistance) { return false; } } return true; } protected static ExtendedZDO Spawn(int prefab, Vector3 pos, Quaternion rot) { //IL_0005: 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) ExtendedZDO extendedZDO = (ExtendedZDO)(object)ZDOMan.instance.CreateNewZDO(pos, prefab); ((ZDO)extendedZDO).SetPrefab(prefab); ((ZDO)extendedZDO).Persistent = true; ((ZDO)extendedZDO).Distant = false; ((ZDO)extendedZDO).Type = (ObjectType)0; ((ZDO)extendedZDO).SetRotation(rot); return extendedZDO; } protected ExtendedZDO PlaceObject(Vector3 pos, int prefab, float rot, CreatorMarkers marker = CreatorMarkers.None) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) return PlaceObject(pos, prefab, Quaternion.Euler(0f, rot, 0f), marker); } protected ExtendedZDO PlaceObject(Vector3 pos, int prefab, Quaternion rot, CreatorMarkers marker = CreatorMarkers.None) { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Unknown result type (might be due to invalid IL or missing references) ExtendedZDO extendedZDO = (ExtendedZDO)(object)ZDOMan.instance.CreateNewZDO(pos, prefab); PlacedObjects.Add(extendedZDO); ((ZDO)extendedZDO).SetPrefab(prefab); ((ZDO)extendedZDO).Persistent = true; ((ZDO)extendedZDO).Distant = false; ((ZDO)extendedZDO).Type = (ObjectType)0; ((ZDO)extendedZDO).SetRotation(rot); extendedZDO.SetModAsCreator(marker); extendedZDO.Vars.SetHealth(-1f, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\Processor.cs", 225); if (marker.HasFlag(CreatorMarkers.ProcessorOwned)) { extendedZDO.Vars.SetProcessorId(Id, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\Processor.cs", 227); } return extendedZDO; } protected ExtendedZDO PlacePiece(Vector3 pos, int prefab, float rot, CreatorMarkers marker = CreatorMarkers.None) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) return PlacePiece(pos, prefab, Quaternion.Euler(0f, rot, 0f), marker); } protected ExtendedZDO PlacePiece(Vector3 pos, int prefab, Quaternion rot, CreatorMarkers marker = CreatorMarkers.None) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0003: Unknown result type (might be due to invalid IL or missing references) ExtendedZDO extendedZDO = PlaceObject(pos, prefab, rot, marker); extendedZDO.Fields(getUnknownComponent: false).Set(() => (Piece x) => x.m_canBeRemoved, value: false, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\Processor.cs", 238); extendedZDO.Fields(getUnknownComponent: false).Set(() => (WearNTear x) => x.m_noRoofWear, value: false, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\Processor.cs", 240).Set(() => (WearNTear x) => x.m_noSupportWear, value: false, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\Processor.cs", 241) .Set(() => (WearNTear x) => x.m_health, -1f, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\Processor.cs", 242); return extendedZDO; } protected ExtendedZDO RecreatePiece(ExtendedZDO zdo) { if (!PlacedObjects.Remove(zdo)) { throw new ArgumentException(); } PlacedObjects.Add(zdo = zdo.Recreate()); return zdo; } protected void DestroyObject(ExtendedZDO zdo) { if (!PlacedObjects.Remove(zdo)) { throw new ArgumentException(); } zdo.Destroy(); } protected static Heightmap GetHeightmap(Vector3 pos) { //IL_0000: 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) return Heightmap.FindHeightmap(pos) ?? SharedProcessorState.CreateHeightmap(pos); } protected static Biome GetBiome(Vector3 pos) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000d: Unknown result type (might be due to invalid IL or missing references) return GetHeightmap(pos).GetBiome(pos, 0.02f, false); } protected static float GetHeight(Vector3 pos) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) return GetHeightmap(pos).GetHeight(pos); } protected static string ConvertToRegexPattern(string searchPattern) { searchPattern = Regex.Escape(searchPattern); searchPattern = searchPattern.Replace("\\*", ".*").Replace("\\?", ".?"); return "(?i)^" + searchPattern + "$"; } protected bool IsItemTeleportable(ItemData item) { if (item.m_shared.m_teleportable || ZoneSystem.instance.GetGlobalKey((GlobalKeys)30)) { return true; } if (!Config.NonTeleportableItems.Enable.Value) { return false; } return TeleportableItems.ContainsKey(item); } protected bool HasNonTeleportableItem(IEnumerable items) { foreach (ItemData item in items) { if (!IsItemTeleportable(item)) { return true; } } return false; } [MemberNotNull("__teleportableItems")] private void UpdateTeleportableItems() { Dictionary dictionary = __teleportableItems as Dictionary; dictionary?.Clear(); if (Config.NonTeleportableItems.Enable.Value) { foreach (ModConfigBase.NonTeleportableItemsConfig.Entry entry in Config.NonTeleportableItems.Entries) { if (!string.IsNullOrEmpty(entry.Config.Value) && ZoneSystem.instance.GetGlobalKey(entry.Config.Value)) { (dictionary ?? (dictionary = new Dictionary(SharedItemDataKeyComparer.Instance))).Add(entry.ItemDrop.m_itemData, ((Component)entry.ItemDrop).gameObject); } } if (__teleportableItems == null) { ZoneSystemSendGlobalKeys.GlobalKeysChanged += UpdateTeleportableItems; } } IReadOnlyDictionary readOnlyDictionary = dictionary; __teleportableItems = readOnlyDictionary ?? ReadOnlyDictionary.Empty; } private static bool HandleRoutedRPCPrefix(RoutedRPCData data) { //IL_00d2: 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) if (__methods.TryGetValue(data.m_methodHash, out RpcMethod value)) { ExtendedZDO extendedZDO = null; for (int j = 0; j < value.Delegates.Count; j++) { RpcDelegate rpcDelegate = value.Delegates[j]; try { __args.Clear(); ZRpc.Deserialize(rpcDelegate.Parameters, data.m_parameters, ref __args); data.m_parameters.SetPos(0); if (rpcDelegate.DataParameterIndex < rpcDelegate.ZdoParameterIndex) { if (rpcDelegate.DataParameterIndex > -1) { __args.Insert(rpcDelegate.DataParameterIndex, data); } if (rpcDelegate.ZdoParameterIndex > -1) { __args.Insert(rpcDelegate.ZdoParameterIndex, extendedZDO ?? (extendedZDO = ZDOMan.instance.GetExtendedZDO(data.m_targetZDO))); } } else { if (rpcDelegate.ZdoParameterIndex > -1) { __args.Insert(rpcDelegate.ZdoParameterIndex, extendedZDO ?? (extendedZDO = ZDOMan.instance.GetExtendedZDO(data.m_targetZDO))); } if (rpcDelegate.DataParameterIndex > -1) { __args.Insert(rpcDelegate.DataParameterIndex, data); } } if (!__argArrays.TryGetValue(__args.Count, out object[] value2)) { __argArrays.Add(__args.Count, value2 = __args.ToArray()); } else { __args.CopyTo(value2); } __loopCounter++; _ = __loopCounter; _ = 1; object obj = rpcDelegate.Delegate.DynamicInvoke(value2); __loopCounter--; if (obj is bool && !(bool)obj) { return false; } } catch (Exception ex) { Main.Instance.Logger.LogError($"{value.Name}: {rpcDelegate.Delegate.Method.DeclaringType.Name}.{rpcDelegate.Delegate.Method.Name}: {ex}"); Main.Instance.Logger.LogError("Arguments: " + string.Join(", ", __args.Select((object x, int i) => $"{i}: {x?.GetType().Name}"))); value.Delegates.RemoveAt(j--); if (value.Delegates.Count == 0 && __methods.Remove(data.m_methodHash) && __methods.Count == 0) { Main.HarmonyInstance.Unpatch((MethodBase)__handleRoutedRPCMethod, __handleRoutedRPCPrefix); } } } } return true; } protected static void UpdateRpcSubscription(string methodName, Delegate handler, bool subscribe) { //IL_00e9: Unknown result type (might be due to invalid IL or missing references) //IL_00f7: Expected O, but got Unknown Delegate handler2 = handler; int stableHashCode = StringExtensionMethods.GetStableHashCode(methodName, true); if (!__methods.TryGetValue(stableHashCode, out RpcMethod value) && subscribe) { __methods.Add(stableHashCode, value = new RpcMethod(methodName, new List())); } if (subscribe) { if (!value.Delegates.Any((RpcDelegate x) => x.Delegate == handler2)) { value.Delegates.Add(new RpcDelegate(handler2)); } } else if ((object)value != null) { int num = value.Delegates.FindIndex((RpcDelegate x) => x.Delegate == handler2); if (num > -1) { value.Delegates.RemoveAt(num); if (value.Delegates.Count == 0) { __methods.Remove(stableHashCode); } } } Main.HarmonyInstance.Unpatch((MethodBase)__handleRoutedRPCMethod, __handleRoutedRPCPrefix); if (__methods.Count > 0) { Main.HarmonyInstance.Patch((MethodBase)__handleRoutedRPCMethod, new HarmonyMethod(__handleRoutedRPCPrefix), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } } protected static void ShowMessage(IEnumerable peers, Vector3 pos, string message, MessageTypes type, TextType inWorldTextType = 0) { //IL_0007: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_007d: 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_00a4: 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) switch (type) { default: return; case MessageTypes.TopLeftNear: case MessageTypes.CenterNear: case MessageTypes.InWorld: peers = peers.Where((Peer x) => Vector3.Distance(x.m_refPos, pos) <= DamageText.instance.m_maxTextDistance); break; case MessageTypes.TopLeftFar: case MessageTypes.CenterFar: peers = peers.Where((Peer x) => Vector3.Distance(x.m_refPos, pos) <= Main.Instance.Config.General.FarMessageRange.Value); break; } bool flag; switch (type) { case MessageTypes.InWorld: RPC.ShowInWorldText(peers.Select((Peer x) => x.m_uid), inWorldTextType, pos, StringExtensionMethods.RemoveRichTextTags(message)); return; case MessageTypes.TopLeftNear: case MessageTypes.TopLeftFar: flag = true; break; default: flag = false; break; } MessageType type2 = (MessageType)(flag ? 1 : 2); foreach (Peer peer in peers) { RPC.ShowMessage(peer.m_uid, type2, message); } } protected static void ShowMessage(IEnumerable peers, ExtendedZDO zdo, string message, MessageTypes type, TextType inWorldTextType = 0) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) //IL_0009: Unknown result type (might be due to invalid IL or missing references) ShowMessage(peers, ((ZDO)zdo).GetPosition(), message, type, inWorldTextType); } [Conditional("DEBUG")] protected static void DevShowMessage(ZDO zdo, string message, TextType type = 0, [CallerFilePath] string callerFile = null, [CallerLineNumber] int callerLineNo = 0) { } } internal readonly record struct ItemDataKey(string Name, int Quality, int Variant) { public ItemDataKey(string Name, int Quality, int Variant) { this.Name = Name; this.Quality = Quality; this.Variant = Variant; } public static implicit operator ItemDataKey(ItemData data) { return new ItemDataKey(data); } public ItemDataKey(ItemData data) : this(data.m_shared.m_name, data.m_quality, data.m_variant) { } } internal readonly record struct SharedItemDataKey(string Name) { public static implicit operator SharedItemDataKey(SharedData data) { return new SharedItemDataKey(data.m_name); } public static implicit operator SharedItemDataKey(ItemData data) { return new SharedItemDataKey(data.m_shared.m_name); } } internal sealed class ItemDataKeyComparer : EqualityComparer { public static ItemDataKeyComparer Instance { get; } = new ItemDataKeyComparer(); public override bool Equals(ItemData x, ItemData y) { return new ItemDataKey(x) == y; } public override int GetHashCode(ItemData obj) { return new ItemDataKey(obj).GetHashCode(); } } internal sealed class SharedItemDataKeyComparer : EqualityComparer { public static SharedItemDataKeyComparer Instance { get; } = new SharedItemDataKeyComparer(); public override bool Equals(ItemData x, ItemData y) { return (SharedItemDataKey)x == (SharedItemDataKey)y; } public override int GetHashCode(ItemData obj) { return ((SharedItemDataKey)obj).GetHashCode(); } } internal static class SharedProcessorState { private sealed record PieceTableInfo(HashSet PieceTables, Dictionary PieceTablesByName); private static PieceTableInfo? __pieceTables; private static readonly Dictionary __prefabInfo = new Dictionary(); private static readonly IReadOnlyList __componentTypes; private static readonly IReadOnlyList> __componentTypeCombinations; private static IReadOnlyDictionary? __characterByTrophy; private static IReadOnlyDictionary? __bossesByBiome; private static readonly List<(Vector2s ZoneId, GameObject Root)> _zoneRoots; private static DateTimeOffset __nextCleanup; public static IReadOnlyCollection PieceTables => (__pieceTables ?? (__pieceTables = GetPieceTableInfo())).PieceTables; public static IReadOnlyDictionary PieceTablesByPiece => (__pieceTables ?? (__pieceTables = GetPieceTableInfo())).PieceTablesByName; public static IReadOnlyDictionary CharacterByTrophy => __characterByTrophy ?? (__characterByTrophy = ((Func>)delegate { Dictionary dictionary = new Dictionary(); foreach (GameObject prefab2 in ZNetScene.instance.m_prefabs) { Character component = prefab2.GetComponent(); if (component != null && !component.m_boss) { CharacterDrop component2 = prefab2.GetComponent(); if (component2 != null) { ItemDrop val = component2.m_drops.Select(delegate(Drop x) { GameObject prefab = x.m_prefab; return (prefab == null) ? null : prefab.GetComponent(); }).FirstOrDefault((Func)delegate(ItemDrop x) { //IL_0018: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Invalid comparison between Unknown and I4 if (x != null) { ItemData itemData = x.m_itemData; if (itemData != null) { SharedData shared = itemData.m_shared; if (shared != null) { return (int)shared.m_itemType == 13; } } } return false; }); if (val != null) { if (!dictionary.TryGetValue(((Object)val).name, out var value)) { dictionary.Add(((Object)val).name, component); } else if (((Object)val).name.Contains(((Object)prefab2).name) || ((Object)prefab2).name.Length < ((Object)value).name.Length) { dictionary[((Object)val).name] = component; } } } } } return dictionary; })()); public static IReadOnlyDictionary BossesByBiome => __bossesByBiome ?? (__bossesByBiome = ((Func>)delegate { //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_006e: 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_0072: Unknown result type (might be due to invalid IL or missing references) //IL_0079: Invalid comparison between Unknown and I4 //IL_007b: Unknown result type (might be due to invalid IL or missing references) //IL_0082: Invalid comparison between Unknown and I4 //IL_00b1: Unknown result type (might be due to invalid IL or missing references) //IL_018c: Unknown result type (might be due to invalid IL or missing references) //IL_014d: Unknown result type (might be due to invalid IL or missing references) //IL_0152: Unknown result type (might be due to invalid IL or missing references) //IL_0156: Unknown result type (might be due to invalid IL or missing references) Dictionary dictionary = new Dictionary(); foreach (bool item in (IEnumerable)new <>z__ReadOnlyArray(new bool[2] { false, true })) { foreach (ZoneLocation location in ZoneSystem.instance.m_locations) { bool flag = !location.m_enable || !location.m_prioritized; bool flag2 = flag; if (!flag2) { Biome biome = location.m_biome; bool flag3 = (((int)biome == 0 || (int)biome == 256 || (int)biome == 895) ? true : false); flag2 = flag3; } if (!flag2 && !dictionary.ContainsKey(location.m_biome)) { try { location.m_prefab.Load(); } catch (Exception arg) { Main.Instance.Logger.LogWarning($"Loading location asset {location.m_prefabName} failed: {arg}"); continue; } GameObject asset = location.m_prefab.Asset; if (asset == null) { Main.Instance.Logger.LogWarning("Loading location asset " + location.m_prefabName + " failed"); } else { OfferingBowl componentInChildren = asset.GetComponentInChildren(); if (item && componentInChildren == null) { DungeonGenerator componentInChildren2 = asset.GetComponentInChildren(); if (componentInChildren2 != null) { SoftReference[] availableRoomPrefabs = componentInChildren2.GetAvailableRoomPrefabs(); for (int i = 0; i < availableRoomPrefabs.Length; i++) { SoftReference val = availableRoomPrefabs[i]; val.Load(); Room component = val.Asset.GetComponent(); componentInChildren = ((Component)component).GetComponentInChildren(); if (componentInChildren != null) { break; } } } } if (componentInChildren != null) { dictionary.Add(location.m_biome, componentInChildren.m_bossPrefab.GetComponent()); } } } } } return dictionary; })()); private static PieceTableInfo GetPieceTableInfo() { PieceTableInfo pieceTableInfo = new PieceTableInfo(new HashSet(), new Dictionary()); foreach (GameObject prefab in ZNetScene.instance.m_prefabs) { PieceTable val = prefab.GetComponent()?.m_itemData.m_shared.m_buildPieces; if (val == null || !pieceTableInfo.PieceTables.Add(val)) { continue; } foreach (GameObject piece in val.m_pieces) { if (!pieceTableInfo.PieceTablesByName.ContainsKey(((Object)piece).name)) { pieceTableInfo.PieceTablesByName.Add(((Object)piece).name, val); } } } return pieceTableInfo; } public static PrefabInfo? GetPrefabInfo(int hash) { if (!__prefabInfo.TryGetValue(hash, out PrefabInfo value)) { GameObject prefab2 = ZNetScene.instance.GetPrefab(hash); if (prefab2 == null) { return null; } value = Get(hash, prefab2); __prefabInfo.Add(hash, value); } return value; static PrefabInfo? Get(int hash, GameObject prefab) { GameObject prefab3 = prefab; ZNetView component = prefab3.GetComponent(); MonoBehaviour[] availableComponents2 = ((component != null) ? ((Component)component).gameObject.GetComponentsInChildren() : null); if (availableComponents2 == null) { return null; } Dictionary components = null; foreach (Type _componentType in __componentTypes) { MonoBehaviour component2 = GetComponent(prefab3, _componentType, availableComponents2); if (component2 != null) { (components ?? (components = new Dictionary())).Add(_componentType, component2); } } foreach (IReadOnlyList<(Type, bool)> _componentTypeCombination in __componentTypeCombinations) { List<(Type, bool, MonoBehaviour)> list = _componentTypeCombination.Select<(Type, bool), (Type, bool, MonoBehaviour)>(delegate((Type Type, bool Optional) x) { Type item = x.Type; bool item2 = x.Optional; Dictionary dictionary = components; MonoBehaviour value3; return (item, item2, (MonoBehaviour)((dictionary != null && dictionary.TryGetValue(x.Type, out value3)) ? ((object)value3) : ((object)GetComponent(prefab3, x.Type, availableComponents2)))); }).ToList(); if (list.Count > 0 && !list.Any<(Type, bool, MonoBehaviour)>(((Type Type, bool Optional, MonoBehaviour Component) x) => x.Component == null && !x.Optional)) { if (components == null) { components = new Dictionary(); } foreach (var (key, _, val) in list) { if (val != null && !components.ContainsKey(key)) { components.Add(key, val); } } } } GameObject prefab4 = prefab3; IReadOnlyDictionary readOnlyDictionary = components; return new PrefabInfo(prefab4, readOnlyDictionary ?? ReadOnlyDictionary.Empty); } static MonoBehaviour? GetComponent(GameObject prefab, Type componentType, IReadOnlyList availableComponents) { Type componentType2 = componentType; if (componentType2 == typeof(PieceTable)) { if (!PieceTablesByPiece.TryGetValue(((Object)prefab).name, out PieceTable value2)) { return null; } return (MonoBehaviour?)(object)value2; } return ((IEnumerable)availableComponents).FirstOrDefault((Func)((MonoBehaviour x) => ((object)x).GetType() == componentType2)); } } public static Heightmap CreateHeightmap(Vector2s zoneId) { //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) //IL_0006: 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_0012: 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) Vector3 zonePos = ZoneSystem.GetZonePos(zoneId); GameObject val = Object.Instantiate(ZoneSystem.instance.m_zonePrefab, zonePos, Quaternion.identity); _zoneRoots.Add((zoneId, val)); return val.GetComponentInChildren(); } public static Heightmap CreateHeightmap(Vector3 refPos) { //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) return CreateHeightmap(ZoneSystem.GetZone(refPos)); } public static void CleanUp(IEnumerable peers) { //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) if (__nextCleanup > DateTimeOffset.UtcNow) { return; } for (int num = _zoneRoots.Count - 1; num >= 0; num--) { var (zone, val) = _zoneRoots[num]; if (!peers.Any((Peer x) => ZNetScene.InActiveArea(zone, x.m_refPos))) { _zoneRoots.RemoveAt(num); Object.Destroy((Object)(object)val); } } __nextCleanup = DateTimeOffset.UtcNow.AddSeconds(2.0); } static SharedProcessorState() { List list = new List(); list.AddRange(from x in typeof(PrefabInfo).GetProperties() select x.PropertyType into x where typeof(MonoBehaviour).IsAssignableFrom(x) select x); __componentTypes = new <>z__ReadOnlyList(list); List> list2 = new List>(); list2.AddRange(from x in (from x in typeof(PrefabInfo).GetProperties() select x.PropertyType into x where x.IsConstructedGenericType && x.GetGenericTypeDefinition() == typeof(Nullable<>) && x.GenericTypeArguments[0].IsConstructedGenericType select x.GenericTypeArguments[0] into x where x.IsConstructedGenericType && typeof(ITuple).IsAssignableFrom(x) select x).Select(delegate(Type x) { List<(Type, bool)> list3 = new List<(Type, bool)>(x.GenericTypeArguments.Length); Type[] genericTypeArguments = x.GenericTypeArguments; foreach (Type type in genericTypeArguments) { if (typeof(MonoBehaviour).IsAssignableFrom(type)) { list3.Add((type, false)); } else { if (!type.IsConstructedGenericType || !(type.GetGenericTypeDefinition() == typeof(PrefabInfo.Optional<>))) { list3 = null; break; } list3.Add((type.GenericTypeArguments[0], true)); } } return list3; }) where x != null select x); __componentTypeCombinations = new <>z__ReadOnlyList>(list2); _zoneRoots = new List<(Vector2s, GameObject)>(); } } internal sealed class ShieldGeneratorProcessor : Processor { public readonly record struct ShieldGeneratorInfo(ExtendedZDO ShieldGenerator, bool HasFuel); public delegate void ShieldGeneratorChangedHandler(ExtendedZDO shieldGenerator, bool hasFuel); private readonly Dictionary _shieldGenerators = new Dictionary(); private IReadOnlyList? _info; protected override Guid Id { get; } = Guid.Parse("0ccc72d2-cddb-4007-a206-61cea0308af3"); public IReadOnlyList ShieldGenerators { get { IReadOnlyList? readOnlyList = _info; if (readOnlyList == null) { List list = new List(); list.AddRange(_shieldGenerators.Select, ShieldGeneratorInfo>((KeyValuePair x) => new ShieldGeneratorInfo(x.Key, x.Value))); readOnlyList = (_info = new <>z__ReadOnlyList(list)); } return readOnlyList; } } public event ShieldGeneratorChangedHandler? ShieldGeneratorChanged; public override void Initialize(bool firstTime) { base.Initialize(firstTime); if (firstTime) { _shieldGenerators.Clear(); _info = null; } } private void OnShieldGeneratorDestroyed(ExtendedZDO zdo) { if (_shieldGenerators.Remove(zdo)) { _info = null; } } protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { if (zdo.PrefabInfo.ShieldGenerator == null) { base.UnregisterZdoProcessor = true; return false; } bool flag = zdo.Vars.GetFuel() > 0f; if (!_shieldGenerators.TryGetValue(zdo, out var value) || flag != value) { if (!_shieldGenerators.ContainsKey(zdo)) { zdo.Destroyed += OnShieldGeneratorDestroyed; } _shieldGenerators[zdo] = flag; _info = null; this.ShieldGeneratorChanged?.Invoke(zdo, flag); } return true; } } internal sealed class ShipProcessor : Processor { private readonly HashSet _ships = new HashSet(); protected override Guid Id { get; } = Guid.Parse("822bb8e2-75a4-4519-b144-0b4f927ae6c2"); public IReadOnlyCollection Ships => _ships; public override void Initialize(bool firstTime) { base.Initialize(firstTime); if (!firstTime) { return; } _ships.Clear(); foreach (ExtendedZDO @object in ZDOMan.instance.GetObjects()) { if (@object.PrefabInfo.Ship.HasValue) { _ships.Add(@object); @object.Destroyed += OnShipDestroyed; } } } private void OnShipDestroyed(ExtendedZDO zdo) { _ships.Remove(zdo); } protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { base.UnregisterZdoProcessor = true; if (!zdo.PrefabInfo.Ship.HasValue) { return false; } _ships.Add(zdo); zdo.Destroyed += OnShipDestroyed; if (zdo.Fields(getUnknownComponent: false).UpdateValue(() => (Piece x) => x.m_canBeRemoved, base.Config.Ships.DeconstructWithHammer.Value, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\ShipProcessor.cs", 38)) { base.RecreateZdo = true; } return false; } } internal sealed class SignProcessor : Processor { internal const string MagnetEmoji = "\ud83e\uddf2"; private readonly Regex _chestPickupRangeRegex = new Regex(Regex.Escape("\ud83e\uddf2") + "\\s*(?\\d+)"); internal const string LeftRightArrowEmoji = "↔\ufe0f"; private readonly Regex _chestFeedRangeRegex = new Regex(Regex.Escape("↔\ufe0f") + "\\s*(?\\d+)"); internal const string LinkEmoji = "\ud83d\udd17"; private readonly Regex _incineratorTagRegex = new Regex(Regex.Escape("\ud83d\udd17") + "\\s*(?\\w*)"); private readonly Regex _clockRegex = new Regex("(?:" + string.Join("|", ClockEmojis.Select(Regex.Escape)) + ")(?:\\s*\\d\\d\\:\\d\\d)?"); private readonly Regex _defaultColorRegex = new Regex("]+ d>"); private string _defaultColor = ""; private const string ContentListStart = ""; private const string ContentListEnd = ""; private readonly Regex _contentListRegex = new Regex(".*?"); private Regex _contentListRegex2; private string? _timeText; private readonly Dictionary _chestDataRevisions = new Dictionary(); protected override Guid Id { get; } = Guid.Parse("806bdb85-c857-4154-a246-a0b1d0917987"); internal static IReadOnlyList ClockEmojis { get; } = new <>z__ReadOnlyArray(new string[24] { "\ud83d\udd5b", "\ud83d\udd67", "\ud83d\udd50", "\ud83d\udd5c", "\ud83d\udd51", "\ud83d\udd5d", "\ud83d\udd52", "\ud83d\udd5e", "\ud83d\udd53", "\ud83d\udd5f", "\ud83d\udd54", "\ud83d\udd60", "\ud83d\udd55", "\ud83d\udd61", "\ud83d\udd56", "\ud83d\udd62", "\ud83d\udd57", "\ud83d\udd63", "\ud83d\udd58", "\ud83d\udd64", "\ud83d\udd59", "\ud83d\udd65", "\ud83d\udd5a", "\ud83d\udd66" }); public override void Initialize(bool firstTime) { base.Initialize(firstTime); _contentListRegex2 = new Regex(Regex.Escape(base.Config.Containers.ChestSignsContentListPlaceholder.Value)); _defaultColor = (base.Config.Signs.DefaultColor.Value.StartsWith('#') ? base.Config.Signs.DefaultColor.Value : (string.IsNullOrEmpty(base.Config.Signs.DefaultColor.Value) ? "" : ("\"" + base.Config.Signs.DefaultColor.Value + "\""))); if (firstTime) { _chestDataRevisions.Clear(); Processor.Instance().ContainerChanged -= OnContainerChanged; Processor.Instance().ContainerChanged += OnContainerChanged; } } private void OnContainerChanged(ExtendedZDO zdo) { if (!Processor.Instance().SignsByChests.TryGetValue(zdo, out List value)) { return; } uint dataRevision = ((ZDO)zdo).DataRevision; if (!_chestDataRevisions.TryGetValue(zdo, out var value2)) { _chestDataRevisions.Add(zdo, dataRevision); zdo.Destroyed += delegate(ExtendedZDO x) { _chestDataRevisions.Remove(x); }; } else { if (value2 == dataRevision) { return; } _chestDataRevisions[zdo] = dataRevision; } string text = zdo.Vars.GetText(); foreach (ExtendedZDO item in value) { item.Vars.SetText(text, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\SignProcessor.cs", 69); item.ResetProcessorDataRevision(this); } } protected override void PreProcessCore(IEnumerable peers) { _timeText = null; } public override bool ClaimExclusive(ExtendedZDO zdo) { if (!base.ClaimExclusive(zdo)) { return Processor.Instance().ChestsBySigns.ContainsKey(zdo); } return true; } protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { if (zdo.PrefabInfo.Sign == null) { base.UnregisterZdoProcessor = true; return false; } bool isTimeSign = false; string text = zdo.Vars.GetText(); if (base.Config.Signs.TimeSigns.Value) { string text2 = _clockRegex.Replace(text, delegate { isTimeSign = true; if (_timeText == null) { float dayFraction = EnvMan.instance.GetDayFraction(); int index = (int)Math.Floor((float)(ClockEmojis.Count * 2) * dayFraction) % ClockEmojis.Count; TimeSpan timeSpan = TimeSpan.FromDays(dayFraction); _timeText = $"{ClockEmojis[index]} {timeSpan:hh\\:mm}"; } return _timeText; }); if (text2 != text) { zdo.Vars.SetText(text = text2, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\SignProcessor.cs", 108); } } bool found2 = false; string text3 = _defaultColorRegex.Replace(text, delegate { found2 = true; return ""; }, 1); if (!found2 && !string.IsNullOrEmpty(_defaultColor)) { text3 = "" + text; } if (text3 != text) { zdo.Vars.SetText(text = text3, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\SignProcessor.cs", 125); } bool found; if (Processor.Instance().ChestsBySigns.TryGetValue(zdo, out ExtendedZDO chest)) { string input = text; if (base.Config.Containers.AutoPickup.Value) { chest.Inventory.PickupRange = null; input = _chestPickupRangeRegex.Replace(input, delegate(Match match) { string result2 = match.Value; int num3 = int.Parse(match.Groups["R"].Value); if (num3 > base.Config.Containers.AutoPickupMaxRange.Value) { num3 = base.Config.Containers.AutoPickupMaxRange.Value; result2 = FormattableString.Invariant(FormattableStringFactory.Create("{0}{1}", "\ud83e\uddf2", num3)); } chest.Inventory.PickupRange = num3; return result2; }); } if (base.Config.Smelters.FeedFromContainers.Value) { chest.Inventory.FeedRange = null; input = _chestFeedRangeRegex.Replace(input, delegate(Match match) { string result = match.Value; int num2 = int.Parse(match.Groups["R"].Value); if (num2 > base.Config.Smelters.FeedFromContainersMaxRange.Value) { num2 = base.Config.Smelters.FeedFromContainersMaxRange.Value; result = FormattableString.Invariant(FormattableStringFactory.Create("{0}{1}", "↔\ufe0f", num2)); } chest.Inventory.FeedRange = num2; return result; }); } int num = 0; if (base.Config.Containers.ObliteratorItemTeleporter.Value != 0) { (Container, PrefabInfo.Optional, PrefabInfo.Optional, PrefabInfo.Optional, PrefabInfo.Optional)? container = chest.PrefabInfo.Container; if (container.HasValue) { PrefabInfo.Optional item = container.GetValueOrDefault().Item4; if (item.Value != null) { Match match2 = _incineratorTagRegex.Match(input); if (match2 != null && match2.Success) { num = StringExtensionMethods.GetStableHashCode(match2.Groups["T"].Value, true); } } } } found = false; input = _contentListRegex.Replace(input, EvaluateMatch, 1); if (!found) { input = _contentListRegex2.Replace(input, EvaluateMatch, 1); } if (input != text) { zdo.Vars.SetText(text = input, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\SignProcessor.cs", 203); } if (text != chest.Vars.GetText() || num != chest.Vars.GetIntTag()) { if (!chest.IsOwnerOrUnassigned()) { Processor.Instance().RequestOwnership(chest, 0L, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\SignProcessor.cs", 209); return false; } chest.Vars.SetText(text, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\SignProcessor.cs", 213); if (num == 0) { chest.Vars.RemoveIntTag("D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\SignProcessor.cs", 215); } else { chest.Vars.SetIntTag(num, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\SignProcessor.cs", 217); } } } if (isTimeSign) { return false; } return true; string EvaluateMatch(Match match) { found = true; if (base.Config.Containers.ChestSignsContentListMaxCount.Value <= 0 || chest.InventoryReadOnly.Items.Count == 0) { return base.Config.Containers.ChestSignsContentListPlaceholder.Value; } List<(string, int)> list = (from x in chest.InventoryReadOnly.Items.GroupBy((ItemData x) => ((Object)x.m_dropPrefab).name, (string k, IEnumerable g) => (base.Config.Containers.ItemNames[k], g.Sum((ItemData x) => x.m_stack))) orderby x.Count descending select x).ToList(); IEnumerable<(string, int)> source = list.AsBoxedEnumerable(); if (list.Count > base.Config.Containers.ChestSignsContentListMaxCount.Value) { source = list.Take(base.Config.Containers.ChestSignsContentListMaxCount.Value - 1).Append((base.Config.Containers.ChestSignsContentListNameRest.Value, list.Skip(base.Config.Containers.ChestSignsContentListMaxCount.Value - 1).Sum<(string, int)>(((string Name, int Count) x) => x.Count))); } string text4 = string.Join(base.Config.Containers.ChestSignsContentListSeparator.Value, source.Select<(string, int), string>(((string Name, int Count) x) => string.Format(base.Config.Containers.ChestSignsContentListEntryFormat.Value, x.Name, x.Count))); return "" + text4 + ""; } } } internal sealed class SmelterProcessor : Processor { private readonly List _smelters = new List(); protected override Guid Id { get; } = Guid.Parse("fb9d92e2-c7bb-4d9d-9cae-6b23828da3ef"); public override void Initialize(bool firstTime) { base.Initialize(firstTime); if (firstTime) { _smelters.Clear(); Processor.Instance().ContainerChanged -= OnContainerChanged; Processor.Instance().ContainerChanged += OnContainerChanged; } } private void OnContainerChanged(ExtendedZDO containerZdo) { //IL_006c: 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) if (containerZdo.Inventory.Items.Count == 0) { return; } float num = ((float?)containerZdo.Inventory.FeedRange) ?? base.Config.Smelters.FeedFromContainersRange.Value; num *= num; if (num == 0f) { return; } foreach (ExtendedZDO smelter in _smelters) { if (Utils.DistanceSqr(((ZDO)smelter).GetPosition(), ((ZDO)containerZdo).GetPosition()) <= num) { smelter.ResetProcessorDataRevision(this); } } } protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { //IL_0a63: Unknown result type (might be due to invalid IL or missing references) //IL_0a6a: Unknown result type (might be due to invalid IL or missing references) //IL_0574: Unknown result type (might be due to invalid IL or missing references) //IL_057b: Unknown result type (might be due to invalid IL or missing references) PrefabInfo prefabInfo = zdo.PrefabInfo; if ((object)prefabInfo == null) { goto IL_001e; } Smelter smelter = prefabInfo.Smelter; if (smelter == null) { ShieldGenerator shieldGenerator = prefabInfo.ShieldGenerator; if (shieldGenerator == null) { goto IL_001e; } } bool flag = false; goto IL_0024; IL_001e: flag = true; goto IL_0024; IL_0024: if (flag) { base.UnregisterZdoProcessor = true; return false; } if (base.Config.Smelters.CapacityMultiplier.Value == 1f) { if (zdo.PrefabInfo.Smelter != null) { zdo.Fields(getUnknownComponent: false).Reset(() => (Smelter x) => x.m_maxFuel, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\SmelterProcessor.cs", 52).Reset(() => (Smelter x) => x.m_maxOre, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\SmelterProcessor.cs", 53); } else { zdo.Fields(getUnknownComponent: false).Reset(() => (ShieldGenerator x) => x.m_maxFuel, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\SmelterProcessor.cs", 56); } } else if (zdo.PrefabInfo.Smelter == null) { base.RecreateZdo = zdo.Fields(getUnknownComponent: false).UpdateValue(() => (ShieldGenerator x) => x.m_maxFuel, Mathf.RoundToInt(base.Config.Smelters.CapacityMultiplier.Value * (float)zdo.PrefabInfo.ShieldGenerator.m_maxFuel), "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\SmelterProcessor.cs", 61); } else { if (zdo.Fields(getUnknownComponent: false).UpdateValue(() => (Smelter x) => x.m_maxFuel, Mathf.RoundToInt(base.Config.Smelters.CapacityMultiplier.Value * (float)zdo.PrefabInfo.Smelter.m_maxFuel), "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\SmelterProcessor.cs", 64)) { base.RecreateZdo = true; } if (zdo.Fields(getUnknownComponent: false).UpdateValue(() => (Smelter x) => x.m_maxOre, Mathf.RoundToInt(base.Config.Smelters.CapacityMultiplier.Value * (float)zdo.PrefabInfo.Smelter.m_maxOre), "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\SmelterProcessor.cs", 66)) { base.RecreateZdo = true; } } if (zdo.PrefabInfo.Smelter?.m_conversion.Any((ItemConversion x) => x.m_to != null) ?? false) { if (base.Config.Smelters.TimePerProductMultiplier.Value == 1f) { zdo.Fields(getUnknownComponent: false).Reset(() => (Smelter x) => x.m_secPerProduct, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\SmelterProcessor.cs", 74); } else if (zdo.Fields(getUnknownComponent: false).UpdateValue(() => (Smelter x) => x.m_secPerProduct, Mathf.Max(1f, zdo.PrefabInfo.Smelter.m_secPerProduct * base.Config.Smelters.TimePerProductMultiplier.Value), "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\SmelterProcessor.cs", 75)) { base.RecreateZdo = true; } } if (!base.Config.Smelters.FeedFromContainers.Value) { base.UnregisterZdoProcessor = true; return false; } if (!CheckMinDistance(peers, (ZDO)(object)zdo)) { return false; } int num = ((zdo.PrefabInfo.Smelter != null) ? zdo.Fields(getUnknownComponent: false).GetInt(() => (Smelter x) => x.m_maxFuel, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\SmelterProcessor.cs", 91) : zdo.Fields(getUnknownComponent: false).GetInt(() => (ShieldGenerator x) => x.m_maxFuel, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\SmelterProcessor.cs", 92)); float num2 = zdo.Vars.GetFuel(); int num3 = (int)((float)num - num2); ConcurrentHashSet value2; if (num3 > num / 2) { foreach (ItemData fuelItem in zdo.PrefabInfo.ShieldGenerator?.m_fuelItems.Select((ItemDrop x) => x.m_itemData) ?? new <>z__ReadOnlySingleElementList(zdo.PrefabInfo.Smelter.m_fuelItem.m_itemData)) { int num4 = 0; if (Processor.Instance().ContainersByItemName.TryGetValue(fuelItem.m_shared, out ConcurrentHashSet value)) { List list = null; foreach (ExtendedZDO item in (IEnumerable)value) { if (!((ZDO)item).IsValid() || !item.PrefabInfo.Container.HasValue) { value.Remove(item); } else { if (item.Vars.GetInUse()) { continue; } float num5 = ((float?)item.Inventory.FeedRange) ?? base.Config.Smelters.FeedFromContainersRange.Value; num5 *= num5; if (num5 == 0f || Utils.DistanceSqr(((ZDO)zdo).GetPosition(), ((ZDO)item).GetPosition()) > num5) { continue; } list?.Clear(); int num6 = 0; int num7 = base.Config.Smelters.FeedFromContainersLeaveAtLeastFuel.Value; bool flag2 = false; bool flag3 = false; foreach (ItemData item2 in from x in item.Inventory.Items where new ItemDataKey(x) == fuelItem orderby x.m_stack select x) { flag2 = flag2 || (item2 != null && item2.m_stack > 0); int num8 = Math.Min(num3, item2.m_stack); int num9 = Math.Min(num8, num7); num7 -= num9; num8 -= num9; if (num8 != 0) { if (!item.IsOwnerOrUnassigned()) { flag3 = true; break; } num6 += num8; item2.m_stack -= num8; if (item2.m_stack == 0) { (list ?? (list = new List())).Add(item2); } num3 -= num8; if (num3 == 0) { break; } } } if (flag3) { Processor.Instance().RequestOwnership(item, 0L, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\SmelterProcessor.cs", 151); continue; } if (num6 == 0) { if (!flag2) { value.Remove(item); if (value != null && value.Count == 0) { Processor.Instance().ContainersByItemName.TryRemove(fuelItem.m_shared, out value2); } } continue; } if (list != null && list.Count > 0) { foreach (ItemData item3 in list) { item.Inventory.Items.Remove(item3); } IList items = item.Inventory.Items; if (items != null && items.Count == 0) { value.Remove(item); if (value != null && value.Count == 0) { Processor.Instance().ContainersByItemName.TryRemove(fuelItem.m_shared, out value2); } } } zdo.ReleaseOwnership(); num2 += (float)num6; zdo.Vars.SetFuel(num2, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\SmelterProcessor.cs", 181); item.Inventory.Save(); num4 += num6; if (num3 == 0) { break; } } } if (num3 == 0) { break; } } if (num4 != 0) { Processor.ShowMessage(peers, zdo, base.Config.Localization.Smelters.FormatFuelAdded(zdo.PrefabInfo.Smelter?.m_name ?? zdo.PrefabInfo.ShieldGenerator.m_name, fuelItem.m_shared.m_name, num4), base.Config.Smelters.OreOrFuelAddedMessageType.Value, (TextType)0); } } } if (zdo.PrefabInfo.Smelter != null) { int @int = zdo.Fields(getUnknownComponent: false).GetInt(() => (Smelter x) => x.m_maxOre, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\SmelterProcessor.cs", 205); int num10 = zdo.Vars.GetQueued(); int num11 = @int - num10; if (num11 > @int / 2) { foreach (ItemConversion item4 in zdo.PrefabInfo.Smelter.m_conversion) { ItemData oreItem = item4.m_from.m_itemData; int num12 = 0; if (Processor.Instance().ContainersByItemName.TryGetValue(oreItem.m_shared, out ConcurrentHashSet value3)) { List list2 = null; foreach (ExtendedZDO item5 in (IEnumerable)value3) { if (!((ZDO)item5).IsValid() || !item5.PrefabInfo.Container.HasValue) { value3.Remove(item5); } else { if (item5.Vars.GetInUse()) { continue; } float num13 = ((float?)item5.Inventory.FeedRange) ?? base.Config.Smelters.FeedFromContainersRange.Value; num13 *= num13; if (num13 == 0f || Utils.DistanceSqr(((ZDO)zdo).GetPosition(), ((ZDO)item5).GetPosition()) > num13) { continue; } list2?.Clear(); int num14 = 0; int num15 = base.Config.Smelters.FeedFromContainersLeaveAtLeastOre.Value; bool flag4 = false; bool flag5 = false; foreach (ItemData item6 in from x in item5.Inventory.Items where new ItemDataKey(x) == oreItem orderby x.m_stack select x) { flag4 = flag4 || (item6 != null && item6.m_stack > 0); int num16 = Math.Min(num11, item6.m_stack); int num17 = Math.Min(num16, num15); num15 -= num17; num16 -= num17; if (num16 != 0) { if (!item5.IsOwnerOrUnassigned()) { flag5 = true; break; } num14 += num16; item6.m_stack -= num16; if (item6.m_stack == 0) { (list2 ?? (list2 = new List())).Add(item6); } num11 -= num16; if (num11 == 0) { break; } } } if (flag5) { Processor.Instance().RequestOwnership(item5, 0L, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\SmelterProcessor.cs", 265); continue; } if (num14 == 0) { if (!flag4) { value3.Remove(item5); if (value3 != null && value3.Count == 0) { Processor.Instance().ContainersByItemName.TryRemove(oreItem.m_shared, out value2); } } continue; } if (list2 != null && list2.Count > 0) { foreach (ItemData item7 in list2) { item5.Inventory.Items.Remove(item7); } IList items = item5.Inventory.Items; if (items != null && items.Count == 0) { value3.Remove(item5); if (value3 != null && value3.Count == 0) { Processor.Instance().ContainersByItemName.TryRemove(oreItem.m_shared, out value2); } } } zdo.ReleaseOwnership(); for (int i = 0; i < num14; i++) { zdo.Vars.SetItem(num10 + i, ((Object)((Component)item4.m_from).gameObject).name, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\SmelterProcessor.cs", 295); } num10 += num14; zdo.Vars.SetQueued(num10, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\SmelterProcessor.cs", 297); item5.Inventory.Save(); num12 += num14; if (num11 == 0) { break; } } } } if (num12 != 0) { Processor.ShowMessage(peers, zdo, base.Config.Localization.Smelters.FormatOreAdded(zdo.PrefabInfo.Smelter.m_name, oreItem.m_shared.m_name, num12), base.Config.Smelters.OreOrFuelAddedMessageType.Value, (TextType)0); } } } } if (!_smelters.Contains(zdo)) { _smelters.Add(zdo); zdo.Destroyed += delegate(ExtendedZDO x) { _smelters.Remove(x); }; } return true; } } internal sealed class TameableProcessor : Processor { public interface ITameableState { ExtendedZDO ZDO { get; } bool IsTamed { get; } } private sealed record TameableState(ExtendedZDO ZDO) : ITameableState { public bool IsTamed { get; set; } public DateTimeOffset NextMessage { get; set; } } private readonly ConcurrentDictionary _states = new ConcurrentDictionary(); protected override Guid Id { get; } = Guid.Parse("fbc11c11-6193-4e9e-956d-615107d80682"); public IReadOnlyCollection Tames => (IReadOnlyCollection)_states.Values; public override void Initialize(bool firstTime) { base.Initialize(firstTime); if (firstTime) { _states.Clear(); } } protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { //IL_00cd: Unknown result type (might be due to invalid IL or missing references) //IL_00d2: 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_00d8: Unknown result type (might be due to invalid IL or missing references) //IL_00dc: Invalid comparison between Unknown and I4 //IL_0247: Unknown result type (might be due to invalid IL or missing references) //IL_024c: 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_0252: Unknown result type (might be due to invalid IL or missing references) //IL_0256: Invalid comparison between Unknown and I4 Tameable val = zdo.PrefabInfo.Tameable?.Tameable; if (val == null) { base.UnregisterZdoProcessor = true; return false; } ExtendedZDO.ComponentFieldAccessor componentFieldAccessor = zdo.Fields(getUnknownComponent: false); bool tamed = zdo.Vars.GetTamed(); float @float = componentFieldAccessor.GetFloat(() => (Tameable x) => x.m_tamingTime, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TameableProcessor.cs", 46); float tameTimeLeft = zdo.Vars.GetTameTimeLeft(@float); bool flag = tameTimeLeft < @float; bool flag2 = tamed || flag; bool flag3 = flag2; bool flag4; if (flag3) { (Humanoid, PrefabInfo.Optional, PrefabInfo.Optional)? humanoid = zdo.PrefabInfo.Humanoid; if (humanoid.HasValue) { var (val2, _, _) = humanoid.GetValueOrDefault(); if (val2 != null) { Faction faction = ((Character)val2).m_faction; if ((int)faction == 0 || (int)faction == 11) { flag4 = true; goto IL_00e6; } } } flag4 = false; goto IL_00e6; } goto IL_00ed; IL_0660: return true; IL_00ed: if (flag3) { if (base.Config.Tames.FedDurationMultiplier.Value == 1f) { componentFieldAccessor.Reset(() => (Tameable x) => x.m_fedDuration, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TameableProcessor.cs", 53); } else if (componentFieldAccessor.UpdateValue(() => (Tameable x) => x.m_fedDuration, val.m_fedDuration * base.Config.Tames.FedDurationMultiplier.Value, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TameableProcessor.cs", 54)) { base.RecreateZdo = true; } } if (tamed) { base.UnregisterZdoProcessor = true; if (!base.Config.Tames.MakeCommandable.Value) { componentFieldAccessor.Reset(() => (Tameable x) => x.m_commandable, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TameableProcessor.cs", 63); } else if (componentFieldAccessor.UpdateValue(() => (Tameable x) => x.m_commandable, value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TameableProcessor.cs", 64)) { base.RecreateZdo = true; } (Humanoid, PrefabInfo.Optional, PrefabInfo.Optional)? humanoid = zdo.PrefabInfo.Humanoid; if (humanoid.HasValue) { var (val2, _, _) = humanoid.GetValueOrDefault(); if (val2 != null) { Faction faction = ((Character)val2).m_faction; if ((int)faction == 0 || (int)faction == 11) { flag4 = true; goto IL_0260; } } } flag4 = false; goto IL_0260; } if (flag) { if (base.Config.Tames.TamingTimeMultiplier.Value == 1f) { componentFieldAccessor.Reset(() => (Tameable x) => x.m_tamingTime, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TameableProcessor.cs", 93); } else if (componentFieldAccessor.UpdateValue(() => (Tameable x) => x.m_tamingTime, val.m_tamingTime * base.Config.Tames.TamingTimeMultiplier.Value, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TameableProcessor.cs", 94)) { base.RecreateZdo = true; } if (base.Config.Tames.PotionTamingBoostMultiplier.Value == 1f) { componentFieldAccessor.Reset(() => (Tameable x) => x.m_tamingBoostMultiplier, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TameableProcessor.cs", 98); } else if (componentFieldAccessor.UpdateValue(() => (Tameable x) => x.m_tamingBoostMultiplier, val.m_tamingBoostMultiplier * base.Config.Tames.PotionTamingBoostMultiplier.Value, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TameableProcessor.cs", 99)) { base.RecreateZdo = true; } if (base.Config.Tames.TamingProgressMessageType.Value != 0) { if (!_states.TryGetValue(zdo, out TameableState value)) { _states.TryAdd(zdo, value = new TameableState(zdo)); zdo.Destroyed += delegate(ExtendedZDO x) { _states.Remove(x, out var _); }; } DateTimeOffset utcNow = DateTimeOffset.UtcNow; if (value.NextMessage < utcNow) { value.NextMessage = utcNow.AddSeconds(DamageText.instance.m_textDuration); float tameness = 1f - Mathf.Clamp01(tameTimeLeft / @float); bool isHungry = false; if ((ZNet.instance.GetTime() - zdo.Vars.GetTameLastFeeding()).TotalSeconds > (double)componentFieldAccessor.GetFloat(() => (Tameable x) => x.m_fedDuration, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TameableProcessor.cs", 118)) { isHungry = true; } Processor.ShowMessage(peers, zdo, base.Config.Localization.Tames.FormatTaming(tameness, isHungry), base.Config.Tames.TamingProgressMessageType.Value, (TextType)0); } } } goto IL_0660; IL_00e6: flag3 = !flag4; goto IL_00ed; IL_0260: if (flag4) { if (base.Config.Summons.UnsummonDistanceMultiplier.Value == 1f) { componentFieldAccessor.Reset(() => (Tameable x) => x.m_unsummonDistance, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TameableProcessor.cs", 70); } else if (componentFieldAccessor.UpdateValue(() => (Tameable x) => x.m_unsummonDistance, val.m_unsummonDistance * base.Config.Summons.UnsummonDistanceMultiplier.Value, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TameableProcessor.cs", 71)) { base.RecreateZdo = true; } if (base.Config.Summons.UnsummonLogoutTimeMultiplier.Value == 1f) { componentFieldAccessor.Reset(() => (Tameable x) => x.m_unsummonOnOwnerLogoutSeconds, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TameableProcessor.cs", 75); } else if (componentFieldAccessor.UpdateValue(() => (Tameable x) => x.m_unsummonOnOwnerLogoutSeconds, val.m_unsummonOnOwnerLogoutSeconds * base.Config.Summons.UnsummonLogoutTimeMultiplier.Value, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TameableProcessor.cs", 76)) { base.RecreateZdo = true; } } if (!base.RecreateZdo) { if (!_states.TryGetValue(zdo, out TameableState value2)) { _states.TryAdd(zdo, value2 = new TameableState(zdo)); zdo.Destroyed += delegate(ExtendedZDO x) { _states.Remove(x, out var _); }; } value2.IsTamed = true; } goto IL_0660; } } internal sealed class TrapProcessor : Processor { private readonly List<(ExtendedZDO ZDO, DateTimeOffset RearmAfter)> _rearmAfter = new List<(ExtendedZDO, DateTimeOffset)>(); protected override Guid Id { get; } = Guid.Parse("9617e1bc-80d0-4852-af9d-2946bd6cb801"); public override void Initialize(bool firstTime) { base.Initialize(firstTime); Processor.UpdateRpcSubscription("RPC_OnStateChanged", new Action(RPC_OnStateChanged), base.Config.Traps.AutoRearm.Value); if (firstTime) { _rearmAfter.Clear(); } } private void RPC_OnStateChanged(ExtendedZDO zdo, int state, long idOfClientModifyingState) { if (state != 0) { return; } (Aoe, Piece, PieceTable, PrefabInfo.Optional)? trap = zdo.PrefabInfo.Trap; if (trap.HasValue) { PrefabInfo.Optional item = trap.GetValueOrDefault().Item4; if (item.Value != null) { _rearmAfter.Add((zdo, DateTimeOffset.UtcNow.AddSeconds(zdo.PrefabInfo.Trap.Value.Trap.Value.m_rearmCooldown))); } } } protected override void PreProcessCore(IEnumerable peers) { for (int num = _rearmAfter.Count - 1; num >= 0; num--) { var (extendedZDO, dateTimeOffset) = _rearmAfter[num]; if (DateTimeOffset.UtcNow > dateTimeOffset) { if (((ZDO)extendedZDO).IsValid()) { (Aoe, Piece, PieceTable, PrefabInfo.Optional)? trap = extendedZDO.PrefabInfo.Trap; if (trap.HasValue) { PrefabInfo.Optional item = trap.GetValueOrDefault().Item4; if (item.Value != null) { RPC.RequestStateChange(extendedZDO, 1); } } } _rearmAfter.RemoveAt(num); } } } protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { base.UnregisterZdoProcessor = true; if (!zdo.PrefabInfo.Trap.HasValue || zdo.Vars.GetCreator(0L) == 0L) { return false; } (Aoe, Piece, PieceTable, PrefabInfo.Optional)? trap = zdo.PrefabInfo.Trap; if (trap.HasValue) { PrefabInfo.Optional item = trap.GetValueOrDefault().Item4; if (item.Value != null) { if (!base.Config.Traps.DisableTriggeredByPlayers.Value) { zdo.Fields(getUnknownComponent: false).Reset(() => (Trap x) => x.m_triggeredByPlayers, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TrapProcessor.cs", 53); } else if (zdo.Fields(getUnknownComponent: false).UpdateValue(() => (Trap x) => x.m_triggeredByPlayers, value: false, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TrapProcessor.cs", 54)) { base.RecreateZdo = true; } } } ExtendedZDO.ComponentFieldAccessor componentFieldAccessor = zdo.Fields(getUnknownComponent: false); if (!base.Config.Traps.DisableFriendlyFire.Value) { componentFieldAccessor.Reset(() => (Aoe x) => x.m_hitFriendly, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TrapProcessor.cs", 60); } else if (componentFieldAccessor.UpdateValue(() => (Aoe x) => x.m_hitFriendly, value: false, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TrapProcessor.cs", 61)) { base.RecreateZdo = true; } if (componentFieldAccessor.UpdateValue(() => (Aoe x) => x.m_damageSelf, zdo.PrefabInfo.Trap.Value.Aoe.m_damageSelf * base.Config.Traps.SelfDamageMultiplier.Value, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TrapProcessor.cs", 64)) { base.RecreateZdo = true; } return false; } } internal sealed class TrophyProcessor : Processor { private sealed class TrophyState { public ExtendedZDO Trophy { get; } public Character TrophyCharacter { get; } public int CharacterPrefab { get; } public DateTimeOffset TrophySpawnTime { get; } public DateTimeOffset LastMessage { get; set; } public DateTimeOffset LastSpawned { get; set; } public TrophyState(ExtendedZDO trophy, Character trophyCharacter) { Trophy = trophy; TrophyCharacter = trophyCharacter; CharacterPrefab = StringExtensionMethods.GetStableHashCode(((Object)trophyCharacter).name, true); TrophySpawnTime = trophy.Vars.GetSpawnTime(); LastSpawned = trophy.Vars.GetLastSpawnedTime(); base..ctor(); } } private TimeSpan _activationDelay; private TimeSpan _respawnDelay; private readonly Dictionary _stateByTrophy = new Dictionary(); private readonly List<(int Prefab, Vector3 Pos, Vector2s Zone, DateTimeOffset DiscardAfter)> _expectedRagdolls = new List<(int, Vector3, Vector2s, DateTimeOffset)>(); private readonly TimeSpan _textDuration = TimeSpan.FromSeconds(DamageText.instance.m_textDuration * 2f); private readonly List _sectorZdos = new List(); private readonly Vector3 _dropOffset = new Vector3(0f, -1000f, 0f); private const float MaxRagdollDistance = 32f; protected override Guid Id { get; } = Guid.Parse("e320985c-d7c9-4922-b778-2efee903ed4d"); public override void Initialize(bool firstTime) { base.Initialize(firstTime); foreach (ExtendedZDO @object in ZDOMan.instance.GetObjects()) { if (@object.Vars.GetSpawnedByTrophy()) { @object.Destroyed -= OnSpawnedDestroyed; if (base.Config.TrophySpawner.SuppressDrops.Value) { @object.Destroyed += OnSpawnedDestroyed; } } } if (firstTime) { _activationDelay = TimeSpan.FromSeconds(base.Config.TrophySpawner.ActivationDelay.Value); _respawnDelay = TimeSpan.FromSeconds(base.Config.TrophySpawner.RespawnDelay.Value); _stateByTrophy.Clear(); _expectedRagdolls.Clear(); _sectorZdos.Clear(); } } public bool IsAttracting(ExtendedZDO zdo) { if (_stateByTrophy.TryGetValue(zdo, out TrophyState value)) { return value.LastSpawned != default(DateTimeOffset); } return false; } private void OnTrophyDestroyed(ExtendedZDO zdo) { _stateByTrophy.Remove(zdo); } private void OnSpawnedDestroyed(ExtendedZDO zdo) { //IL_00a6: Unknown result type (might be due to invalid IL or missing references) //IL_00ab: Unknown result type (might be due to invalid IL or missing references) //IL_00c2: Unknown result type (might be due to invalid IL or missing references) //IL_00de: Unknown result type (might be due to invalid IL or missing references) //IL_0159: Unknown result type (might be due to invalid IL or missing references) //IL_0160: Unknown result type (might be due to invalid IL or missing references) //IL_0132: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Unknown result type (might be due to invalid IL or missing references) EffectData[] effectPrefabs = ((Character)(((object)zdo.PrefabInfo.Humanoid?.Humanoid) ?? ((object)zdo.PrefabInfo.Character?.Character))).m_deathEffects.m_effectPrefabs; EffectData[] array = effectPrefabs; foreach (EffectData val in array) { if (!val.m_enabled) { continue; } Ragdoll component = val.m_prefab.GetComponent(); if (component == null) { continue; } int stableHashCode = StringExtensionMethods.GetStableHashCode(((Object)val.m_prefab).name, true); Vector2s zone = ((ZDO)zdo).GetSector(); _sectorZdos.Clear(); ZDOMan.instance.FindSectorObjects(zone, 0, 0, _sectorZdos, (List)null); ExtendedZDO closestRagdoll = GetClosestRagdoll(_sectorZdos, stableHashCode, ((ZDO)zdo).GetPosition()); if (closestRagdoll == null) { DateTimeOffset item = DateTimeOffset.UtcNow + TimeSpan.FromSeconds(component.m_ttl); int num = _expectedRagdolls.FindLastIndex(((int Prefab, Vector3 Pos, Vector2s Zone, DateTimeOffset DiscardAfter) x) => x.Zone == zone); if (num < 0) { _expectedRagdolls.Add((stableHashCode, ((ZDO)zdo).GetPosition(), zone, item)); } else { _expectedRagdolls.Insert(num + 1, (stableHashCode, ((ZDO)zdo).GetPosition(), zone, item)); } } else { closestRagdoll.Destroy(); } _sectorZdos.Clear(); break; } } private static ExtendedZDO? GetClosestRagdoll(IReadOnlyList zdos, int prefab, Vector3 pos) { //IL_000e: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) return (from ExtendedZDO x in zdos where ((ZDO)x).GetPrefab() == prefab select (x, Utils.DistanceXZ(((ZDO)x).GetPosition(), pos)) into x where x.Distance <= 32f orderby x.Distance select x).FirstOrDefault().Item1; } protected override void PreProcessCore(IEnumerable peers) { //IL_0046: 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_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_0077: 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_00ab: 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_0083: 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 (_expectedRagdolls.Count == 0) { return; } Vector2s val = default(Vector2s); ((Vector2s)(ref val))..ctor(int.MaxValue, int.MaxValue); for (int num = _expectedRagdolls.Count - 1; num >= 0; num--) { var (prefab, pos, val2, dateTimeOffset) = _expectedRagdolls[num]; if (dateTimeOffset < DateTimeOffset.UtcNow) { _expectedRagdolls.RemoveAt(num); } else { if (val2 != val) { val = val2; _sectorZdos.Clear(); ZDOMan.instance.FindSectorObjects(val2, 1, 0, _sectorZdos, (List)null); } ExtendedZDO closestRagdoll = GetClosestRagdoll(_sectorZdos, prefab, pos); if (closestRagdoll != null) { closestRagdoll.Destroy(); _expectedRagdolls.RemoveAt(num); _sectorZdos.Remove((ZDO)(object)closestRagdoll); } } } } private bool ShouldAttemptSpawn(TrophyState state) { //IL_00c5: Unknown result type (might be due to invalid IL or missing references) //IL_00ca: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Unknown result type (might be due to invalid IL or missing references) TrophyState state2 = state; if (state2.LastSpawned == default(DateTimeOffset)) { state2.LastSpawned = DateTimeOffset.UtcNow - _respawnDelay + TimeSpan.FromSeconds(10.0); return false; } if (DateTimeOffset.UtcNow - state2.LastSpawned < _respawnDelay) { return false; } state2.LastSpawned = DateTimeOffset.UtcNow - _respawnDelay + TimeSpan.FromSeconds(Math.Min(10.0, _respawnDelay.TotalSeconds)); Vector2s sector = ((ZDO)state2.Trophy).GetSector(); _sectorZdos.Clear(); ZDOMan.instance.FindSectorObjects(sector, ZoneSystem.instance.GetLoadedArea(), 0, _sectorZdos, (List)null); int num = _sectorZdos.Cast().Count((ExtendedZDO x) => ((ZDO)x).GetPrefab() == state2.CharacterPrefab && x.Vars.GetSpawnedByTrophy()); _sectorZdos.Clear(); if (num < base.Config.TrophySpawner.SpawnLimit.Value) { return true; } return false; } protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_01f0: Unknown result type (might be due to invalid IL or missing references) //IL_01f5: Unknown result type (might be due to invalid IL or missing references) //IL_0245: Unknown result type (might be due to invalid IL or missing references) //IL_024a: Unknown result type (might be due to invalid IL or missing references) //IL_024f: Unknown result type (might be due to invalid IL or missing references) //IL_0254: Unknown result type (might be due to invalid IL or missing references) //IL_0257: Unknown result type (might be due to invalid IL or missing references) //IL_025c: 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_026a: Unknown result type (might be due to invalid IL or missing references) //IL_026c: Unknown result type (might be due to invalid IL or missing references) //IL_026e: Unknown result type (might be due to invalid IL or missing references) //IL_029a: Unknown result type (might be due to invalid IL or missing references) //IL_029c: Unknown result type (might be due to invalid IL or missing references) //IL_02a3: 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_02af: Unknown result type (might be due to invalid IL or missing references) //IL_02b1: Unknown result type (might be due to invalid IL or missing references) //IL_02b6: Unknown result type (might be due to invalid IL or missing references) //IL_02b8: Unknown result type (might be due to invalid IL or missing references) //IL_02ba: 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_02cd: Unknown result type (might be due to invalid IL or missing references) //IL_032e: Unknown result type (might be due to invalid IL or missing references) //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_0341: 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_0307: 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_0310: Unknown result type (might be due to invalid IL or missing references) //IL_0322: Unknown result type (might be due to invalid IL or missing references) //IL_0327: Unknown result type (might be due to invalid IL or missing references) //IL_032c: Unknown result type (might be due to invalid IL or missing references) //IL_0393: Unknown result type (might be due to invalid IL or missing references) //IL_03da: Unknown result type (might be due to invalid IL or missing references) //IL_0439: 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_03f3: 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_0586: Unknown result type (might be due to invalid IL or missing references) ItemDrop val = zdo.PrefabInfo.ItemDrop?.ItemDrop; if (!base.Config.TrophySpawner.Enable.Value || val == null || Character.InInterior(((ZDO)zdo).GetPosition()) || !SharedProcessorState.CharacterByTrophy.TryGetValue(((Object)val).name, out Character value)) { base.UnregisterZdoProcessor = true; return false; } if (!_stateByTrophy.TryGetValue(zdo, out TrophyState value2)) { _stateByTrophy.Add(zdo, value2 = new TrophyState(zdo, value)); zdo.Destroyed += OnTrophyDestroyed; } double num = zdo.GetTimeSinceSpawned().TotalSeconds / _activationDelay.TotalSeconds; if (num < 1.0) { if (DateTimeOffset.UtcNow - value2.LastMessage > _textDuration) { value2.LastMessage = DateTimeOffset.UtcNow; Processor.ShowMessage(peers, zdo, base.Config.Localization.TrophySpawner.FormatAttractingProgress(value.m_name, num), base.Config.TrophySpawner.MessageType.Value, (TextType)0); } return false; } if (zdo.Fields(getUnknownComponent: false).UpdateValue(() => (ItemDrop x) => x.m_autoPickup, value: false, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TrophyProcessor.cs", 194)) { base.RecreateZdo = true; return false; } if (ShouldAttemptSpawn(value2)) { int i = 1; float num2 = ((base.Config.TrophySpawner.LevelUpChanceOverride.Value < 0) ? 0f : SpawnSystem.GetLevelUpChance((float)base.Config.TrophySpawner.LevelUpChanceOverride.Value)); if (num2 > 0f) { for (; i < base.Config.TrophySpawner.MaxLevel.Value; i++) { if ((float)Random.Range(0, 100) > num2) { break; } } } Vector2s sector = ((ZDO)zdo).GetSector(); int num3 = 0; while (num3 < 10) { float num4 = Mathf.Min(base.Config.TrophySpawner.MinSpawnDistance.Value, 64f * (float)ZoneSystem.instance.GetActiveArea()); Vector3 val2 = Quaternion.Euler(0f, Random.Range(0f, 360f), 0f) * Vector3.forward; Vector3 val3 = ((ZDO)zdo).GetPosition() + val2 * num4; Vector3 val4 = val3; int num5 = Mathf.CeilToInt((base.Config.TrophySpawner.MaxSpawnDistance.Value - num4) / 2f); int j; for (j = 0; j < num5; j++) { Vector3 val5 = val4 + val2 * 2f; Vector2s zone = ZoneSystem.GetZone(val5); if (!ZNetScene.InActiveArea(zone, sector)) { j--; break; } val4 = val5; } if (base.Config.TrophySpawner.MinSpawnDistance.Value < base.Config.TrophySpawner.MaxSpawnDistance.Value) { val4 = val3 + val2 * 2f * Random.Range(0f, (float)j); } Vector2s zone2 = ZoneSystem.GetZone(val4); bool flag = true; val4.y = ZoneSystem.instance.GetGroundHeight(val4); if (val4.y < 30f && !value.m_canSwim && !value.m_flying) { flag = false; } else { val4.y += 8f; _sectorZdos.Clear(); ZDOMan.instance.FindSectorObjects(zone2, 1, 0, _sectorZdos, (List)null); foreach (ExtendedZDO item3 in _sectorZdos.Cast()) { if (item3.PrefabInfo.EffectArea != null && ((Enum)item3.PrefabInfo.EffectArea.m_type).HasFlag((Enum)(object)(Type)4) && Utils.DistanceXZ(((ZDO)item3).GetPosition(), val4) < 20f) { flag = false; break; } } _sectorZdos.Clear(); } ExtendedZDO extendedZDO; bool flag2; if (flag) { extendedZDO = (ExtendedZDO)(object)ZDOMan.instance.CreateNewZDO(val4, value2.CharacterPrefab); ((ZDO)extendedZDO).SetPrefab(value2.CharacterPrefab); ((ZDO)extendedZDO).Persistent = true; ((ZDO)extendedZDO).Distant = false; ((ZDO)extendedZDO).Type = (ObjectType)0; extendedZDO.Vars.SetLevel(i, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TrophyProcessor.cs", 288); extendedZDO.Vars.SetSpawnPoint(((ZDO)zdo).GetPosition(), "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TrophyProcessor.cs", 290); extendedZDO.Vars.SetSpawnedByTrophy(value: true, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TrophyProcessor.cs", 291); if (base.Config.TrophySpawner.SuppressDrops.Value) { PrefabInfo prefabInfo = extendedZDO.PrefabInfo; if ((object)prefabInfo != null) { (Humanoid, PrefabInfo.Optional, PrefabInfo.Optional)? humanoid = prefabInfo.Humanoid; if (humanoid.HasValue) { PrefabInfo.Optional item = humanoid.GetValueOrDefault().Item3; CharacterDrop value3 = item.Value; if (value3 != null) { goto IL_0552; } } (Character, PrefabInfo.Optional)? character = prefabInfo.Character; if (character.HasValue) { PrefabInfo.Optional item2 = character.GetValueOrDefault().Item2; CharacterDrop value4 = item2.Value; if (value4 != null) { goto IL_0552; } } } flag2 = false; goto IL_055a; } goto IL_05ae; } num3++; continue; IL_055a: if (flag2) { extendedZDO.Fields(getUnknownComponent: false).Set(() => (CharacterDrop x) => x.m_spawnOffset, _dropOffset, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TrophyProcessor.cs", 297); } extendedZDO.Destroyed += OnSpawnedDestroyed; goto IL_05ae; IL_05ae: ExtendedZDO.ZDOVars_ vars = zdo.Vars; DateTimeOffset value5 = (value2.LastSpawned = DateTimeOffset.UtcNow); vars.SetLastSpawnedTime(value5, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TrophyProcessor.cs", 301); break; IL_0552: flag2 = true; goto IL_055a; } } if (DateTimeOffset.UtcNow - value2.LastMessage > _textDuration) { value2.LastMessage = DateTimeOffset.UtcNow; Processor.ShowMessage(peers, zdo, base.Config.Localization.TrophySpawner.FormatAttracting(value.m_name), base.Config.TrophySpawner.MessageType.Value, (TextType)2); } return false; } } internal sealed class TurretProcessor : Processor { private readonly List _turrets = new List(); protected override Guid Id { get; } = Guid.Parse("4b69158e-1790-40be-8dd1-5d1d57197bba"); public override void Initialize(bool firstTime) { base.Initialize(firstTime); if (firstTime) { _turrets.Clear(); Processor.Instance().ContainerChanged -= OnContainerChanged; Processor.Instance().ContainerChanged += OnContainerChanged; } } private void OnContainerChanged(ExtendedZDO containerZdo) { //IL_006c: 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) if (containerZdo.Inventory.Items.Count == 0) { return; } float num = ((float?)containerZdo.Inventory.FeedRange) ?? base.Config.Turrets.LoadFromContainersRange.Value; num *= num; if (num == 0f) { return; } foreach (ExtendedZDO turret in _turrets) { if (Utils.DistanceSqr(((ZDO)turret).GetPosition(), ((ZDO)containerZdo).GetPosition()) <= num && turret.Vars.GetAmmo() == 0) { turret.ResetProcessorDataRevision(this); } } } protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { //IL_037c: Unknown result type (might be due to invalid IL or missing references) //IL_0383: Unknown result type (might be due to invalid IL or missing references) if (!zdo.PrefabInfo.Turret.HasValue) { base.UnregisterZdoProcessor = true; return false; } ExtendedZDO.ComponentFieldAccessor componentFieldAccessor = zdo.Fields(getUnknownComponent: false); if (!base.Config.Turrets.DontTargetPlayers.Value) { componentFieldAccessor.Reset(() => (Turret x) => x.m_targetPlayers, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TurretProcessor.cs", 47); } else if (componentFieldAccessor.UpdateValue(() => (Turret x) => x.m_targetPlayers, value: false, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TurretProcessor.cs", 48)) { base.RecreateZdo = true; } if (!base.Config.Turrets.DontTargetTames.Value) { componentFieldAccessor.Reset(() => (Turret x) => x.m_targetTamed, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TurretProcessor.cs", 52); } else if (componentFieldAccessor.UpdateValue(() => (Turret x) => x.m_targetTamed, value: false, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TurretProcessor.cs", 53)) { base.RecreateZdo = true; } if (!base.Config.Turrets.DontTargetTames.Value) { componentFieldAccessor.Reset(() => (Turret x) => x.m_targetTamedConfig, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TurretProcessor.cs", 57); } else if (componentFieldAccessor.UpdateValue(() => (Turret x) => x.m_targetTamedConfig, value: false, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TurretProcessor.cs", 58)) { base.RecreateZdo = true; } if (!base.Config.Turrets.LoadFromContainers.Value) { base.UnregisterZdoProcessor = true; return false; } if (!CheckMinDistance(peers, (ZDO)(object)zdo)) { return false; } int @int = componentFieldAccessor.GetInt(() => (Turret x) => x.m_maxAmmo, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TurretProcessor.cs", 116); int num = zdo.Vars.GetAmmo(); int num2 = @int - num; if (num2 < @int / 2) { return num > 0; } string text = ((num > 0) ? zdo.Vars.GetAmmoType() : null); ItemData val = null; int num3 = 0; foreach (ItemDrop ammoItem in zdo.PrefabInfo.Turret.Value.Turret.m_allowedAmmo.Select((AmmoType x) => x.m_ammo)) { if ((!string.IsNullOrEmpty(text) && ((Object)ammoItem).name != text) || !Processor.Instance().ContainersByItemName.TryGetValue(ammoItem.m_itemData.m_shared, out ConcurrentHashSet value)) { continue; } List list = null; foreach (ExtendedZDO item in (IEnumerable)value) { if (!((ZDO)item).IsValid() || !item.PrefabInfo.Container.HasValue) { value.Remove(item); continue; } float num4 = ((float?)item.Inventory.FeedRange) ?? base.Config.Turrets.LoadFromContainersRange.Value; num4 *= num4; if (num4 == 0f || Utils.DistanceSqr(((ZDO)zdo).GetPosition(), ((ZDO)item).GetPosition()) > num4 || item.Vars.GetInUse()) { continue; } list?.Clear(); int num5 = 0; bool flag = false; bool flag2 = false; foreach (ItemData item2 in from x in item.Inventory.Items where new ItemDataKey(x) == ammoItem.m_itemData orderby x.m_stack select x) { flag = flag || (item2 != null && item2.m_stack > 0); int num6 = Math.Min(num2, item2.m_stack); if (num6 != 0) { if (!item.IsOwnerOrUnassigned()) { flag2 = true; break; } text = ((Object)ammoItem).name; val = ammoItem.m_itemData; num5 += num6; item2.m_stack -= num6; if (item2.m_stack == 0) { (list ?? (list = new List())).Add(item2); } num2 -= num6; if (num2 == 0) { break; } } } if (flag2) { Processor.Instance().RequestOwnership(item, 0L, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TurretProcessor.cs", 183); continue; } ConcurrentHashSet value2; if (num5 == 0) { if (!flag) { value.Remove(item); if (value != null && value.Count == 0) { Processor.Instance().ContainersByItemName.TryRemove(ammoItem.m_itemData.m_shared, out value2); } } continue; } if (list != null && list.Count > 0) { foreach (ItemData item3 in list) { item.Inventory.Items.Remove(item3); } IList items = item.Inventory.Items; if (items != null && items.Count == 0) { value.Remove(item); if (value != null && value.Count == 0) { Processor.Instance().ContainersByItemName.TryRemove(ammoItem.m_itemData.m_shared, out value2); } } } num += num5; zdo.Vars.SetAmmo(num, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TurretProcessor.cs", 212); zdo.Vars.SetAmmoType(text, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\TurretProcessor.cs", 213); item.Inventory.Save(); num3 += num5; if (num2 != 0) { continue; } break; } } if (num3 != 0) { Processor.ShowMessage(peers, zdo, base.Config.Localization.Turrets.FormatAmmoAdded(zdo.PrefabInfo.Turret.Value.Piece.m_name, val.m_shared.m_name, num3), base.Config.Turrets.AmmoAddedMessageType.Value, (TextType)0); } else if (num == 0) { Processor.ShowMessage(peers, zdo, base.Config.Localization.Turrets.NoAmmoFound, base.Config.Turrets.NoAmmoMessageType.Value, (TextType)7); } if (!_turrets.Contains(zdo)) { _turrets.Add(zdo); zdo.Destroyed += delegate(ExtendedZDO x) { _turrets.Remove(x); }; } return true; } } internal sealed class VagonProcesser : Processor { protected override Guid Id { get; } = Guid.Parse("c4463e98-16e0-419b-9096-90307a332803"); protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { base.UnregisterZdoProcessor = true; if (!zdo.PrefabInfo.Vagon.HasValue) { return false; } ExtendedZDO.ComponentFieldAccessor componentFieldAccessor = zdo.Fields(getUnknownComponent: false); if (base.Config.Carts.ContentMassMultiplier.Value == 1f || float.IsNaN(base.Config.Carts.ContentMassMultiplier.Value)) { componentFieldAccessor.Reset(() => (Vagon x) => x.m_itemWeightMassFactor, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\VagonProcesser.cs", 16); } else if (componentFieldAccessor.UpdateValue(() => (Vagon x) => x.m_itemWeightMassFactor, zdo.PrefabInfo.Vagon.Value.Vagon.m_itemWeightMassFactor * base.Config.Carts.ContentMassMultiplier.Value, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\VagonProcesser.cs", 17)) { base.RecreateZdo = true; } if (zdo.Fields(getUnknownComponent: false).UpdateValue(() => (Piece x) => x.m_canBeRemoved, base.Config.Carts.DeconstructWithHammer.Value, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\VagonProcesser.cs", 20)) { base.RecreateZdo = true; } return false; } } internal sealed class WearNTearProcessor : Processor { protected override Guid Id { get; } = Guid.Parse("46374d89-a351-48f5-96b2-b1ad46e71ee6"); protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { base.UnregisterZdoProcessor = true; if (!zdo.PrefabInfo.WearNTear.HasValue) { return false; } PlayerProcessor.BuildModifiers buildModifiers = zdo.Vars.GetAdminBuildModifiers((PlayerProcessor.BuildModifiers)4294967295u); long creator = zdo.Vars.GetCreator(0L); if (buildModifiers == (PlayerProcessor.BuildModifiers)4294967295u) { IPeerInfo peerInfoFromPlayerID = Processor.Instance().GetPeerInfoFromPlayerID(creator); if (peerInfoFromPlayerID == null) { buildModifiers = PlayerProcessor.BuildModifiers.None; } else { buildModifiers = peerInfoFromPlayerID.BuildModifiers; zdo.Vars.SetAdminBuildModifiers(buildModifiers, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\WearNTearProcessor.cs", 25); } } ExtendedZDO.ComponentFieldAccessor componentFieldAccessor = zdo.Fields(getUnknownComponent: false); (WearNTear, PrefabInfo.Optional, PrefabInfo.Optional)? wearNTear = zdo.PrefabInfo.WearNTear; int num; if (wearNTear.HasValue) { (WearNTear, PrefabInfo.Optional, PrefabInfo.Optional) valueOrDefault = wearNTear.GetValueOrDefault(); PrefabInfo.Optional item = valueOrDefault.Item2; if (item.Value != null) { PrefabInfo.Optional item2 = valueOrDefault.Item3; if (item2.Value != null) { num = ((creator != 0) ? 1 : 0); goto IL_00cd; } } } num = 0; goto IL_00cd; IL_00cd: bool flag = (byte)num != 0; if (flag) { if (base.Config.WearNTear.DisableRainDamage.Value) { buildModifiers |= PlayerProcessor.BuildModifiers.DisableRainDamage; } if (base.Config.WearNTear.MakeIndestructible.Value) { buildModifiers |= PlayerProcessor.BuildModifiers.MakeIndestructible; } } if ((buildModifiers & PlayerProcessor.BuildModifiers.DisableSupportRequirements) == 0 && base.Config.WearNTear.DisableSupportRequirements.Value != 0 && ((base.Config.WearNTear.DisableSupportRequirements.Value.HasFlag(ModConfigBase.WearNTearConfig.DisableSupportRequirementsOptions.PlayerBuilt) && flag) || (base.Config.WearNTear.DisableSupportRequirements.Value.HasFlag(ModConfigBase.WearNTearConfig.DisableSupportRequirementsOptions.World) && !flag))) { buildModifiers |= PlayerProcessor.BuildModifiers.DisableSupportRequirements; } if ((buildModifiers & PlayerProcessor.BuildModifiers.DisableRainDamage) == 0) { componentFieldAccessor.Reset(() => (WearNTear x) => x.m_noRoofWear, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\WearNTearProcessor.cs", 49); } else if (componentFieldAccessor.UpdateValue(() => (WearNTear x) => x.m_noRoofWear, value: false, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\WearNTearProcessor.cs", 50)) { base.RecreateZdo = true; } if ((buildModifiers & PlayerProcessor.BuildModifiers.DisableSupportRequirements) == 0) { componentFieldAccessor.Reset(() => (WearNTear x) => x.m_noSupportWear, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\WearNTearProcessor.cs", 54); } else if (componentFieldAccessor.UpdateValue(() => (WearNTear x) => x.m_noSupportWear, value: false, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\WearNTearProcessor.cs", 55)) { base.RecreateZdo = true; } if ((buildModifiers & PlayerProcessor.BuildModifiers.MakeIndestructible) == 0) { if (componentFieldAccessor.UpdateResetValue(() => (WearNTear x) => x.m_health, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\WearNTearProcessor.cs", 60)) { zdo.Vars.RemoveHealth("D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\WearNTearProcessor.cs", 61); } } else if (componentFieldAccessor.UpdateValue(() => (WearNTear x) => x.m_health, -1f, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\WearNTearProcessor.cs", 63)) { zdo.Vars.SetHealth(-1f, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\WearNTearProcessor.cs", 65); base.RecreateZdo = true; } return false; } } internal sealed class WindmillProcesser : Processor { protected override Guid Id { get; } = Guid.Parse("fd865439-b237-48a8-a27e-76f262eedf31"); protected override bool ProcessCore(ExtendedZDO zdo, IReadOnlyList peers) { base.UnregisterZdoProcessor = true; if (zdo.PrefabInfo.Windmill == null) { return false; } ExtendedZDO.ComponentFieldAccessor componentFieldAccessor = zdo.Fields(getUnknownComponent: false); if (!base.Config.Windmills.IgnoreWind.Value) { componentFieldAccessor.Reset(() => (Windmill x) => x.m_minWindSpeed, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\WindmillProcesser.cs", 16); } else if (componentFieldAccessor.UpdateValue(() => (Windmill x) => x.m_minWindSpeed, float.MinValue, "D:\\a\\ValheimServersideQoL\\ValheimServersideQoL\\ValheimServersideQoL\\Processors\\WindmillProcesser.cs", 17)) { base.RecreateZdo = true; } return true; } } } namespace Valheim.ServersideQoL.HarmonyPatches { [HarmonyPatch(typeof(ZDOPool), "Get")] public static class ZDOPoolGet { [CompilerGenerated] private sealed class d__2 : IEnumerable, IEnumerable, IEnumerator, IEnumerator, IDisposable { private int <>1__state; private CodeInstruction <>2__current; private int <>l__initialThreadId; private IEnumerable instructions; public IEnumerable <>3__instructions; private bool 5__2; private IEnumerator <>7__wrap2; CodeInstruction IEnumerator.Current { [DebuggerHidden] get { return <>2__current; } } object IEnumerator.Current { [DebuggerHidden] 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 || num == 1) { try { } finally { <>m__Finally1(); } } <>7__wrap2 = null; <>1__state = -2; } private bool MoveNext() { try { switch (<>1__state) { default: return false; case 0: <>1__state = -1; 5__2 = false; <>7__wrap2 = instructions.GetEnumerator(); <>1__state = -3; break; case 1: <>1__state = -3; break; } if (<>7__wrap2.MoveNext()) { CodeInstruction current = <>7__wrap2.Current; if (current.opcode == OpCodes.Newobj && (ConstructorInfo)current.operand == __targetMethod) { current.operand = __replacementMethod; 5__2 = true; } <>2__current = current; <>1__state = 1; return true; } <>m__Finally1(); <>7__wrap2 = null; if (!5__2) { throw new Exception("HarmonyPatch ZDOPoolGet.Transpiler failed"); } 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__wrap2 != null) { <>7__wrap2.Dispose(); } } [DebuggerHidden] void IEnumerator.Reset() { throw new NotSupportedException(); } [DebuggerHidden] 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] IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)this).GetEnumerator(); } } private static readonly ConstructorInfo __targetMethod = typeof(ZDO).GetConstructor(Type.EmptyTypes) ?? throw new ArgumentNullException(); private static readonly ConstructorInfo __replacementMethod = typeof(ExtendedZDO).GetConstructor(Type.EmptyTypes) ?? throw new ArgumentNullException(); [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 }; } } [HarmonyPatch(typeof(ZoneSystem), "SendGlobalKeys")] public static class ZoneSystemSendGlobalKeys { private static readonly Dictionary __prevKeys = new Dictionary(); public static event Action? GlobalKeysChanged; public static event Action? GlobalKeyValuesChanged; public static void Prefix(ZoneSystem __instance, long peer) { if (peer != ZRoutedRpc.Everybody) { return; } bool flag = false; if (ZoneSystemSendGlobalKeys.GlobalKeysChanged != null && !__prevKeys.Keys.SequenceEqual(__instance.m_globalKeysValues.Keys)) { flag = true; ZoneSystemSendGlobalKeys.GlobalKeysChanged(); } if (ZoneSystemSendGlobalKeys.GlobalKeyValuesChanged != null && !__prevKeys.SequenceEqual>(__instance.m_globalKeysValues)) { flag = true; ZoneSystemSendGlobalKeys.GlobalKeyValuesChanged(); } if (!flag) { return; } __prevKeys.Clear(); foreach (var (key, value) in __instance.m_globalKeysValues) { __prevKeys.Add(key, value); } } private static IEnumerable Transpiler(IEnumerable instructions) { //IL_0044: 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: Expected O, but got Unknown //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Expected O, but got Unknown //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Expected O, but got Unknown //IL_009b: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Expected O, but got Unknown ConstructorInfo constructor = typeof(List).GetConstructor(new Type[1] { typeof(IEnumerable) }); MethodInfo method = new Func, long, List>(ModfiyGlobalKeys).Method; return new CodeMatcher().Start().Insert(instructions).Start() .MatchForward(false, (CodeMatch[])(object)new CodeMatch[1] { new CodeMatch(new CodeInstruction(OpCodes.Newobj, (object)constructor), (string)null) }) .Advance(1) .Insert((CodeInstruction[])(object)new CodeInstruction[2] { new CodeInstruction(OpCodes.Ldarg_1, (object)null), new CodeInstruction(OpCodes.Call, (object)method) }) .ThrowIfInvalid("Failed to apply patch ZoneSystemSendGlobalKeys.Transpiler") .InstructionEnumeration(); static List ModfiyGlobalKeys(List globalKeys, long peer) { IPeerInfo peerInfo = Processor.Instance().GetPeerInfo(peer); if (peerInfo == null) { return globalKeys; } foreach (KeyValuePair globalKeyModification in peerInfo.GlobalKeyModifications) { var (key, flag2) = (KeyValuePair)(ref globalKeyModification); if (!flag2) { globalKeys.Remove(key); } else if (!globalKeys.Contains(key)) { globalKeys.Add(key); } } return globalKeys; } } } } namespace System.Runtime.CompilerServices { [EditorBrowsable(EditorBrowsableState.Never)] internal static class IsExternalInit { } [AttributeUsage(AttributeTargets.All, AllowMultiple = true, Inherited = false)] [EditorBrowsable(EditorBrowsableState.Never)] internal sealed class CompilerFeatureRequiredAttribute : Attribute { public const string RefStructs = "RefStructs"; public const string RequiredMembers = "RequiredMembers"; public string FeatureName { get; } public bool IsOptional { get; init; } public CompilerFeatureRequiredAttribute(string featureName) { FeatureName = featureName; } } [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false, Inherited = false)] [EditorBrowsable(EditorBrowsableState.Never)] internal sealed class RequiredMemberAttribute : Attribute { } } namespace System.Diagnostics.CodeAnalysis { [AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false, Inherited = false)] [EditorBrowsable(EditorBrowsableState.Never)] internal sealed class SetsRequiredMembersAttribute : Attribute { } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property, Inherited = false, AllowMultiple = true)] 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)] internal sealed class MemberNotNullWhenAttribute : Attribute { public string[] Members { get; } public bool ReturnValue { 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; } } }