Decompiled source of DawnLib v0.1.9
BepInEx/plugins/DawnLib/com.github.teamxiaolan.dawnlib.dll
Decompiled 3 days ago
The result has been truncated due to the large size, download it to view full contents!
using System; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Configuration; using BepInEx.Logging; using Dawn; using Dawn.Internal; using Dawn.Preloader.Interfaces; using Dawn.Utils; using DunGen; using DunGen.Graph; using GameNetcodeStuff; using GoodItemScan; using IL; using IL.TerminalFormatter.Nodes; using LethalConfig.ConfigItems; using LethalLevelLoader; using LethalLib.Modules; using LethalQuantities.Objects; using Microsoft.CodeAnalysis; using Mono.Cecil; using Mono.Cecil.Cil; using MonoMod.Cil; using MonoMod.RuntimeDetour; using MrovLib.Events; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using On; using On.BepInEx.Configuration; using On.DunGen; using On.LethalConfig.AutoConfig; using On.LethalLevelLoader; using On.LethalQuantities.Patches; using PathfindingLib.API.SmartPathfinding; using TMPro; using Unity.Netcode; using Unity.Netcode.Components; using UnityEngine; using UnityEngine.AI; using UnityEngine.Audio; using UnityEngine.Events; using UnityEngine.UI; using WeatherRegistry; using com.github.teamxiaolan.dawnlib.NetcodePatcher; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: InternalsVisibleTo("com.github.teamxiaolan.dawnlib.dusk")] [assembly: IgnoresAccessChecksTo("AmazingAssets.TerrainToMesh")] [assembly: IgnoresAccessChecksTo("Assembly-CSharp-firstpass")] [assembly: IgnoresAccessChecksTo("Assembly-CSharp")] [assembly: IgnoresAccessChecksTo("ClientNetworkTransform")] [assembly: IgnoresAccessChecksTo("com.olegknyazev.softmask")] [assembly: IgnoresAccessChecksTo("DissonanceVoip")] [assembly: IgnoresAccessChecksTo("EasyTextEffects")] [assembly: IgnoresAccessChecksTo("Facepunch Transport for Netcode for GameObjects")] [assembly: IgnoresAccessChecksTo("Facepunch.Steamworks.Win64")] [assembly: IgnoresAccessChecksTo("GoodItemScan")] [assembly: IgnoresAccessChecksTo("LethalConfig")] [assembly: IgnoresAccessChecksTo("LethalLevelLoader")] [assembly: IgnoresAccessChecksTo("LethalLib")] [assembly: IgnoresAccessChecksTo("LethalQuantities")] [assembly: IgnoresAccessChecksTo("MrovLib")] [assembly: IgnoresAccessChecksTo("StarlancerAI")] [assembly: IgnoresAccessChecksTo("Unity.AI.Navigation")] [assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging")] [assembly: IgnoresAccessChecksTo("Unity.Animation.Rigging.DocCodeExamples")] [assembly: IgnoresAccessChecksTo("Unity.Burst")] [assembly: IgnoresAccessChecksTo("Unity.Burst.Unsafe")] [assembly: IgnoresAccessChecksTo("Unity.Collections")] [assembly: IgnoresAccessChecksTo("Unity.Collections.LowLevel.ILSupport")] [assembly: IgnoresAccessChecksTo("Unity.InputSystem")] [assembly: IgnoresAccessChecksTo("Unity.InputSystem.ForUI")] [assembly: IgnoresAccessChecksTo("Unity.Jobs")] [assembly: IgnoresAccessChecksTo("Unity.Mathematics")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.Common")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.MetricTypes")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStats")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Component")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Configuration")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsMonitor.Implementation")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetStatsReporting")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkProfiler.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.Multiplayer.Tools.NetworkSolutionInterface")] [assembly: IgnoresAccessChecksTo("Unity.Netcode.Components")] [assembly: IgnoresAccessChecksTo("Unity.Netcode.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.Networking.Transport")] [assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Csg")] [assembly: IgnoresAccessChecksTo("Unity.ProBuilder")] [assembly: IgnoresAccessChecksTo("Unity.ProBuilder.KdTree")] [assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Poly2Tri")] [assembly: IgnoresAccessChecksTo("Unity.ProBuilder.Stl")] [assembly: IgnoresAccessChecksTo("Unity.Profiling.Core")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.Core.ShaderLibrary")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Config.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.HighDefinition.Runtime")] [assembly: IgnoresAccessChecksTo("Unity.RenderPipelines.ShaderGraph.ShaderGraphLibrary")] [assembly: IgnoresAccessChecksTo("Unity.Services.Authentication")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Analytics")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Configuration")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Device")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Environments.Internal")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Internal")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Networking")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Registration")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Scheduler")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Telemetry")] [assembly: IgnoresAccessChecksTo("Unity.Services.Core.Threading")] [assembly: IgnoresAccessChecksTo("Unity.Services.QoS")] [assembly: IgnoresAccessChecksTo("Unity.Services.Relay")] [assembly: IgnoresAccessChecksTo("Unity.TextMeshPro")] [assembly: IgnoresAccessChecksTo("Unity.Timeline")] [assembly: IgnoresAccessChecksTo("Unity.VisualEffectGraph.Runtime")] [assembly: IgnoresAccessChecksTo("UnityEngine.ARModule")] [assembly: IgnoresAccessChecksTo("UnityEngine.NVIDIAModule")] [assembly: IgnoresAccessChecksTo("UnityEngine.UI")] [assembly: IgnoresAccessChecksTo("WeatherRegistry")] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: AssemblyCompany("XuXiaolan,loaforc")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("A modern API for Lethal Company content and all sizes of mods.")] [assembly: AssemblyFileVersion("0.1.9.0")] [assembly: AssemblyInformationalVersion("0.1.9+09cb71a636e1df245dcd8b6809da4e52cfd9ebcf")] [assembly: AssemblyProduct("DawnLib")] [assembly: AssemblyTitle("com.github.teamxiaolan.dawnlib")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.1.9.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: NetcodePatchedAssembly] internal class <Module> { static <Module>() { NetworkVariableSerializationTypes.InitializeSerializer_UnmanagedINetworkSerializable<NetworkTransformState>(); NetworkVariableSerializationTypes.InitializeEqualityChecker_UnmanagedValueEquals<NetworkTransformState>(); } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } public class DawnMapObjectInfoContainer : DawnInfoContainer<DawnMapObjectInfo> { } namespace Dawn { public abstract class BaseInfoBuilder { internal abstract void SoloAddTags(IEnumerable<NamespacedKey> newTags); } public abstract class BaseInfoBuilder<TInfo, T, TBuilder> : BaseInfoBuilder where TInfo : INamespaced<TInfo> where TBuilder : BaseInfoBuilder<TInfo, T, TBuilder> { protected HashSet<NamespacedKey> tags = new HashSet<NamespacedKey>(); protected IDataContainer? customData; protected NamespacedKey<TInfo> key { get; private set; } protected T value { get; private set; } internal BaseInfoBuilder(NamespacedKey<TInfo> key, T value) { this.key = key; this.value = value; } public TBuilder AddTag(NamespacedKey tag) { tags.Add(tag); return (TBuilder)this; } public TBuilder AddTags(IEnumerable<NamespacedKey> newTags) { foreach (NamespacedKey newTag in newTags) { AddTag(newTag); } return (TBuilder)this; } internal override void SoloAddTags(IEnumerable<NamespacedKey> newTags) { AddTags(newTags); } public TBuilder EditCustomData(Action<IDataContainer> callback) { if (customData == null) { customData = new DataContainer(); } callback(customData); return (TBuilder)this; } internal abstract TInfo Build(); } public class DataContainer : IDataContainer { protected Dictionary<NamespacedKey, object> dictionary = new Dictionary<NamespacedKey, object>(); public IEnumerable<NamespacedKey> Keys => dictionary.Keys; public int Count => dictionary.Count; public bool Has(NamespacedKey key) { return dictionary.ContainsKey(key); } public bool TryGet<T>(NamespacedKey key, [NotNullWhen(true)] out T? value) { if (dictionary.TryGetValue(key, out object value2)) { JToken val = (JToken)((value2 is JToken) ? value2 : null); if (val != null) { value = val.ToObject<T>(); return true; } if (value2 is T val2) { value = val2; return true; } if (typeof(T) == typeof(int) && value2 is long num) { value = (T)(object)(int)num; return true; } if (typeof(T) == typeof(long) && value2 is int num2) { value = (T)(object)(long)num2; return true; } throw new InvalidCastException($"type of '{key}' is {value2.GetType().Name} which can not be {typeof(T).Name}"); } value = default(T); return false; } public T GetOrSetDefault<T>(NamespacedKey key, T defaultValue) { if (TryGet<T>(key, out T value)) { return value; } Set(key, defaultValue); return defaultValue; } public T GetOrCreateDefault<T>(NamespacedKey key) where T : new() { if (TryGet<T>(key, out T value)) { return value; } value = new T(); Set(key, value); return value; } public virtual void Set<T>(NamespacedKey key, T value) { if (value == null) { throw new ArgumentNullException("value"); } dictionary[key] = value; } public virtual void Remove(NamespacedKey key) { dictionary.Remove(key); } public virtual void Clear() { dictionary.Clear(); } } public class FrozenEmptyDataContainer : IDataContainer { public static FrozenEmptyDataContainer Instance { get; private set; } = new FrozenEmptyDataContainer(); public IEnumerable<NamespacedKey> Keys { get; } = Array.Empty<NamespacedKey>(); public int Count => 0; private FrozenEmptyDataContainer() { } public bool TryGet<T>(NamespacedKey key, [NotNullWhen(true)] out T? value) { value = default(T); return false; } public T GetOrSetDefault<T>(NamespacedKey key, T defaultValue) { throw new RegistryFrozenException(); } public T GetOrCreateDefault<T>(NamespacedKey key) where T : new() { throw new RegistryFrozenException(); } public void Set<T>(NamespacedKey key, T value) { throw new RegistryFrozenException(); } public void Remove(NamespacedKey key) { throw new RegistryFrozenException(); } public void Clear() { throw new RegistryFrozenException(); } } public interface IDataContainer { IEnumerable<NamespacedKey> Keys { get; } int Count { get; } bool TryGet<T>(NamespacedKey key, [NotNullWhen(true)] out T? value); T GetOrSetDefault<T>(NamespacedKey key, T defaultValue); T GetOrCreateDefault<T>(NamespacedKey key) where T : new(); void Set<T>(NamespacedKey key, T value); void Remove(NamespacedKey key); void Clear(); } public interface INamespaced { NamespacedKey Key { get; } } public interface INamespaced<T> : INamespaced where T : INamespaced<T> { NamespacedKey<T> TypedKey { get; } } public class JSONTagDefinition { public string Tag; public string[] Values; } [Serializable] public class NamespacedKey : INetworkSerializable { private static readonly Regex NamespacedKeyRegex = new Regex("[?!.\\n\\t\"`\\[\\]'-]"); private static readonly Dictionary<char, string> NumberWords = new Dictionary<char, string> { { '0', "Zero" }, { '1', "One" }, { '2', "Two" }, { '3', "Three" }, { '4', "Four" }, { '5', "Five" }, { '6', "Six" }, { '7', "Seven" }, { '8', "Eight" }, { '9', "Nine" } }; public const char Separator = ':'; public const string VanillaNamespace = "lethal_company"; [SerializeField] private string _namespace; [SerializeField] private string _key; public string Namespace => _namespace; public string Key => _key; internal static string NormalizeStringForNamespacedKey(string input, bool CSharpName) { if (string.IsNullOrEmpty(input)) { return string.Empty; } string text = NamespacedKeyRegex.Replace(input, string.Empty); StringBuilder stringBuilder = new StringBuilder(text.Length); bool flag = false; string text2 = text; foreach (char c in text2) { if (flag || (!char.IsDigit(c) && c != ' ')) { flag = true; stringBuilder.Append(c); } } StringBuilder stringBuilder2 = new StringBuilder(stringBuilder.Length); string text3 = stringBuilder.ToString(); foreach (char c2 in text3) { if (NumberWords.TryGetValue(c2, out string value)) { stringBuilder2.Append(value); } else { stringBuilder2.Append(c2); } } string text4 = stringBuilder2.ToString(); if (CSharpName) { text4 = text4.Replace(" ", ""); text4 = text4.Replace("_", ""); return text4.ToCapitalized(); } return text4.ToLowerInvariant().Replace(" ", "_"); } protected NamespacedKey(string @namespace, string key) { _namespace = @namespace; _key = key; } [EditorBrowsable(EditorBrowsableState.Never)] public NamespacedKey() { } public static NamespacedKey From(string @namespace, string key) { return new NamespacedKey(@namespace, key); } public static NamespacedKey Vanilla(string key) { return From("lethal_company", key); } public static NamespacedKey Parse(string input) { string[] array = input.Split(':'); return From(array[0], array[1]); } public static bool TryParse(string input, [NotNullWhen(true)] out NamespacedKey? result) { result = null; string[] array = input.Split(':'); if (array.Length != 2) { return false; } result = From(array[0], array[1]); return true; } public static NamespacedKey ForceParse(string input) { string[] array = input.Split(':'); if (array.Length == 1) { array = new string[2] { "lethal_company", array[0] }; } return From(array[0], array[1]); } public override string ToString() { return $"{Namespace}{':'}{Key}"; } public void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter { serializer.SerializeValue(ref _namespace, false); serializer.SerializeValue(ref _key, false); } public override bool Equals(object? obj) { if (obj == null) { return false; } NamespacedKey namespacedKey = (NamespacedKey)obj; if (Namespace == namespacedKey.Namespace) { return Key == namespacedKey.Key; } return false; } public override int GetHashCode() { int num = 13; num = num * 17 + Namespace.GetHashCode(); return num * 17 + Key.GetHashCode(); } public NamespacedKey<T> AsTyped<T>() where T : INamespaced { return NamespacedKey<T>.From(Namespace, Key); } public bool IsVanilla() { return Namespace == "lethal_company"; } public bool IsModded() { return !IsVanilla(); } } [Serializable] public class NamespacedKey<T> : NamespacedKey where T : INamespaced { protected NamespacedKey(string @namespace, string key) : base(@namespace, key) { } [EditorBrowsable(EditorBrowsableState.Never)] public NamespacedKey() { } public new static NamespacedKey<T> From(string @namespace, string key) { return new NamespacedKey<T>(@namespace, key); } public new static NamespacedKey<T> Vanilla(string key) { return From("lethal_company", key); } public new static NamespacedKey<T> Parse(string input) { string[] array = input.Split(':'); return From(array[0], array[1]); } } public class NamespacedKeyConverter : JsonConverter { public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { if (value is NamespacedKey namespacedKey) { writer.WriteValue(namespacedKey.ToString()); } else { writer.WriteNull(); } } public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0008: Invalid comparison between Unknown and I4 //IL_009f: Unknown result type (might be due to invalid IL or missing references) if ((int)reader.TokenType == 11) { return null; } string text = reader.Value?.ToString(); if (text == null) { return null; } NamespacedKey namespacedKey = NamespacedKey.ForceParse(text); if (objectType == typeof(NamespacedKey)) { return namespacedKey; } if (objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(NamespacedKey<>)) { MethodInfo method = typeof(NamespacedKey).GetMethod("AsTyped"); MethodInfo methodInfo = method.MakeGenericMethod(objectType.GetGenericArguments()[0]); return methodInfo.Invoke(namespacedKey, null); } throw new JsonSerializationException($"Cannot deserialize {objectType}"); } public override bool CanConvert(Type objectType) { if (objectType == typeof(NamespacedKey)) { return true; } if (objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(NamespacedKey<>)) { return true; } return false; } } public class NamespacedKeyDictionaryConverter : JsonConverter { public override bool CanConvert(Type objectType) { if (objectType.IsGenericType && objectType.GetGenericTypeDefinition() == typeof(Dictionary<, >)) { return objectType.GetGenericArguments()[0] == typeof(NamespacedKey); } return false; } public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) { writer.WriteStartObject(); IDictionary dictionary = (IDictionary)value; foreach (object key in dictionary.Keys) { NamespacedKey namespacedKey = (NamespacedKey)key; object obj = dictionary[key]; writer.WritePropertyName(namespacedKey.ToString()); serializer.Serialize(writer, obj); } writer.WriteEndObject(); } public override object ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) { Type type = objectType.GetGenericArguments()[1]; Type type2 = typeof(Dictionary<, >).MakeGenericType(typeof(NamespacedKey), type); IDictionary dictionary = (IDictionary)Activator.CreateInstance(type2); JObject val = JObject.Load(reader); foreach (JProperty item in val.Properties()) { NamespacedKey key = NamespacedKey.ForceParse(item.Name); object value = item.Value.ToObject(type, serializer); dictionary[key] = value; } return dictionary; } } public class PersistentDataContainer : DataContainer { public class EditContext : IDisposable { private PersistentDataContainer _container; public EditContext(PersistentDataContainer container) { _container = container; _container._autoSave = false; } public void Dispose() { _container._autoSave = true; Task.Run((Func<Task?>)_container.SaveAsync); } } private string _filePath; private bool _autoSave = true; private readonly SemaphoreSlim _saveLock = new SemaphoreSlim(1, 1); internal static List<PersistentDataContainer> HasCorruptedData { get; private set; } = new List<PersistentDataContainer>(); public string FileName => Path.GetFileName(_filePath); public PersistentDataContainer(string filePath) { Debuggers.PersistentDataContainer?.Log("new PersistentDataContainer: " + Path.GetFileName(filePath)); _filePath = filePath; if (File.Exists(filePath)) { Debuggers.PersistentDataContainer?.Log("loading existing file"); try { dictionary = JsonConvert.DeserializeObject<Dictionary<NamespacedKey, object>>(File.ReadAllText(_filePath), DawnLib.JSONSettings); } catch (Exception arg) { DawnPlugin.Logger.LogFatal((object)$"Exception when loading from persistent data container ({Path.GetFileName(_filePath)}):\n{arg}"); HasCorruptedData.Add(this); } Debuggers.PersistentDataContainer?.Log($"loaded {dictionary.Count} entries."); } } public override void Set<T>(NamespacedKey key, T value) { base.Set(key, value); if (_autoSave) { Task.Run((Func<Task?>)SaveAsync); } } public override void Clear() { base.Clear(); if (_autoSave) { Task.Run((Func<Task?>)SaveAsync); } } public override void Remove(NamespacedKey key) { base.Remove(key); if (_autoSave) { Task.Run((Func<Task?>)SaveAsync); } } public IDisposable LargeEdit() { return new EditContext(this); } private async Task SaveAsync() { Debuggers.PersistentDataContainer?.Log("saving (" + Path.GetFileName(_filePath) + ")"); await _saveLock.WaitAsync().ConfigureAwait(continueOnCapturedContext: false); try { await using FileStream stream = new FileStream(_filePath, FileMode.Create, FileAccess.Write, FileShare.None, 4096, useAsync: true); using StreamWriter writer = new StreamWriter(stream, Encoding.UTF8); string value = JsonConvert.SerializeObject((object)dictionary, DawnLib.JSONSettings); await writer.WriteAsync(value).ConfigureAwait(continueOnCapturedContext: false); await writer.FlushAsync().ConfigureAwait(continueOnCapturedContext: false); await stream.FlushAsync().ConfigureAwait(continueOnCapturedContext: false); Debuggers.PersistentDataContainer?.Log("saved (" + Path.GetFileName(_filePath) + ")"); } catch (Exception arg) { DawnPlugin.Logger.LogError((object)$"Error happened while trying to save PersistentDataContainer ({Path.GetFileName(_filePath)}):\n{arg}"); } finally { _saveLock.Release(); } } internal void DeleteFile() { File.Delete(_filePath); } } public abstract class DawnBaseInfo<T> : INamespaced<T>, INamespaced, ITaggable, IRegistryEvents where T : DawnBaseInfo<T> { private HashSet<NamespacedKey> _tags; private IDataContainer? _customData; public IDataContainer CustomData { get { if (_customData == null) { _customData = new DataContainer(); } return _customData; } } public NamespacedKey Key => TypedKey; public NamespacedKey<T> TypedKey { get; } protected DawnBaseInfo(NamespacedKey<T> key, HashSet<NamespacedKey> tags, IDataContainer? customData) { TypedKey = key; _tags = tags; _customData = customData; } public bool HasTag(NamespacedKey tag) { return _tags.Contains(tag); } public IEnumerable<NamespacedKey> AllTags() { return _tags; } internal void Internal_AddTag(NamespacedKey tag) { Debuggers.Tags?.Log($"Internal_AddTag: {tag} !!!"); _tags.Add(tag); } public void OnFrozen() { if (_customData == null) { _customData = FrozenEmptyDataContainer.Instance; } } } public class DawnInfoContainer<T> : MonoBehaviour where T : DawnBaseInfo<T> { public T Value { get; internal set; } } public static class DawnLib { public const string PLUGIN_GUID = "com.github.teamxiaolan.dawnlib"; internal static readonly JsonSerializerSettings JSONSettings = new JsonSerializerSettings { TypeNameHandling = (TypeNameHandling)3, Formatting = (Formatting)1, Converters = new List<JsonConverter>(2) { (JsonConverter)(object)new NamespacedKeyConverter(), (JsonConverter)(object)new NamespacedKeyDictionaryConverter() } }; public static PersistentDataContainer? GetCurrentSave() { return NetworkSingleton<DawnNetworker>.Instance?.SaveContainer; } public static PersistentDataContainer? GetCurrentContract() { return NetworkSingleton<DawnNetworker>.Instance?.ContractContainer; } public static void RegisterNetworkPrefab(GameObject prefab) { if (!Object.op_Implicit((Object)(object)prefab)) { throw new ArgumentNullException("prefab"); } MiscFixesPatch.networkPrefabsToAdd.Add(prefab); } public static void FixMixerGroups(GameObject prefab) { if (!Object.op_Implicit((Object)(object)prefab)) { throw new ArgumentNullException("prefab"); } MiscFixesPatch.soundPrefabsToFix.Add(prefab); } public static void FixDoorwaySockets(GameObject prefab) { if (!Object.op_Implicit((Object)(object)prefab)) { throw new ArgumentNullException("prefab"); } MiscFixesPatch.tilesToFixSockets.Add(prefab); } public static DawnTileSetInfo DefineTileSet(NamespacedKey<DawnTileSetInfo> key, TileSet tileSet, Action<TilesetInfoBuilder> callback) { TilesetInfoBuilder tilesetInfoBuilder = new TilesetInfoBuilder(key, tileSet); callback(tilesetInfoBuilder); DawnTileSetInfo dawnTileSetInfo = tilesetInfoBuilder.Build(); tileSet.SetDawnInfo(dawnTileSetInfo); LethalContent.TileSets.Register(dawnTileSetInfo); return dawnTileSetInfo; } public static DawnMapObjectInfo DefineMapObject(NamespacedKey<DawnMapObjectInfo> key, GameObject mapObject, Action<MapObjectInfoBuilder> callback) { MapObjectInfoBuilder mapObjectInfoBuilder = new MapObjectInfoBuilder(key, mapObject); callback(mapObjectInfoBuilder); DawnMapObjectInfo dawnMapObjectInfo = mapObjectInfoBuilder.Build(); DawnMapObjectInfoContainer dawnMapObjectInfoContainer = mapObject.AddComponent<DawnMapObjectInfoContainer>(); dawnMapObjectInfoContainer.Value = dawnMapObjectInfo; LethalContent.MapObjects.Register(dawnMapObjectInfo); return dawnMapObjectInfo; } public static DawnUnlockableItemInfo DefineUnlockable(NamespacedKey<DawnUnlockableItemInfo> key, UnlockableItem unlockableItem, Action<UnlockableInfoBuilder> callback) { UnlockableInfoBuilder unlockableInfoBuilder = new UnlockableInfoBuilder(key, unlockableItem); callback(unlockableInfoBuilder); DawnUnlockableItemInfo dawnUnlockableItemInfo = unlockableInfoBuilder.Build(); unlockableItem.SetDawnInfo(dawnUnlockableItemInfo); LethalContent.Unlockables.Register(dawnUnlockableItemInfo); return dawnUnlockableItemInfo; } public static DawnItemInfo DefineItem(NamespacedKey<DawnItemInfo> key, Item item, Action<ItemInfoBuilder> callback) { ItemInfoBuilder itemInfoBuilder = new ItemInfoBuilder(key, item); callback(itemInfoBuilder); DawnItemInfo dawnItemInfo = itemInfoBuilder.Build(); item.SetDawnInfo(dawnItemInfo); LethalContent.Items.Register(dawnItemInfo); return dawnItemInfo; } public static DawnEnemyInfo DefineEnemy(NamespacedKey<DawnEnemyInfo> key, EnemyType enemy, Action<EnemyInfoBuilder> callback) { EnemyInfoBuilder enemyInfoBuilder = new EnemyInfoBuilder(key, enemy); callback(enemyInfoBuilder); DawnEnemyInfo dawnEnemyInfo = enemyInfoBuilder.Build(); enemy.SetDawnInfo(dawnEnemyInfo); LethalContent.Enemies.Register(dawnEnemyInfo); return dawnEnemyInfo; } public static void ApplyTag(JSONTagDefinition definition) { JSONTagDefinition definition2 = definition; NamespacedKey namespacedKey2 = NamespacedKey.Parse(definition2.Tag); ListenToRegistry<DawnMoonInfo>(LethalContent.Moons, namespacedKey2); ListenToRegistry<DawnMapObjectInfo>(LethalContent.MapObjects, namespacedKey2); ListenToRegistry<DawnEnemyInfo>(LethalContent.Enemies, namespacedKey2); ListenToRegistry<DawnItemInfo>(LethalContent.Items, namespacedKey2); ListenToRegistry<DawnWeatherEffectInfo>(LethalContent.Weathers, namespacedKey2); ListenToRegistry<DawnDungeonInfo>(LethalContent.Dungeons, namespacedKey2); ListenToRegistry<DawnUnlockableItemInfo>(LethalContent.Unlockables, namespacedKey2); Debuggers.Tags?.Log($"Scheduled applying tag: {namespacedKey2}"); void ListenToRegistry<T>(TaggedRegistry<T> registry, NamespacedKey namespacedKey) where T : notnull, DawnBaseInfo<T> { TaggedRegistry<T> registry2 = registry; NamespacedKey namespacedKey3 = namespacedKey; registry2.OnFreeze += delegate { string[] values = definition2.Values; foreach (string input in values) { if (registry2.TryGetValue(NamespacedKey.Parse(input), out var value)) { value.Internal_AddTag(namespacedKey3); } } }; } } public static void ApplyAllTagsInFolder(string path) { string[] files = Directory.GetFiles(path, "*.tag.json", SearchOption.AllDirectories); foreach (string path2 in files) { JSONTagDefinition definition = JsonConvert.DeserializeObject<JSONTagDefinition>(File.ReadAllText(path2)); ApplyTag(definition); } } } internal static class AdditionalTilesRegistrationHandler { [CompilerGenerated] private static class <>O { public static hook_Awake <0>__CollectVanillaDungeons; public static hook_Start <1>__CollectModdedDungeons; } [Serializable] [CompilerGenerated] private sealed class <>c { public static readonly <>c <>9 = new <>c(); public static hook_Generate <>9__0_0; public static Func<IndoorMapType, DungeonFlow> <>9__1_0; public static Func<IndoorMapType, DungeonFlow> <>9__2_0; internal void <Init>b__0_0(orig_Generate orig, RuntimeDungeon self) { TryInjectTileSets(self.Generator.DungeonFlow); orig.Invoke(self); } internal DungeonFlow <CollectVanillaDungeons>b__1_0(IndoorMapType it) { return it.dungeonFlow; } internal DungeonFlow <CollectModdedDungeons>b__2_0(IndoorMapType it) { return it.dungeonFlow; } } private static readonly Dictionary<string, string> _internalToHumanDungeonNames = new Dictionary<string, string> { { "LevelOne", "Facility" }, { "LevelTwo", "Mansion" }, { "LevelThree", "Mineshaft" } }; internal static void Init() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //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_003b: Expected O, but got Unknown //IL_0054: Unknown result type (might be due to invalid IL or missing references) //IL_0059: Unknown result type (might be due to invalid IL or missing references) //IL_005f: Expected O, but got Unknown object obj = <>O.<0>__CollectVanillaDungeons; if (obj == null) { hook_Awake val = CollectVanillaDungeons; <>O.<0>__CollectVanillaDungeons = val; obj = (object)val; } StartOfRound.Awake += (hook_Awake)obj; object obj2 = <>O.<1>__CollectModdedDungeons; if (obj2 == null) { hook_Start val2 = CollectModdedDungeons; <>O.<1>__CollectModdedDungeons = val2; obj2 = (object)val2; } RoundManager.Start += (hook_Start)obj2; object obj3 = <>c.<>9__0_0; if (obj3 == null) { hook_Generate val3 = delegate(orig_Generate orig, RuntimeDungeon self) { TryInjectTileSets(self.Generator.DungeonFlow); orig.Invoke(self); }; <>c.<>9__0_0 = val3; obj3 = (object)val3; } RuntimeDungeon.Generate += (hook_Generate)obj3; } private static void CollectVanillaDungeons(orig_Awake orig, StartOfRound self) { if (LethalContent.Dungeons.IsFrozen) { orig.Invoke(self); return; } foreach (DungeonFlow item in ((Component)((Component)self).transform.parent).GetComponentInChildren<RoundManager>().dungeonFlowTypes.Select((IndoorMapType it) => it.dungeonFlow)) { if (!((Object)(object)item == (Object)null)) { string name = FormatFlowName(item); NamespacedKey<DawnDungeonInfo> byReflection = DungeonKeys.GetByReflection(name); if (byReflection == null) { DawnPlugin.Logger.LogWarning((object)(((Object)item).name + " is vanilla, but DawnLib couldn't get a corresponding NamespacedKey!")); continue; } HashSet<NamespacedKey> tags = new HashSet<NamespacedKey> { DawnLibTags.IsExternal }; CollectLLLTags(item, tags); DawnDungeonInfo dawnDungeonInfo = new DawnDungeonInfo(byReflection, tags, item, null); item.SetDawnInfo(dawnDungeonInfo); LethalContent.Dungeons.Register(dawnDungeonInfo); } } orig.Invoke(self); } private static void CollectModdedDungeons(orig_Start orig, RoundManager self) { if (LethalContent.Dungeons.IsFrozen) { orig.Invoke(self); return; } orig.Invoke(self); foreach (DungeonFlow item in self.dungeonFlowTypes.Select((IndoorMapType it) => it.dungeonFlow)) { if (!((Object)(object)item == (Object)null) && !item.HasDawnInfo()) { Debuggers.Dungeons?.Log("Registering potentially modded dungeon: " + ((Object)item).name); string modName; NamespacedKey<DawnDungeonInfo> key = ((!LethalLevelLoaderCompat.Enabled || !LethalLevelLoaderCompat.TryGetExtendedDungeonModName(item, out modName)) ? NamespacedKey<DawnDungeonInfo>.From("unknown_modded", NamespacedKey.NormalizeStringForNamespacedKey(((Object)item).name, CSharpName: false)) : NamespacedKey<DawnDungeonInfo>.From(NamespacedKey.NormalizeStringForNamespacedKey(modName, CSharpName: false), NamespacedKey.NormalizeStringForNamespacedKey(((Object)item).name, CSharpName: false))); HashSet<NamespacedKey> tags = new HashSet<NamespacedKey> { DawnLibTags.IsExternal }; CollectLLLTags(item, tags); DawnDungeonInfo dawnDungeonInfo = new DawnDungeonInfo(key, tags, item, null); item.SetDawnInfo(dawnDungeonInfo); LethalContent.Dungeons.Register(dawnDungeonInfo); } } CollectArchetypesAndTileSets(); LethalContent.Dungeons.Freeze(); } private static void CollectArchetypesAndTileSets() { foreach (DawnDungeonInfo value in LethalContent.Dungeons.Values) { DungeonArchetype[] usedArchetypes = value.DungeonFlow.GetUsedArchetypes(); foreach (DungeonArchetype val in usedArchetypes) { Debuggers.Dungeons?.Log("dungeonArchetype.name: " + ((Object)val).name); NamespacedKey<DawnArchetypeInfo> namespacedKey; if (value.Key.IsVanilla()) { string name = FormatArchetypeName(val); namespacedKey = DungeonArchetypeKeys.GetByReflection(name); if (namespacedKey == null) { DawnPlugin.Logger.LogWarning((object)$"archetype: '{((Object)val).name}' (part of {value.Key}) is vanilla, but DawnLib couldn't get a corresponding NamespacedKey!"); continue; } } else { namespacedKey = NamespacedKey<DawnArchetypeInfo>.From(value.Key.Namespace, NamespacedKey.NormalizeStringForNamespacedKey(((Object)val).name, CSharpName: false)); } if (LethalContent.Archetypes.ContainsKey(namespacedKey)) { Debuggers.Dungeons?.Log($"LethalContent.Archetypes already contains {namespacedKey}"); continue; } DawnArchetypeInfo dawnArchetypeInfo = new DawnArchetypeInfo(namespacedKey, new HashSet<NamespacedKey> { DawnLibTags.IsExternal }, val, null); val.SetDawnInfo(dawnArchetypeInfo); dawnArchetypeInfo.ParentInfo = value; LethalContent.Archetypes.Register(dawnArchetypeInfo); List<TileSet> tileSets = val.TileSets; List<TileSet> branchCapTileSets = val.BranchCapTileSets; int num = 0; TileSet[] array = (TileSet[])(object)new TileSet[tileSets.Count + branchCapTileSets.Count]; foreach (TileSet item in tileSets) { array[num] = item; num++; } foreach (TileSet item2 in branchCapTileSets) { array[num] = item2; num++; } IEnumerable<TileSet> enumerable = new <>z__ReadOnlyArray<TileSet>(array); foreach (TileSet item3 in enumerable) { Debuggers.Dungeons?.Log("tileSet.name: " + ((Object)item3).name); NamespacedKey<DawnTileSetInfo> namespacedKey2; if (value.Key.IsVanilla()) { string name2 = FormatTileSetName(item3); namespacedKey2 = DungeonTileSetKeys.GetByReflection(name2); if (namespacedKey2 == null) { DawnPlugin.Logger.LogWarning((object)$"tileset: '{((Object)item3).name}' (part of {namespacedKey}) is vanilla, but DawnLib couldn't get a corresponding NamespacedKey!"); continue; } } else { namespacedKey2 = NamespacedKey<DawnTileSetInfo>.From(value.Key.Namespace, NamespacedKey.NormalizeStringForNamespacedKey(((Object)val).name, CSharpName: false)); } if (LethalContent.TileSets.ContainsKey(namespacedKey2)) { Debuggers.Dungeons?.Log($"LethalContent.TileSets already contains {namespacedKey2}"); continue; } DawnTileSetInfo dawnTileSetInfo = new DawnTileSetInfo(namespacedKey2, new HashSet<NamespacedKey> { DawnLibTags.IsExternal }, ConstantPredicate.True, item3, val.BranchCapTileSets.Contains(item3), val.TileSets.Contains(item3), null); dawnArchetypeInfo.AddTileSet(dawnTileSetInfo); item3.SetDawnInfo(dawnTileSetInfo); LethalContent.TileSets.Register(dawnTileSetInfo); } } } LethalContent.Archetypes.Freeze(); LethalContent.TileSets.Freeze(); } private static string FormatTileSetName(TileSet tileSet) { string input = NamespacedKey.NormalizeStringForNamespacedKey(((Object)tileSet).name, CSharpName: true); return ReplaceInternalLevelNames(input).Replace("Tiles", string.Empty); } private static string FormatArchetypeName(DungeonArchetype dungeonArchetype) { string input = NamespacedKey.NormalizeStringForNamespacedKey(((Object)dungeonArchetype).name, CSharpName: true); return ReplaceInternalLevelNames(input).Replace("Archetype", string.Empty); } private static string FormatFlowName(DungeonFlow dungeonFlow) { string input = NamespacedKey.NormalizeStringForNamespacedKey(((Object)dungeonFlow).name, CSharpName: true); return ReplaceInternalLevelNames(input); } private static string ReplaceInternalLevelNames(string input) { foreach (KeyValuePair<string, string> internalToHumanDungeonName in _internalToHumanDungeonNames) { internalToHumanDungeonName.Deconstruct(out var key, out var value); string oldValue = key; string newValue = value; input = input.Replace(oldValue, newValue); } return input; } private static void CollectLLLTags(DungeonFlow dungeonFlow, HashSet<NamespacedKey> tags) { if (LethalLevelLoaderCompat.Enabled && LethalLevelLoaderCompat.TryGetAllTagsWithModNames(dungeonFlow, out List<(string, string)> allTagsWithModNames)) { tags.AddToList(allTagsWithModNames, Debuggers.Dungeons, ((Object)dungeonFlow).name); } } internal static void TryInjectTileSets(DungeonFlow dungeonFlow) { DungeonArchetype[] usedArchetypes = dungeonFlow.GetUsedArchetypes(); foreach (DungeonArchetype val in usedArchetypes) { foreach (DawnTileSetInfo tileSet in val.GetDawnInfo().TileSets) { if (tileSet.HasTag(DawnLibTags.IsExternal)) { continue; } if (val.BranchCapTileSets.Contains(tileSet.TileSet)) { val.BranchCapTileSets.Remove(tileSet.TileSet); } if (val.TileSets.Contains(tileSet.TileSet)) { val.TileSets.Remove(tileSet.TileSet); } if (tileSet.InjectionPredicate.Evaluate()) { if (tileSet.IsBranchCap) { val.BranchCapTileSets.Add(tileSet.TileSet); } if (tileSet.IsRegular) { val.TileSets.Add(tileSet.TileSet); } } } } } } public class DawnArchetypeInfo : DawnBaseInfo<DawnArchetypeInfo> { private List<DawnTileSetInfo> _tileSets = new List<DawnTileSetInfo>(); public DungeonArchetype DungeonArchetype { get; } public IReadOnlyList<DawnTileSetInfo> TileSets => _tileSets.AsReadOnly(); public DawnDungeonInfo ParentInfo { get; internal set; } internal DawnArchetypeInfo(NamespacedKey<DawnArchetypeInfo> key, HashSet<NamespacedKey> tags, DungeonArchetype archetype, IDataContainer? customData) : base(key, tags, customData) { DungeonArchetype = archetype; } public void AddTileSet(DawnTileSetInfo info) { if (LethalContent.Dungeons.IsFrozen) { throw new RegistryFrozenException(); } _tileSets.Add(info); } } public class DawnDungeonInfo : DawnBaseInfo<DawnDungeonInfo> { private List<DoorwaySocket> _sockets; public DungeonFlow DungeonFlow { get; } public IReadOnlyList<DoorwaySocket> Sockets => _sockets.AsReadOnly(); internal DawnDungeonInfo(NamespacedKey<DawnDungeonInfo> key, HashSet<NamespacedKey> tags, DungeonFlow dungeonFlow, IDataContainer? customData) : base(key, tags, customData) { DungeonFlow = dungeonFlow; _sockets = new List<DoorwaySocket>(); foreach (GameObjectChance item in (from it in DungeonFlow.GetUsedTileSets() select it.TileWeights.Weights).SelectMany((List<GameObjectChance> it) => it)) { Doorway[] componentsInChildren = item.Value.GetComponentsInChildren<Doorway>(); Doorway[] array = componentsInChildren; foreach (Doorway val in array) { if (!Sockets.Contains(val.socket)) { _sockets.Add(val.socket); } } } } } public class DawnTileSetInfo : DawnBaseInfo<DawnTileSetInfo> { public TileSet TileSet { get; } public bool IsBranchCap { get; } public bool IsRegular { get; } public IPredicate InjectionPredicate { get; } internal DawnTileSetInfo(NamespacedKey<DawnTileSetInfo> key, HashSet<NamespacedKey> tags, IPredicate injectionRule, TileSet tileSet, bool isBranchCap, bool isRegular, IDataContainer? customData) : base(key, tags, customData) { TileSet = tileSet; IsBranchCap = isBranchCap; IsRegular = isRegular; InjectionPredicate = injectionRule; } } public static class DungeonArchetypeExtensions { public static DawnArchetypeInfo GetDawnInfo(this DungeonArchetype archetype) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) return (DawnArchetypeInfo)((IDawnObject)archetype).DawnInfo; } internal static bool HasDawnInfo(this DungeonArchetype archetype) { return archetype.GetDawnInfo() != null; } internal static void SetDawnInfo(this DungeonArchetype archetype, DawnArchetypeInfo archetypeInfo) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) ((IDawnObject)archetype).DawnInfo = archetypeInfo; } } public static class DungeonFlowExtensions { public static DawnDungeonInfo GetDawnInfo(this DungeonFlow dungeonFlow) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) return (DawnDungeonInfo)((IDawnObject)dungeonFlow).DawnInfo; } internal static bool HasDawnInfo(this DungeonFlow dungeonFlow) { return dungeonFlow.GetDawnInfo() != null; } internal static void SetDawnInfo(this DungeonFlow dungeonFlow, DawnDungeonInfo dungeonInfo) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) ((IDawnObject)dungeonFlow).DawnInfo = dungeonInfo; } } public static class TileSetExtensions { public static DawnTileSetInfo GetDawnInfo(this TileSet tileSet) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) return (DawnTileSetInfo)((IDawnObject)tileSet).DawnInfo; } internal static bool HasDawnInfo(this TileSet tileSet) { return tileSet.GetDawnInfo() != null; } internal static void SetDawnInfo(this TileSet tileSet, DawnTileSetInfo tileSetInfo) { //IL_0003: Unknown result type (might be due to invalid IL or missing references) ((IDawnObject)tileSet).DawnInfo = tileSetInfo; } } public class TilesetInfoBuilder : BaseInfoBuilder<DawnTileSetInfo, TileSet, TilesetInfoBuilder> { private bool _branchCap; private bool _regular = true; private IPredicate? _predicate; internal TilesetInfoBuilder(NamespacedKey<DawnTileSetInfo> key, TileSet value) : base(key, value) { } public TilesetInfoBuilder SetIsBranchCap(bool value) { _branchCap = value; return this; } public TilesetInfoBuilder SetIsRegular(bool value) { _regular = value; return this; } public TilesetInfoBuilder SetInjectionPredicate(IPredicate predicate) { _predicate = predicate; return this; } internal override DawnTileSetInfo Build() { if (_predicate == null) { _predicate = ConstantPredicate.True; } return new DawnTileSetInfo(base.key, new HashSet<NamespacedKey>(), _predicate, base.value, _branchCap, _regular, customData); } } internal static class EnemyRegistrationHandler { [CompilerGenerated] private static class <>O { public static hook_RefreshEnemiesList <0>__UpdateEnemyWeights; public static hook_SetPlanetsWeather <1>__UpdateEnemyWeights; public static hook_Start <2>__EnsureCorrectEnemyVariables; public static Action <3>__RegisterEnemies; public static hook_Start <4>__AddEnemiesToDebugList; public static hook_Awake <5>__AddBestiaryNodes; } internal static void Init() { //IL_00d0: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00db: Expected O, but got Unknown //IL_00f0: Unknown result type (might be due to invalid IL or missing references) //IL_00f5: Unknown result type (might be due to invalid IL or missing references) //IL_00fb: Expected O, but got Unknown //IL_0110: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Unknown result type (might be due to invalid IL or missing references) //IL_011b: Expected O, but got Unknown //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_0160: Expected O, but got Unknown //IL_0175: Unknown result type (might be due to invalid IL or missing references) //IL_017a: Unknown result type (might be due to invalid IL or missing references) //IL_0180: Expected O, but got Unknown LethalContent.Enemies.AddAutoTaggers(new SimpleAutoTagger<DawnEnemyInfo>(Tags.Killable, (DawnEnemyInfo info) => info.EnemyType.canDie), new SimpleAutoTagger<DawnEnemyInfo>(Tags.Small, (DawnEnemyInfo info) => (int)info.EnemyType.EnemySize == 0), new SimpleAutoTagger<DawnEnemyInfo>(Tags.Medium, (DawnEnemyInfo info) => (int)info.EnemyType.EnemySize == 2), new SimpleAutoTagger<DawnEnemyInfo>(Tags.Large, (DawnEnemyInfo info) => (int)info.EnemyType.EnemySize == 1)); object obj = <>O.<0>__UpdateEnemyWeights; if (obj == null) { hook_RefreshEnemiesList val = UpdateEnemyWeights; <>O.<0>__UpdateEnemyWeights = val; obj = (object)val; } RoundManager.RefreshEnemiesList += (hook_RefreshEnemiesList)obj; object obj2 = <>O.<1>__UpdateEnemyWeights; if (obj2 == null) { hook_SetPlanetsWeather val2 = UpdateEnemyWeights; <>O.<1>__UpdateEnemyWeights = val2; obj2 = (object)val2; } StartOfRound.SetPlanetsWeather += (hook_SetPlanetsWeather)obj2; object obj3 = <>O.<2>__EnsureCorrectEnemyVariables; if (obj3 == null) { hook_Start val3 = EnsureCorrectEnemyVariables; <>O.<2>__EnsureCorrectEnemyVariables = val3; obj3 = (object)val3; } EnemyAI.Start += (hook_Start)obj3; LethalContent.Moons.OnFreeze += RegisterEnemies; object obj4 = <>O.<4>__AddEnemiesToDebugList; if (obj4 == null) { hook_Start val4 = AddEnemiesToDebugList; <>O.<4>__AddEnemiesToDebugList = val4; obj4 = (object)val4; } QuickMenuManager.Start += (hook_Start)obj4; object obj5 = <>O.<5>__AddBestiaryNodes; if (obj5 == null) { hook_Awake val5 = AddBestiaryNodes; <>O.<5>__AddBestiaryNodes = val5; obj5 = (object)val5; } Terminal.Awake += (hook_Awake)obj5; } private static void AddBestiaryNodes(orig_Awake orig, Terminal self) { //IL_0134: 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) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_0158: Expected O, but got Unknown TerminalKeyword val = self.terminalNodes.allKeywords.First((TerminalKeyword it) => it.word == "info"); List<TerminalKeyword> list = self.terminalNodes.allKeywords.ToList(); List<CompatibleNoun> list2 = val.compatibleNouns.ToList(); foreach (DawnEnemyInfo value in LethalContent.Enemies.Values) { if (!value.HasTag(DawnLibTags.IsExternal) && Object.op_Implicit((Object)(object)value.BestiaryNode) && Object.op_Implicit((Object)(object)value.NameKeyword)) { value.BestiaryNode.creatureFileID = self.enemyFiles.Count; self.enemyFiles.Add(value.BestiaryNode); ScanNodeProperties[] componentsInChildren = value.EnemyType.enemyPrefab.GetComponentsInChildren<ScanNodeProperties>(); ScanNodeProperties[] array = componentsInChildren; foreach (ScanNodeProperties val2 in array) { val2.creatureScanID = value.BestiaryNode.creatureFileID; } if (!list.Contains(value.NameKeyword)) { value.NameKeyword.defaultVerb = val; list.Add(value.NameKeyword); list2.Add(new CompatibleNoun { noun = value.NameKeyword, result = value.BestiaryNode }); } } } val.compatibleNouns = list2.ToArray(); self.terminalNodes.allKeywords = list.ToArray(); orig.Invoke(self); } private static void AddEnemiesToDebugList(orig_Start orig, QuickMenuManager self) { //IL_0051: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0067: Unknown result type (might be due to invalid IL or missing references) //IL_006f: Expected O, but got Unknown SelectableLevel level = LethalContent.Moons[MoonKeys.Test].Level; foreach (DawnEnemyInfo enemyInfo in LethalContent.Enemies.Values) { if (!enemyInfo.HasTag(DawnLibTags.IsExternal)) { SpawnableEnemyWithRarity item = new SpawnableEnemyWithRarity { enemyType = enemyInfo.EnemyType, rarity = 0 }; if (enemyInfo.Inside != null && level.Enemies.All((SpawnableEnemyWithRarity enemy) => (Object)(object)enemy.enemyType != (Object)(object)enemyInfo.EnemyType)) { Debuggers.Enemies?.Log($"Adding {enemyInfo.EnemyType} to test level {((Object)level).name} inside."); level.Enemies.Add(item); } if (enemyInfo.Outside != null && level.OutsideEnemies.All((SpawnableEnemyWithRarity enemy) => (Object)(object)enemy.enemyType != (Object)(object)enemyInfo.EnemyType)) { Debuggers.Enemies?.Log($"Adding {enemyInfo.EnemyType} to test level {((Object)level).name} outside."); level.OutsideEnemies.Add(item); } if (enemyInfo.Daytime != null && level.DaytimeEnemies.All((SpawnableEnemyWithRarity enemy) => (Object)(object)enemy.enemyType != (Object)(object)enemyInfo.EnemyType)) { Debuggers.Enemies?.Log($"Adding {enemyInfo.EnemyType} to test level {((Object)level).name} daytime."); level.DaytimeEnemies.Add(item); } } } orig.Invoke(self); } private static void EnsureCorrectEnemyVariables(orig_Start orig, EnemyAI self) { //IL_00d2: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Unknown result type (might be due to invalid IL or missing references) //IL_011a: Unknown result type (might be due to invalid IL or missing references) //IL_0125: Unknown result type (might be due to invalid IL or missing references) if (!self.enemyType.HasDawnInfo()) { DawnPlugin.Logger.LogError((object)("Enemy with names " + ((Object)self.enemyType).name + " and " + self.enemyType.enemyName + " has no DawnEnemyInfo, this means this enemy is not properly registered.")); orig.Invoke(self); return; } DawnEnemyInfo dawnInfo = self.enemyType.GetDawnInfo(); if (dawnInfo.HasTag(DawnLibTags.IsExternal) || StarlancerAIFixCompat.Enabled) { orig.Invoke(self); return; } if (dawnInfo.Daytime != null) { self.enemyType.isDaytimeEnemy = true; } GameObject[] insideAINodes = RoundManager.Instance.insideAINodes; GameObject[] outsideAINodes = RoundManager.Instance.outsideAINodes; bool flag = true; float num = float.MaxValue; if (insideAINodes != null) { GameObject[] array = insideAINodes; foreach (GameObject val in array) { float num2 = Vector3.Distance(val.transform.position, ((Component)self).transform.position); if (!(num2 >= num)) { num = num2; } } } if (outsideAINodes != null) { GameObject[] array2 = outsideAINodes; foreach (GameObject val2 in array2) { float num3 = Vector3.Distance(val2.transform.position, ((Component)self).transform.position); if (num3 < num) { num = num3; flag = false; break; } } } bool isOutsideEnemy = self.enemyType.isOutsideEnemy; if (flag) { self.enemyType.isOutsideEnemy = false; } else { self.enemyType.isOutsideEnemy = true; } orig.Invoke(self); if (isOutsideEnemy != self.enemyType.isOutsideEnemy) { self.enemyType.isOutsideEnemy = isOutsideEnemy; } } private static void UpdateEnemyWeights(orig_RefreshEnemiesList orig, RoundManager self) { UpdateEnemyWeightsOnLevel(self.currentLevel); orig.Invoke(self); } private static void UpdateEnemyWeights(orig_SetPlanetsWeather orig, StartOfRound self, int connectedPlayersOnServer) { orig.Invoke(self, connectedPlayersOnServer); UpdateEnemyWeightsOnLevel(self.currentLevel); } internal static void UpdateEnemyWeightsOnLevel(SelectableLevel level) { if (!LethalContent.Enemies.IsFrozen || (Object)(object)StartOfRound.Instance == (Object)null || (WeatherRegistryCompat.Enabled && WeatherRegistryCompat.IsWeatherManagerReady())) { return; } foreach (DawnEnemyInfo enemyInfo in LethalContent.Enemies.Values) { if (enemyInfo.HasTag(DawnLibTags.IsExternal)) { continue; } Debuggers.Enemies?.Log($"Updating weights for {enemyInfo.EnemyType} on level {level.PlanetName}"); if (enemyInfo.Outside != null) { level.OutsideEnemies.Where((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyInfo.EnemyType).First().rarity = enemyInfo.Outside.Weights.GetFor(level.GetDawnInfo()).GetValueOrDefault(); } if (enemyInfo.Inside != null) { level.Enemies.Where((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyInfo.EnemyType).First().rarity = enemyInfo.Inside.Weights.GetFor(level.GetDawnInfo()).GetValueOrDefault(); } if (enemyInfo.Daytime != null) { level.DaytimeEnemies.Where((SpawnableEnemyWithRarity x) => (Object)(object)x.enemyType == (Object)(object)enemyInfo.EnemyType).First().rarity = enemyInfo.Daytime.Weights.GetFor(level.GetDawnInfo()).GetValueOrDefault(); } } } private static void RegisterEnemies() { Dictionary<EnemyType, WeightTableBuilder<DawnMoonInfo>> dictionary = new Dictionary<EnemyType, WeightTableBuilder<DawnMoonInfo>>(); Dictionary<EnemyType, WeightTableBuilder<DawnMoonInfo>> dictionary2 = new Dictionary<EnemyType, WeightTableBuilder<DawnMoonInfo>>(); Dictionary<EnemyType, WeightTableBuilder<DawnMoonInfo>> dictionary3 = new Dictionary<EnemyType, WeightTableBuilder<DawnMoonInfo>>(); foreach (DawnMoonInfo value4 in LethalContent.Moons.Values) { SelectableLevel level = value4.Level; NamespacedKey<DawnMoonInfo> typedKey = value4.TypedKey; foreach (SpawnableEnemyWithRarity enemy in level.Enemies) { if (!((Object)(object)enemy.enemyType == (Object)null)) { if (!dictionary.TryGetValue(enemy.enemyType, out var value)) { value = new WeightTableBuilder<DawnMoonInfo>(); dictionary[enemy.enemyType] = value; } value.AddWeight(typedKey, enemy.rarity); } } foreach (SpawnableEnemyWithRarity outsideEnemy in level.OutsideEnemies) { if (!((Object)(object)outsideEnemy.enemyType == (Object)null)) { if (!dictionary2.TryGetValue(outsideEnemy.enemyType, out var value2)) { value2 = new WeightTableBuilder<DawnMoonInfo>(); dictionary2[outsideEnemy.enemyType] = value2; } value2.AddWeight(typedKey, outsideEnemy.rarity); } } foreach (SpawnableEnemyWithRarity daytimeEnemy in level.DaytimeEnemies) { if (!((Object)(object)daytimeEnemy.enemyType == (Object)null)) { if (!dictionary3.TryGetValue(daytimeEnemy.enemyType, out var value3)) { value3 = new WeightTableBuilder<DawnMoonInfo>(); dictionary3[daytimeEnemy.enemyType] = value3; } value3.AddWeight(typedKey, daytimeEnemy.rarity); } } } TerminalKeyword infoKeyword = TerminalRefs.InfoKeyword; foreach (DawnMoonInfo value5 in LethalContent.Moons.Values) { SelectableLevel level2 = value5.Level; List<SpawnableEnemyWithRarity> enemies = level2.Enemies; List<SpawnableEnemyWithRarity> outsideEnemies = level2.OutsideEnemies; List<SpawnableEnemyWithRarity> daytimeEnemies = level2.DaytimeEnemies; List<SpawnableEnemyWithRarity> list = new List<SpawnableEnemyWithRarity>(enemies.Count + outsideEnemies.Count + daytimeEnemies.Count); foreach (SpawnableEnemyWithRarity item in enemies) { list.Add(item); } foreach (SpawnableEnemyWithRarity item2 in outsideEnemies) { list.Add(item2); } foreach (SpawnableEnemyWithRarity item3 in daytimeEnemies) { list.Add(item3); } List<SpawnableEnemyWithRarity> list2 = list; foreach (SpawnableEnemyWithRarity item4 in list2) { EnemyType enemyType = item4.enemyType; if ((Object)(object)enemyType == (Object)null || (Object)(object)enemyType.enemyPrefab == (Object)null || enemyType.HasDawnInfo()) { continue; } string name = NamespacedKey.NormalizeStringForNamespacedKey(enemyType.enemyName, CSharpName: true); NamespacedKey<DawnEnemyInfo> namespacedKey = EnemyKeys.GetByReflection(name); string modName2; if (namespacedKey == null && LethalLibCompat.Enabled && LethalLibCompat.TryGetEnemyTypeFromLethalLib(enemyType, out string modName)) { namespacedKey = NamespacedKey<DawnEnemyInfo>.From(NamespacedKey.NormalizeStringForNamespacedKey(modName, CSharpName: false), NamespacedKey.NormalizeStringForNamespacedKey(enemyType.enemyName, CSharpName: false)); } else if (namespacedKey == null && LethalLevelLoaderCompat.Enabled && LethalLevelLoaderCompat.TryGetExtendedEnemyTypeModName(enemyType, out modName2)) { namespacedKey = NamespacedKey<DawnEnemyInfo>.From(NamespacedKey.NormalizeStringForNamespacedKey(modName2, CSharpName: false), NamespacedKey.NormalizeStringForNamespacedKey(enemyType.enemyName, CSharpName: false)); } else if (namespacedKey == null) { namespacedKey = NamespacedKey<DawnEnemyInfo>.From("unknown_lib", NamespacedKey.NormalizeStringForNamespacedKey(enemyType.enemyName, CSharpName: false)); } if (LethalContent.Enemies.ContainsKey(namespacedKey)) { DawnPlugin.Logger.LogWarning((object)("Enemy " + enemyType.enemyName + " is already registered by the same creator to LethalContent. This is likely to cause issues.")); enemyType.SetDawnInfo(LethalContent.Enemies[namespacedKey]); continue; } if (!Object.op_Implicit((Object)(object)enemyType.enemyPrefab)) { DawnPlugin.Logger.LogWarning((object)(enemyType.enemyName + " (" + ((Object)enemyType).name + ") didn't have a spawn prefab?")); continue; } DawnEnemyLocationInfo inside = null; DawnEnemyLocationInfo outside = null; DawnEnemyLocationInfo daytime = null; if (dictionary.ContainsKey(enemyType)) { inside = new DawnEnemyLocationInfo(dictionary[enemyType].Build()); } if (dictionary2.ContainsKey(enemyType)) { outside = new DawnEnemyLocationInfo(dictionary2[enemyType].Build()); } if (dictionary3.ContainsKey(enemyType)) { daytime = new DawnEnemyLocationInfo(dictionary3[enemyType].Build()); } HashSet<NamespacedKey> tags = new HashSet<NamespacedKey> { DawnLibTags.IsExternal }; CollectLLLTags(enemyType, tags); TerminalNode bestiaryNode = null; TerminalKeyword nameKeyword = null; ScanNodeProperties componentInChildren = enemyType.enemyPrefab.GetComponentInChildren<ScanNodeProperties>(); if ((Object)(object)componentInChildren != (Object)null) { int creatureScanID = componentInChildren.creatureScanID; CompatibleNoun[] compatibleNouns = infoKeyword.compatibleNouns; foreach (CompatibleNoun val in compatibleNouns) { if (val.result.creatureFileID == creatureScanID) { bestiaryNode = val.result; nameKeyword = val.noun; } } } DawnEnemyInfo dawnEnemyInfo = new DawnEnemyInfo(namespacedKey, tags, enemyType, outside, inside, daytime, bestiaryNode, nameKeyword, null); enemyType.SetDawnInfo(dawnEnemyInfo); LethalContent.Enemies.Register(dawnEnemyInfo); } foreach (DawnEnemyInfo value6 in LethalContent.Enemies.Values) { if (!value6.HasTag(DawnLibTags.IsExternal)) { if (value6.Outside != null) { TryAddToEnemyList(value6, level2.OutsideEnemies); } if (value6.Daytime != null) { TryAddToEnemyList(value6, level2.DaytimeEnemies); } if (value6.Inside != null) { TryAddToEnemyList(value6, level2.Enemies); } } } } LethalContent.Enemies.Freeze(); } private static void CollectLLLTags(EnemyType enemyType, HashSet<NamespacedKey> tags) { if (LethalLevelLoaderCompat.Enabled && LethalLevelLoaderCompat.TryGetAllTagsWithModNames(enemyType, out List<(string, string)> allTagsWithModNames)) { tags.AddToList(allTagsWithModNames, Debuggers.Enemies, ((Object)enemyType).name); } } private static void TryAddToEnemyList(DawnEnemyInfo enemyInfo, List<SpawnableEnemyWithRarity> list) { //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_0019: Expected O, but got Unknown SpawnableEnemyWithRarity item = new SpawnableEnemyWithRarity { enemyType = enemyInfo.EnemyType, rarity = 0 }; list.Add(item); } } public sealed class DawnEnemyInfo : DawnBaseInfo<DawnEnemyInfo> { public EnemyType EnemyType { get; } public DawnEnemyLocationInfo? Outside { get; } public DawnEnemyLocationInfo? Inside { get; } public DawnEnemyLocationInfo? Daytime { get; } public TerminalNode? BestiaryNode { get; } public TerminalKeyword? NameKeyword { get; } internal DawnEnemyInfo(NamespacedKey<DawnEnemyInfo> key, HashSet<NamespacedKey> tags, EnemyType enemyType, DawnEnemyLocationInfo? outside, DawnEnemyLocationInfo? inside, DawnEnemyLocationInfo? daytime, TerminalNode? bestiaryNode, TerminalKeyword? nameKeyword, IDataContainer? customData) : base(key, tags, customData) { EnemyType = enemyType; Outside = outside; if (Outside != null) { Outside.ParentInfo = this; } Inside = inside; if (Inside != null) { Inside.ParentInfo = this; } Daytime = daytime; if (Daytime != null) { Daytime.ParentInfo = this; } BestiaryNode = bestiaryNode; NameKeyword = nameKeyword; } public IEnumerable<T> GetAllSpawned<T>() where T : EnemyAI { foreach (EnemyAI spawnedEnemy in RoundManager.Instance.SpawnedEnemies) { if ((Object)(object)spawnedEnemy.enemyType == (Object)(object)EnemyType) { yield return (T)(object)spawnedEnemy; } } } } public class DawnEnemyLocationInfo { public DawnEnemyInfo ParentInfo { get; internal set; } public ProviderTable<int?, DawnMoonInfo> Weights { get; } internal DawnEnemyLocationInfo(ProviderTable<int?, DawnMoonInfo> weights) { Weights = weights; } } public class EnemyInfoBuilder : BaseInfoBuilder<DawnEnemyInfo, EnemyType, EnemyInfoBuilder> { public class EnemyLocationBuilder { private ProviderTable<int?, DawnMoonInfo>? _weights; private EnemyInfoBuilder _parent; public EnemyLocationBuilder SetWeights(Action<WeightTableBuilder<DawnMoonInfo>> callback) { WeightTableBuilder<DawnMoonInfo> weightTableBuilder = new WeightTableBuilder<DawnMoonInfo>(); callback(weightTableBuilder); _weights = weightTableBuilder.Build(); return this; } internal EnemyLocationBuilder(EnemyInfoBuilder parent) { _parent = parent; } internal DawnEnemyLocationInfo Build() { if (_weights == null) { DawnPlugin.Logger.LogWarning((object)$"Enemy '{_parent.key}' didn't set weights. If you intend to have no weights (doing something special), call .SetWeights(() => {{}})"); _weights = ProviderTable<int?, DawnMoonInfo>.Empty(); } return new DawnEnemyLocationInfo(_weights); } } private DawnEnemyLocationInfo? _inside; private DawnEnemyLocationInfo? _outside; private DawnEnemyLocationInfo? _daytime; private TerminalNode? _bestiaryNode; private TerminalKeyword? _nameKeyword; internal EnemyInfoBuilder(NamespacedKey<DawnEnemyInfo> key, EnemyType enemyType) : base(key, enemyType) { } public EnemyInfoBuilder DefineOutside(Action<EnemyLocationBuilder> callback) { EnemyLocationBuilder enemyLocationBuilder = new EnemyLocationBuilder(this); callback(enemyLocationBuilder); _outside = enemyLocationBuilder.Build(); return this; } public EnemyInfoBuilder DefineInside(Action<EnemyLocationBuilder> callback) { EnemyLocationBuilder enemyLocationBuilder = new EnemyLocationBuilder(this); callback(enemyLocationBuilder); _inside = enemyLocationBuilder.Build(); return this; } public EnemyInfoBuilder DefineDaytime(Action<EnemyLocationBuilder> callback) { EnemyLocationBuilder enemyLocationBuilder = new EnemyLocationBuilder(this); callback(enemyLocationBuilder); _daytime = enemyLocationBuilder.Build(); return this; } public EnemyInfoBuilder SetBestiaryNode(TerminalNode node) { _bestiaryNode = node; return this; } public EnemyInfoBuilder OverrideNameKeyword(string word) { _nameKeyword = ScriptableObject.CreateInstance<TerminalKeyword>(); ((Object)_nameKeyword).name = word; _nameKeyword.word = word; return this; } public EnemyInfoBuilder OverrideNameKeyword(TerminalKeyword keyword) { _nameKeyword = keyword; return this; } internal override DawnEnemyInfo Build() { if ((Object)(object)_bestiaryNode == (Object)null) { _bestiaryNode = new TerminalNodeBuilder(base.value.enemyName + "BestiaryNode").SetDisplayText(base.value.enemyName + "\n\nDanger level: Unknown\n\n[No information about this creature was found.]\n\n").SetClearPreviousText(clearPreviousText: true).SetMaxCharactersToType(35) .Build(); } if ((Object)(object)_nameKeyword == (Object)null) { string word = base.value.enemyName.ToLowerInvariant().Replace(' ', '-'); OverrideNameKeyword(word); } _bestiaryNode.creatureName = base.value.enemyName; return new DawnEnemyInfo(base.key, tags, base.value, _outside, _inside, _daytime, _bestiaryNode, _nameKeyword, customData); } } public static class EnemyTypeExtensions { public static DawnEnemyInfo GetDawnInfo(this EnemyType enemyType) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return (DawnEnemyInfo)((IDawnObject)enemyType).DawnInfo; } internal static bool HasDawnInfo(this EnemyType enemyType) { return enemyType.GetDawnInfo() != null; } internal static void SetDawnInfo(this EnemyType enemyType, DawnEnemyInfo enemyInfo) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) ((IDawnObject)enemyType).DawnInfo = enemyInfo; } } public class BundleException : Exception { public AssetBundle Bundle { get; } public BundleException(AssetBundle bundle, string message) { Bundle = bundle; base..ctor(message); } } public class MalformedAnimationCurveConfigException : Exception { public string Pair { get; } public MalformedAnimationCurveConfigException(string pair) { Pair = pair; base..ctor(); } public void LogNicely(ManualLogSource? logger) { if (logger != null) { string[] array = (from s in Pair.Split(',') select s.Trim()).ToArray(); logger.LogError((object)("Invalid key,value pair format: '" + Pair + "'! More details:")); logger.LogError((object)$" Found '{array.Length}' parts"); if (array.Length != 2) { logger.LogError((object)" FAIL -> Should have only 2 parts!"); return; } LogNicelyFloatParse(logger, "first", array[0]); LogNicelyFloatParse(logger, "second", array[1]); } } private void LogNicelyFloatParse(ManualLogSource logger, string context, string value) { logger.LogError((object)(" Attempting to parse " + context + " value: '" + value + "'")); if (float.TryParse(value, NumberStyles.Float, CultureInfo.InvariantCulture, out var result)) { logger.LogError((object)$" Parsed {context} value! Parsed Value is {result}"); } else { logger.LogError((object)$" FAIL -> Couldn't parse {context} value! Parsed Value is {result}"); } } } public interface IPredicate { bool Evaluate(); } public class ConstantPredicate : IPredicate { public static readonly ConstantPredicate True = new ConstantPredicate(value: true); public static readonly ConstantPredicate False = new ConstantPredicate(value: false); private bool _value; private ConstantPredicate(bool value) { _value = value; } public bool Evaluate() { return _value; } } public interface IProvider<out T> { T Provide(); } public class SimpleProvider<T> : IProvider<T> { [CompilerGenerated] private T <value>P; public SimpleProvider(T value) { <value>P = value; base..ctor(); } public T Provide() { return <value>P; } } internal static class ItemRegistrationHandler { [CompilerGenerated] private static class <>O { public static hook_SpawnScrapInLevel <0>__UpdateItemWeights; public static hook_SetPlanetsWeather <1>__UpdateItemWeights; public static hook_Awake <2>__RegisterShopItemsToTerminal; public static Action <3>__FreezeItemContent; } internal static void Init() { //IL_02b0: Unknown result type (might be due to invalid IL or missing references) //IL_02b5: Unknown result type (might be due to invalid IL or missing references) //IL_02bb: Expected O, but got Unknown //IL_02d0: Unknown result type (might be due to invalid IL or missing references) //IL_02d5: Unknown result type (might be due to invalid IL or missing references) //IL_02db: Expected O, but got Unknown //IL_02f0: Unknown result type (might be due to invalid IL or missing references) //IL_02f5: Unknown result type (might be due to invalid IL or missing references) //IL_02fb: Expected O, but got Unknown LethalContent.Items.AddAutoTaggers(new AutoNonInteractableTagger(), new SimpleAutoTagger<DawnItemInfo>(Tags.Conductive, (DawnItemInfo itemInfo) => itemInfo.Item.isConductiveMetal), new SimpleAutoTagger<DawnItemInfo>(Tags.Noisy, (DawnItemInfo itemInfo) => (Object)(object)itemInfo.Item.spawnPrefab.GetComponent<NoisemakerProp>() != (Object)null), new SimpleAutoTagger<DawnItemInfo>(Tags.Interactable, (DawnItemInfo itemInfo) => !itemInfo.HasTag(Tags.NonInteractable) && !itemInfo.HasTag(Tags.Noisy)), new SimpleAutoTagger<DawnItemInfo>(Tags.Paid, (DawnItemInfo itemInfo) => itemInfo.ShopInfo != null), new SimpleAutoTagger<DawnItemInfo>(Tags.Scrap, (DawnItemInfo itemInfo) => itemInfo.ScrapInfo != null), new SimpleAutoTagger<DawnItemInfo>(Tags.Chargeable, (DawnItemInfo itemInfo) => itemInfo.Item.requiresBattery), new SimpleAutoTagger<DawnItemInfo>(Tags.TwoHanded, (DawnItemInfo itemInfo) => itemInfo.Item.twoHanded), new SimpleAutoTagger<DawnItemInfo>(Tags.OneHanded, (DawnItemInfo itemInfo) => !itemInfo.Item.twoHanded), new SimpleAutoTagger<DawnItemInfo>(Tags.Weapon, (DawnItemInfo itemInfo) => itemInfo.Item.isDefensiveWeapon), new AutoItemGroupTagger(Tags.GeneralItemClassGroup, "GeneralItemClass"), new AutoItemGroupTagger(Tags.SmallItemsGroup, "SmallItems"), new AutoItemGroupTagger(Tags.TabletopItemsGroup, "TabletopItems"), new AutoItemGroupTagger(Tags.TestItemGroup, "TestItem"), new AutoValueTagger(Tags.LowValue, new BoundedRange(0f, 100f)), new AutoValueTagger(Tags.MediumValue, new BoundedRange(100f, 200f)), new AutoValueTagger(Tags.HighValue, new BoundedRange(200f, 2.1474836E+09f)), new AutoWeightTagger(Tags.LightWeight, new BoundedRange(0f, 1.2f)), new AutoWeightTagger(Tags.MediumWeight, new BoundedRange(1.2f, 1.4f)), new AutoWeightTagger(Tags.HeavyWeight, new BoundedRange(1.4f, 2.1474836E+09f))); object obj = <>O.<0>__UpdateItemWeights; if (obj == null) { hook_SpawnScrapInLevel val = UpdateItemWeights; <>O.<0>__UpdateItemWeights = val; obj = (object)val; } RoundManager.SpawnScrapInLevel += (hook_SpawnScrapInLevel)obj; object obj2 = <>O.<1>__UpdateItemWeights; if (obj2 == null) { hook_SetPlanetsWeather val2 = UpdateItemWeights; <>O.<1>__UpdateItemWeights = val2; obj2 = (object)val2; } StartOfRound.SetPlanetsWeather += (hook_SetPlanetsWeather)obj2; object obj3 = <>O.<2>__RegisterShopItemsToTerminal; if (obj3 == null) { hook_Awake val3 = RegisterShopItemsToTerminal; <>O.<2>__RegisterShopItemsToTerminal = val3; obj3 = (object)val3; } Terminal.Awake += (hook_Awake)obj3; LethalContent.Moons.OnFreeze += FreezeItemContent; } internal static void UpdateAllShopItemPrices() { foreach (DawnItemInfo value in LethalContent.Items.Values) { DawnShopItemInfo shopInfo = value.ShopInfo; if (shopInfo != null && !value.HasTag(DawnLibTags.IsExternal)) { UpdateShopItemPrices(shopInfo); } } } private static void UpdateShopItemPrices(DawnShopItemInfo shopInfo) { int num = shopInfo.Cost.Provide(); shopInfo.ParentInfo.Item.creditsWorth = num; shopInfo.ReceiptNode.itemCost = num; shopInfo.RequestNode.itemCost = num; } private static void UpdateItemWeights(orig_SpawnScrapInLevel orig, RoundManager self) { UpdateItemWeightsOnLevel(self.currentLevel); orig.Invoke(self); } private static void UpdateItemWeights(orig_SetPlanetsWeather orig, StartOfRound self, int connectedPlayersOnServer) { orig.Invoke(self, connectedPlayersOnServer); UpdateItemWeightsOnLevel(self.currentLevel); } internal static void UpdateItemWeightsOnLevel(SelectableLevel level) { if (!LethalContent.Items.IsFrozen || (Object)(object)StartOfRound.Instance == (Object)null || (WeatherRegistryCompat.Enabled && WeatherRegistryCompat.IsWeatherManagerReady())) { return; } foreach (DawnItemInfo itemInfo in LethalContent.Items.Values) { DawnScrapItemInfo scrapInfo = itemInfo.ScrapInfo; if (scrapInfo != null && !itemInfo.HasTag(DawnLibTags.IsExternal)) { Debuggers.Items?.Log("Updating " + itemInfo.Item.itemName + "'s weights on level " + level.PlanetName + "."); level.spawnableScrap.Where((SpawnableItemWithRarity x) => (Object)(object)x.spawnableItem == (Object)(object)itemInfo.Item).First().rarity = scrapInfo.Weights.GetFor(level.GetDawnInfo()).GetValueOrDefault(); } } } private static void FreezeItemContent() { //IL_03c7: Unknown result type (might be due to invalid IL or missing references) //IL_03cc: Unknown result type (might be due to invalid IL or missing references) //IL_03d4: Unknown result type (might be due to invalid IL or missing references) //IL_03de: Expected O, but got Unknown if (LethalContent.Items.IsFrozen) { return; } Dictionary<Item, WeightTableBuilder<DawnMoonInfo>> dictionary = new Dictionary<Item, WeightTableBuilder<DawnMoonInfo>>(); Dictionary<Item, DawnShopItemInfo> dictionary2 = new Dictionary<Item, DawnShopItemInfo>(); foreach (DawnMoonInfo value5 in LethalContent.Moons.Values) { SelectableLevel level = value5.Level; foreach (SpawnableItemWithRarity item2 in level.spawnableScrap) { if (!dictionary.TryGetValue(item2.spawnableItem, out var value)) { value = new WeightTableBuilder<DawnMoonInfo>(); dictionary[item2.spawnableItem] = value; } value.AddWeight(value5.TypedKey, item2.rarity); } } Terminal instance = TerminalRefs.Instance; TerminalKeyword buyKeyword = TerminalRefs.BuyKeyword; TerminalKeyword infoKeyword = TerminalRefs.InfoKeyword; List<CompatibleNoun> list = buyKeyword.compatibleNouns.ToList(); List<CompatibleNoun> list2 = infoKeyword.compatibleNouns.ToList(); List<TerminalKeyword> list3 = instance.terminalNodes.allKeywords.ToList(); foreach (TerminalKeyword item3 in list3) { Debuggers.Items?.Log("TerminalKeyword.word for " + ((Object)item3).name + ": " + item3.word); item3.word = item3.word.Replace(" ", "-").ToLowerInvariant(); } int i; for (i = 0; i < instance.buyableItemsList.Length; i++) { Item val = instance.buyableItemsList[i]; TerminalNode val2 = null; TerminalNode requestNode = null; TerminalNode val3 = null; Debuggers.Items?.Log("Processing " + val.itemName); string simplifiedItemName = val.itemName.Replace(" ", "-").ToLowerInvariant(); requestNode = (from noun in TerminalRefs.BuyKeyword.compatibleNouns where noun.result.buyItemIndex == i select noun.result).FirstOrDefault(); if ((Object)(object)requestNode == (Object)null) { DawnPlugin.Logger.LogWarning((object)("No request Node found for " + val.itemName + " despite it being a buyable item, this is likely the result of an item being removed from the shop items list by LethalLib, i.e. Night Vision Goggles from MoreShipUpgrades")); continue; } val3 = requestNode.terminalOptions[0].result; TerminalKeyword val4 = (from noun in TerminalRefs.BuyKeyword.compatibleNouns where (Object)(object)noun.result == (Object)(object)requestNode select noun.noun).FirstOrDefault() ?? ((IEnumerable<TerminalKeyword>)list3).FirstOrDefault((Func<TerminalKeyword, bool>)((TerminalKeyword keyword) => keyword.word == simplifiedItemName)); if ((Object)(object)val4 == (Object)null) { DawnPlugin.Logger.LogWarning((object)("No buy Keyword found for " + val.itemName + " despite it being a buyable item, this is likely the result of an item being removed from the shop items list by LethalLib, i.e. Night Vision Goggles from MoreShipUpgrades")); continue; } CompatibleNoun[] compatibleNouns = infoKeyword.compatibleNouns; foreach (CompatibleNoun val5 in compatibleNouns) { if ((Object)(object)val5.noun == (Object)(object)val4) { val2 = val5.result; break; } Debuggers.Items?.Log("Checking compatible nouns for info node: " + val5.noun.word); } if ((Object)(object)val2 == (Object)null) { val2 = new TerminalNodeBuilder(simplifiedItemName + "InfoNode").SetDisplayText("[No information about this object was found.]\n\n").SetClearPreviousText(clearPreviousText: true).SetMaxCharactersToType(25) .Build(); CompatibleNoun item = new CompatibleNoun { noun = val4, result = val2 }; List<CompatibleNoun> list4 = infoKeyword.compatibleNouns.ToList(); list4.Add(item); infoKeyword.compatibleNouns = list4.ToArray(); } CompatibleNoun[] compatibleNouns2 = buyKeyword.compatibleNouns; foreach (CompatibleNoun val6 in compatibleNouns2) { if ((Object)(object)val6.noun == (Object)(object)val4) { requestNode = val6.result; break; } Debuggers.Items?.Log("Checking compatible nouns for request node: " + val6.noun.word); } DawnShopItemInfo value2 = new DawnShopItemInfo(ITerminalPurchasePredicate.AlwaysSuccess(), val2, requestNode, val3, new SimpleProvider<int>(val.creditsWorth)); dictionary2[val] = value2; } foreach (Item items in StartOfRound.Instance.allItemsList.itemsList) { if (items.HasDawnInfo()) { continue; } string name = NamespacedKey.NormalizeStringForNamespacedKey(items.itemName, CSharpName: true); NamespacedKey<DawnItemInfo> namespacedKey = ItemKeys.GetByReflection(name); string modName2; if (namespacedKey == null && LethalLibCompat.Enabled && LethalLibCompat.TryGetItemFromLethalLib(items, out string modName)) { namespacedKey = NamespacedKey<DawnItemInfo>.From(NamespacedKey.NormalizeStringForNamespacedKey(modName, CSharpName: false), NamespacedKey.NormalizeStringForNamespacedKey(items.itemName, CSharpName: false)); } else if (namespacedKey == null && LethalLevelLoaderCompat.Enabled && LethalLevelLoaderCompat.TryGetExtendedItemModName(items, out modName2)) { namespacedKey = NamespacedKey<DawnItemInfo>.From(NamespacedKey.NormalizeStringForNamespacedKey(modName2, CSharpName: false), NamespacedKey.NormalizeStringForNamespacedKey(items.itemName, CSharpName: false)); } else if (namespacedKey == null) { namespacedKey = NamespacedKey<DawnItemInfo>.From("unknown_lib", NamespacedKey.NormalizeStringForNamespacedKey(items.itemName, CSharpName: false)); } if (LethalContent.Items.ContainsKey(namespacedKey)) { DawnPlugin.Logger.LogWarning((object)("Item " + items.itemName + " is already registered by the same creator to LethalContent. This is likely to cause issues.")); items.SetDawnInfo(LethalContent.Items[namespacedKey]); continue; } dictionary.TryGetValue(items, out var value3); DawnScrapItemInfo scrapItemInfo = null; dictionary2.TryGetValue(items, out var value4); if (value3 != null) { scrapItemInfo = new DawnScrapItemInfo(value3.Build()); } if (!Object.op_Implicit((Object)(object)items.spawnPrefab)) { DawnPlugin.Logger.LogWarning((object)(items.itemName + " (" + ((Object)items).name + ") didn't have a spawn prefab?")); continue; } HashSet<NamespacedKey> tags = new HashSet<NamespacedKey> { DawnLibTags.IsExternal }; CollectLLLTags(items, tags); DawnItemInfo dawnItemInfo = new DawnItemInfo(namespacedKey, tags, items, scrapItemInfo, value4, null); items.SetDawnInfo(dawnItemInfo); LethalContent.Items.Register(dawnItemInfo); } RegisterScrapItemsToAllLevels(); LethalContent.Items.Freeze(); } private static void RegisterScrapItemsToAllLevels() { //IL_005c: 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_006d: Unknown result type (might be due to invalid IL or missing references) //IL_0076: Expected O, but got Unknown foreach (DawnItemInfo value in LethalContent.Items.Values) { DawnScrapItemInfo scrapInfo = value.ScrapInfo; if (scrapInfo == null || value.HasTag(DawnLibTags.IsExternal)) { continue; } foreach (DawnMoonInfo value2 in LethalContent.Moons.Values) { SelectableLevel level = value2.Level; SpawnableItemWithRarity item = new SpawnableItemWithRarity { spawnableItem = value.Item, rarity = 0 }; level.spawnableScrap.Add(item); } if (value.ShopInfo == null) { StartOfRound.Instance.allItemsList.itemsList.Add(value.Item); } } } private static void RegisterShopItemsToTerminal(orig_Awake orig, Terminal self) { //IL_01af: Unknown result type (might be due to invalid IL or missing references) //IL_01b4: Unknown result type (might be due to invalid IL or missing references) //IL_01bb: Unknown result type (might be due to invalid IL or missing references) //IL_01c4: Expected O, but got Unknown //IL_01c6: Unknown result type (might be due to invalid IL or missing references) //IL_01cb: Unknown result type (might be due to invalid IL or missing references) //IL_01d3: Unknown result type (might be due to invalid IL or missing references) //IL_01dc: Expected O, but got Unknown //IL_01e3: Unknown result type (might be due to invalid IL or missing references) //IL_01e8: Unknown result type (might be due to invalid IL or missing references) //IL_01f0: Unknown result type (might be due to invalid IL or missing references) //IL_01fd: Expected O, but got Unknown //IL_01ff: Unknown result type (might be due to invalid IL or missing references) //IL_0204: Unknown result type (might be due to invalid IL or missing references) //IL_020c: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Expected O, but got Unknown Terminal instance = TerminalRefs.Instance; TerminalKeyword buyKeyword = TerminalRefs.BuyKeyword; TerminalKeyword infoKeyword = TerminalRefs.InfoKeyword; TerminalKeyword confirmPurchaseKeyword = TerminalRefs.ConfirmPurchaseKeyword; TerminalKeyword denyKeyword = TerminalRefs.DenyKeyword; TerminalNode cancelPurchaseNode = TerminalRefs.CancelPurchaseNode; List<Item> list = self.buyableItemsList.ToList(); List<CompatibleNoun> list2 = buyKeyword.compatibleNouns.ToList(); List<CompatibleNoun> list3 = infoKeyword.compatibleNouns.ToList(); List<TerminalKeyword> list4 = self.terminalNodes.allKeywords.ToList(); StartOfRound instance2 = StartOfRoundRefs.Instance; foreach (DawnItemInfo value in LethalContent.Items.Values) { DawnShopItemInfo shopInfo = value.ShopInfo; if (shopInfo == null || value.HasTag(DawnLibTags.IsExternal)) { continue; } string text = value.Item.itemName.Replace(" ", "-").ToLowerInvariant(); list.Add(value.Item); foreach (TerminalKeyword item in list4) { _ = item.word == text; } TerminalKeyword val = ScriptableObject.CreateInstance<TerminalKeyword>(); ((Object)val).name = text; val.word = text; val.isVerb = false; val.compatibleNouns = null; val.specialKeywordResult = null; val.defaultVerb = buyKeyword; val.accessTerminalObjects = false; list4.Add(val); TerminalNode receiptNode = shopInfo.ReceiptNode; TerminalNode requestNode = shopInfo.RequestNode; UpdateShopItemPrices(shopInfo); receiptNode.buyItemIndex = list.Count - 1; requestNode.buyItemIndex = list.Count - 1; requestNode.isConfirmationNode = true; requestNode.overrideOptions = true; requestNode.terminalOptions = (CompatibleNoun[])(object)new CompatibleNoun[2] { new CompatibleNoun { noun = confirmPurchaseKeyword, result = receiptNode }, new CompatibleNoun { noun = denyKeyword, result = cancelPurchaseNode } }; list2.Add(new CompatibleNoun { noun = val, result = requestNode }); list3.Add(new CompatibleNoun { noun = val, result = shopInfo.InfoNode }); instance2.allItemsList.itemsList.Add(value.Item); } self.buyableItemsList = list.ToArray(); infoKeyword.compatibleNouns = list3.ToArray(); buyKeyword.compatibleNouns = list2.ToArray(); self.terminalNodes.allKeywords = list4.ToArray(); orig.Invoke(self); } private static void CollectLLLTags(Item item, HashSet<NamespacedKey> tags) { if (LethalLevelLoaderCompat.Enabled && LethalLevelLoaderCompat.TryGetAllTagsWithModNames(item, out List<(string, string)> allTagsWithModNames)) { tags.AddToList(allTagsWithModNames, Debuggers.Items, ((Object)item).name); } } } public class AutoItemGroupTagger : IAutoTagger<DawnItemInfo> { [CompilerGenerated] private NamespacedKey <tag>P; [CompilerGenerated] private string <itemGroupName>P; public NamespacedKey Tag => <tag>P; public AutoItemGroupTagger(NamespacedKey tag, string itemGroupName) { <tag>P = tag; <itemGroupName>P = itemGroupName; base..ctor(); } public bool ShouldApply(DawnItemInfo info) { if (info.Item.spawnPositionTypes == null) { return false; } foreach (ItemGroup spawnPositionType in info.Item.spawnPositionTypes) { if ((Object)(object)spawnPositionType == (Object)null) { DawnPlugin.Logger.LogWarning((object)$"Item: {info.Key} has a null ItemGroup, why!?!?"); } else if (((Object)spawnPositionType).name == <itemGroupName>P) { return true; } } return false; } } public class AutoNonInteractableTagger : IAutoTagger<DawnItemInfo> { public NamespacedKey Tag => Tags.NonInteractable; public bool ShouldApply(DawnItemInfo info) { GrabbableObject val = default(GrabbableObject); if (info.Item.spawnPrefab.TryGetComponent<GrabbableObject>(ref val)) { return ((object)val).GetType() == typeof(GrabbableObject); } return false; } } public class AutoValueTagger : IAutoTagger<DawnItemInfo> { [CompilerGenerated] private NamespacedKey <tag>P; [CompilerGenerated] private BoundedRange <range>P; public NamespacedKey Tag => <tag>P; public AutoValueTagger(NamespacedKey tag, BoundedRange range) { <tag>P = tag; <range>P = range; base..ctor(); } public bool ShouldApply(DawnItemInfo info) { float value = (float)(info.Item.maxValue + info.Item.minValue) / 2f; return <range>P.IsInRange(value); } } public class AutoWeightTagger : IAutoTagger<DawnItemInfo> { [CompilerGenerated] private NamespacedKey <tag>P; [CompilerGenerated] private BoundedRange <range>P; public NamespacedKey Tag => <tag>P; public AutoWeightTagger(NamespacedKey tag, BoundedRange range) { <tag>P = tag; <range>P = range; base..ctor(); } public bool ShouldApply(DawnItemInfo info) { return <range>P.IsInRange(info.Item.weight); } } public sealed class DawnItemInfo : DawnBaseInfo<DawnItemInfo> { public Item Item { get; } public DawnScrapItemInfo? ScrapInfo { get; } public DawnShopItemInfo? ShopInfo { get; } internal DawnItemInfo(NamespacedKey<DawnItemInfo> key, HashSet<NamespacedKey> tags, Item item, DawnScrapItemInfo? scrapItemInfo, DawnShopItemInfo? shopItemInfo, IDataContainer? customData) : base(key, tags, customData) { Item = item; ScrapInfo = scrapItemInfo; if (ScrapInfo != null) { ScrapInfo.ParentInfo = this; } ShopInfo = shopItemInfo; if (ShopInfo != null) { ShopInfo.ParentInfo = this; } } } public sealed class DawnScrapItemInfo { public DawnItemInfo ParentInfo { get; internal set; } public ProviderTable<int?, DawnMoonInfo> Weights { get; } internal DawnScrapItemInfo(ProviderTable<int?, DawnMoonInfo> weights) { Weights = weights; } } public sealed class DawnShopItemInfo : ITerminalPurchase { public DawnItemInfo ParentInfo { get; internal set; } public TerminalNode? InfoNode { get; } public TerminalNode RequestNode { get; } public TerminalNode ReceiptNode { get; } public IProvider<int> Cost { get; } public ITerminalPurchasePredicate PurchasePredicate { get; } internal DawnShopItemInfo(ITerminalPurchasePredicate predicate, TerminalNode? infoNode, TerminalNode requestNode, TerminalNode receiptNode, IProvider<int> cost) { PurchasePredicate = predicate; InfoNode = infoNode; RequestNode = requestNode; ReceiptNode = receiptNode; Cost = cost; } public void AddToDropship(bool ignoreMax = false, int count = 1) { Terminal instance = TerminalRefs.Instance; for (int i = 0; i < count; i++) { if (!ignoreMax && instance.orderedItemsFromTerminal.Count > 12) { break; } instance.orderedItemsFromTerminal.Add(RequestNode.buyItemIndex); instance.numberOfItemsInDropship++; } } public int GetSalePercentage() { Terminal instance = TerminalRefs.Instance; return instance.itemSalesPercentages[RequestNode.buyItemIndex]; } } public static class ItemExtensions { public static DawnItemInfo GetDawnInfo(this Item item) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return (DawnItemInfo)((IDawnObject)item).DawnInfo; } internal static bool HasDawnInfo(this Item item) { return item.GetDawnInfo() != null; } internal static void SetDawnInfo(this Item item, DawnItemInfo itemInfo) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) ((IDawnObject)item).DawnInfo = itemInfo; } } public class ItemInfoBuilder : BaseInfoBuilder<DawnItemInfo, Item, ItemInfoBuilder> { public class ScrapBuilder { private ItemInfoBuilder _parentBuilder; private ProviderTable<int?, DawnMoonInfo>? _weights; internal ScrapBuilder(ItemInfoBuilder parent) { _parentBuilder = parent; } public ScrapBuilder SetWeights(Action<WeightTableBuilder<DawnMoonInfo>> callback) { WeightTableBuilder<DawnMoonInfo> weightTableBuilder = new WeightTableBuilder<DawnMoonInfo>(); callback(weightTableBuilder); _weights = weightTableBuilder.Build(); return this; } internal DawnScrapItemInfo Build() { if (_weights == null) { DawnPlugin.Logger.LogWarning((object)("Scrap item '" + _parentBuilder.value.itemName + "' didn't set weights. If you intend to have no weights (doing something special), call .SetWeights(() => {})")); _weights = ProviderTable<int?, DawnMoonInfo>.Empty(); } return new DawnScrapItemInfo(_weights); } } public class ShopBuilder { private ItemInfoBuilder _parentBuilder; private TerminalNode? _infoNode; private TerminalNode? _requestNode; private TerminalNode? _receiptNode; private IProvider<int>? _costOverride; private ITerminalPurchasePredicate? _purchasePredicate; internal ShopBuilder(ItemInfoBuilder parent) { _parentBuilder = parent; } public ShopBuilder OverrideCost(int cost) { return OverrideCost(new SimpleProvider<int>(cost)); } public ShopBuilder OverrideCost(IProvider<int> cost) { _costOverride = cost; return this; } public ShopBuilder SetPurchasePredicate(ITerminalPurchasePredicate predicate) { _purchasePredicate = predicate; return this; } public ShopBuilder OverrideInfoNode(TerminalNode infoNode) { _infoNode = infoNode; return this; } public ShopBuilder OverrideRequestNode(TerminalNode requestNode) { _requestNode = requestNode; return this; } public ShopBuilder OverrideReceiptNode(TerminalNode receiptNode) { _receiptNode = receiptNode; return this; } internal DawnShopItemInfo Build() { if ((Object)(object)_receiptNode == (Object)null) { _receiptNode = new TerminalNodeBuilder(_parentBuilder.value.itemName + "ReceiptNode").SetDisplayText("Ordered [variableAmount] " + _parentBuilder.value.itemName + ". Your new balance is [playerCredits].\n\nOur contractors enjoy fast, free shipping while on the job! Any purchased items will arrive hourly at your approximate location.\r\n\r\n").SetClearPreviousText(clearPreviousText: true).SetMaxCharactersToType(15) .Build(); } if ((Object)(object)_requestNode == (Object)null) { _requestNode = new TerminalNodeBuilder(_parentBuilder.value.itemName + "RequestNode").SetDisplayText("You have requested to order " + _parentBuilder.value.itemName + ". Amount: [variableAmount].\nTotal cost of items: [totalCost].\n\nPlease CONFIRM or DENY.\r\n\r\n").SetClearPreviousText(clearPreviousText: true).SetMaxCharactersToType(35) .Build(); } if ((Object)(object)_infoNode == (Object)null) { _infoNode = new TerminalNodeBuilder(_parentBuilder.value.itemName + "InfoNode").SetDisplayText("[No information about this object was found.]\n\n").SetClearPreviousText(clearPreviousText: true).SetMaxCharactersToType(25) .Build(); } if (_purchasePredicate == null) { _purchasePredicate = ITerminalPurchasePredicate.AlwaysSuccess(); } if (_costOverride == null) { _costOverride = new SimpleProvider<int>(_parentBuilder.value.creditsWorth); } return new DawnShopItemInfo(_purchasePredicate, _infoNode, _requestNode, _receiptNode, _costOverride); } } private DawnScrapItemInfo? _scrapInfo; private DawnShopItemInfo? _shopInfo; internal ItemInfoBuilder(NamespacedKey<DawnItemInfo> key, Item item) : base(key, item) { } public ItemInfoBuilder DefineShop(Action<ShopBuilder> callback) { ShopBuilder shopBuilder = new ShopBuilder(this); callback(shopBuilder); _shopInfo = shopBuilder.Build(); return this; } public ItemInfoBuilder DefineScrap(Action<ScrapBuilder> callback) { ScrapBuilder scrapBuilder = new ScrapBuilder(this); callback(scrapBuilder); _scrapInfo = scrapBuilder.Build(); return this; } internal override DawnItemInfo Build() { return new DawnItemInfo(base.key, tags, base.value, _scrapInfo, _shopInfo, customData); } } public static class LethalContent { public static TaggedRegistry<DawnItemInfo> Items = new TaggedRegistry<DawnItemInfo>(); public static TaggedRegistry<DawnEnemyInfo> Enemies = new TaggedRegistry<DawnEnemyInfo>(); public static TaggedRegistry<DawnMapObjectInfo> MapObjects = new TaggedRegistry<DawnMapObjectInfo>(); public static TaggedRegistry<DawnMoonInfo> Moons = new TaggedRegistry<DawnMoonInfo>(); public static Registry<DawnTileSetInfo> TileSets = new Registry<DawnTileSetInfo>(); public static TaggedRegistry<DawnDungeonInfo> Dungeons = new TaggedRegistry<DawnDungeonInfo>(); public static TaggedRegistry<DawnUnlockableItemInfo> Unlockables = new TaggedRegistry<DawnUnlockableItemInfo>(); public static TaggedRegistry<DawnWeatherEffectInfo> Weathers = new TaggedRegistry<DawnWeatherEffectInfo>(); public static Registry<DawnArchetypeInfo> Archetypes = new Registry<DawnArchetypeInfo>(); } public static class DawnLibTags { internal static readonly NamespacedKey IsExternal = NamespacedKey.From("dawn_lib", "is_external"); } internal static class MapObjectRegistrationHandler { [CompilerGenerated] private static class <>O { public static hook_SetPlanetsWeather <0>__UpdateMapObjectSpawnWeights; public static hook_SpawnOutsideHazards <1>__SpawnOutsideMapObjects; public static Manipulator <2>__RegenerateNavMeshTranspiler; public static hook_SpawnMapObjects <3>__UpdateMapObjectSpawnWeights; public static Action <4>__RegisterMapObjects; } private static int _spawnedObjects; internal static void Init() { //IL_0010: Unknown result type (might be due to invalid IL or missing references) //IL_0015: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown //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_003b: Expected O, but got Unknown //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0055: Unknown result type (might be due to invalid IL or missing references) //IL_005b: Expected O, but got Unknown //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_007b: Expected O, but got Unknown object obj = <>O.<0>__UpdateMapObjectSpawnWeights; if (obj == null) { hook_SetPlanetsWeather val = UpdateMapObjectSpawnWeights; <>O.<0>__UpdateMapObjectSpawnWeights = val; obj = (object)val; } StartOfRound.SetPlanetsWeather += (hook_SetPlanetsWeather)obj; object obj2 = <>O.<1>__SpawnOutsideMapObjects; if (obj2 == null) { hook_SpawnOutsideHazards val2 = SpawnOutsideMapObjects; <>O.<1>__SpawnOutsideMapObjects = val2;
BepInEx/plugins/DawnLib/com.github.teamxiaolan.dawnlib.dusk.dll
Decompiled 3 days 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.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using System.Text; using System.Text.RegularExpressions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using Dawn; using Dawn.Internal; using Dawn.Preloader.Interfaces; using Dawn.Utils; using DunGen; using Dusk.Internal; using Dusk.Utils; using Dusk.Weights; using Dusk.Weights.Transformers; using GameNetcodeStuff; using IL; using Microsoft.CodeAnalysis; using Mono.Cecil.Cil; using MonoMod.Cil; using MonoMod.RuntimeDetour; using Newtonsoft.Json; using On; using TMPro; using Unity.Netcode; using UnityEngine; using UnityEngine.EventSystems; using UnityEngine.Events; using UnityEngine.SceneManagement; using UnityEngine.Serialization; using UnityEngine.UI; using UnityEngine.Video; using WeatherRegistry; using WeatherRegistry.Modules; using com.github.teamxiaolan.dawnlib.dusk.NetcodePatcher; [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("XuXiaolan,loaforc")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("Assetloading, content and config management built ontop of DawnLib.")] [assembly: AssemblyFileVersion("0.1.9.0")] [assembly: AssemblyInformationalVersion("0.1.9+09cb71a636e1df245dcd8b6809da4e52cfd9ebcf")] [assembly: AssemblyProduct("DawnLib.DuskMod")] [assembly: AssemblyTitle("com.github.teamxiaolan.dawnlib.dusk")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.1.9.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [module: NetcodePatchedAssembly] internal class <Module> { static <Module>() { } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace Dusk { [AttributeUsage(AttributeTargets.Field)] public class AssertAssetInCorrectBundle : PropertyAttribute { } [AttributeUsage(AttributeTargets.Field)] public class AssertFieldNotNull : PropertyAttribute { } [AttributeUsage(AttributeTargets.Field)] public class AssertNotEmpty : PropertyAttribute { } [Serializable] public class AssetBundleData { [AssetBundleReference] public string assetBundleName; [AssertNotEmpty] public string configName; public List<WeatherData> weathers; public List<EnemyData> enemies; public List<ItemData> items; public List<MapObjectData> mapObjects; public List<UnlockableData> unlockables; public List<DungeonData> dungeons; public List<VehicleData> vehicles; [field: SerializeField] [field: FormerlySerializedAs("keepLoaded")] public bool AlwaysKeepLoaded { get; private set; } } public abstract class AssetBundleLoader<TLoader> : IAssetBundleLoader where TLoader : AssetBundleLoader<TLoader> { private readonly bool _hasNonPreloadAudioClips; private List<string> _audioClipNames = new List<string>(); private readonly bool _hasVideoClips; private List<string> _videoClipNames = new List<string>(); private AssetBundle? _bundle; public AssetBundleData? AssetBundleData { get; set; } public DuskContentDefinition[] Content { get; } public Dictionary<string, ConfigEntryBase> ConfigEntries => Content.SelectMany((DuskContentDefinition c) => c.generalConfigs).ToDictionary<KeyValuePair<string, ConfigEntryBase>, string, ConfigEntryBase>((KeyValuePair<string, ConfigEntryBase> it) => it.Key, (KeyValuePair<string, ConfigEntryBase> it) => it.Value); protected AssetBundleLoader(DuskMod mod, string filePath) : this(mod.Assembly, filePath) { } internal AssetBundleLoader(Assembly assembly, string filePath) : this(AssetBundleUtils.LoadBundle(assembly, filePath)) { } protected AssetBundleLoader(AssetBundle bundle) { _bundle = bundle; DebugLogSource assetLoading = Debuggers.AssetLoading; if (assetLoading != null) { assetLoading.Log((object)(((Object)bundle).name + " contains these objects: " + string.Join(",", bundle.GetAllAssetNames()))); } Type typeFromHandle = typeof(TLoader); PropertyInfo[] properties = typeFromHandle.GetProperties(); foreach (PropertyInfo propertyInfo in properties) { LoadFromBundleAttribute loadFromBundleAttribute = (LoadFromBundleAttribute)propertyInfo.GetCustomAttribute(typeof(LoadFromBundleAttribute)); if (loadFromBundleAttribute != null) { propertyInfo.SetValue(this, LoadAsset(bundle, loadFromBundleAttribute.BundleFile)); } } Object[] array = bundle.LoadAllAssets(); foreach (Object val in array) { GameObject val2 = (GameObject)(object)((val is GameObject) ? val : null); if (val2 == null) { VideoClip val3 = (VideoClip)(object)((val is VideoClip) ? val : null); if (val3 == null) { AudioClip val4 = (AudioClip)(object)((val is AudioClip) ? val : null); if (val4 != null && !val4.preloadAudioData) { _audioClipNames.Add(((Object)val4).name); _hasNonPreloadAudioClips = true; } } else { _videoClipNames.Add(((Object)val3).name); _hasVideoClips = true; } continue; } DawnLib.FixMixerGroups(val2); DebugLogSource assetLoading2 = Debuggers.AssetLoading; if (assetLoading2 != null) { assetLoading2.Log((object)("Fixed Mixer Groups: " + ((Object)val2).name)); } if (!((Object)(object)val2.GetComponent<NetworkObject>() == (Object)null)) { DawnLib.RegisterNetworkPrefab(val2); DebugLogSource assetLoading3 = Debuggers.AssetLoading; if (assetLoading3 != null) { assetLoading3.Log((object)("Registered Network Prefab: " + ((Object)val2).name)); } } } Content = bundle.LoadAllAssets<DuskContentDefinition>(); List<Type> definitionOrder = new List<Type>(7) { typeof(DuskWeatherDefinition), typeof(DuskMapObjectDefinition), typeof(DuskEnemyDefinition), typeof(DuskUnlockableDefinition), typeof(DuskItemDefinition), typeof(DuskAdditionalTilesDefinition), typeof(DuskAchievementDefinition) }; Content = Content.OrderBy(delegate(DuskContentDefinition it) { Type type = ((object)it).GetType(); int num = definitionOrder.IndexOf(type); return (num < 0) ? int.MaxValue : num; }).ToArray(); } public ConfigEntry<T> GetConfig<T>(string configName) { return (ConfigEntry<T>)(object)ConfigEntries[configName]; } public bool TryGetConfig<T>(string configName, [NotNullWhen(true)] out ConfigEntry<T>? entry) { if (ConfigEntries.TryGetValue(configName, out ConfigEntryBase value)) { entry = (ConfigEntry<T>)(object)value; return true; } if (Debuggers.Dusk != null) { DuskContentDefinition? duskContentDefinition = Content.FirstOrDefault(); if (duskContentDefinition != null) { ManualLogSource? logger = duskContentDefinition.Mod.Logger; if (logger != null) { logger.LogWarning((object)$"TryGetConfig: '{configName}' does not exist on '{Content}', returning false and entry will be null"); } } } entry = null; return false; } internal void TryUnload() { AssetBundleData? assetBundleData = AssetBundleData; if (assetBundleData == null || assetBundleData.AlwaysKeepLoaded) { return; } if ((Object)(object)_bundle == (Object)null) { DawnPlugin.Logger.LogError((object)"Tried to unload bundle twice?"); throw new NullReferenceException(); } if (_hasVideoClips) { DawnPlugin.Logger.LogWarning((object)("Bundle: '" + ((Object)_bundle).name + "' has at least one VideoClip but is being unloaded! Playing video clips from this bundle could cause errors! Mark `AlwaysKeepLoaded` as true to stop this warning from happening, unloading stopped.")); { foreach (string videoClipName in _videoClipNames) { DebugLogSource assetLoading = Debuggers.AssetLoading; if (assetLoading != null) { assetLoading.Log((object)("VideoClip Name: " + videoClipName)); } } return; } } if (_hasNonPreloadAudioClips) { DawnPlugin.Logger.LogWarning((object)("Bundle: '" + ((Object)_bundle).name + "' is being unloaded but contains an AudioClip that has 'preloadAudioData' to false! This will cause errors when trying to play this clip, unloading stopped.")); { foreach (string audioClipName in _audioClipNames) { DebugLogSource assetLoading2 = Debuggers.AssetLoading; if (assetLoading2 != null) { assetLoading2.Log((object)("AudioClip Name: " + audioClipName)); } } return; } } _bundle.Unload(false); _bundle = null; } private Object LoadAsset(AssetBundle bundle, string path) { Object val = bundle.LoadAsset<Object>(path); if (val == (Object)null) { throw new ArgumentException(path + " is not valid in the assetbundle!"); } return val; } } [AttributeUsage(AttributeTargets.Field)] public class AssetBundleReference : PropertyAttribute { } [CreateAssetMenu(fileName = "New Content Container", menuName = "DawnLib/Content Container", order = -10)] public class ContentContainer : ScriptableObject { public List<AssetBundleData> assetBundles; } public class DefaultBundle : AssetBundleLoader<DefaultBundle> { public DefaultBundle(DuskMod mod, string filePath) : base(mod, filePath) { } internal DefaultBundle(AssetBundle bundle) : base(bundle) { } } public interface IAssetBundleLoader { DuskContentDefinition[] Content { get; } AssetBundleData? AssetBundleData { get; set; } } [AttributeUsage(AttributeTargets.Property)] public class LoadFromBundleAttribute : Attribute { public string BundleFile { get; private set; } public LoadFromBundleAttribute(string bundleFile) { BundleFile = bundleFile; base..ctor(); } } public class AutoDuskModHandler { public static void AutoRegisterMods() { string[] files = Directory.GetFiles(Paths.PluginPath, "*.duskmod", SearchOption.AllDirectories); foreach (string text in files) { AssetBundle val = AssetBundle.LoadFromFile(text); DebugLogSource assetLoading = Debuggers.AssetLoading; if (assetLoading != null) { assetLoading.Log((object)(((Object)val).name + " contains these objects: " + string.Join(",", val.GetAllAssetNames()))); } DuskModInformation[] array = val.LoadAllAssets<DuskModInformation>(); if (array.Length == 0) { DawnPlugin.Logger.LogError((object)(".duskmod bundle: '" + Path.GetFileName(text) + "' does not have a 'Mod Information' file!")); continue; } if (array.Length > 1) { DawnPlugin.Logger.LogError((object)(".duskmod bundle: '" + Path.GetFileName(text) + "' has multiple 'Mod Information' files! Only the first one will be used.")); } DawnPlugin.Logger.LogInfo((object)("AuthorName: " + array[0].AuthorName + ", ModName: " + array[0].ModName + ", Version: " + array[0].Version)); DuskMod.RegisterNoCodeMod(array[0], val, Path.GetDirectoryName(text)); } } } public class DefaultContentHandler : ContentHandler { public DefaultContentHandler(DuskMod mod) : base(mod) { foreach (AssetBundleData assetBundle in mod.Content.assetBundles) { ManualLogSource? logger = mod.Logger; if (logger != null) { logger.LogDebug((object)$"Trying to register bundle: {assetBundle}"); } if (!IsContentEnabled(assetBundle)) { continue; } if (!mod.TryGetRelativeFile(out string fullPath, "Assets", assetBundle.assetBundleName)) { ManualLogSource? logger2 = mod.Logger; if (logger2 != null) { logger2.LogError((object)("The bundle: " + assetBundle.configName + " is not defined at plugins/" + Path.GetRelativePath(Paths.PluginPath, fullPath) + ".")); } if (mod.TryGetRelativeFile(out string fullPath2, assetBundle.assetBundleName)) { ManualLogSource? logger3 = mod.Logger; if (logger3 != null) { logger3.LogError((object)("The bundle is instead defined at plugins/" + Path.GetRelativePath(Paths.PluginPath, fullPath2) + ". It should be in an Assets/ subfolder.")); } } } else { LoadAllContent(new DefaultBundle(AssetBundle.LoadFromFile(fullPath)) { AssetBundleData = assetBundle }); } } } } [CreateAssetMenu(fileName = "Mod Information", menuName = "DawnLib/Mod Information", order = -10)] public class DuskModInformation : ScriptableObject { [field: SerializeField] public string AuthorName { get; internal set; } [field: SerializeField] public string ModName { get; internal set; } [field: SerializeField] public string Version { get; internal set; } [field: SerializeField] public TextAsset? READMEFile { get; private set; } [field: SerializeField] public TextAsset? ChangelogFile { get; private set; } [field: SerializeField] public string ModDescription { get; internal set; } [Tooltip("Comma separated list of dependencies that this mod depends on apart from the default CRLib, BepInEx and potentially WeatherRegistry, grab from the thunderstore page.")] [field: SerializeField] public List<string> ExtraDependencies { get; internal set; } = new List<string>(); [field: SerializeField] public string WebsiteUrl { get; internal set; } [field: SerializeField] public Sprite? ModIcon { get; internal set; } public BepInPlugin CreatePluginMetadata() { //IL_0022: Unknown result type (might be due to invalid IL or missing references) //IL_0028: Expected O, but got Unknown return new BepInPlugin(AuthorName + "." + ModName, ModName, Version); } } public class ConfigContext : IDisposable { [CompilerGenerated] private ConfigFile <file>P; [CompilerGenerated] private string <heading>P; public ConfigContext(ConfigFile file, string heading) { <file>P = file; <heading>P = heading; base..ctor(); } public void Dispose() { } public ConfigEntry<T> Bind<T>(string name, string description, T defaultValue = default(T)) { return <file>P.Bind<T>(ConfigManager.CleanStringForConfig(<heading>P), ConfigManager.CleanStringForConfig(name), defaultValue, description); } } public class ConfigManager { [CompilerGenerated] private ConfigFile <file>P; private static readonly Regex ConfigCleanerRegex = new Regex("[\\n\\t\"`\\[\\]']"); public ConfigManager(ConfigFile file) { <file>P = file; base..ctor(); } internal static string CleanStringForConfig(string input) { return ConfigCleanerRegex.Replace(input, string.Empty); } public ConfigContext CreateConfigSection(string header) { return new ConfigContext(<file>P, header); } public ConfigContext CreateConfigSectionForBundleData(AssetBundleData data) { return CreateConfigSection(data.configName + " Options"); } public ConfigEntryBase CreateDynamicConfig(DuskDynamicConfig configDefinition, ConfigContext context) { ConfigContext context2 = context; DuskDynamicConfig configDefinition2 = configDefinition; return (ConfigEntryBase)(configDefinition2.DynamicConfigType switch { DuskDynamicConfigType.String => Bind<string>(configDefinition2.defaultString), DuskDynamicConfigType.Int => Bind<int>(configDefinition2.defaultInt), DuskDynamicConfigType.Bool => Bind<bool>(configDefinition2.defaultBool), DuskDynamicConfigType.Float => Bind<float>(configDefinition2.defaultFloat), DuskDynamicConfigType.BoundedRange => Bind<BoundedRange>(configDefinition2.defaultBoundedRange), DuskDynamicConfigType.AnimationCurve => Bind<AnimationCurve>(configDefinition2.defaultAnimationCurve), _ => throw new ArgumentOutOfRangeException($"DynamicConfigType of '{configDefinition2.DynamicConfigType}' is not yet internally implemented!!"), }); ConfigEntryBase Bind<T>(T defaultValue) { return (ConfigEntryBase)(object)context2.Bind(configDefinition2.settingName, configDefinition2.Description, defaultValue); } } public static Dictionary<string, string> ParseLevelNameWithCurves(string configMoonRarity) { Dictionary<string, string> dictionary = new Dictionary<string, string>(); foreach (string item in from s in configMoonRarity.Split('|') select s.Trim()) { string[] array = (from s in item.Split('-') select s.Trim()).ToArray(); if (array.Length == 2) { string text = array[0].ToLowerInvariant(); if (text == "custom") { text = "modded"; } dictionary[text] = array[1]; dictionary[text + "level"] = array[1]; } } return dictionary; } public static AnimationCurve ParseCurve(string keyValuePairs) { return TomlTypeConverter.ConvertToValue<AnimationCurve>(keyValuePairs); } internal static ConfigFile GenerateConfigFile(BepInPlugin plugin) { //IL_0028: Unknown result type (might be due to invalid IL or missing references) //IL_002e: Expected O, but got Unknown return new ConfigFile(Utility.CombinePaths(new string[2] { Paths.ConfigPath, plugin.GUID + ".cfg" }), false, plugin); } } public class DuskContentConfig { public bool Enabled; } [Serializable] public class DuskDynamicConfig { public string settingName; public DuskDynamicConfigType DynamicConfigType; public string defaultString; public int defaultInt; public float defaultFloat; public bool defaultBool; public BoundedRange defaultBoundedRange; public AnimationCurve defaultAnimationCurve; public string Description; } public enum DuskDynamicConfigType { String, Int, Float, Bool, BoundedRange, AnimationCurve } public abstract class ContentHandler { [CompilerGenerated] private DuskMod <mod>P; protected ContentHandler(DuskMod mod) { <mod>P = mod; base..ctor(); } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] protected bool IsContentEnabled(string bundleName) { if (!<mod>P.TryGetBundleDataFromName(bundleName, out AssetBundleData data)) { return false; } return IsContentEnabled(data); } [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] protected bool IsContentEnabled(AssetBundleData assetBundleData) { string configName = assetBundleData.configName; using ConfigContext configContext = <mod>P.ConfigManager.CreateConfigSectionForBundleData(assetBundleData); return configContext.Bind("Enabled", "Whether " + configName + " is enabled.", defaultValue: true).Value; } protected bool TryLoadContentBundle<TAsset>(string assetBundleName, out TAsset? asset, bool forceEnabled = false) where TAsset : AssetBundleLoader<TAsset> { asset = null; if (!<mod>P.TryGetBundleDataFromName(assetBundleName, out AssetBundleData data)) { ManualLogSource? logger = <mod>P.Logger; if (logger != null) { logger.LogWarning((object)("Assetbundle name: " + assetBundleName + " is not implemented yet!")); } return false; } if (!IsContentEnabled(data) && !forceEnabled) { return false; } ConstructorInfo constructor = typeof(TAsset).GetConstructor(new Type[2] { typeof(DuskMod), typeof(string) }); if (constructor == null) { ManualLogSource? logger2 = <mod>P.Logger; if (logger2 != null) { logger2.LogError((object)(typeof(TAsset).Name + " is not properly setup to handle TryLoadContentBundle. It must have a constructor with (DuskMod, string) as arguments!")); } return false; } asset = (TAsset)constructor.Invoke(new object[2] { <mod>P, assetBundleName }); asset.AssetBundleData = data; asset.TryUnload(); return true; } protected void LoadAllContent(IAssetBundleLoader bundle) { DuskContentDefinition[] content = bundle.Content; DuskContentDefinition[] array = content; foreach (DuskContentDefinition duskContentDefinition in array) { duskContentDefinition.AssetBundleData = bundle.AssetBundleData; duskContentDefinition.Register(<mod>P); } } protected void LoadAllContent(params IAssetBundleLoader[] bundles) { foreach (IAssetBundleLoader bundle in bundles) { LoadAllContent(bundle); } } protected bool RegisterContent<TAsset>(string bundleName, out TAsset? asset, bool forceEnabled = false) where TAsset : AssetBundleLoader<TAsset> { if (TryLoadContentBundle<TAsset>(bundleName, out asset, forceEnabled)) { LoadAllContent(asset); return true; } return false; } } public abstract class ContentHandler<T> : ContentHandler where T : ContentHandler<T> { public static T Instance { get; private set; } public ContentHandler(DuskMod mod) : base(mod) { Instance = (T)this; } } public class AchievementConfig : EntityConfig { } public class AchievementSaveData { public bool Completed { get; set; } public AchievementSaveData(bool completed) { Completed = completed; base..ctor(); } } public class AchievementTriggers : MonoBehaviour { [SerializeReference] private DuskAchievementReference _reference; [SerializeField] private UnityEvent _onAchievementCompleted = new UnityEvent(); public void TryCompleteAchievement() { if (DuskModContent.Achievements.TryTriggerAchievement(_reference.Resolve().TypedKey)) { _onAchievementCompleted.Invoke(); } } public void TryIncrementAchievement(float amountToIncrement) { if (DuskModContent.Achievements.TryIncrementAchievement(_reference.Resolve().TypedKey, amountToIncrement)) { _onAchievementCompleted.Invoke(); } } public void TryDiscoverMoreProgressAchievement(string uniqueStringID) { if (DuskModContent.Achievements.TryDiscoverMoreProgressAchievement(_reference.Resolve().TypedKey, uniqueStringID)) { _onAchievementCompleted.Invoke(); } } public void ResetAllAchievementProgress() { } } public class AchievementModUIElement : MonoBehaviour { [SerializeField] private TextMeshProUGUI _modNameText; [SerializeField] private Image _modIcon; [SerializeField] private Button _achievementAccessButton; [SerializeField] private GameObject _achievementUIElementPrefab; internal GameObject _achievementsContainer; internal List<AchievementUIElement> achievementsContainerList = new List<AchievementUIElement>(); internal static List<AchievementModUIElement> achievementModUIElements = new List<AchievementModUIElement>(); private void Awake() { achievementModUIElements.Add(this); } private void OnDestroy() { achievementModUIElements.Remove(this); } internal void SetupModUI(DuskMod mod) { //IL_0045: Unknown result type (might be due to invalid IL or missing references) //IL_0146: Unknown result type (might be due to invalid IL or missing references) //IL_0150: Expected O, but got Unknown ((TMP_Text)_modNameText).text = mod.ModInformation.ModName; if ((Object)(object)mod.ModInformation.ModIcon != (Object)null) { _modIcon.sprite = mod.ModInformation.ModIcon; ((Graphic)_modIcon).color = Color.white; } List<DuskAchievementDefinition> list = DuskModContent.Achievements.Values.OrderByDescending((DuskAchievementDefinition a) => a.AchievementName).ToList(); foreach (DuskAchievementDefinition item in list) { DebugLogSource achievements = Debuggers.Achievements; if (achievements != null) { achievements.Log((object)("Adding achievement: " + item.AchievementName)); } GameObject val = Object.Instantiate<GameObject>(_achievementUIElementPrefab, _achievementsContainer.transform); val.SetActive(false); AchievementUIElement component = val.GetComponent<AchievementUIElement>(); component.SetupAchievementUI(item); ((Object)val).name = "DawnLib Achievement UI - " + item.AchievementName + " - " + mod.Plugin.GUID; achievementsContainerList.Add(component); } ((UnityEvent)_achievementAccessButton.onClick).AddListener(new UnityAction(OnButtonClick)); } public void OnButtonClick() { foreach (AchievementModUIElement modUIElement in Singleton<AchievementUICanvas>.Instance._modUIElements) { if ((Object)(object)modUIElement == (Object)(object)this) { continue; } foreach (AchievementUIElement achievementsContainer in modUIElement.achievementsContainerList) { ((Component)achievementsContainer).gameObject.SetActive(!((Component)achievementsContainer).gameObject.activeSelf); } } foreach (AchievementUIElement achievementsContainer2 in achievementsContainerList) { ((Component)achievementsContainer2).gameObject.SetActive(!((Component)achievementsContainer2).gameObject.activeSelf); } } } public class AchievementUICanvas : Singleton<AchievementUICanvas> { [SerializeField] internal GameObject _achievementContents; [SerializeField] private GameObject _modContents; [SerializeField] private Button _backButton; [SerializeField] private GameObject _background; [SerializeField] private GameObject _achievementModUIElementPrefab; internal Button _achievementsButton; private GameObject _mainButtons; internal MenuManager _menuManager; internal List<AchievementModUIElement> _modUIElements = new List<AchievementModUIElement>(); private void Start() { //IL_0023: Unknown result type (might be due to invalid IL or missing references) //IL_002d: Expected O, but got Unknown //IL_0044: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Expected O, but got Unknown _mainButtons = _menuManager.menuButtons; ((UnityEvent)_backButton.onClick).AddListener(new UnityAction(BackButtonOnClick)); ((UnityEvent)_backButton.onClick).AddListener(new UnityAction(_menuManager.PlayCancelSFX)); AddAllAchievementsToContents(); } private void AddAllAchievementsToContents() { foreach (DuskMod duskMod in DuskMod.AllMods) { if (DuskModContent.Achievements.Values.Where((DuskAchievementDefinition a) => a.Mod == duskMod).Count() > 0) { GameObject val = Object.Instantiate<GameObject>(_achievementModUIElementPrefab, _modContents.transform); AchievementModUIElement component = val.GetComponent<AchievementModUIElement>(); component._achievementsContainer = _achievementContents; _modUIElements.Add(component); component.SetupModUI(duskMod); } } } public void BackButtonOnClick() { _menuManager.EnableUIPanel(_mainButtons); ((Selectable)_achievementsButton).Select(); _background.SetActive(false); } public void AchievementsButtonOnClick() { _mainButtons.SetActive(false); _background.SetActive(true); ((Selectable)_backButton).Select(); } } public class AchievementUIElement : MonoBehaviour { [SerializeField] [FormerlySerializedAs("_achievementNameTMP")] internal TextMeshProUGUI achievementNameTMP; [SerializeField] [FormerlySerializedAs("_achievementDescriptionTMP")] internal TextMeshProUGUI achievementDescriptionTMP; [SerializeField] [FormerlySerializedAs("_achievementProgressGO")] internal GameObject achievementProgressGO; [SerializeField] [FormerlySerializedAs("_achievementHiddenButton")] internal Button achievementHiddenButton; [SerializeField] [FormerlySerializedAs("_achievementIcon")] internal Image achievementIcon; [SerializeField] [FormerlySerializedAs("_unfinishedAchievementColor")] internal Color unfinishedAchievementColor = new Color(0.5f, 0.5f, 0.5f); [SerializeField] [FormerlySerializedAs("_backgroundImage")] internal Image backgroundImage; [SerializeField] [FormerlySerializedAs("_progressBar")] internal Image progressBar; [SerializeField] internal AudioSource audioSource; [SerializeField] [FormerlySerializedAs("_eventTrigger")] internal EventTrigger? eventTrigger; internal DuskAchievementDefinition achievementDefinition; public void SetupAchievementUI(DuskAchievementDefinition definition) { achievementDefinition = definition; DuskAchievementHandler.UpdateUIElement(this, definition); } public void ResetAchievementProgress() { achievementDefinition.ResetProgress(); } } public class AchievementUIGetCanvas : Singleton<AchievementUIGetCanvas> { private static readonly int SlideOut = Animator.StringToHash("SlideOut"); [SerializeField] private GameObject _achievementGetUIElementPrefab; [SerializeField] private GameObject achievementContent; private Queue<DuskAchievementDefinition> achievementQueue = new Queue<DuskAchievementDefinition>(); private void Start() { DuskAchievementHandler.OnAchievementUnlocked += QueuePopup; } private void OnDestroy() { DuskAchievementHandler.OnAchievementUnlocked -= QueuePopup; } internal void QueuePopup(DuskAchievementDefinition achievement) { achievementQueue.Enqueue(achievement); if (achievementContent.transform.childCount == 0) { ((MonoBehaviour)this).StartCoroutine(ShowNextAchievement()); } } private IEnumerator ShowNextAchievement() { while (achievementQueue.Count > 0) { DuskAchievementDefinition duskAchievementDefinition = achievementQueue.Dequeue(); GameObject achievementElement = Object.Instantiate<GameObject>(_achievementGetUIElementPrefab, achievementContent.transform); AchievementUIElement component = achievementElement.GetComponent<AchievementUIElement>(); component.SetupAchievementUI(duskAchievementDefinition); if ((Object)(object)duskAchievementDefinition.FinishAchievementAudioClip != (Object)null) { component.audioSource.clip = duskAchievementDefinition.FinishAchievementAudioClip; } component.audioSource.Play(); yield return (object)new WaitForSeconds(duskAchievementDefinition.PopupTime); achievementElement.GetComponent<Animator>().SetTrigger(SlideOut); yield return (object)new WaitForSeconds(3f); Object.Destroy((Object)(object)achievementElement); } } } public abstract class DuskAchievementDefinition : DuskContentDefinition, INamespaced<DuskAchievementDefinition>, INamespaced { [SerializeField] private NamespacedKey<DuskAchievementDefinition> _typedKey; public const string REGISTRY_ID = "achievements"; [field: SerializeField] public Sprite? AchievementIcon { get; private set; } [field: Space(10f)] [field: SerializeField] public string AchievementName { get; private set; } [field: SerializeField] public string AchievementDescription { get; private set; } [field: SerializeField] public TMP_ColorGradient? FinishedAchievementNameColorGradientPreset { get; private set; } [field: SerializeField] public TMP_ColorGradient? FinishedAchievementDescColorGradientPreset { get; private set; } [field: SerializeField] public Sprite? FinishedAchievementBackgroundIcon { get; private set; } [field: SerializeField] public AudioClip? FinishAchievementAudioClip { get; private set; } [field: Space(10f)] [field: SerializeField] public string AchievementRequirement { get; private set; } [field: SerializeField] public bool IsHidden { get; private set; } [field: SerializeField] public bool CanBeUnhidden { get; private set; } [field: SerializeField] public float PopupTime { get; private set; } = 5f; public bool Completed { get; protected set; } public NamespacedKey<DuskAchievementDefinition> TypedKey => _typedKey; public override NamespacedKey Key { get { return (NamespacedKey)(object)TypedKey; } protected set { _typedKey = value.AsTyped<DuskAchievementDefinition>(); } } protected override string EntityNameReference => AchievementName; protected virtual AchievementSaveData GetSaveData() { return new AchievementSaveData(Completed); } protected virtual void LoadSaveData(AchievementSaveData saveData) { Completed = saveData.Completed; } public void LoadAchievementState(IDataContainer dataContainer) { LoadSaveData(dataContainer.GetOrSetDefault<AchievementSaveData>(Key, GetSaveData())); DebugLogSource achievements = Debuggers.Achievements; if (achievements != null) { achievements.Log((object)$"Loaded Achievement: {AchievementName} with value: {Completed}"); } } public void SaveAchievementState(IDataContainer dataContainer) { dataContainer.Set<AchievementSaveData>(Key, GetSaveData()); DebugLogSource achievements = Debuggers.Achievements; if (achievements != null) { achievements.Log((object)$"Saving Achievement: {AchievementName} with value: {Completed}"); } } protected bool TryCompleteAchievement() { if (Completed) { return false; } Completed = true; Singleton<AchievementUIGetCanvas>.Instance?.QueuePopup(this); return Completed; } internal bool TryCompleteFromServer() { return TryCompleteAchievement(); } public virtual void ResetProgress() { Completed = false; DuskAchievementHandler.SaveAll(); DuskAchievementHandler.LoadAll(); foreach (AchievementModUIElement achievementModUIElement in AchievementModUIElement.achievementModUIElements) { foreach (AchievementUIElement achievementsContainer in achievementModUIElement.achievementsContainerList) { DuskAchievementHandler.UpdateUIElement(achievementsContainer, achievementsContainer.achievementDefinition); } } } public override void Register(DuskMod mod) { base.Register(mod); DuskModContent.Achievements.Register(this); } public virtual bool IsActive() { return true; } } public static class DuskAchievementExtensions { public static bool TryTriggerAchievement(this Registry<DuskAchievementDefinition> registry, NamespacedKey<DuskAchievementDefinition> achievementKey) { DuskAchievementDefinition duskAchievementDefinition = default(DuskAchievementDefinition); if (registry.TryGetValue(achievementKey, ref duskAchievementDefinition) && duskAchievementDefinition is DuskInstantAchievement duskInstantAchievement) { return duskInstantAchievement.TriggerAchievement(); } return false; } public static bool TryIncrementAchievement(this Registry<DuskAchievementDefinition> registry, NamespacedKey<DuskAchievementDefinition> achievementKey, float amount) { DuskAchievementDefinition duskAchievementDefinition = default(DuskAchievementDefinition); if (registry.TryGetValue(achievementKey, ref duskAchievementDefinition) && duskAchievementDefinition is DuskStatAchievement duskStatAchievement) { return duskStatAchievement.IncrementProgress(amount); } return false; } public static bool TryDiscoverMoreProgressAchievement(this Registry<DuskAchievementDefinition> registry, NamespacedKey<DuskAchievementDefinition> achievementKey, IEnumerable<string> uniqueStringIDs) { DuskAchievementDefinition duskAchievementDefinition = default(DuskAchievementDefinition); if (registry.TryGetValue(achievementKey, ref duskAchievementDefinition) && duskAchievementDefinition is DuskDiscoveryAchievement duskDiscoveryAchievement) { return duskDiscoveryAchievement.TryDiscoverMoreProgress(uniqueStringIDs); } return false; } public static bool TryDiscoverMoreProgressAchievement(this Registry<DuskAchievementDefinition> registry, NamespacedKey<DuskAchievementDefinition> achievementKey, string uniqueStringID) { DuskAchievementDefinition duskAchievementDefinition = default(DuskAchievementDefinition); if (registry.TryGetValue(achievementKey, ref duskAchievementDefinition) && duskAchievementDefinition is DuskDiscoveryAchievement duskDiscoveryAchievement) { return duskDiscoveryAchievement.TryDiscoverMoreProgress(uniqueStringID); } return false; } public static void ResetAchievementProgress(this Registry<DuskAchievementDefinition> registry, NamespacedKey<DuskAchievementDefinition> achievementKey) { DuskAchievementDefinition duskAchievementDefinition = default(DuskAchievementDefinition); if (registry.TryGetValue(achievementKey, ref duskAchievementDefinition)) { duskAchievementDefinition.ResetProgress(); } } } internal static class DuskAchievementHandler { public static event Action<DuskAchievementDefinition> OnAchievementUnlocked; internal static void LoadAll() { using (DuskPlugin.PersistentData.LargeEdit()) { foreach (DuskAchievementDefinition value in DuskModContent.Achievements.Values) { value.LoadAchievementState((IDataContainer)(object)DuskPlugin.PersistentData); } } } internal static void SaveAll() { using (DuskPlugin.PersistentData.LargeEdit()) { foreach (DuskAchievementDefinition value in DuskModContent.Achievements.Values) { value.SaveAchievementState((IDataContainer)(object)DuskPlugin.PersistentData); } } } internal static void UpdateUIElement(AchievementUIElement achievementUIElement, DuskAchievementDefinition achievementDefinition) { //IL_00dc: Unknown result type (might be due to invalid IL or missing references) //IL_00ed: Unknown result type (might be due to invalid IL or missing references) //IL_010e: Unknown result type (might be due to invalid IL or missing references) //IL_0113: Unknown result type (might be due to invalid IL or missing references) //IL_015c: Unknown result type (might be due to invalid IL or missing references) ((TMP_Text)achievementUIElement.achievementNameTMP).text = achievementDefinition.AchievementName; ((TMP_Text)achievementUIElement.achievementDescriptionTMP).text = achievementDefinition.AchievementDescription; achievementUIElement.achievementIcon.sprite = achievementDefinition.AchievementIcon; ((Selectable)achievementUIElement.achievementHiddenButton).interactable = false; if ((Object)(object)achievementUIElement.eventTrigger != (Object)null) { ((Behaviour)achievementUIElement.eventTrigger).enabled = false; } if (achievementDefinition.CanBeUnhidden) { ((Selectable)achievementUIElement.achievementHiddenButton).interactable = true; if ((Object)(object)achievementUIElement.eventTrigger != (Object)null) { ((Behaviour)achievementUIElement.eventTrigger).enabled = true; } } if (!achievementDefinition.IsHidden || achievementDefinition.Completed) { if ((Object)(object)achievementUIElement.eventTrigger != (Object)null) { ((Behaviour)achievementUIElement.eventTrigger).enabled = true; } ((Selectable)achievementUIElement.achievementHiddenButton).interactable = true; ((UnityEvent)achievementUIElement.achievementHiddenButton.onClick).Invoke(); } if (!achievementDefinition.Completed) { ((Graphic)achievementUIElement.achievementNameTMP).color = achievementUIElement.unfinishedAchievementColor; ((Graphic)achievementUIElement.achievementDescriptionTMP).color = achievementUIElement.unfinishedAchievementColor; achievementUIElement.backgroundImage.sprite = null; ((Graphic)achievementUIElement.backgroundImage).color = Color32.op_Implicit(new Color32((byte)0, (byte)0, (byte)0, (byte)107)); ((TMP_Text)achievementUIElement.achievementNameTMP).colorGradientPreset = null; ((TMP_Text)achievementUIElement.achievementDescriptionTMP).colorGradientPreset = null; } else { if ((Object)(object)achievementDefinition.FinishedAchievementBackgroundIcon != (Object)null) { achievementUIElement.backgroundImage.sprite = achievementDefinition.FinishedAchievementBackgroundIcon; ((Graphic)achievementUIElement.backgroundImage).color = Color.white; } ((TMP_Text)achievementUIElement.achievementNameTMP).colorGradientPreset = achievementDefinition.FinishedAchievementNameColorGradientPreset; ((TMP_Text)achievementUIElement.achievementDescriptionTMP).colorGradientPreset = achievementDefinition.FinishedAchievementDescColorGradientPreset; } IProgress val = (IProgress)(object)((achievementDefinition is IProgress) ? achievementDefinition : null); if (val != null) { DebugLogSource achievements = Debuggers.Achievements; if (achievements != null) { achievements.Log((object)$"Setting up progress achievement: {achievementDefinition.AchievementName} with percentage: {IProgressExtensions.Percentage(val)}"); } achievementUIElement.progressBar.fillAmount = IProgressExtensions.Percentage(val); ((TMP_Text)((Component)achievementUIElement.progressBar).GetComponentInChildren<TextMeshProUGUI>()).text = $"{val.CurrentProgress}/{val.MaxProgress}"; } else { achievementUIElement.achievementProgressGO.SetActive(false); } } } [Serializable] public class DuskAchievementReference : DuskContentReference<DuskAchievementDefinition, DuskAchievementDefinition> { public DuskAchievementReference() { } public DuskAchievementReference(NamespacedKey<DuskAchievementDefinition> key) : base(key) { } public override bool TryResolve(out DuskAchievementDefinition info) { return DuskModContent.Achievements.TryGetValue(base.TypedKey, ref info); } public override DuskAchievementDefinition Resolve() { return DuskModContent.Achievements[base.TypedKey]; } } [CreateAssetMenu(fileName = "New Discovery Achievement Definition", menuName = "DawnLib/Definitions/Achievements/Discovery Definition")] public class DuskDiscoveryAchievement : DuskAchievementDefinition, IProgress { public class DiscoverySaveData : AchievementSaveData { public List<string> CurrentlyCollectedUniqueStringIDs { get; } public DiscoverySaveData(bool completed, List<string> currentlyCollectedUniqueStringIDs) { CurrentlyCollectedUniqueStringIDs = currentlyCollectedUniqueStringIDs; base..ctor(completed); } } [Tooltip("Unique string ID for each discovery to account for progress.")] [field: SerializeField] public List<string> UniqueStringIDs { get; private set; } public List<string> CurrentlyCollectedUniqueStringIDs { get; private set; } = new List<string>(); public float MaxProgress => UniqueStringIDs.Count; public float CurrentProgress => CurrentlyCollectedUniqueStringIDs.Count; protected override AchievementSaveData GetSaveData() { return new DiscoverySaveData(base.Completed, CurrentlyCollectedUniqueStringIDs); } protected override void LoadSaveData(AchievementSaveData saveData) { base.LoadSaveData(saveData); CurrentlyCollectedUniqueStringIDs = ((DiscoverySaveData)saveData).CurrentlyCollectedUniqueStringIDs; } public override void ResetProgress() { CurrentlyCollectedUniqueStringIDs.Clear(); base.ResetProgress(); } public bool TryDiscoverMoreProgress(string UniqueID) { if (CurrentlyCollectedUniqueStringIDs.Contains(UniqueID)) { return false; } if (!UniqueStringIDs.Contains(UniqueID)) { return false; } CurrentlyCollectedUniqueStringIDs.Add(UniqueID); if (CurrentProgress >= MaxProgress) { CurrentlyCollectedUniqueStringIDs = UniqueStringIDs; return TryCompleteAchievement(); } return false; } public bool TryDiscoverMoreProgress(IEnumerable<string> UniqueID) { foreach (string item in UniqueID) { if (TryDiscoverMoreProgress(item)) { return true; } } return false; } public void UndiscoverProgress(string UniqueID) { if (UniqueStringIDs.Contains(UniqueID)) { CurrentlyCollectedUniqueStringIDs.Remove(UniqueID); } } public void UndiscoverProgress(IEnumerable<string> UniqueID) { foreach (string item in UniqueID) { UndiscoverProgress(item); } } } [CreateAssetMenu(fileName = "New Instant Achievement Definition", menuName = "DawnLib/Definitions/Achievements/Instant Definition")] public class DuskInstantAchievement : DuskAchievementDefinition { [field: SerializeField] public bool SyncedCompletion { get; private set; } public bool TriggerAchievement() { if (SyncedCompletion) { NetworkSingleton<DuskNetworker>.Instance?.TriggerAchievementServerRpc(Key); } return TryCompleteAchievement(); } } [CreateAssetMenu(fileName = "New Parent Achievement Definition", menuName = "DawnLib/Definitions/Achievements/Parent Definition")] public class DuskParentAchievement : DuskAchievementDefinition, IProgress { [field: SerializeReference] [field: FormerlySerializedAs("ChildrenAchievementNames")] public List<DuskAchievementReference> ChildrenAchievementReferences { get; private set; } = new List<DuskAchievementReference>(); public float MaxProgress => ChildrenAchievementReferences.Count; public float CurrentProgress => CountCompleted(); public override void Register(DuskMod mod) { DuskMod mod2 = mod; base.Register(mod2); DuskAchievementHandler.OnAchievementUnlocked += delegate(DuskAchievementDefinition definition) { if (definition.Mod == mod2 && CountCompleted() >= ChildrenAchievementReferences.Count) { TryCompleteAchievement(); } }; } private int CountCompleted() { int num = 0; foreach (DuskAchievementDefinition value in DuskModContent.Achievements.Values) { if (!value.Completed) { continue; } foreach (DuskAchievementReference childrenAchievementReference in ChildrenAchievementReferences) { if (childrenAchievementReference.Resolve().AchievementName == value.AchievementName) { num++; break; } } } return num; } public override bool IsActive() { int num = 0; foreach (DuskAchievementDefinition value in DuskModContent.Achievements.Values) { if ((Object)(object)value == (Object)(object)this || !value.IsActive()) { continue; } foreach (DuskAchievementReference childrenAchievementReference in ChildrenAchievementReferences) { if (childrenAchievementReference.Resolve().AchievementName == value.AchievementName) { num++; break; } } } return num == ChildrenAchievementReferences.Count; } } [CreateAssetMenu(fileName = "New Stat Achievement Definition", menuName = "DawnLib/Definitions/Achievements/Stat Definition")] public class DuskStatAchievement : DuskAchievementDefinition, IProgress { public class StatSaveData : AchievementSaveData { public float CurrentProgress { get; } public StatSaveData(bool completed, float currentProgress) { CurrentProgress = currentProgress; base..ctor(completed); } } [field: SerializeField] public float MaxProgress { get; private set; } public float CurrentProgress { get; private set; } protected override AchievementSaveData GetSaveData() { return new StatSaveData(base.Completed, CurrentProgress); } protected override void LoadSaveData(AchievementSaveData saveData) { base.LoadSaveData(saveData); CurrentProgress = ((StatSaveData)saveData).CurrentProgress; } public override void ResetProgress() { CurrentProgress = 0f; base.ResetProgress(); } public bool IncrementProgress(float amount) { CurrentProgress = Mathf.Max(0f, CurrentProgress + amount); if (CurrentProgress >= MaxProgress) { CurrentProgress = MaxProgress; return TryCompleteAchievement(); } return false; } public void DecrementProgress(float amount) { CurrentProgress -= Mathf.Max(0f, amount); if (CurrentProgress <= 0f) { CurrentProgress = 0f; } } } public class DungeonConfig : EntityConfig { } [Serializable] public class DungeonData : EntityData<DuskAdditionalTilesReference> { } [CreateAssetMenu(fileName = "New Additional Tiles Definition", menuName = "DawnLib/Definitions/Additional Tiles Definition")] public class DuskAdditionalTilesDefinition : DuskContentDefinition<DungeonData, DawnTileSetInfo> { [Flags] public enum BranchCapSetting { Regular = 1, BranchCap = 2 } public const string REGISTRY_ID = "additional_tiles"; [SerializeField] public List<NamespacedKey<DawnArchetypeInfo>> archetypeKeys = new List<NamespacedKey<DawnArchetypeInfo>>(); private DawnTileSetInfo _info; [field: SerializeField] public TileSet TilesToAdd { get; private set; } [field: SerializeField] public BranchCapSetting BranchCap { get; private set; } protected override string EntityNameReference { get { TileSet tilesToAdd = TilesToAdd; return ((tilesToAdd != null) ? ((Object)tilesToAdd).name : null) ?? string.Empty; } } public override void Register(DuskMod mod, DungeonData data) { Register(mod); foreach (GameObjectChance weight in TilesToAdd.TileWeights.Weights) { DawnLib.FixDoorwaySockets(weight.Value); } _info = DawnLib.DefineTileSet(base.TypedKey, TilesToAdd, (Action<TilesetInfoBuilder>)delegate(TilesetInfoBuilder builder) { ApplyTagsTo((BaseInfoBuilder)(object)builder); builder.SetIsRegular(BranchCap.HasFlag(BranchCapSetting.Regular)); builder.SetIsBranchCap(BranchCap.HasFlag(BranchCapSetting.BranchCap)); }); LethalContent.Archetypes.BeforeFreeze += delegate { DawnArchetypeInfo val = default(DawnArchetypeInfo); foreach (NamespacedKey<DawnArchetypeInfo> archetypeKey in archetypeKeys) { if (LethalContent.Archetypes.TryGetValue(archetypeKey, ref val)) { val.AddTileSet(_info); } } }; } public override List<DungeonData> GetEntities(DuskMod mod) { return mod.Content.assetBundles.SelectMany((AssetBundleData it) => it.dungeons).ToList(); } } [Serializable] public class DuskAdditionalTilesReference : DuskContentReference<DuskAdditionalTilesDefinition, DawnTileSetInfo> { public DuskAdditionalTilesReference() { } public DuskAdditionalTilesReference(NamespacedKey<DawnTileSetInfo> key) : base(key) { } public override bool TryResolve(out DawnTileSetInfo info) { return LethalContent.TileSets.TryGetValue(base.TypedKey, ref info); } public override DawnTileSetInfo Resolve() { return LethalContent.TileSets[base.TypedKey]; } } public abstract class DuskContentDefinition : ScriptableObject { [FormerlySerializedAs("ConfigEntries")] [SerializeField] private List<DuskDynamicConfig> _configEntries = new List<DuskDynamicConfig>(); [SerializeField] internal List<NamespacedKey> _tags = new List<NamespacedKey>(); internal readonly Dictionary<string, ConfigEntryBase> generalConfigs = new Dictionary<string, ConfigEntryBase>(); internal AssetBundleData AssetBundleData; public abstract NamespacedKey Key { get; protected set; } public DuskMod Mod { get; private set; } protected abstract string EntityNameReference { get; } public virtual void Register(DuskMod mod) { if (AssetBundleData == null) { ManualLogSource? logger = mod.Logger; if (logger != null) { logger.LogError((object)("BUG! Tried to register " + ((Object)this).name + " without setting AssetBundleData?")); } return; } Mod = mod; using ConfigContext context = mod.ConfigManager.CreateConfigSectionForBundleData(AssetBundleData); foreach (DuskDynamicConfig configEntry in _configEntries) { generalConfigs[ConfigManager.CleanStringForConfig(configEntry.settingName)] = mod.ConfigManager.CreateDynamicConfig(configEntry, context); } } public string GetDefaultKey() { return NamespacedKey.NormalizeStringForNamespacedKey(EntityNameReference, false); } protected void ApplyTagsTo(BaseInfoBuilder builder) { builder.SoloAddTags((IEnumerable<NamespacedKey>)_tags); } } public abstract class DuskContentDefinition<T, TInfo> : DuskContentDefinition where T : EntityData where TInfo : INamespaced<TInfo> { public NamespacedKey<TInfo> TypedKey => Key.AsTyped<TInfo>(); public override NamespacedKey Key { get; protected set; } public override void Register(DuskMod mod) { try { Register(mod, GetEntities(mod).First(delegate(T it) { if (it.Key != null) { DebugLogSource dusk = Debuggers.Dusk; if (dusk != null) { dusk.Log((object)$"{this} | Comparing {Key} with {it.Key}."); } return object.Equals(it.Key, Key); } return false; })); } catch (InvalidOperationException ex) { ManualLogSource? logger = mod.Logger; if (logger != null) { logger.LogError((object)$"{this} with {Key} failed to find a matching entity. {ex.Message}"); } } base.Register(mod); } public abstract void Register(DuskMod mod, T data); public abstract List<T> GetEntities(DuskMod mod); } [Serializable] public abstract class DuskContentReference : INetworkSerializable { [SerializeField] internal string assetGUID; public abstract Type Type { get; } public abstract Type DefinitionType { get; } public abstract NamespacedKey Key { get; protected set; } public abstract void NetworkSerialize<T>(BufferSerializer<T> serializer) where T : IReaderWriter; } [Serializable] public abstract class DuskContentReference<TDef, TInfo> : DuskContentReference where TDef : DuskContentDefinition where TInfo : INamespaced<TInfo> { public NamespacedKey<TInfo> TypedKey => Key.AsTyped<TInfo>(); public override NamespacedKey Key { get; protected set; } public override Type Type => typeof(TInfo); public override Type DefinitionType => typeof(TDef); public DuskContentReference() { Key = (NamespacedKey)(object)NamespacedKey<?>.From("", ""); } protected DuskContentReference(NamespacedKey<TInfo> key) { Key = (NamespacedKey)(object)key; } public unsafe override void NetworkSerialize<T>(BufferSerializer<T> serializer) { NamespacedKey key = Key; ((BufferSerializer<NamespacedKey>*)(&serializer))->SerializeNetworkSerializable<NamespacedKey>(ref key); Key = key; } public abstract bool TryResolve(out TInfo info); public abstract TInfo Resolve(); } [Flags] public enum SpawnTable { Inside = 1, Outside = 2, Daytime = 4 } [CreateAssetMenu(fileName = "New Enemy Definition", menuName = "DawnLib/Definitions/Enemy Definition")] public class DuskEnemyDefinition : DuskContentDefinition<EnemyData, DawnEnemyInfo> { public const string REGISTRY_ID = "enemies"; [field: FormerlySerializedAs("enemyType")] [field: SerializeField] public EnemyType EnemyType { get; private set; } [field: SerializeField] public SpawnTable SpawnTable { get; private set; } [field: FormerlySerializedAs("terminalNode")] [field: SerializeField] public TerminalNode? TerminalNode { get; private set; } [field: FormerlySerializedAs("terminalKeyword")] [field: SerializeField] public TerminalKeyword? TerminalKeyword { get; private set; } public SpawnWeightsPreset SpawnWeights { get; private set; } = new SpawnWeightsPreset(); public EnemyConfig Config { get; private set; } protected override string EntityNameReference => EnemyType?.enemyName ?? string.Empty; public override void Register(DuskMod mod, EnemyData data) { using ConfigContext section = mod.ConfigManager.CreateConfigSectionForBundleData(AssetBundleData); Config = CreateEnemyConfig(section, data, SpawnWeights, EnemyType.enemyName); EnemyType enemyType = EnemyType; enemyType.MaxCount = Config.MaxSpawnCount.Value; enemyType.PowerLevel = Config.PowerLevel.Value; SpawnWeights.SetupSpawnWeightsPreset(Config.MoonSpawnWeights?.Value ?? data.moonSpawnWeights, Config.InteriorSpawnWeights?.Value ?? data.interiorSpawnWeights, Config.WeatherSpawnWeights?.Value ?? data.weatherSpawnWeights); DawnLib.DefineEnemy(base.TypedKey, EnemyType, (Action<EnemyInfoBuilder>)delegate(EnemyInfoBuilder builder) { if (SpawnTable.HasFlag(SpawnTable.Daytime)) { builder.DefineDaytime((Action<EnemyLocationBuilder>)delegate(EnemyLocationBuilder daytimeBuilder) { daytimeBuilder.SetWeights((Action<WeightTableBuilder<DawnMoonInfo>>)delegate(WeightTableBuilder<DawnMoonInfo> weightBuilder) { weightBuilder.SetGlobalWeight((IWeighted)(object)SpawnWeights); }); }); } if (SpawnTable.HasFlag(SpawnTable.Outside)) { builder.DefineOutside((Action<EnemyLocationBuilder>)delegate(EnemyLocationBuilder outsideBuilder) { outsideBuilder.SetWeights((Action<WeightTableBuilder<DawnMoonInfo>>)delegate(WeightTableBuilder<DawnMoonInfo> weightBuilder) { weightBuilder.SetGlobalWeight((IWeighted)(object)SpawnWeights); }); }); } if (SpawnTable.HasFlag(SpawnTable.Inside)) { builder.DefineInside((Action<EnemyLocationBuilder>)delegate(EnemyLocationBuilder insideBuilder) { insideBuilder.SetWeights((Action<WeightTableBuilder<DawnMoonInfo>>)delegate(WeightTableBuilder<DawnMoonInfo> weightBuilder) { weightBuilder.SetGlobalWeight((IWeighted)(object)SpawnWeights); }); }); } if ((Object)(object)TerminalKeyword != (Object)null) { builder.OverrideNameKeyword(TerminalKeyword); } if ((Object)(object)TerminalNode != (Object)null) { builder.SetBestiaryNode(TerminalNode); } ApplyTagsTo((BaseInfoBuilder)(object)builder); }); } public static EnemyConfig CreateEnemyConfig(ConfigContext section, EnemyData data, SpawnWeightsPreset spawnWeightsPreset, string enemyName) { return new EnemyConfig { MoonSpawnWeights = (data.generateSpawnWeightsConfig ? section.Bind(enemyName + " | Preset Moon Weights", "Preset moon weights for " + enemyName + ".", spawnWeightsPreset.MoonSpawnWeightsTransformer.ToConfigString()) : null), InteriorSpawnWeights = (data.generateSpawnWeightsConfig ? section.Bind(enemyName + " | Preset Interior Weights", "Preset interior weights for " + enemyName + ".", spawnWeightsPreset.InteriorSpawnWeightsTransformer.ToConfigString()) : null), WeatherSpawnWeights = (data.generateSpawnWeightsConfig ? section.Bind(enemyName + " | Preset Weather Weights", "Preset weather weights for " + enemyName + ".", spawnWeightsPreset.WeatherSpawnWeightsTransformer.ToConfigString()) : null), PowerLevel = section.Bind(enemyName + " | Power Level", "Power level for " + enemyName + ".", data.powerLevel), MaxSpawnCount = section.Bind(enemyName + " | Max Spawn Count", "Max spawn count for " + enemyName + ".", data.maxSpawnCount) }; } public override List<EnemyData> GetEntities(DuskMod mod) { return mod.Content.assetBundles.SelectMany((AssetBundleData it) => it.enemies).ToList(); } } [Serializable] public class DuskEnemyReference : DuskContentReference<DuskEnemyDefinition, DawnEnemyInfo> { public DuskEnemyReference() { } public DuskEnemyReference(NamespacedKey<DawnEnemyInfo> key) : base(key) { } public override bool TryResolve(out DawnEnemyInfo info) { return ((Registry<DawnEnemyInfo>)(object)LethalContent.Enemies).TryGetValue(base.TypedKey, ref info); } public override DawnEnemyInfo Resolve() { return ((Registry<DawnEnemyInfo>)(object)LethalContent.Enemies)[base.TypedKey]; } } public class EnemyConfig : EntityConfig { public ConfigEntry<int> MaxSpawnCount; public ConfigEntry<float> PowerLevel; public ConfigEntry<string>? MoonSpawnWeights; public ConfigEntry<string>? InteriorSpawnWeights; public ConfigEntry<string>? WeatherSpawnWeights; } [Serializable] public class EnemyData : EntityData<DuskEnemyReference> { public string moonSpawnWeights; public string interiorSpawnWeights; public string weatherSpawnWeights; public bool generateSpawnWeightsConfig; public float powerLevel; public int maxSpawnCount; } public class EntityConfig { } [Serializable] public abstract class EntityData { public abstract NamespacedKey Key { get; } } [Serializable] public abstract class EntityData<T> : EntityData where T : DuskContentReference, new() { [FormerlySerializedAs("reference")] [SerializeReference] [AssertFieldNotNull] private T _reference = new T(); public override NamespacedKey Key { get { if (_reference != null) { return _reference.Key; } return null; } } public EntityData() { if (_reference == null) { _reference = new T(); } } } public abstract class DuskEntityReplacementDefinition : DuskContentDefinition, INamespaced<DuskEntityReplacementDefinition>, INamespaced { public const string REGISTRY_ID = "entityreplacements"; [SerializeField] private NamespacedKey<DuskEntityReplacementDefinition> _typedKey; [field: SerializeField] public NamespacedKey EntityToReplaceKey { get; private set; } public NamespacedKey<DuskEntityReplacementDefinition> TypedKey => _typedKey; public override NamespacedKey Key { get { return (NamespacedKey)(object)TypedKey; } protected set { _typedKey = value.AsTyped<DuskEntityReplacementDefinition>(); } } public List<StringWithAudioClip> AudioClipToReplaceWithFieldNames { get; private set; } = new List<StringWithAudioClip>(); public List<StringWithAudioClipArray> AudioClipToReplaceWithFieldNamesArray { get; private set; } = new List<StringWithAudioClipArray>(); public List<StringWithAudioClipList> AudioClipToReplaceWithFieldNamesList { get; private set; } = new List<StringWithAudioClipList>(); protected override string EntityNameReference => ((NamespacedKey)TypedKey).Key; public override void Register(DuskMod mod) { base.Register(mod); DuskModContent.EntityReplacements.Register(this); } } public abstract class DuskEntityReplacementDefinition<TAI> : DuskEntityReplacementDefinition where TAI : class { public abstract void Apply(TAI ai); } [CreateAssetMenu(fileName = "New Enemy Replacement Definition", menuName = "DawnLib/Definitions/Entity Replacements/Enemy Replacement Definition")] public abstract class DuskEnemyReplacementDefinition : DuskEntityReplacementDefinition<EnemyAI> { [field: SerializeField] public AudioClip? HitBodySFX { get; private set; } [field: SerializeField] public AudioClip HitEnemyVoiceSFX { get; private set; } [field: SerializeField] public AudioClip DeathSFX { get; private set; } [field: SerializeField] public AudioClip StunSFX { get; private set; } [field: SerializeField] public AudioClip[] AnimVoiceClips { get; private set; } = Array.Empty<AudioClip>(); [field: SerializeField] public AudioClip[] AudioClips { get; private set; } = Array.Empty<AudioClip>(); public override void Apply(EnemyAI enemyAI) { } } public abstract class DuskEnemyReplacementDefinition<T> : DuskEnemyReplacementDefinition where T : EnemyAI { protected abstract void Apply(T enemyAI); public override void Apply(EnemyAI enemyAI) { base.Apply(enemyAI); Apply((T)(object)enemyAI); } } public static class EnemyTypeExtensions { public static DuskEnemyReplacementDefinition? GetEnemyReplacement(this EnemyType enemyType) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) return (DuskEnemyReplacementDefinition)((ICurrentEntityReplacement)enemyType).CurrentEntityReplacement; } internal static bool HasEnemyReplacement(this EnemyType enemyType) { return (Object)(object)enemyType.GetEnemyReplacement() != (Object)null; } internal static void SetEnemyReplacement(this EnemyType enemyType, DuskEnemyReplacementDefinition enemyReplacementDefinition) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) ((ICurrentEntityReplacement)enemyType).CurrentEntityReplacement = enemyReplacementDefinition; } } [Serializable] public class StringWithAudioClip { [field: SerializeField] public string FieldName { get; private set; } [field: SerializeField] public AudioClip ReplacementAudioClip { get; private set; } } [Serializable] public class StringWithAudioClipArray { [field: SerializeField] public string FieldName { get; private set; } [field: SerializeField] public AudioClip[] ReplacementAudioClipArray { get; private set; } } [Serializable] public class StringWithAudioClipList { [field: SerializeField] public string FieldName { get; private set; } [field: SerializeField] public List<AudioClip> ReplacementAudioClipList { get; private set; } } [CreateAssetMenu(fileName = "New Item Definition", menuName = "DawnLib/Definitions/Item Definition")] public class DuskItemDefinition : DuskContentDefinition<ItemData, DawnItemInfo> { public const string REGISTRY_ID = "items"; [field: FormerlySerializedAs("item")] [field: SerializeField] public Item Item { get; private set; } [field: SerializeField] public ShopItemPreset ShopItemPreset { get; private set; } = new ShopItemPreset(); [field: SerializeField] public DuskTerminalPredicate TerminalPredicate { get; private set; } [field: SerializeField] public DuskPricingStrategy PricingStrategy { get; private set; } public SpawnWeightsPreset SpawnWeights { get; private set; } = new SpawnWeightsPreset(); public ItemConfig Config { get; private set; } protected override string EntityNameReference => Item?.itemName ?? string.Empty; public override void Register(DuskMod mod, ItemData data) { //IL_0038: Unknown result type (might be due to invalid IL or missing references) //IL_003e: Expected O, but got Unknown ItemData data2 = data; BoundedRange val = new BoundedRange((float)Item.minValue * 0.4f, (float)Item.maxValue * 0.4f); using ConfigContext context = mod.ConfigManager.CreateConfigSectionForBundleData(AssetBundleData); Config = CreateItemConfig(context, this, data2, val, SpawnWeights, Item.itemName); if (Config.Worth != null) { BoundedRange value = Config.Worth.Value; if (value.Min == -1f || value.Max == -1f) { ManualLogSource? logger = mod.Logger; if (logger != null) { logger.LogInfo((object)("Migrating scrap value of " + Item.itemName + " from -1,-1.")); } Config.Worth.Value = val; } else { val = value; } } Item.minValue = (int)(val.Min / 0.4f); Item.maxValue = (int)(val.Max / 0.4f); SpawnWeights.SetupSpawnWeightsPreset(Config.MoonSpawnWeights?.Value ?? data2.moonSpawnWeights, Config.InteriorSpawnWeights?.Value ?? data2.interiorSpawnWeights, Config.WeatherSpawnWeights?.Value ?? data2.weatherSpawnWeights); DawnLib.DefineItem(base.TypedKey, Item, (Action<ItemInfoBuilder>)delegate(ItemInfoBuilder builder) { if (Config.IsScrapItem?.Value ?? data2.isScrap) { builder.DefineScrap((Action<ScrapBuilder>)delegate(ScrapBuilder scrapBuilder) { scrapBuilder.SetWeights((Action<WeightTableBuilder<DawnMoonInfo>>)delegate(WeightTableBuilder<DawnMoonInfo> weightBuilder) { weightBuilder.SetGlobalWeight((IWeighted)(object)SpawnWeights); }); }); } if (Config.IsShopItem?.Value ?? data2.isShopItem) { builder.DefineShop((Action<ShopBuilder>)delegate(ShopBuilder shopItemBuilder) { shopItemBuilder.OverrideRequestNode(ShopItemPreset.OrderRequestNode); shopItemBuilder.OverrideReceiptNode(ShopItemPreset.OrderReceiptNode); shopItemBuilder.OverrideInfoNode(ShopItemPreset.ItemInfoNode); ConfigEntry<bool>? disableUnlockRequirements = Config.DisableUnlockRequirements; if ((disableUnlockRequirements == null || !disableUnlockRequirements.Value) && Object.op_Implicit((Object)(object)TerminalPredicate)) { TerminalPredicate.Register((NamespacedKey)(object)base.TypedKey); shopItemBuilder.SetPurchasePredicate((ITerminalPurchasePredicate)(object)TerminalPredicate); } bool flag = Config.DisablePricingStrategy?.Value ?? false; if (Object.op_Implicit((Object)(object)PricingStrategy) && !flag) { PricingStrategy.Register(Key); shopItemBuilder.OverrideCost((IProvider<int>)PricingStrategy); } else { shopItemBuilder.OverrideCost(Config.Cost?.Value ?? data2.cost); } }); } ApplyTagsTo((BaseInfoBuilder)(object)builder); }); } public static ItemConfig CreateItemConfig(ConfigContext context, DuskItemDefinition definition, ItemData data, BoundedRange defaultScrapValue, SpawnWeightsPreset spawnWeightsPreset, string itemName) { ConfigEntry<bool> val = (data.generateScrapConfig ? context.Bind(itemName + " | Is Scrap", "Whether " + itemName + " is a scrap item.", data.isScrap) : null); ConfigEntry<bool> val2 = (data.generateShopItemConfig ? context.Bind(itemName + " | Is Shop Item", "Whether " + itemName + " is a shop item.", data.isShopItem) : null); return new ItemConfig { MoonSpawnWeights = (data.generateSpawnWeightsConfig ? context.Bind(itemName + " | Preset Moon Weights", "Preset moon weights for " + itemName + ".", spawnWeightsPreset.MoonSpawnWeightsTransformer.ToConfigString()) : null), InteriorSpawnWeights = (data.generateSpawnWeightsConfig ? context.Bind(itemName + " | Preset Interior Weights", "Preset interior weights for " + itemName + ".", spawnWeightsPreset.InteriorSpawnWeightsTransformer.ToConfigString()) : null), WeatherSpawnWeights = (data.generateSpawnWeightsConfig ? context.Bind(itemName + " | Preset Weather Weights", "Preset weather weights for " + itemName + ".", spawnWeightsPreset.WeatherSpawnWeightsTransformer.ToConfigString()) : null), IsScrapItem = val, DisableUnlockRequirements = (data.generateDisableUnlockConfig ? context.Bind(itemName + " | Disable Unlock Requirements", "Whether " + itemName + " should have it's unlock requirements disabled.", defaultValue: false) : null), DisablePricingStrategy = (data.generateDisablePricingStrategyConfig ? context.Bind(itemName + " | Disable Pricing Strategy", "Whether " + itemName + " should have it's pricing strategy disabled.", defaultValue: false) : null), Worth = ((val?.Value ?? data.isScrap) ? context.Bind<BoundedRange>(itemName + " | Value", "How much " + itemName + " is worth when spawning.", defaultScrapValue) : null), IsShopItem = val2, Cost = ((val2?.Value ?? data.isShopItem) ? context.Bind(itemName + " | Cost", "Cost for " + itemName + " in the shop.", data.cost) : null) }; } public override List<ItemData> GetEntities(DuskMod mod) { return mod.Content.assetBundles.SelectMany((AssetBundleData it) => it.items).ToList(); } } [Serializable] public class DuskItemReference : DuskContentReference<DuskItemDefinition, DawnItemInfo> { public DuskItemReference() { } public DuskItemReference(NamespacedKey<DawnItemInfo> key) : base(key) { } public override bool TryResolve(out DawnItemInfo info) { return ((Registry<DawnItemInfo>)(object)LethalContent.Items).TryGetValue(base.TypedKey, ref info); } public override DawnItemInfo Resolve() { return ((Registry<DawnItemInfo>)(object)LethalContent.Items)[base.TypedKey]; } } public class ItemConfig : EntityConfig { public ConfigEntry<int>? Cost; public ConfigEntry<bool>? IsScrapItem; public ConfigEntry<bool>? IsShopItem; public ConfigEntry<bool>? DisableUnlockRequirements; public ConfigEntry<bool>? DisablePricingStrategy; public ConfigEntry<string>? MoonSpawnWeights; public ConfigEntry<string>? InteriorSpawnWeights; public ConfigEntry<string>? WeatherSpawnWeights; public ConfigEntry<BoundedRange>? Worth; } [Serializable] public class ItemData : EntityData<DuskItemReference> { public string moonSpawnWeights; public string interiorSpawnWeights; public string weatherSpawnWeights; public bool generateSpawnWeightsConfig; public bool isScrap; public bool generateScrapConfig; public bool isShopItem; public bool generateShopItemConfig; [FormerlySerializedAs("generateProgressiveConfig")] public bool generateDisableUnlockConfig; public bool generateDisablePricingStrategyConfig; public int cost; } public class ItemUpgradeScrap : GrabbableObject { [field: SerializeReference] public DuskItemReference ItemReference { get; private set; } protected override void __initializeVariables() { ((GrabbableObject)this).__initializeVariables(); } [MethodImpl(MethodImplOptions.NoInlining)] protected internal override string __getTypeName() { return "ItemUpgradeScrap"; } } [Serializable] public class ShopItemPreset { [field: SerializeField] public TerminalNode OrderRequestNode { get; private set; } [field: SerializeField] public TerminalNode OrderReceiptNode { get; private set; } [field: SerializeField] public TerminalNode ItemInfoNode { get; private set; } } [CreateAssetMenu(fileName = "New Map Definition", menuName = "DawnLib/Definitions/Map Object Definition")] public class DuskMapObjectDefinition : DuskContentDefinition<MapObjectData, DawnMapObjectInfo> { public const string REGISTRY_ID = "map_objects"; [field: FormerlySerializedAs("gameObject")] [field: SerializeField] public GameObject GameObject { get; private set; } [field: FormerlySerializedAs("objectName")] [field: FormerlySerializedAs("ObjectName")] [field: SerializeField] public string MapObjectName { get; private set; } [field: SerializeField] public InsideMapObjectSettings InsideMapObjectSettings { get; private set; } [field: SerializeField] public OutsideMapObjectSettings OutsideMapObjectSettings { get; private set; } public MapObjectConfig Config { get; private set; } protected override string EntityNameReference => MapObjectName; public override void Register(DuskMod mod, MapObjectData data) { MapObjectData data2 = data; using ConfigContext section = mod.ConfigManager.CreateConfigSectionForBundleData(AssetBundleData); Config = CreateMapObjectConfig(section, data2, MapObjectName); DawnLib.DefineMapObject(base.TypedKey, GameObject, (Action<MapObjectInfoBuilder>)delegate(MapObjectInfoBuilder builder) { if (Config.InsideHazard?.Value ?? data2.isInsideHazard) { MapObjectSpawnMechanics InsideSpawnMechanics = new MapObjectSpawnMechanics(Config.InsideCurveSpawnWeights?.Value ?? data2.defaultInsideCurveSpawnWeights); builder.DefineInside((Action<InsideBuilder>)delegate(InsideBuilder insideBuilder) { insideBuilder.OverrideSpawnFacingWall(InsideMapObjectSettings.spawnFacingWall); insideBuilder.OverrideSpawnFacingAwayFromWall(InsideMapObjectSettings.spawnFacingAwayFromWall); insideBuilder.OverrideRequireDistanceBetweenSpawns(InsideMapObjectSettings.requireDistanceBetweenSpawns); insideBuilder.OverrideDisallowSpawningNearEntrances(InsideMapObjectSettings.disallowSpawningNearEntrances); insideBuilder.OverrideSpawnWithBackToWall(InsideMapObjectSettings.spawnWithBackFlushAgainstWall); insideBuilder.OverrideSpawnWithBackFlushAgainstWall(InsideMapObjectSettings.spawnWithBackFlushAgainstWall); insideBuilder.SetWeights((Action<CurveTableBuilder<DawnMoonInfo>>)delegate(CurveTableBuilder<DawnMoonInfo> weightBuilder) { weightBuilder.SetGlobalCurve((IContextualProvider<AnimationCurve, DawnMoonInfo>)(object)InsideSpawnMechanics); }); }); } builder.DefineOutside((Action<OutsideBuilder>)delegate(OutsideBuilder outsideBuilder) { MapObjectSpawnMechanics OutsideSpawnMechanics = new MapObjectSpawnMechanics(Config.OutsideCurveSpawnWeights?.Value ?? data2.defaultOutsideCurveSpawnWeights); outsideBuilder.OverrideAlignWithTerrain(OutsideMapObjectSettings.AlignWithTerrain); outsideBuilder.SetWeights((Action<CurveTableBuilder<DawnMoonInfo>>)delegate(CurveTableBuilder<DawnMoonInfo> weightBuilder) { weightBuilder.SetGlobalCurve((IContextualProvider<AnimationCurve, DawnMoonInfo>)(object)OutsideSpawnMechanics); }); }); ApplyTagsTo((BaseInfoBuilder)(object)builder); }); } public static MapObjectConfig CreateMapObjectConfig(ConfigContext section, MapObjectData data, string objectName) { ConfigEntry<bool> val = null; ConfigEntry<bool> val2 = null; ConfigEntry<string> insideCurveSpawnWeights = null; ConfigEntry<string> outsideCurveSpawnWeights = null; if (data.createInsideHazardConfig) { val = section.Bind(objectName + " | Is Inside Hazard", "Whether " + objectName + " is an inside hazard", data.isInsideHazard); } if (data.createOutsideHazardConfig) { val2 = section.Bind(objectName + " | Is Outside Hazard", "Whether " + objectName + " is an outside hazard", data.isOutsideHazard); } if ((val?.Value ?? data.isInsideHazard) && data.createInsideCurveSpawnWeightsConfig) { insideCurveSpawnWeights = section.Bind(objectName + " | Inside Spawn Weights", "Curve weights for " + objectName + " when spawning inside.", data.defaultInsideCurveSpawnWeights); } if ((val2?.Value ?? data.isOutsideHazard) && data.createOutsideCurveSpawnWeightsConfig) { outsideCurveSpawnWeights = section.Bind(objectName + " | Outside Spawn Weights", "Curve weights for " + objectName + " when spawning outside.", data.defaultOutsideCurveSpawnWeights); } return new MapObjectConfig { InsideHazard = val, OutsideHazard = val2, InsideCurveSpawnWeights = insideCurveSpawnWeights, OutsideCurveSpawnWeights = outsideCurveSpawnWeights }; } public override List<MapObjectData> GetEntities(DuskMod mod) { return mod.Content.assetBundles.SelectMany((AssetBundleData it) => it.mapObjects).ToList(); } } [Serializable] public class DuskMapObjectReference : DuskContentReference<DuskMapObjectDefinition, DawnMapObjectInfo> { public DuskMapObjectReference() { } public DuskMapObjectReference(NamespacedKey<DawnMapObjectInfo> key) : base(key) { } public override bool TryResolve(out DawnMapObjectInfo info) { return ((Registry<DawnMapObjectInfo>)(object)LethalContent.MapObjects).TryGetValue(base.TypedKey, ref info); } public override DawnMapObjectInfo Resolve() { return ((Registry<DawnMapObjectInfo>)(object)LethalContent.MapObjects)[base.TypedKey]; } } public class MapObjectConfig : EntityConfig { public ConfigEntry<string>? InsideCurveSpawnWeights; public ConfigEntry<bool>? InsideHazard; public ConfigEntry<string>? OutsideCurveSpawnWeights; public ConfigEntry<bool>? OutsideHazard; } [Serializable] public class MapObjectData : EntityData<DuskMapObjectReference> { public bool isInsideHazard; public bool createInsideHazardConfig; public string defaultInsideCurveSpawnWeights; public bool createInsideCurveSpawnWeightsConfig; public bool isOutsideHazard; public bool createOutsideHazardConfig; public string defaultOutsideCurveSpawnWeights; public bool createOutsideCurveSpawnWeightsConfig; } public class MapObjectSpawnMechanics : IContextualProvider<AnimationCurve?, DawnMoonInfo> { public Dictionary<string, AnimationCurve> CurvesByMoonOrTagName { get; } = new Dictionary<string, AnimationCurve>(); public AnimationCurve? AllCurve { get; } public AnimationCurve? VanillaCurve { get; } public AnimationCurve? ModdedCurve { get; } public MapObjectSpawnMechanics(string configString) { Dictionary<string, string> dictionary = ConfigManager.ParseLevelNameWithCurves(configString); string key; string value; foreach (KeyValuePair<string, string> item in dictionary) { item.Deconstruct(out key, out value); string text = key; string keyValuePairs = value; AnimationCurve val = ConfigManager.ParseCurve(keyValuePairs); switch (text) { case "vanilla": VanillaCurve = val; break; case "modded": ModdedCurve = val; break; case "all": AllCurve = val; break; } } foreach (KeyValuePair<string, string> item2 in dictionary) { item2.Deconstruct(out value, out key); string key2 = value; string keyValuePairs2 = key; CurvesByMoonOrTagName[key2] = ConfigManager.ParseCurve(keyValuePairs2); } } public AnimationCurve CurveFunction(DawnMoonInfo moonInfo) { //IL_0133: Unknown result type (might be due to invalid IL or missing references) //IL_0139: Expected O, but got Unknown //IL_010f: Unknown result type (might be due to invalid IL or missing references) if (moonInfo == null || (Object)(object)moonInfo.Level == (Object)null) { return AnimationCurve.Constant(0f, 1f, 0f); } if (CurvesByMoonOrTagName.TryGetValue(moonInfo.GetConfigName(), out AnimationCurve value)) { return value; } List<AnimationCurve> list = new List<AnimationCurve>(); NamespacedKey val2 = default(NamespacedKey); foreach (var (text2, item) in CurvesByMoonOrTagName) { if (NamespacedKey.TryParse(text2, ref val2) && ((DawnBaseInfo<DawnMoonInfo>)(object)moonInfo).HasTag(val2)) { list.Add(item); } } if (list.Count > 0) { List<Keyframe> list2 = new List<Keyframe>(); for (float num = 0f; num < 1f; num += 0.01f) { List<float> list3 = new List<float>(); foreach (AnimationCurve item2 in list) { list3.Add(item2.Evaluate(num)); } float num2 = list3.Average(); list2.Add(new Keyframe(num, num2)); } return new AnimationCurve(list2.ToArray()); } if (((DawnBaseInfo<DawnMoonInfo>)(object)moonInfo).HasTag(Tags.Vanilla) && VanillaCurve != null) { return VanillaCurve; } if (ModdedCurve != null) { return ModdedCurve; } if (AllCurve != null) { return AllCurve; } DebugLogSource mapObjects = Debuggers.MapObjects; if (mapObjects != null) { mapObjects.Log((object)$"Failed to find curve for level: {moonInfo.Level}"); } return AnimationCurve.Constant(0f, 1f, 0f); } public AnimationCurve? Provide(DawnMoonInfo info) { return CurveFunction(info); } } [CreateAssetMenu(fileName = "New Unlockable Definition", menuName = "DawnLib/Definitions/Unlockable Definition")] public class DuskUnlockableDefinition : DuskContentDefinition<UnlockableData, DawnUnlockableItemInfo> { public const string REGISTRY_ID = "unlockables"; [field: SerializeField] public UnlockableItem UnlockableItem { get; private set; } = new UnlockableItem(); [field: SerializeField] public DuskTerminalPredicate TerminalPredicate { get; private set; } [field: SerializeField] public DuskPricingStrategy PricingStrategy { get; private set; } public UnlockableConfig Config { get; private set; } protected override string EntityNameReference => UnlockableItem.unlockableName; public override void Register(DuskMod mod, UnlockableData data) { UnlockableData data2 = data; using ConfigContext context = mod.ConfigManager.CreateConfigSectionForBundleData(AssetBundleData); Config = CreateUnlockableConfig(context, this, data2, UnlockableItem.unlockableName); DawnLib.DefineUnlockable(base.TypedKey, UnlockableItem, (Action<UnlockableInfoBuilder>)delegate(UnlockableInfoBuilder builder) { bool flag = Config.DisablePricingStrategy?.Value ?? false; if (Object.op_Implicit((Object)(object)PricingStrategy) && !flag) { PricingStrategy.Register(Key); builder.SetCost((IProvider<int>)PricingStrategy); } else { builder.SetCost(Config.Cost.Value); } if ((Object)(object)UnlockableItem.prefabObject != (Object)null) { builder.DefinePlaceableObject((Action<PlaceableObjectBuilder>)delegate(PlaceableObjectBuilder shopBuilder) { shopBuilder.Build(); if (Config.IsShipUpgrade?.Value ?? data2.isShipUpgrade) { DebugLogSource unlockables = Debuggers.Unlockables; if (unlockables != null) { unlockables.Log((object)("Making " + UnlockableItem.unlockableName + " a Ship Upgrade")); } shopBuilder.SetShipUpgrade(); } else if (Config.IsDecor?.Value ?? data2.isDecor) { DebugLogSource unlockables2 = Debuggers.Unlockables; if (unlockables2 != null) { unlockables2.Log((object)("Making " + UnlockableItem.unlockableName + " a Decor")); } shopBuilder.SetDecor(); } }); } if ((Object)(object)UnlockableItem.suitMaterial != (Object)null) { builder.DefineSuit((Action<SuitBuilder>)delegate(SuitBuilder suitBuilder) { suitBuilder.OverrideSuitMaterial(UnlockableItem.suitMaterial); suitBuilder.OverrideJumpAudioClip(UnlockableItem.jumpAudio); suitBuilder.Build(); }); } ConfigEntry<bool>? disableUnlockRequirement = Config.DisableUnlockRequirement; if ((disableUnlockRequirement == null || !disableUnlockRequirement.Value) && Object.op_Implicit((Object)(object)TerminalPredicate)) { TerminalPredicate.Register(Key); builder.SetPurchasePredicate((ITerminalPurchasePredicate)(object)TerminalPredicate); } ApplyTagsTo((BaseInfoBuilder)(object)builder); }); } public static UnlockableConfig CreateUnlockableConfig(ConfigContext context, DuskUnlockableDefinition definition, UnlockableData data, string unlockableName) { return new UnlockableConfig { DisablePricingStrategy = (data.generateDisablePricingStrategyConfig ? context.Bind(unlockableName + " | Disable Pricing Strategy", "Whether " + unlockableName + " should have it's pricing strategy disabled.", defaultValue: false) : null), DisableUnlockRequirement = (data.generateDisableUnlockRequirementConfig ? context.Bind(unlockableName + " | Disable Unlock Requirements", "Whether " + unlockableName + " should have it's unlock requirements disabled.", defaultValue: false) : null), IsDecor = context.Bind(unlockableName + " | Is Decor", "Whether " + unlockableName + " is considered a decor.", data.isDecor), IsShipUpgrade = context.Bind(unlockableName + " | Is Ship Upgrade", "Whether " + unlockableName + " is considered a ship upgrade.", data.isShipUpgrade), Cost = context.Bind(unlockableName + " | Cost", "Cost for " + unlockableName + " in the shop.", data.cost) }; } public override List<UnlockableData> GetEntities(DuskMod mod) { return mod.Content.assetBundles.SelectMany((AssetBundleData it) => it.unlockables).ToList(); } } [Serializable] public class DuskUnlockableReference : DuskContentReference<DuskUnlockableDefinition, DawnUnlockableItemInfo> { public DuskUnlockableReference() { } public DuskUnlockableReference(NamespacedKey<DawnUnlockableItemInfo> key) : base(key) { } public override bool TryResolve(out DawnUnlockableItemInfo info) { return ((Registry<DawnUnlockableItemInfo>)(object)LethalContent.Unlockables).TryGetValue(base.TypedKey, ref info); } public override DawnUnlockableItemInfo Resolve() { return ((Registry<DawnUnlockableItemInfo>)(object)LethalContent.Unlockables)[base.TypedKey]; } } public class UnlockableUpgradeScrap : GrabbableObject { [field: SerializeReference] public DuskUnlockableReference UnlockableReference { get; private set; } protected override void __initializeVariables() { ((GrabbableObject)this).__initializeVariables(); } [MethodImpl(MethodImplOptions.NoInlining)] protected internal override string __getTypeName() { return "UnlockableUpgradeScrap"; } } public class UnlockableConfig : EntityConfig { public ConfigEntry<int> Cost; public ConfigEntry<bool> IsDecor; public ConfigEntry<bool>? DisableUnlockRequirement; public ConfigEntry<bool>? DisablePricingStrategy; public ConfigEntry<bool> IsShipUpgrade; } [Serializable] public class UnlockableData : EntityData<DuskUnlockableReference> { public int cost; public bool isShipUpgrade; public bool isDecor; [FormerlySerializedAs("createProgressiveConfig")] public bool generateDisableUnlockRequirementConfig; public bool generateDisablePricingStrategyConfig; } public static class BuyableVehicleExtensions { public static NamespacedKey<DuskVehicleDefinition> ToNamespacedKey(this BuyableVehicle buyableVehicle) { if (!buyableVehicle.TryGetDuskDefinition(out DuskVehicleDefinition buyableVehicleDefinition)) { DebugLogSource unlockables = Debuggers.Unlockables; if (unlockables != null) { unlockables.Log((object)$"BuyableVehicle {buyableVehicle} has no DuskDefinition"); } throw new Exception(); } return ((NamespacedKey)buyableVehicleDefinition.TypedKey).AsTyped<DuskVehicleDefinition>(); } internal static bool TryGetDuskDefinition(this BuyableVehicle buyableVehicle, [NotNullWhen(true)] out DuskVehicleDefinition? buyableVehicleDefinition) { //IL_0002: Unknown result type (might be due to invalid IL or missing references) buyableVehicleDefinition = (DuskVehicleDefinition)((IDawnObject)buyableVehicle).DawnInfo; return (Object)(object)buyableVehicleDefinition != (Object)null; } internal static void SetDuskDefinition(this BuyableVehicle buyableVehicle, DuskVehicleDefinition buyableVehicleDefinition) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) ((IDawnObject)buyableVehicle).DawnInfo = buyableVehicleDefinition; } } [Serializable] public class BuyableVehiclePreset { public GameObject VehiclePrefab; [Header("Optional")] public GameObject? StationPrefab; public GameObject? SecondaryPrefab; [TextArea(2, 20)] public string DisplayNodeText; public string BuyKeywordText; internal TerminalNode BuyNode; internal TerminalKeyword BuyKeyword; internal TerminalNode ConfirmPurchaseNode; public TerminalNode? InfoNode; } [CreateAssetMenu(fileName = "New Vehicle Definition", menuName = "DawnLib/Definitions/Vehicle Definition")] public class DuskVehicleDefinition : DuskContentDefinition<VehicleData, DawnVehicleInfo>, INamespaced<DuskVehicleDefinition>, INamespaced { public const string REGISTRY_ID = "vehicles"; [field: SerializeField] public string VehicleDisplayName { get; private set; } [field: SerializeField] public BuyableVehiclePreset BuyableVehiclePreset { get; private set; } [field: SerializeField] public DuskTerminalPredicate? TerminalPredicate { get; private set; } [field: SerializeField] public DuskPricingStrategy? PricingStrategy { get; private set; } public VehicleConfig Config { get; private set; } NamespacedKey<DuskVehicleDefinition> INamespaced<DuskVehicleDefinition>.TypedKey => ((NamespacedKey)base.TypedKey).AsTyped<DuskVehicleDefinition>(); protected override string EntityNameReference => VehicleDisplayName; public override void Register(DuskMod mod, VehicleData data) { using ConfigContext context = mod.ConfigManager.CreateConfigSectionForBundleData(AssetBundleData); Config = CreateVehicleConfig(context, this, data, VehicleDisplayName); DuskModContent.Vehicles.Register(this); } public static VehicleConfig CreateVehicleConfig(ConfigContext context, DuskVehicleDefinition definition, VehicleData data, string vehicleName) { return new VehicleConfig { DisableUnlockRequirements = (data.generateDisableUnlockConfig ? context.Bind(vehicleName + " | Disable Unlock Requirements", "Whether " + vehicleName + " should have it's unlock requirements disabled.", defaultValue: false) : null), DisablePricingStrategy = (data.generateDisablePricingStrategyConfig ? context.Bind(vehicleName + " | Disable Pricing Strategy", "Whether " + vehicleName + " should have it's pricing strategy disabled.", defaultValue: false) : null), Cost = context.Bind(vehicleName + " | Cost", "Cost for " + vehicleName + " in the shop.", data.cost) }; } public override List<VehicleData> GetEntities(DuskMod mod) { return mod.Content.assetBundles.SelectMany((AssetBundleData it) => it.vehicles).ToList(); } } [Serializable] public class DuskVehicleReference : DuskContentReference<DuskVehicleDefinition, DuskVehicleDefinition> { public DuskVehicleReference() { } public DuskVehicleReference(NamespacedKey<DuskVehicleDefinition> key) : base(key) { } public override bool TryResolve(out DuskVehicleDefinition info) { return DuskModContent.Vehicles.TryGetValue(base.TypedKey, ref info); } public override DuskVehicleDefinition Resolve() { return DuskModContent.Vehicles[base.TypedKey]; } } public class VehicleConfig : EntityConfig { public ConfigEntry<int> Cost; public ConfigEntry<bool>? DisableUnlockRequirements; public ConfigEntry<bool>? DisablePricingStrategy; } [Serializable] public class VehicleData : EntityData<DuskVehicleReference> { public bool generateDisableUnlockConfig; public bool generateDisablePricingStrategyConfig; public int cost; } public interface IAnchorModule { IEnumerator EnableAnchor(IVehicle vehicle, IStation station); IEnumerator DisableAnchor(IVehicle vehicle, IStation station); } public interface IDropShipAttachment { Transform[] RopeAttachmentEndPoints { get; } int RealLength { get; } } public interface IStation : IAnchorModule { NamespacedKey StationKey { get; } Transform AnchorPoint { get; } bool IsOccupied { get; } IVehicle? CurrentVehicle { get; } bool CanAccept(IVehicle? vehicle); bool Engage(IVehicle? vehicle); bool Release(IVehicle? vehicle); } public interface IVehicle : IDropShipAttachment { NamespacedKey VehicleKey { get; } bool IsDocked { get; } IStation? CurrentStation { get; } UnityEvent<IStation> Docked { get; } UnityEvent<IStation> Undocked { get; } Collider[] VehicleColliders { get; } void RequestDock(IStation? station); void RequestUndock(IStation? station); void OnDocked(IStation station); void OnUndocked(IStation station); } [RequireComponent(typeof(AutoParentToShip))] [RequireComponent(typeof(PlaceableShipObject))] public abstract class StationBase : NetworkBehaviour, IStation, IAnchorModule { [field: SerializeField] public Transform AnchorPoint { get; private set; } public bool IsOccupied => CurrentVehicle != null; public IVehicle? CurrentVehicle { get; private set; } [field: SerializeField] public NamespacedKey StationKey { get; private set; } [field: SerializeField] public NamespacedKey<DuskVehicleDefinition> CorrespondingVehicleKey { get; private set; } public virtual void Awake() { } public virtual bool CanAccept([NotNullWhen(true)] IVehicle? vehicle) { if (vehicle == null || vehicle.IsDocked) { return false; } if (CorrespondingVehicleKey != vehicle.VehicleKey) { return false; } if (IsOccupied) { return false; } return true; } public abstract IEnumerator DisableAnchor(IVehicle vehicle, IStation station); public abstract IEnumerator EnableAnchor(IVehicle vehicle, IStation station); public virtual bool Engage(IVehicle? vehicle) { if (!CanAccept(vehicle)) { return false; } CurrentVehicle = vehicle; vehicle.OnDocked(this); ((MonoBehaviour)this).StartCoroutine(EnableAnchor(vehicle, this)); return true; } public virtual bool Release(IVehicle? vehicle) { if (vehicle == null || vehicle != CurrentVehicle) { return false; } if (!IsOccupied) { return false; } CurrentVehicle = null; vehicle.OnUndocked(this); ((MonoBehaviour)this).StartCoroutine(DisableAnchor(vehicle, this)); return true; } protected override void __initializeVariables() { ((NetworkBehaviour)this).__initializeVariables(); } [MethodImpl(MethodImplOptions.NoInlining)] protected internal override string __getTypeName() { return "StationBase"; } } public abstract class VehicleBase : NetworkBehaviour, IVehicle, IDropShipAttachment { [field: SerializeField] public UnityEvent<IStation> Docked { get; private set; } [field: SerializeField] public UnityEvent<IStation> Undocked { get; private set; } public bool IsDocked { get; private set; } public IStation? CurrentStation { get; private set; } [field: SerializeField] public NamespacedKey<DuskVehicleDefinition> VehicleKey { get; private set; } [field: SerializeField] public NamespacedKey CorrespondingStationKey { get; private set; } [field: SerializeField] public Transform[] RopeAttachmentEndPoints { get; private set; } NamespacedKey IVehicle.VehicleKey => (NamespacedKey)(object)VehicleKey; public int RealLength { get; private set; } = 4; public Collider[] VehicleColliders { get; private set; } public virtual void Awake() { //IL_0061: Unknown result type (might be due to invalid IL or missing references) //IL_008e: Unknown result type (might be due to invalid IL or missing references) if (RopeAttachmentEndPoints.Length > 4) { RopeAttachmentEndPoints = RopeAttachmentEndPoints.Take(4).ToArray(); } else if (RopeAttachmentEndPoints.Length < 4) { RealLength = RopeAttachmentEndPoints.Length; for (int i = RopeAttachmentEndPoints.Length; i < 4; i++) { RopeAttachmentEndPoints[i] = new GameObject($"RopeAttachmentPoint{i + 1}").transform; RopeAttachmentEndPoints[i].SetParent(((Component)this).transform, false); RopeAttachmentEndPoints[i].position = ((Component)this).transform.position; } } VehicleColliders = ((Component)this).GetComponentsInChildren<Collider>(); int num = LayerMask.NameToLayer("Vehicle"); VehicleBase[] array = Object.FindObjectsOfType<VehicleBase>(); foreach (VehicleBase vehicleBase in array) { if ((Object)(object)vehicleBase == (Object)(object)this) { continue; } Collider[] vehicleColliders = vehicleBase.VehicleColliders; foreach (Collider val in vehicleColliders) { if (val.isTrigger || ((Component)val).gameObject.layer != num) { continue; } Collider[] vehicleColliders2 = VehicleColliders; foreach (Collider val2 in vehicleColliders2) { if (!val2.isTrigger && ((Component)val2).gameObject.layer == num) { Physics.IgnoreCollision(val, val2); } } } } } public virtual void Update() { } public virtual void LateUpdate() { //IL_006c: Unknown result type (might be due to invalid IL or missing references) if (!StartOfRoundRefs.Instance.inShipPhase && TerminalRefs.LastVehicleDelivered == DuskModContent.Vehicles[VehicleKey].BuyableVehiclePreset.BuyNode.buyVehicleIndex && ItemDropshipRefs.Instance.deliveringVehicle && !ItemDropshipRefs.Instance.untetheredVehicle) { for (int i = RealLength; i < 4; i++) { RopeAttachmentEndPoints[i].position = ((Component)ItemDropshipRefs.Instance.ropes[i]).transform.position; } } } public virtual void FixedUpdate() { //IL_005a: Unknown result type (might be due to invalid IL or missing references) if (!StartOfRoundRefs.Instance.inShipPhase && TerminalRefs.LastVehicleDelivered == DuskModContent.Vehicles[VehicleKey].BuyableVehiclePreset.BuyNode.buyVehicleIndex && ItemDropshipRefs.Instance.deliveringVehicle && !ItemDropshipRefs.Instance.untetheredVehicle) { ((Component)this).transform.position = ItemDropshipRefs.Instance.deliverVehiclePoint.position; } } public virtual void RequestDock(IStation? station) { if (station != null && station.CanAccept(this) && CorrespondingStationKey == station.StationKey) { station.Engage(this); } } public virtual void RequestUndock(IStation? station) { if (CurrentStation != null && station == CurrentStation) { station.Release(this); } } public virtual void OnDocked(IStation station) { IsDocked = true; CurrentStation = station; Docked?.Invoke(station); } public virtual void OnUndocked(IStation station) { IsDocked = false; CurrentStation = null; Undocked?.Invoke(station); } protected override void __initializeVariables() { ((NetworkBehaviour)this).__initializeVariables(); } [MethodImpl(MethodImplOptions.NoInlining)] protected internal override string __getTypeName() { return "VehicleBase"; } } [CreateAssetMenu(fileName = "New Weather Definition", menuName = "DawnLib/Definitions/Weather Definition")] public class DuskWeatherDefinition : DuskContentDefinition<WeatherData, DawnWeatherEffectInfo> { public const string REGISTRY_ID = "weathers"; [field: SerializeField] public Weather Weather { get; private set; } protected override string EntityNameReference => Weather?.Name ?? string.Empty; public override void Register(DuskMod mod, WeatherData data) { //IL_008e: Unknown result type (might be due to invalid IL or missing references) //IL_0093: Unknown result type (might be due to invalid IL or missing references) //IL_009a: Unknown result type (might be due to invalid IL or missing references) //IL_00a2: Expected O, but got Unknown //IL_00a3: Unknown result type (might be due to invalid IL or missing references) //IL_00a9: Expected O, but got Unknown //IL_00f8: Unknown result type (might be due to invalid IL or missing references) /
BepInEx/plugins/DawnLib/com.github.teamxiaolan.dawnlib.compatibility.dll
Decompiled 3 days agousing System; using System.Diagnostics; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Bootstrap; using BepInEx.Logging; using Microsoft.CodeAnalysis; using UnityEngine; using loaforcsSoundAPI; using loaforcsSoundAPI.SoundPacks.Data.Conditions; [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("XuXiaolan,loaforc")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.1.9.0")] [assembly: AssemblyInformationalVersion("0.1.9+09cb71a636e1df245dcd8b6809da4e52cfd9ebcf")] [assembly: AssemblyProduct("DawnLib.Compatibility")] [assembly: AssemblyTitle("com.github.teamxiaolan.dawnlib.compatibility")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.1.9.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace Dawn.Compatibility { [BepInPlugin("com.github.teamxiaolan.dawnlib.compatibility", "DawnLib.Compatibility", "0.1.9")] [BepInDependency(/*Could not decode attribute arguments.*/)] [BepInDependency(/*Could not decode attribute arguments.*/)] public class DawnCompatibilityPlugin : BaseUnityPlugin { internal static ManualLogSource Logger { get; private set; } private void Awake() { Logger = ((BaseUnityPlugin)this).Logger; if (SoundAPICompat.Enabled) { SoundAPICompat.Init(); } Logger.LogInfo((object)"com.github.teamxiaolan.dawnlib.compatibility v0.1.9 has loaded!"); } } internal class DawnTaggableCondition : Condition { [CompilerGenerated] private Func<ITaggable?> <generator>P; private NamespacedKey? _key; public string Value { get; private set; } public DawnTaggableCondition(Func<ITaggable?> generator) { <generator>P = generator; ((Condition)this)..ctor(); } public override bool Evaluate(IContext context) { if (_key == null) { _key = NamespacedKey.ForceParse(Value); } ITaggable val = <generator>P(); if (val != null) { return val.HasTag(_key); } return false; } } internal static class SoundAPICompat { public static bool Enabled => Chainloader.PluginInfos.ContainsKey("me.loaforc.soundapi"); [MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)] internal static void Init() { SoundAPI.RegisterCondition("DawnLib:moon:has_tag", (Func<Condition>)(() => (Condition)(object)new DawnTaggableCondition(() => (ITaggable?)(object)((!Object.op_Implicit((Object)(object)StartOfRound.Instance)) ? null : SelectableLevelExtensions.GetDawnInfo(StartOfRound.Instance.currentLevel))))); SoundAPI.RegisterCondition("DawnLib:dungeon:has_tag", (Func<Condition>)(() => (Condition)(object)new DawnTaggableCondition(delegate { if (!Object.op_Implicit((Object)(object)RoundManager.Instance)) { return null; } return (ITaggable?)(object)((!Object.op_Implicit((Object)(object)RoundManager.Instance.dungeonGenerator)) ? null : DungeonFlowExtensions.GetDawnInfo(RoundManager.Instance.dungeonGenerator.Generator.DungeonFlow)); }))); } } public static class MyPluginInfo { public const string PLUGIN_GUID = "com.github.teamxiaolan.dawnlib.compatibility"; public const string PLUGIN_NAME = "DawnLib.Compatibility"; public const string PLUGIN_VERSION = "0.1.9"; } }
BepInEx/patchers/com.github.teamxiaolan.dawnlib.preloader.dll
Decompiled 3 days agousing System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx.Logging; using Microsoft.CodeAnalysis; using Mono.Cecil; using Mono.Cecil.Cil; using Mono.Collections.Generic; using MonoMod.Utils; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")] [assembly: IgnoresAccessChecksTo("")] [assembly: AssemblyCompany("XuXiaolan,loaforc")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyFileVersion("0.1.9.0")] [assembly: AssemblyInformationalVersion("0.1.9+09cb71a636e1df245dcd8b6809da4e52cfd9ebcf")] [assembly: AssemblyProduct("DawnLibPreloader")] [assembly: AssemblyTitle("DawnLibPreloader")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.1.9.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)] internal sealed class NullableAttribute : Attribute { public readonly byte[] NullableFlags; public NullableAttribute(byte P_0) { NullableFlags = new byte[1] { P_0 }; } public NullableAttribute(byte[] P_0) { NullableFlags = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)] internal sealed class NullableContextAttribute : Attribute { public readonly byte Flag; public NullableContextAttribute(byte P_0) { Flag = P_0; } } [CompilerGenerated] [Microsoft.CodeAnalysis.Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace Dawn { internal static class MyPluginInfo { public const string PLUGIN_GUID = "com.github.teamxiaolan.dawnlib.preloader"; public const string PLUGIN_NAME = "DawnLibPreloader"; public const string PLUGIN_VERSION = "0.1.9"; } } namespace Dawn.Preloader { public static class CecilHelper { public static bool AddField(this TypeDefinition self, FieldAttributes fieldAttributes, string name, TypeReference type, Action<bool, string> logCallback = null) { //IL_0056: 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_0062: Expected O, but got Unknown logCallback?.Invoke(arg1: false, "Adding field '" + name + "' to " + ((MemberReference)self).FullName); if (Extensions.FindField(self, name) != null) { logCallback?.Invoke(arg1: true, "Field '" + name + "' already exists in " + ((MemberReference)self).FullName); return false; } self.Fields.Add(new FieldDefinition(name, fieldAttributes, type)); return true; } public static bool AddMethod(this TypeDefinition self, string methodName, MethodAttributes attributes = 1, TypeReference returnType = null, ParameterDefinition[] parameters = null, Action<bool, string> logCallback = null) { //IL_00cf: Unknown result type (might be due to invalid IL or missing references) //IL_00d5: Unknown result type (might be due to invalid IL or missing references) //IL_00d7: Unknown result type (might be due to invalid IL or missing references) //IL_00dd: Expected O, but got Unknown //IL_0103: Unknown result type (might be due to invalid IL or missing references) //IL_010f: Unknown result type (might be due to invalid IL or missing references) //IL_0115: Invalid comparison between Unknown and I4 //IL_0149: 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_0166: Unknown result type (might be due to invalid IL or missing references) if (returnType == null) { returnType = ((MemberReference)self).Module.TypeSystem.Void; } if (parameters == null) { parameters = Array.Empty<ParameterDefinition>(); } logCallback?.Invoke(arg1: false, "Adding method " + ((MemberReference)returnType).FullName + " " + methodName + "(" + string.Join(",", parameters.Select((ParameterDefinition p) => ((MemberReference)((ParameterReference)p).ParameterType).FullName)) + ") to " + ((MemberReference)self).FullName); if (Extensions.FindMethod(self, methodName, true) != null) { logCallback?.Invoke(arg1: true, "Method '" + methodName + "' already exists in " + ((MemberReference)self).FullName); return false; } MethodDefinition val = new MethodDefinition(methodName, (MethodAttributes)(attributes | 0x80), returnType); self.Methods.Add(val); Extensions.AddRange<ParameterDefinition>(((MethodReference)val).Parameters, (IEnumerable<ParameterDefinition>)parameters); ILProcessor iLProcessor = val.Body.GetILProcessor(); Instruction val2 = iLProcessor.Create(OpCodes.Ret); if ((int)returnType.MetadataType != 1) { ConstructorInfo constructor = typeof(NotImplementedException).GetConstructor(new Type[1] { typeof(string) }); MethodReference val3 = ((MemberReference)self).Module.ImportReference((MethodBase)constructor); iLProcessor.Emit(OpCodes.Ldstr, "This is a Stub"); iLProcessor.Emit(OpCodes.Newobj, val3); iLProcessor.Emit(OpCodes.Throw); } iLProcessor.Append(val2); return true; } } internal class DawnLibPreloader { internal static ManualLogSource Log { get; } = Logger.CreateLogSource("DawnLib.Preloader"); public static IEnumerable<string> TargetDLLs { get; } = new string[1] { "Assembly-CSharp.dll" }; public static void Patch(AssemblyDefinition assembly) { //IL_00f4: Unknown result type (might be due to invalid IL or missing references) //IL_00f9: Unknown result type (might be due to invalid IL or missing references) Log.LogInfo((object)("Patching " + ((AssemblyNameReference)assembly.Name).Name)); Dictionary<string, List<Type>> dictionary = new Dictionary<string, List<Type>>(); Type[] types = Assembly.GetExecutingAssembly().GetTypes(); foreach (Type type in types) { if (!type.IsInterface) { continue; } IEnumerable<InjectInterfaceAttribute> enumerable = type.GetCustomAttributes(typeof(InjectInterfaceAttribute)).Cast<InjectInterfaceAttribute>(); if (!enumerable.Any()) { continue; } foreach (InjectInterfaceAttribute item in enumerable) { if (!dictionary.TryGetValue(item.FullName, out var value)) { value = new List<Type>(); } value.Add(type); dictionary[item.FullName] = value; } } Log.LogInfo((object)$"Injecting interfaces into '{dictionary.Count}' different types."); Enumerator<TypeDefinition> enumerator2 = assembly.MainModule.Types.GetEnumerator(); try { while (enumerator2.MoveNext()) { TypeDefinition current2 = enumerator2.Current; if (!dictionary.TryGetValue(((MemberReference)current2).FullName, out var value2)) { continue; } Log.LogInfo((object)$"{((MemberReference)current2).Name} has {value2.Count} interface(s) to inject."); foreach (Type item2 in value2) { ImplementInterface(current2, item2); } } } finally { ((IDisposable)enumerator2).Dispose(); } } private static void ImplementInterface(TypeDefinition type, Type @interface) { //IL_0171: Unknown result type (might be due to invalid IL or missing references) //IL_0178: Expected O, but got Unknown //IL_0182: Unknown result type (might be due to invalid IL or missing references) //IL_0189: Expected O, but got Unknown //IL_018e: Unknown result type (might be due to invalid IL or missing references) //IL_01a1: Unknown result type (might be due to invalid IL or missing references) //IL_01a5: Unknown result type (might be due to invalid IL or missing references) //IL_01ac: Expected O, but got Unknown //IL_01bc: Unknown result type (might be due to invalid IL or missing references) //IL_01c8: Unknown result type (might be due to invalid IL or missing references) //IL_01d6: 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_01fe: Unknown result type (might be due to invalid IL or missing references) //IL_0205: Expected O, but got Unknown //IL_0214: Unknown result type (might be due to invalid IL or missing references) //IL_021e: Expected O, but got Unknown //IL_022e: Unknown result type (might be due to invalid IL or missing references) //IL_023a: Unknown result type (might be due to invalid IL or missing references) //IL_0246: Unknown result type (might be due to invalid IL or missing references) //IL_0254: Unknown result type (might be due to invalid IL or missing references) //IL_02e5: Unknown result type (might be due to invalid IL or missing references) //IL_02ef: Expected O, but got Unknown TypeDefinition type2 = type; Log.LogDebug((object)("Injecting " + @interface.FullName + " into " + ((MemberReference)type2).FullName + ".")); ModuleDefinition module = ((MemberReference)type2).Module; MethodInfo[] methods = @interface.GetMethods(); foreach (MethodInfo methodInfo in methods) { Log.LogDebug((object)$"trying to inject {methodInfo.Name} ({methodInfo.Attributes})"); if (!methodInfo.Attributes.HasFlag(MethodAttributes.SpecialName)) { type2.AddMethod(methodInfo.Name, (MethodAttributes)70, module.ImportReference(methodInfo.ReturnType), (from it in methodInfo.GetParameters() select ToMonoCecilParameter(it, ((MemberReference)type2).Module)).ToArray()); } } PropertyInfo[] properties = @interface.GetProperties(); foreach (PropertyInfo propertyInfo in properties) { Log.LogDebug((object)("Injecting " + propertyInfo.Name)); TypeReference val = module.ImportReference(propertyInfo.PropertyType); FieldDefinition val2 = new FieldDefinition("<" + propertyInfo.Name + ">k__BackingField", (FieldAttributes)33, val); PropertyDefinition val3 = new PropertyDefinition(propertyInfo.Name, (PropertyAttributes)0, val); MethodAttributes val4 = (MethodAttributes)2502; MethodDefinition val5 = new MethodDefinition("get_" + propertyInfo.Name, val4, val); ILProcessor iLProcessor = val5.Body.GetILProcessor(); iLProcessor.Emit(OpCodes.Ldarg_0); iLProcessor.Emit(OpCodes.Ldfld, (FieldReference)(object)val2); iLProcessor.Emit(OpCodes.Ret); MethodDefinition val6 = new MethodDefinition("set_" + propertyInfo.Name, val4, module.TypeSystem.Void); ((MethodReference)val6).Parameters.Add(new ParameterDefinition("value", (ParameterAttributes)0, val)); ILProcessor iLProcessor2 = val6.Body.GetILProcessor(); iLProcessor2.Emit(OpCodes.Ldarg_0); iLProcessor2.Emit(OpCodes.Ldarg_1); iLProcessor2.Emit(OpCodes.Stfld, (FieldReference)(object)val2); iLProcessor2.Emit(OpCodes.Ret); type2.Methods.Add(val5); type2.Methods.Add(val6); val3.GetMethod = val5; val3.SetMethod = val6; type2.Properties.Add(val3); type2.Fields.Add(val2); } type2.Interfaces.Add(new InterfaceImplementation(((MemberReference)type2).Module.ImportReference(@interface))); } private static ParameterDefinition ToMonoCecilParameter(ParameterInfo pi, ModuleDefinition module) { //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_0021: Expected O, but got Unknown TypeReference val = module.ImportReference(pi.ParameterType); return new ParameterDefinition(pi.Name, (ParameterAttributes)(ushort)pi.Attributes, val); } public static void Initialize() { Log.LogInfo((object)"Prepatcher Started"); } public static void Finish() { Log.LogInfo((object)"Prepatcher Finished"); } } [AttributeUsage(AttributeTargets.Interface, AllowMultiple = true)] public sealed class InjectInterfaceAttribute : Attribute { [CompilerGenerated] private string <fullName>P; public string FullName => <fullName>P; public InjectInterfaceAttribute(string fullName) { <fullName>P = fullName; base..ctor(); } } } namespace Dawn.Preloader.Interfaces { [InjectInterface("EnemyType")] [InjectInterface("Item")] public interface ICurrentEntityReplacement { object? CurrentEntityReplacement { get; set; } } [InjectInterface("SelectableLevel")] [InjectInterface("WeatherEffect")] [InjectInterface("EnemyType")] [InjectInterface("Item")] [InjectInterface("UnlockableItem")] [InjectInterface("DunGen.TileSet")] [InjectInterface("DunGen.DungeonArchetype")] [InjectInterface("DunGen.Graph.DungeonFlow")] [InjectInterface("BuyableVehicle")] public interface IDawnObject { object DawnInfo { get; set; } } [InjectInterface("ScanNodeProperties")] public interface IDawnScanNode { object RectTransformInfo { get; set; } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { public IgnoresAccessChecksToAttribute(string assemblyName) { } } }