Decompiled source of RaftResourceMultiplier v0.1.5

patchers/RaftResourceMultiplier.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("RaftResourceMultiplier.Patcher")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.3.0")]
[assembly: AssemblyInformationalVersion("0.1.3+d82f2ca6059878300f514f00e50a68d52ea1484c")]
[assembly: AssemblyProduct("RaftResourceMultiplier.Patcher")]
[assembly: AssemblyTitle("RaftResourceMultiplier.Patcher")]
[assembly: AssemblyVersion("0.1.3.0")]
namespace RaftResourceMultiplier.Preloader;

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

	public static void Patch(AssemblyDefinition assembly)
	{
		//IL_0021: Unknown result type (might be due to invalid IL or missing references)
		//IL_0027: Expected O, but got Unknown
		//IL_017a: Unknown result type (might be due to invalid IL or missing references)
		//IL_01a0: Expected O, but got Unknown
		//IL_01bf: Unknown result type (might be due to invalid IL or missing references)
		//IL_01e5: Expected O, but got Unknown
		//IL_01fd: Unknown result type (might be due to invalid IL or missing references)
		//IL_020e: Expected O, but got Unknown
		//IL_0275: Unknown result type (might be due to invalid IL or missing references)
		//IL_028d: Unknown result type (might be due to invalid IL or missing references)
		//IL_02da: Unknown result type (might be due to invalid IL or missing references)
		//IL_02e7: Unknown result type (might be due to invalid IL or missing references)
		//IL_037d: Unknown result type (might be due to invalid IL or missing references)
		//IL_038a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0441: Unknown result type (might be due to invalid IL or missing references)
		//IL_045b: Unknown result type (might be due to invalid IL or missing references)
		//IL_046a: Unknown result type (might be due to invalid IL or missing references)
		//IL_0479: Unknown result type (might be due to invalid IL or missing references)
		//IL_0486: Unknown result type (might be due to invalid IL or missing references)
		//IL_0493: Unknown result type (might be due to invalid IL or missing references)
		//IL_04a0: Unknown result type (might be due to invalid IL or missing references)
		//IL_04ba: Unknown result type (might be due to invalid IL or missing references)
		//IL_04c9: Unknown result type (might be due to invalid IL or missing references)
		//IL_04d9: Unknown result type (might be due to invalid IL or missing references)
		ModuleDefinition mainModule = assembly.MainModule;
		TypeDefinition val = new TypeDefinition("RaftResourceMultiplier", "GameCallbacks", (TypeAttributes)385, mainModule.TypeSystem.Object);
		MethodDefinition val2 = Find(mainModule, "Pickup", "AddItemToInventory");
		MethodDefinition val3 = Find(mainModule, "HarvestableTree", "Harvest");
		MethodDefinition val4 = Find(mainModule, "ObjectSpawner_RaftDirection", "SpawnNewItems");
		MethodDefinition val5 = Find(mainModule, "GameManager", "OnWorldRecieved");
		MethodDefinition val6 = Find(mainModule, "Raft_Network", "CleanupState");
		MethodDefinition val7 = Find(mainModule, "Raft_Network", "SendWorld");
		MethodDefinition val8 = Find(mainModule, "Raft_Network", "OnDataMessageReceived");
		Instruction[] array = RewardCalls(val2, "System.String", 2);
		Instruction val9 = RewardCalls(val2, "ItemInstance", 1).Single();
		Instruction[] array2 = RewardCalls(val3, "System.String", 2);
		Instruction val10 = ((IEnumerable<Instruction>)val4.Body.Instructions).Single(delegate(Instruction i)
		{
			object operand = i.Operand;
			MethodReference val17 = (MethodReference)((operand is MethodReference) ? operand : null);
			return val17 != null && ((MemberReference)val17).Name == "GetRandomValue" && ((MemberReference)((MemberReference)val17).DeclaringType).FullName == "Interval`1<System.Int32>";
		});
		MethodDefinition[] array3 = (MethodDefinition[])(object)new MethodDefinition[7] { val2, val3, val4, val5, val6, val7, val8 };
		for (int num = 0; num < array3.Length; num++)
		{
			MethodBodyRocks.SimplifyMacros(array3[num].Body);
		}
		mainModule.Types.Add(val);
		TypeReference type = (TypeReference)(object)mainModule.GetType("PlayerInventory");
		ReplaceRewards(val2, array, AddCallback(val, "PickupNamed", (MethodReference)array[0].Operand, type, ((ParameterReference)((MethodReference)val2).Parameters[0]).ParameterType), passPickup: true);
		ReplaceRewards(val2, (Instruction[])(object)new Instruction[1] { val9 }, AddCallback(val, "PickupInstance", (MethodReference)val9.Operand, type, ((ParameterReference)((MethodReference)val2).Parameters[0]).ParameterType), passPickup: true);
		ReplaceRewards(val3, array2, AddCallback(val, "TreeReward", (MethodReference)array2[0].Operand, type), passPickup: false);
		MethodDefinition val11 = AddCallback(val, "ScaleSpawn", mainModule.TypeSystem.Int32, (TypeReference[])(object)new TypeReference[2]
		{
			mainModule.TypeSystem.Int32,
			(TypeReference)val4.DeclaringType
		}, delegate(ILProcessor il)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			il.Emit(OpCodes.Ldarg_0);
		});
		ILProcessor iLProcessor = val4.Body.GetILProcessor();
		Instruction val12 = Instruction.Create(OpCodes.Ldarg_0);
		iLProcessor.InsertAfter(val10, val12);
		iLProcessor.InsertAfter(val12, Instruction.Create(OpCodes.Call, (MethodReference)(object)val11));
		MethodDefinition val13 = AddCallback(val, "PickupEntered", mainModule.TypeSystem.Void, (TypeReference[])(object)new TypeReference[1] { ((ParameterReference)((MethodReference)val2).Parameters[0]).ParameterType });
		InsertEntry(val2, Instruction.Create(OpCodes.Ldarg_1), Instruction.Create(OpCodes.Call, (MethodReference)(object)val13));
		InsertAtReturns(val5, (MethodReference)(object)AddCallback(val, "WorldReceived", mainModule.TypeSystem.Void, Array.Empty<TypeReference>()));
		InsertAtReturns(val6, (MethodReference)(object)AddCallback(val, "SessionReset", mainModule.TypeSystem.Void, Array.Empty<TypeReference>()));
		MethodDefinition val14 = AddCallback(val, "SendWorld", mainModule.TypeSystem.Void, (TypeReference[])(object)new TypeReference[1] { ((ParameterReference)((MethodReference)val7).Parameters[0]).ParameterType });
		InsertEntry(val7, Instruction.Create(OpCodes.Ldarg_1), Instruction.Create(OpCodes.Call, (MethodReference)(object)val14));
		MethodDefinition val15 = AddCallback(val, "ReceivePacket", mainModule.TypeSystem.Boolean, (TypeReference[])(object)new TypeReference[4]
		{
			(TypeReference)val8.DeclaringType,
			((ParameterReference)((MethodReference)val8).Parameters[1]).ParameterType,
			((ParameterReference)((MethodReference)val8).Parameters[2]).ParameterType,
			((ParameterReference)((MethodReference)val8).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 val16 = val8.Body.Instructions[0];
		InsertEntry(val8, Instruction.Create(OpCodes.Ldarg, ((MethodReference)val8).Parameters[3]), Instruction.Create(OpCodes.Ldc_I4, 15), Instruction.Create(OpCodes.Bne_Un, val16), Instruction.Create(OpCodes.Ldarg_0), Instruction.Create(OpCodes.Ldarg_2), Instruction.Create(OpCodes.Ldarg_3), Instruction.Create(OpCodes.Ldarg, ((MethodReference)val8).Parameters[3]), Instruction.Create(OpCodes.Call, (MethodReference)(object)val15), Instruction.Create(OpCodes.Brtrue, val16), 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);
	}

	private static Instruction[] RewardCalls(MethodDefinition target, string argument, int expectedCount)
	{
		Instruction[] array = ((IEnumerable<Instruction>)target.Body.Instructions).Where(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)
			if (i.OpCode == OpCodes.Callvirt)
			{
				object operand = i.Operand;
				MethodReference val = (MethodReference)((operand is MethodReference) ? operand : null);
				if (val != null && ((MemberReference)val).Name == "AddItem" && ((MemberReference)((MemberReference)val).DeclaringType).Name == "Inventory" && val.Parameters.Count == 2)
				{
					return ((MemberReference)((ParameterReference)val.Parameters[0]).ParameterType).FullName == argument;
				}
			}
			return false;
		}).ToArray();
		if (array.Length != expectedCount)
		{
			throw new InvalidOperationException("Unexpected reward calls in " + ((MemberReference)target).FullName + ".");
		}
		return array;
	}

	private static void ReplaceRewards(MethodDefinition target, Instruction[] calls, MethodDefinition callback, bool passPickup)
	{
		//IL_0040: Unknown result type (might be due to invalid IL or missing references)
		//IL_001a: Unknown result type (might be due to invalid IL or missing references)
		//IL_002d: Unknown result type (might be due to invalid IL or missing references)
		ILProcessor iLProcessor = target.Body.GetILProcessor();
		foreach (Instruction val in calls)
		{
			if (passPickup)
			{
				val.OpCode = OpCodes.Ldarg_1;
				val.Operand = null;
				iLProcessor.InsertAfter(val, Instruction.Create(OpCodes.Call, (MethodReference)(object)callback));
			}
			else
			{
				val.OpCode = OpCodes.Call;
				val.Operand = callback;
			}
		}
	}

	private static MethodDefinition AddCallback(TypeDefinition owner, string name, MethodReference vanilla, TypeReference inventory, params TypeReference[] context)
	{
		TypeReference[] parameters = ((IEnumerable<TypeReference>)(object)new TypeReference[1] { inventory }).Concat(((IEnumerable<ParameterDefinition>)vanilla.Parameters).Select((ParameterDefinition p) => ((ParameterReference)p).ParameterType)).Concat(context).ToArray();
		return AddCallback(owner, name, vanilla.ReturnType, parameters, delegate(ILProcessor il)
		{
			//IL_0001: Unknown result type (might be due to invalid IL or missing references)
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0017: Unknown result type (might be due to invalid IL or missing references)
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			il.Emit(OpCodes.Ldarg_0);
			il.Emit(OpCodes.Ldarg_1);
			il.Emit(OpCodes.Ldarg_2);
			il.Emit(OpCodes.Callvirt, vanilla);
		});
	}

	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/RaftResourceMultiplier.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("RaftResourceMultiplier")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.5.0")]
