Decompiled source of AfineQuota v1.0.2

BepInEx/plugins/FatFunT.AfineQuota.dll

Decompiled 2 hours ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization.Formatters.Binary;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Unity.Collections;
using Unity.Netcode;
using UnityEngine;

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

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

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

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

		public RefSafetyRulesAttribute(int P_0)
		{
			Version = P_0;
		}
	}
}
namespace AfineQuota
{
	[BepInPlugin("FatFunT.AfineQuota", "AfineQuota", "1.0.1")]
	public class AfineQuota : BaseUnityPlugin
	{
		public static AfineQuota Instance { get; private set; }

		internal static ManualLogSource Logger { get; private set; }

		internal static Harmony? Harmony { get; set; }

		internal static ModConfig BoundConfig { get; private set; }

		private void Awake()
		{
			Logger = ((BaseUnityPlugin)this).Logger;
			Instance = this;
			Patch();
			BoundConfig = new ModConfig(((BaseUnityPlugin)this).Config);
			Logger.LogInfo((object)"FatFunT.AfineQuota v1.0.1 has loaded!");
		}

		internal static void Patch()
		{
			//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)
			//IL_0017: Expected O, but got Unknown
			if (Harmony == null)
			{
				Harmony = new Harmony("FatFunT.AfineQuota");
			}
			Logger.LogDebug((object)"Patching...");
			Harmony.PatchAll();
			Logger.LogDebug((object)"Finished patching!");
		}

		internal static void Unpatch()
		{
			Logger.LogDebug((object)"Unpatching...");
			Harmony? harmony = Harmony;
			if (harmony != null)
			{
				harmony.UnpatchSelf();
			}
			Logger.LogDebug((object)"Finished unpatching!");
		}
	}
	[Serializable]
	internal class ModConfig : SyncedInstance<ModConfig>
	{
		public readonly ConfigEntry<int> Deadlinemin;

		public readonly ConfigEntry<int> Deadlinemax;

		public readonly ConfigEntry<int> QuotaCeiling;

		public readonly ConfigEntry<float> Scale;

		public readonly ConfigEntry<int> FlatMin;

		public readonly ConfigEntry<int> FlatMax;

		public ModConfig(ConfigFile cfg)
		{
			InitInstance(this);
			cfg.SaveOnConfigSet = false;
			Deadlinemin = cfg.Bind<int>("Deadline Min", "deadlinemin", 3, "Minimum day for deadline.");
			Deadlinemax = cfg.Bind<int>("Deadline Max", "deadlinemax", 4, "Maximum day for deadline.");
			QuotaCeiling = cfg.Bind<int>("Day Ceiling", "dayceiling", 6, "Day at which the quota is going to start to soften.");
			Scale = cfg.Bind<float>("Scaling", "scaling", 11f, "Scaling of the softening [Lower values soften the quota increase harder].");
			ClearOrphanedEntries(cfg);
			cfg.Save();
			cfg.SaveOnConfigSet = true;
		}

		private static void ClearOrphanedEntries(ConfigFile cfg)
		{
			PropertyInfo propertyInfo = AccessTools.Property(typeof(ConfigFile), "OrphanedEntries");
			Dictionary<ConfigDefinition, string> dictionary = (Dictionary<ConfigDefinition, string>)propertyInfo.GetValue(cfg);
			dictionary.Clear();
		}

