using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Reflection;
using System.Reflection.Emit;
using System.Runtime.CompilerServices;
using BepInEx;
using Fusion;
using HarmonyLib;
using Microsoft.CodeAnalysis;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints)]
[assembly: AssemblyVersion("0.0.0.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 PerSaveDebtRewards
{
[BepInPlugin("per-save-debt-rewards.crimesimulator", "Per-Save Debt Rewards", "1.0.0")]
[BepInProcess("Crime Simulator.exe")]
public sealed class Plugin : BaseUnityPlugin
{
private const string Id = "per-save-debt-rewards.crimesimulator";
private const string KeyPrefix = "PerSaveDebtRewards/";
private static readonly FieldInfo SharedRewards = typeof(BackupManager).GetField("WORLD_REWARDS_FILE_NAME", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
private static readonly (Type Type, string Name, int Calls, bool Settings)[] Targets = new(Type, string, int, bool)[11]
{
(typeof(ChallengesManager), "ActivateRandomChallenges", 2, false),
(typeof(FurnitureButton), "CheckIfUnlocked", 2, false),
(typeof(PlayerStats), "DisplayStats", 1, false),
(typeof(FPP_Player), "SaveWorldXP", 4, true),
(typeof(FPP_Player), "LoadWorldXP", 4, true),
(typeof(FPP_Player), "GetStartingCash", 1, false),
(typeof(MainMenu), "CheckGameModeButtons", 2, false),
(typeof(VictoryManager), "SetRewardUnlocked", 1, false),
(typeof(VictoryManager), "Activate", 2, false),
(typeof(VictoryManager), "CheckRewardsUnlocked", 1, false),
(typeof(VictoryManager), "LoadRewards", 1, true)
};
private void Awake()
{
//IL_0005: Unknown result type (might be due to invalid IL or missing references)
//IL_000b: Expected O, but got Unknown
//IL_001b: Unknown result type (might be due to invalid IL or missing references)
//IL_0021: Expected O, but got Unknown
//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
//IL_00c7: Expected O, but got Unknown
Harmony val = new Harmony("per-save-debt-rewards.crimesimulator");
try
{
HarmonyMethod val2 = new HarmonyMethod(typeof(Plugin), "RewriteRewardAccess", (Type[])null);
(Type, string, int, bool)[] targets = Targets;
for (int i = 0; i < targets.Length; i++)
{
(Type, string, int, bool) tuple = targets[i];
MethodInfo methodInfo = AccessTools.DeclaredMethod(tuple.Item1, tuple.Item2, (Type[])null, (Type[])null);
val.Patch((MethodBase)(methodInfo ?? throw new MissingMethodException(tuple.Item1.Name, tuple.Item2)), (HarmonyMethod)null, (HarmonyMethod)null, val2, (HarmonyMethod)null, (HarmonyMethod)null);
}
val.Patch((MethodBase)AccessTools.DeclaredMethod(typeof(ES3), "DeleteFile", new Type[1] { typeof(ES3Settings) }, (Type[])null), (HarmonyMethod)null, new HarmonyMethod(typeof(Plugin), "DiscardDeletedSlotCache", (Type[])null), (HarmonyMethod)null, (HarmonyMethod)null, (HarmonyMethod)null);
((BaseUnityPlugin)this).Logger.LogInfo((object)"Post-debt rewards and world progression are scoped to the selected save.");
}
catch (Exception arg)
{
val.UnpatchSelf();
((BaseUnityPlugin)this).Logger.LogError((object)$"Per-Save Debt Rewards disabled itself because setup failed: {arg}");
}
}
private static IEnumerable<CodeInstruction> RewriteRewardAccess(IEnumerable<CodeInstruction> instructions, MethodBase original)
{
//IL_0153: Unknown result type (might be due to invalid IL or missing references)
//IL_015a: Expected O, but got Unknown
(Type, string, int, bool) tuple = Array.Find(Targets, ((Type Type, string Name, int Calls, bool Settings) candidate) => candidate.Type == original.DeclaringType && candidate.Name == original.Name);
List<CodeInstruction> list = new List<CodeInstruction>();
int num = 0;
bool flag = false;
foreach (CodeInstruction instruction in instructions)
{
if (CodeInstructionExtensions.LoadsField(instruction, SharedRewards, false))
{
flag = true;
}
if ((tuple.Item4 || flag) && instruction.opcode == OpCodes.Call)
{
object operand = instruction.operand;
MethodInfo method = operand as MethodInfo;
if ((object)method != null && method.DeclaringType == typeof(ES3))
{
flag = false;
num++;
Type[] arguments = Array.ConvertAll(method.GetParameters(), (ParameterInfo parameter) => (!parameter.ParameterType.IsGenericParameter) ? parameter.ParameterType : method.GetGenericArguments()[0]);
MethodInfo operand2 = FindRedirect(method, arguments);
if (original.DeclaringType == typeof(VictoryManager) && original.Name == "Activate" && method.Name == "Save")
{
CodeInstruction val = new CodeInstruction(OpCodes.Ldarg_0, (object)null);
val.labels.AddRange(instruction.labels);
val.blocks.AddRange(instruction.blocks);
instruction.labels.Clear();
instruction.blocks.Clear();
list.Add(val);
operand2 = typeof(Plugin).GetMethod("SaveHostedVictory", BindingFlags.Static | BindingFlags.NonPublic);
}
instruction.operand = operand2;
}
}
list.Add(instruction);
}
if (num != tuple.Item3)
{
throw new InvalidOperationException($"Expected {tuple.Item3} reward calls in {original}, found {num}.");
}
return list;
}
private static MethodInfo FindRedirect(MethodInfo original, Type[] arguments)
{
MethodInfo[] methods = typeof(Plugin).GetMethods(BindingFlags.Static | BindingFlags.NonPublic);
foreach (MethodInfo methodInfo in methods)
{
if (methodInfo.Name != original.Name + "Reward")
{
continue;
}
MethodInfo methodInfo2 = (methodInfo.IsGenericMethodDefinition ? methodInfo.MakeGenericMethod(original.GetGenericArguments()) : methodInfo);
if (methodInfo2.ReturnType != original.ReturnType)
{
continue;
}
ParameterInfo[] parameters = methodInfo2.GetParameters();
if (parameters.Length == arguments.Length)
{
bool flag = true;
for (int j = 0; j < arguments.Length; j++)
{
flag &= parameters[j].ParameterType == arguments[j];
}
if (flag)
{
return methodInfo2;
}
}
}
throw new MissingMethodException($"No reward redirect for {original}.");
}
private static ES3Settings SlotSettings()
{
//IL_0005: Unknown result type (might be due to invalid IL or missing references)
//IL_000b: Expected O, but got Unknown
//IL_001a: Unknown result type (might be due to invalid IL or missing references)
//IL_0020: Expected O, but got Unknown
ES3Settings val = new ES3Settings(Array.Empty<Enum>());
ES3Settings val2 = new ES3Settings(new Enum[1] { (Enum)(object)(Location)4 });
if (ES3.FileExists(val2))
{
return val2;
}
val.location = (Location)0;
return val;
}
private static T LoadReward<T>(string key, string sharedFile, T fallback)
{
return ES3.Load<T>("PerSaveDebtRewards/" + key, fallback, SlotSettings());
}
private static T LoadReward<T>(string key, T fallback, ES3Settings sharedSettings)
{
return ES3.Load<T>("PerSaveDebtRewards/" + key, fallback, SlotSettings());
}
private static bool KeyExistsReward(string key, string sharedFile)
{
return ES3.KeyExists("PerSaveDebtRewards/" + key, SlotSettings());
}
private static void SaveReward<T>(string key, T value, ES3Settings sharedSettings)
{
ES3.Save<T>("PerSaveDebtRewards/" + key, value, SlotSettings());
}
private static void SaveReward<T>(string key, T value, string sharedFile)
{
//IL_0019: Unknown result type (might be due to invalid IL or missing references)
//IL_001f: Invalid comparison between Unknown and I4
ES3Settings val = SlotSettings();
ES3.Save<T>("PerSaveDebtRewards/" + key, value, val);
if ((int)val.location == 4)
{
ES3.StoreCachedFile(val);
}
}
private static void SaveHostedVictory(string key, int value, string sharedFile, VictoryManager manager)
{
if (((SimulationBehaviour)manager).Runner.IsSharedModeMasterClient || ((SimulationBehaviour)manager).Runner.IsSinglePlayer)
{
SaveReward(key, value, sharedFile);
}
}
private static void DiscardDeletedSlotCache(ES3Settings __0)
{
//IL_0001: 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)
//IL_0079: Expected O, but got Unknown
if ((int)__0.location == 0 && !string.IsNullOrEmpty(__0.path))
{
string path = __0.path;
string mAIN_SAVE_FILE_PREFIX = BackupManager.MAIN_SAVE_FILE_PREFIX;
if (path.StartsWith(mAIN_SAVE_FILE_PREFIX, StringComparison.Ordinal) && path.EndsWith(".es3", StringComparison.Ordinal) && int.TryParse(path.Substring(mAIN_SAVE_FILE_PREFIX.Length, path.Length - mAIN_SAVE_FILE_PREFIX.Length - 4), out var _))
{
ES3.DeleteFile(new ES3Settings(path, new Enum[1] { (Enum)(object)(Location)4 }));
}
}
}
}
}