Decompiled source of WorkerShifts v0.1.2

plugins/WorkerShifts.dll

Decompiled a day ago
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using BepInEx;
using BepInEx.Bootstrap;
using BepInEx.Configuration;
using HarmonyLib;
using SuperFantasyKingdom;
using SuperFantasyKingdom.Buildings;
using SuperFantasyKingdom.Jobs;
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("WorkerShifts")]
[assembly: AssemblyConfiguration("Release")]
[assembly: AssemblyFileVersion("0.1.2.0")]
[assembly: AssemblyInformationalVersion("0.1.2+d428e935ef3a57ac1a580a1138ff8663db6c15f4")]
[assembly: AssemblyProduct("WorkerShifts")]
[assembly: AssemblyTitle("WorkerShifts")]
[assembly: AssemblyVersion("0.1.2.0")]
namespace WorkerShifts;

[BepInPlugin("gkj.sfk.workershifts", "Worker Shifts", "0.1.2")]
[BepInDependency(/*Could not decode attribute arguments.*/)]
public sealed class Plugin : BaseUnityPlugin
{
	internal const string Id = "gkj.sfk.workershifts";

	internal const string NoBreaksId = "No_Breaks";

	private Harmony harmony;

	private void Awake()
	{
		//IL_007c: Unknown result type (might be due to invalid IL or missing references)
		//IL_0086: Expected O, but got Unknown
		string version = Application.version;
		if (!Version.TryParse(version, out Version result) || result > new Version("0.8.071"))
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)("Super Fantasy Kingdom " + version + " is untested for this mod. Last tested on 0.8.071. If you encounter an issue while playing with this mod, report it at https://github.com/GKJ-Super-Fantasy-Kingdom/worker-shifts/issues"));
		}
		var (shiftCutoff, heldEveningPolicy) = ReadSchedule(((BaseUnityPlugin)this).Config);
		if (NoBreaksOwnsSchedule())
		{
			((BaseUnityPlugin)this).Logger.LogWarning((object)"No Breaks is installed. Worker Shifts is inactive for this launch. Disable No Breaks and restart to use Worker Shifts.");
		}
		else
		{
			if (shiftCutoff != ShiftCutoff.WorkUntilEvening && shiftCutoff != ShiftCutoff.WorkUntilNight)
			{
				return;
			}
			harmony = new Harmony("gkj.sfk.workershifts");
			try
			{
				ShiftHooks.Install(harmony);
				WorkerClock.Cutoff = shiftCutoff;
				WorkerClock.HeldEvening = heldEveningPolicy;
				DaytimeManager.OnEveningStart += OnEvening;
				if (ShiftSchedule.StopsOnHold(shiftCutoff, heldEveningPolicy))
				{
					DaytimeManager.OnNightHold += OnNightHold;
				}
				DaytimeManager.OnNightStart += OnNight;
				((BaseUnityPlugin)this).Logger.LogInfo((object)$"Worker Shifts active with cutoff {shiftCutoff} and held-Evening policy {heldEveningPolicy}.");
			}
			catch (Exception arg)
			{
				Stop();
				((BaseUnityPlugin)this).Logger.LogError((object)$"Worker Shifts disabled because the native worker hooks could not bind. {arg}");
			}
		}
	}

	private static (ShiftCutoff Cutoff, HeldEveningPolicy HeldEvening) ReadSchedule(ConfigFile config)
	{
		ShiftCutoff value = config.Bind<ShiftCutoff>("Schedule", "ShiftCutoff", ShiftCutoff.WorkUntilNight, "Vanilla stops at Sunset. WorkUntilEvening includes Sunset. WorkUntilNight includes Evening until native Night, subject to HeldEvening. Restart the game to apply changes.").Value;
		HeldEveningPolicy value2 = config.Bind<HeldEveningPolicy>("Schedule", "HeldEvening", HeldEveningPolicy.KeepWorking, "Applies to WorkUntilNight only. KeepWorking continues until native Night. StopOnHold stops new work at the first native Night hold. Restart the game to apply changes.").Value;
		return (Cutoff: value, HeldEvening: value2);
	}

	private static bool NoBreaksOwnsSchedule()
	{
		if (!Chainloader.PluginInfos.ContainsKey("No_Breaks"))
		{
			return Harmony.HasAnyPatches("No_Breaks");
		}
		return true;
	}

	private void OnEvening(int day)
	{
		WorkerClock.ResetHold();
		if (WorkerClock.Cutoff == ShiftCutoff.WorkUntilEvening)
		{
			ReturnIdleWorkers(day);
		}
	}

	private void OnNightHold(int day)
	{
		if (WorkerClock.CloseAtHold(DaytimeManager.Instance, day))
		{
			ReturnIdleWorkers(day);
		}
	}

	private void OnNight(int day)
	{
		if (WorkerClock.Cutoff == ShiftCutoff.WorkUntilNight)
		{
			ReturnIdleWorkers(day);
		}
	}

	private void ReturnIdleWorkers(int day)
	{
		JobManager instance = JobManager.Instance;
		if ((Object)(object)instance == (Object)null || !WorkerClock.CanExtend())
		{
			return;
		}
		try
		{
			ShiftHooks.ReturnIdleWorkers(instance, day);
		}
		catch (Exception arg)
		{
			((BaseUnityPlugin)this).Logger.LogError((object)$"The native idle-worker return did not complete. {arg}");
		}
	}

	private void OnDestroy()
	{
		Stop();
	}

	private void Stop()
	{
		if (harmony != null)
		{
			WorkerClock.Cutoff = ShiftCutoff.Vanilla;
			WorkerClock.ResetHold();
			DaytimeManager.OnEveningStart -= OnEvening;
			DaytimeManager.OnNightHold -= OnNightHold;
			DaytimeManager.OnNightStart -= OnNight;
			harmony.UnpatchSelf();
			harmony = null;
		}
	}
}
internal static class ShiftHooks
{
	private static readonly MethodInfo NativeClock = Method(typeof(DaytimeManager), "IsWorkTime", typeof(bool));

