Decompiled source of Bitencola Hot Fixes v1.8.0

BitencolaHotFixes.dll

Decompiled a month ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.IO;
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.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using BitencolaHotFixes.Core;
using BitencolaHotFixes.Core.Cosmetics;
using BitencolaHotFixes.Features;
using BitencolaHotFixes.Features.Cosmetics;
using BitencolaHotFixes.Features.Hud;
using BitencolaHotFixes.Features.Remains;
using GameNetcodeStuff;
using HarmonyLib;
using LethalCompanyInputUtils.Api;
using LethalLib.Modules;
using Microsoft.CodeAnalysis;
using TMPro;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Utilities;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: IgnoresAccessChecksTo("Assembly-CSharp")]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("BitencolaHotFixes")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.0.0")]
[assembly: AssemblyInformationalVersion("1.0.0+10a938a95c59546f20ef27d6dbda009edd7b70ea")]
[assembly: AssemblyProduct("BitencolaHotFixes")]
[assembly: AssemblyTitle("BitencolaHotFixes")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("1.0.0.0")]
[module: UnverifiableCode]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Event | AttributeTargets.Parameter | AttributeTargets.ReturnValue | AttributeTargets.GenericParameter, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableAttribute : Attribute
	{
		public readonly byte[] NullableFlags;

		public NullableAttribute(byte P_0)
		{
			NullableFlags = new byte[1] { P_0 };
		}

		public NullableAttribute(byte[] P_0)
		{
			NullableFlags = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Method | AttributeTargets.Interface | AttributeTargets.Delegate, AllowMultiple = false, Inherited = false)]
	internal sealed class NullableContextAttribute : Attribute
	{
		public readonly byte Flag;

		public NullableContextAttribute(byte P_0)
		{
			Flag = P_0;
		}
	}
	[CompilerGenerated]
	[Embedded]
	[AttributeUsage(AttributeTargets.Module, AllowMultiple = false, Inherited = false)]
	internal sealed class RefSafetyRulesAttribute : Attribute
	{
		public readonly int Version;

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace BitencolaHotFixes
{
	[BepInPlugin("Bitencola.HotFixes", "Bitencola Hot Fixes", "1.8.0")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "Bitencola.HotFixes";

		public const string PluginName = "Bitencola Hot Fixes";

		public const string PluginVersion = "1.8.0";

		public static Plugin Instance { get; private set; } = null;

		public static ManualLogSource Log { get; private set; } = null;

		public static PluginConfig Cfg { get; private set; } = null;

		public static bool CosmeticsActive { get; private set; } = true;

		private void Awake()
		{
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_001e: Invalid comparison between Unknown and I4
			//IL_0057: Unknown result type (might be due to invalid IL or missing references)
			//IL_0137: Unknown result type (might be due to invalid IL or missing references)
			//IL_0141: Expected O, but got Unknown
			Instance = this;
			Log = ((BaseUnityPlugin)this).Logger;
			Cfg = new PluginConfig(((BaseUnityPlugin)this).Config, (int)Application.systemLanguage == 28);
			Log.LogInfo((object)$"Idioma dos textos do mod: {Cfg.Lang} (opção {Cfg.LanguageOption.Value}, Windows em {Application.systemLanguage})");
			CosmeticsActive = !Chainloader.PluginInfos.ContainsKey("Bitencola.Cosmetics");
			if (!CosmeticsActive)
			{
				Log.LogWarning((object)((Cfg.Lang == Language.English) ? "Bitencola Cosmetics is installed: the Hot Fixes cosmetics stay off and Bitencola Cosmetics keeps handling them. Uninstall Bitencola Cosmetics, which now comes inside Hot Fixes." : "O Bitencola Cosmetics está instalado: os cosméticos do Hot Fixes ficam desligados e o Bitencola Cosmetics continua cuidando deles. Desinstale o Bitencola Cosmetics, que agora vem dentro do Hot Fixes."));
			}
			try
			{
				RemainsItems.CreateAndRegister();
			}
			catch (Exception arg)
			{
				Log.LogError((object)$"Falha ao registrar os restos de monstro: {arg}");
			}
			try
			{
				KillCreditPatches.Register();
			}
			catch (Exception arg2)
			{
				Log.LogError((object)$"Falha ao ligar quem matou às caixas de restos: {arg2}");
			}
			if (CosmeticsActive)
			{
				try
				{
					JokeSuits.Register();
				}
				catch (Exception arg3)
				{
					Log.LogError((object)$"Falha ao registrar as roupas: {arg3}");
				}
			}
			try
			{
				SetUpInputs();
			}
			catch (Exception arg4)
			{
				Log.LogError((object)$"Falha ao criar as teclas do mod (1-4 e C ficam sem efeito): {arg4}");
			}
			PatchEachClass(new Harmony("Bitencola.HotFixes"));
			Log.LogInfo((object)"Bitencola Hot Fixes 1.8.0 carregado");
		}

		private static void PatchEachClass(Harmony harmony)
		{
			string text = typeof(JokeSuits).Namespace;
			Type[] typesFromAssembly = AccessTools.GetTypesFromAssembly(typeof(Plugin).Assembly);
			foreach (Type type in typesFromAssembly)
			{
				if (CosmeticsActive || !(type.Namespace == text))
				{
					try
					{
						harmony.CreateClassProcessor(type).Patch();
					}
					catch (Exception arg)
					{
						Log.LogError((object)$"Falha ao aplicar os patches de {type.Name}: {arg}");
					}
				}
			}
		}

		[MethodImpl(MethodImplOptions.NoInlining)]
		private static void SetUpInputs()
		{
			HotFixesInputs.Create();
			SlotHotkeys.Bind(HotFixesInputs.Instance);
			ScrapKey.Bind(HotFixesInputs.Instance);
		}
	}
	public class PluginConfig
	{
		private const string Absent = "\u0001";

		private readonly Dictionary<MonsterEntry, (ConfigEntry<int> min, ConfigEntry<int> max)> _valueRanges = new Dictionary<MonsterEntry, (ConfigEntry<int>, ConfigEntry<int>)>();

		private readonly Dictionary<ConfigKey, ConfigEntryBase> _entries = new Dictionary<ConfigKey, ConfigEntryBase>();

		public ConfigEntry<LanguageSetting> LanguageOption { get; private set; }

		public Language Lang { get; private set; }

		public ConfigEntry<bool> SlotHotkeysEnabled { get; private set; }

		public ConfigEntry<float> SlotSwitchCooldownSeconds { get; private set; }

		public ConfigEntry<bool> ShowSlotNumbers { get; private set; }

		public ConfigEntry<bool> SellAllAtCounterEnabled { get; private set; }

		public ConfigEntry<bool> DropScrapEnabled { get; private set; }

		public ConfigEntry<bool> MoveEmotesEnabled { get; private set; }

		public ConfigEntry<bool> ShowSlotValues { get; private set; }

		public ConfigEntry<bool> WeightInKilograms { get; private set; }

		public ConfigEntry<bool> KeyPromptsEnabled { get; private set; }

		public ConfigEntry<bool> ShowReais { get; private set; }

		public ConfigEntry<bool> ShowInventoryTotal { get; private set; }

		public ConfigEntry<bool> ShowCrosshair { get; private set; }

		public ConfigEntry<bool> RegenEnabled { get; private set; }

		public ConfigEntry<float> RegenDelaySeconds { get; private set; }

		public ConfigEntry<float> RegenSecondsPerPoint { get; private set; }

		public ConfigEntry<bool> ShowHealthNumbers { get; private set; }

		public ConfigEntry<bool> ShipHealEnabled { get; private set; }

		public ConfigEntry<bool> ShipRechargeEnabled { get; private set; }

		public ConfigEntry<float> ShipRechargeSecondsToFull { get; private set; }

		public ConfigEntry<bool> RemainsEnabled { get; private set; }

		public ConfigEntry<bool> ShowKillerEnabled { get; private set; }

		public ConfigEntry<bool> ShowRemainsNames { get; private set; }

		public ConfigEntry<bool> DeathNoticesEnabled { get; private set; }

		public ConfigEntry<bool> DailyScoreboardEnabled { get; private set; }

		public ConfigEntry<bool> BeltBagScrapEnabled { get; private set; }

		public ConfigEntry<int> BeltBagScrapLimit { get; private set; }

		public ConfigEntry<float> BeltBagScrapWeightPercent { get; private set; }

		public ConfigEntry<float> DayLengthMinutes { get; private set; }

		public ConfigEntry<bool> CosmeticPointsEnabled { get; private set; }

		public ConfigEntry<int> CosmeticPointsPercent { get; private set; }

		public PluginConfig(ConfigFile config, bool systemIsPortuguese)
		{
			ConfigFileState configFileState = ConfigFileState.Read(ReadFile(config.ConfigFilePath));
			bool saveOnConfigSet = config.SaveOnConfigSet;
			config.SaveOnConfigSet = false;
			try
			{
				BindAll(config, systemIsPortuguese, configFileState);
				CleanUpOldOptions(config, configFileState.UpgradingFromPortuguese);
				SaveSafely(config);
			}
			finally
			{
				config.SaveOnConfigSet = saveOnConfigSet;
			}
		}

		private void BindAll(ConfigFile config, bool systemIsPortuguese, ConfigFileState state)
		{
			LanguageOption = Add(config, ConfigKeys.Language, LanguageSetting.Auto, "Language of the mod's texts in the game and of these descriptions. Auto follows the computer's language: Portuguese for Portuguese, English for everything else. Takes effect the next time the game starts. / Idioma dos textos do mod no jogo e destas descrições. Auto segue o idioma do computador. Vale ao abrir o jogo de novo.");
			if (state.UpgradingFromPortuguese)
			{
				LanguageOption.Value = LanguageSetting.Portugues;
			}
			Lang = LanguageChoice.Resolve(LanguageOption.Value, systemIsPortuguese);
			SlotHotkeysEnabled = Add(config, ConfigKeys.SlotHotkeys, defaultValue: true, T("As teclas 1, 2, 3 e 4 selecionam os slots do inventário. Dá para remapear no menu de Controles do jogo.", "Keys 1, 2, 3 and 4 select the inventory slots. They can be rebound in the game's Controls menu."));
			SlotSwitchCooldownSeconds = Add(config, ConfigKeys.SlotSwitchInterval, 0.1f, T("Tempo mínimo entre duas trocas pelas teclas 1 a 4. Um aperto dentro desse tempo não se perde: a troca acontece assim que o tempo passa. A rolagem do mouse continua com o tempo do jogo (0,3 s).", "Minimum time between two switches with keys 1 to 4. A press inside this time is not lost: the switch happens as soon as the time is up. The mouse wheel keeps the game's own timing (0.3 s)."), (AcceptableValueBase?)(object)new AcceptableValueRange<float>(0.05f, 1f));
			ShowSlotNumbers = Add(config, ConfigKeys.ShowSlotNumbers, defaultValue: true, T("Mostra [1], [2], [3] e [4] em cima dos slots, como o [TAB] do slot extra. Se a tecla for trocada no menu de Controles, o texto acompanha.", "Shows [1], [2], [3] and [4] above the slots, like the [TAB] of the utility slot. If a key is rebound in the Controls menu, the text follows it."));
			SellAllAtCounterEnabled = Add(config, ConfigKeys.SellAllAtCounter, defaultValue: true, T("No balcão da Companhia, a tecla C põe a sucata no balcão, um item por vez, em vez de largar no chão. As ferramentas ficam com você.", "At the Company counter, the C key puts your scrap on the counter, one item at a time, instead of dropping it on the floor. Your tools stay with you."));
			DropScrapEnabled = Add(config, ConfigKeys.DropScrap, defaultValue: true, T("Uma tecla (C por padrão) larga no chão só a sucata dos slots normais, um item por vez. Ferramentas e o item do slot extra ficam com você. No balcão da Companhia, põe a sucata no balcão (opção \"Sell all at the counter\"). Dá para remapear no menu de Controles do jogo.", "A key (C by default) drops only the scrap in your normal slots, one item at a time. Tools and the utility slot item stay with you. At the Company counter it puts your scrap on the counter (option \"Sell all at the counter\"). It can be rebound in the game's Controls menu."));
			MoveEmotesEnabled = Add(config, ConfigKeys.MoveEmotes, defaultValue: true, T("Move os emotes do jogo (dançar e apontar) das teclas 1 e 2 para 5 e 6, liberando 1 a 4 para os slots.", "Moves the game's emotes (dance and point) from keys 1 and 2 to 5 and 6, freeing 1 to 4 for the slots."));
			ShowSlotValues = Add(config, ConfigKeys.ShowSlotValues, defaultValue: true, T("Mostra o valor de venda de cada sucata embaixo do slot em que ela está.", "Shows the sale value of each scrap item under its slot."));
			WeightInKilograms = Add(config, ConfigKeys.WeightInKilograms, defaultValue: true, T("Mostra o peso que você carrega em quilos (kg) em vez de libras (lb).", "Shows the weight you carry in kilograms (kg) instead of pounds (lb)."));
			ShowReais = Add(config, ConfigKeys.ShowReais, Lang == Language.Portuguese, T("Mostra os valores com R$ em vez de $: embaixo dos slots, no total do inventário, no scanner e no placar do dia. Só muda o símbolo, os números são os do jogo. Terminal, cota e créditos continuam com $.", "Shows values with R$ (Brazilian reais) instead of $: under the slots, in the inventory total, in the scanner and in the daily scoreboard. Only the symbol changes; the numbers are the game's own. The terminal, quota and credits keep $."));
			ShowInventoryTotal = Add(config, ConfigKeys.ShowInventoryTotal, defaultValue: true, T("Mostra ao lado dos slots o valor total da sucata que você carrega, contando a que está dentro da pochete.", "Shows next to the slots the total value of the scrap you carry, including the scrap inside your belt bag."));
			ShowCrosshair = Add(config, ConfigKeys.ShowCrosshair, defaultValue: true, T("Mostra um + no meio da tela. Ele some quando o jogo mostra a mãozinha de interagir, no terminal e nos menus.", "Shows a + in the middle of the screen. It hides when the game shows its interact hand, in the terminal and in menus."));
			KeyPromptsEnabled = Add(config, ConfigKeys.KeyPrompts, defaultValue: true, T("Os avisos do jogo (\"Grab : [E]\", portas, escadas, \"Drop : [G]\" e as dicas do item na mão) mostram a tecla escolhida no menu de Controles, em vez da tecla padrão escrita pelo jogo. Com controle, fica como o jogo já faz.", "The game's prompts (\"Grab : [E]\", doors, ladders, \"Drop : [G]\" and the held item tips) show the key you chose in the Controls menu instead of the default key the game writes. With a controller, prompts stay as the game shows them."));
			RegenEnabled = Add(config, ConfigKeys.Regen, defaultValue: true, T("Recupera vida aos poucos depois de levar dano, até 100. A regeneração nativa do jogo (abaixo de 20) continua igual.", "Slowly heals you after taking damage, up to 100. The game's own healing below 20 health is unchanged."));
			RegenDelaySeconds = Add(config, ConfigKeys.RegenDelay, 20f, T("Segundos sem levar dano antes de a cura gradual começar. Qualquer dano reinicia a contagem.", "Seconds without taking damage before gradual healing starts. Any damage restarts the wait."));
			RegenSecondsPerPoint = Add(config, ConfigKeys.RegenSecondsPerPoint, 3f, T("Quantos segundos leva para recuperar 1 ponto de vida durante a cura gradual.", "How many seconds it takes to heal 1 health point during gradual healing."));
			ShowHealthNumbers = Add(config, ConfigKeys.ShowHealthNumbers, defaultValue: true, T("Mostra sua vida em números (por exemplo 75/100) perto do ícone do jogador.", "Shows your health as numbers (for example 75/100) next to the player icon."));
			ShipHealEnabled = Add(config, ConfigKeys.ShipHeal, defaultValue: true, T("Ao entrar na nave, a vida volta a 100 na hora e o estado de gravemente ferido é removido.", "When you enter the ship, your health goes back to 100 at once and the critically injured state ends."));
			ShipRechargeEnabled = Add(config, ConfigKeys.ShipRecharge, defaultValue: true, T("Itens com bateria que você carrega recarregam sozinhos dentro da nave. Quem hospeda a partida também recarrega os itens soltos na nave.", "Battery items you carry recharge on their own inside the ship. The host also recharges the items lying in the ship."));
			ShipRechargeSecondsToFull = Add(config, ConfigKeys.ShipRechargeSeconds, 20f, T("Quantos segundos uma bateria vazia leva para chegar a 100% dentro da nave.", "How many seconds an empty battery takes to reach 100% inside the ship."), (AcceptableValueBase?)(object)new AcceptableValueRange<float>(1f, 300f));
			RemainsEnabled = Add(config, ConfigKeys.Remains, defaultValue: true, T("Monstros mortos viram um item carregável que pode ser vendido na Companhia como sucata.", "Dead monsters turn into a box you can carry and sell at the Company as scrap."));
			ShowKillerEnabled = Add(config, ConfigKeys.ShowKiller, defaultValue: true, T("O scanner da caixa de restos mostra quem matou o monstro: o último jogador que acertou um golpe nele. Monstros que nenhum jogador acertou (mortos por mina, torreta ou queda) não mostram ninguém.", "The scanner of a remains box shows who killed the monster: the last player who hit it. Monsters no player hit (killed by a mine, a turret or a fall) show no one."));
			ShowRemainsNames = Add(config, ConfigKeys.ShowRemainsNames, defaultValue: true, T("Escreve o nome do monstro nos quatro lados e no topo da caixa de restos. Monstros sem nome próprio (de outros mods) aparecem como \"Monstro\".", "Writes the monster's name on the four sides and the top of the remains box. Monsters without a name of their own (from other mods) show as \"Monster\"."));
			DeathNoticesEnabled = Add(config, ConfigKeys.DeathNotices, defaultValue: true, T("Mostra um aviso na tela com o nome e a causa da morte quando outro jogador morre.", "Shows a notice with the name and cause of death when another player dies."));
			DailyScoreboardEnabled = Add(config, ConfigKeys.DailyScoreboard, defaultValue: true, T("No fim do dia, quando a nave decola, mostra quantos monstros cada jogador matou e o valor dos restos.", "At the end of the day, when the ship takes off, shows how many monsters each player killed and the value of their remains."));
			BeltBagScrapEnabled = Add(config, ConfigKeys.BeltBagScrap, defaultValue: true, T("A pochete (belt bag) também guarda sucata de uma mão: mire na sucata e aperte Q com a pochete na mão. Sucata de duas mãos e caixas de restos de monstro não entram.", "The belt bag also holds one-handed scrap: aim at the scrap and press Q with the belt bag in your hand. Two-handed scrap and monster remains boxes don't fit."));
			BeltBagScrapLimit = Add(config, ConfigKeys.BeltBagScrapLimit, 5, T("Quantos dos 15 espaços da pochete podem ter sucata. Os outros continuam só para ferramentas.", "How many of the belt bag's 15 spaces can hold scrap. The rest stay for tools only."), (AcceptableValueBase?)(object)new AcceptableValueRange<int>(0, 15));
			BeltBagScrapWeightPercent = Add(config, ConfigKeys.BeltBagScrapWeight, 150f, T("Quanto pesa a sucata dentro da pochete para quem carrega a pochete, em porcentagem do peso normal. 150 = 50% a mais (um item de 20 lb pesa 30 lb). 0 = não pesa nada. Pochete no chão ou na nave não pesa para ninguém.", "How much the scrap inside the belt bag weighs for whoever carries the bag, as a percentage of its normal weight. 150 = 50% more (a 20 lb item weighs 30 lb). 0 = weightless. A belt bag on the floor or in the ship weighs nothing for anyone."), (AcceptableValueBase?)(object)new AcceptableValueRange<float>(0f, 500f));
			DayLengthMinutes = Add(config, ConfigKeys.DayLengthMinutes, 0f, T("Minutos de verdade do pouso até a nave ir embora sozinha, em qualquer lua. 0 = como no jogo. O relógio anda mais devagar ou mais rápido e o prazo da cota continua contando em dias. Só vale a opção de quem hospeda a partida: o relógio dos amigos acompanha sozinho. Uma mudança vale a partir do próximo pouso.", "Real minutes from landing until the ship leaves on its own, on any moon. 0 = as in the game. The clock runs slower or faster, and the quota deadline still counts in days. Only the host's setting counts: the other players' clocks follow it. A change takes effect from the next landing."), (AcceptableValueBase?)(object)new AcceptableValueRange<float>(0f, 120f));
			CosmeticPointsEnabled = Add(config, ConfigKeys.CosmeticPoints, defaultValue: true, T("Pontos de cosmético: vender sucata dá pontos, e as roupas e decorações da nave da loja custam pontos em vez de créditos. Vale a opção de quem hospeda: os amigos seguem.", "Cosmetic points: selling scrap gives points, and suits and ship decorations from the store cost points instead of credits. Only the host's setting counts: the other players follow it."));
			CosmeticPointsPercent = Add(config, ConfigKeys.PointsFromSales, 20, T("Porcentagem do dinheiro da venda de sucata que vira pontos de cosmético. Vale a de quem hospeda.", "Percentage of the scrap sale money that becomes cosmetic points. The host's value is used."), (AcceptableValueBase?)(object)new AcceptableValueRange<int>(0, 100));
			AcceptableValueRange<int> acceptable = new AcceptableValueRange<int>(1, 10000);
			foreach (MonsterEntry entry in MonsterCatalog.Entries)
			{
				string text = ((entry.Tier == MonsterTier.Other) ? "outros monstros" : entry.DisplayName);
				string text2 = ((entry.Tier == MonsterTier.Other) ? "other monsters" : entry.DisplayName);
				ConfigEntry<int> item = Add(config, ConfigKeys.MonsterMin(entry), entry.MinValue, T("Valor mínimo de venda dos restos de " + text + ".", "Minimum sale value of " + text2 + " remains."), (AcceptableValueBase?)(object)acceptable);
				ConfigEntry<int> item2 = Add(config, ConfigKeys.MonsterMax(entry), entry.MaxValue, T("Valor máximo de venda dos restos de " + text + ".", "Maximum sale value of " + text2 + " remains."), (AcceptableValueBase?)(object)acceptable);
				_valueRanges[entry] = (item, item2);
			}
		}

		public (int min, int max) GetValueRange(MonsterEntry entry)
		{
			var (val, val2) = _valueRanges[entry];
			return (min: val.Value, max: val2.Value);
		}

		private string T(string portuguese, string english)
		{
			if (Lang != Language.English)
			{
				return portuguese;
			}
			return english;
		}

		private ConfigEntry<TValue> Add<TValue>(ConfigFile config, ConfigKey key, TValue defaultValue, string description, AcceptableValueBase? acceptable = null)
		{
			//IL_000d: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0026: Expected O, but got Unknown
			//IL_0026: Expected O, but got Unknown
			ConfigEntry<TValue> val = config.Bind<TValue>(new ConfigDefinition(key.Section, key.Key), defaultValue, new ConfigDescription(description, acceptable, Array.Empty<object>()));
			_entries[key] = (ConfigEntryBase)(object)val;
			return val;
		}

		private void CleanUpOldOptions(ConfigFile config, bool moveValues)
		{
			Safely(ConfigKeys.LegacyRegenDelay, delegate
			{
				CarryCustom(config, ConfigKeys.LegacyRegenDelay, 5f, RegenDelaySeconds, moveValues);
			});
			Safely(ConfigKeys.LegacyRegenSecondsPerPoint, delegate
			{
				CarryCustom(config, ConfigKeys.LegacyRegenSecondsPerPoint, 1.5f, RegenSecondsPerPoint, moveValues);
			});
			foreach (KeyRename rename in ConfigKeys.Renames)
			{
				Safely(rename.From, delegate
				{
					Move(config, rename.From, _entries[rename.To], moveValues);
				});
			}
			foreach (KeyRename rename2 in ConfigKeys.EnglishRenames)
			{
				Safely(rename2.From, delegate
				{
					Move(config, rename2.From, _entries[rename2.To], moveValue: true);
				});
			}
			foreach (ConfigKey obsolete in ConfigKeys.Obsolete)
			{
				Safely(obsolete, delegate
				{
					TakeOld(config, obsolete);
				});
			}
		}

		private static void Safely(ConfigKey key, Action action)
		{
			try
			{
				action();
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao passar a opção antiga {key} para a nova: {arg}");
			}
		}

		private static void Move(ConfigFile config, ConfigKey from, ConfigEntryBase to, bool moveValue)
		{
			string text = TakeOld(config, from);
			if (text != null && moveValue)
			{
				to.SetSerializedValue(text);
			}
		}

		private static void CarryCustom(ConfigFile config, ConfigKey from, float oldDefault, ConfigEntry<float> to, bool moveValue)
		{
			string text = TakeOld(config, from);
			if (text != null && moveValue)
			{
				float result;
				float? num = (float.TryParse(text, NumberStyles.Float, CultureInfo.InvariantCulture, out result) ? ConfigMigration.CustomValue(result, oldDefault) : ((float?)null));
				if (num.HasValue)
				{
					to.Value = num.Value;
				}
			}
		}

		private static void SaveSafely(ConfigFile config)
		{
			try
			{
				config.Save();
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao gravar o arquivo de config (as opções valem nesta partida): {arg}");
			}
		}

		private static string ReadFile(string path)
		{
			try
			{
				return File.Exists(path) ? File.ReadAllText(path) : "";
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao ler o arquivo de config antes de abrir: {arg}");
				return "";
			}
		}

		private static string? TakeOld(ConfigFile config, ConfigKey key)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			ConfigDefinition val = new ConfigDefinition(key.Section, key.Key);
			string value = config.Bind<string>(val, "\u0001", (ConfigDescription)null).Value;
			config.Remove(val);
			if (!(value == "\u0001"))
			{
				return value;
			}
			return null;
		}
	}
}
namespace BitencolaHotFixes.Features
{
	[HarmonyPatch]
	internal static class BeltBagScrap
	{
		private const float ReachDistance = 4f;