[assembly: AssemblyInformationalVersion("0.1.5+d82f2ca6059878300f514f00e50a68d52ea1484c")]
[assembly: AssemblyProduct("RaftResourceMultiplier")]
[assembly: AssemblyTitle("RaftResourceMultiplier")]
[assembly: AssemblyVersion("0.1.5.0")]
namespace RaftResourceMultiplier;

internal readonly struct Multipliers
{
	internal static readonly Multipliers Vanilla = new Multipliers(100, 100, 100);

	internal int Spawn { get; }

	internal int Flotsam { get; }

	internal int Harvest { get; }

	internal Multipliers(int spawn, int flotsam, int harvest)
	{
		Spawn = spawn;
		Flotsam = flotsam;
		Harvest = harvest;
	}
}
internal sealed class FractionalAmounts<TKey>
{
	private readonly Dictionary<TKey, int> remainders = new Dictionary<TKey, int>();

	internal int Scale(TKey key, int amount, int percent)
	{
		if (amount <= 0 || percent == 100)
		{
			return amount;
		}
		remainders.TryGetValue(key, out var value);
		long num = (long)amount * (long)percent + value;
		remainders[key] = (int)(num % 100);
		return (int)Math.Min(num / 100, 2147483647L);
	}

	internal void Clear()
	{
		remainders.Clear();
	}
}
[BepInPlugin("dev.yudle.raftresourcemultiplier", "Raft Resource Multiplier", "0.1.5")]
[BepInProcess("Raft.exe")]
public sealed class Plugin : BaseUnityPlugin
{
	internal const string PluginGuid = "dev.yudle.raftresourcemultiplier";

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