	private static readonly MethodInfo SunsetSweep = Method(typeof(JobManager), "OnSunsetStart", typeof(void), typeof(int));

	private static readonly Dictionary<MethodBase, (MethodInfo Gate, bool PassInstance)> Replacements = new Dictionary<MethodBase, (MethodInfo, bool)>();

	internal static void Install(Harmony harmony)
	{
		//IL_0389: Unknown result type (might be due to invalid IL or missing references)
		//IL_0395: Expected O, but got Unknown
		//IL_03b6: Unknown result type (might be due to invalid IL or missing references)
		//IL_03c4: Expected O, but got Unknown
		(MethodBase, string, bool)[] array = new(MethodBase, string, bool)[13]
		{
			(Method(typeof(JobManager), "CheckAllJobsInternal", typeof(bool)), "IsOpen", false),
			(Method(typeof(JobManager), "GetNewJob", typeof(Job), typeof(Worker), typeof(Job)), "IsOpenForAssignment", true),
			(Method(typeof(Worker), "FindNewJob", typeof(void)), "IsOpen", false),
			(Method(typeof(Worker), "GetMoveSpeed", typeof(float)), "UsesWorkingPace", true),
			(Method(typeof(Worker), "Reached", typeof(bool)), "UsesWorkingPace", true),
			(Method(typeof(WorkerOutside), "FindNewJob", typeof(void)), "IsOpen", false),
			(Method(typeof(WorkerSpecialist), "FindNewJob", typeof(void)), "IsOpen", false),
			(AccessTools.EnumeratorMoveNext((MethodBase)Method(typeof(WorkerSpecialist), "CheckForWork", typeof(IEnumerator))), "IsOpen", false),
			(Method(typeof(JobVein), "GetTarget", typeof(Vector2), typeof(Vector2)), "IsOpen", false),
			(Method(typeof(BuildingDemand), "Update", typeof(void)), "IsOpen", false),
			(Method(typeof(BuildingDemand), "Demand", typeof(void), typeof(int)), "IsOpen", false),
			(Method(typeof(BuildingGeneratingg), "Update", typeof(void)), "IsOpenForGenerator", true),
			(Method(typeof(BuildingGeneratingElves), "CheckForSpendingFaith", typeof(void)), "IsOpen", false)
		};
		(MethodBase, string, bool)[] array2 = array;
		for (int i = 0; i < array2.Length; i++)
		{
			(MethodBase, string, bool) tuple = array2[i];
			if (tuple.Item1 == null)
			{
				throw new MissingMethodException("WorkerSpecialist.CheckForWork.MoveNext");
			}
			MethodInfo item = AccessTools.DeclaredMethod(typeof(WorkerClock), tuple.Item2, (Type[])null, (Type[])null);
			Replacements[tuple.Item1] = (item, tuple.Item3);
		}
		array2 = array;
		for (int i = 0; i < array2.Length; i++)
		{
			(MethodBase, string, bool) tuple2 = array2[i];
			harmony.Patch(tuple2.Item1, (HarmonyMethod)null, (HarmonyMethod)null, new HarmonyMethod(typeof(ShiftHooks), "ReplaceClock", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null);
		}
		harmony.Patch((MethodBase)SunsetSweep, new HarmonyMethod(typeof(ShiftHooks), "BeforeSunsetSweep", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
	}

	private static IEnumerable<CodeInstruction> ReplaceClock(IEnumerable<CodeInstruction> instructions, MethodBase original)
	{
		//IL_00a5: Unknown result type (might be due to invalid IL or missing references)
		//IL_00af: Expected O, but got Unknown
		List<CodeInstruction> list = instructions.ToList();
		List<CodeInstruction> list2 = list.FindAll((CodeInstruction instruction) => CodeInstructionExtensions.Calls(instruction, NativeClock));
		if (list2.Count != 1)
		{
			throw new InvalidOperationException($"Expected one native work clock in {original.DeclaringType}.{original.Name}.");
		}
		CodeInstruction val = list2[0];
		(MethodInfo, bool) tuple = Replacements[original];
		if (tuple.Item2)
		{
			OpCode opcode = ((original.DeclaringType == typeof(JobManager)) ? OpCodes.Ldarg_1 : OpCodes.Ldarg_0);
			list.Insert(list.IndexOf(val) + 1, new CodeInstruction(OpCodes.Call, (object)tuple.Item1));
			val.opcode = opcode;
			val.operand = null;
		}
		else
		{
			val.opcode = OpCodes.Call;
			(val.operand, _) = tuple;
		}
		return list;
	}

	private static bool BeforeSunsetSweep()
	{
		DaytimeManager instance = DaytimeManager.Instance;
		if (!((Object)(object)instance == (Object)null) && WorkerClock.Extends(instance))
		{
			return WorkerClock.ChurchAtSunset();
		}
		return true;
	}

	internal static void ReturnIdleWorkers(JobManager jobs, int day)
	{
		SunsetSweep.Invoke(jobs, new object[1] { day });
	}

	private static MethodInfo Method(Type type, string name, Type result, params Type[] parameters)
	{
		MethodInfo methodInfo = AccessTools.DeclaredMethod(type, name, parameters, (Type[])null);
		if (methodInfo == null || methodInfo.IsStatic || methodInfo.ReturnType != result)
		{
			throw new MissingMethodException(type.FullName, name);
		}
		return methodInfo;
	}
}
internal enum ShiftCutoff
{
	Vanilla,
	WorkUntilEvening,
	WorkUntilNight
}
internal enum ShiftPhase
{
	Other,
	Sunset,
	Evening
}
internal enum HeldEveningPolicy
{
	KeepWorking,
	StopOnHold
}
internal static class ShiftSchedule
{
	internal const ShiftCutoff Default = ShiftCutoff.WorkUntilNight;

	internal const HeldEveningPolicy DefaultHeldEvening = HeldEveningPolicy.KeepWorking;

	internal static bool StopsOnHold(ShiftCutoff cutoff, HeldEveningPolicy policy)
	{
		if (cutoff == ShiftCutoff.WorkUntilNight)
		{
			return policy == HeldEveningPolicy.StopOnHold;
		}
		return false;
	}

	internal static bool Extends(ShiftCutoff cutoff, ShiftPhase phase, bool closedAtHold)
	{
		if (phase != ShiftPhase.Sunset || (cutoff != ShiftCutoff.WorkUntilEvening && cutoff != ShiftCutoff.WorkUntilNight))
		{
			if (phase == ShiftPhase.Evening && cutoff == ShiftCutoff.WorkUntilNight)
			{
				return !closedAtHold;
			}
			return false;
		}
		return true;
	}
}
internal static class WorkerClock
{
	private static DaytimeManager heldClock;

	private static int heldDay;

	internal static ShiftCutoff Cutoff { get; set; }

	internal static HeldEveningPolicy HeldEvening { get; set; }

	internal static bool CloseAtHold(DaytimeManager clock, int day)
	{
		if (!ShiftSchedule.StopsOnHold(Cutoff, HeldEvening) || (Object)(object)clock == (Object)null || !clock.IsEvening() || clock.CurrentDay() != day || IsClosedAtHold(clock) || !CanExtend())
		{
			return false;
		}
		heldClock = clock;
		heldDay = day;
		return true;
	}

	internal static void ResetHold()
	{
		heldClock = null;
	}

	private static bool IsClosedAtHold(DaytimeManager clock)
	{
		if (clock == heldClock)
		{
			return clock.CurrentDay() == heldDay;
		}
		return false;
	}

	internal static bool CanExtend()
	{
		MainManager instance = MainManager.Instance;
		GameManager instance2 = GameManager.Instance;
		if ((Object)(object)instance != (Object)null && !instance.IsChallenge() && (Object)(object)instance2 != (Object)null && instance2.IsGameRunning() && !instance2.IsGameOver())
		{
			return !instance2.IsUnloading();
		}
		return false;
	}

	internal static bool ChurchAtSunset()
	{
		//IL_0012: Unknown result type (might be due to invalid IL or missing references)
		//IL_0018: Invalid comparison between Unknown and I4
		if ((Object)(object)RaceManager.Instance != (Object)null && (int)RaceManager.Instance.GetRace() == 2 && (Object)(object)CityManager.Instance != (Object)null)
		{
			return (Object)(object)CityManager.Instance.GetChurch() != (Object)null;
		}
		return false;
	}

	internal static bool IsOpen(DaytimeManager clock)
	{
		if (!clock.IsWorkTime())
		{
			return Extends(clock);
		}
		return true;
	}

	internal static bool IsOpenForAssignment(DaytimeManager clock, Worker worker)
	{
		if (!clock.IsWorkTime())
		{
			if (Extends(clock))
			{
				if (clock.IsSunset() && worker.CanWork())
				{
					return !ChurchAtSunset();
				}
				return true;
			}
			return false;
		}
		return true;
	}

	internal static bool UsesWorkingPace(DaytimeManager clock, Worker worker)
	{
		if (!clock.IsWorkTime())
		{
			if (!(worker is King) && !(worker.GetJob() is JobChurch))
			{
				return Extends(clock);
			}
			return false;
		}
		return true;
	}

	internal static bool IsOpenForGenerator(DaytimeManager clock, BuildingGeneratingg building)
	{
		if (!clock.IsWorkTime())
		{
			if (building is BuildingGeneratingNature || building is BuildingGeneratingElves || building is BuildingLaboratory)
			{
				return Extends(clock);
			}
			return false;
		}
		return true;
	}

	internal static bool Extends(DaytimeManager clock)
	{
		if (ShiftSchedule.Extends(Cutoff, GetPhase(clock), IsClosedAtHold(clock)))
		{
			return CanExtend();
		}
		return false;
	}

	private static ShiftPhase GetPhase(DaytimeManager clock)
	{
		//IL_0001: Unknown result type (might be due to invalid IL or missing references)
		//IL_0006: Unknown result type (might be due to invalid IL or missing references)
		//IL_0007: Unknown result type (might be due to invalid IL or missing references)
		//IL_0009: Invalid comparison between Unknown and I4
		//IL_000b: Unknown result type (might be due to invalid IL or missing references)
		//IL_000d: Invalid comparison between Unknown and I4
		DaytimePhase daytimePhase = clock.GetDaytimePhase();
		if ((int)daytimePhase != 2)
		{
			if ((int)daytimePhase == 4)
			{
				return ShiftPhase.Evening;
			}
			return ShiftPhase.Other;
		}
		return ShiftPhase.Sunset;
	}
}