		private const int GrabbableLayerMask = 1073742144;

		private const int ManeaterBabyItemId = 123984;

		private const int OtherBlockedItemId = 819501;

		private const float WeightEpsilon = 0.0001f;

		private static readonly Predicate<GrabbableObject> IsDestroyed = (GrabbableObject item) => (Object)(object)item == (Object)null;

		private static readonly Func<GrabbableObject, IReadOnlyList<GrabbableObject?>?> ContentsOfBag = ContentsOf;

		private static readonly Func<GrabbableObject, bool> IsScrapItem = IsScrap;

		private static readonly List<GrabbableObject> CarriedScrap = new List<GrabbableObject>();

		private static readonly HashSet<GrabbableObject> VisitedBags = new HashSet<GrabbableObject>();

		private static readonly List<float> ScrapWeights = new List<float>();

		private static PlayerControllerB? _weightedPlayer;

		private static float _appliedExtra;

		internal static void PruneDestroyed(BeltBagItem bag)
		{
			if ((Object)(object)bag != (Object)null && bag.objectsInBag != null)
			{
				bag.objectsInBag.RemoveAll(IsDestroyed);
			}
		}

		private static void PruneUnlessOpenLocally(BeltBagItem bag)
		{
			GameNetworkManager instance = GameNetworkManager.Instance;
			if (!((Object)(object)bag.currentPlayerChecking != (Object)null) || !((Object)(object)instance != (Object)null) || !((Object)(object)bag.currentPlayerChecking == (Object)(object)instance.localPlayerController))
			{
				PruneDestroyed(bag);
			}
		}