	private readonly ManualLogSource logger;

	private readonly ConfigEntry<float> spawn;

	private readonly ConfigEntry<float> flotsam;

	private readonly ConfigEntry<float> harvest;

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

	internal static MultiplierRuntime Instance { get; private set; }

	private MultiplierRuntime(ConfigFile config, ManualLogSource logger)
	{
		this.config = config;
		this.logger = logger;
		spawn = BindMultiplier("FlotsamSpawn", "Ocean flotsam spawn attempts per wave.");
		flotsam = BindMultiplier("FlotsamPickup", "Rewards from the first pickup of ocean flotsam.");
		harvest = BindMultiplier("Harvest", "Rewards from chopping trees and mining with a hook.");
	}

	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;
		}
		MultiplierRuntime multiplierRuntime = (Instance = new MultiplierRuntime(config, logger));
		try
		{
			multiplierRuntime.BindGameCallbacks();
			Application.onBeforeRender += new UnityAction(SettingsSync.RequestIfNeeded);
			Application.quitting += multiplierRuntime.Shutdown;
			logger.LogInfo((object)"Raft Resource Multiplier initialized. Preloader callbacks bound for the game process.");
		}
		catch (Exception ex)
		{
			multiplierRuntime.Shutdown();
			logger.LogError((object)ex);
		}
	}

	private void BindGameCallbacks()
	{
		Type type = typeof(Pickup).Assembly.GetType("RaftResourceMultiplier.GameCallbacks");
		if (type == null)
		{
			throw new InvalidOperationException("Resource multiplier patcher is missing or failed. Install RaftResourceMultiplier.Patcher.dll in BepInEx/patchers and restart.");
		}
		foreach (KeyValuePair<string, Delegate> item in new Dictionary<string, Delegate>
		{
			["PickupNamed"] = new Func<PlayerInventory, string, int, PickupItem, int>(RewardPatches.AddPickupReward),
			["PickupInstance"] = new Action<PlayerInventory, ItemInstance, bool, PickupItem>(RewardPatches.AddPickupInstance),
			["TreeReward"] = new Func<PlayerInventory, string, int, int>(RewardPatches.AddTreeReward),
			["ScaleSpawn"] = new Func<int, ObjectSpawner_RaftDirection, int>(SpawnPatch.ScaleSpawn),
			["PickupEntered"] = new Action<PickupItem>(RewardPatches.PickupEntered),
			["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 preloader callback " + item.Key + ". Install the matching patcher version.");
			fieldInfo.SetValue(null, item.Value);
			boundFields.Add(fieldInfo);
		}
	}

	private void ClearGameCallbacks()
	{
		foreach (FieldInfo boundField in boundFields)
		{
			boundField.SetValue(null, null);
		}
		boundFields.Clear();
	}

	private ConfigEntry<float> BindMultiplier(string key, string description)
	{
		//IL_0030: Unknown result type (might be due to invalid IL or missing references)
		//IL_003a: Expected O, but got Unknown
		return config.Bind<float>("Multipliers", key, 1f, new ConfigDescription(description + " The host's settings are loaded when a world opens, at 0.01 precision.", (AcceptableValueBase)(object)new AcceptableValueRange<float>(0.2f, 5f), Array.Empty<object>()));
	}

	internal Multipliers ReadSettings()
	{
		config.Reload();
		Multipliers result = new Multipliers(ToPercent(spawn.Value), ToPercent(flotsam.Value), ToPercent(harvest.Value));
		logger.LogInfo((object)$"Host settings loaded: spawn {(float)result.Spawn / 100f:0.##}x, flotsam pickup {(float)result.Flotsam / 100f:0.##}x, harvest {(float)result.Harvest / 100f:0.##}x.");
		return result;
	}

	internal void LogPickup(string itemName, string source, int original, int scaled)
	{
		logger.LogInfo((object)$"Pickup {itemName}: {source}, {original} -> {scaled}.");
	}

	internal void LogPickupEntered(PickupItem item)
	{
		logger.LogInfo((object)$"Pickup path called: {((Object)item).name}, tag {((Component)item).tag}, dropped {item.isDropped}.");
	}

	internal void LogSynced(Multipliers settings)
	{
		logger.LogInfo((object)$"Host settings received: flotsam pickup {(float)settings.Flotsam / 100f:0.##}x, harvest {(float)settings.Harvest / 100f:0.##}x.");
	}

	private static int ToPercent(float multiplier)
	{
		if (!float.IsNaN(multiplier))
		{
			return (int)Math.Round(multiplier * 100f, MidpointRounding.AwayFromZero);
		}
		return 100;
	}

	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;
		ClearGameCallbacks();
		SettingsSync.Reset();
		Instance = null;
	}
}
internal static class RewardPatches
{
	private static readonly FractionalAmounts<string> Flotsam = new FractionalAmounts<string>();

