Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of Expand World Prefabs v1.65.0
ExpandWorldPrefabs.dll
Decompiled 2 weeks ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Threading; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using Common; using Data; using ExpandWorld.Prefab; using HarmonyLib; using Microsoft.CodeAnalysis; using Service; using SoftReferenceableAssets; using Splatform; using UnityEngine; using YamlDotNet.Core; using YamlDotNet.Core.Events; using YamlDotNet.Serialization; using YamlDotNet.Serialization.NamingConventions; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.8", FrameworkDisplayName = ".NET Framework 4.8")] [assembly: InternalsVisibleTo("ExpandWorldPrefabs.Tests")] [assembly: AssemblyCompany("ExpandWorldPrefabs")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0+b57d075253182076aae14863b91a3c83173de25b")] [assembly: AssemblyProduct("ExpandWorldPrefabs")] [assembly: AssemblyTitle("ExpandWorldPrefabs")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("1.0.0.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [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] [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] [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 Service { public class DataStorage { private static Dictionary<string, string> Database = new Dictionary<string, string>(); private static readonly Stopwatch LastSaveStopwatch = Stopwatch.StartNew(); private static bool UnsavedChanges = false; public static Action<string, string>? OnSet; private static string SavedDataFile => Path.Combine(Yaml.BaseDirectory, "ewp_data.yaml"); public static void LoadSavedData() { if (!Directory.Exists(Yaml.BaseDirectory)) { Directory.CreateDirectory(Yaml.BaseDirectory); } if (!File.Exists(SavedDataFile)) { return; } foreach (KeyValuePair<string, string> item in Yaml.DeserializeData(File.ReadAllText(SavedDataFile))) { Database[item.Key.ToLowerInvariant()] = item.Value; } Log.Info($"Reloaded saved data ({Database.Count} entries)."); } public static void SaveSavedData() { if (UnsavedChanges && !(LastSaveStopwatch.Elapsed.TotalSeconds < 10.0)) { LastSaveStopwatch.Restart(); if (!Directory.Exists(Yaml.BaseDirectory)) { Directory.CreateDirectory(Yaml.BaseDirectory); } string contents = Yaml.SerializeData(Database); Yaml.BackupFile(SavedDataFile, overwrite: false); File.WriteAllText(SavedDataFile, contents); UnsavedChanges = false; } } public static string GetValue(string key, string defaultValue = "") { if (!Database.TryGetValue(key.ToLowerInvariant(), out string value)) { return defaultValue; } return value; } public static bool TryGetValue(string key, out string value) { return Database.TryGetValue(key.ToLowerInvariant(), out value); } public static void SetValue(string key, string value) { if (!(key == "")) { key = key.ToLowerInvariant(); int num = key.IndexOf('*'); if (num < 0) { SetValueSub(key, value); } else { SetValues(MatchKeys(key, num), value); } } } public static string IncrementValue(string key, long amount) { if (key == "") { return "0"; } key = key.ToLowerInvariant(); int num = key.IndexOf('*'); if (num < 0) { long num2 = Parse.Long(GetValue(key, "0"), 0L) + amount; SetValueSub(key, num2.ToString()); return num2.ToString(); } foreach (string item in MatchKeys(key, num)) { if (Database.TryGetValue(item, out string value)) { SetValueSub(item, (Parse.Long(value, 0L) + amount).ToString()); } } return "0"; } private static List<string> MatchKeys(string key, int wildIndex) { if (key == "*") { Dictionary<string, string>.KeyCollection keys = Database.Keys; List<string> list = new List<string>(keys.Count); list.AddRange(keys); return list; } if (key[0] == '*' && key[key.Length - 1] == '*') { List<string> list2 = new List<string>(); list2.AddRange(Database.Keys.Where((string k) => k.Contains(key.Substring(1, key.Length - 2)))); return list2; } if (key[0] == '*') { List<string> list3 = new List<string>(); list3.AddRange(Database.Keys.Where((string k) => k.EndsWith(key.Substring(1), StringComparison.OrdinalIgnoreCase))); return list3; } if (key[key.Length - 1] == '*') { List<string> list4 = new List<string>(); list4.AddRange(Database.Keys.Where((string k) => k.StartsWith(key.Substring(0, key.Length - 1), StringComparison.OrdinalIgnoreCase))); return list4; } if (wildIndex > 0 && wildIndex < key.Length - 1) { string prefix = key.Substring(0, wildIndex); string suffix = key.Substring(wildIndex + 1); List<string> list5 = new List<string>(); list5.AddRange(Database.Keys.Where((string k) => k.StartsWith(prefix, StringComparison.OrdinalIgnoreCase) && k.EndsWith(suffix, StringComparison.OrdinalIgnoreCase))); return list5; } return new List<string>(); } public static void SetValues(List<string> keys, string value) { foreach (string key in keys) { SetValueSub(key, value); } } private static void SetValueSub(string key, string value) { if ((!(value == "") || Database.ContainsKey(key)) && (!Database.TryGetValue(key, out string value2) || !(value2 == value))) { if (value == "") { Database.Remove(key); } else { Database[key] = value; } UnsavedChanges = true; OnSet?.Invoke(key, value); } } private static bool ValueMatches(string dbValue, string conditionValue) { if (conditionValue == "") { return true; } if (!Enumerable.Contains(conditionValue, ';')) { return dbValue == conditionValue; } string[] array = conditionValue.Split(new char[1] { ';' }); if (array.Length < 2) { return false; } long? num = Parse.LongNull(array[0]); long? num2 = Parse.LongNull(array[1]); if (!num.HasValue || !num2.HasValue) { return false; } if (num.Value > num2.Value) { return false; } long num3 = 1L; if (array.Length >= 3 && array[2] != "") { long? num4 = Parse.LongNull(array[2]); if (!num4.HasValue || num4.Value <= 0) { return false; } num3 = num4.Value; } long? num5 = Parse.LongNull(dbValue); if (!num5.HasValue) { return false; } if (num5.Value < num.Value || num5.Value > num2.Value) { return false; } return (num5.Value - num.Value) % num3 == 0; } public static bool HasAnyKey(List<string> keys, Functions f) { foreach (string key in keys) { KeyValuePair<string, string> keyValuePair = Parse.Kvp(key.Contains("<") ? f.Replace(key) : key, ' '); string text = keyValuePair.Key.ToLowerInvariant(); if (text == "") { continue; } int num = text.IndexOf('*'); string value2; if (num >= 0) { List<string> list = MatchKeys(text, num); if (list.Count == 0) { continue; } foreach (string item in list) { if (Database.TryGetValue(item, out string value) && ValueMatches(value, keyValuePair.Value)) { return true; } } } else if (Database.TryGetValue(text, out value2) && ValueMatches(value2, keyValuePair.Value)) { return true; } } return false; } public static bool HasEveryKey(List<string> keys, Functions f) { foreach (string key in keys) { KeyValuePair<string, string> keyValuePair = Parse.Kvp(key.Contains("<") ? f.Replace(key) : key, ' '); int num = keyValuePair.Key.IndexOf('*'); string value2; if (num >= 0) { List<string> list = MatchKeys(keyValuePair.Key, num); if (list.Count == 0) { return false; } foreach (string item in list) { if (!Database.TryGetValue(item, out string value) || !ValueMatches(value, keyValuePair.Value)) { return false; } } } else if (!Database.TryGetValue(keyValuePair.Key.ToLowerInvariant(), out value2) || !ValueMatches(value2, keyValuePair.Value)) { return false; } } return true; } } public static class FileLoading { private const string PrefabFileName = "expand_prefabs.yaml"; private static readonly string PrefabFilePath = Path.Combine(Yaml.BaseDirectory, "expand_prefabs.yaml"); public static readonly string DataGamePath = Path.GetFullPath(Path.Combine("BepInEx", "config", "data")); public static readonly string DataProfilePath = Path.GetFullPath(Path.Combine(Paths.ConfigPath, "data")); public const string DataPattern = "expand_data*.yaml"; public const string PrefabPattern = "expand_prefabs*.yaml"; private static readonly Dictionary<string, List<RuleYaml>> PrefabFileEntries = new Dictionary<string, List<RuleYaml>>(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary<string, List<DataYaml>> DataFileEntries = new Dictionary<string, List<DataYaml>>(StringComparer.OrdinalIgnoreCase); private static readonly Dictionary<string, List<ConfigYaml>> ConfigFileEntries = new Dictionary<string, List<ConfigYaml>>(StringComparer.OrdinalIgnoreCase); public static string NormalizePath(string path) { try { return Path.GetFullPath(path); } catch { return path; } } public static bool IsYaml(string path) { return path.EndsWith(".yaml", StringComparison.OrdinalIgnoreCase); } public static bool IsInFolder(string path, string folder) { string text = NormalizePath(path); string text2 = NormalizePath(folder).TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar); char directorySeparatorChar = Path.DirectorySeparatorChar; string value = text2 + directorySeparatorChar; return text.StartsWith(value, StringComparison.OrdinalIgnoreCase); } public static bool MatchesPattern(string path, string pattern) { string fileName = Path.GetFileName(path); if (pattern == "*.yaml") { return fileName.EndsWith(".yaml", StringComparison.OrdinalIgnoreCase); } int num = pattern.IndexOf('*'); if (num < 0) { return fileName.Equals(pattern, StringComparison.OrdinalIgnoreCase); } string text = pattern.Substring(0, num); string text2 = pattern.Substring(num + 1); if (text != "" && !fileName.StartsWith(text, StringComparison.OrdinalIgnoreCase)) { return false; } if (text2 != "" && !fileName.EndsWith(text2, StringComparison.OrdinalIgnoreCase)) { return false; } return true; } public static List<string> GetPatternFiles(string folder, string pattern) { if (!Directory.Exists(folder)) { Directory.CreateDirectory(folder); } return Directory.GetFiles(folder, pattern, SearchOption.AllDirectories).Select(NormalizePath).Distinct<string>(StringComparer.OrdinalIgnoreCase) .ToList(); } public static List<string> GetDataSourceFiles(string gamePath, string profilePath, string baseDirectory, string dataPattern, string prefabPattern) { if (!Directory.Exists(gamePath)) { Directory.CreateDirectory(gamePath); } if (!Directory.Exists(profilePath)) { Directory.CreateDirectory(profilePath); } if (!Directory.Exists(baseDirectory)) { Directory.CreateDirectory(baseDirectory); } return Directory.GetFiles(gamePath, "*.yaml", SearchOption.AllDirectories).Concat(Directory.GetFiles(profilePath, "*.yaml", SearchOption.AllDirectories)).Concat(Directory.GetFiles(baseDirectory, dataPattern, SearchOption.AllDirectories)) .Concat(Directory.GetFiles(baseDirectory, prefabPattern, SearchOption.AllDirectories)) .Select(NormalizePath) .Distinct<string>(StringComparer.OrdinalIgnoreCase) .ToList(); } public static void EnsureDataDirectories() { if (!Directory.Exists(DataGamePath)) { Directory.CreateDirectory(DataGamePath); } if (!Directory.Exists(DataProfilePath)) { Directory.CreateDirectory(DataProfilePath); } if (!Directory.Exists(Yaml.BaseDirectory)) { Directory.CreateDirectory(Yaml.BaseDirectory); } } private static void EnsurePrefabFile() { if (!Directory.Exists(Yaml.BaseDirectory)) { Directory.CreateDirectory(Yaml.BaseDirectory); } if (!File.Exists(PrefabFilePath)) { File.WriteAllText(PrefabFilePath, "# Write your entries here. Good luck!"); } } public static List<string> GetDataSourceFiles() { return GetDataSourceFiles(DataGamePath, DataProfilePath, Yaml.BaseDirectory, "expand_data*.yaml", "expand_prefabs*.yaml"); } public static void SetupWatchers(bool overwriteBackup = true) { EnsureDataDirectories(); EnsurePrefabFile(); Yaml.SetupWatcher(DataGamePath, "*", HandleDataFileChange, overwriteBackup); if (DataGamePath != DataProfilePath) { Yaml.SetupWatcher(DataProfilePath, "*", HandleDataFileChange, overwriteBackup); } Yaml.SetupWatcher("expand_data*.yaml", HandleDataFileChange, overwriteBackup); Yaml.SetupWatcher("expand_prefabs*.yaml", HandlePrefabFileChange, overwriteBackup); } public static void ReloadAll() { if (Helper.IsClient()) { return; } EnsureDataDirectories(); EnsurePrefabFile(); List<string> patternFiles = GetPatternFiles(Yaml.BaseDirectory, "expand_prefabs*.yaml"); patternFiles.Reverse(); PrefabFileEntries.Clear(); ConfigFileEntries.Clear(); DataFileEntries.Clear(); foreach (string item in patternFiles) { LoadPrefabFile(item); } List<string> dataSourceFiles = GetDataSourceFiles(); EnsureCache(DataFileEntries, dataSourceFiles, (string file) => ReadDataEntries(file)); DataLoading.LoadFromFiles(dataSourceFiles, DataFileEntries); ConfigManager.LoadFromFiles(patternFiles, ConfigFileEntries); Loading.LoadFromFiles(patternFiles, PrefabFileEntries); } private static void HandleDataFileChange(string path, string? oldPath, Yaml.FileChangeType type) { if (Helper.IsClient()) { return; } path = NormalizePath(path); oldPath = ((oldPath == null) ? null : NormalizePath(oldPath)); if (IsTrackedDataPath(path) || (oldPath != null && IsTrackedDataPath(oldPath))) { if (oldPath != null && oldPath != path) { DataFileEntries.Remove(oldPath); } if (type == Yaml.FileChangeType.Deleted) { DataFileEntries.Remove(path); } else if (IsYaml(path) && File.Exists(path)) { DataFileEntries[path] = ReadDataEntries(path); } List<string> dataSourceFiles = GetDataSourceFiles(); PruneStaleCache(DataFileEntries, dataSourceFiles); EnsureCache(DataFileEntries, dataSourceFiles, (string file) => ReadDataEntries(file)); DataLoading.LoadFromFiles(dataSourceFiles, DataFileEntries); } } private static void HandlePrefabFileChange(string path, string? oldPath, Yaml.FileChangeType type) { if (Helper.IsClient()) { return; } path = NormalizePath(path); oldPath = ((oldPath == null) ? null : NormalizePath(oldPath)); if (!IsPrefabPath(path) && (oldPath == null || !IsPrefabPath(oldPath))) { return; } if (oldPath != null && oldPath != path) { PrefabFileEntries.Remove(oldPath); DataFileEntries.Remove(oldPath); ConfigFileEntries.Remove(oldPath); } if (type == Yaml.FileChangeType.Deleted) { PrefabFileEntries.Remove(path); DataFileEntries.Remove(path); ConfigFileEntries.Remove(path); } else { LoadPrefabFile(path); } List<string> patternFiles = GetPatternFiles(Yaml.BaseDirectory, "expand_prefabs*.yaml"); patternFiles.Reverse(); PruneStaleCache(PrefabFileEntries, patternFiles); PruneStaleCache(ConfigFileEntries, patternFiles); foreach (string item in patternFiles) { if (!PrefabFileEntries.ContainsKey(item) || !ConfigFileEntries.ContainsKey(item) || !DataFileEntries.ContainsKey(item)) { LoadPrefabFile(item); } } List<string> dataSourceFiles = GetDataSourceFiles(); PruneStaleCache(DataFileEntries, dataSourceFiles); EnsureCache(DataFileEntries, dataSourceFiles, (string file) => ReadDataEntries(file)); DataLoading.LoadFromFiles(dataSourceFiles, DataFileEntries); ConfigManager.LoadFromFiles(patternFiles, ConfigFileEntries); Loading.LoadFromFiles(patternFiles, PrefabFileEntries); } public static bool IsPrefabPath(string path, string baseDirectory, string prefabPattern) { if (IsYaml(path) && IsInFolder(path, baseDirectory)) { return MatchesPattern(path, prefabPattern); } return false; } public static bool IsPrefabPath(string path) { return IsPrefabPath(path, Yaml.BaseDirectory, "expand_prefabs*.yaml"); } public static bool IsTrackedDataPath(string path, string gamePath, string profilePath, string baseDirectory, string dataPattern, string prefabPattern) { if (!IsYaml(path)) { return false; } if (IsInFolder(path, gamePath)) { return true; } if (IsInFolder(path, profilePath)) { return true; } if (IsInFolder(path, baseDirectory)) { if (!MatchesPattern(path, dataPattern)) { return MatchesPattern(path, prefabPattern); } return true; } return false; } public static bool IsTrackedDataPath(string path) { return IsTrackedDataPath(path, DataGamePath, DataProfilePath, Yaml.BaseDirectory, "expand_data*.yaml", "expand_prefabs*.yaml"); } public static void PruneStaleCache<T>(Dictionary<string, T> cache, List<string> files) { HashSet<string> hashSet = files.ToHashSet<string>(StringComparer.OrdinalIgnoreCase); foreach (string item in cache.Keys.ToList()) { if (!hashSet.Contains(item)) { cache.Remove(item); } } } public static void EnsureCache<T>(Dictionary<string, T> cache, List<string> files, Func<string, T> loader) { foreach (string file in files) { if (!cache.ContainsKey(file)) { cache[file] = loader(file); } } } private static void LoadPrefabFile(string file) { Yaml.MixedFileEntries mixedFileEntries = (File.Exists(file) ? Yaml.ReadMixedFile(file) : new Yaml.MixedFileEntries()); PrefabFileEntries[file] = mixedFileEntries.ScriptEntries; DataFileEntries[file] = mixedFileEntries.DataEntries; ConfigFileEntries[file] = mixedFileEntries.ConfigEntries; } public static List<DataYaml> ReadDataEntries(string file) { if (!File.Exists(file)) { return new List<DataYaml>(); } return Yaml.ReadMixedFile(file).DataEntries; } } internal static class FilterShorthand { public static string Normalize(string yaml) { //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_000c: Expected O, but got Unknown //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0019: Expected O, but got Unknown Parser val = new Parser((TextReader)new StringReader(yaml)); using StringWriter stringWriter = new StringWriter(); Emitter emitter = new Emitter((TextWriter)stringWriter); val.MoveNext(); while (val.Current != null) { WriteNode((IParser)(object)val, (IEmitter)(object)emitter); } return stringWriter.ToString(); } private static void WriteNode(IParser parser, IEmitter emitter) { //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0062: Expected O, but got Unknown //IL_0064: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0080: Unknown result type (might be due to invalid IL or missing references) //IL_0091: Unknown result type (might be due to invalid IL or missing references) //IL_009b: Expected O, but got Unknown //IL_00c8: Unknown result type (might be due to invalid IL or missing references) //IL_00ce: Invalid comparison between Unknown and I4 //IL_00d1: 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_00fc: Unknown result type (might be due to invalid IL or missing references) //IL_0101: Unknown result type (might be due to invalid IL or missing references) //IL_0108: Unknown result type (might be due to invalid IL or missing references) //IL_0112: Expected O, but got Unknown //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_0124: Expected O, but got Unknown if (parser.Current is MappingStart) { Copy(parser, emitter); while (!(parser.Current is MappingEnd)) { ParsingEvent current = parser.Current; Scalar val = (Scalar)(object)((current is Scalar) ? current : null); int num; if (val != null) { if (!(val.Value == "filter")) { num = ((val.Value == "bannedFilter") ? 1 : 0); if (num == 0) { goto IL_00a4; } } else { num = 1; } Scalar val2 = (Scalar)parser.Current; emitter.Emit((ParsingEvent)new Scalar(((NodeEvent)val2).Anchor, ((NodeEvent)val2).Tag, val2.Value + "s", val2.Style, val2.IsPlainImplicit, val2.IsQuotedImplicit)); parser.MoveNext(); goto IL_00ab; } num = 0; goto IL_00a4; IL_00a4: WriteNode(parser, emitter); goto IL_00ab; IL_00ab: ParsingEvent current2 = parser.Current; Scalar val3 = (Scalar)(object)((current2 is Scalar) ? current2 : null); int num2; if (val3 != null) { if (val3.Value.Length == 0 && (int)val3.Style == 1) { TagName tag = ((NodeEvent)val3).Tag; num2 = ((!((TagName)(ref tag)).IsEmpty) ? 1 : 0); } else { num2 = 1; } } else { num2 = 0; } bool flag = (byte)num2 != 0; if (num != 0 && (flag || parser.Current is AnchorAlias)) { emitter.Emit((ParsingEvent)new SequenceStart(AnchorName.Empty, TagName.Empty, true, (SequenceStyle)1)); WriteNode(parser, emitter); emitter.Emit((ParsingEvent)new SequenceEnd()); } else { WriteNode(parser, emitter); } } Copy(parser, emitter); } else if (parser.Current is SequenceStart) { Copy(parser, emitter); while (!(parser.Current is SequenceEnd)) { WriteNode(parser, emitter); } Copy(parser, emitter); } else { Copy(parser, emitter); } } private static void Copy(IParser parser, IEmitter emitter) { //IL_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Invalid comparison between Unknown and I4 //IL_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) //IL_004a: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_005d: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Expected O, but got Unknown if (parser.Current == null) { throw new YamlException("Unexpected end of YAML while normalizing filter shorthand."); } ParsingEvent current = parser.Current; Scalar val = (Scalar)(object)((current is Scalar) ? current : null); if (val != null && val.Value.Length == 0 && (int)val.Style == 1) { TagName tag = ((NodeEvent)val).Tag; if (((TagName)(ref tag)).IsEmpty) { emitter.Emit((ParsingEvent)new Scalar(((NodeEvent)val).Anchor, ((NodeEvent)val).Tag, "null", (ScalarStyle)1, true, false)); goto IL_0075; } } emitter.Emit(parser.Current); goto IL_0075; IL_0075: parser.MoveNext(); } } public class Log { private static ManualLogSource Logger; public static void Init(ManualLogSource logger) { Logger = logger; } public static void Error(string message) { Logger.LogError((object)message); } public static void Warning(string message) { Logger.LogWarning((object)message); } public static void Info(string message) { Logger.LogInfo((object)message); } public static void Debug(string message) { Logger.LogDebug((object)message); } } public class ServerClient { private static bool IsPatched = false; private static PlayerInfo? client; private static string name = "Server"; public static PlayerInfo Client { get { //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_002a: 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_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) PlayerInfo valueOrDefault = client.GetValueOrDefault(); if (!client.HasValue) { valueOrDefault = CreatePlayerInfo(); client = valueOrDefault; return valueOrDefault; } return valueOrDefault; } } public static void Patch(Harmony harmony, bool shouldPatch) { if (shouldPatch && !IsPatched) { DoPatch(harmony); } if (!shouldPatch && IsPatched) { DoUnpatch(harmony); } } private static void DoPatch(Harmony harmony) { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0045: Expected O, but got Unknown //IL_0077: Unknown result type (might be due to invalid IL or missing references) //IL_0085: Expected O, but got Unknown IsPatched = true; MethodInfo methodInfo = AccessTools.Method(typeof(ZNet), "TryGetPlayerByPlatformUserID", (Type[])null, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(typeof(ServerClient), "RecognizeServerClient", (Type[])null, (Type[])null); harmony.Patch((MethodBase)methodInfo, (HarmonyMethod)null, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); methodInfo = AccessTools.Method(typeof(ZNet), "SendPlayerList", (Type[])null, (Type[])null); methodInfo2 = AccessTools.Method(typeof(ServerClient), "SendPlayerListPrefix", (Type[])null, (Type[])null); harmony.Patch((MethodBase)methodInfo, new HarmonyMethod(methodInfo2), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null); } private static void DoUnpatch(Harmony harmony) { IsPatched = false; MethodInfo methodInfo = AccessTools.Method(typeof(ZNet), "TryGetPlayerByPlatformUserID", (Type[])null, (Type[])null); MethodInfo methodInfo2 = AccessTools.Method(typeof(ServerClient), "RecognizeServerClient", (Type[])null, (Type[])null); harmony.Unpatch((MethodBase)methodInfo, methodInfo2); methodInfo = AccessTools.Method(typeof(ZNet), "SendPlayerList", (Type[])null, (Type[])null); methodInfo2 = AccessTools.Method(typeof(ServerClient), "SendPlayerListPrefix", (Type[])null, (Type[])null); harmony.Unpatch((MethodBase)methodInfo, methodInfo2); } private static bool RecognizeServerClient(bool result, PlatformUserID platformUserID, ref PlayerInfo playerInfo) { //IL_0005: 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_000b: Unknown result type (might be due to invalid IL or missing references) //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_001f: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Unknown result type (might be due to invalid IL or missing references) if (result) { return result; } if (platformUserID != Client.m_userInfo.m_id) { return result; } playerInfo = Client; return true; } private static bool SendPlayerListPrefix(ZNet __instance) { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) //IL_005c: Unknown result type (might be due to invalid IL or missing references) //IL_0063: Expected O, but got Unknown //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Unknown result type (might be due to invalid IL or missing references) //IL_006a: Unknown result type (might be due to invalid IL or missing references) //IL_0109: Unknown result type (might be due to invalid IL or missing references) //IL_010e: 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_009f: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Unknown result type (might be due to invalid IL or missing references) //IL_00a8: Unknown result type (might be due to invalid IL or missing references) __instance.UpdatePlayerList(); if (__instance.m_peers.Count <= 0) { return false; } foreach (ZNetPeer peer in __instance.m_peers) { if (!peer.IsReady()) { continue; } Vector3 center = peer.m_refPos; ZDO zDO = ZDOMan.instance.GetZDO(peer.m_characterID); if (zDO != null) { center = zDO.m_position; } ZPackage val = new ZPackage(); if (NPCManager.IsEnabled) { List<NPCManager.NPCSelection> list = NPCManager.Search(center); val.Write(__instance.m_players.Count + 1 + list.Count); foreach (PlayerInfo player in __instance.m_players) { WritePlayer(val, player); } Write(val); if (list.Count > 0) { NPCManager.WriteProfiles(val, list); } } else { val.Write(__instance.m_players.Count + 1); foreach (PlayerInfo player2 in __instance.m_players) { WritePlayer(val, player2); } Write(val); } peer.m_rpc.Invoke("PlayerList", new object[1] { val }); } __instance.UpdatePlayerHistory(); return false; } private static void WritePlayer(ZPackage pkg, PlayerInfo player) { //IL_0001: 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_000e: 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_0031: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Unknown result type (might be due to invalid IL or missing references) pkg.Write(player.m_name); pkg.Write(player.m_characterID); ((CrossNetworkUserInfo)(ref player.m_userInfo)).Write(pkg); pkg.Write(player.m_publicPosition); if (player.m_publicPosition) { pkg.Write(player.m_position); } } public static void SetName(string value) { name = value; client = null; } private static PlayerInfo CreatePlayerInfo() { //IL_0002: 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_0021: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_0032: 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_0054: 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_0064: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_006e: Unknown result type (might be due to invalid IL or missing references) return new PlayerInfo { m_name = name, m_characterID = new ZDOID(ZDOMan.GetSessionID(), uint.MaxValue), m_userInfo = new CrossNetworkUserInfo { m_id = GetServerUserId(), m_displayName = name, m_serverAssignedDisplayName = name }, m_publicPosition = false, m_position = Vector3.zero }; } private static PlatformUserID GetServerUserId() { //IL_0075: Unknown result type (might be due to invalid IL or missing references) //IL_007b: Invalid comparison between Unknown and I4 //IL_0044: 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_00b7: Unknown result type (might be due to invalid IL or missing references) //IL_00cb: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Unknown result type (might be due to invalid IL or missing references) //IL_00ac: Unknown result type (might be due to invalid IL or missing references) //IL_008b: Unknown result type (might be due to invalid IL or missing references) //IL_00d1: Unknown result type (might be due to invalid IL or missing references) try { string text = (Type.GetType("Steamworks.SteamGameServer, com.rlabrecque.steamworks.net", throwOnError: false)?.GetMethod("GetSteamID"))?.Invoke(null, null)?.ToString(); if (!string.IsNullOrEmpty(text)) { return new PlatformUserID(ZNet.instance.m_steamPlatform, text); } } catch { } string text2 = ZPlayFabMatchmaking.m_instance?.m_serverData?.remotePlayerId; if ((int)ZNet.m_onlineBackend == 1 && !string.IsNullOrEmpty(text2)) { return new PlatformUserID("playfab", text2); } if (ZNet.instance.m_hostSocket == null) { return new PlatformUserID(ZNet.instance.m_steamPlatform, "Server"); } return new PlatformUserID(ZNet.instance.m_steamPlatform, ZNet.instance.m_hostSocket.GetHostName()); } public static void Write(ZPackage pkg) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0020: 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) pkg.Write(Client.m_name); pkg.Write(Client.m_characterID); PlayerInfo val = Client; ((CrossNetworkUserInfo)(ref val.m_userInfo)).Write(pkg); pkg.Write(false); } } public class Yaml { public enum FileChangeType { Created, Changed, Renamed, Deleted } public class MixedFileEntries { public List<RuleYaml> ScriptEntries = new List<RuleYaml>(); public List<DataYaml> DataEntries = new List<DataYaml>(); public List<ConfigYaml> ConfigEntries = new List<ConfigYaml>(); } private class MixedSplit { public List<string> ScriptLines = new List<string>(); public List<string> DataLines = new List<string>(); public List<string> ConfigLines = new List<string>(); } public static string BaseDirectory = Path.Combine(Paths.ConfigPath, "expand_world"); public static string BackupDirectory = Path.Combine(Paths.ConfigPath, "expand_world_backups"); public static List<T> Read<T>(string pattern, bool migrate) { if (!Directory.Exists(BaseDirectory)) { Directory.CreateDirectory(BaseDirectory); } return Read<T>(Directory.GetFiles(BaseDirectory, pattern, SearchOption.AllDirectories).Reverse().ToList(), migrate); } public static List<T> Read<T>(List<string> files, bool migrate) { List<T> list = new List<T>(); foreach (string file in files) { try { string raw = (migrate ? PreParse(File.ReadAllLines(file)) : File.ReadAllText(file)); list.AddRange(Deserialize<T>(raw, file)); } catch (Exception ex) { Log.Error("Error reading " + Path.GetFileName(file) + ": " + ex.Message); } } return list; } public static List<T> ReadFile<T>(string file, bool migrate) { try { return Deserialize<T>(migrate ? PreParse(File.ReadAllLines(file)) : File.ReadAllText(file), file); } catch (Exception ex) { Log.Error("Error reading " + Path.GetFileName(file) + ": " + ex.Message); return new List<T>(); } } public static MixedFileEntries ReadMixedFile(string file) { try { MixedSplit mixedSplit = SplitMixed(File.ReadAllLines(file)); MixedFileEntries mixedFileEntries = new MixedFileEntries(); if (mixedSplit.ScriptLines.Count > 0) { string raw = PreParse(mixedSplit.ScriptLines.ToArray()); mixedFileEntries.ScriptEntries = Deserialize<RuleYaml>(raw, file); mixedFileEntries.DataEntries.AddRange(DataField.Hoist(mixedFileEntries.ScriptEntries, file)); } if (mixedSplit.DataLines.Count > 0) { string raw2 = string.Join("\n", mixedSplit.DataLines); mixedFileEntries.DataEntries.InsertRange(0, Deserialize<DataYaml>(raw2, file)); } if (mixedSplit.ConfigLines.Count > 0) { string raw3 = string.Join("\n", mixedSplit.ConfigLines); mixedFileEntries.ConfigEntries = Deserialize<ConfigYaml>(raw3, file); } return mixedFileEntries; } catch (Exception ex) { Log.Error("Error reading " + Path.GetFileName(file) + ": " + ex.Message); return new MixedFileEntries(); } } private static MixedSplit SplitMixed(string[] lines) { MixedSplit mixedSplit = new MixedSplit(); List<string> list = new List<string>(); List<string> list2 = new List<string>(); foreach (string text in lines) { if (IsTopLevelListItem(text)) { if (list2.Count > 0) { AddMixedBlock(mixedSplit, list2); } list2 = new List<string>(); if (list.Count > 0) { list2.AddRange(list); list.Clear(); } list2.Add(text); } else if (list2.Count == 0) { list.Add(text); } else { list2.Add(text); } } if (list2.Count > 0) { AddMixedBlock(mixedSplit, list2); } return mixedSplit; } private static void AddMixedBlock(MixedSplit split, List<string> block) { if (IsConfigBlock(block)) { split.ConfigLines.AddRange(block); } else if (IsDataBlock(block)) { split.DataLines.AddRange(block); } else { split.ScriptLines.AddRange(block); } } private static bool IsTopLevelListItem(string line) { return ((line.Length > 0 && line[0] == '\ufeff') ? line.Substring(1) : line).StartsWith("- "); } private static bool IsConfigBlock(List<string> block) { foreach (string item in block) { string text = ParseBlockKey(item); if (text != null) { return text.Equals("config", StringComparison.OrdinalIgnoreCase); } } return false; } private static bool IsDataBlock(List<string> block) { foreach (string item in block) { string text = ParseBlockKey(item); if (text != null) { return text.Equals("name", StringComparison.OrdinalIgnoreCase) || text.Equals("valueGroup", StringComparison.OrdinalIgnoreCase) || text.Equals("value", StringComparison.OrdinalIgnoreCase); } } return false; } private static string? ParseBlockKey(string line) { string text = line.Split(new char[1] { '#' })[0].Trim(); if (text.Length == 0) { return null; } if (text.StartsWith("- ")) { text = text.Substring(2).TrimStart(Array.Empty<char>()); } if (text.Length == 0 || text.StartsWith("-")) { return null; } int num = text.IndexOf(':'); if (num <= 0) { return null; } string text2 = text.Substring(0, num).Trim(); if (text2.Length == 0) { return null; } if (text2.StartsWith("\"") && text2.EndsWith("\"") && text2.Length > 1) { text2 = text2.Substring(1, text2.Length - 2); } return text2; } private static string PreParse(string[] lines) { return FilterShorthand.Normalize(string.Join("\n", lines)); } public static void SetupWatcher(ConfigFile config) { FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(Path.GetDirectoryName(config.ConfigFilePath), Path.GetFileName(config.ConfigFilePath)); fileSystemWatcher.Changed += delegate(object s, FileSystemEventArgs e) { ReadConfigValues(e.FullPath, config); }; fileSystemWatcher.Created += delegate(object s, FileSystemEventArgs e) { ReadConfigValues(e.FullPath, config); }; fileSystemWatcher.Renamed += delegate(object s, RenamedEventArgs e) { ReadConfigValues(e.FullPath, config); }; fileSystemWatcher.IncludeSubdirectories = true; fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher.EnableRaisingEvents = true; } private static void ReadConfigValues(string path, ConfigFile config) { if (!File.Exists(path) || (ConfigManager.IsSelfWrite && config == Config.Main)) { return; } BackupFile(path, overwrite: true); try { config.Reload(); } catch { Log.Error("There was an issue loading your " + config.ConfigFilePath); Log.Error("Please check your config entries for spelling and format!"); } } public static void SetupWatcher(string pattern, Action<string> action) { SetupWatcherSub(Paths.ConfigPath, pattern, action); } public static void SetupWatcher(string folder, string pattern, Action action, bool overwriteBackup) { SetupWatcherSub(folder, pattern, delegate(string file) { BackupFile(file, overwriteBackup); action(); }); } public static void SetupWatcher(string folder, string pattern, Action<string, string?, FileChangeType> action, bool overwriteBackup) { SetupWatcherSub(folder, pattern, delegate(string path, string? oldPath, FileChangeType type) { if (type != FileChangeType.Deleted && path != "") { BackupFile(path, overwriteBackup); } action(path, oldPath, type); }); } public static void SetupWatcher(string pattern, Action action, bool overwriteBackup) { SetupWatcherSub(BaseDirectory, pattern, delegate(string file) { BackupFile(file, overwriteBackup); action(); }); } public static void SetupWatcher(string pattern, Action<string, string?, FileChangeType> action, bool overwriteBackup) { SetupWatcherSub(BaseDirectory, pattern, delegate(string path, string? oldPath, FileChangeType type) { if (type != FileChangeType.Deleted && path != "") { BackupFile(path, overwriteBackup); } action(path, oldPath, type); }); } private static void SetupWatcherSub(string folder, string pattern, Action<string> action) { FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(folder, pattern); fileSystemWatcher.Created += delegate(object s, FileSystemEventArgs e) { action(e.FullPath); }; fileSystemWatcher.Changed += delegate(object s, FileSystemEventArgs e) { action(e.FullPath); }; fileSystemWatcher.Renamed += delegate(object s, RenamedEventArgs e) { action(e.FullPath); }; fileSystemWatcher.Deleted += delegate(object s, FileSystemEventArgs e) { action(e.FullPath); }; fileSystemWatcher.IncludeSubdirectories = true; fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher.EnableRaisingEvents = true; } private static void SetupWatcherSub(string folder, string pattern, Action<string, string?, FileChangeType> action) { FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(folder, pattern); fileSystemWatcher.Created += delegate(object s, FileSystemEventArgs e) { action(e.FullPath, null, FileChangeType.Created); }; fileSystemWatcher.Changed += delegate(object s, FileSystemEventArgs e) { action(e.FullPath, null, FileChangeType.Changed); }; fileSystemWatcher.Renamed += delegate(object s, RenamedEventArgs e) { action(e.FullPath, e.OldFullPath, FileChangeType.Renamed); }; fileSystemWatcher.Deleted += delegate(object s, FileSystemEventArgs e) { action(e.FullPath, null, FileChangeType.Deleted); }; fileSystemWatcher.IncludeSubdirectories = true; fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher.EnableRaisingEvents = true; } private static void SetupWatcherSub(string folder, string pattern, Action action) { FileSystemWatcher fileSystemWatcher = new FileSystemWatcher(folder, pattern); fileSystemWatcher.Created += delegate { action(); }; fileSystemWatcher.Changed += delegate { action(); }; fileSystemWatcher.Renamed += delegate { action(); }; fileSystemWatcher.Deleted += delegate { action(); }; fileSystemWatcher.IncludeSubdirectories = true; fileSystemWatcher.SynchronizingObject = ThreadingHelper.SynchronizingObject; fileSystemWatcher.EnableRaisingEvents = true; } public static void BackupFile(string path, bool overwrite) { if (File.Exists(path)) { if (!Directory.Exists(BackupDirectory)) { Directory.CreateDirectory(BackupDirectory); } string text = DateTime.Now.ToString("yyyy-MM-dd"); string path2 = Path.GetFileNameWithoutExtension(path) + "_" + text + Path.GetExtension(path) + ".bak"; string text2 = Path.Combine(BackupDirectory, path2); if (overwrite) { File.Copy(path, text2, overwrite: true); } else if (!File.Exists(text2)) { File.Copy(path, text2); } } } public static void Init() { if (!Directory.Exists(BaseDirectory)) { Directory.CreateDirectory(BaseDirectory); } } private static IDeserializer Deserializer() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Expected O, but got Unknown return ((BuilderSkeleton<DeserializerBuilder>)(object)((BuilderSkeleton<DeserializerBuilder>)new DeserializerBuilder()).WithNamingConvention(CamelCaseNamingConvention.Instance)).WithTypeConverter((IYamlTypeConverter)(object)new FlexibleYamlConverter()).Build(); } private static IDeserializer DeserializerUnSafe() { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Expected O, but got Unknown return ((BuilderSkeleton<DeserializerBuilder>)(object)((BuilderSkeleton<DeserializerBuilder>)new DeserializerBuilder()).WithNamingConvention(CamelCaseNamingConvention.Instance)).WithTypeConverter((IYamlTypeConverter)(object)new FlexibleYamlConverter()).IgnoreUnmatchedProperties().Build(); } private static List<T> Deserialize<T>(string raw, string file) { try { return Deserializer().Deserialize<List<T>>(raw) ?? new List<T>(); } catch (Exception ex) { Log.Error(Path.GetFileName(file) + ": " + ex.Message); try { return DeserializerUnSafe().Deserialize<List<T>>(raw) ?? new List<T>(); } catch (Exception) { return new List<T>(); } } } public static Dictionary<string, string> DeserializeData(string raw) { try { return Deserializer().Deserialize<Dictionary<string, string>>(raw) ?? new Dictionary<string, string>(); } catch { try { return DeserializerUnSafe().Deserialize<Dictionary<string, string>>(raw) ?? new Dictionary<string, string>(); } catch (Exception) { return new Dictionary<string, string>(); } } } public static string SerializeData(Dictionary<string, string> data) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Expected O, but got Unknown return ((BuilderSkeleton<SerializerBuilder>)new SerializerBuilder()).WithNamingConvention(CamelCaseNamingConvention.Instance).Build().Serialize((object)data); } } } namespace Common { public static class FloatCompare { public static bool Approx(float a, float b) { return Mathf.Abs(a - b) < 0.001f; } public static bool ApproxBetween(float a, float min, float max) { if (min - 0.001f <= a) { return a <= max + 0.001f; } return false; } } public static class Formatting { public static string Format(float value) { return value.ToString("0.#####", NumberFormatInfo.InvariantInfo); } public static string Format(double value) { return value.ToString("0.#####", NumberFormatInfo.InvariantInfo); } public static string FormatPos(Vector3 value) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) return Format(value.x) + "," + Format(value.z) + "," + Format(value.y); } public static string FormatRot(Vector3 value) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Unknown result type (might be due to invalid IL or missing references) //IL_0034: Unknown result type (might be due to invalid IL or missing references) return Format(value.y) + "," + Format(value.x) + "," + Format(value.z); } } public class ValueRange<T> { public T Min; public T Max; public bool Uniform = true; public ValueRange(T value) { Min = value; Max = value; } public ValueRange(T min, T max) { Min = min; Max = max; } } public static class Parse { private static Dictionary<string, Color> Paints = new Dictionary<string, Color> { { "grass", Color.black }, { "patches", new Color(0f, 0.75f, 0f) }, { "grass_dark", new Color(0.6f, 0.5f, 0f) }, { "dirt", Color.red }, { "cultivated", Color.green }, { "paved", Color.blue }, { "paved_moss", new Color(0f, 0f, 0.5f) }, { "paved_dirt", new Color(1f, 0f, 0.5f) }, { "paved_dark", new Color(0f, 1f, 0.5f) } }; public static List<string> ToList(string str, bool removeEmpty = true) { string[] array = Split(str, removeEmpty); List<string> list = new List<string>(array.Length); list.AddRange(array); return list; } public static string[] ToArr(string str, bool removeEmpty = true) { string[] array = Split(str, removeEmpty); int num = 0; string[] array2 = new string[array.Length]; string[] array3 = array; foreach (string text in array3) { array2[num] = text; num++; } return array2; } public static Vector2i Vector2Int(string arg) { //IL_0024: Unknown result type (might be due to invalid IL or missing references) string[] array = SplitWithEmpty(arg); return new Vector2i(Int(array[0]), (array.Length > 1) ? Int(array[1]) : 0); } public static int Int(string arg, int defaultValue = 0) { if (!TryInt(arg, out var result)) { return defaultValue; } return result; } public static uint UInt(string arg, uint defaultValue = 0u) { if (!TryUInt(arg, out var result)) { return defaultValue; } return result; } public static long Long(string arg, long defaultValue = 0L) { if (!long.TryParse(arg, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { return defaultValue; } return result; } public static bool TryLong(string arg, out long result) { return long.TryParse(arg, NumberStyles.Integer, CultureInfo.InvariantCulture, out result); } public static int Int(string[] args, int index, int defaultValue = 0) { if (args.Length <= index) { return defaultValue; } return Int(args[index], defaultValue); } public static bool TryUInt(string arg, out uint result) { return uint.TryParse(arg, NumberStyles.Integer, CultureInfo.InvariantCulture, out result); } public static bool TryInt(string arg, out int result) { return int.TryParse(arg, NumberStyles.Integer, CultureInfo.InvariantCulture, out result); } public static float Float(string arg, float defaultValue = 0f) { if (!TryFloat(arg, out var result)) { return defaultValue; } return result; } public static float Float(string[] args, int index, float defaultValue = 0f) { if (args.Length <= index) { return defaultValue; } return Float(args[index], defaultValue); } public static bool TryFloat(string arg, out float result) { return float.TryParse(arg, NumberStyles.Float, CultureInfo.InvariantCulture, out result); } public static bool TryDistanceAngle(string arg, out Vector3 vector) { return TryDistanceAngle(Split(arg), out vector); } public static bool TryDistanceAngle(string[] values, out Vector3 vector) { //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) vector = Vector3.zero; if (values.Length < 2 || values.Length > 3) { return false; } if (values[1] == null || !HasAngleSuffix(values[1].Trim())) { return false; } if (!TryDistanceAngle(values[0], values[1], out vector)) { return false; } if (values.Length > 2 && !TryFloat(values[2], out vector.y)) { return false; } return true; } private static bool TryDistanceAngle(string distanceValue, string angleValue, out Vector3 vector) { //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_0039: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Unknown result type (might be due to invalid IL or missing references) vector = Vector3.zero; if (!TryFloat(distanceValue, out var result)) { return false; } if (!TryAngleRadians(angleValue, out var radians)) { return false; } vector = new Vector3(Mathf.Cos(radians) * result, 0f, Mathf.Sin(radians) * result); return true; } private static bool HasAngleSuffix(string arg) { if (!arg.EndsWith("deg", StringComparison.OrdinalIgnoreCase)) { return arg.EndsWith("rad", StringComparison.OrdinalIgnoreCase); } return true; } public static bool TryAngleRadians(string arg, out float radians) { radians = 0f; if (arg == null) { return false; } string text = arg.Trim(); if (text.EndsWith("deg", StringComparison.OrdinalIgnoreCase)) { if (!TryFloat(text.Substring(0, text.Length - 3).Trim(), out var result)) { return false; } radians = result * ((float)Math.PI / 180f); return true; } if (text.EndsWith("rad", StringComparison.OrdinalIgnoreCase)) { if (!TryFloat(text.Substring(0, text.Length - 3).Trim(), out radians)) { return false; } return true; } return TryFloat(text, out radians); } public static bool TryAngleDegrees(string arg, out float degrees) { degrees = 0f; if (arg == null) { return false; } string text = arg.Trim(); if (text.EndsWith("deg", StringComparison.OrdinalIgnoreCase)) { return TryFloat(text.Substring(0, text.Length - 3).Trim(), out degrees); } if (text.EndsWith("rad", StringComparison.OrdinalIgnoreCase)) { if (!TryFloat(text.Substring(0, text.Length - 3).Trim(), out var result)) { return false; } degrees = result * 57.29578f; return true; } return TryFloat(text, out degrees); } public static bool TryBoolean(string arg, out bool result) { result = false; if (arg.ToLowerInvariant() == "true") { result = true; return true; } if (arg.ToLowerInvariant() == "false") { return true; } return false; } public static Quaternion AngleYXZ(string arg) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Unknown result type (might be due to invalid IL or missing references) return AngleYXZ(Split(arg), 0, Vector3.zero); } public static Quaternion AngleYXZ(string[] args, int index) { //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) return AngleYXZ(args, index, Vector3.zero); } public static Quaternion AngleYXZ(string[] args, int index, Vector3 defaultValue) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000a: 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_0036: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_0047: Unknown result type (might be due to invalid IL or missing references) Vector3 zero = Vector3.zero; zero.y = Float(args, index, defaultValue.y); zero.x = Float(args, index + 1, defaultValue.x); zero.z = Float(args, index + 2, defaultValue.z); return Quaternion.Euler(zero); } public static string[] Split(string arg, bool removeEmpty = true, char split = ',') { List<string> list; if (!removeEmpty) { list = new List<string>(); list.AddRange(from s in arg.Split(new char[1] { split }) select s.Trim()); return list.ToArray(); } list = new List<string>(); list.AddRange(from s in arg.Split(new char[1] { split }) select s.Trim() into s where s != "" select s); return list.ToArray(); } public static KeyValuePair<string, string> Kvp(string str, char separator = ',') { int num = str.IndexOf(separator); if (num < 0) { return new KeyValuePair<string, string>(str, ""); } return new KeyValuePair<string, string>(str.Substring(0, num), str.Substring(num + 1).Trim()); } public static bool TryKvp(string str, out KeyValuePair<string, string> kvp, char separator = ',') { kvp = Kvp(str, separator); return kvp.Value != ""; } public static string[] SplitWithEmpty(string arg, char split = ',') { List<string> list = new List<string>(); list.AddRange(from s in arg.Split(new char[1] { split }) select s.Trim()); return list.ToArray(); } public static string[] SplitWithEscape(string arg, char separator = ',') { List<string> list = new List<string>(); string[] array = arg.Split(new char[1] { separator }); for (int i = 0; i < array.Length; i++) { string text = array[i].TrimStart(Array.Empty<char>()); if (text.StartsWith("\"")) { array[i] = text.Substring(1); int j; for (j = i; j < array.Length; j++) { text = array[j].TrimEnd(Array.Empty<char>()); if (text.EndsWith("\"")) { array[j] = text.Substring(0, text.Length - 1); break; } } list.Add(string.Join(separator.ToString(), array.Skip(i).Take(j - i + 1))); i = j; } else { list.Add(array[i].Trim()); } } return list.ToArray(); } public static string Name(string arg) { return arg.Split(new char[1] { ':' })[0]; } public static Vector3 VectorXZY(string arg) { //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) return VectorXZY(arg, Vector3.zero); } public static Vector3 VectorXZY(string arg, Vector3 defaultValue) { //IL_001d: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0017: Unknown result type (might be due to invalid IL or missing references) string[] array = Split(arg); if (!TryDistanceAngle(array, out var vector)) { return VectorXZY(array, 0, defaultValue); } return vector; } public static Vector3 VectorXZY(string[] args, int index) { //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) return VectorXZY(args, index, Vector3.zero); } public static Vector3 VectorXZY(string[] args, int index, Vector3 defaultValue) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_000a: 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_0036: 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) Vector3 zero = Vector3.zero; zero.x = Float(args, index, defaultValue.x); zero.z = Float(args, index + 1, defaultValue.z); zero.y = Float(args, index + 2, defaultValue.y); return zero; } public static Vector2 VectorXY(string arg) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0036: Unknown result type (might be due to invalid IL or missing references) Vector2 zero = Vector2.zero; string[] args = Split(arg); zero.x = Float(args, 0); zero.y = Float(args, 1); return zero; } public static Vector3 Scale(string args) { //IL_000a: Unknown result type (might be due to invalid IL or missing references) return Scale(Split(args), 0); } public static Vector3 Scale(string[] args) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) return Scale(args, 0); } public static Vector3 Scale(string[] args, int index) { //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) return SanityCheck(VectorXZY(args, index)); } private static Vector3 SanityCheck(Vector3 scale) { //IL_0000: 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_0033: 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_004d: 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) if (scale.x == 0f) { scale.x = 1f; } if (scale.y == 0f) { scale.y = scale.x; } if (scale.z == 0f) { scale.z = scale.x; } return scale; } public static ValueRange<string> StringRange(string arg) { string[] array = Split(arg, removeEmpty: true, ';'); if (array.Length > 1) { return new ValueRange<string>(array[0], array[1]); } return new ValueRange<string>(array[0], array[0]); } public static ValueRange<int> IntRange(string arg) { ValueRange<string> valueRange = StringRange(arg); return new ValueRange<int>(Int(valueRange.Min), Int(valueRange.Max)); } public static ValueRange<float> FloatRange(string arg) { ValueRange<string> valueRange = StringRange(arg); return new ValueRange<float>(Float(valueRange.Min), Float(valueRange.Max)); } public static ValueRange<long> LongRange(string arg) { ValueRange<string> valueRange = StringRange(arg); return new ValueRange<long>(Long(valueRange.Min, 0L), Long(valueRange.Max, 0L)); } public static int? IntNull(string arg) { if (int.TryParse(arg, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { return result; } return null; } public static int? IntNull(string[] args, int index) { if (args.Length <= index) { return null; } return IntNull(args[index]); } public static float? FloatNull(string arg) { if (float.TryParse(arg, NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { return result; } return null; } public static float? FloatNull(string[] args, int index) { if (args.Length <= index) { return null; } return FloatNull(args[index]); } public static long? LongNull(string[] args, int index) { if (args.Length <= index) { return null; } return LongNull(args[index]); } public static long? LongNull(string arg) { if (long.TryParse(arg, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result)) { return result; } return null; } public static Vector3? VectorXZYNull(string? arg) { if (arg != null) { return VectorXZYNull(Split(arg)); } return null; } public static Vector3? VectorXZYNull(string[] args) { //IL_000a: 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) if (TryDistanceAngle(args, out var vector)) { return vector; } float? num = FloatNull(args, 0); float? num2 = FloatNull(args, 2); float? num3 = FloatNull(args, 1); if (!num.HasValue && !num2.HasValue && !num3.HasValue) { return null; } return new Vector3(num.GetValueOrDefault(), num2.GetValueOrDefault(), num3.GetValueOrDefault()); } public static Quaternion? AngleYXZNull(string? arg) { if (arg != null) { return AngleYXZNull(Split(arg)); } return null; } public static Quaternion? AngleYXZNull(string[] values) { //IL_00d2: 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_0071: Unknown result type (might be due to invalid IL or missing references) if (values.Length >= 4) { float? num = FloatNull(values, 0); float? num2 = FloatNull(values, 1); float? num3 = FloatNull(values, 2); float? num4 = FloatNull(values, 3); if (!num.HasValue && !num2.HasValue && !num3.HasValue && !num4.HasValue) { return null; } return new Quaternion(num.GetValueOrDefault(), num2.GetValueOrDefault(), num3.GetValueOrDefault(), num4.GetValueOrDefault()); } float? num5 = FloatNull(values, 0); float? num6 = FloatNull(values, 1); float? num7 = FloatNull(values, 2); if (!num5.HasValue && !num6.HasValue && !num7.HasValue) { return null; } return Quaternion.Euler(new Vector3(num6.GetValueOrDefault(), num5.GetValueOrDefault(), num7.GetValueOrDefault())); } public static string String(string[] args, int index) { if (args.Length <= index) { return ""; } return args[index]; } public static int Hash(string[] args, int index) { if (args.Length <= index) { return 0; } return StringExtensionMethods.GetStableHashCode(args[index]); } public static bool Boolean(string[] args, int index) { if (args.Length > index) { return Boolean(args[index]); } return false; } public static bool Boolean(string arg) { return arg.ToLowerInvariant() == "true"; } public static ZDOID ZdoId(string arg) { //IL_0008: Unknown result type (might be due to invalid IL or missing references) //IL_0099: Unknown result type (might be due to invalid IL or missing references) //IL_00a1: Unknown result type (might be due to invalid IL or missing references) if (string.IsNullOrWhiteSpace(arg)) { return ZDOID.None; } string text = arg.Trim().Trim('(', ')', '[', ']', '{', '}'); string[] array = (from value in text.Split(new char[2] { ':', ',' }, StringSplitOptions.RemoveEmptyEntries) select value.Trim()).ToArray(); if (array.Length < 2) { array = text.Split((char[]?)null, StringSplitOptions.RemoveEmptyEntries); } if (array.Length < 2 || !long.TryParse(array[0], out var result) || !uint.TryParse(array[1], out var result2)) { return ZDOID.None; } return new ZDOID(result, result2); } public static HitData Hit(ZDO? zdo, string arg) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0011: 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_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001c: Expected O, but got Unknown //IL_0291: Unknown result type (might be due to invalid IL or missing references) //IL_0296: Unknown result type (might be due to invalid IL or missing references) //IL_02df: Unknown result type (might be due to invalid IL or missing references) //IL_02e4: Unknown result type (might be due to invalid IL or missing references) //IL_0313: Unknown result type (might be due to invalid IL or missing references) //IL_0318: Unknown result type (might be due to invalid IL or missing references) //IL_0391: 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) HitData val = new HitData { m_point = (zdo?.m_position ?? Vector3.zero) }; string[] array = Split(arg, removeEmpty: true, ' '); for (int i = 0; i < array.Length; i++) { KeyValuePair<string, string> keyValuePair = Kvp(array[i], '='); string key = keyValuePair.Key; string value = keyValuePair.Value; if (key == "damage") { val.m_damage.m_damage = Float(value); } if (key == "blunt") { val.m_damage.m_blunt = Float(value); } if (key == "slash") { val.m_damage.m_slash = Float(value); } if (key == "pierce") { val.m_damage.m_pierce = Float(value); } if (key == "chop") { val.m_damage.m_chop = Float(value); } if (key == "pickaxe") { val.m_damage.m_pickaxe = Float(value); } if (key == "fire") { val.m_damage.m_fire = Float(value); } if (key == "frost") { val.m_damage.m_frost = Float(value); } if (key == "lightning") { val.m_damage.m_lightning = Float(value); } if (key == "poison") { val.m_damage.m_poison = Float(value); } if (key == "spirit") { val.m_damage.m_spirit = Float(value); } if (key == "tier") { val.m_toolTier = (short)Int(value); } if (key == "force") { val.m_pushForce = Float(value); } if (key == "backstab") { val.m_backstabBonus = Float(value); } if (key == "stagger") { val.m_staggerMultiplier = Float(value); } if (key == "dodge") { val.m_dodgeable = Boolean(value); } if (key == "block") { val.m_blockable = Boolean(value); } if (key == "dir") { val.m_dir = VectorXZY(value); } if (key == "ranged") { val.m_ranged = Boolean(value); } if (key == "pvp") { val.m_ignorePVP = Boolean(value); } if (key == "pos") { val.m_point = VectorXZY(value); } if (key == "status") { val.m_statusEffectHash = StringExtensionMethods.GetStableHashCode(value); } if (key == "attacker") { val.m_attacker = ZdoId(value); } if (key == "skill") { val.m_skillLevel = Float(value); } if (key == "level") { val.m_itemLevel = (short)Int(value); } if (key == "world") { val.m_itemWorldLevel = (byte)Int(value); } if (key == "type") { val.m_hitType = (HitType)(Enum.TryParse<HitType>(value, ignoreCase: true, out HitType result) ? ((int)result) : 0); } if (key == "spot") { val.m_weakSpot = (short)Int(value); } } return val; } public static int EnumMessage(string arg) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected I4, but got Unknown if (!Enum.TryParse<MessageType>(arg, ignoreCase: true, out MessageType result)) { return Int(arg, 2); } return (int)result; } public static int EnumReason(string arg) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected I4, but got Unknown if (!Enum.TryParse<AggravatedReason>(arg, ignoreCase: true, out AggravatedReason result)) { return Int(arg); } return (int)result; } public static int EnumTrap(string arg) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected I4, but got Unknown if (!Enum.TryParse<TrapState>(arg, ignoreCase: true, out TrapState result)) { return Int(arg); } return (int)result; } public static int EnumDamageText(string arg) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected I4, but got Unknown if (!Enum.TryParse<TextType>(arg, ignoreCase: true, out TextType result)) { return Int(arg); } return (int)result; } public static int EnumTerrainPaint(string arg) { //IL_0013: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Expected I4, but got Unknown if (!Enum.TryParse<PaintType>(arg, ignoreCase: true, out PaintType result)) { return Int(arg); } return (int)result; } public static Color? Color(string arg, float defaultAlpha) { //IL_0016: 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) string key = arg.ToLowerInvariant(); if (Paints.TryGetValue(key, out var value)) { return value; } string[] array = Split(arg); if (array.Length < 3) { return null; } return new Color(Float(array[0]), Float(array[1]), Float(array[2]), (array.Length > 3) ? Float(array[3]) : defaultAlpha); } } public static class Wildcard { public static bool IsPattern(string value) { return value.IndexOf('*') >= 0; } public static bool Match(string value, string pattern, bool ignoreCase = false) { StringComparison comparisonType = (ignoreCase ? StringComparison.OrdinalIgnoreCase : StringComparison.Ordinal); if (string.Equals(value, pattern, comparisonType)) { return true; } if (pattern == "") { return false; } if (pattern == "*") { return true; } bool flag = pattern[0] == '*'; bool flag2 = pattern[pattern.Length - 1] == '*'; if (flag && flag2) { return value.IndexOf(pattern.Substring(1, pattern.Length - 2), comparisonType) >= 0; } if (flag) { return value.EndsWith(pattern.Substring(1), comparisonType); } if (flag2) { return value.StartsWith(pattern.Substring(0, pattern.Length - 1), comparisonType); } int num = pattern.IndexOf('*'); if (num < 0) { return false; } if (value.Length >= pattern.Length - 1 && value.StartsWith(pattern.Substring(0, num), comparisonType)) { return value.EndsWith(pattern.Substring(num + 1), comparisonType); } return false; } } } namespace Data { public class Calculator { private sealed class DoubleParser(string expression) { private readonly string expression = expression; private int index; public double Parse() { double result = ParseExpression(); SkipWhiteSpace(); if (index != expression.Length) { throw new InvalidOperationException("Failed to parse expression: " + expression); } return result; } private double ParseExpression() { double num = ParseTerm(); while (true) { SkipWhiteSpace(); if (TryRead('+')) { num += ParseTerm(); continue; } if (!TryRead('-')) { break; } num -= ParseTerm(); } return num; } private double ParseTerm() { double num = ParseUnary(); while (true) { SkipWhiteSpace(); if (TryRead('*')) { num *= ParseUnary(); continue; } if (!TryRead('/')) { break; } num /= ParseUnary(); } return num; } private double ParseUnary() { SkipWhiteSpace(); if (TryRead('+')) { return ParseUnary(); } if (TryRead('-')) { return 0.0 - ParseUnary(); } return ParsePower(); } private double ParsePower() { double num = ParsePrimary(); SkipWhiteSpace(); if (TryRead('^')) { num = Math.Pow(num, ParseUnary()); } return num; } private double ParsePrimary() { SkipWhiteSpace(); if (TryRead('(')) { double result = ParseExpression(); SkipWhiteSpace(); if (!TryRead(')')) { throw new InvalidOperationException("Failed to parse expression: " + expression); } return result; } return ParseNumber(); } private double ParseNumber() { SkipWhiteSpace(); int num = index; bool flag = false; while (index < expression.Length && char.IsDigit(expression[index])) { flag = true; index++; } if (index < expression.Length && expression[index] == '.') { index++; while (index < expression.Length && char.IsDigit(expression[index])) { flag = true; index++; } } if (index < expression.Length && (expression[index] == 'e' || expression[index] == 'E')) { int num2 = index; index++; if (index < expression.Length && (expression[index] == '+' || expression[index] == '-')) { index++; } int num3 = index; while (index < expression.Length && char.IsDigit(expression[index])) { index++; } if (num3 == index) { index = num2; } } if (!flag) { throw new InvalidOperationException("Failed to parse expression: " + expression); } return double.Parse(expression.Substring(num, index - num), NumberFormatInfo.InvariantInfo); } private bool TryRead(char c) { if (index >= expression.Length || expression[index] != c) { return false; } index++; return true; } private void SkipWhiteSpace() { while (index < expression.Length && char.IsWhiteSpace(expression[index])) { index++; } } } private sealed class LongParser(string expression) { private readonly string expression = expression; private int index; public long Parse() { long result = ParseExpression(); SkipWhiteSpace(); if (index != expression.Length) { throw new InvalidOperationException("Failed to parse expression: " + expression); } return result; } private long ParseExpression() { long num = ParseTerm(); while (true) { SkipWhiteSpace(); if (TryRead('+')) { num += ParseTerm(); continue; } if (!TryRead('-')) { break; } num -= ParseTerm(); } return num; } private long ParseTerm() { long num = ParseUnary(); while (true) { SkipWhiteSpace(); if (TryRead('*')) { num *= ParseUnary(); continue; } if (!TryRead('/')) { break; } num /= ParseUnary(); } return num; } private long ParseUnary() { SkipWhiteSpace(); if (TryRead('+')) { return ParseUnary(); } if (TryRead('-')) { return -ParseUnary(); } return ParsePower(); } private long ParsePower() { long num = ParsePrimary(); SkipWhiteSpace(); if (TryRead('^')) { long num2 = ParseUnary(); if (num2 < 0) { throw new InvalidOperationException("Failed to parse expression: " + expression); } num = Pow(num, num2); } return num; } private long ParsePrimary() { SkipWhiteSpace(); if (TryRead('(')) { long result = ParseExpression(); SkipWhiteSpace(); if (!TryRead(')')) { throw new InvalidOperationException("Failed to parse expression: " + expression); } return result; } return ParseNumber(); } private long ParseNumber() { SkipWhiteSpace(); int num = index; while (index < expression.Length && char.IsDigit(expression[index])) { index++; } if (num == index) { throw new InvalidOperationException("Failed to parse expression: " + expression); } return long.Parse(expression.Substring(num, index - num), NumberFormatInfo.InvariantInfo); } private static long Pow(long value, long exponent) { long num = 1L; checked { while (exponent > 0) { if ((exponent & 1) == 1) { num *= value; } exponent >>= 1; if (exponent > 0) { value *= value; } } return num; } } private bool TryRead(char c) { if (index >= expression.Length || expression[index] != c) { return false; } index++; return true; } private void SkipWhiteSpace() { while (index < expression.Length && char.IsWhiteSpace(expression[index])) { index++; } } } public static Vector3 EvaluateVector3(string expression) { //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0014: Unknown result type (might be due to invalid IL or missing references) //IL_006d: Unknown result type (might be due to invalid IL or missing references) string[] array = Parse.Split(expression); if (Parse.TryDistanceAngle(array, out var vector)) { return vector; } Vector3 zero = Vector3.zero; zero.x = EvaluateFloat(array[0]).GetValueOrDefault(); if (array.Length > 1) { zero.z = EvaluateFloat(array[1]).GetValueOrDefault(); } if (array.Length > 2) { zero.y = EvaluateFloat(array[2]).GetValueOrDefault(); } return zero; } public static Quaternion EvaluateQuaternion(string expression) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0005: Unknown result type (might be due to invalid IL or missing references) //IL_0061: 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) Vector3 zero = Vector3.zero; string[] array = Parse.Split(expression); zero.y = EvaluateFloat(array[0]).GetValueOrDefault(); if (array.Length > 1) { zero.x = EvaluateFloat(array[1]).GetValueOrDefault(); } if (array.Length > 2) { zero.z = EvaluateFloat(array[2]).GetValueOrDefault(); } return Quaternion.Euler(zero); } public static int? EvaluateInt(string expression) { try { return (int?)EvaluateLong(expression); } catch { return null; } } public static float? EvaluateFloat(string expression) { try { return (float)EvaluateDouble(expression); } catch { return null; } } private static double EvaluateDouble(string expression) { return new DoubleParser(expression.Replace("**", "^")).Parse(); } public static long? EvaluateLong(string expression) { try { return EvalLong(expression); } catch { return null; } } private static long EvalLong(string expression) { return new LongParser(expression.Replace("**", "^")).Parse(); } } public class DataEntry { private static readonly int HasFieldsHash = ZdoHelper.Hash("HasFields"); public bool CanBeInjected = true; public Dictionary<int, IStringValue>? Strings; public Dictionary<int, IFloatValue>? Floats; public Dictionary<int, IIntValue>? Ints; public Dictionary<int, IIntValue>? Components; public Dictionary<int, IBoolValue>? Bools; public Dictionary<int, IHashValue>? Hashes; public Dictionary<int, ILongValue>? Longs; public Dictionary<int, IVector3Value>? Vecs; public Dictionary<int, IQuaternionValue>? Quats; public Dictionary<int, IBytesValue>? ByteArrays; public List<ItemValue>? Items; public ItemValue? Item; public Vector2i? ContainerSize; public IIntValue? ItemAmount; public ConnectionType? ConnectionType; public int ConnectionHash; public IZdoIdValue? OriginalId; public IZdoIdValue? TargetConnectionId; public IBoolValue? Persistent; public IBoolValue? Distant; public ObjectType? Priority; public IVector3Value? Position; public IQuaternionValue? Rotation; public static HashSet<string> SupportedTypes = new HashSet<string> { "float", "int", "bool", "hash", "long", "string", "vec", "vec3", "quat", "bytes" }; public DataEntry() { } public DataEntry(string[] typeKeyValues) { Load(typeKeyValues); } public DataEntry(DataYaml data) { Load(data); } public DataEntry(ZDO zdo) { Load(zdo); } public DataEntry(ZPackage pkg) { Load(pkg); } public void Load(DataEntry data) { if (data.Floats != null) { if (Floats == null) { Floats = new Dictionary<int, IFloatValue>(); } foreach (KeyValuePair<int, IFloatValue> @float in data.Floats) { Floats[@float.Key] = @float.Value; } } if (data.Vecs != null) { if (Vecs == null) { Vecs = new Dictionary<int, IVector3Value>(); } foreach (KeyValuePair<int, IVector3Value> vec in data.Vecs) { Vecs[vec.Key] = vec.Value; } } if (data.Quats != null) { if (Quats == null) { Quats = new Dictionary<int, IQuaternionValue>(); } foreach (KeyValuePair<int, IQuaternionValue> quat in data.Quats) { Quats[quat.Key] = quat.Value; } } if (data.Ints != null) { if (Ints == null) { Ints = new Dictionary<int, IIntValue>(); } foreach (KeyValuePair<int, IIntValue> @int in data.Ints) { Ints[@int.Key] = @int.Value; } } if (data.Strings != null) { if (Strings == null) { Strings = new Dictionary<int, IStringValue>(); } foreach (KeyValuePair<int, IStringValue> @string in data.Strings) { Strings[@string.Key] = @string.Value; } } if (data.ByteArrays != null) { if (ByteArrays == null) { ByteArrays = new Dictionary<int, IBytesValue>(); } foreach (KeyValuePair<int, IBytesValue> byteArray in data.ByteArrays) { ByteArrays[byteArray.Key] = byteArray.Value; } } if (data.Longs != null) { if (Longs == null) { Longs = new Dictionary<int, ILongValue>(); } foreach (KeyValuePair<int, ILongValue> @long in data.Longs) { Longs[@long.Key] = @long.Value; } } if (data.Bools != null) { if (Bools == null) { Bools = new Dictionary<int, IBoolValue>(); } foreach (KeyValuePair<int, IBoolValue> @bool in data.Bools) { Bools[@bool.Key] = @bool.Value; } } if (data.Hashes != null) { if (Hashes == null) { Hashes = new Dictionary<int, IHashValue>(); } foreach (KeyValuePair<int, IHashValue> hash in data.Hashes) { Hashes[hash.Key] = hash.Value; } } if (data.Components != null) { if (Components == null) { Components = new Dictionary<int, IIntValue>(); } foreach (KeyValuePair<int, IIntValue> component in data.Components) { Components[component.Key] = component.Value; } } if (data.Items != null) { if (Items == null) { Items = new List<ItemValue>(); } foreach (ItemValue item in data.Items) { Items.Add(item); } } if (data.Item != null) { Item = data.Item; } if (data.ContainerSize.HasValue) { ContainerSize = data.ContainerSize; } if (data.ItemAmount != null) { ItemAmount = data.ItemAmount; } ConnectionType = data.ConnectionType; ConnectionHash = data.ConnectionHash; OriginalId = data.OriginalId; TargetConnectionId = data.TargetConnectionId; if (data.Persistent != null) { Persistent = data.Persistent; } if (data.Distant != null) { Distant = data.Distant; } if (data.Priority.HasValue) { Priority = data.Priority; } if (data.Position != null) { Position = data.Position; } if (data.Rotation != null) { Rotation = data.Rotation; } CanBeInjected = data.CanBeInjected; } public DataEntry Reset(DataYaml data) { CanBeInjected = true; Floats = null; Vecs = null; Quats = null; Ints = null; Strings = null; ByteArrays = null; Longs = null; Bools = null; Hashes = null; Items = null; Item = null; Components = null; ContainerSize = null; ItemAmount = null; ConnectionType = null; ConnectionHash = 0; OriginalId = null; TargetConnectionId = null; Position = null; Rotation = null; Distant = null; Persistent = null; Priority = null; Load(data); return this; } private bool CheckCanBeInjected() { if ((Ints == null || (!Ints.ContainsKey(HasFieldsHash) && !Ints.ContainsKey(ZDOVars.s_level))) && Components == null && Position == null) { return Rotation == null; } return false; } public byte[]? CreateItemData(Functions f, ZDO? zdo) { if (zdo != null) { return Item?.Create(f, zdo); } return null; } public byte[]? CreateInventory(Functions f, ZDO? zdo) { //IL_0033: 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_0038: Unknown result type (might be due to invalid IL or missing references) //IL_0040: Unknown result type (might be due to invalid IL or missing references) if (Items == null || Items.Count == 0) { return null; } Vector2i size = (Vector2i)(((??)ContainerSize) ?? ZdoHelper.GetInventorySize(this, f, zdo)); return ItemValue.LoadItemBytes(f, Items, size, (ItemAmount?.Get(f)).GetValueOrDefault()); } public void Load(ZDO zdo) { //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_000d: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Unknown result type (might be due to invalid IL or missing references) //IL_00c5: 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_017e: Unknown result type (might be due to invalid IL or missing references) //IL_01db: Unknown result type (might be due to invalid IL or missing references) //IL_0238: Unknown result type (might be due to invalid IL or missing references) //IL_0294: Unknown result type (might be due to invalid IL or missing references) //IL_02be: Unknown result type (might be due to invalid IL or missing references) //IL_02ce: Unknown result type (might be due to invalid IL or missing references) //IL_02a1: Unknown result type (might be due to invalid IL or missing references) //IL_02da: 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_02ee: 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) ZDOID uid = zdo.m_uid; Floats = (ZDOExtraData.s_floats.TryGetValue(uid, out var value) ? ((IEnumerable<KeyValuePair<int, float>>)value).ToDictionary((KeyValuePair<int, float> kvp) => kvp.Key, (KeyValuePair<int, float> kvp) => DataValue.Constant(kvp.Value)) : null); Ints = (ZDOExtraData.s_ints.TryGetValue(uid, out var value2) ? ((IEnumerable<KeyValuePair<int, int>>)value2).ToDictionary((KeyValuePair<int, int> kvp) => kvp.Key, (KeyValuePair<int, int> kvp) => DataValue.Constant(kvp.Value)) : null); Longs = (ZDOExtraData.s_longs.TryGetValue(uid, out var value3) ? ((IEnumerable<KeyValuePair<int, long>>)value3).ToDictionary((KeyValuePair<int, long> kvp) => kvp.Key, (KeyValuePair<int, long> kvp) => DataValue.Constant(kvp.Value)) : null); Strings = (ZDOExtraData.s_strings.TryGetValue(uid, out var value4) ? ((IEnumerable<KeyValuePair<int, string>>)value4).ToDictionary((KeyValuePair<int, string> kvp) => kvp.Key, (KeyValuePair<int, string> kvp) => DataValue.Constant(kvp.Value)) : null); Vecs = (ZDOExtraData.s_vec3.TryGetValue(uid, out var value5) ? ((IEnumerable<KeyValuePair<int, Vector3>>)value5).ToDictionary((KeyValuePair<int, Vector3> kvp) => kvp.Key, (KeyValuePair<int, Vector3> kvp) => DataValue.Constant(kvp.Value)) : null); Quats = (ZDOExtraData.s_quats.TryGetValue(uid, out var value6) ? ((IEnumerable<KeyValuePair<int, Quaternion>>)value6).ToDictionary((KeyValuePair<int, Quaternion> kvp) => kvp.Key, (KeyValuePair<int, Quaternion> kvp) => DataValue.Constant(kvp.Value)) : null); ByteArrays = (ZDOExtraData.s_byteArrays.TryGetValue(uid, out var value7) ? ((IEnumerable<KeyValuePair<int, byte[]>>)value7).ToDictionary((KeyValuePair<int, byte[]> kvp) => kvp.Key, (KeyValuePair<int, byte[]> kvp) => DataValue.Constant(kvp.Value)) : null); if (ZDOExtraData.s_connectionsHashData.TryGetValue(uid, out var value8)) { ConnectionType = value8.m_type; ConnectionHash = value8.m_hash; } OriginalId = new ConstantZdoIdValue(uid); if (ZDOExtraData.s_connections.TryGetValue(uid, out var value9) && value9.m_target != ZDOID.None) { TargetConnectionId = new ConstantZdoIdValue(value9.m_target); ConnectionType = value9.m_type; } Persistent = null; Distant = null; Priority = null; CanBeInjected = CheckCanBeInjected(); } public void Load(DataYaml data) { //IL_0ac3: Unknown result type (might be due to invalid IL or missing references) //IL_0c17: Unknown result type (might be due to invalid IL or missing references) //IL_0c8e: Unknown result type (might be due to invalid IL or missing references) //IL_0c5c: Unknown result type (might be due to invalid IL or missing references) HashSet<string> hashSet = new HashSet<string>(); if (data.floats != null) { if (Floats == null) { Floats = new Dictionary<int, IFloatValue>(); } string[] floats = data.floats; foreach (string text in floats) { KeyValuePair<string, string> keyValuePair = Parse.Kvp(text); if (keyValuePair.Key == "") { throw new InvalidOperationException("Failed to parse float " + text + "."); } if (keyValuePair.Key.Contains(".")) { hashSet.Add(keyValuePair.Key.Split(new char[1] { '.' })[0]); } int key = ZdoHelper.Hash(keyValuePair.Key); if (Floats.ContainsKey(key)) { Log.Warning("Data " + data.name + ": Duplicate float key " + keyValuePair.Key + "."); } Floats[key] = DataValue.Float(keyValuePair.Value); } } if (data.ints != null) { if (Ints == null) { Ints = new Dictionary<int, IIntValue>(); } string[] floats = data.ints; foreach (string text2 in floats) { KeyValuePair<string, string> keyValuePair2 = Parse.Kvp(text2); if (keyValuePair2.Key == "") { throw new InvalidOperationException("Failed to parse int " + text2 + "."); } if (keyValuePair2.Key.Contains(".")) { hashSet.Add(keyValuePair2.Key.Split(new char[1] { '.' })[0]); } int key2 = ZdoHelper.Hash(keyValuePair2.Key); if (Ints.ContainsKey(key2)) { Log.Warning("Data " + data.name + ": Duplicate int key " + keyValuePair2.Key + "."); } Ints[key2] = DataValue.Int(keyValuePair2.Value); } } if (data.bools != null) { if (Bools == null) { Bools = new Dictionary<int, IBoolValue>(); } string[] floats = data.bools; foreach (string text3 in floats) { KeyValuePair<string, string> keyValuePair3 = Parse.Kvp(text3); if (keyValuePair3.Key == "") { throw new InvalidOperationException("Failed to parse bool " + text3 + "."); } if (keyValuePair3.Key.Contains(".")) { hashSet.Add(keyValuePair3.Key.Split(new char[1] { '.' })[0]); } int key3 = ZdoHelper.Hash(keyValuePair3.Key); if (Bools.ContainsKey(key3)) { Log.Warning("Data " + data.name + ": Duplicate bool key " + keyValuePair3.Key + "."); } Bools[key3] = DataValue.Bool(keyValuePair3.Value); } } if (data.hashes != null) { if (Hashes == null) { Hashes = new Dictionary<int, IHashValue>(); } string[] floats = data.hashes; foreach (string text4 in floats) { KeyValuePair<string, string> keyValuePair4 = Parse.Kvp(text4); if (keyValuePair4.Key == "") { throw new InvalidOperationException("Failed to parse hash " + text4 + "."); } if (keyValuePair4.Key.Contains(".")) { hashSet.Add(keyValuePair4.Key.Split(new char[1] { '.' })[0]); } int key4 = ZdoHelper.Hash(keyValuePair4.Key); if (Hashes.ContainsKey(key4)) { Log.Warning("Data " + data.name + ": Duplicate hash key " + keyValuePair4.Key + "."); } Hashes[key4] = DataValue.Hash(keyValuePair4.Value); } } if (data.longs != null) { if (Longs == null) { Longs = new Dictionary<int, ILongValue>(); } string[] floats = data.longs; foreach (string text5 in floats) { KeyValuePair<string, string> keyValuePair5 = Parse.Kvp(text5); if (keyValuePair5.Key == "") { throw new InvalidOperationException("Failed to parse long " + text5 + "."); } if (keyValuePair5.Key.Contains(".")) { hashSet.Add(keyValuePair5.Key.Split(new char[1] { '.' })[0]); } int key5 = ZdoHelper.Hash(keyValuePair5.Key); if (Longs.ContainsKey(key5)) { Log.Warning("Data " + data.name + ": Duplicate long key " + keyValuePair5.Key + "."); } Longs[key5] = DataValue.Long(keyValuePair5.Value); } } if (data.strings != null) { if (Strings == null) { Strings = new Dictionary<int, IStringValue>(); } string[] floats = data.strings; foreach (string text6 in floats) { KeyValuePair<string, string> keyValuePair6 = Parse.Kvp(text6); if (keyValuePair6.Key == "") { throw new InvalidOperationException("Failed to parse string " + text6 + "."); } if (keyValuePair6.Key.Contains(".")) { hashSet.Add(keyValuePair6.Key.Split(new char[1] { '.' })[0]); } int num = ZdoHelper.Hash(keyValuePair6.Key); if (num == ZDOVars.s_items) { if (ByteArrays == null) { ByteArrays = new Dictionary<int, IBytesValue>(); } if (ByteArrays.ContainsKey(num)) { Log.Warning("Data " + data.name + ": Duplicate string key " + keyValuePair6.Key + "."); } ByteArrays[num] = DataValue.Bytes(keyValuePair6.Value); } else { if (Strings.ContainsKey(num)) { Log.Warning("Data " + data.name + ": Duplicate string key " + keyValuePair6.Key + "."); } Strings[num] = DataValue.String(keyValuePair6.Value); } } } if (data.vecs != null) { if (Vecs == null) { Vecs = new Dictionary<int, IVector3Value>(); } string[] floats = data.vecs; foreach (string text7 in floats) { KeyValuePair<string, string> keyValuePair7 = Parse.K