Decompiled source of Stronger Service Buildings v1.0.1

BepInEx/plugins/ServiceOverhaul/Reman.ServiceOverhaul.dll

Decompiled 2 hours 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 BepInEx;
using BepInEx.Logging;
using Eremite;
using Eremite.Buildings;
using Eremite.Characters;
using Eremite.Characters.Villagers;
using Eremite.Controller;
using Eremite.Model;
using Eremite.Model.Effects;
using Eremite.Model.State;
using Eremite.Services;
using HarmonyLib;
using Microsoft.CodeAnalysis;
using UnityEngine;
using UnityEngine.InputSystem;
using UnityEngine.InputSystem.Controls;

[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: TargetFramework(".NETFramework,Version=v4.7.2", FrameworkDisplayName = ".NET Framework 4.7.2")]
[assembly: AssemblyCompany("Reman.ServiceOverhaul")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("1.0.1.0")]
[assembly: AssemblyInformationalVersion("1.0.1+e6300c6f18070a5259bb70763d6198d48071eeee")]
[assembly: AssemblyProduct("Reman.ServiceOverhaul")]
[assembly: AssemblyTitle("Reman.ServiceOverhaul")]
[assembly: AssemblyVersion("1.0.1.0")]
[module: RefSafetyRules(11)]
namespace Microsoft.CodeAnalysis
{
	[CompilerGenerated]
	[Embedded]
	internal sealed class EmbeddedAttribute : Attribute
	{
	}
}
namespace System.Runtime.CompilerServices
{
	[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 Reman.ServiceOverhaul
{
	[BepInPlugin("reman.serviceoverhaul", "Stronger Service Buildings", "1.0.1")]
	public sealed class Plugin : BaseUnityPlugin
	{
		public const string Id = "reman.serviceoverhaul";

		internal static ManualLogSource Log;

		private float nextRefresh;

		private bool showStatus;

		private void Awake()
		{
			//IL_0010: Unknown result type (might be due to invalid IL or missing references)
			Log = ((BaseUnityPlugin)this).Logger;
			new Harmony("reman.serviceoverhaul").PatchAll(typeof(Plugin).Assembly);
			((BaseUnityPlugin)this).Logger.LogInfo((object)"Stronger Service Buildings 1.0.1 loaded. F9 shows staffing and bonus status.");
		}

		private void Update()
		{
			if (Keyboard.current != null && ((ButtonControl)Keyboard.current.f9Key).wasPressedThisFrame)
			{
				showStatus = !showStatus;
			}
			if (!(Time.unscaledTime < nextRefresh))
			{
				nextRefresh = Time.unscaledTime + 0.25f;
				if (Runtime.Ready)
				{
					Runtime.Reconcile();
				}
			}
		}

		private void OnGUI()
		{
			//IL_004c: Unknown result type (might be due to invalid IL or missing references)
			//IL_006f: Unknown result type (might be due to invalid IL or missing references)
			if (showStatus)
			{
				string[] value = Rules.Kinds.Select((string k) => k + ": " + (Runtime.Active(k) ? "ACTIVE" : "requires full staffing")).ToArray();
				GUI.Box(new Rect(16f, 130f, 460f, 365f), "Stronger Service Buildings — F9 to close");
				GUI.Label(new Rect(30f, 158f, 430f, 330f), string.Join("\n", value) + $"\n\nAcademy: +{Runtime.AcademyBonus() * 100f:0.##}% global crit\nMonastery: +{Runtime.MonasteryBonus()} Global Resolve\nOne bonus per type; normal and Hallowed copies share it.");
			}
		}
	}
	internal static class Runtime
	{
		internal static bool Configured;

		internal static readonly Dictionary<EffectModel, string> Markers = new Dictionary<EffectModel, string>();

		private static readonly Dictionary<string, EffectModel> removedBathEffects = new Dictionary<string, EffectModel>();

		private static readonly HashSet<InstitutionModel> configured = new HashSet<InstitutionModel>();

		internal static readonly HashSet<string> FoodNeeds = new HashSet<string>();

		internal static readonly HashSet<string> ComplexGoods = new HashSet<string>();

		internal static readonly HashSet<ResolveEffectModel> ClothingEffects = new HashSet<ResolveEffectModel>();

		private static IGameServices migratedGame;

		private static bool? previousTavern;

		private static int cachedFrame = -1;

		private static readonly HashSet<string> active = new HashSet<string>();

		internal static Settings Settings
		{
			get
			{
				IController instance = MainController.Instance;
				if (instance == null)
				{
					return null;
				}
				return instance.Settings;
			}
		}

		internal static IGameServices Game
		{
			get
			{
				if (!GameController.IsGameActive)
				{
					return null;
				}
				IGameController instance = GameController.Instance;
				if (instance == null)
				{
					return null;
				}
				return instance.GameServices;
			}
		}

		internal static bool Ready
		{
			get
			{
				IGameServices game = Game;
				if (game == null)
				{
					return false;
				}
				return game.Loaded;
			}
		}

		internal static void Invalidate()
		{
			cachedFrame = -1;
		}

		internal static bool Active(string kind)
		{
			if (!Ready || !Configured)
			{
				return false;
			}
			if (cachedFrame != Time.frameCount)
			{
				active.Clear();
				foreach (Institution value in Game.BuildingsService.Institutions.Values)
				{
					string text = Rules.Kind(((SO)value.model).Name);
					if (text != null && Rules.FullyStaffed(((Building)value).IsFinished(), ((BuildingState)value.state).isSleeping, ((ProductionBuilding)value).CountWorkers(), ((BuildingModel)value.model).WorkplacesCount))
					{
						active.Add(text);
					}
				}
				cachedFrame = Time.frameCount;
			}
			return active.Contains(kind);
		}

		internal static void Configure(Settings settings)
		{
			//IL_0541: Unknown result type (might be due to invalid IL or missing references)
			//IL_0546: Unknown result type (might be due to invalid IL or missing references)
			//IL_054e: Unknown result type (might be due to invalid IL or missing references)
			//IL_0565: Expected O, but got Unknown
			//IL_0511: Unknown result type (might be due to invalid IL or missing references)
			//IL_0516: Unknown result type (might be due to invalid IL or missing references)
			FoodNeeds.Clear();
			ComplexGoods.Clear();
			ClothingEffects.Clear();
			NeedModel[] needs = settings.Needs;
			foreach (NeedModel val in needs)
			{
				GoodModel referenceGood = val.referenceGood;
				if ((Object)(object)referenceGood != (Object)null && Rules.IsComplexFood(((SO)referenceGood).Name))
				{
					FoodNeeds.Add(((SO)val).Name);
					ComplexGoods.Add(((SO)referenceGood).Name);
				}
				if (!(((SO)val).Name == "Clothes") && !(((SO)val).Name == "Boots"))
				{
					NeedCategoryModel category = val.category;
					if (!(((category != null) ? ((SO)category).Name : null) == "Clothing"))
					{
						continue;
					}
				}
				ClothingEffects.Add(val.effect);
			}
			GoodModel[] goods = settings.Goods;
			foreach (GoodModel val2 in goods)
			{
				if (Rules.IsComplexFood(((SO)val2).Name))
				{
					ComplexGoods.Add(((SO)val2).Name);
				}
			}
			ResolveEffectModel[] resolveEffects = settings.resolveEffects;
			foreach (ResolveEffectModel val3 in resolveEffects)
			{
				if (((SO)val3).Name == "SE Storm Clothes - Resolve Status")
				{
					ClothingEffects.Add(val3);
				}
			}
			if (FoodNeeds.Count == 0 || ClothingEffects.Count == 0)
			{
				throw new InvalidOperationException("Need classification failed; check the game version.");
			}
			string[] kinds = Rules.Kinds;
			foreach (string kind in kinds)
			{
				if (!settings.Institutions.Any((InstitutionModel m) => Rules.Kind(((SO)m).Name) == kind))
				{
					throw new InvalidOperationException("Missing institution: " + kind);
				}
			}
			Dictionary<string, Sprite> dictionary = (from sprite in Resources.FindObjectsOfTypeAll<Sprite>()
				group sprite by ((Object)sprite).name).ToDictionary((IGrouping<string, Sprite> group) => group.Key, (IGrouping<string, Sprite> group) => group.First());
			Dictionary<string, EffectModel> dictionary2 = new Dictionary<string, EffectModel>();
			foreach (KeyValuePair<EffectModel, string> marker in Markers)
			{
				dictionary2[marker.Value] = marker.Key;
			}
			InstitutionModel[] institutions = settings.Institutions;
			foreach (InstitutionModel model in institutions)
			{
				string text = Rules.Kind(((SO)model).Name);
				if (text == null || !configured.Add(model))
				{
					continue;
				}
				InstitutionEffectModel[] activeEffects = model.activeEffects;
				Plugin.Log.LogInfo((object)string.Format("Model {0}: {1} workers; original effects: {2}", ((SO)model).Name, ((BuildingModel)model).WorkplacesCount, string.Join(", ", activeEffects.Select((InstitutionEffectModel e) => e.Name))));
				List<InstitutionEffectModel> list = ((IEnumerable<InstitutionEffectModel>)activeEffects).Select((Func<InstitutionEffectModel, InstitutionEffectModel>)((InstitutionEffectModel e) => new InstitutionEffectModel
				{
					effect = e.effect,
					minWorkers = ((BuildingModel)model).WorkplacesCount
				})).ToList();
				if (text == "Bath House")
				{
					InstitutionEffectModel[] array = list.Where((InstitutionEffectModel e) => e.Name == "Institution Slower Leaving").ToArray();
					foreach (InstitutionEffectModel val4 in array)
					{
						removedBathEffects[val4.Name] = val4.effect;
						list.Remove(val4);
					}
				}
				if (Rules.Description(text) != null)
				{
					if (!dictionary2.TryGetValue(text, out var value))
					{
						CompositeEffectModel val5 = ScriptableObject.CreateInstance<CompositeEffectModel>();
						((Object)val5).name = IdFor(text);
						val5.isPerk = false;
						((EffectModel)val5).SetIsPositive(true);
						((EffectModel)val5).frameColorByPositive = true;
						val5.rewards = (EffectModel[])(object)new EffectModel[0];
						((EffectModel)val5).blockedBy = (EffectModel[])(object)new EffectModel[0];
						((EffectModel)val5).usabilityTags = (ModelTag[])(object)new ModelTag[0];
						string text2 = Rules.EffectIconName(text);
						if (text2 != null && dictionary.TryGetValue(text2, out var value2))
						{
							((EffectModel)val5).overrideIcon = value2;
							Plugin.Log.LogInfo((object)("Effect icon for " + text + ": " + text2));
						}
						else
						{
							((EffectModel)val5).overrideIcon = ((BuildingModel)model).icon;
							Plugin.Log.LogWarning((object)("Effect icon " + text2 + " unavailable; using " + ((SO)model).Name + "'s building icon."));
						}
						((EffectModel)val5).label = activeEffects.LastOrDefault()?.effect.label;
						InstitutionEffectModel? obj = activeEffects.LastOrDefault();
						((EffectModel)val5).rarity = (EffectRarity)((obj != null) ? ((int)obj.effect.rarity) : 0);
						((EffectModel)val5).forceHideOnHUD = true;
						value = (EffectModel)(object)val5;
						Markers[value] = text;
						dictionary2[text] = value;
					}
					list.Add(new InstitutionEffectModel
					{
						effect = value,
						minWorkers = ((BuildingModel)model).WorkplacesCount
					});
				}
				model.activeEffects = list.ToArray();
			}
			Plugin.Log.LogInfo((object)$"Configured {configured.Count} service models, {FoodNeeds.Count} food needs, {ComplexGoods.Count} complex foods, {ClothingEffects.Count} clothing Resolve effects.");
			Configured = true;
		}

		private static string IdFor(string kind)
		{
			return "reman.serviceoverhaul.display." + kind.Replace(" ", "");
		}

		internal static string TooltipProgress(string kind)
		{
			if (!Ready || !Configured)
			{
				return null;
			}
			switch (kind)
			{
			case "Monastery":
				return Rules.MonasteryProgress(Game.StateService.Stats.cystsBurned);
			case "Academy":
			{
				CountCompletedEvents(out var dangerous, out var forbidden);
				return $"Expected gain: +{3 * dangerous + 5 * forbidden}%. Events: {dangerous}/{forbidden}.";
			}
			case "Feast Hall":
			case "Tea Doctor":
			{
				int num = 0;
				int num2 = 0;
				foreach (List<Villager> value in Game.VillagersService.Races.Values)
				{
					using List<Villager>.Enumerator enumerator2 = value.GetEnumerator();
					while (enumerator2.MoveNext())
					{
						switch (Rules.FoodTier(FoodCount(enumerator2.Current)))
						{
						case 1:
							num++;
							break;
						case 2:
							num2++;
							break;
						}
					}
				}
				return $"Villagers (2 / 3+ foods): {num} / {num2}.";
			}
			default:
				return null;
			}
		}

		private static void CountCompletedEvents(out int dangerous, out int forbidden)
		{
			//IL_0044: Unknown result type (might be due to invalid IL or missing references)
			//IL_004a: Invalid comparison between Unknown and I4
			//IL_0055: Unknown result type (might be due to invalid IL or missing references)
			//IL_005b: Invalid comparison between Unknown and I4
			dangerous = 0;
			forbidden = 0;
			foreach (RelicResolvedState item in Game.StateService.Stats.relicsResolved)
			{
				if (item.isGladeEvent)
				{
					RelicModel relic = Settings.GetRelic(item.model);
					if ((int)relic.dangerLevel == 2)
					{
						dangerous++;
					}
					else if ((int)relic.dangerLevel == 3)
					{
						forbidden++;
					}
				}
			}
		}

		internal static int FoodCount(Villager v)
		{
			if (v?.state?.needsfulfilled != null)
			{
				return v.state.needsfulfilled.Count(FoodNeeds.Contains);
			}
			return 0;
		}

		internal static float AcademyBonus()
		{
			if (!Active("Academy"))
			{
				return 0f;
			}
			CountCompletedEvents(out var dangerous, out var forbidden);
			return Rules.AcademyCrit(dangerous, forbidden);
		}

		internal static int MonasteryBonus()
		{
			if (!Active("Monastery"))
			{
				return 0;
			}
			return Rules.MonasteryResolve(Game.StateService.Stats.cystsBurned);
		}

		internal static int PersonalResolve(Villager v)
		{
			if (!Active("Feast Hall"))
			{
				return 0;
			}
			return 3 * Rules.FoodTier(FoodCount(v));
		}

		internal static float RaceResolve(string race)
		{
			if (!Ready || !Game.VillagersService.Races.TryGetValue(race, out var value) || value.Count == 0)
			{
				return 0f;
			}
			return (float)MonasteryBonus() + ((IEnumerable<Villager>)value).Average((Func<Villager, float>)((Villager v) => PersonalResolve(v)));
		}

		internal static float YieldBonus(Building building, string goodName)
		{
			if ((Object)(object)building == (Object)null || !Ready)
			{
				return 0f;
			}
			float num = 0f;
			bool flag = building is Camp;
			if (Active("Forum"))
			{
				if (flag)
				{
					num += 1f;
				}
				else if (Settings.GetGood(goodName).canBeBurned)
				{
					num += 0.5f;
				}
			}
			if (Active("Feast Hall") && ComplexGoods.Contains(goodName))
			{
				num += 0.5f;
			}
			if (Active("Market") && (building.BuildingModel is FarmModel || building.ModelName == "Greenhouse Workshop" || building.ModelName == "Clay Pit Workshop"))
			{
				num += 1f;
			}
			return num;
		}

		internal static void Reconcile()
		{
			if (!Configured)
			{
				return;
			}
			Invalidate();
			IGameServices game = Game;
			if (migratedGame != game)
			{
				foreach (KeyValuePair<string, EffectModel> removedBathEffect in removedBathEffects)
				{
					if (game.StateService.BuildingsEffects.activeInstitutionsEffects.Contains(removedBathEffect.Key))
					{
						removedBathEffect.Value.Remove((EffectContextType)1, "Bath House", 0);
						game.StateService.BuildingsEffects.activeInstitutionsEffects.Remove(removedBathEffect.Key);
						Plugin.Log.LogInfo((object)("Removed saved Bath House effect: " + removedBathEffect.Key));
					}
				}
				migratedGame = game;
				previousTavern = null;
			}
			foreach (Institution value in game.BuildingsService.Institutions.Values)
			{
				if (Rules.Kind(((SO)value.model).Name) != null)
				{
					game.InstitutionsService.WorkerLeft(value);
					game.InstitutionsService.WorkerJoined(value);
				}
			}
			bool flag = Active("Tavern");
			if (previousTavern != flag)
			{
				IHostilityService hostilityService = game.HostilityService;
				hostilityService.SetSource((HostilitySource)50, hostilityService.GetSourceAmount((HostilitySource)50));
				previousTavern = flag;
			}
		}
	}
	[HarmonyPatch(typeof(Settings), "SetUpContent")]
	internal static class ConfigurePatch
	{
		[HarmonyPostfix]
		[HarmonyPriority(0)]
		private static void Postfix(Settings __instance)
		{
			Dictionary<InstitutionModel, InstitutionEffectModel[]> dictionary = __instance.Institutions.ToDictionary((InstitutionModel m) => m, (InstitutionModel m) => m.activeEffects);
			try
			{
				Runtime.Configure(__instance);
			}
			catch (Exception ex)
			{
				Runtime.Configured = false;
				foreach (KeyValuePair<InstitutionModel, InstitutionEffectModel[]> item in dictionary)
				{
					item.Key.activeEffects = item.Value;
				}
				Plugin.Log.LogError((object)("Service overhaul disabled; original service models restored. " + ex));
			}
		}
	}
	[HarmonyPatch(typeof(InstitutionsService), "ShouldBeActiveFor")]
	internal static class StaffingPatch
	{
		private static bool Prefix(Institution institution, ref bool __result)
		{
			if (!Runtime.Configured || Rules.Kind(((SO)institution.model).Name) == null)
			{
				return true;
			}
			__result = Rules.FullyStaffed(((Building)institution).IsFinished(), ((BuildingState)institution.state).isSleeping, ((ProductionBuilding)institution).CountWorkers(), ((BuildingModel)institution.model).WorkplacesCount);
			return false;
		}
	}
	[HarmonyPatch]
	internal static class DisplayEffectPersistencePatch
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			yield return AccessTools.Method(typeof(InstitutionsService), "Apply", (Type[])null, (Type[])null);
			yield return AccessTools.Method(typeof(InstitutionsService), "Remove", (Type[])null, (Type[])null);
		}

		private static bool Prefix(InstitutionEffectModel effect)
		{
			return !Runtime.Markers.ContainsKey(effect.effect);
		}
	}
	[HarmonyPatch(typeof(EffectModel), "get_DisplayName")]
	internal static class DisplayNamePatch
	{
		private static bool Prefix(EffectModel __instance, ref string __result)
		{
			if (!Runtime.Markers.TryGetValue(__instance, out var value))
			{
				return true;
			}
			__result = Rules.EffectName(value);
			return false;
		}
	}
	[HarmonyPatch(typeof(CompositeEffectModel), "GetTooltipFootnote")]
	internal static class TooltipProgressPatch
	{
		private static bool Prefix(CompositeEffectModel __instance, ref string __result)
		{
			if (!Runtime.Markers.TryGetValue((EffectModel)(object)__instance, out var value))
			{
				return true;
			}
			__result = Runtime.TooltipProgress(value);
			return false;
		}
	}
	[HarmonyPatch(typeof(EffectModel), "get_Description")]
	internal static class DescriptionPatch
	{
		private static bool Prefix(EffectModel __instance, ref string __result)
		{
			if (!Runtime.Markers.TryGetValue(__instance, out var value))
			{
				return true;
			}
			__result = Rules.Description(value);
			return false;
		}
	}
	[HarmonyPatch]
	internal static class StaffingInvalidationPatch
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			yield return AccessTools.Method(typeof(InstitutionsService), "WorkerJoined", (Type[])null, (Type[])null);
			yield return AccessTools.Method(typeof(InstitutionsService), "WorkerLeft", (Type[])null, (Type[])null);
		}

		private static void Prefix()
		{
			Runtime.Invalidate();
		}
	}
	[HarmonyPatch(typeof(Villager), "GetNeedsInterval")]
	internal static class BreakIntervalPatch
	{
		private static void Postfix(Villager __instance, ref float __result)
		{
			__result *= 1f + Rules.IntervalBonus(Runtime.Active("Bath House"), Runtime.Active("Feast Hall"), Runtime.FoodCount(__instance));
		}
	}
	[HarmonyPatch(typeof(ProductionCalculator), "GetExtraProductionChance")]
	internal static class CritPatch
	{
		private static void Postfix(Actor actor, ref float __result)
		{
			if (!((Object)(object)actor == (Object)null) && actor.CanCritProduction)
			{
				__result += Runtime.AcademyBonus();
				Villager val = (Villager)(object)((actor is Villager) ? actor : null);
				if (val != null && Runtime.Active("Tea Doctor"))
				{
					__result += 0.15f * (float)Rules.FoodTier(Runtime.FoodCount(val));
				}
			}
		}
	}
	[HarmonyPatch]
	internal static class ProductionContextPatch
	{
		[ThreadStatic]
		internal static string OutputGood;

		private static IEnumerable<MethodBase> TargetMethods()
		{
			return from m in AccessTools.GetDeclaredMethods(typeof(ProductionCalculator))
				where m.Name == "GetResult"
				select m;
		}

		private static void Prefix(Good baseProduction, out string __state)
		{
			//IL_0007: Unknown result type (might be due to invalid IL or missing references)
			__state = OutputGood;
			OutputGood = baseProduction.name;
		}

		private static void Finalizer(string __state)
		{
			OutputGood = __state;
		}
	}
	[HarmonyPatch(typeof(ProductionCalculator), "GetProductionFactor")]
	internal static class YieldPatch
	{
		private static void Postfix(Building building, RecipeModel recipe, ref float __result)
		{
			string text = ProductionContextPatch.OutputGood ?? ((recipe != null) ? recipe.GetProducedGood() : null);
			if (text != null)
			{
				__result += Runtime.YieldBonus(building, text);
			}
		}
	}
	[HarmonyPatch(typeof(EffectsService), "GetRelicWorkingTime")]
	internal static class EventSpeedPatch
	{
		private static void Postfix(Relic relic, ref float __result)
		{
			if (relic.model.isGladeEvent && Runtime.Active("Academy"))
			{
				__result /= 1.4f;
			}
		}
	}
	[HarmonyPatch(typeof(EffectsService), "GetNewcomersIntervalRate")]
	internal static class NewcomerSpeedPatch
	{
		private static void Postfix(ref float __result)
		{
			if (Runtime.Active("Tavern"))
			{
				__result *= 1.5f;
			}
		}
	}
	[HarmonyPatch(typeof(EffectsService), "GetNewcomersGoodsRate")]
	internal static class NewcomerGoodsPatch
	{
		private static void Postfix(ref float __result)
		{
			if (Runtime.Active("Tavern"))
			{
				__result *= 2f;
			}
		}
	}
	[HarmonyPatch]
	internal static class HostilityPatch
	{
		private static IEnumerable<MethodBase> TargetMethods()
		{
			return from m in AccessTools.GetDeclaredMethods(typeof(HostilityMonitor))
				where (m.Name == "GetPointsFor" && m.GetParameters().Length == 3) || m.Name == "GetPointsForEachSource"
				select m;
		}

		private static void Postfix(HostilitySource source, ref int __result)
		{
			//IL_0000: Unknown result type (might be due to invalid IL or missing references)
			//IL_0003: Invalid comparison between Unknown and I4
			if ((int)source == 50 && Runtime.Active("Tavern"))
			{
				__result = Mathf.RoundToInt(-0.5f * (float)__result);
			}
		}
	}
	[HarmonyPatch(typeof(Villager), "GetResolveImpact", new Type[] { typeof(ResolveEffectModel) })]
	internal static class ClothingResolvePatch
	{
		private static void Postfix(ResolveEffectModel effect, ref int __result)
		{
			if (__result > 0 && Runtime.Active("Bath House") && Runtime.ClothingEffects.Contains(effect))
			{
				__result *= 2;
			}
		}
	}
	[HarmonyPatch(typeof(Villager), "GetResolveImpact", new Type[] { })]
	internal static class VillagerTotalResolvePatch
	{
		private static void Postfix(Villager __instance, ref int __result)
		{
			__result += Runtime.PersonalResolve(__instance) + Runtime.MonasteryBonus();
			if (!Runtime.Active("Bath House"))
			{
				return;
			}
			foreach (ResolveEffectModel clothingEffect in Runtime.ClothingEffects)
			{
				if (__instance.state.resolveEffects.TryGetValue(((SO)clothingEffect).Name, out var value))
				{
					__result += Math.Max(0, value.Resolve);
				}
			}
		}
	}
	[HarmonyPatch(typeof(ResolveService), "CalculateTargetResolve")]
	internal static class RaceResolvePatch
	{
		private static void Postfix(RaceModel model, ref float __result)
		{
			__result += Runtime.RaceResolve(((SO)model).Name);
		}
	}
	[HarmonyPatch(typeof(ResolveService), "GetRawResolveChangeFor")]
	internal static class ResolvePreviewPatch
	{
		private static void Postfix(string race, bool positive, ref float __result)
		{
			if (positive)
			{
				__result += Runtime.RaceResolve(race);
			}
		}
	}
	internal static class Rules
	{
		internal static readonly string[] Kinds = new string[11]
		{
			"Academy", "Bath House", "Clan Hall", "Feast Hall", "Forum", "Guild House", "Market", "Monastery", "Tavern", "Tea Doctor",
			"Temple"
		};

		internal static string Kind(string name)
		{
			if (name == null)
			{
				return null;
			}
			string[] array = new string[2] { "Hallowed ", "Holy " };
			foreach (string text in array)
			{
				if (name.StartsWith(text, StringComparison.Ordinal))
				{
					name = name.Substring(text.Length);
				}
			}
			array = Kinds;
			foreach (string text2 in array)
			{
				if (name == text2)
				{
					return text2;
				}
			}
			return null;
		}

		internal static bool FullyStaffed(bool finished, bool sleeping, int workers, int capacity)
		{
			if (finished && !sleeping && capacity > 0)
			{
				return workers >= capacity;
			}
			return false;
		}

		internal static int FoodTier(int needs)
		{
			if (needs < 3)
			{
				return (needs == 2) ? 1 : 0;
			}
			return 2;
		}

		internal static bool IsComplexFood(string modelName)
		{
			return modelName?.StartsWith("[Food Processed] ", StringComparison.OrdinalIgnoreCase) ?? false;
		}

		internal static float IntervalBonus(bool bath, bool feast, int foodNeeds)
		{
			return (bath ? 0.75f : 0f) + (feast ? (0.5f * (float)FoodTier(foodNeeds)) : 0f);
		}

		internal static float AcademyCrit(int dangerous, int forbidden)
		{
			return 0.03f * (float)dangerous + 0.05f * (float)forbidden;
		}

		internal static int MonasteryResolve(int burned)
		{
			return Math.Max(0, burned) / 20;
		}

		internal static string EffectIconName(string kind)
		{
			return kind switch
			{
				"Academy" => "Icon_Cornerstone_ExplorationExpedition", 
				"Bath House" => "Icon_Need_Cleanliness", 
				"Feast Hall" => "Icon_Cornerstone_BedAndBReakfast", 
				"Forum" => "Icon_MetaReward_EverlastingFlame", 
				"Market" => "Icon_MetaReward_GatheringTechnique", 
				"Monastery" => "Icon_Cornerstone_FirekeepersPrayers", 
				"Tavern" => "Icon_MetaReward_StockedCaravan", 
				"Tea Doctor" => "Icon_Resource_Tea", 
				_ => null, 
			};
		}

		internal static string MonasteryProgress(int cysts)
		{
			cysts = Math.Max(0, cysts);
			return $"Expected gain: +{MonasteryResolve(cysts)}. Progress: {cysts % 20}/20.";
		}

		internal static string EffectName(string kind)
		{
			return kind switch
			{
				"Academy" => "Lessons of the Wilds", 
				"Bath House" => "Restorative Waters", 
				"Feast Hall" => "Bountiful Tables", 
				"Forum" => "Stoke the Flame", 
				"Market" => "Fruits of the Land", 
				"Monastery" => "Purifying Rites", 
				"Tavern" => "A Welcoming Hearth", 
				"Tea Doctor" => "Nourishing Remedies", 
				_ => kind, 
			};
		}

		internal static string Description(string kind)
		{
			return kind switch
			{
				"Academy" => "+3% global double-production chance per completed dangerous glade event; +5% per forbidden event (retroactive). Glade events are worked 40% faster.", 
				"Bath House" => "+75% time between breaks. Double Resolve from fulfilled clothing needs. Replaces Regular Baths.", 
				"Feast Hall" => "+50% yield to complex food recipes. Villagers with 2 / 3+ complex food needs fulfilled get +50% / +100% time between breaks and +3 / +6 Resolve.", 
				"Forum" => "+100% yield from Woodcutter's Camps. +50% yield to fuel production.", 
				"Market" => "+100% yield from fertile-soil buildings, including farms, Greenhouses and Clay Pits.", 
				"Monastery" => "+1 Global Resolve for every 20 blightrot cysts burned in this settlement (retroactive).", 
				"Tavern" => "Newcomers travel 50% faster and bring +100% goods. Villager hostility becomes a reduction equal to 50% of its usual value.", 
				"Tea Doctor" => "Villagers with 2 / 3+ complex food needs fulfilled gain an additional +15% / +30% double-production chance.", 
				_ => null, 
			};
		}
	}
}