	private static readonly FractionalAmounts<string> Harvest = new FractionalAmounts<string>();

	private static int pickupLogs;

	private static int pickupPathLogs;

	internal static void Reset()
	{
		Flotsam.Clear();
		Harvest.Clear();
		pickupLogs = 0;
		pickupPathLogs = 0;
	}

	private static int ScalePickup(PickupItem pickup, string itemName, int amount)
	{
		//IL_0086: Unknown result type (might be due to invalid IL or missing references)
		if (pickup.isDropped)
		{
			return LogReward(itemName, "player drop", amount, amount);
		}
		if (((Component)pickup).CompareTag("PickupHook"))
		{
			return LogReward(itemName, "hook harvest", amount, Harvest.Scale(itemName, amount, SettingsSync.Current.Harvest));
		}
		PickupItem_Networked val = pickup.networkID;
		if ((Object)(object)val == (Object)null)
		{
			val = ((Component)pickup).GetComponent<PickupItem_Networked>();
		}
		ObjectSpawner val2 = (((Object)(object)val != (Object)null) ? val.spawner : null);
		bool flag = val2 is ObjectSpawner_RaftDirection || ((Object)(object)val2 == (Object)null && (int)pickup.pickupItemType == 0 && (Object)(object)((Component)pickup).GetComponent<WaterFloatSemih2>() != (Object)null);
		int scaled = (flag ? Flotsam.Scale(itemName, amount, SettingsSync.Current.Flotsam) : amount);
		return LogReward(itemName, flag ? "flotsam" : "other", amount, scaled);
	}