		public static void RequestSync()
		{
			//IL_0022: Unknown result type (might be due to invalid IL or missing references)
			if (!SyncedInstance<ModConfig>.IsClient)
			{
				return;
			}
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(SyncedInstance<ModConfig>.IntSize, (Allocator)2, -1);
			try
			{
				SyncedInstance<ModConfig>.MessageManager.SendNamedMessage("ModName_OnRequestConfigSync", 0uL, val, (NetworkDelivery)3);
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

		public static void OnRequestSync(ulong clientId, FastBufferReader _)
		{
			//IL_0050: 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_0072: Unknown result type (might be due to invalid IL or missing references)
			if (!SyncedInstance<ModConfig>.IsHost)
			{
				return;
			}
			AfineQuota.Logger.LogInfo((object)$"Config sync request received from client: {clientId}");
			byte[] array = SyncedInstance<ModConfig>.SerializeToBytes(SyncedInstance<ModConfig>.Instance);
			int num = array.Length;
			int num2 = FastBufferWriter.GetWriteSize<byte>(array, -1, 0) + SyncedInstance<ModConfig>.IntSize;
			FastBufferWriter val = default(FastBufferWriter);
			((FastBufferWriter)(ref val))..ctor(num2, (Allocator)2, -1);
			try
			{
				((FastBufferWriter)(ref val)).WriteValueSafe<int>(ref num, default(ForPrimitives));
				((FastBufferWriter)(ref val)).WriteBytesSafe(array, -1, 0);
				SyncedInstance<ModConfig>.MessageManager.SendNamedMessage("ModName_OnReceiveConfigSync", clientId, val, (NetworkDelivery)3);
			}
			catch (Exception arg)
			{
				AfineQuota.Logger.LogInfo((object)$"Error occurred syncing config with client: {clientId}\n{arg}");
			}
			finally
			{
				((IDisposable)(FastBufferWriter)(ref val)).Dispose();
			}
		}

		public static void OnReceiveSync(ulong _, FastBufferReader reader)
		{
			//IL_0024: Unknown result type (might be due to invalid IL or missing references)
			//IL_002a: Unknown result type (might be due to invalid IL or missing references)
			if (!((FastBufferReader)(ref reader)).TryBeginRead(SyncedInstance<ModConfig>.IntSize))
			{
				AfineQuota.Logger.LogError((object)"Config sync error: Could not begin reading buffer.");
				return;
			}
			int num = default(int);
			((FastBufferReader)(ref reader)).ReadValueSafe<int>(ref num, default(ForPrimitives));
			if (!((FastBufferReader)(ref reader)).TryBeginRead(num))
			{
				AfineQuota.Logger.LogError((object)"Config sync error: Host could not sync.");
				return;
			}
			byte[] data = new byte[num];
			((FastBufferReader)(ref reader)).ReadBytesSafe(ref data, num, 0);
			SyncedInstance<ModConfig>.SyncInstance(data);
			AfineQuota.Logger.LogInfo((object)"Successfully synced config with host.");
		}
	}
	[HarmonyPatch(typeof(TimeOfDay), "Awake")]
	internal class QuotaPatch
	{
		private static void Postfix(TimeOfDay __instance)
		{
			if (__instance.quotaVariables != null)
			{
				AfineQuota.Logger.LogInfo((object)"quota deadline initiated.");
				__instance.quotaVariables.deadlineDaysAmount = 1;
			}
		}
	}
	[HarmonyPatch(typeof(TimeOfDay), "SetNewProfitQuota")]
	internal class OnQuotaPatch
	{
		private static void Prefix(TimeOfDay __instance)
		{
			if (__instance.quotaVariables != null)
			{
				int num = Random.Range(AfineQuota.BoundConfig.Deadlinemin.Value, AfineQuota.BoundConfig.Deadlinemax.Value);
				AfineQuota.Logger.LogInfo((object)$"quota deadline random: {num}");
				__instance.quotaVariables.deadlineDaysAmount = num;
			}
		}
	}
	[HarmonyPatch(typeof(TimeOfDay), "SetNewProfitQuota")]
	internal class QuotaCalculation
	{
		private static void Prefix(TimeOfDay __instance, out int __state)
		{
			__state = __instance.profitQuota;
		}

		private static void Postfix(TimeOfDay __instance, ref int __state)
		{
			int num = __state;
			int profitQuota = __instance.profitQuota;
			int timesFulfilledQuota = __instance.timesFulfilledQuota;
			int value = AfineQuota.BoundConfig.QuotaCeiling.Value;
			float value2 = AfineQuota.BoundConfig.Scale.Value;
			if (timesFulfilledQuota > value)
			{
				float num2 = timesFulfilledQuota - value;
				float num3 = profitQuota - num;
				float num4 = num3 / (1f + Mathf.Pow(num2 / value2, 2f));
				__instance.profitQuota = Mathf.RoundToInt((float)num + num4);
			}
		}
	}
	[Serializable]
	public class SyncedInstance<T>
	{
		[NonSerialized]
		protected static int IntSize = 4;

		internal static CustomMessagingManager MessageManager => NetworkManager.Singleton.CustomMessagingManager;

		internal static bool IsClient => NetworkManager.Singleton.IsClient;

		internal static bool IsHost => NetworkManager.Singleton.IsHost;

		public static T Default { get; private set; }

		public static T Instance { get; private set; }

		public static bool Synced { get; internal set; }

		protected void InitInstance(T instance)
		{
			Default = instance;
			Instance = instance;
			IntSize = 4;
		}

		internal static void SyncInstance(byte[] data)
		{
			Instance = DeserializeFromBytes(data);
			Synced = true;
		}

		internal static void RevertSync()
		{
			Instance = Default;
			Synced = false;
		}

		public static byte[] SerializeToBytes(T val)
		{
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			using MemoryStream memoryStream = new MemoryStream();
			try
			{
				binaryFormatter.Serialize(memoryStream, val);
				return memoryStream.ToArray();
			}
			catch (Exception arg)
			{
				AfineQuota.Logger.LogError((object)$"Error serializing instance: {arg}");
				return null;
			}
		}

		public static T DeserializeFromBytes(byte[] data)
		{
			BinaryFormatter binaryFormatter = new BinaryFormatter();
			using MemoryStream serializationStream = new MemoryStream(data);
			try
			{
				return (T)binaryFormatter.Deserialize(serializationStream);
			}
			catch (Exception arg)
			{
				AfineQuota.Logger.LogError((object)$"Error deserializing instance: {arg}");
				return default(T);
			}
		}
	}
	public static class MyPluginInfo
	{
		public const string PLUGIN_GUID = "FatFunT.AfineQuota";

		public const string PLUGIN_NAME = "AfineQuota";

		public const string PLUGIN_VERSION = "1.0.1";
	}
}
namespace System.Runtime.CompilerServices
{
	[AttributeUsage(AttributeTargets.Assembly, AllowMultiple = true)]
	internal sealed class IgnoresAccessChecksToAttribute : Attribute
	{
		public IgnoresAccessChecksToAttribute(string assemblyName)
		{
		}
	}
}