Decompiled source of RaftDurability v0.2.0

patchers/RaftDurability.Patcher.dll

Decompiled an hour ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using Mono.Cecil;
using Mono.Cecil.Cil;
using Mono.Cecil.Rocks;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("RaftDurability.Patcher")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.2.0.0")]
[assembly: AssemblyInformationalVersion("0.2.0+d82f2ca6059878300f514f00e50a68d52ea1484c")]
[assembly: AssemblyProduct("RaftDurability.Patcher")]
[assembly: AssemblyTitle("RaftDurability.Patcher")]
[assembly: AssemblyVersion("0.2.0.0")]
namespace RaftDurability.Preloader;

public static class Patcher
{
	public static IEnumerable<string> TargetDLLs { get; } = new string[1] { "Assembly-CSharp.dll" };

	public static void Patch(AssemblyDefinition assembly)
	{
		//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e8: Invalid comparison between Unknown and I4
		//IL_0109: Unknown result type (might be due to invalid IL or missing references)
		//IL_010f: Invalid comparison between Unknown and I4
		//IL_0132: Unknown result type (might be due to invalid IL or missing references)
		//IL_0139: Invalid comparison between Unknown and I4
		//IL_023e: Unknown result type (might be due to invalid IL or missing references)
		//IL_0245: Expected O, but got Unknown
		//IL_02b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_02b9: Expected O, but got Unknown
		//IL_02e0: Unknown result type (might be due to invalid IL or missing references)
		//IL_02ef: Unknown result type (might be due to invalid IL or missing references)
		//IL_02fe: Unknown result type (might be due to invalid IL or missing references)
		//IL_030b: Unknown result type (might be due to invalid IL or missing references)
		//IL_04a8: Unknown result type (might be due to invalid IL or missing references)
		//IL_04b5: Unknown result type (might be due to invalid IL or missing references)
		//IL_056d: Unknown result type (might be due to invalid IL or missing references)
		//IL_0587: Unknown result type (might be due to invalid IL or missing references)
		//IL_0596: Unknown result type (might be due to invalid IL or missing references)
		//IL_05a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_05b2: Unknown result type (might be due to invalid IL or missing references)
		//IL_05bf: Unknown result type (might be due to invalid IL or missing references)
		//IL_05cc: Unknown result type (might be due to invalid IL or missing references)
		//IL_05e6: Unknown result type (might be due to invalid IL or missing references)
		//IL_05f5: Unknown result type (might be due to invalid IL or missing references)
		//IL_0605: Unknown result type (might be due to invalid IL or missing references)
		ModuleDefinition mainModule = assembly.MainModule;
		if (mainModule.GetType("RaftDurability.GameCallbacks") != null)
		{
			throw new InvalidOperationException("Raft Durability callbacks already exist. Remove duplicate patchers.");
		}
		MethodDefinition val = Find(mainModule, "PlayerInventory", "RemoveDurabillityFromHotSlot");
		MethodDefinition val2 = Find(mainModule, "PlayerInventory", "RemoveDurabillityFromEquipment");
		MethodDefinition[] array = (MethodDefinition[])(object)new MethodDefinition[4]
		{
			Find(mainModule, "Equipment_ArmorPiece", "RemoveDurability"),
			Find(mainModule, "Equipment_AirBottle", "UpdateEquipment"),
			Find(mainModule, "Equipment_Flipper", "UpdateEquipment"),
			Find(mainModule, "Equipment_HeadLight", "UpdateEquipment")
		};
		MethodDefinition val3 = Find(mainModule, "GameManager", "OnWorldRecieved");
		MethodDefinition val4 = Find(mainModule, "Raft_Network", "CleanupState");
		MethodDefinition val5 = Find(mainModule, "Raft_Network", "SendWorld");
		MethodDefinition val6 = Find(mainModule, "Raft_Network", "OnDataMessageReceived");
		if ((int)((MethodReference)val).ReturnType.MetadataType != 2 || ((MethodReference)val).Parameters.Count != 1 || (int)((ParameterReference)((MethodReference)val).Parameters[0]).ParameterType.MetadataType != 8 || ((MethodReference)val6).Parameters.Count != 4 || (int)((ParameterReference)((MethodReference)val6).Parameters[3]).ParameterType.MetadataType != 9)
		{
			throw new InvalidOperationException("Unsupported Raft durability/network signatures.");
		}
		Instruction val7 = ((IEnumerable<Instruction>)val.Body.Instructions).Single(delegate(Instruction i)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0069: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Invalid comparison between Unknown and I4
			//IL_0077: Unknown result type (might be due to invalid IL or missing references)
			//IL_007d: Invalid comparison between Unknown and I4
			if (i.OpCode == OpCodes.Call)
			{
				object operand = i.Operand;
				MethodReference val15 = (MethodReference)((operand is MethodReference) ? operand : null);
				if (val15 != null && ((MemberReference)((MemberReference)val15).DeclaringType).Name == "PlayerInventory" && ((MemberReference)val15).Name == "RemoveStacksFromHotSlot" && val15.Parameters.Count == 1 && (int)((ParameterReference)val15.Parameters[0]).ParameterType.MetadataType == 8)
				{
					return (int)val15.ReturnType.MetadataType == 2;
				}
			}
			return false;
		});
		Instruction call = FindCall(val2, "PlayerInventory", "RemoveStacksFromSlot", "Slot", "System.Int32");
		Instruction[] array2 = array.Select((MethodDefinition m) => FindCall(m, "Slot", "IncrementUses", "System.Int32", "System.Boolean")).ToArray();
		foreach (MethodDefinition item in ((IEnumerable<MethodDefinition>)(object)new MethodDefinition[6] { val, val2, val3, val4, val5, val6 }).Concat(array))
		{
			MethodBodyRocks.SimplifyMacros(item.Body);
		}
		TypeDefinition val8 = new TypeDefinition("RaftDurability", "GameCallbacks", (TypeAttributes)385, mainModule.TypeSystem.Object);
		mainModule.Types.Add(val8);
		MethodDefinition val9 = AddCallback(val8, "ScaleToolDurability", mainModule.TypeSystem.Int32, (TypeReference[])(object)new TypeReference[2]
		{
			(TypeReference)val.DeclaringType,
			mainModule.TypeSystem.Int32
		}, delegate(ILProcessor il)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			il.Emit(OpCodes.Ldarg_1);
		});
		VariableDefinition val10 = new VariableDefinition(mainModule.TypeSystem.Int32);
		val.Body.Variables.Add(val10);
		ILProcessor iLProcessor = val.Body.GetILProcessor();
		Instruction[] array3 = (Instruction[])(object)new Instruction[4]
		{
			Instruction.Create(OpCodes.Call, (MethodReference)(object)val9),
			Instruction.Create(OpCodes.Stloc, val10),
			Instruction.Create(OpCodes.Ldarg_0),
			Instruction.Create(OpCodes.Ldloc, val10)
		};
		foreach (Instruction val11 in array3)
		{
			iLProcessor.InsertBefore(val7, val11);
		}
		MethodDefinition scale = AddCallback(val8, "ScaleEquipmentDurability", mainModule.TypeSystem.Int32, (TypeReference[])(object)new TypeReference[2]
		{
			(TypeReference)mainModule.GetType("Slot"),
			mainModule.TypeSystem.Int32
		}, delegate(ILProcessor il)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			il.Emit(OpCodes.Ldarg_1);
		});
		MethodDefinition scale2 = AddCallback(val8, "ScaleEquipmentDelta", mainModule.TypeSystem.Int32, (TypeReference[])(object)new TypeReference[2]
		{
			(TypeReference)mainModule.GetType("Slot"),
			mainModule.TypeSystem.Int32
		}, delegate(ILProcessor il)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			il.Emit(OpCodes.Ldarg_1);
		});
		ScaleSlotCall(val2, call, (MethodReference)(object)scale, hasTrailingBoolean: false);
		for (int num2 = 0; num2 < array.Length; num2++)
		{
			ScaleSlotCall(array[num2], array2[num2], (MethodReference)(object)scale2, hasTrailingBoolean: true);
		}
		InsertAtReturns(val3, (MethodReference)(object)AddCallback(val8, "WorldReceived", mainModule.TypeSystem.Void, Array.Empty<TypeReference>()));
		InsertAtReturns(val4, (MethodReference)(object)AddCallback(val8, "SessionReset", mainModule.TypeSystem.Void, Array.Empty<TypeReference>()));
		MethodDefinition val12 = AddCallback(val8, "SendWorld", mainModule.TypeSystem.Void, (TypeReference[])(object)new TypeReference[1] { ((ParameterReference)((MethodReference)val5).Parameters[0]).ParameterType });
		InsertEntry(val5, Instruction.Create(OpCodes.Ldarg_1), Instruction.Create(OpCodes.Call, (MethodReference)(object)val12));
		MethodDefinition val13 = AddCallback(val8, "ReceivePacket", mainModule.TypeSystem.Boolean, (TypeReference[])(object)new TypeReference[4]
		{
			(TypeReference)val6.DeclaringType,
			((ParameterReference)((MethodReference)val6).Parameters[1]).ParameterType,
			((ParameterReference)((MethodReference)val6).Parameters[2]).ParameterType,
			((ParameterReference)((MethodReference)val6).Parameters[3]).ParameterType
		}, delegate(ILProcessor il)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			il.Emit(OpCodes.Ldc_I4_1);
		});
		Instruction val14 = val6.Body.Instructions[0];
		InsertEntry(val6, Instruction.Create(OpCodes.Ldarg, ((MethodReference)val6).Parameters[3]), Instruction.Create(OpCodes.Ldc_I4, 15), Instruction.Create(OpCodes.Bne_Un, val14), Instruction.Create(OpCodes.Ldarg_0), Instruction.Create(OpCodes.Ldarg_2), Instruction.Create(OpCodes.Ldarg_3), Instruction.Create(OpCodes.Ldarg, ((MethodReference)val6).Parameters[3]), Instruction.Create(OpCodes.Call, (MethodReference)(object)val13), Instruction.Create(OpCodes.Brtrue, val14), Instruction.Create(OpCodes.Ret));
	}

	private static MethodDefinition Find(ModuleDefinition module, string type, string method)
	{
		return ((IEnumerable<MethodDefinition>)module.GetType(type).Methods).Single((MethodDefinition candidate) => ((MemberReference)candidate).Name == method && candidate.HasBody);
	}

	private static Instruction FindCall(MethodDefinition owner, string type, string name, params string[] parameters)
	{
		return ((IEnumerable<Instruction>)owner.Body.Instructions).Single(delegate(Instruction i)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_0006: Unknown result type (might be due to invalid IL or missing references)
			//IL_0013: Unknown result type (might be due to invalid IL or missing references)
			//IL_0018: Unknown result type (might be due to invalid IL or missing references)
			if (i.OpCode == OpCodes.Call || i.OpCode == OpCodes.Callvirt)
			{
				object operand = i.Operand;
				MethodReference val = (MethodReference)((operand is MethodReference) ? operand : null);
				if (val != null && ((MemberReference)((MemberReference)val).DeclaringType).FullName == type && ((MemberReference)val).Name == name)
				{
					return ((IEnumerable<ParameterDefinition>)val.Parameters).Select((ParameterDefinition p) => ((MemberReference)((ParameterReference)p).ParameterType).FullName).SequenceEqual(parameters);
				}
			}
			return false;
		});
	}

	private static void ScaleSlotCall(MethodDefinition owner, Instruction call, MethodReference scale, bool hasTrailingBoolean)
	{
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Expected O, but got Unknown
		//IL_006b: Unknown result type (might be due to invalid IL or missing references)
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		//IL_008c: 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_0042: Unknown result type (might be due to invalid IL or missing references)
		//IL_0048: Expected O, but got Unknown
		//IL_005a: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b1: Unknown result type (might be due to invalid IL or missing references)
		VariableDefinition val = new VariableDefinition(((MemberReference)owner).Module.TypeSystem.Int32);
		owner.Body.Variables.Add(val);
		List<Instruction> list = new List<Instruction>();
		VariableDefinition val2 = null;
		if (hasTrailingBoolean)
		{
			val2 = new VariableDefinition(((MemberReference)owner).Module.TypeSystem.Boolean);
			owner.Body.Variables.Add(val2);
			list.Add(Instruction.Create(OpCodes.Stloc, val2));
		}
		list.Add(Instruction.Create(OpCodes.Stloc, val));
		list.Add(Instruction.Create(OpCodes.Dup));
		list.Add(Instruction.Create(OpCodes.Ldloc, val));
		list.Add(Instruction.Create(OpCodes.Call, scale));
		if (val2 != null)
		{
			list.Add(Instruction.Create(OpCodes.Ldloc, val2));
		}
		ILProcessor iLProcessor = owner.Body.GetILProcessor();
		foreach (Instruction item in list)
		{
			iLProcessor.InsertBefore(call, item);
		}
		owner.Body.MaxStackSize = Math.Max(owner.Body.MaxStackSize, 4);
	}

	private static MethodDefinition AddCallback(TypeDefinition owner, string name, TypeReference returns, TypeReference[] parameters, Action<ILProcessor> fallback = null)
	{
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0020: Expected O, but got Unknown
		//IL_003a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0040: Expected O, but got Unknown
		//IL_0063: Unknown result type (might be due to invalid IL or missing references)
		//IL_006d: Expected O, but got Unknown
		//IL_0087: 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_00a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ad: Unknown result type (might be due to invalid IL or missing references)
		//IL_00b9: Unknown result type (might be due to invalid IL or missing references)
		//IL_00c7: Unknown result type (might be due to invalid IL or missing references)
		//IL_00e2: Unknown result type (might be due to invalid IL or missing references)
		//IL_00ed: Unknown result type (might be due to invalid IL or missing references)
		//IL_00fa: Unknown result type (might be due to invalid IL or missing references)
		//IL_0144: Unknown result type (might be due to invalid IL or missing references)
		//IL_0169: Unknown result type (might be due to invalid IL or missing references)
		//IL_016f: Invalid comparison between Unknown and I4
		//IL_012c: Unknown result type (might be due to invalid IL or missing references)
		//IL_011d: Unknown result type (might be due to invalid IL or missing references)
		//IL_017f: Unknown result type (might be due to invalid IL or missing references)
		//IL_0172: Unknown result type (might be due to invalid IL or missing references)
		//IL_018b: Unknown result type (might be due to invalid IL or missing references)
		//IL_01aa: Unknown result type (might be due to invalid IL or missing references)
		ModuleDefinition module = ((MemberReference)owner).Module;
		FieldDefinition val = new FieldDefinition(name, (FieldAttributes)22, module.ImportReference(typeof(Delegate)));
		owner.Fields.Add(val);
		MethodDefinition val2 = new MethodDefinition("Invoke" + name, (MethodAttributes)22, returns);
		owner.Methods.Add(val2);
		foreach (TypeReference val3 in parameters)
		{
			((MethodReference)val2).Parameters.Add(new ParameterDefinition(val3));
		}
		ILProcessor iLProcessor = val2.Body.GetILProcessor();
		Instruction val4 = Instruction.Create(OpCodes.Nop);
		iLProcessor.Emit(OpCodes.Ldsfld, (FieldReference)(object)val);
		iLProcessor.Emit(OpCodes.Brfalse, val4);
		iLProcessor.Emit(OpCodes.Ldsfld, (FieldReference)(object)val);
		iLProcessor.Emit(OpCodes.Ldc_I4, parameters.Length);
		iLProcessor.Emit(OpCodes.Newarr, module.TypeSystem.Object);
		for (int j = 0; j < parameters.Length; j++)
		{
			iLProcessor.Emit(OpCodes.Dup);
			iLProcessor.Emit(OpCodes.Ldc_I4, j);
			iLProcessor.Emit(OpCodes.Ldarg, ((MethodReference)val2).Parameters[j]);
			if (parameters[j].IsValueType)
			{
				iLProcessor.Emit(OpCodes.Box, parameters[j]);
			}
			iLProcessor.Emit(OpCodes.Stelem_Ref);
		}
		iLProcessor.Emit(OpCodes.Callvirt, module.ImportReference((MethodBase)typeof(Delegate).GetMethod("DynamicInvoke")));
		if ((int)returns.MetadataType == 1)
		{
			iLProcessor.Emit(OpCodes.Pop);
		}
		else
		{
			iLProcessor.Emit(OpCodes.Unbox_Any, returns);
		}
		iLProcessor.Emit(OpCodes.Ret);
		iLProcessor.Append(val4);
		fallback?.Invoke(iLProcessor);
		iLProcessor.Emit(OpCodes.Ret);
		return val2;
	}

	private static void InsertEntry(MethodDefinition target, params Instruction[] instructions)
	{
		ILProcessor iLProcessor = target.Body.GetILProcessor();
		Instruction val = target.Body.Instructions[0];
		foreach (Instruction val2 in instructions)
		{
			iLProcessor.InsertBefore(val, val2);
		}
	}

	private static void InsertAtReturns(MethodDefinition target, MethodReference callback)
	{
		//IL_004a: Unknown result type (might be due to invalid IL or missing references)
		//IL_005d: Unknown result type (might be due to invalid IL or missing references)
		ILProcessor iLProcessor = target.Body.GetILProcessor();
		Instruction[] array = ((IEnumerable<Instruction>)target.Body.Instructions).Where((Instruction i) => i.OpCode == OpCodes.Ret).ToArray();
		foreach (Instruction val in array)
		{
			val.OpCode = OpCodes.Call;
			val.Operand = callback;
			iLProcessor.InsertAfter(val, Instruction.Create(OpCodes.Ret));
		}
	}
}