	private static int LogReward(string itemName, string source, int amount, int scaled)
	{
		if (pickupLogs < 8)
		{
			pickupLogs++;
			MultiplierRuntime.Instance.LogPickup(itemName, source, amount, scaled);
		}
		return scaled;
	}

	internal static int AddPickupReward(PlayerInventory inventory, string itemName, int amount, PickupItem pickup)
	{
		return ((Inventory)inventory).AddItem(itemName, ScalePickup(pickup, itemName, amount));
	}

	internal static void AddPickupInstance(PlayerInventory inventory, ItemInstance item, bool dropIfFull, PickupItem pickup)
	{
		int num = ScalePickup(pickup, item.UniqueName, item.Amount);
		if (num != 0)
		{
			if (num != item.Amount)
			{
				item = item.Clone();
				item.Amount = num;
			}
			((Inventory)inventory).AddItem(item, dropIfFull);
		}
	}

	internal static int AddTreeReward(PlayerInventory inventory, string itemName, int amount)
	{
		return ((Inventory)inventory).AddItem(itemName, Harvest.Scale(itemName, amount, SettingsSync.Current.Harvest));
	}

	internal static void PickupEntered(PickupItem item)
	{
		if ((Object)(object)item != (Object)null && pickupPathLogs < 8)
		{
			pickupPathLogs++;
			MultiplierRuntime.Instance.LogPickupEntered(item);
		}
	}
}
internal static class SettingsSync
{
	private static Multipliers? settings;

