Decompiled source of MinMaxPrices v0.1.2

plugins/MinMaxPrices/MinMaxPrices.dll

Decompiled a day ago
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using BepInEx.Logging;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using Photon.Pun;
using RepoMods.Shared;
using TMPro;
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: AssemblyCompany("saya")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.2.0")]
[assembly: AssemblyInformationalVersion("0.1.2")]
[assembly: AssemblyProduct("MinMaxPrices")]
[assembly: AssemblyTitle("MinMaxPrices")]
[assembly: AssemblyVersion("0.1.2.0")]
[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 RepoMods.Shared
{
	internal sealed class RepoConfigLocalization
	{
		[DataContract]
		private sealed class Catalog
		{
			[DataMember(Name = "sections")]
			public Translation[]? Sections { get; set; }

			[DataMember(Name = "settings")]
			public Setting[] Settings { get; set; } = Array.Empty<Setting>();

			[DataMember(Name = "toggle")]
			public Translation[]? Toggle { get; set; }
		}

		[DataContract]
		private sealed class Setting
		{
			[DataMember(Name = "section")]
			public string Section { get; set; } = string.Empty;

			[DataMember(Name = "key")]
			public string Key { get; set; } = string.Empty;

			[DataMember(Name = "label")]
			public string? Label { get; set; }

			[DataMember(Name = "choices")]
			public Translation[]? Choices { get; set; }
		}

		[DataContract]
		private sealed class Translation
		{
			[DataMember(Name = "key")]
			public string Key { get; set; } = string.Empty;

			[DataMember(Name = "label")]
			public string? Label { get; set; }
		}

		internal const string RepoConfigGuid = "nickklmao.repoconfig";

		private const string MenuLibGuid = "nickklmao.menulib";

		private static RepoConfigLocalization? _active;

		private readonly ConfigFile _config;

		private readonly ManualLogSource _log;

		private readonly Harmony _harmony;

		private readonly Catalog _catalog;

		private readonly MethodInfo _createEntries;

		private readonly Func<string, string> _displayName;

		private readonly Func<string?> _localeCode;

		private readonly Type _rowType;

		private readonly Type _labelType;

		private readonly Type _sliderType;

		private readonly Type _toggleType;

		private readonly Dictionary<Type, FieldInfo> _settingLabels;

		private readonly FieldInfo _categoryLabel;

		private readonly FieldInfo _leftToggle;

		private readonly FieldInfo _rightToggle;

		private readonly FieldInfo _sliderValue;

		private readonly FieldInfo _sliderText;

		private readonly FieldInfo _maskedSliderText;

		private readonly PropertyInfo _sliderOptions;

		private readonly MethodInfo _updateSliderText;

		private readonly ConditionalWeakTable<Component, Translation[]> _choices = new ConditionalWeakTable<Component, Translation[]>();

		private bool _failed;

		private RepoConfigLocalization(BaseUnityPlugin plugin, Catalog catalog, Assembly repoConfig, Assembly menuLib, Func<string?> localeCode)
		{
			//IL_005d: Unknown result type (might be due to invalid IL or missing references)
			//IL_0067: Expected O, but got Unknown
			_config = plugin.Config;
			_log = Logger.CreateLogSource(plugin.Info.Metadata.Name + " REPOConfig");
			_harmony = new Harmony(plugin.Info.Metadata.GUID + ".repoconfig-localization");
			_catalog = catalog;
			_localeCode = localeCode;
			Type type = repoConfig.GetType("REPOConfig.ConfigMenu", throwOnError: true);
			_createEntries = Method(type, "CreateModEntries", MenuType(menuLib, "REPOPopupPage"), typeof(ConfigEntryBase[]));
			_displayName = (Func<string, string>)Method(type, "FixNaming", typeof(string)).CreateDelegate(typeof(Func<string, string>));
			_rowType = MenuType(menuLib, "REPOElement");
			_labelType = MenuType(menuLib, "REPOLabel");
			_sliderType = MenuType(menuLib, "REPOSlider");
			_toggleType = MenuType(menuLib, "REPOToggle");
			Type type2 = MenuType(menuLib, "REPOInputField");
			_settingLabels = new Dictionary<Type, FieldInfo>
			{
				[_sliderType] = Field(_sliderType, "labelTMP"),
				[_toggleType] = Field(_toggleType, "labelTMP"),
				[type2] = Field(type2, "labelTMP")
			};
			_categoryLabel = Field(_labelType, "labelTMP");
			_leftToggle = Field(_toggleType, "leftButtonTMP");
			_rightToggle = Field(_toggleType, "rightButtonTMP");
			_sliderValue = Field(_sliderType, "value");
			_sliderText = Field(_sliderType, "valueTMP");
			_maskedSliderText = Field(_sliderType, "maskedValueTMP");
			_sliderOptions = AccessTools.DeclaredProperty(_sliderType, "stringOptions") ?? throw new MissingMemberException(_sliderType.FullName, "stringOptions");
			_updateSliderText = Method(_sliderType, "UpdateBarText");
		}

		internal static void Start(BaseUnityPlugin plugin)
		{
			if (!Chainloader.PluginInfos.TryGetValue("nickklmao.repoconfig", out var value) || !Chainloader.PluginInfos.TryGetValue("nickklmao.menulib", out var value2))
			{
				return;
			}
			RepoConfigLocalization repoConfigLocalization = null;
			try
			{
				Type type = Type.GetType("UnityEngine.Localization.Settings.LocalizationSettings, Unity.Localization");
				if ((object)type == null)
				{
					return;
				}
				string path = Path.ChangeExtension(plugin.Info.Location, ".repoconfig.ja.json");
				if (!File.Exists(path))
				{
					return;
				}
				using FileStream stream = File.OpenRead(path);
				if (!(new DataContractJsonSerializer(typeof(Catalog)).ReadObject(stream) is Catalog catalog))
				{
					return;
				}
				Setting[] settings = catalog.Settings;
				if (settings != null && settings.Length > 0)
				{
					repoConfigLocalization = new RepoConfigLocalization(plugin, catalog, ((object)value.Instance).GetType().Assembly, ((object)value2.Instance).GetType().Assembly, CreateLocaleReader(type));
					repoConfigLocalization._harmony.Patch((MethodBase)repoConfigLocalization._createEntries, (HarmonyMethod)null, Hook("AfterCreateEntries"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					if (catalog.Settings.Any(delegate(Setting setting)
					{
						Translation[] choices = setting.Choices;
						return choices != null && choices.Length > 0;
					}))
					{
						repoConfigLocalization._harmony.Patch((MethodBase)repoConfigLocalization._updateSliderText, (HarmonyMethod)null, Hook("AfterUpdateSliderText"), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
					}
					_active = repoConfigLocalization;
				}
			}
			catch (Exception ex)
			{
				if (repoConfigLocalization != null)
				{
					repoConfigLocalization._harmony.UnpatchSelf();
				}
				(repoConfigLocalization?._log ?? Logger.CreateLogSource(plugin.Info.Metadata.Name + " REPOConfig")).LogWarning((object)("Localization could not start (" + ex.GetType().Name + "); using REPOConfig defaults."));
			}
		}

		internal static void Stop()
		{
			RepoConfigLocalization? active = _active;
			_active = null;
			if (active != null)
			{
				active._harmony.UnpatchSelf();
			}
		}

		private static Func<string?> CreateLocaleReader(Type settings)
		{
			PropertyInfo selected = settings.GetProperty("SelectedLocale", BindingFlags.Static | BindingFlags.Public) ?? throw new MissingMemberException(settings.FullName, "SelectedLocale");
			PropertyInfo identifier = selected.PropertyType.GetProperty("Identifier") ?? throw new MissingMemberException(selected.PropertyType.FullName, "Identifier");
			PropertyInfo code = identifier.PropertyType.GetProperty("Code") ?? throw new MissingMemberException(identifier.PropertyType.FullName, "Code");
			return delegate
			{
				object value = selected.GetValue(null);
				return (value == null) ? null : (code.GetValue(identifier.GetValue(value)) as string);
			};
		}

		private static void AfterCreateEntries(Component __0, ConfigEntryBase[] __1)
		{
			RepoConfigLocalization active = _active;
			if (active == null || active._failed || __1.Length == 0 || __1[0].ConfigFile != active._config)
			{
				return;
			}
			try
			{
				string a = active._localeCode();
				if (string.Equals(a, "ja-JP", StringComparison.OrdinalIgnoreCase) || string.Equals(a, "ja", StringComparison.OrdinalIgnoreCase))
				{
					active.TranslatePage(__0, __1);
				}
			}
			catch (Exception ex)
			{
				active._failed = true;
				active._log.LogWarning((object)("Localization could not update the menu (" + ex.GetType().Name + ")."));
			}
		}

		private void TranslatePage(Component page, ConfigEntryBase[] entries)
		{
			ILookup<string, IGrouping<string, ConfigEntryBase>> lookup = (from val3 in entries
				group val3 by val3.Definition.Section).ToLookup<IGrouping<string, ConfigEntryBase>, string>((IGrouping<string, ConfigEntryBase> section) => _displayName(section.Key), StringComparer.Ordinal);
			IGrouping<string, ConfigEntryBase> grouping = null;
			Component[] componentsInChildren = page.GetComponentsInChildren(_rowType, true);
			foreach (Component val in componentsInChildren)
			{
				Type type = ((object)val).GetType();
				if (type == _labelType)
				{
					TMP_Text val2 = ReadText(_categoryLabel, val);
					if (val2 != null)
					{
						grouping = Unique(lookup[val2.text]);
						SetText(val2, FindLabel(_catalog.Sections, grouping?.Key));
						continue;
					}
				}
				if (grouping == null || !_settingLabels.TryGetValue(type, out FieldInfo value))
				{
					continue;
				}
				TMP_Text label = ReadText(value, val);
				if (label == null)
				{
					continue;
				}
				ConfigEntryBase entry = Unique(grouping.Where((ConfigEntryBase item) => _displayName(item.Definition.Key) == label.text));
				if (entry != null)
				{
					Setting setting = _catalog.Settings.FirstOrDefault((Setting item) => item.Section == entry.Definition.Section && item.Key == entry.Definition.Key);
					SetText(label, setting?.Label);
					if (type == _toggleType)
					{
						TranslateToggle(val, _leftToggle);
						TranslateToggle(val, _rightToggle);
					}
					Translation[] array = setting?.Choices;
					if (array != null && array.Length > 0 && type == _sliderType)
					{
						_choices.Add(val, array);
						_updateSliderText.Invoke(val, null);
					}
				}
			}
		}

		private void TranslateToggle(Component row, FieldInfo field)
		{
			TMP_Text val = ReadText(field, row);
			if (val != null)
			{
				SetText(val, FindLabel(_catalog.Toggle, val.text));
			}
		}

		private static void AfterUpdateSliderText(Component __instance)
		{
			RepoConfigLocalization active = _active;
			if (active != null && !active._failed && active._choices.TryGetValue(__instance, out Translation[] value) && active._sliderOptions.GetValue(__instance) is string[] array && array.Length > 0)
			{
				int num = Convert.ToInt32((float)active._sliderValue.GetValue(__instance));
				string label = FindLabel(value, (num >= 0 && num < array.Length) ? array[num] : array[0]);
				SetText(ReadText(active._sliderText, __instance), label);
				SetText(ReadText(active._maskedSliderText, __instance), label);
			}
		}

		private static T? Unique<T>(IEnumerable<T> matches) where T : class
		{
			using IEnumerator<T> enumerator = matches.GetEnumerator();
			if (!enumerator.MoveNext())
			{
				return null;
			}
			T current = enumerator.Current;
			return enumerator.MoveNext() ? null : current;
		}

		private static string? FindLabel(Translation[]? translations, string? key)
		{
			return translations?.FirstOrDefault((Translation translation) => translation.Key == key)?.Label;
		}

		private static TMP_Text? ReadText(FieldInfo field, Component row)
		{
			object? value = field.GetValue(row);
			return (TMP_Text?)((value is TMP_Text) ? value : null);
		}

		private static void SetText(TMP_Text? text, string? label)
		{
			if (text != null && !string.IsNullOrWhiteSpace(label))
			{
				text.text = label;
			}
		}

		private static Type MenuType(Assembly assembly, string name)
		{
			return assembly.GetType("MenuLib.MonoBehaviors." + name, throwOnError: true);
		}

		private static MethodInfo Method(Type type, string name, params Type[] parameters)
		{
			return AccessTools.DeclaredMethod(type, name, parameters, (Type[])null) ?? throw new MissingMethodException(type.FullName, name);
		}

		private static FieldInfo Field(Type type, string name)
		{
			return AccessTools.DeclaredField(type, name) ?? throw new MissingFieldException(type.FullName, name);
		}

		private static HarmonyMethod Hook(string name)
		{
			//IL_000c: Unknown result type (might be due to invalid IL or missing references)
			//IL_0012: Expected O, but got Unknown
			return new HarmonyMethod(typeof(RepoConfigLocalization), name, (Type[])null);
		}
	}
}
namespace MinMaxPrices
{
	internal sealed class DeferredPrices
	{
		internal sealed class Scope
		{
			internal readonly Scope? Parent;

			internal readonly List<Action> Changes = new List<Action>();

			internal bool Closed;

			internal Scope(Scope? parent)
			{
				Parent = parent;
			}
		}

		private Scope? _current;

		public Scope Begin()
		{
			return _current = new Scope(_current);
		}

		public void ApplyOrDefer(Action change)
		{
			if (_current == null)
			{
				change();
			}
			else
			{
				_current.Changes.Add(change);
			}
		}

		public void End(Scope scope, bool success)
		{
			if (scope.Closed)
			{
				return;
			}
			scope.Closed = true;
			_current = scope.Parent;
			if (!success)
			{
				return;
			}
			if (_current != null)
			{
				_current.Changes.AddRange(scope.Changes);
				return;
			}
			foreach (Action change in scope.Changes)
			{
				change();
			}
		}
	}
	[BepInPlugin("saya.MinMaxPrices", "MinMaxPrices", "0.1.2")]
	[BepInDependency(/*Could not decode attribute arguments.*/)]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string PluginGuid = "saya.MinMaxPrices";

		public const string PluginName = "MinMaxPrices";

		public const string PluginVersion = "0.1.2";

		private readonly Harmony _harmony = new Harmony("saya.MinMaxPrices");

		private static ConfigEntry<PriceMode>? _valuableMode;

		private static ConfigEntry<PriceMode>? _shopMode;

		internal static PriceMode ValuableMode => _valuableMode?.Value ?? PriceMode.Normal;

		internal static PriceMode ShopMode => _shopMode?.Value ?? PriceMode.Normal;

		internal static bool IsAuthority
		{
			get
			{
				if ((Object)(object)GameManager.instance != (Object)null)
				{
					if (GameManager.Multiplayer())
					{
						return PhotonNetwork.IsMasterClient;
					}
					return true;
				}
				return false;
			}
		}

		private void Awake()
		{
			((Component)this).transform.SetParent((Transform)null);
			((Object)((Component)this).gameObject).hideFlags = (HideFlags)61;
			Object.DontDestroyOnLoad((Object)(object)((Component)this).gameObject);
			_valuableMode = ((BaseUnityPlugin)this).Config.Bind<PriceMode>("Prices", "ValuablePrice", PriceMode.Normal, "Normal keeps random valuable prices. Min or Max selects each valuable's own range endpoint, including enemy orbs. Applies to newly spawned valuables only; damage and fixed-value rewards are unchanged. Spawn budgeting keeps the original roll, but the extraction goal follows the selected prices. Only the host's setting is used.");
			_shopMode = ((BaseUnityPlugin)this).Config.Bind<PriceMode>("Prices", "ShopPrice", PriceMode.Normal, "Normal keeps random shop prices. Min or Max selects each item's base range endpoint before vanilla multipliers and rounding. Applies to newly generated shop stock only; existing prices and carried items are unchanged. Only the host's setting is used.");
			try
			{
				_harmony.PatchAll(typeof(ValuablePricePatch));
				_harmony.PatchAll(typeof(ValuableSpawnPatch));
				_harmony.PatchAll(typeof(ShopPricePatch));
				RepoConfigLocalization.Start((BaseUnityPlugin)(object)this);
				((BaseUnityPlugin)this).Logger.LogInfo((object)string.Format("{0} v{1} loaded. ValuablePrice={2}, ShopPrice={3}.", "MinMaxPrices", "0.1.2", ValuableMode, ShopMode));
			}
			catch (Exception arg)
			{
				_harmony.UnpatchSelf();
				((Behaviour)this).enabled = false;
				((BaseUnityPlugin)this).Logger.LogError((object)$"MinMaxPrices initialization failed: {arg}");
			}
		}

		private void OnDestroy()
		{
			RepoConfigLocalization.Stop();
			_harmony.UnpatchSelf();
			_valuableMode = null;
			_shopMode = null;
		}
	}
	public enum PriceMode
	{
		Normal,
		Min,
		Max
	}
	internal static class PriceSelection
	{
		public static bool TrySelect(PriceMode mode, float minimum, float maximum, out float value)
		{
			value = 0f;
			if ((mode != PriceMode.Min && mode != PriceMode.Max) || float.IsNaN(minimum) || float.IsInfinity(minimum) || float.IsNaN(maximum) || float.IsInfinity(maximum) || minimum < 0f || maximum < minimum)
			{
				return false;
			}
			value = ((mode == PriceMode.Min) ? minimum : maximum);
			return true;
		}

		public static float RoundValuable(float value)
		{
			return (float)Math.Round((float)Math.Round(value) / 100f) * 100f;
		}
	}
	[HarmonyPatch(typeof(ItemAttributes), "GetValue")]
	internal static class ShopPricePatch
	{
		private readonly struct SavedRange
		{
			public readonly float Minimum;

			public readonly float Maximum;

			public SavedRange(float minimum, float maximum)
			{
				Minimum = minimum;
				Maximum = maximum;
			}
		}

		[HarmonyPrefix]
		private static void Prefix(bool ___shopItem, ref float ___itemValueMin, ref float ___itemValueMax, out SavedRange? __state)
		{
			__state = null;
			if (Plugin.IsAuthority && ___shopItem && PriceSelection.TrySelect(Plugin.ShopMode, ___itemValueMin, ___itemValueMax, out var value))
			{
				__state = new SavedRange(___itemValueMin, ___itemValueMax);
				___itemValueMin = value;
				___itemValueMax = value;
			}
		}

		[HarmonyFinalizer]
		private static void Finalizer(ref float ___itemValueMin, ref float ___itemValueMax, SavedRange? __state)
		{
			if (__state.HasValue)
			{
				___itemValueMin = __state.Value.Minimum;
				___itemValueMax = __state.Value.Maximum;
			}
		}
	}
	[HarmonyPatch(typeof(ValuableObject), "DollarValueSetLogic")]
	internal static class ValuablePricePatch
	{
		internal static readonly DeferredPrices Pending = new DeferredPrices();

		private static readonly FieldRef<ValuableObject, float> Original = AccessTools.FieldRefAccess<ValuableObject, float>("dollarValueOriginal");

		private static readonly FieldRef<ValuableObject, float> Current = AccessTools.FieldRefAccess<ValuableObject, float>("dollarValueCurrent");

		[HarmonyPrefix]
		private static void Prefix(ValuableObject __instance, bool ___dollarValueSet, int ___dollarValueOverride, out float? __state)
		{
			__state = null;
			if (!(!Plugin.IsAuthority || ___dollarValueSet) && ___dollarValueOverride == 0 && !((Object)(object)__instance.valuePreset == (Object)null) && PriceSelection.TrySelect(Plugin.ValuableMode, __instance.valuePreset.valueMin, __instance.valuePreset.valueMax, out var value))
			{
				__state = PriceSelection.RoundValuable(value);
			}
		}

		[HarmonyPostfix]
		private static void Postfix(ValuableObject __instance, bool ___dollarValueSet, bool __runOriginal, float? __state)
		{
			if (!__runOriginal || !___dollarValueSet || !__state.HasValue)
			{
				return;
			}
			float price = __state.Value;
			Pending.ApplyOrDefer(delegate
			{
				if (!((Object)(object)__instance == (Object)null))
				{
					Original.Invoke(__instance) = price;
					Current.Invoke(__instance) = price;
				}
			});
		}
	}
	[HarmonyPatch(typeof(ValuableDirector), "SpawnValuable")]
	internal static class ValuableSpawnPatch
	{
		[HarmonyPrefix]
		private static void Prefix(out DeferredPrices.Scope? __state)
		{
			__state = (Plugin.IsAuthority ? ValuablePricePatch.Pending.Begin() : null);
		}

		[HarmonyFinalizer]
		private static void Finalizer(DeferredPrices.Scope? __state, Exception? __exception)
		{
			if (__state != null)
			{
				ValuablePricePatch.Pending.End(__state, __exception == null);
			}
		}
	}
}