		[HarmonyPatch(typeof(BeltBagItem), "OnDisable")]
		[HarmonyPrefix]
		private static void BeforeBagDisabled(BeltBagItem __instance)
		{
			try
			{
				PruneDestroyed(__instance);
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao limpar a pochete antes de ela sumir: {arg}");
			}
		}

		[HarmonyPatch(typeof(BeltBagInventoryUI), "FillSlots")]
		[HarmonyPrefix]
		private static void BeforeFillSlots(BeltBagItem beltBag)
		{
			try
			{
				PruneDestroyed(beltBag);
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao limpar a pochete antes de mostrar o menu: {arg}");
			}
		}

		[HarmonyPatch(typeof(BeltBagItem), "ItemInteractLeftRight")]
		[HarmonyPrefix]
		private static void BeforeItemInteractLeftRight(BeltBagItem __instance)
		{
			try
			{
				PruneUnlessOpenLocally(__instance);
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao limpar a pochete: {arg}");
			}
		}

		[HarmonyPatch(typeof(BeltBagItem), "ItemInteractLeftRight")]
		[HarmonyPostfix]
		private static void AfterItemInteractLeftRight(BeltBagItem __instance, bool right)
		{
			//IL_0060: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (right || __instance.tryingAddToBag || !Plugin.Cfg.BeltBagScrapEnabled.Value)
				{
					return;
				}
				PlayerControllerB playerHeldBy = ((GrabbableObject)__instance).playerHeldBy;
				GameNetworkManager instance = GameNetworkManager.Instance;
				if ((Object)(object)playerHeldBy == (Object)null || (Object)(object)instance == (Object)null || (Object)(object)playerHeldBy != (Object)(object)instance.localPlayerController)
				{
					return;
				}
				Transform transform = ((Component)playerHeldBy.gameplayCamera).transform;
				RaycastHit val = default(RaycastHit);
				if (!Physics.Raycast(transform.position, transform.forward, ref val, 4f, 1073742144, (QueryTriggerInteraction)1))
				{
					return;
				}
				GrabbableObject component = ((Component)((RaycastHit)(ref val)).collider).gameObject.GetComponent<GrabbableObject>();
				if (!((Object)(object)component == (Object)null) && !((Object)(object)component == (Object)(object)__instance) && IsLooseScrap(component))
				{
					PruneUnlessOpenLocally(__instance);
					if (BeltBagRules.CanAddScrap(CountScrap(__instance), __instance.objectsInBag.Count, Plugin.Cfg.BeltBagScrapLimit.Value, component.itemProperties.twoHanded))
					{
						__instance.TryAddObjectToBag(component);
					}
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao guardar sucata na pochete: {arg}");
			}
		}