plugins/RaftDurability.dll

Decompiled an hour ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using PlayFab.Party;
using UnityEngine;
using UnityEngine.Events;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = ".NET Standard 2.1")]
[assembly: AssemblyCompany("RaftDurability")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.2.0.0")]
[assembly: AssemblyInformationalVersion("0.2.0+d82f2ca6059878300f514f00e50a68d52ea1484c")]
[assembly: AssemblyProduct("RaftDurability")]
[assembly: AssemblyTitle("RaftDurability")]
[assembly: AssemblyVersion("0.2.0.0")]
namespace RaftDurability;

internal static class DurabilityLoss
{
	private static ConditionalWeakTable<ItemInstance, DurabilityRemainder> remainders = new ConditionalWeakTable<ItemInstance, DurabilityRemainder>();

	internal static int Scale(PlayerInventory inventory, int vanillaLoss)
	{
		int tool = SettingsSync.Current.Tool;
		if (tool == 100 || vanillaLoss <= 0)
		{
			return vanillaLoss;
		}
		Slot selectedHotbarSlot = inventory.GetSelectedHotbarSlot();
		if ((Object)(object)selectedHotbarSlot == (Object)null || selectedHotbarSlot.IsEmpty)
		{
			return vanillaLoss;
		}
		return remainders.GetValue(selectedHotbarSlot.itemInstance, (ItemInstance _) => new DurabilityRemainder()).Scale(vanillaLoss, tool);
	}

	internal static int ScaleEquipment(Slot slot, int vanillaLoss)
	{
		int equipment = SettingsSync.Current.Equipment;
		if (equipment == 100 || vanillaLoss <= 0 || (Object)(object)slot == (Object)null || slot.IsEmpty)
		{
			return vanillaLoss;
		}
		return remainders.GetValue(slot.itemInstance, (ItemInstance _) => new DurabilityRemainder()).Scale(vanillaLoss, equipment);
	}

	internal static int ScaleEquipmentDelta(Slot slot, int delta)
	{
		if (delta >= 0)
		{
			return delta;
		}
		return -ScaleEquipment(slot, (delta == int.MinValue) ? int.MaxValue : (-delta));
	}

	internal static void Reset()
	{
		remainders = new ConditionalWeakTable<ItemInstance, DurabilityRemainder>();
	}
}
internal sealed class DurabilityRemainder
{
	private long remainder;

	internal int Scale(int amount, int percent)
	{
		if (amount <= 0)
		{
			return amount;
		}
		long num = (long)amount * (long)percent + remainder;
		remainder = num % 100;
		return (int)Math.Min(2147483647L, num / 100);
	}
}
internal readonly struct DurabilitySettings
{
	internal int Tool { get; }

	internal int Equipment { get; }

	internal bool IsValid
	{
		get
		{
			if (Tool >= 0 && Tool <= 500 && Equipment >= 0)
			{
				return Equipment <= 500;
			}
			return false;
		}
	}

	internal static DurabilitySettings Vanilla => new DurabilitySettings(100, 100);

	internal DurabilitySettings(int tool, int equipment)
	{
		Tool = tool;
		Equipment = equipment;
	}
}
[BepInPlugin("dev.yudle.raftdurability", "Raft Durability", "0.2.0")]
[BepInProcess("Raft.exe")]
public sealed class Plugin : BaseUnityPlugin
{
	internal const string PluginGuid = "dev.yudle.raftdurability";

	private void Awake()
	{
		DurabilityRuntime.Start(((BaseUnityPlugin)this).Config, ((BaseUnityPlugin)this).Logger);
	}
}
internal sealed class DurabilityRuntime
{
	private readonly ConfigFile config;

	private readonly ManualLogSource logger;

	private readonly ConfigEntry<float> loss;

	private readonly ConfigEntry<float> equipmentLoss;

	private readonly List<FieldInfo> boundFields = new List<FieldInfo>();

	internal static DurabilityRuntime Instance { get; private set; }

	private DurabilityRuntime(ConfigFile config, ManualLogSource logger)
	{
		//IL_0049: Unknown result type (might be due to invalid IL or missing references)
		//IL_0053: Expected O, but got Unknown
		//IL_0082: Unknown result type (might be due to invalid IL or missing references)
		//IL_008c: Expected O, but got Unknown
		this.config = config;
		this.logger = logger;
		loss = config.Bind<float>("Durability", "ToolLossMultiplier", 1f, new ConfigDescription("Tool durability consumption: 0 = no loss, 0.5 = half loss, 1 = vanilla, 2 = double loss. Host settings load per world at 0.01 precision. All players need the plugin and patcher.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 5f), Array.Empty<object>()));
		equipmentLoss = config.Bind<float>("Durability", "EquipmentLossMultiplier", 1f, new ConfigDescription("Equipped armor, air bottle, flippers, headlight and zipline tool durability consumption. 0 = no loss, 0.5 = half loss, 1 = vanilla, 2 = double loss. Host settings load per world.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0f, 5f), Array.Empty<object>()));
	}

	internal static void Start(ConfigFile config, ManualLogSource logger)
	{
		//IL_0023: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Expected O, but got Unknown
		if (Instance != null)
		{
			return;
		}
		DurabilityRuntime durabilityRuntime = (Instance = new DurabilityRuntime(config, logger));
		try
		{
			durabilityRuntime.BindCallbacks();
			Application.onBeforeRender += new UnityAction(SettingsSync.RequestIfNeeded);
			Application.quitting += durabilityRuntime.Shutdown;
			logger.LogInfo((object)"Raft Durability initialized. Preloader callbacks bound for the game process.");
		}
		catch (Exception ex)
		{
			durabilityRuntime.Shutdown();
			logger.LogError((object)ex);
		}
	}

	private void BindCallbacks()
	{
		Type type = typeof(PlayerInventory).Assembly.GetType("RaftDurability.GameCallbacks") ?? throw new InvalidOperationException("Install RaftDurability.Patcher.dll in BepInEx/patchers and restart.");
		foreach (KeyValuePair<string, Delegate> item in new Dictionary<string, Delegate>
		{
			["ScaleToolDurability"] = new Func<PlayerInventory, int, int>(DurabilityLoss.Scale),
			["ScaleEquipmentDurability"] = new Func<Slot, int, int>(DurabilityLoss.ScaleEquipment),
			["ScaleEquipmentDelta"] = new Func<Slot, int, int>(DurabilityLoss.ScaleEquipmentDelta),
			["WorldReceived"] = new Action(SettingsSync.WorldReceived),
			["SessionReset"] = new Action(SettingsSync.Reset),
			["SendWorld"] = new Action<Network_UserId>(SettingsSync.BeforeSendWorld),
			["ReceivePacket"] = new Func<Raft_Network, PlayFabPlayer, IntPtr, uint, bool>(SettingsSync.ReceivePacket)
		})
		{
			FieldInfo fieldInfo = type.GetField(item.Key, BindingFlags.Static | BindingFlags.Public) ?? throw new InvalidOperationException("Missing durability callback " + item.Key + ". Install the matching patcher.");
			fieldInfo.SetValue(null, item.Value);
			boundFields.Add(fieldInfo);
		}
	}

	internal DurabilitySettings ReadSettings()
	{
		config.Reload();
		DurabilitySettings result = new DurabilitySettings(ToPercent(loss.Value), ToPercent(equipmentLoss.Value));
		logger.LogInfo((object)$"Host settings loaded: tool durability loss {(float)result.Tool / 100f:0.##}x, equipment {(float)result.Equipment / 100f:0.##}x.");
		return result;
	}

	private static int ToPercent(float value)
	{
		if (!float.IsNaN(value))
		{
			return (int)Math.Round(Math.Max(0f, Math.Min(5f, value)) * 100f, MidpointRounding.AwayFromZero);
		}
		return 100;
	}

	internal void LogSynced(DurabilitySettings settings)
	{
		logger.LogInfo((object)$"Host settings received: tool durability loss {(float)settings.Tool / 100f:0.##}x, equipment {(float)settings.Equipment / 100f:0.##}x.");
	}

	private void Shutdown()
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0011: Expected O, but got Unknown
		Application.onBeforeRender -= new UnityAction(SettingsSync.RequestIfNeeded);
		Application.quitting -= Shutdown;
		foreach (FieldInfo boundField in boundFields)
		{
			boundField.SetValue(null, null);
		}
		boundFields.Clear();
		SettingsSync.Reset();
		Instance = null;
	}
}
internal static class SettingsPacket
{
	internal const int Request = 65535;

	private static readonly byte[] Header = new byte[11]
	{
		224, 38, 1, 1, 0, 0, 0, 89, 68, 77,
		2
	};

	internal static byte[] Create(int tool, int equipment)
	{
		byte[] array = new byte[15];
		Header.CopyTo(array, 0);
		array[11] = (byte)tool;
		array[12] = (byte)(tool >> 8);
		array[13] = (byte)equipment;
		array[14] = (byte)(equipment >> 8);
		return array;
	}

	internal static bool TryRead(IntPtr ptr, uint size, out int tool, out int equipment)
	{
		tool = (equipment = 100);
		if (ptr == IntPtr.Zero || size != 15)
		{
			return false;
		}
		for (int i = 0; i < Header.Length; i++)
		{
			if (Marshal.ReadByte(ptr, i) != Header[i])
			{
				return false;
			}
		}
		tool = Marshal.ReadByte(ptr, 11) | (Marshal.ReadByte(ptr, 12) << 8);
		equipment = Marshal.ReadByte(ptr, 13) | (Marshal.ReadByte(ptr, 14) << 8);
		return true;
	}
}
internal static class SettingsSync
{
	private static DurabilitySettings? settings;

	private static float nextRequest;

	internal static DurabilitySettings Current
	{
		get
		{
			if (Raft_Network.IsHost && !settings.HasValue)
			{
				settings = DurabilityRuntime.Instance.ReadSettings();
			}
			return settings ?? DurabilitySettings.Vanilla;
		}
	}

	internal static void Reset()
	{
		settings = null;
		nextRequest = 0f;
		DurabilityLoss.Reset();
	}

	internal static void RequestIfNeeded()
	{
		//IL_004f: Unknown result type (might be due to invalid IL or missing references)
		if (!Raft_Network.IsHost && !settings.HasValue && !(Time.unscaledTime < nextRequest))
		{
			nextRequest = Time.unscaledTime + 2f;
			Raft_Network value = ComponentManager<Raft_Network>.Value;
			if ((Object)(object)value != (Object)null && value.IsConnectedToHost && !GameManager.IsLeavingGame)
			{
				SendTo(value.HostID, SettingsPacket.Create(65535, 65535));
			}
		}
	}

	private static void SendTo(Network_UserId recipient, byte[] packet)
	{
		//IL_0010: Unknown result type (might be due to invalid IL or missing references)
		//IL_0016: Invalid comparison between Unknown and I4
		//IL_0039: Unknown result type (might be due to invalid IL or missing references)
		//IL_003e: Unknown result type (might be due to invalid IL or missing references)
		PlayFabMultiplayerManager val = PlayFabMultiplayerManager.Get();
		if ((Object)(object)val == (Object)null || (int)val.State != 3)
		{
			return;
		}
		foreach (PlayFabPlayer remotePlayer in val.RemotePlayers)
		{
			if (!(Network_UserId.op_Implicit(remotePlayer.EntityKey.Id) != recipient))
			{
				val.SendDataMessage(packet, (IEnumerable<PlayFabPlayer>)(object)new PlayFabPlayer[1] { remotePlayer }, (DeliveryOption)1);
				break;
			}
		}
	}

	internal static void BeforeSendWorld(Network_UserId recipient)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		if (Raft_Network.IsHost)
		{
			SendTo(recipient, SettingsPacket.Create(Current.Tool, Current.Equipment));
		}
	}

	internal static void WorldReceived()
	{
		_ = Current;
	}

	internal static bool ReceivePacket(Raft_Network network, PlayFabPlayer from, IntPtr ptr, uint size)
	{
		//IL_002b: Unknown result type (might be due to invalid IL or missing references)
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_0081: Unknown result type (might be due to invalid IL or missing references)
		//IL_0083: Unknown result type (might be due to invalid IL or missing references)
		//IL_0051: Unknown result type (might be due to invalid IL or missing references)
		if (!SettingsPacket.TryRead(ptr, size, out var tool, out var equipment))
		{
			return true;
		}
		if (!network.IsConnectedToHost || GameManager.IsLeavingGame)
		{
			return false;
		}
		Network_UserId val = Network_UserId.op_Implicit(from.EntityKey.Id);
		DurabilitySettings value = new DurabilitySettings(tool, equipment);
		if (Raft_Network.IsHost && tool == 65535 && equipment == 65535)
		{
			SendTo(val, SettingsPacket.Create(Current.Tool, Current.Equipment));
		}
		else if (!Raft_Network.IsHost && val == network.HostID && !settings.HasValue && value.IsValid)
		{
			settings = value;
			DurabilityLoss.Reset();
			DurabilityRuntime.Instance.LogSynced(value);
		}
		return false;
	}
}