Please disclose if any significant portion of your mod was created using AI tools by adding the 'AI Generated' category. Failing to do so may result in the mod being removed from Thunderstore.
Decompiled source of DvergrHeadlamp v0.1.1
DvergrHeadlamp.dll
Decompiled 4 hours agousing System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Reflection; using System.Reflection.Emit; using System.Runtime.CompilerServices; using System.Runtime.Versioning; using System.Security; using System.Security.Permissions; using BepInEx; using BepInEx.Configuration; using BepInEx.Logging; using DvergrHeadlamp.Core; using DvergrHeadlamp.Headlamps; using DvergrHeadlamp.Prefabs; using HarmonyLib; using Jotunn.Configs; using Jotunn.Entities; using Jotunn.Managers; using Jotunn.Utils; using Microsoft.CodeAnalysis; using UnityEngine; [assembly: CompilationRelaxations(8)] [assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)] [assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)] [assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")] [assembly: IgnoresAccessChecksTo("")] [assembly: AssemblyCompany("DvergrHeadlamp")] [assembly: AssemblyConfiguration("Release")] [assembly: AssemblyDescription("Craft a Dvergr headlamp early on and change its light colour at a workbench with one easy-to-find material.")] [assembly: AssemblyFileVersion("0.1.1.0")] [assembly: AssemblyInformationalVersion("0.1.1+14064a1776c237b13f52141411c87536d7299d44")] [assembly: AssemblyProduct("DvergrHeadlamp")] [assembly: AssemblyTitle("DvergrHeadlamp")] [assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)] [assembly: AssemblyVersion("0.1.1.0")] [module: UnverifiableCode] [module: RefSafetyRules(11)] [DebuggerDisplay("Count = {System.Collections.ICollection.Count}")] [CompilerGenerated] internal sealed class <>z__ReadOnlyArray<T> : IEnumerable, ICollection, IList, IEnumerable<T>, IReadOnlyCollection<T>, IReadOnlyList<T>, ICollection<T>, IList<T> { int ICollection.Count => _items.Length; bool ICollection.IsSynchronized => false; object ICollection.SyncRoot => this; object IList.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } bool IList.IsFixedSize => true; bool IList.IsReadOnly => true; int IReadOnlyCollection<T>.Count => _items.Length; T IReadOnlyList<T>.this[int index] => _items[index]; int ICollection<T>.Count => _items.Length; bool ICollection<T>.IsReadOnly => true; T IList<T>.this[int index] { get { return _items[index]; } set { throw new NotSupportedException(); } } public <>z__ReadOnlyArray(T[] items) { _items = items; } IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_items).GetEnumerator(); } void ICollection.CopyTo(Array array, int index) { ((ICollection)_items).CopyTo(array, index); } int IList.Add(object value) { throw new NotSupportedException(); } void IList.Clear() { throw new NotSupportedException(); } bool IList.Contains(object value) { return ((IList)_items).Contains(value); } int IList.IndexOf(object value) { return ((IList)_items).IndexOf(value); } void IList.Insert(int index, object value) { throw new NotSupportedException(); } void IList.Remove(object value) { throw new NotSupportedException(); } void IList.RemoveAt(int index) { throw new NotSupportedException(); } IEnumerator<T> IEnumerable<T>.GetEnumerator() { return ((IEnumerable<T>)_items).GetEnumerator(); } void ICollection<T>.Add(T item) { throw new NotSupportedException(); } void ICollection<T>.Clear() { throw new NotSupportedException(); } bool ICollection<T>.Contains(T item) { return ((ICollection<T>)_items).Contains(item); } void ICollection<T>.CopyTo(T[] array, int arrayIndex) { ((ICollection<T>)_items).CopyTo(array, arrayIndex); } bool ICollection<T>.Remove(T item) { throw new NotSupportedException(); } int IList<T>.IndexOf(T item) { return ((IList<T>)_items).IndexOf(item); } void IList<T>.Insert(int index, T item) { throw new NotSupportedException(); } void IList<T>.RemoveAt(int index) { throw new NotSupportedException(); } } namespace Microsoft.CodeAnalysis { [CompilerGenerated] [Embedded] internal sealed class EmbeddedAttribute : Attribute { } } namespace System.Runtime.CompilerServices { [CompilerGenerated] [Embedded] [AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)] internal sealed class RefSafetyRulesAttribute : Attribute { public readonly int Version; public RefSafetyRulesAttribute(int P_0) { Version = P_0; } } } namespace DvergrHeadlamp { [BepInPlugin("javidahmed64592.dvergrheadlamp", "Dvergr Headlamp", "0.1.1")] [BepInDependency(/*Could not decode attribute arguments.*/)] [NetworkCompatibility(/*Could not decode attribute arguments.*/)] public class DvergrHeadlampPlugin : BaseUnityPlugin { public const string PluginGUID = "javidahmed64592.dvergrheadlamp"; public const string PluginName = "Dvergr Headlamp"; public const string PluginVersion = "0.1.1"; internal static ManualLogSource _log; private Harmony _harmony; private static bool _recipes; private void Awake() { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_001b: Expected O, but got Unknown _log = ((BaseUnityPlugin)this).Logger; _harmony = new Harmony("javidahmed64592.dvergrheadlamp"); _recipes = SafePatcher.PatchAll(_harmony, ((BaseUnityPlugin)this).Config, ((BaseUnityPlugin)this).Logger); HeadlampBrightness.BindConfig(((BaseUnityPlugin)this).Config); Translations.Load(); PrefabManager.OnVanillaPrefabsAvailable += RegisterItems; } private static void RegisterItems() { PrefabManager.OnVanillaPrefabsAvailable -= RegisterItems; HeadlampPrefabs.Register(_recipes); } private void Update() { HeadlampBrightness.Update(Player.m_localPlayer); if (!_recipes || SafePatcher.ModEnabled || !((Object)(object)ObjectDB.instance != (Object)null)) { return; } _recipes = false; foreach (Recipe recipe in ObjectDB.instance.m_recipes) { if (HeadlampColour.Of(recipe) != null) { recipe.m_enabled = false; } } } private void OnDestroy() { Harmony harmony = _harmony; if (harmony != null) { harmony.UnpatchSelf(); } } } } namespace DvergrHeadlamp.Prefabs { internal static class HeadlampIcons { private const float GemHueMin = 0.4f; private const float GemHueMax = 0.6f; private const float GemMinSaturation = 0.25f; public static Sprite Recolour(Sprite circlet, HeadlampColour colour) { //IL_0009: Unknown result type (might be due to invalid IL or missing references) //IL_000f: Invalid comparison between Unknown and I4 //IL_001b: Unknown result type (might be due to invalid IL or missing references) //IL_003a: Unknown result type (might be due to invalid IL or missing references) //IL_003f: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_00d6: Unknown result type (might be due to invalid IL or missing references) //IL_00e5: Unknown result type (might be due to invalid IL or missing references) //IL_0084: Unknown result type (might be due to invalid IL or missing references) //IL_0089: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_009e: Unknown result type (might be due to invalid IL or missing references) if ((Object)(object)circlet == (Object)null || (int)SystemInfo.graphicsDeviceType == 4) { return circlet; } Texture2D val = ReadSprite(circlet); float num = default(float); float num2 = default(float); float num3 = default(float); Color.RGBToHSV(colour.Light, ref num, ref num2, ref num3); Color[] pixels = val.GetPixels(); float num4 = default(float); float num5 = default(float); float num6 = default(float); for (int i = 0; i < pixels.Length; i++) { Color val2 = pixels[i]; Color.RGBToHSV(val2, ref num4, ref num5, ref num6); if (!(val2.a <= 0f) && !(num5 < 0.25f) && !(num4 < 0.4f) && !(num4 > 0.6f)) { Color val3 = Color.HSVToRGB(num, num5 * num2 / 0.8f, num6); val3.a = val2.a; pixels[i] = val3; } } val.SetPixels(pixels); val.Apply(); Sprite obj = Sprite.Create(val, new Rect(0f, 0f, (float)((Texture)val).width, (float)((Texture)val).height), new Vector2(0.5f, 0.5f), circlet.pixelsPerUnit); ((Object)obj).name = colour.Prefab; return obj; } private static Texture2D ReadSprite(Sprite sprite) { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0048: Unknown result type (might be due to invalid IL or missing references) //IL_004d: Unknown result type (might be due to invalid IL or missing references) //IL_004e: Unknown result type (might be due to invalid IL or missing references) //IL_0056: Unknown result type (might be due to invalid IL or missing references) //IL_0069: Expected O, but got Unknown Rect textureRect = sprite.textureRect; Texture2D texture = sprite.texture; RenderTexture temporary = RenderTexture.GetTemporary(((Texture)texture).width, ((Texture)texture).height, 0, (RenderTextureFormat)0, (RenderTextureReadWrite)0); Graphics.Blit((Texture)(object)texture, temporary); RenderTexture active = RenderTexture.active; RenderTexture.active = temporary; Texture2D val = new Texture2D((int)((Rect)(ref textureRect)).width, (int)((Rect)(ref textureRect)).height, (TextureFormat)4, false); val.ReadPixels(textureRect, 0, 0); val.Apply(); RenderTexture.active = active; RenderTexture.ReleaseTemporary(temporary); return val; } } internal static class HeadlampPrefabs { private const string CircletPrefab = "HelmetDverger"; private const string Workbench = "piece_workbench"; private const string StoneMaterial = "dvergerhat_stone"; public static void Register(bool withRecipes) { //IL_0017: Unknown result type (might be due to invalid IL or missing references) //IL_001e: Expected O, but got Unknown //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_008c: Expected O, but got Unknown //IL_0096: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Expected O, but got Unknown //IL_006e: Unknown result type (might be due to invalid IL or missing references) //IL_0074: Expected O, but got Unknown //IL_00b0: Unknown result type (might be due to invalid IL or missing references) //IL_00b6: Expected O, but got Unknown //IL_00bd: Unknown result type (might be due to invalid IL or missing references) foreach (HeadlampColour item in HeadlampColour.All) { ItemConfig val = new ItemConfig(); val.Name = item.Token; val.Description = "$item_dvergrheadlamp_description"; val.Enabled = withRecipes; val.CraftingStation = "piece_workbench"; val.MinStationLevel = 1; val.Requirements = (RequirementConfig[])(object)((!item.IsNeutral) ? new RequirementConfig[1] { new RequirementConfig(item.Ingredient, 1, 0, true) } : new RequirementConfig[2] { new RequirementConfig("Copper", 1, 0, true), new RequirementConfig("SurtlingCore", 1, 0, true) }); ItemConfig val2 = val; CustomItem val3 = new CustomItem(item.Prefab, "HelmetDverger", val2); Recolour(val3.ItemPrefab, item.Light); SharedData shared = val3.ItemDrop.m_itemData.m_shared; Sprite[] icons = shared.m_icons; if (icons != null && icons.Length > 0) { shared.m_icons = (Sprite[])(object)new Sprite[1] { HeadlampIcons.Recolour(shared.m_icons[0], item) }; } ItemManager.Instance.AddItem(val3); } } private static void Recolour(GameObject prefab, Color colour) { //IL_0011: Unknown result type (might be due to invalid IL or missing references) //IL_0097: Unknown result type (might be due to invalid IL or missing references) //IL_009c: Unknown result type (might be due to invalid IL or missing references) //IL_00b4: Expected O, but got Unknown //IL_00bb: Unknown result type (might be due to invalid IL or missing references) //IL_00c0: Unknown result type (might be due to invalid IL or missing references) //IL_00c9: Unknown result type (might be due to invalid IL or missing references) //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_00db: Unknown result type (might be due to invalid IL or missing references) //IL_00e2: Unknown result type (might be due to invalid IL or missing references) //IL_00f3: 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) Light[] componentsInChildren = prefab.GetComponentsInChildren<Light>(true); foreach (Light val in componentsInChildren) { val.color = colour; HeadlampLight headlampLight = ((Component)val).gameObject.AddComponent<HeadlampLight>(); headlampLight.BaseIntensity = val.intensity; headlampLight.BaseRange = val.range; } Renderer[] componentsInChildren2 = prefab.GetComponentsInChildren<Renderer>(true); foreach (Renderer val2 in componentsInChildren2) { Material[] sharedMaterials = val2.sharedMaterials; bool flag = false; for (int j = 0; j < sharedMaterials.Length; j++) { if (!((Object)(object)sharedMaterials[j] == (Object)null) && ((Object)sharedMaterials[j]).name.StartsWith("dvergerhat_stone", StringComparison.Ordinal)) { Material val3 = new Material(sharedMaterials[j]) { name = "dvergerhat_stone_" + ((Object)prefab).name }; Color color = val3.GetColor("_Color"); val3.SetColor("_Color", new Color(colour.r, colour.g, colour.b, color.a)); val3.SetColor("_EmissionColor", colour * 0.95f); sharedMaterials[j] = val3; flag = true; } } if (flag) { val2.sharedMaterials = sharedMaterials; } } } } } namespace DvergrHeadlamp.Patches { [HarmonyPatch(typeof(InventoryGui), "DoCrafting")] internal static class InventoryGui_DoCrafting_Patch { private static bool Prefix(InventoryGui __instance, Player player) { return !HeadlampSwap.TrySwap(__instance, player, __instance.m_craftRecipe); } } [HarmonyPatch(typeof(InventoryGui), "Update")] internal static class InventoryGui_Update_Patch { private static void Prefix() { if ((Object)(object)Player.m_localPlayer != (Object)null && InventoryGui.IsVisible()) { HeadlampSwap.UpdateNeutralCost(Player.m_localPlayer); } } } [HarmonyPatch(typeof(Player), "HaveRequirements", new Type[] { typeof(Recipe), typeof(bool), typeof(int), typeof(int) })] internal static class Player_HaveRequirements_Patch { private static void Postfix(Player __instance, Recipe recipe, bool discover, ref bool __result) { if (__result && !(discover ? HeadlampSwap.Unlocked(__instance, recipe) : HeadlampSwap.HaveHeadlampFor(__instance, recipe))) { __result = false; } } } } namespace DvergrHeadlamp.Headlamps { internal static class HeadlampBrightness { public enum Level { Dim, Normal, Bright, Off } public static readonly int ZdoKey = StringExtensionMethods.GetStableHashCode("dvergrheadlamp_brightness"); private const string SaveKey = "dvergrheadlamp_brightness"; private static KeyBinding _key; public static void BindConfig(ConfigFile config) { _key = KeyBinding.Bind(config, "Keybinds", "Brightness", (KeyCode)105, KeyModifier.None, "While wearing a headlamp, changes its brightness: dim, normal, bright or off. Other players see it too."); } public static float Factor(Level level) { return level switch { Level.Dim => 0.5f, Level.Bright => 1.75f, Level.Off => 0f, _ => 1f, }; } public static void Update(Player player) { if (!((Object)(object)player == (Object)null) && !((Object)(object)((Character)player).m_nview == (Object)null) && ((Character)player).m_nview.IsValid() && ((Character)player).m_nview.IsOwner()) { Level level = Saved(player); ZDO zDO = ((Character)player).m_nview.GetZDO(); if (zDO.GetInt(ZdoKey, 1) != (int)level) { zDO.Set(ZdoKey, (int)level, false); } if (!Blocked() && HeadlampColour.Of(((Humanoid)player).m_helmetItem) != null && _key.IsDown()) { level = (Level)((int)(level + 1) % 4); Dictionary<string, string> customData = player.m_customData; int num = (int)level; customData["dvergrheadlamp_brightness"] = num.ToString(CultureInfo.InvariantCulture); zDO.Set(ZdoKey, (int)level, false); ((Character)player).Message((MessageType)1, Localization.instance.Localize("$dvergrheadlamp_brightness", new string[1] { "$dvergrheadlamp_level_" + level.ToString().ToLowerInvariant() }), 0, (Sprite)null, false); } } } private static Level Saved(Player player) { if (!player.m_customData.TryGetValue("dvergrheadlamp_brightness", out var value) || !int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out var result) || result < 0 || result > 3) { return Level.Normal; } return (Level)result; } private static bool Blocked() { if (!Menu.IsVisible() && (!((Object)(object)Chat.instance != (Object)null) || !Chat.instance.HasFocus()) && !Console.IsVisible()) { return TextInput.IsVisible(); } return true; } } internal sealed class HeadlampColour(string prefab, string token, string ingredient, Color light) { public static readonly HeadlampColour Neutral = new HeadlampColour("DvergrHeadlamp", "$item_dvergrheadlamp", null, new Color(1f, 0.93f, 0.82f)); public static readonly IReadOnlyList<HeadlampColour> All = new <>z__ReadOnlyArray<HeadlampColour>(new HeadlampColour[6] { Neutral, new HeadlampColour("DvergrHeadlamp_Blue", "$item_dvergrheadlamp_blue", "GreydwarfEye", new Color(0.35f, 0.6f, 1f)), new HeadlampColour("DvergrHeadlamp_Green", "$item_dvergrheadlamp_green", "Guck", new Color(0.45f, 1f, 0.35f)), new HeadlampColour("DvergrHeadlamp_Orange", "$item_dvergrheadlamp_orange", "Amber", new Color(1f, 0.6f, 0.18f)), new HeadlampColour("DvergrHeadlamp_Pink", "$item_dvergrheadlamp_pink", "AmberPearl", new Color(1f, 0.68f, 0.84f)), new HeadlampColour("DvergrHeadlamp_Red", "$item_dvergrheadlamp_red", "Ruby", new Color(1f, 0.28f, 0.22f)) }); private static Dictionary<string, HeadlampColour> _byPrefab; public string Prefab { get; } = prefab; public string Token { get; } = token; public string Ingredient { get; } = ingredient; public Color Light { get; } = light; public bool IsNeutral => Ingredient == null; public static HeadlampColour Of(string prefab) { if (_byPrefab == null) { _byPrefab = new Dictionary<string, HeadlampColour>(); foreach (HeadlampColour item in All) { _byPrefab[item.Prefab] = item; } } if (prefab == null || !_byPrefab.TryGetValue(prefab, out var value)) { return null; } return value; } public static HeadlampColour Of(ItemData item) { if (!((Object)(object)item?.m_dropPrefab != (Object)null)) { return null; } return Of(((Object)item.m_dropPrefab).name); } public static HeadlampColour Of(Recipe recipe) { if (!((Object)(object)recipe?.m_item != (Object)null)) { return null; } return Of(((Object)((Component)recipe.m_item).gameObject).name); } } internal sealed class HeadlampLight : MonoBehaviour { public float BaseIntensity; public float BaseRange; private Light _light; private ZNetView _owner; private bool _ownerSearched; private int _applied = -1; private void Update() { if ((Object)(object)_light == (Object)null) { _light = ((Component)this).GetComponent<Light>(); if ((Object)(object)_light == (Object)null) { return; } } if (!_ownerSearched) { _owner = ((Component)this).GetComponentInParent<ZNetView>(); _ownerSearched = true; } int num = ((!((Object)(object)_owner != (Object)null) || !_owner.IsValid()) ? 1 : _owner.GetZDO().GetInt(HeadlampBrightness.ZdoKey, 1)); if (num != _applied) { _applied = num; float num2 = HeadlampBrightness.Factor((HeadlampBrightness.Level)num); ((Behaviour)_light).enabled = num2 > 0f; _light.intensity = BaseIntensity * num2; _light.range = BaseRange * Mathf.Sqrt(Mathf.Max(num2, 0.01f)); } } } internal static class HeadlampSwap { private static Recipe _neutralRecipe; private static Requirement[] _neutralCost; public static ItemData Source(Player player, HeadlampColour target) { ItemData helmetItem = ((Humanoid)player).m_helmetItem; HeadlampColour headlampColour = HeadlampColour.Of(helmetItem); if (headlampColour != null && headlampColour != target) { return helmetItem; } foreach (ItemData allItem in ((Humanoid)player).GetInventory().GetAllItems()) { HeadlampColour headlampColour2 = HeadlampColour.Of(allItem); if (headlampColour2 != null && headlampColour2 != target) { return allItem; } } return null; } public static bool IsSwap(Player player, Recipe recipe) { HeadlampColour headlampColour = HeadlampColour.Of(recipe); if (headlampColour == null) { return false; } if (!headlampColour.IsNeutral) { return true; } ItemData val = Source(player, headlampColour); if (val != null) { return !HeadlampColour.Of(val).IsNeutral; } return false; } public static void UpdateNeutralCost(Player player) { if ((Object)(object)_neutralRecipe == (Object)null) { if ((Object)(object)ObjectDB.instance == (Object)null) { return; } foreach (Recipe recipe in ObjectDB.instance.m_recipes) { if (HeadlampColour.Of(recipe) == HeadlampColour.Neutral) { _neutralRecipe = recipe; _neutralCost = recipe.m_resources; break; } } if ((Object)(object)_neutralRecipe == (Object)null) { return; } } Requirement[] array = (IsSwap(player, _neutralRecipe) ? Array.Empty<Requirement>() : _neutralCost); if (_neutralRecipe.m_resources != array) { _neutralRecipe.m_resources = array; } } public static bool Unlocked(Player player, Recipe recipe) { HeadlampColour headlampColour = HeadlampColour.Of(recipe); if (headlampColour != null && !headlampColour.IsNeutral) { return player.IsRecipeKnown(HeadlampColour.Neutral.Token); } return true; } public static bool HaveHeadlampFor(Player player, Recipe recipe) { HeadlampColour headlampColour = HeadlampColour.Of(recipe); if (headlampColour != null && !headlampColour.IsNeutral) { return Source(player, headlampColour) != null; } return true; } public static bool TrySwap(InventoryGui gui, Player player, Recipe recipe) { //IL_0063: Unknown result type (might be due to invalid IL or missing references) //IL_0068: Unknown result type (might be due to invalid IL or missing references) //IL_008d: Unknown result type (might be due to invalid IL or missing references) //IL_009f: Unknown result type (might be due to invalid IL or missing references) //IL_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_0121: Unknown result type (might be due to invalid IL or missing references) //IL_0127: Unknown result type (might be due to invalid IL or missing references) if (!IsSwap(player, recipe)) { return false; } HeadlampColour headlampColour = HeadlampColour.Of(recipe); ItemData val = Source(player, headlampColour); bool flag = player.NoCostCheat() || ZoneSystem.instance.GetGlobalKey((GlobalKeys)25); if (val == null || (!flag && !player.HaveRequirements(recipe, false, 1, 1))) { return true; } Inventory inventory = ((Humanoid)player).GetInventory(); bool flag2 = ((Humanoid)player).IsItemEquiped(val); if (flag2) { ((Humanoid)player).UnequipItem(val, false); } Vector2i gridPos = val.m_gridPos; inventory.RemoveItem(val); ItemData val2 = inventory.AddItem(headlampColour.Prefab, 1, val.m_quality, 0, val.m_crafterID, val.m_crafterName, gridPos, false, false, false); if (val2 == null) { inventory.AddItem(val, gridPos); if (flag2) { ((Humanoid)player).EquipItem(val, false); } return true; } val2.m_durability = Mathf.Min(val.m_durability, val2.GetMaxDurability()); if (!flag) { player.ConsumeResources(recipe.m_resources, 1, -1, 1); } if (flag2) { ((Humanoid)player).EquipItem(val2, true); } CraftingStation currentCraftingStation = player.GetCurrentCraftingStation(); if ((Object)(object)currentCraftingStation != (Object)null) { currentCraftingStation.m_craftItemDoneEffects.Create(((Component)player).transform.position, Quaternion.identity, (Transform)null, 1f, -1, default(ZDOID)); } gui.UpdateCraftingPanel(false); return true; } } } namespace DvergrHeadlamp.Core { [AttributeUsage(AttributeTargets.Class, Inherited = false)] internal sealed class FeatureAttribute(string name) : Attribute() { public string Name { get; } = name; } internal enum KeyModifier { None, Shift, Ctrl, Alt } internal sealed class KeyBinding { private static readonly List<KeyBinding> All = new List<KeyBinding>(); private readonly ConfigEntry<KeyModifier> _modifier; internal ConfigEntry<KeyCode> KeyEntry { get; } internal KeyCode Key => KeyEntry.Value; internal KeyModifier Modifier => _modifier.Value; private KeyBinding(ConfigEntry<KeyCode> key, ConfigEntry<KeyModifier> modifier) { KeyEntry = key; _modifier = modifier; } internal static KeyBinding Bind(ConfigFile config, string section, string name, KeyCode key, KeyModifier modifier, string description) { //IL_000f: Unknown result type (might be due to invalid IL or missing references) //IL_0016: Unknown result type (might be due to invalid IL or missing references) //IL_0020: Expected O, but got Unknown //IL_0020: Expected O, but got Unknown //IL_0023: Unknown result type (might be due to invalid IL or missing references) string text = name + " Modifier"; MoveOldShortcut(config, new ConfigDefinition(section, name), new ConfigDefinition(section, text)); KeyBinding keyBinding = new KeyBinding(config.Bind<KeyCode>(section, name, key, description), config.Bind<KeyModifier>(section, text, modifier, "Held with the " + name + " key: Shift, Ctrl or Alt (either side), or None for the key on its own.")); All.Add(keyBinding); return keyBinding; } internal bool IsDown() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) if ((int)Key != 0 && UnityInput.Current.GetKeyDown(Key)) { return Accepts(); } return false; } internal bool IsHeld() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) //IL_000e: Unknown result type (might be due to invalid IL or missing references) if ((int)Key != 0 && UnityInput.Current.GetKey(Key)) { return Accepts(); } return false; } internal bool Accepts() { //IL_003b: Unknown result type (might be due to invalid IL or missing references) //IL_0041: Unknown result type (might be due to invalid IL or missing references) if (!ModifierHeld(Modifier)) { return false; } if (Modifier != KeyModifier.None) { return true; } foreach (KeyBinding item in All) { if (item != this && item.Modifier != KeyModifier.None && item.Key == Key && ModifierHeld(item.Modifier)) { return false; } } return true; } internal static bool AnyComboDown() { foreach (KeyBinding item in All) { if (item.Modifier != KeyModifier.None && item.IsDown()) { return true; } } return false; } internal string[] HintKeys() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) string text = KeyName(Key); return Modifier switch { KeyModifier.Shift => new string[2] { "Left Shift", text }, KeyModifier.Ctrl => new string[2] { "Left Ctrl", text }, KeyModifier.Alt => new string[2] { "Left Alt", text }, _ => new string[1] { text }, }; } public override string ToString() { //IL_0001: Unknown result type (might be due to invalid IL or missing references) string text = KeyName(Key); if (Modifier != KeyModifier.None) { return Modifier.ToString() + " + " + text; } return text; } private unsafe static string KeyName(KeyCode key) { //IL_0000: Unknown result type (might be due to invalid IL or missing references) //IL_0006: Unknown result type (might be due to invalid IL or missing references) //IL_0024: Expected I4, but got Unknown //IL_0024: Unknown result type (might be due to invalid IL or missing references) //IL_002a: Unknown result type (might be due to invalid IL or missing references) //IL_003c: Expected I4, but got Unknown return (key - 303) switch { 3 => "Left Ctrl", 2 => "Right Ctrl", 1 => "Left Shift", 0 => "Right Shift", 5 => "Left Alt", 4 => "Right Alt", _ => (key - 323) switch { 0 => "Mouse 1", 1 => "Mouse 2", 2 => "Mouse 3", _ => ((object)(*(KeyCode*)(&key))/*cast due to .constrained prefix*/).ToString(), }, }; } private static bool ModifierHeld(KeyModifier modifier) { return modifier switch { KeyModifier.Shift => UnityInput.Current.GetKey((KeyCode)304) || UnityInput.Current.GetKey((KeyCode)303), KeyModifier.Ctrl => UnityInput.Current.GetKey((KeyCode)306) || UnityInput.Current.GetKey((KeyCode)305), KeyModifier.Alt => UnityInput.Current.GetKey((KeyCode)308) || UnityInput.Current.GetKey((KeyCode)307), _ => true, }; } private static void MoveOldShortcut(ConfigFile config, ConfigDefinition keyDefinition, ConfigDefinition modifierDefinition) { //IL_0041: Unknown result type (might be due to invalid IL or missing references) //IL_0046: Unknown result type (might be due to invalid IL or missing references) //IL_004b: Unknown result type (might be due to invalid IL or missing references) //IL_0050: Unknown result type (might be due to invalid IL or missing references) //IL_0078: Unknown result type (might be due to invalid IL or missing references) //IL_007d: Unknown result type (might be due to invalid IL or missing references) //IL_007f: Unknown result type (might be due to invalid IL or missing references) //IL_0086: Unknown result type (might be due to invalid IL or missing references) //IL_00a4: Expected I4, but got Unknown if (!(AccessTools.Property(typeof(ConfigFile), "OrphanedEntries")?.GetValue(config) is Dictionary<ConfigDefinition, string> dictionary) || !dictionary.TryGetValue(keyDefinition, out var value) || Enum.TryParse<KeyCode>(value, out KeyCode _)) { return; } KeyboardShortcut val = KeyboardShortcut.Deserialize(value); dictionary[keyDefinition] = ((object)((KeyboardShortcut)(ref val)).MainKey/*cast due to .constrained prefix*/).ToString(); KeyModifier keyModifier = KeyModifier.None; foreach (KeyCode modifier in ((KeyboardShortcut)(ref val)).Modifiers) { KeyModifier keyModifier2; switch (modifier - 303) { case 0: case 1: keyModifier2 = KeyModifier.Shift; break; case 2: case 3: keyModifier2 = KeyModifier.Ctrl; break; case 4: case 5: keyModifier2 = KeyModifier.Alt; break; default: keyModifier2 = keyModifier; break; } keyModifier = keyModifier2; } if (!dictionary.ContainsKey(modifierDefinition)) { dictionary[modifierDefinition] = keyModifier.ToString(); } } } internal static class SafePatcher { private const string DebugSection = "Debug"; private const string DisabledFeaturesKey = "DisabledFeatures"; private static readonly Assembly OurAssembly = typeof(SafePatcher).Assembly; private static readonly MethodInfo GuardMethod = AccessTools.Method(typeof(SafePatcher), "Guard", (Type[])null, (Type[])null); private static readonly Dictionary<Type, string> Owners = new Dictionary<Type, string>(); private static readonly Dictionary<string, List<Type>> Features = new Dictionary<string, List<Type>>(); private static readonly HashSet<string> Off = new HashSet<string>(); private static readonly Dictionary<MethodBase, List<MethodBase>> Callees = new Dictionary<MethodBase, List<MethodBase>>(); private static readonly Dictionary<short, OpCode> OpCodesByValue = (from field in typeof(OpCodes).GetFields(BindingFlags.Static | BindingFlags.Public) select (OpCode)field.GetValue(null)).ToDictionary((OpCode code) => code.Value); private static Harmony _harmony; private static ManualLogSource _log; public static bool ModEnabled { get; private set; } public static bool IsOn(string feature) { if (ModEnabled && Features.ContainsKey(feature)) { return !Off.Contains(feature); } return false; } public static bool PatchAll(Harmony harmony, ConfigFile config, ManualLogSource log) { _harmony = harmony; _log = log; List<Type> list = new List<Type>(); Type[] typesFromAssembly = AccessTools.GetTypesFromAssembly(OurAssembly); foreach (Type type in typesFromAssembly) { if (type.IsDefined(typeof(HarmonyPatch), inherit: false)) { string text = type.GetCustomAttribute<FeatureAttribute>()?.Name; Owners[type] = text; if (text == null) { list.Add(type); continue; } if (Features.TryGetValue(text, out var value)) { value.Add(type); continue; } Features[text] = new List<Type>(1) { type }; } } HashSet<string> hashSet = ReadDisabledFeatures(config); foreach (Type item in list) { if (!TryPatch(item, out var reason)) { TurnModOff(item.Name + " couldn't be patched (" + reason + ")"); return false; } } ModEnabled = true; foreach (KeyValuePair<string, List<Type>> feature in Features) { if (hashSet.Contains(feature.Key)) { Off.Add(feature.Key); _log.LogInfo((object)("Feature \"" + feature.Key + "\" is off: turned off in the config.")); continue; } foreach (Type item2 in feature.Value) { if (!TryPatch(item2, out var reason2)) { Off.Add(feature.Key); Unpatch(feature.Value); _log.LogError((object)("Feature \"" + feature.Key + "\" is off: " + item2.Name + " couldn't be patched (" + reason2 + "). The game may have changed; the rest of the mod still works.")); break; } } } AddGuards(); return true; } private static HashSet<string> ReadDisabledFeatures(ConfigFile config) { HashSet<string> hashSet = new HashSet<string>(); if (Features.Count == 0) { return hashSet; } string text = string.Join(", ", Features.Keys); string[] array = config.Bind<string>("Debug", "DisabledFeatures", "", "For testing: features to turn off, separated by commas. Leave empty to play normally. Features: " + text + ".").Value.Split(new char[1] { ',' }); foreach (string text2 in array) { string name = text2.Trim(); if (name.Length != 0) { string text3 = Features.Keys.FirstOrDefault((string key) => string.Equals(key, name, StringComparison.OrdinalIgnoreCase)); if (text3 != null) { hashSet.Add(text3); continue; } _log.LogWarning((object)("DisabledFeatures: there is no feature called \"" + name + "\". Features: " + text + ".")); } } return hashSet; } private static bool TryPatch(Type type, out string reason) { try { List<MethodInfo> list = _harmony.CreateClassProcessor(type).Patch(); reason = ((list != null && list.Count > 0) ? FindMissingMember(type) : null); if (reason != null) { Unpatch(new List<Type>(1) { type }); return false; } return true; } catch (Exception exception) { reason = Describe(exception); return false; } } private static string FindMissingMember(Type type) { Stack<MethodBase> stack = new Stack<MethodBase>(); foreach (Type item3 in from t in AccessTools.GetTypesFromAssembly(OurAssembly) where Outermost(t) == type select t) { MethodInfo[] methods = item3.GetMethods(AccessTools.allDeclared); foreach (MethodBase item in methods) { stack.Push(item); } ConstructorInfo[] constructors = item3.GetConstructors(AccessTools.allDeclared); foreach (MethodBase item2 in constructors) { stack.Push(item2); } } HashSet<MethodBase> hashSet = new HashSet<MethodBase>(); while (stack.Count > 0) { MethodBase methodBase = stack.Pop(); if (!hashSet.Add(methodBase)) { continue; } if (!Callees.TryGetValue(methodBase, out var value)) { value = ReadCallees(methodBase, out var reason); if (reason != null) { return methodBase.DeclaringType?.Name + "." + methodBase.Name + " uses something the game no longer has (" + reason + ")"; } Callees[methodBase] = value; } foreach (MethodBase item4 in value) { stack.Push(item4); } } return null; } private static List<MethodBase> ReadCallees(MethodBase method, out string reason) { reason = null; List<MethodBase> list = new List<MethodBase>(); byte[] array = (method.IsAbstract ? null : method.GetMethodBody()?.GetILAsByteArray()); if (array == null) { return list; } Type declaringType = method.DeclaringType; Type[] genericTypeArguments = (((object)declaringType != null && declaringType.IsGenericType) ? declaringType.GetGenericArguments() : null); Type[] genericMethodArguments = (method.IsGenericMethod ? method.GetGenericArguments() : null); try { foreach (int item in MemberTokens(array)) { MemberInfo memberInfo = method.Module.ResolveMember(item, genericTypeArguments, genericMethodArguments); if (memberInfo is MethodBase methodBase && methodBase.DeclaringType?.Assembly == OurAssembly) { list.Add((methodBase is MethodInfo methodInfo && methodBase.IsGenericMethod) ? methodInfo.GetGenericMethodDefinition() : methodBase); } Type type = (memberInfo as Type) ?? memberInfo.DeclaringType; if (type?.Assembly == OurAssembly && type.TypeInitializer != null) { list.Add(type.TypeInitializer); } } return list; } catch (Exception exception) { reason = Describe(exception); return null; } } private static IEnumerable<int> MemberTokens(byte[] il) { int position = 0; while (position < il.Length) { short num = il[position++]; if (num == 254) { num = (short)(0xFE00 | il[position++]); } switch (OpCodesByValue[num].OperandType) { case OperandType.InlineField: case OperandType.InlineMethod: case OperandType.InlineTok: case OperandType.InlineType: yield return BitConverter.ToInt32(il, position); position += 4; break; case OperandType.ShortInlineBrTarget: case OperandType.ShortInlineI: case OperandType.ShortInlineVar: position++; break; case OperandType.InlineVar: position += 2; break; case OperandType.InlineI8: case OperandType.InlineR: position += 8; break; case OperandType.InlineSwitch: position += 4 + BitConverter.ToInt32(il, position) * 4; break; default: position += 4; break; case OperandType.InlineNone: break; } } } private static void Unpatch(List<Type> types) { foreach (MethodBase item in _harmony.GetPatchedMethods().ToList()) { foreach (MethodInfo item2 in OurPatches(item).ToList()) { if (types.Contains(Outermost(item2.DeclaringType))) { _harmony.Unpatch(item, item2); } } if (OurPatches(item).All((MethodInfo patch) => patch == GuardMethod)) { _harmony.Unpatch(item, GuardMethod); } } } private static IEnumerable<MethodInfo> OurPatches(MethodBase original) { Patches patchInfo = Harmony.GetPatchInfo(original); if (patchInfo != null) { return from patch in patchInfo.Prefixes.Concat(patchInfo.Postfixes).Concat(patchInfo.Transpilers).Concat(patchInfo.Finalizers) where patch.owner == _harmony.Id select patch.PatchMethod; } return Array.Empty<MethodInfo>(); } private static void AddGuards() { //IL_0030: Unknown result type (might be due to invalid IL or missing references) //IL_003b: Expected O, but got Unknown foreach (MethodBase item in _harmony.GetPatchedMethods().ToList()) { try { _harmony.Patch(item, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(GuardMethod), (HarmonyMethod)null); } catch (Exception exception) { _log.LogWarning((object)("Couldn't guard " + item.DeclaringType?.Name + "." + item.Name + " (" + Describe(exception) + "); a game update that breaks it will show up as errors instead.")); } } } private static Exception Guard(Exception __exception, MethodBase __originalMethod) { if (ModEnabled) { Exception ex = Innermost(__exception); if (ex is MissingMemberException || ex is TypeLoadException) { bool core; HashSet<string> hashSet = FindOwners(__exception, __originalMethod, out core); if (core) { TurnModOff(Describe(__exception)); return null; } if (hashSet.Count == 0) { return __exception; } foreach (string item in hashSet) { if (Off.Add(item)) { _log.LogError((object)("Feature \"" + item + "\" is off: " + Describe(__exception) + ". The game may have changed; the rest of the mod still works.")); List<Type> types = Features[item]; ThreadingHelper.Instance.StartSyncInvoke((Action)delegate { Unpatch(types); }); } } return null; } } return __exception; } private static HashSet<string> FindOwners(Exception exception, MethodBase original, out bool core) { HashSet<string> hashSet = new HashSet<string>(); core = false; bool flag = false; StackFrame[] array = new StackTrace(exception, fNeedFileInfo: false).GetFrames() ?? Array.Empty<StackFrame>(); for (int i = 0; i < array.Length; i++) { Type type = Outermost(array[i].GetMethod()?.DeclaringType); if (type == null || type.Assembly != OurAssembly) { continue; } flag = true; if (Owners.TryGetValue(type, out var value)) { core = value == null; if (!core) { hashSet.Add(value); } return hashSet; } } if (!flag) { return hashSet; } foreach (MethodInfo item in OurPatches(original)) { if (item != GuardMethod && Owners.TryGetValue(Outermost(item.DeclaringType), out var value2)) { if (value2 == null) { core = true; } else { hashSet.Add(value2); } } } return hashSet; } private static void TurnModOff(string reason) { bool modEnabled = ModEnabled; ModEnabled = false; _log.LogError((object)("The mod is off: " + reason + ". The game may have changed; wait for an update of this mod.")); if (modEnabled) { ThreadingHelper.Instance.StartSyncInvoke((Action)_harmony.UnpatchSelf); } else { _harmony.UnpatchSelf(); } } private static Type Outermost(Type type) { while (type?.DeclaringType != null) { type = type.DeclaringType; } return type; } private static Exception Innermost(Exception exception) { while (exception?.InnerException != null) { exception = exception.InnerException; } return exception; } private static string Describe(Exception exception) { exception = Innermost(exception); string text = exception.Message.Split(new char[1] { '\n' })[0].Trim(); return exception.GetType().Name + ": " + text; } } internal static class Translations { private const string TranslationResourcePrefix = "DvergrHeadlamp.Translations."; public static void Load() { CustomLocalization localization = LocalizationManager.Instance.GetLocalization(); Assembly executingAssembly = Assembly.GetExecutingAssembly(); string[] manifestResourceNames = executingAssembly.GetManifestResourceNames(); foreach (string text in manifestResourceNames) { if (text.StartsWith("DvergrHeadlamp.Translations.", StringComparison.Ordinal) && text.EndsWith(".json", StringComparison.Ordinal)) { string text2 = text.Substring("DvergrHeadlamp.Translations.".Length, text.Length - "DvergrHeadlamp.Translations.".Length - ".json".Length); using StreamReader streamReader = new StreamReader(executingAssembly.GetManifestResourceStream(text)); localization.AddJsonFile(text2, streamReader.ReadToEnd()); } } } } } namespace System.Runtime.CompilerServices { [AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)] internal sealed class IgnoresAccessChecksToAttribute : Attribute { internal IgnoresAccessChecksToAttribute(string assemblyName) { } } }