	private static float nextRequest;

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

	internal static void Reset()
	{
		settings = null;
		nextRequest = 0f;
		SpawnPatch.Reset();
		RewardPatches.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(0, 0));
			}
		}
	}

	private static void SendHostSettings(Network_UserId recipient)
	{
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		Multipliers current = Current;
		SendTo(recipient, SettingsPacket.Create(current.Flotsam, current.Harvest));
	}

	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 id)
	{
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		if (Raft_Network.IsHost)
		{
			SendHostSettings(id);
		}
	}

	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_004d: 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_003e: Unknown result type (might be due to invalid IL or missing references)
		if (!SettingsPacket.TryRead(ptr, size, out var flotsam, out var harvest))
		{
			return true;
		}
		if (!network.IsConnectedToHost || GameManager.IsLeavingGame)
		{
			return false;
		}
		Network_UserId val = Network_UserId.op_Implicit(from.EntityKey.Id);
		if (Raft_Network.IsHost && flotsam == 0 && harvest == 0)
		{
			SendHostSettings(val);
		}
		else if (!Raft_Network.IsHost && val == network.HostID && !settings.HasValue && flotsam >= 20 && flotsam <= 500 && harvest >= 20 && harvest <= 500)
		{
			settings = new Multipliers(100, flotsam, harvest);
			MultiplierRuntime.Instance.LogSynced(settings.Value);
		}
		return false;
	}
}
internal static class SettingsPacket
{
	private static readonly byte[] Header = new byte[11]
	{
		224, 38, 1, 1, 0, 0, 0, 89, 82, 77,
		1
	};

	internal static byte[] Create(int flotsam, int harvest)
	{
		byte[] array = new byte[Header.Length + 4];
		Header.CopyTo(array, 0);
		array[Header.Length] = (byte)flotsam;
		array[Header.Length + 1] = (byte)(flotsam >> 8);
		array[Header.Length + 2] = (byte)harvest;
		array[Header.Length + 3] = (byte)(harvest >> 8);
		return array;
	}

	internal static bool TryRead(IntPtr packet, uint size, out int flotsam, out int harvest)
	{
		flotsam = (harvest = 0);
		if (size != Header.Length + 4 || packet == IntPtr.Zero)
		{
			return false;
		}
		for (int i = 0; i < Header.Length; i++)
		{
			if (Marshal.ReadByte(packet, i) != Header[i])
			{
				return false;
			}
		}
		flotsam = Marshal.ReadByte(packet, Header.Length) | (Marshal.ReadByte(packet, Header.Length + 1) << 8);
		harvest = Marshal.ReadByte(packet, Header.Length + 2) | (Marshal.ReadByte(packet, Header.Length + 3) << 8);
		return true;
	}
}
internal static class SpawnPatch
{
	private static readonly FractionalAmounts<ObjectSpawner_RaftDirection> Amounts = new FractionalAmounts<ObjectSpawner_RaftDirection>();

	internal static void Reset()
	{
		Amounts.Clear();
	}

	internal static bool IsFlotsamSpawner(ObjectSpawner spawner)
	{
		ObjectSpawnerManager value = ComponentManager<ObjectSpawnerManager>.Value;
		if ((Object)(object)spawner != (Object)null && (Object)(object)value != (Object)null)
		{
			if (!((Object)(object)spawner == (Object)(object)value.plankSpawner))
			{
				return (Object)(object)spawner == (Object)(object)value.itemSpawner;
			}
			return true;
		}
		return false;
	}

	internal static int ScaleSpawn(int amount, ObjectSpawner_RaftDirection spawner)
	{
		int spawn = SettingsSync.Current.Spawn;
		if (spawn == 100 || !IsFlotsamSpawner((ObjectSpawner)(object)spawner))
		{
			return amount;
		}
		int num = Amounts.Scale(spawner, amount, spawn);
		if (spawner.maxSpawnedObjects >= 0)
		{
			return Math.Min(num, Math.Max(0, spawner.maxSpawnedObjects - ((ObjectSpawner)spawner).spawnedObjects.Count));
		}
		return num;
	}
}