		[HarmonyPatch(typeof(BeltBagItem), "TryAddObjectToBag")]
		[HarmonyPrefix]
		private static bool BeforeTryAddObjectToBag(BeltBagItem __instance, GrabbableObject gObject)
		{
			try
			{
				BeltBagItem val = (BeltBagItem)(object)((gObject is BeltBagItem) ? gObject : null);
				if ((Object)(object)val == (Object)null || !Plugin.Cfg.BeltBagScrapEnabled.Value)
				{
					return true;
				}
				PruneUnlessOpenLocally(__instance);
				return BeltBagRules.CanAddBag(CountScrap(__instance), CountScrap(val), Plugin.Cfg.BeltBagScrapLimit.Value);
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao conferir a sucata da pochete: {arg}");
				return true;
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		[HarmonyPostfix]
		private static void AfterPlayerUpdate(PlayerControllerB __instance)
		{
			try
			{
				GameNetworkManager instance = GameNetworkManager.Instance;
				if ((Object)(object)instance == (Object)null || (Object)(object)__instance != (Object)(object)instance.localPlayerController)
				{
					return;
				}
				if (_weightedPlayer != __instance)
				{
					_weightedPlayer = __instance;
					_appliedExtra = 0f;
				}
				if (__instance.isPlayerDead)
				{
					_appliedExtra = 0f;
				}
				else
				{
					if (!__instance.isPlayerControlled)
					{
						return;
					}
					float num = (Plugin.Cfg.BeltBagScrapEnabled.Value ? ExpectedExtra(__instance) : 0f);
					float num2 = num - _appliedExtra;
					if (!(Math.Abs(num2) < 0.0001f))
					{
						__instance.carryWeight = Math.Max(1f, __instance.carryWeight + num2);
						_appliedExtra = num;
						if ((Object)(object)HUDManager.Instance != (Object)null)
						{
							HUDManager.Instance.UpdateWeightCounter();
						}
					}
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao atualizar o peso da sucata na pochete: {arg}");
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "DropAllHeldItems")]
		[HarmonyPostfix]
		private static void AfterDropAllHeldItems(PlayerControllerB __instance)
		{
			try
			{
				GameNetworkManager instance = GameNetworkManager.Instance;
				if ((Object)(object)instance != (Object)null && (Object)(object)__instance == (Object)(object)instance.localPlayerController)
				{
					_weightedPlayer = __instance;
					_appliedExtra = 0f;
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao zerar o peso da sucata na pochete: {arg}");
			}
		}

		private static bool IsLooseScrap(GrabbableObject item)
		{
			Item itemProperties = item.itemProperties;
			if ((Object)(object)itemProperties != (Object)null && itemProperties.isScrap && item.grabbable && !item.deactivated && !item.isHeld && !item.isHeldByEnemy && itemProperties.itemId != 123984 && itemProperties.itemId != 819501)
			{
				return !IsTrackedByMonster(item);
			}
			return false;
		}

		private static bool IsTrackedByMonster(GrabbableObject item)
		{
			if (item is KiwiBabyItem)
			{
				return true;
			}
			List<HoarderBugItem> hoarderBugItems = HoarderBugAI.HoarderBugItems;
			if (hoarderBugItems != null)
			{
				foreach (HoarderBugItem item2 in hoarderBugItems)
				{
					if (item2 != null && (Object)(object)item2.itemGrabbableObject == (Object)(object)item)
					{
						return true;
					}
				}
			}
			RedLocustBees[] array = Object.FindObjectsOfType<RedLocustBees>();
			foreach (RedLocustBees val in array)
			{
				if ((Object)(object)val != (Object)null && (Object)(object)val.hive == (Object)(object)item)
				{
					return true;
				}
			}
			return false;
		}

		private static int CountScrap(BeltBagItem bag)
		{
			return BeltBagRules.CountScrap((GrabbableObject)(object)bag, ContentsOfBag, IsScrapItem);
		}

		private static float ExpectedExtra(PlayerControllerB player)
		{
			CarriedScrap.Clear();
			VisitedBags.Clear();
			if (player.ItemSlots != null)
			{
				GrabbableObject[] itemSlots = player.ItemSlots;
				foreach (GrabbableObject val in itemSlots)
				{
					if ((Object)(object)val != (Object)null)
					{
						BeltBagRules.CollectScrap(val, ContentsOfBag, IsScrapItem, CarriedScrap, VisitedBags);
					}
				}
			}
			if ((Object)(object)player.ItemOnlySlot != (Object)null)
			{
				BeltBagRules.CollectScrap(player.ItemOnlySlot, ContentsOfBag, IsScrapItem, CarriedScrap, VisitedBags);
			}
			ScrapWeights.Clear();
			foreach (GrabbableObject item in CarriedScrap)
			{
				ScrapWeights.Add(item.itemProperties.weight);
			}
			CarriedScrap.Clear();
			VisitedBags.Clear();
			return BeltBagRules.ExtraCarryWeight(ScrapWeights, Plugin.Cfg.BeltBagScrapWeightPercent.Value);
		}

		private static IReadOnlyList<GrabbableObject?>? ContentsOf(GrabbableObject item)
		{
			BeltBagItem val = (BeltBagItem)(object)((item is BeltBagItem) ? item : null);
			if ((Object)(object)val == (Object)null || val.objectsInBag == null)
			{
				return null;
			}
			PruneUnlessOpenLocally(val);
			return val.objectsInBag;
		}

		private static bool IsScrap(GrabbableObject item)
		{
			if ((Object)(object)item != (Object)null && (Object)(object)item.itemProperties != (Object)null)
			{
				return item.itemProperties.isScrap;
			}
			return false;
		}
	}
	[HarmonyPatch]
	internal static class DayLengthPatches
	{
		private static readonly HostRateEstimator HostRate = new HostRateEstimator();

		private static bool _dayRunning;

		private static bool _hostSpeedApplied;

		private static float? _measuredHostSpeed;

		private static bool _speedChanged;

		[HarmonyPatch(typeof(TimeOfDay), "Update")]
		[HarmonyPostfix]
		private static void AfterUpdate(TimeOfDay __instance)
		{
			try
			{
				if ((Object)(object)GameNetworkManager.Instance == (Object)null || (Object)(object)GameNetworkManager.Instance.localPlayerController == (Object)null)
				{
					return;
				}
				if (!__instance.currentDayTimeStarted)
				{
					if (_dayRunning)
					{
						EndDay(__instance);
					}
				}
				else if (__instance.timeHasStarted)
				{
					if (!_dayRunning)
					{
						_dayRunning = true;
						_hostSpeedApplied = false;
					}
					bool leavingEarly = DayLength.LeavingEarly(__instance.shipLeaveAutomaticallyTime);
					if (((NetworkBehaviour)__instance).IsServer)
					{
						UpdateHost(__instance, leavingEarly);
					}
					else
					{
						UpdateClient(__instance, leavingEarly);
					}
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao ajustar a duração do dia: {arg}");
			}
		}

		[HarmonyPatch(typeof(TimeOfDay), "SyncTimeClientRpc")]
		[HarmonyPostfix]
		private static void AfterSyncTime(TimeOfDay __instance, float time)
		{
			try
			{
				if (!((NetworkBehaviour)__instance).IsServer)
				{
					float? num = HostRate.AddSync(time, Time.realtimeSinceStartup);
					if (num.HasValue)
					{
						_measuredHostSpeed = num.Value;
					}
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao acompanhar o relógio do anfitrião: {arg}");
			}
		}

		private static void UpdateHost(TimeOfDay time, bool leavingEarly)
		{
			if (!_hostSpeedApplied)
			{
				_hostSpeedApplied = true;
				ApplyHostSpeed(time);
			}
			if (leavingEarly && _speedChanged)
			{
				time.globalTimeSpeedMultiplier = 1f;
				_speedChanged = false;
				Plugin.Log.LogInfo((object)"Votação para sair mais cedo: o relógio volta à velocidade normal");
			}
		}

		private static void UpdateClient(TimeOfDay time, bool leavingEarly)
		{
			float num = DayLength.ClientSpeed(_measuredHostSpeed, leavingEarly);
			if (num != 1f || _speedChanged)
			{
				time.globalTimeSpeedMultiplier = num;
				_speedChanged = num != 1f;
			}
			float num2 = DayLength.CapToNextSync(time.globalTime, HostRate.LastHostTime);
			if (num2 < time.globalTime)
			{
				time.timeUntilDeadline += time.globalTime - num2;
				time.globalTime = num2;
			}
		}

		private static void ApplyHostSpeed(TimeOfDay time)
		{
			float value = Plugin.Cfg.DayLengthMinutes.Value;
			float num = time.globalTimeAtEndOfDay - time.globalTime;
			if (!(value > 0f))
			{
				if (_speedChanged)
				{
					time.globalTimeSpeedMultiplier = 1f;
					_speedChanged = false;
				}
			}
			else
			{
				float num2 = (time.globalTimeSpeedMultiplier = DayLength.HostSpeed(num, value));
				_speedChanged = true;
				float num3 = num / num2 / 60f;
				Plugin.Log.LogInfo((object)$"Duração do dia: {num3:0.#} min (no jogo seriam {DayLength.GameMinutes(num):0.#} min); velocidade do relógio {num2:0.###}");
			}
		}

		private static void EndDay(TimeOfDay time)
		{
			_dayRunning = false;
			_hostSpeedApplied = false;
			_measuredHostSpeed = null;
			HostRate.Reset();
			if (_speedChanged)
			{
				time.globalTimeSpeedMultiplier = 1f;
				_speedChanged = false;
			}
		}
	}
	[HarmonyPatch(typeof(HUDManager), "Update")]
	internal static class DeathNotices
	{
		private static readonly DeathWatcher Watcher = new DeathWatcher();

		private static readonly List<PlayerLife> Lives = new List<PlayerLife>();

		private static StartOfRound? _lastRound;

		private const string TipSource = "morte";

		private static readonly List<(string name, string cause)> Recent = new List<(string, string)>();

		[HarmonyPostfix]
		private static void UpdatePostfix()
		{
			//IL_0170: Unknown result type (might be due to invalid IL or missing references)
			//IL_0184: Expected I4, but got Unknown
			try
			{
				if (!Plugin.Cfg.DeathNoticesEnabled.Value)
				{
					return;
				}
				StartOfRound instance = StartOfRound.Instance;
				if ((Object)(object)instance == (Object)null || instance.allPlayerScripts == null)
				{
					return;
				}
				if (instance != _lastRound)
				{
					_lastRound = instance;
					Recent.Clear();
					Watcher.Reset();
				}
				Lives.Clear();
				PlayerControllerB[] allPlayerScripts = instance.allPlayerScripts;
				foreach (PlayerControllerB val in allPlayerScripts)
				{
					if (!((Object)(object)val == (Object)null))
					{
						Lives.Add(new PlayerLife((int)val.playerClientId, val.isPlayerControlled || val.isPlayerDead, val.isPlayerDead));
					}
				}
				IReadOnlyList<int> readOnlyList = Watcher.Update(Lives);
				if (readOnlyList.Count == 0)
				{
					return;
				}
				PlayerControllerB val2 = (((Object)(object)GameNetworkManager.Instance != (Object)null) ? GameNetworkManager.Instance.localPlayerController : null);
				if (!TipQueue.IsQueuedOrOnScreen("morte"))
				{
					Recent.Clear();
				}
				bool flag = false;
				for (int j = 0; j < readOnlyList.Count; j++)
				{
					PlayerControllerB val3 = null;
					for (int k = 0; k < allPlayerScripts.Length; k++)
					{
						if ((Object)(object)allPlayerScripts[k] != (Object)null && (int)allPlayerScripts[k].playerClientId == readOnlyList[j])
						{
							val3 = allPlayerScripts[k];
							break;
						}
					}
					if (!((Object)(object)val3 == (Object)null) && !((Object)(object)val3 == (Object)(object)val2))
					{
						Recent.Add((val3.playerUsername, DeathCauseText.For((int)val3.causeOfDeath, Plugin.Cfg.Lang)));
						flag = true;
					}
				}
				if (flag)
				{
					var (header, body) = DeathNoticeText.Build(Recent, Plugin.Cfg.Lang);
					TipQueue.Show("morte", header, body);
				}
			}
			catch (Exception ex)
			{
				Plugin.Log.LogError((object)("DeathNotices: " + ex));
			}
		}
	}
	[HarmonyPatch]
	internal static class EmoteRebindPatches
	{
		private static readonly string[] EmoteActions = new string[2] { "Emote1", "Emote2" };

		[HarmonyPostfix]
		[HarmonyPatch(typeof(IngamePlayerSettings), "LoadSettingsFromPrefs")]
		private static void AfterLoadSettings()
		{
			ApplyEmoteRemap();
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(IngamePlayerSettings), "DiscardChangedSettings")]
		private static void AfterDiscardChanges(IngamePlayerSettings __instance)
		{
			RefreshKeybindMenuIfChanged(__instance);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(IngamePlayerSettings), "ResetAllKeybinds")]
		private static void AfterResetKeybinds(IngamePlayerSettings __instance)
		{
			RefreshKeybindMenuIfChanged(__instance);
		}

		private static void RefreshKeybindMenuIfChanged(IngamePlayerSettings settings)
		{
			if (!ApplyEmoteRemap())
			{
				return;
			}
			try
			{
				settings.UpdateAllKeybindOptions();
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao atualizar o menu de Controles: {arg}");
			}
		}

		private static bool ApplyEmoteRemap()
		{
			//IL_0094: Unknown result type (might be due to invalid IL or missing references)
			//IL_0099: Unknown result type (might be due to invalid IL or missing references)
			//IL_0059: Unknown result type (might be due to invalid IL or missing references)
			//IL_005e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			try
			{
				if (!Plugin.Cfg.MoveEmotesEnabled.Value)
				{
					return false;
				}
				InputActionAsset actions = InputSystem.actions;
				if ((Object)(object)actions == (Object)null)
				{
					return false;
				}
				bool result = false;
				string[] emoteActions = EmoteActions;
				foreach (string text in emoteActions)
				{
					InputAction val = actions.FindAction(text, false);
					if (val == null)
					{
						continue;
					}
					for (int j = 0; j < val.bindings.Count; j++)
					{
						InputBinding val2 = val.bindings[j];
						string text2 = EmoteRemap.NewPath(text, ((InputBinding)(ref val2)).effectivePath);
						if (text2 != null)
						{
							InputActionRebindingExtensions.ApplyBindingOverride(val, j, text2);
							result = true;
						}
					}
				}
				return result;
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao mover os emotes para 5 e 6: {arg}");
				return false;
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "Update")]
	internal static class HealthPatches
	{
		private const int MaxHealth = 100;

		private const int VanillaFloor = 20;

		private const float MinDelaySeconds = 0f;

		private const float MinSecondsPerPoint = 0.1f;

		private static readonly ShipEntryTracker Ship = new ShipEntryTracker();

		private static RegenTracker? _regen;

		private static float _regenDelay;

		private static float _regenSecondsPerPoint;

		[HarmonyPostfix]
		private static void UpdatePostfix(PlayerControllerB __instance)
		{
			GameNetworkManager instance = GameNetworkManager.Instance;
			if ((Object)(object)instance == (Object)null || (Object)(object)__instance != (Object)(object)instance.localPlayerController)
			{
				return;
			}
			if (__instance.isPlayerDead)
			{
				_regen?.Reset();
				Ship.Update(__instance.isInHangarShipRoom, isAlive: false);
			}
			else if (__instance.isPlayerControlled)
			{
				PluginConfig cfg = Plugin.Cfg;
				if (Ship.Update(__instance.isInHangarShipRoom, isAlive: true) && cfg.ShipHealEnabled.Value)
				{
					HealToFullInShip(__instance);
				}
				if (cfg.RegenEnabled.Value)
				{
					RegenerateGradually(__instance, cfg);
				}
				else
				{
					_regen?.Reset();
				}
			}
		}

		private static void HealToFullInShip(PlayerControllerB player)
		{
			if (player.health < 100 || player.criticallyInjured)
			{
				player.health = 100;
				if (player.criticallyInjured)
				{
					player.MakeCriticallyInjured(false);
				}
				HUDManager.Instance.UpdateHealthUI(100, false);
				Plugin.Log.LogInfo((object)"Cura na nave");
			}
		}

		private static void RegenerateGradually(PlayerControllerB player, PluginConfig cfg)
		{
			int num = EnsureRegenMatchesConfig(cfg).Tick(player.health, Time.deltaTime);
			if (num > 0)
			{
				player.health += num;
				HUDManager.Instance.UpdateHealthUI(player.health, false);
				if (player.health >= 20 && player.criticallyInjured)
				{
					player.MakeCriticallyInjured(false);
				}
			}
		}

		private static RegenTracker EnsureRegenMatchesConfig(PluginConfig cfg)
		{
			float num = Mathf.Max(cfg.RegenDelaySeconds.Value, 0f);
			float num2 = Mathf.Max(cfg.RegenSecondsPerPoint.Value, 0.1f);
			if (_regen == null || num != _regenDelay || num2 != _regenSecondsPerPoint)
			{
				_regenDelay = num;
				_regenSecondsPerPoint = num2;
				_regen = new RegenTracker(num, num2);
			}
			return _regen;
		}
	}
	public class HotFixesInputs : LcInputActions
	{
		public static HotFixesInputs Instance { get; private set; }

		[InputAction("<Keyboard>/1", Name = "Slot 1")]
		public InputAction Slot1 { get; set; }

		[InputAction("<Keyboard>/2", Name = "Slot 2")]
		public InputAction Slot2 { get; set; }

		[InputAction("<Keyboard>/3", Name = "Slot 3")]
		public InputAction Slot3 { get; set; }

		[InputAction("<Keyboard>/4", Name = "Slot 4")]
		public InputAction Slot4 { get; set; }

		[InputAction("<Keyboard>/c", Name = "Drop scrap")]
		public InputAction DropAll { get; set; }

		public static void Create()
		{
			Instance = new HotFixesInputs();
		}
	}
	internal enum UnloadMode
	{
		DropOnFloor,
		PlaceOnCounter
	}
	internal static class InventoryUnloader
	{
		private const int UtilitySlot = 50;

		private const int CounterObjectLimit = 150;

		private const float SettleAfterSwitchSeconds = 0.15f;

		private const float PauseBetweenItemsSeconds = 0.15f;

		private const float StepTimeoutSeconds = 1f;

		private const float StaleAfterSeconds = 3f;

		private static int _lastSequenceId;

		private static int _runningId;

		private static PlayerControllerB? _runningOn;

		private static float _heartbeat;

		private static DepositItemsDesk? _counter;

		private static bool _counterSearched;

		private static int _counterScenesKey;

		public static bool IsRunning
		{
			get
			{
				if (_runningId != 0 && (Object)(object)_runningOn != (Object)null)
				{
					return Time.time - _heartbeat < 3f;
				}
				return false;
			}
		}

		public static void Start(PlayerControllerB player, UnloadMode mode)
		{
			if (IsRunning || (Object)(object)player == (Object)null || !((Behaviour)player).isActiveAndEnabled)
			{
				return;
			}
			int currentItemSlot = player.currentItemSlot;
			IReadOnlyList<int> readOnlyList = ScrapSelection.UnloadOrder(ClassifySlots(player), currentItemSlot);
			if (readOnlyList.Count == 0)
			{
				return;
			}
			DepositItemsDesk desk = null;
			if (mode == UnloadMode.PlaceOnCounter && !TryGetCounterInReach(player, out desk))
			{
				return;
			}
			int id = (_runningId = ++_lastSequenceId);
			_runningOn = player;
			_heartbeat = Time.time;
			try
			{
				((MonoBehaviour)player).StartCoroutine(Guarded(id, Run(player, mode, desk, readOnlyList, currentItemSlot)));
			}
			catch
			{
				Release(id);
				throw;
			}
		}

		public static bool HasScrapToUnload(PlayerControllerB player)
		{
			return ScrapSelection.SlotsToUnload(ClassifySlots(player)).Count > 0;
		}

		public static bool TryGetCounterInReach(PlayerControllerB player, [NotNullWhen(true)] out DepositItemsDesk? desk)
		{
			desk = FindCounter();
			if ((Object)(object)desk != (Object)null)
			{
				return InReach(desk, player);
			}
			return false;
		}

		public static bool InBuildMode()
		{
			ShipBuildModeManager instance = ShipBuildModeManager.Instance;
			if ((Object)(object)instance != (Object)null)
			{
				return instance.InBuildMode;
			}
			return false;
		}

		private static IEnumerator Guarded(int id, IEnumerator steps)
		{
			try
			{
				while (true)
				{
					object current;
					try
					{
						if (_runningId != id)
						{
							break;
						}
						_heartbeat = Time.time;
						if (!steps.MoveNext())
						{
							break;
						}
						current = steps.Current;
					}
					catch (Exception arg)
					{
						Plugin.Log.LogError((object)$"Falha ao tirar a sucata dos slots; a sequência parou: {arg}");
						break;
					}
					yield return current;
				}
			}
			finally
			{
				Release(id);
			}
		}

		private static IEnumerator Run(PlayerControllerB player, UnloadMode mode, DepositItemsDesk? desk, IReadOnlyList<int> order, int savedSlot)
		{
			bool canRestoreSlot = true;
			foreach (int slot in order)
			{
				if (!CanStartStep(player, mode, desk, out string reason))
				{
					Stopped(reason);
					break;
				}
				if (player.currentItemSlot != slot)
				{
					if (player.twoHanded)
					{
						Stopped("item de duas mãos na mão");
						break;
					}
					SlotSwitcher.SwitchNow(player, slot);
				}
				float deadline = Time.time + 1f;
				while (!SettledAfterSwitch(player) && Time.time < deadline && IsLocalPlayer(player))
				{
					yield return null;
				}
				if (mode == UnloadMode.DropOnFloor)
				{
					yield return (object)new WaitForEndOfFrame();
				}
				if (!CanActNow(player, mode, desk, out reason))
				{
					Stopped(reason);
					break;
				}
				if (HoldsScrapFrom(player, slot))
				{
					if (mode == UnloadMode.PlaceOnCounter)
					{
						desk.PlaceItemOnCounter(player);
					}
					else
					{
						player.DiscardHeldObject(false, (NetworkObject)null, default(Vector3), true);
					}
					deadline = Time.time + 1f;
					while (player.throwingObject && Time.time < deadline && IsLocalPlayer(player))
					{
						yield return null;
					}
					if (player.throwingObject)
					{
						canRestoreSlot = false;
						Plugin.Log.LogWarning((object)"O jogo não confirmou a tempo que o item foi largado; a sequência parou.");
						break;
					}
				}
				yield return (object)new WaitForSeconds(0.15f);
			}
			if (canRestoreSlot)
			{
				RestoreSlot(player, savedSlot);
			}
		}

		private static bool CanStartStep(PlayerControllerB player, UnloadMode mode, DepositItemsDesk? desk, out string reason)
		{
			if (!LocalPlayerInput.TryGet(out PlayerControllerB player2, out PlayerInputState state) || (Object)(object)player2 != (Object)(object)player)
			{
				reason = "o jogador não é mais o jogador local";
				return false;
			}
			if (!InputGate.CanUnloadScrap(in state, InBuildMode()))
			{
				reason = "o jogador está ocupado ou não pode agir";
				return false;
			}
			return CounterStillAccepts(player, mode, desk, out reason);
		}

		private static bool CanActNow(PlayerControllerB player, UnloadMode mode, DepositItemsDesk? desk, out string reason)
		{
			if (!LocalPlayerInput.TryGet(out PlayerControllerB player2, out PlayerInputState state) || (Object)(object)player2 != (Object)(object)player)
			{
				reason = "o jogador não é mais o jogador local";
				return false;
			}
			if (!state.CanAct || state.Busy || InBuildMode() || !SettledAfterSwitch(player))
			{
				reason = "o jogador está ocupado ou não pode agir";
				return false;
			}
			return CounterStillAccepts(player, mode, desk, out reason);
		}

		private static bool CounterStillAccepts(PlayerControllerB player, UnloadMode mode, DepositItemsDesk? desk, out string reason)
		{
			reason = "";
			if (mode != UnloadMode.PlaceOnCounter)
			{
				return true;
			}
			if ((Object)(object)desk == (Object)null || !InReach(desk, player))
			{
				reason = "o balcão saiu do alcance";
				return false;
			}
			if (desk.inGrabbingObjectsAnimation || ObjectsOnCounter(desk) >= 150)
			{
				reason = "o balcão não está aceitando itens agora";
				return false;
			}
			return true;
		}

		private static void RestoreSlot(PlayerControllerB player, int savedSlot)
		{
			if (player.currentItemSlot != savedSlot && (savedSlot == 50 || (savedSlot >= 0 && savedSlot < player.ItemSlots.Length)) && LocalPlayerInput.TryGet(out PlayerControllerB player2, out PlayerInputState state) && !((Object)(object)player2 != (Object)(object)player) && state.CanAct && !state.Busy && !state.TwoHanded && !InBuildMode())
			{
				SlotSwitcher.SwitchNow(player, savedSlot);
			}
		}

		private static bool SettledAfterSwitch(PlayerControllerB player)
		{
			if (!player.isGrabbingObjectAnimation)
			{
				return player.timeSinceSwitchingSlots >= 0.15f;
			}
			return false;
		}

		private static bool IsLocalPlayer(PlayerControllerB player)
		{
			GameNetworkManager instance = GameNetworkManager.Instance;
			if ((Object)(object)player != (Object)null && (Object)(object)instance != (Object)null && (Object)(object)instance.localPlayerController == (Object)(object)player)
			{
				return !player.isPlayerDead;
			}
			return false;
		}

		private static bool HoldsScrapFrom(PlayerControllerB player, int slot)
		{
			if (slot < 0 || slot >= player.ItemSlots.Length || player.currentItemSlot != slot || !player.isHoldingObject)
			{
				return false;
			}
			GrabbableObject currentlyHeldObjectServer = player.currentlyHeldObjectServer;
			if ((Object)(object)currentlyHeldObjectServer != (Object)null && (Object)(object)player.ItemSlots[slot] == (Object)(object)currentlyHeldObjectServer)
			{
				return Classify(currentlyHeldObjectServer) == SlotItemKind.Scrap;
			}
			return false;
		}

		private static SlotItemKind[] ClassifySlots(PlayerControllerB player)
		{
			GrabbableObject[] itemSlots = player.ItemSlots;
			SlotItemKind[] array = new SlotItemKind[itemSlots.Length];
			for (int i = 0; i < itemSlots.Length; i++)
			{
				array[i] = Classify(itemSlots[i]);
			}
			return array;
		}

		private static SlotItemKind Classify(GrabbableObject? item)
		{
			if ((Object)(object)item == (Object)null)
			{
				return SlotItemKind.Empty;
			}
			if (!((Object)(object)item.itemProperties != (Object)null) || !item.itemProperties.isScrap)
			{
				return SlotItemKind.Tool;
			}
			return SlotItemKind.Scrap;
		}

		private static DepositItemsDesk? FindCounter()
		{
			int num = LoadedScenesKey();
			bool flag = _counter != null && (Object)(object)_counter == (Object)null;
			if (!_counterSearched || num != _counterScenesKey || flag)
			{
				_counter = Object.FindObjectOfType<DepositItemsDesk>();
				_counterScenesKey = num;
				_counterSearched = true;
			}
			if (!((Object)(object)_counter != (Object)null))
			{
				return null;
			}
			return _counter;
		}

		private static int LoadedScenesKey()
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0011: Unknown result type (might be due to invalid IL or missing references)
			int num = 17;
			for (int i = 0; i < SceneManager.sceneCount; i++)
			{
				int num2 = num * 31;
				Scene sceneAt = SceneManager.GetSceneAt(i);
				num = num2 + ((Scene)(ref sceneAt)).handle;
			}
			return num;
		}

		private static bool InReach(DepositItemsDesk desk, PlayerControllerB player)
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_0030: Unknown result type (might be due to invalid IL or missing references)
			if ((Object)(object)desk.triggerCollider != (Object)null && (Object)(object)player.localItemHolder != (Object)null)
			{
				Bounds bounds = ((Collider)desk.triggerCollider).bounds;
				return ((Bounds)(ref bounds)).Contains(player.localItemHolder.position);
			}
			return false;
		}

		private static int ObjectsOnCounter(DepositItemsDesk desk)
		{
			if (!((Object)(object)desk.deskObjectsContainer != (Object)null))
			{
				return int.MaxValue;
			}
			return ((Component)desk.deskObjectsContainer).GetComponentsInChildren<GrabbableObject>().Length;
		}

		private static void Stopped(string reason)
		{
			Plugin.Log.LogInfo((object)("Tirar a sucata dos slots parou no meio: " + reason + "."));
		}

		private static void Release(int id)
		{
			if (_runningId == id)
			{
				_runningId = 0;
				_runningOn = null;
			}
		}
	}
	[HarmonyPatch]
	internal static class KeyPrompts
	{
		private sealed class KeySet
		{
			public Dictionary<string, string> Cursor { get; }

			public Dictionary<string, string> ItemTips { get; }

			public KeySet(Dictionary<string, string> cursor, Dictionary<string, string> itemTips)
			{
				Cursor = cursor;
				ItemTips = itemTips;
			}
		}

		private static KeySet? _keys;

		private static bool _listeningToBindings;

		private static bool _loggedHoverError;

		[HarmonyPatch(typeof(PlayerControllerB), "SetHoverTipAndCurrentInteractTrigger")]
		[HarmonyPostfix]
		private static void AfterHoverTip(PlayerControllerB __instance)
		{
			try
			{
				if (Active() && !((Object)(object)__instance.cursorTip == (Object)null))
				{
					string text = ((TMP_Text)__instance.cursorTip).text;
					string text2 = KeyPromptText.RewriteCursorTip(text, LoadKeys().Cursor);
					if ((object)text2 != text)
					{
						((TMP_Text)__instance.cursorTip).text = text2;
					}
				}
			}
			catch (Exception arg)
			{
				if (!_loggedHoverError)
				{
					_loggedHoverError = true;
					Plugin.Log.LogError((object)$"Falha ao corrigir a tecla do aviso: {arg}");
				}
			}
		}

		[HarmonyPatch(typeof(HUDManager), "ChangeControlTip")]
		[HarmonyPostfix]
		private static void AfterChangeControlTip(HUDManager __instance, int toolTipNumber)
		{
			try
			{
				if (Active())
				{
					RewriteTipLines(__instance, toolTipNumber, toolTipNumber + 1);
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao corrigir a tecla da dica do item: {arg}");
			}
		}

		[HarmonyPatch(typeof(HUDManager), "ForceChangeText")]
		[HarmonyPrefix]
		private static void BeforeForceChangeText(ref string changeTextTo)
		{
			try
			{
				if (Active())
				{
					changeTextTo = KeyPromptText.Rewrite(changeTextTo, LoadKeys().ItemTips);
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao corrigir a tecla da dica do item: {arg}");
			}
		}

		[HarmonyPatch(typeof(HUDManager), "ChangeControlTipMultiple")]
		[HarmonyPostfix]
		private static void AfterChangeControlTipMultiple(HUDManager __instance, string[] allLines, bool holdingItem)
		{
			try
			{
				if (Active())
				{
					int to = (holdingItem ? 1 : 0) + ((allLines != null) ? allLines.Length : 0);
					RewriteTipLines(__instance, 0, to);
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao corrigir as teclas das dicas do item: {arg}");
			}
		}

		[HarmonyPatch(typeof(HUDManager), "SetUtilitySlotKeyText")]
		[HarmonyPostfix]
		private static void AfterSettingsApplied()
		{
			try
			{
				ForgetKeys();
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao atualizar as teclas dos avisos: {arg}");
			}
		}

		private static void RewriteTipLines(HUDManager hud, int from, int to)
		{
			TextMeshProUGUI[] controlTipLines = hud.controlTipLines;
			if (controlTipLines == null)
			{
				return;
			}
			Dictionary<string, string> itemTips = LoadKeys().ItemTips;
			for (int i = Math.Max(0, from); i < Math.Min(to, controlTipLines.Length); i++)
			{
				TextMeshProUGUI val = controlTipLines[i];
				if (!((Object)(object)val == (Object)null))
				{
					string text = ((TMP_Text)val).text;
					string text2 = KeyPromptText.Rewrite(text, itemTips);
					if ((object)text2 != text)
					{
						((TMP_Text)val).text = text2;
					}
				}
			}
		}

		private static bool Active()
		{
			StartOfRound instance = StartOfRound.Instance;
			if (Plugin.Cfg.KeyPromptsEnabled.Value)
			{
				if ((Object)(object)instance != (Object)null)
				{
					return !instance.localPlayerUsingController;
				}
				return true;
			}
			return false;
		}

		private static KeySet LoadKeys()
		{
			ListenToBindingsOnce();
			KeySet keySet = _keys;
			if (keySet == null)
			{
				keySet = (_keys = new KeySet(KeyPromptText.KeysByToken(KeyPromptText.CursorActions, KeyFor), KeyPromptText.KeysByToken(KeyPromptText.ItemTipActions, KeyFor)));
			}
			return keySet;
		}

		private static void ForgetKeys()
		{
			_keys = null;
		}

		private static void ListenToBindingsOnce()
		{
			if (_listeningToBindings)
			{
				return;
			}
			_listeningToBindings = true;
			InputSystem.onActionChange += delegate(object _, InputActionChange change)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				//IL_0002: Invalid comparison between Unknown and I4
				try
				{
					if ((int)change == 8)
					{
						ForgetKeys();
					}
				}
				catch (Exception arg)
				{
					Plugin.Log.LogError((object)$"Falha ao atualizar as teclas dos avisos: {arg}");
				}
			};
		}

		private static string? KeyFor(string actionName)
		{
			//IL_001a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0027: Unknown result type (might be due to invalid IL or missing references)
			//IL_002c: Unknown result type (might be due to invalid IL or missing references)
			InputActionAsset actions = InputSystem.actions;
			InputAction val = ((actions != null) ? actions.FindAction(actionName, false) : null);
			if (val == null)
			{
				return null;
			}
			ReadOnlyArray<InputBinding> bindings = val.bindings;
			for (int i = 0; i < bindings.Count; i++)
			{
				InputBinding val2 = bindings[i];
				if (!((InputBinding)(ref val2)).isComposite && !((InputBinding)(ref val2)).isPartOfComposite)
				{
					string effectivePath = ((InputBinding)(ref val2)).effectivePath;
					if (effectivePath != null && (effectivePath.StartsWith("<Keyboard>", StringComparison.OrdinalIgnoreCase) || effectivePath.StartsWith("<Mouse>", StringComparison.OrdinalIgnoreCase)))
					{
						return KeyPromptText.KeyName(InputActionRebindingExtensions.GetBindingDisplayString(val, i, (DisplayStringOptions)0));
					}
				}
			}
			return null;
		}
	}
	internal static class LocalPlayerInput
	{
		private const int JetpackItemId = 13;

		public static bool TryGet(out PlayerControllerB player, out PlayerInputState state)
		{
			GameNetworkManager instance = GameNetworkManager.Instance;
			player = (((Object)(object)instance != (Object)null) ? instance.localPlayerController : null);
			if ((Object)(object)player == (Object)null)
			{
				state = default(PlayerInputState);
				return false;
			}
			state = new PlayerInputState(CanAct(player), IsBusy(player), player.twoHanded, player.timeSinceSwitchingSlots, player.currentItemSlot, player.ItemSlots.Length);
			return true;
		}

		private static bool CanAct(PlayerControllerB p)
		{
			if (((NetworkBehaviour)p).IsOwner && p.isPlayerControlled && !p.isPlayerDead)
			{
				if (((NetworkBehaviour)p).IsServer)
				{
					return p.isHostPlayerObject;
				}
				return true;
			}
			return false;
		}

		private static bool IsBusy(PlayerControllerB p)
		{
			if (!p.inTerminalMenu && !p.isTypingChat && (!((Object)(object)p.quickMenuManager != (Object)null) || !p.quickMenuManager.isMenuOpen) && !p.inSpecialMenu && !p.isGrabbingObjectAnimation && !p.inSpecialInteractAnimation && !p.throwingObject && !p.activatingItem)
			{
				return IsUsingJetpack(p);
			}
			return true;
		}

		private static bool IsUsingJetpack(PlayerControllerB p)
		{
			GrabbableObject currentlyHeldObjectServer = p.currentlyHeldObjectServer;
			if ((p.jetpackControls || p.disablingJetpackControls) && (Object)(object)currentlyHeldObjectServer != (Object)null)
			{
				return currentlyHeldObjectServer.itemProperties.itemId == 13;
			}
			return false;
		}
	}
	internal static class ScrapKey
	{
		public static void Bind(HotFixesInputs inputs)
		{
			inputs.DropAll.performed += OnPressed;
		}

		private static void OnPressed(CallbackContext context)
		{
			try
			{
				if (((CallbackContext)(ref context)).performed && Plugin.Cfg.DropScrapEnabled.Value && !InventoryUnloader.IsRunning && LocalPlayerInput.TryGet(out PlayerControllerB player, out PlayerInputState state) && InputGate.CanUnloadScrap(in state, InventoryUnloader.InBuildMode()))
				{
					if (Plugin.Cfg.SellAllAtCounterEnabled.Value && InventoryUnloader.HasScrapToUnload(player) && InventoryUnloader.TryGetCounterInReach(player, out DepositItemsDesk _))
					{
						InventoryUnloader.Start(player, UnloadMode.PlaceOnCounter);
					}
					else
					{
						InventoryUnloader.Start(player, UnloadMode.DropOnFloor);
					}
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao largar a sucata: {arg}");
			}
		}
	}
	[HarmonyPatch(typeof(PlayerControllerB), "Update")]
	internal static class ShipRecharge
	{
		private sealed class Entry
		{
			public float LastSyncAt;

			public float LastSeenAt;
		}

		private const float FloorScanInterval = 1f;

		private const float PruneInterval = 10f;

		private const float StaleAfterSeconds = 5f;

		private static readonly Dictionary<int, Entry> Entries = new Dictionary<int, Entry>();

		private static readonly List<int> ToRemove = new List<int>();

		private static float _lastFloorScan;

		private static float _lastPrune;

		[HarmonyPostfix]
		private static void UpdatePostfix(PlayerControllerB __instance)
		{
			try
			{
				GameNetworkManager instance = GameNetworkManager.Instance;
				if ((Object)(object)instance == (Object)null || (Object)(object)__instance != (Object)(object)instance.localPlayerController)
				{
					return;
				}
				PluginConfig cfg = Plugin.Cfg;
				if (!cfg.ShipRechargeEnabled.Value)
				{
					return;
				}
				float value = cfg.ShipRechargeSecondsToFull.Value;
				float time = Time.time;
				if (!__instance.isPlayerDead && __instance.isPlayerControlled && __instance.isInHangarShipRoom)
				{
					float deltaTime = Time.deltaTime;
					GrabbableObject[] itemSlots = __instance.ItemSlots;
					for (int i = 0; i < itemSlots.Length; i++)
					{
						RechargeCarried(itemSlots[i], deltaTime, value, time);
					}
					RechargeCarried(__instance.ItemOnlySlot, deltaTime, value, time);
				}
				NetworkManager singleton = NetworkManager.Singleton;
				if ((Object)(object)singleton != (Object)null && singleton.IsServer && time - _lastFloorScan >= 1f)
				{
					float val = time - _lastFloorScan;
					_lastFloorScan = time;
					RechargeFloorItems(Math.Min(val, 5f), value, time);
				}
				if (time - _lastPrune >= 10f)
				{
					_lastPrune = time;
					Prune(time);
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha na recarga de baterias: {arg}");
			}
		}

		private static void RechargeCarried(GrabbableObject? item, float dt, float secondsToFull, float now)
		{
			if (!((Object)(object)item == (Object)null) && CanRecharge(item))
			{
				Step(item, dt, secondsToFull, now, ((NetworkBehaviour)item).IsOwner, isServerRpc: true);
			}
		}

		private static void RechargeFloorItems(float dt, float secondsToFull, float now)
		{
			GrabbableObject[] array = Object.FindObjectsOfType<GrabbableObject>();
			foreach (GrabbableObject val in array)
			{
				if (!((Object)(object)val == (Object)null) && !val.isHeld && val.isInShipRoom && CanRecharge(val))
				{
					Step(val, dt, secondsToFull, now, canSend: true, isServerRpc: false);
				}
			}
		}

		private static bool CanRecharge(GrabbableObject item)
		{
			Item itemProperties = item.itemProperties;
			Battery insertedBattery = item.insertedBattery;
			if ((Object)(object)itemProperties != (Object)null && itemProperties.requiresBattery && insertedBattery != null && insertedBattery.charge < 1f)
			{
				return !item.isBeingUsed;
			}
			return false;
		}

		private static void Step(GrabbableObject item, float dt, float secondsToFull, float now, bool canSend, bool isServerRpc)
		{
			int instanceID = ((Object)item).GetInstanceID();
			if (!Entries.TryGetValue(instanceID, out Entry value))
			{
				value = new Entry
				{
					LastSyncAt = now - 1f
				};
				Entries[instanceID] = value;
			}
			value.LastSeenAt = now;
			Battery insertedBattery = item.insertedBattery;
			float num = (insertedBattery.charge = BatteryRecharge.Next(insertedBattery.charge, dt, secondsToFull));
			if (num > 0f)
			{
				insertedBattery.empty = false;
			}
			bool flag = num >= 1f;
			if (canSend && SyncThrottle.ShouldSync(now, value.LastSyncAt, flag))
			{
				value.LastSyncAt = now;
				int num2 = Mathf.Clamp(Mathf.RoundToInt(num * 100f), 0, 100);
				if (isServerRpc)
				{
					item.SyncBatteryServerRpc(num2);
				}
				else
				{
					item.SyncBatteryClientRpc(num2);
				}
			}
			if (flag)
			{
				Entries.Remove(instanceID);
			}
		}

		private static void Prune(float now)
		{
			ToRemove.Clear();
			foreach (KeyValuePair<int, Entry> entry in Entries)
			{
				if (now - entry.Value.LastSeenAt > 5f)
				{
					ToRemove.Add(entry.Key);
				}
			}
			foreach (int item in ToRemove)
			{
				Entries.Remove(item);
			}
		}
	}
	internal static class SlotHotkeys
	{
		public static void Bind(HotFixesInputs inputs)
		{
			inputs.Slot1.performed += delegate(CallbackContext context)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				OnSlotPressed(context, 0);
			};
			inputs.Slot2.performed += delegate(CallbackContext context)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				OnSlotPressed(context, 1);
			};
			inputs.Slot3.performed += delegate(CallbackContext context)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				OnSlotPressed(context, 2);
			};
			inputs.Slot4.performed += delegate(CallbackContext context)
			{
				//IL_0000: Unknown result type (might be due to invalid IL or missing references)
				OnSlotPressed(context, 3);
			};
		}

		private static void OnSlotPressed(CallbackContext context, int slot)
		{
			if (((CallbackContext)(ref context)).performed && Plugin.Cfg.SlotHotkeysEnabled.Value)
			{
				SlotSwitcher.Request(slot);
			}
		}
	}
	[HarmonyPatch]
	internal static class SlotKeyLabels
	{
		private const string LabelName = "BitencolaSlotKey";

		private static bool _listeningToConfig;

		private static bool _lastUsingController;

		[HarmonyPatch(typeof(HUDManager), "SetUtilitySlotKeyText")]
		[HarmonyPostfix]
		private static void AfterUtilityKeyText(HUDManager __instance)
		{
			try
			{
				ListenToConfigOnce();
				Refresh(__instance);
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao mostrar os números dos slots: {arg}");
			}
		}

		[HarmonyPatch(typeof(HUDManager), "Update")]
		[HarmonyPostfix]
		private static void AfterHudUpdate(HUDManager __instance)
		{
			try
			{
				if (UsingController() != _lastUsingController)
				{
					Refresh(__instance);
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao atualizar os números dos slots: {arg}");
			}
		}

		private static void ListenToConfigOnce()
		{
			if (!_listeningToConfig)
			{
				_listeningToConfig = true;
				Plugin.Cfg.ShowSlotNumbers.SettingChanged += delegate
				{
					RefreshCurrentHud();
				};
				Plugin.Cfg.SlotHotkeysEnabled.SettingChanged += delegate
				{
					RefreshCurrentHud();
				};
			}
		}

		private static void RefreshCurrentHud()
		{
			try
			{
				if ((Object)(object)HUDManager.Instance != (Object)null)
				{
					Refresh(HUDManager.Instance);
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao atualizar os números dos slots: {arg}");
			}
		}

		private static bool UsingController()
		{
			if ((Object)(object)StartOfRound.Instance != (Object)null)
			{
				return StartOfRound.Instance.localPlayerUsingController;
			}
			return false;
		}

		private static void Refresh(HUDManager hud)
		{
			//IL_003d: 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_0052: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00bc: Unknown result type (might be due to invalid IL or missing references)
			//IL_00be: Unknown result type (might be due to invalid IL or missing references)
			bool usingController = (_lastUsingController = UsingController());
			TextMeshProUGUI utilitySlotKeyText = hud.utilitySlotKeyText;
			Image itemOnlySlotIconFrame = hud.itemOnlySlotIconFrame;
			Image[] itemSlotIconFrames = hud.itemSlotIconFrames;
			if ((Object)(object)utilitySlotKeyText == (Object)null || (Object)(object)itemOnlySlotIconFrame == (Object)null || itemSlotIconFrames == null)
			{
				return;
			}
			Vector3 val = ((Transform)((TMP_Text)utilitySlotKeyText).rectTransform).position - ((Transform)((Graphic)itemOnlySlotIconFrame).rectTransform).position;
			for (int i = 0; i < itemSlotIconFrames.Length; i++)
			{
				Image val2 = itemSlotIconFrames[i];
				if ((Object)(object)val2 == (Object)null)
				{
					continue;
				}
				if (i >= 4)
				{
					Transform val3 = ((Transform)((Graphic)val2).rectTransform).Find("BitencolaSlotKey");
					if ((Object)(object)val3 != (Object)null)
					{
						((Component)val3).gameObject.SetActive(false);
					}
					continue;
				}
				TextMeshProUGUI val4 = HudLabels.FindOrCloneTabLabel(hud, (Transform)(object)((Graphic)val2).rectTransform, "BitencolaSlotKey", ((Transform)((Graphic)val2).rectTransform).position + val);
				if (!((Object)(object)val4 == (Object)null))
				{
					((TMP_Text)val4).text = SlotKeyLabel.Format(BindingDisplay(i), i);
					((Component)val4).gameObject.SetActive(SlotKeyLabel.IsVisible(i, Plugin.Cfg.ShowSlotNumbers.Value, Plugin.Cfg.SlotHotkeysEnabled.Value, usingController));
				}
			}
		}

		private static string? BindingDisplay(int slot)
		{
			try
			{
				return SlotKeyBindings.Display(slot);
			}
			catch (Exception)
			{
				return null;
			}
		}
	}
	internal static class SlotKeyBindings
	{
		private const string UnboundMarker = "Not-Bound";

		[MethodImpl(MethodImplOptions.NoInlining)]
		public static string? Display(int slot)
		{
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0054: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Unknown result type (might be due to invalid IL or missing references)
			//IL_0066: Unknown result type (might be due to invalid IL or missing references)
			//IL_006a: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			HotFixesInputs instance = HotFixesInputs.Instance;
			if (instance == null)
			{
				return null;
			}
			InputAction val = (InputAction)(slot switch
			{
				0 => instance.Slot1, 
				1 => instance.Slot2, 
				2 => instance.Slot3, 
				3 => instance.Slot4, 
				_ => null, 
			});
			if (val == null || val.bindings.Count == 0)
			{
				return null;
			}
			InputBinding val2 = val.bindings[0];
			if (((InputBinding)(ref val2)).effectivePath.Contains("Not-Bound"))
			{
				return "-";
			}
			return InputActionRebindingExtensions.GetBindingDisplayString(val, 0, (DisplayStringOptions)0);
		}
	}
	[HarmonyPatch]
	internal static class SlotSwitcher
	{
		private const float GrabSoundVolume = 0.6f;

		private const float MinCooldownSeconds = 0.05f;

		private static readonly PendingSlotRequest Pending = new PendingSlotRequest();

		public static void Request(int slot)
		{
			if (!LocalPlayerInput.TryGet(out PlayerControllerB player, out PlayerInputState state))
			{
				Pending.Clear();
				return;
			}
			switch (InputGate.DecideSwitch(in state, slot, Cooldown()))
			{
			case SwitchDecision.Switch:
				Pending.Clear();
				SwitchNow(player, slot);
				break;
			case SwitchDecision.Wait:
				Pending.Set(slot, Time.time);
				break;
			default:
				Pending.Clear();
				break;
			}
		}

		[HarmonyPatch(typeof(PlayerControllerB), "Update")]
		[HarmonyPostfix]
		private static void ApplyPendingRequest(PlayerControllerB __instance)
		{
			try
			{
				float num = Cooldown();
				if (Pending.TryGet(Time.time, PendingSlotRequest.MaxAgeFor(num), out var slot) && LocalPlayerInput.TryGet(out PlayerControllerB player, out PlayerInputState state) && !((Object)(object)__instance != (Object)(object)player))
				{
					switch (InputGate.DecideSwitch(in state, slot, num))
					{
					case SwitchDecision.Switch:
						Pending.Clear();
						SwitchNow(player, slot);
						break;
					case SwitchDecision.Ignore:
						Pending.Clear();
						break;
					}
				}
			}
			catch (Exception arg)
			{
				Pending.Clear();
				Plugin.Log.LogError((object)$"Falha ao aplicar a troca de slot guardada: {arg}");
			}
		}

		private static float Cooldown()
		{
			return Mathf.Max(Plugin.Cfg.SlotSwitchCooldownSeconds.Value, 0.05f);
		}

		internal static void SwitchNow(PlayerControllerB player, int slot)
		{
			if ((Object)(object)ShipBuildModeManager.Instance != (Object)null)
			{
				ShipBuildModeManager.Instance.CancelBuildMode(true);
			}
			player.playerBodyAnimator.SetBool("GrabValidated", false);
			player.SwitchToItemSlot(slot, (GrabbableObject)null);
			player.SwitchToSlotServerRpc(slot);
			GrabbableObject currentlyHeldObjectServer = player.currentlyHeldObjectServer;
			if ((Object)(object)currentlyHeldObjectServer != (Object)null)
			{
				AudioSource component = ((Component)currentlyHeldObjectServer).GetComponent<AudioSource>();
				AudioClip grabSFX = currentlyHeldObjectServer.itemProperties.grabSFX;
				if ((Object)(object)component != (Object)null && (Object)(object)grabSFX != (Object)null)
				{
					component.PlayOneShot(grabSFX, 0.6f);
				}
			}
			player.timeSinceSwitchingSlots = 0f;
		}
	}
}
namespace BitencolaHotFixes.Features.Remains
{
	[HarmonyPatch(typeof(GrabbableObject), "Start")]
	internal static class CorpseHider
	{
		private static readonly Dictionary<int, EnemyAI> Hidden = new Dictionary<int, EnemyAI>();

		private static readonly List<int> Destroyed = new List<int>();

		private static readonly List<EnemyAI> Enemies = new List<EnemyAI>();

		private static readonly List<CorpseCandidate> Candidates = new List<CorpseCandidate>();

		internal static event Action<GrabbableObject, EnemyAI>? CorpseMatched;

		[HarmonyPostfix]
		private static void StartPostfix(GrabbableObject __instance)
		{
			//IL_0015: Unknown result type (might be due to invalid IL or missing references)
			EnemyAI val = null;
			try
			{
				if (RemainsItems.IsRemains(__instance.itemProperties))
				{
					val = HideNearestCorpse(((Component)__instance).transform.position);
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao esconder o corpo do monstro: {arg}");
			}
			if ((Object)(object)val == (Object)null)
			{
				return;
			}
			try
			{
				CorpseHider.CorpseMatched?.Invoke(__instance, val);
			}
			catch (Exception arg2)
			{
				Plugin.Log.LogError((object)$"Falha ao avisar qual corpo a caixa de restos escondeu: {arg2}");
			}
		}

		private static EnemyAI? HideNearestCorpse(Vector3 box)
		{
			//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_0048: Unknown result type (might be due to invalid IL or missing references)
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0056: Unknown result type (might be due to invalid IL or missing references)
			//IL_008e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0094: 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)
			ForgetDestroyed();
			Enemies.Clear();
			Candidates.Clear();
			EnemyAI[] array = Object.FindObjectsByType<EnemyAI>((FindObjectsSortMode)0);
			foreach (EnemyAI val in array)
			{
				Vector3 position = ((Component)val).transform.position;
				Enemies.Add(val);
				Candidates.Add(new CorpseCandidate(position.x, position.y, position.z, val.isEnemyDead, Hidden.ContainsKey(((Object)val).GetInstanceID())));
			}
			int num = CorpsePicker.PickNearest(Candidates, box.x, box.y, box.z);
			EnemyAI val2 = ((num >= 0) ? Enemies[num] : null);
			Enemies.Clear();
			if ((Object)(object)val2 == (Object)null)
			{
				Plugin.Log.LogDebug((object)"Restos sem corpo por perto para esconder.");
				return null;
			}
			Hidden[((Object)val2).GetInstanceID()] = val2;
			Hide(val2);
			Plugin.Log.LogInfo((object)("Corpo escondido: " + (((Object)(object)val2.enemyType != (Object)null) ? val2.enemyType.enemyName : ((Object)val2).name)));
			return val2;
		}

		private static void Hide(EnemyAI enemy)
		{
			enemy.overrideSettingEnemyMeshes = true;
			Renderer[] componentsInChildren = ((Component)enemy).GetComponentsInChildren<Renderer>(true);
			foreach (Renderer val in componentsInChildren)
			{
				if (BelongsToEnemy((Component)(object)val))
				{
					val.enabled = false;
				}
			}
			Collider[] componentsInChildren2 = ((Component)enemy).GetComponentsInChildren<Collider>(true);
			foreach (Collider val2 in componentsInChildren2)
			{
				if (BelongsToEnemy((Component)(object)val2))
				{
					val2.enabled = false;
				}
			}
		}

		private static bool BelongsToEnemy(Component component)
		{
			if ((Object)(object)component.GetComponentInParent<GrabbableObject>(true) == (Object)null && (Object)(object)component.GetComponentInParent<PlayerControllerB>(true) == (Object)null)
			{
				return (Object)(object)component.GetComponentInParent<DeadBodyInfo>(true) == (Object)null;
			}
			return false;
		}

		private static void ForgetDestroyed()
		{
			Destroyed.Clear();
			foreach (KeyValuePair<int, EnemyAI> item in Hidden)
			{
				if ((Object)(object)item.Value == (Object)null)
				{
					Destroyed.Add(item.Key);
				}
			}
			foreach (int item2 in Destroyed)
			{
				Hidden.Remove(item2);
			}
		}
	}
	[HarmonyPatch]
	internal static class EnemyDeathPatch
	{
		[HarmonyPostfix]
		[HarmonyPatch(typeof(EnemyAI), "KillEnemy")]
		private static void KillEnemyPostfix(EnemyAI __instance, bool destroy)
		{
			RemainsSpawner.OnEnemyKilled(__instance, destroy);
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(RoundManager), "UnloadSceneObjectsEarly")]
		private static void UnloadSceneObjectsEarlyPostfix()
		{
			RemainsSpawner.OnRoundEnded();
		}
	}
	[HarmonyPatch]
	internal static class KillCreditPatches
	{
		internal static readonly KillCredits Credits = new KillCredits();

		internal static readonly DailyScoreboard Scoreboard = new DailyScoreboard();

		private static readonly Dictionary<int, string> KillerByBox = new Dictionary<int, string>();

		private static readonly Dictionary<int, int> ValueByBox = new Dictionary<int, int>();

		public static void Register()
		{
			CorpseHider.CorpseMatched += OnCorpseMatched;
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(EnemyAI), "HitEnemy")]
		private static void HitEnemyPostfix(EnemyAI __instance, PlayerControllerB? playerWhoHit)
		{
			try
			{
				if (!((Object)(object)playerWhoHit == (Object)null))
				{
					bool isEnemyDead = __instance.isEnemyDead;
					bool lateHitAllowed = isEnemyDead && KillCredits.IsLateHitAllowed(((NetworkBehaviour)__instance).IsOwner, ((NetworkBehaviour)playerWhoHit).OwnerClientId, ((NetworkBehaviour)__instance).OwnerClientId);
					Credits.RecordHit(((Object)__instance).GetInstanceID(), playerWhoHit.playerUsername, isEnemyDead, lateHitAllowed, Time.realtimeSinceStartup);
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao registrar o golpe no monstro: {arg}");
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(EnemyAI), "KillEnemy")]
		private static void KillEnemyPostfix(EnemyAI __instance)
		{
			try
			{
				if (__instance.isEnemyDead)
				{
					Credits.MarkDead(((Object)__instance).GetInstanceID(), Time.realtimeSinceStartup);
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao registrar a morte do monstro: {arg}");
			}
		}

		[HarmonyPostfix]
		[HarmonyPatch(typeof(GrabbableObject), "SetScrapValue")]
		private static void SetScrapValuePostfix(GrabbableObject __instance, int setValueTo)
		{
			try
			{
				if (RemainsItems.IsRemains(__instance.itemProperties))
				{
					int instanceID = ((Object)__instance).GetInstanceID();
					ValueByBox[instanceID] = setValueTo;
					if (KillerByBox.TryGetValue(instanceID, out string value))
					{
						ApplyKiller(__instance, setValueTo, value);
					}
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao mostrar quem matou o monstro: {arg}");
			}
		}

		public static void OnShipLeft()
		{
			Scoreboard.NewDay();
		}

		public static void OnDayEnded()
		{
			Credits.Clear();
			ValueByBox.Clear();
			Scoreboard.NewDay();
		}

		public static void OnSessionStarted()
		{
			Credits.Clear();
			ValueByBox.Clear();
			KillerByBox.Clear();
			Scoreboard.Clear();
		}

		private static void OnCorpseMatched(GrabbableObject box, EnemyAI corpse)
		{
			try
			{
				string text = Credits.KillerOf(((Object)corpse).GetInstanceID());
				if (text != null)
				{
					int instanceID = ((Object)box).GetInstanceID();
					KillerByBox[instanceID] = text;
					if (ValueByBox.TryGetValue(instanceID, out var value))
					{
						ApplyKiller(box, value, text);
					}
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao ligar a caixa de restos a quem matou o monstro: {arg}");
			}
		}

		private static void ApplyKiller(GrabbableObject box, int value, string killer)
		{
			if (Plugin.Cfg.ShowKillerEnabled.Value)
			{
				ScanNodeProperties componentInChildren = ((Component)box).GetComponentInChildren<ScanNodeProperties>();
				if ((Object)(object)componentInChildren != (Object)null)
				{
					componentInChildren.subText = RemainsScanText.Format(value, killer, Plugin.Cfg.ShowReais.Value, Plugin.Cfg.Lang);
				}
			}
			StartOfRound instance = StartOfRound.Instance;
			int instanceID = ((Object)box).GetInstanceID();
			if ((Object)(object)instance != (Object)null && !instance.shipIsLeaving)
			{
				Scoreboard.TryAdd(instanceID, killer, value);
			}
			else
			{
				Scoreboard.Exclude(instanceID);
			}
		}
	}
	internal static class RemainsItems
	{
		private const int ItemIdBase = 41000;

		private const string PrefabNamePrefix = "BitencolaRemains_";

		private const int FallbackPropsLayer = 6;

		private const int FallbackScanNodeLayer = 22;

		private static readonly Dictionary<MonsterEntry, Item> ItemsByEntry = new Dictionary<MonsterEntry, Item>();

		private static readonly Dictionary<Item, MonsterEntry> EntriesByItem = new Dictionary<Item, MonsterEntry>();

		private static readonly HashSet<Item> AllItems = new HashSet<Item>();

		public static IEnumerable<Item> All => AllItems;

		public static void CreateAndRegister()
		{
			if (ItemsByEntry.Count <= 0)
			{
				int propsLayer = ResolveLayer("Props", 6);
				int scanNodeLayer = ResolveLayer("ScanNode", 22);
				(Mesh mesh, Material? material) tuple = CreateBoxVisuals();
				Mesh item = tuple.mesh;
				Dictionary<MonsterTier, Material> dictionary = CreateTierMaterials(tuple.material);
				IReadOnlyList<MonsterEntry> entries = MonsterCatalog.Entries;
				for (int i = 0; i < entries.Count; i++)
				{
					MonsterEntry monsterEntry = entries[i];
					TierSpec tier = MonsterCatalog.Tiers[monsterEntry.Tier];
					Item val = CreateItem(monsterEntry, tier, 41000 + i);
					val.spawnPrefab = CreatePrefab(monsterEntry, tier, val, item, dictionary[monsterEntry.Tier], propsLayer, scanNodeLayer);
					Items.RegisterItem(val);
					ItemsByEntry.Add(monsterEntry, val);
					EntriesByItem.Add(val, monsterEntry);
					AllItems.Add(val);
				}
				Plugin.Log.LogInfo((object)$"{ItemsByEntry.Count} itens de restos de monstro registrados");
			}
		}

		public static Item ItemFor(MonsterEntry entry)
		{
			return ItemsByEntry[entry];
		}

		public static bool IsRemains(Item? item)
		{
			if ((Object)(object)item != (Object)null)
			{
				return AllItems.Contains(item);
			}
			return false;
		}

		public static MonsterEntry? EntryFor(Item? item)
		{
			if (!((Object)(object)item != (Object)null) || !EntriesByItem.TryGetValue(item, out MonsterEntry value))
			{
				return null;
			}
			return value;
		}

		private static Item CreateItem(MonsterEntry entry, TierSpec tier, int itemId)
		{
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b5: Unknown result type (might be due to invalid IL or missing references)
			Item obj = ScriptableObject.CreateInstance<Item>();
			((Object)obj).name = "BitencolaRemains_" + entry.Key;
			((Object)obj).hideFlags = (HideFlags)32;
			obj.itemName = entry.ItemNameIn(Plugin.Cfg.Lang);
			obj.itemId = itemId;
			obj.isScrap = true;
			obj.weight = ItemWeight.ToGameWeight(tier.WeightLb);
			obj.twoHanded = tier.TwoHanded;
			obj.twoHandedAnimation = tier.TwoHanded;
			obj.minValue = entry.MinValue;
			obj.maxValue = entry.MaxValue;
			obj.itemSpawnsOnGround = true;
			obj.canBeGrabbedBeforeGameStart = true;
			obj.requiresBattery = false;
			obj.verticalOffset = tier.BoxSize / 2f;
			obj.restingRotation = Vector3.zero;
			obj.toolTips = Array.Empty<string>();
			obj.meshVariants = Array.Empty<Mesh>();
			obj.materialVariants = Array.Empty<Material>();
			obj.clinkAudios = Array.Empty<AudioClip>();
			obj.spawnPositionTypes = new List<ItemGroup>();
			return obj;
		}

		private static GameObject CreatePrefab(MonsterEntry entry, TierSpec tier, Item item, Mesh mesh, Material? material, int propsLayer, int scanNodeLayer)
		{
			//IL_002e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0039: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b0: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ba: Expected O, but got Unknown
			GameObject obj = NetworkPrefabs.CreateNetworkPrefab("BitencolaRemains_" + entry.Key);
			obj.tag = "PhysicsProp";
			obj.layer = propsLayer;
			obj.transform.localScale = Vector3.one * tier.BoxSize;
			NetworkObject component = obj.GetComponent<NetworkObject>();
			component.AutoObjectParentSync = false;
			component.DontDestroyWithOwner = true;
			obj.AddComponent<MeshFilter>().sharedMesh = mesh;
			MeshRenderer val = obj.AddComponent<MeshRenderer>();
			((Renderer)val).sharedMaterial = material;
			obj.AddComponent<BoxCollider>();
			AudioSource obj2 = obj.AddComponent<AudioSource>();
			obj2.playOnAwake = false;
			obj2.spatialBlend = 1f;
			PhysicsProp obj3 = obj.AddComponent<PhysicsProp>();
			((GrabbableObject)obj3).itemProperties = item;
			((GrabbableObject)obj3).grabbable = true;
			((GrabbableObject)obj3).mainObjectRenderer = val;
			((GrabbableObject)obj3).insertedBattery = new Battery(true, 0f);
			AddScanNode(obj, item, scanNodeLayer);
			Utilities.FixMixerGroups(obj);
			return obj;
		}

		private static void AddScanNode(GameObject prefab, Item item, int scanNodeLayer)
		{
			//IL_0005: Unknown result type (might be due to invalid IL or missing references)
			//IL_000a: Unknown result type (might be due to invalid IL or missing references)
			//IL_001c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0023: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("ScanNode");
			val.transform.SetParent(prefab.transform, false);
			val.layer = scanNodeLayer;
			((Collider)val.AddComponent<BoxCollider>()).isTrigger = true;
			ScanNodeProperties obj = val.AddComponent<ScanNodeProperties>();
			obj.headerText = item.itemName;
			obj.subText = "Value: $0";
			obj.nodeType = 2;
			obj.minRange = 1;
			obj.maxRange = 13;
			obj.requiresLineOfSight = true;
		}

		private static Dictionary<MonsterTier, Material?> CreateTierMaterials(Material? template)
		{
			//IL_0043: 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_0065: Unknown result type (might be due to invalid IL or missing references)
			//IL_006e: Expected O, but got Unknown
			//IL_00ab: Unknown result type (might be due to invalid IL or missing references)
			//IL_00c2: Unknown result type (might be due to invalid IL or missing references)
			Dictionary<MonsterTier, Material> dictionary = new Dictionary<MonsterTier, Material>();
			Color val2 = default(Color);
			foreach (MonsterTier value in Enum.GetValues(typeof(MonsterTier)))
			{
				if ((Object)(object)template == (Object)null)
				{
					dictionary[value] = null;
					continue;
				}
				Material val = new Material(template)
				{
					name = "BitencolaRemains_" + value,
					hideFlags = (HideFlags)32
				};
				var (num, num2, num3) = TierColors.For(value);
				((Color)(ref val2))..ctor(num, num2, num3);
				if (val.HasProperty("_BaseColor"))
				{
					val.SetColor("_BaseColor", val2);
				}
				else if (val.HasProperty("_Color"))
				{
					val.color = val2;
				}
				dictionary[value] = val;
			}
			if ((Object)(object)template != (Object)null)
			{
				Object.Destroy((Object)(object)template);
			}
			return dictionary;
		}

		private static (Mesh mesh, Material? material) CreateBoxVisuals()
		{
			//IL_003a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0040: Expected O, but got Unknown
			//IL_005b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0061: Expected O, but got Unknown
			GameObject obj = GameObject.CreatePrimitive((PrimitiveType)3);
			Mesh sharedMesh = obj.GetComponent<MeshFilter>().sharedMesh;
			Material sharedMaterial = ((Renderer)obj.GetComponent<MeshRenderer>()).sharedMaterial;
			Object.Destroy((Object)(object)obj);
			Material val = null;
			Shader val2 = Shader.Find("HDRP/Lit");
			if ((Object)(object)val2 != (Object)null)
			{
				val = new Material(val2);
			}
			else
			{
				if (!((Object)(object)sharedMaterial != (Object)null))
				{
					Plugin.Log.LogError((object)"Shader HDRP/Lit não encontrado e sem material padrão; os restos ficam sem material.");
					return (mesh: sharedMesh, material: null);
				}
				Plugin.Log.LogWarning((object)"Shader HDRP/Lit não encontrado; os restos usam o material padrão.");
				val = new Material(sharedMaterial);
			}
			return (mesh: sharedMesh, material: val);
		}

		private static int ResolveLayer(string name, int fallback)
		{
			int num = LayerMask.NameToLayer(name);
			if (num >= 0)
			{
				return num;
			}
			Plugin.Log.LogError((object)$"Layer \"{name}\" não encontrado (NameToLayer devolveu -1); usando {fallback}.");
			return fallback;
		}
	}
	[HarmonyPatch]
	internal static class RemainsNameLabels
	{
		private const string RootName = "BitencolaNameLabels";

		private const float PanelUnits = 100f;

		private const float PanelScale = 0.009f;

		private const float MinFontSize = 6f;

		private const float MaxFontSize = 30f;

		private const float OutlineWidth = 0.25f;

		private static bool _listeningToConfig;

		private static bool _warnedNoFont;

		private static readonly Dictionary<TMP_FontAsset, Material> OutlineMaterials = new Dictionary<TMP_FontAsset, Material>();

		[HarmonyPatch(typeof(GrabbableObject), "Start")]
		[HarmonyPostfix]
		private static void StartPostfix(GrabbableObject __instance)
		{
			try
			{
				ListenToConfigOnce();
				if ((Object)(object)__instance == (Object)null)
				{
					return;
				}
				MonsterEntry monsterEntry = RemainsItems.EntryFor(__instance.itemProperties);
				if (monsterEntry != null)
				{
					GameObject val = EnsureLabels(((Component)__instance).gameObject, RemainsLabel.TextFor(monsterEntry, Plugin.Cfg.Lang));
					if ((Object)(object)val != (Object)null)
					{
						val.SetActive(ShouldShow(__instance));
					}
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao escrever o nome na caixa de restos: {arg}");
			}
		}

		[HarmonyPatch(typeof(GrabbableObject), "EnableItemMeshes")]
		[HarmonyPostfix]
		private static void EnableItemMeshesPostfix(GrabbableObject __instance)
		{
			try
			{
				if (!((Object)(object)__instance == (Object)null) && RemainsItems.IsRemains(__instance.itemProperties))
				{
					Transform val = ((Component)__instance).transform.Find("BitencolaNameLabels");
					if ((Object)(object)val != (Object)null)
					{
						((Component)val).gameObject.SetActive(ShouldShow(__instance));
					}
				}
			}
			catch (Exception arg)
			{
				Plugin.Log.LogError((object)$"Falha ao mostrar ou esconder o nome da caixa de restos: {arg}");
			}
		}

		private static bool ShouldShow(GrabbableObject box)
		{
			if (Plugin.Cfg.ShowRemainsNames.Value)
			{
				if (!((Object)(object)box.mainObjectRenderer == (Object)null))
				{
					return ((Renderer)box.mainObjectRenderer).enabled;
				}
				return true;
			}
			return false;
		}

		private static GameObject? EnsureLabels(GameObject box, string text)
		{
			//IL_005a: Unknown result type (might be due to invalid IL or missing references)
			//IL_0060: Expected O, but got Unknown
			Transform val = box.transform.Find("BitencolaNameLabels");
			if ((Object)(object)val != (Object)null)
			{
				return ((Component)val).gameObject;
			}
			TMP_FontAsset val2 = FindFont();
			if ((Object)(object)val2 == (Object)null)
			{
				if (!_warnedNoFont)
				{
					_warnedNoFont = true;
					Plugin.Log.LogWarning((object)"Fonte de texto do jogo não encontrada; as caixas ficam sem o nome escrito.");
				}
				return null;
			}
			Material material = OutlineMaterialFor(val2);
			GameObject val3 = new GameObject("BitencolaNameLabels");
			val3.layer = box.layer;
			val3.transform.SetParent(box.transform, false);
			foreach (LabelFace face in RemainsLabel.Faces)
			{
				CreateFace(val3.transform, face, text, val2, material, box.layer);
			}
			return val3;
		}

		private static void CreateFace(Transform parent, LabelFace face, string text, TMP_FontAsset font, Material? material, int layer)
		{
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			//IL_001d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0025: Unknown result type (might be due to invalid IL or missing references)
			//IL_002b: Unknown result type (might be due to invalid IL or missing references)
			//IL_0031: Expected O, but got Unknown
			//IL_004f: Unknown result type (might be due to invalid IL or missing references)
			//IL_0064: Unknown result type (might be due to invalid IL or missing references)
			//IL_0081: Unknown result type (might be due to invalid IL or missing references)
			//IL_009d: Unknown result type (might be due to invalid IL or missing references)
			//IL_00a8: Unknown result type (might be due to invalid IL or missing references)
			//IL_00b2: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d4: Unknown result type (might be due to invalid IL or missing references)
			//IL_00d9: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e1: Unknown result type (might be due to invalid IL or missing references)
			//IL_00e7: Unknown result type (might be due to invalid IL or missing references)
			//IL_00ec: Unknown result type (might be due to invalid IL or missing references)
			//IL_00f4: 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_00ff: Unknown result type (might be due to invalid IL or missing references)
			//IL_0100: Unknown result type (might be due to invalid IL or missing references)
			//IL_010a: Unknown result type (might be due to invalid IL or missing references)
			//IL_010b: 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_0175: Unknown result type (might be due to invalid IL or missing references)
			GameObject val = new GameObject("Face", new Type[1] { typeof(RectTransform) })
			{
				layer = layer
			};
			RectTransform val2 = (RectTransform)val.transform;
			((Transform)val2).SetParent(parent, false);
			val.AddComponent<Canvas>().renderMode = (RenderMode)2;
			val2.pivot = new Vector2(0.5f, 0