using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security;
using System.Security.Permissions;
using BepInEx;
using BepInEx.Logging;
using CG;
using CG.Client;
using CG.Game.SpaceObjects.Controllers;
using CG.Network;
using CG.Objects;
using CG.Ship;
using CG.Ship.Hull;
using CG.Ship.Modules;
using CG.Ship.Repair;
using CG.Space;
using Gameplay.CompositeWeapons;
using HarmonyLib;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using UI.MainHUD;
using UnityEngine;
using UnityEngine.SceneManagement;
[assembly: CompilationRelaxations(8)]
[assembly: RuntimeCompatibility(WrapNonExceptionThrows = true)]
[assembly: Debuggable(DebuggableAttribute.DebuggingModes.Default | DebuggableAttribute.DebuggingModes.DisableOptimizations | DebuggableAttribute.DebuggingModes.IgnoreSymbolStoreSequencePoints | DebuggableAttribute.DebuggingModes.EnableEditAndContinue)]
[assembly: TargetFramework(".NETStandard,Version=v2.1", FrameworkDisplayName = "")]
[assembly: AssemblyCompany("save_game")]
[assembly: AssemblyConfiguration("Debug")]
[assembly: AssemblyDescription("save_game")]
[assembly: AssemblyFileVersion("0.1.0.0")]
[assembly: AssemblyInformationalVersion("0.1.0")]
[assembly: AssemblyProduct("save_game")]
[assembly: AssemblyTitle("save_game")]
[assembly: SecurityPermission(SecurityAction.RequestMinimum, SkipVerification = true)]
[assembly: AssemblyVersion("0.1.0.0")]
[module: UnverifiableCode]
namespace save_game;
public static class SaveGamePatches
{
[HarmonyPatch(typeof(VoidJumpTravellingStable), "OnExit")]
public class PatchVoidOnExit
{
private static void Prefix()
{
SaveGamePlugin saveGamePlugin = Object.FindAnyObjectByType<SaveGamePlugin>();
if ((Object)(object)saveGamePlugin != (Object)null)
{
saveGamePlugin.canSaveData = false;
}
}
}
[HarmonyPatch(typeof(VoidJumpTravellingStable), "OnEnter")]
public class PatchVoidOnEnter
{
private static void Prefix(ref VoidJumpState previousState)
{
SaveGamePlugin saveGamePlugin = Object.FindAnyObjectByType<SaveGamePlugin>();
if ((Object)(object)saveGamePlugin != (Object)null)
{
saveGamePlugin.canSaveData = true;
}
}
}
[HarmonyPatch(typeof(HomunculusAndBiomassSocket), "Awake")]
public class HomunculusAndBiomassSocketAwake
{
private static void Postfix(HomunculusAndBiomassSocket __instance)
{
if (ShouldUseSave())
{
MethodInfo method = ((object)__instance).GetType().GetMethod("SwitchToBiomassSocket", BindingFlags.Instance | BindingFlags.NonPublic);
method.Invoke(__instance, new object[0]);
}
}
}
[HarmonyPatch(typeof(GameSessionManager), "HostGameSession")]
public class PatchHostGameSession
{
private static void Postfix()
{
//IL_0013: Unknown result type (might be due to invalid IL or missing references)
//IL_0019: Expected O, but got Unknown
SaveGamePlugin saveGamePlugin = Object.FindAnyObjectByType<SaveGamePlugin>();
if ((Object)(object)saveGamePlugin == (Object)null)
{
GameObject val = new GameObject();
val.AddComponent<SaveGamePlugin>();
Object.DontDestroyOnLoad((Object)(object)val);
}
else
{
logger.LogInfo((object)"SGB ALREADY MADE");
}
}
}
[HarmonyPatch(typeof(GameSession), "LoadShip")]
public class PatchLoadShip
{
private static void Prefix(GameSession __instance)
{
if (ShouldUseSave())
{
__instance.ToLoadShipData = previousSave;
}
}
}
[HarmonyPatch(typeof(GameSessionSuppliesManager), "GetTotalPlayerAlloyBonus")]
public class PatchGetTotalAlloy
{
private static void Postfix(ref int __result)
{
if (!ShouldUseSave())
{
return;
}
__result = rd.numAlloys;
HullDamageController val = Object.FindAnyObjectByType<HullDamageController>();
if (!((Object)(object)val != (Object)null))
{
return;
}
ShipInfoHUD val2 = Object.FindObjectOfType<ShipInfoHUD>();
logger.LogInfo((object)"Active breaches");
logger.LogInfo((object)val.ActiveBreachesAmount);
logger.LogInfo(Traverse.Create((object)val2).Field("trackedHullBreachesAmount").GetValue());
ViewEventBus.Instance.OnHullStateChanged.Publish(val.State);
logger.LogInfo((object)val.State.repairableHp);
logger.LogInfo((object)val.Breaches.Count);
foreach (HullBreach breach in val.Breaches)
{
logger.LogInfo((object)((object)(BreachCondition)(ref breach.State.condition)).ToString());
ViewEventBus.Instance.OnBreachUpdated.Publish(breach);
}
}
}
[HarmonyPatch(typeof(GameSessionSuppliesManager), "GetTotalPlayerBiomassBonus")]
public class PatchGetTotalBiomass
{
private static void Postfix(ref int __result)
{
if (ShouldUseSave())
{
__result = rd.numBiomass;
}
}
}
[HarmonyPatch(typeof(FabricatorModule), "Awake")]
public class PatchFabricationModuleAwake
{
private static void Postfix(FabricatorModule __instance)
{
//IL_0038: Unknown result type (might be due to invalid IL or missing references)
//IL_003d: Unknown result type (might be due to invalid IL or missing references)
//IL_0045: Unknown result type (might be due to invalid IL or missing references)
fd = __instance;
if (!ShouldUseSave())
{
return;
}
if (rd.unlockedItems != null)
{
foreach (GUIDUnion unlockedItem in rd.unlockedItems)
{
__instance.SessionBasedUnlockPool.Add(unlockedItem);
}
return;
}
logger.LogInfo((object)"NO UNLOCKED ITEMS");
}
}
[HarmonyPatch(typeof(AbstractPlayerControlledShip), "Start")]
public class PatchAbstractPlayerControlledShipStart
{
private static void Postfix(AbstractPlayerControlledShip __instance)
{
if (ShouldUseSave())
{
SaveGamePlugin saveGamePlugin = Object.FindAnyObjectByType<SaveGamePlugin>();
((OrbitObject)__instance).StartingHitPoints = originalStartingHp;
}
}
}
[HarmonyPatch(typeof(FabricatorModule), "Awake")]
public class PatchFabricatorModuleAwake
{
private static void Postfix(FabricatorModule __instance)
{
if (ShouldUseSave())
{
__instance.CurrentTier = rd.fabricatorLevel;
}
}
}
[HarmonyPatch(typeof(ShipLoadout), "InitializeShip")]
public class PatchInitializeShip
{
private static void Postfix(ref GameObject __result)
{
//IL_01e0: Unknown result type (might be due to invalid IL or missing references)
//IL_0080: Unknown result type (might be due to invalid IL or missing references)
//IL_0085: Unknown result type (might be due to invalid IL or missing references)
//IL_008a: Unknown result type (might be due to invalid IL or missing references)
//IL_02b0: Unknown result type (might be due to invalid IL or missing references)
//IL_02b5: Unknown result type (might be due to invalid IL or missing references)
//IL_02eb: Unknown result type (might be due to invalid IL or missing references)
//IL_02ed: Unknown result type (might be due to invalid IL or missing references)
//IL_02f2: Unknown result type (might be due to invalid IL or missing references)
SaveGamePlugin saveGamePlugin = Object.FindAnyObjectByType<SaveGamePlugin>();
if (!((Object)(object)saveGamePlugin != (Object)null))
{
return;
}
saveGamePlugin.ship = __result;
if (!ShouldUseSave())
{
return;
}
if (rd.relics != null && rd.relics.Count > 0)
{
RelicSocketController[] array = Object.FindObjectsByType<RelicSocketController>((FindObjectsSortMode)0);
if (array.Length != 0)
{
for (int i = 0; i < array.Length && i < rd.relics.Count; i++)
{
AbstractCloneStarObject obj = ObjectFactory.InstantiateSpaceObjectByGUID(rd.relics[i], Vector3.zero, Quaternion.identity, (Dictionary<byte, object>)null);
CarryableObject val = (CarryableObject)(object)((obj is CarryableObject) ? obj : null);
((CarryablesSocket)array[i].RelicSocket).TryInsertCarryable(val);
logger.LogInfo((object)("Inserted Carryable object: " + ((AbstractCloneStarObject)val).DisplayName));
}
}
}
AbstractPlayerControlledShip component = __result.GetComponent<AbstractPlayerControlledShip>();
originalStartingHp = ((OrbitObject)component).StartingHitPoints;
((OrbitObject)component).StartingHitPoints = rd.currShipHP;
HullDamageController val2 = Object.FindObjectOfType<HullDamageController>();
logger.LogInfo((object)"STARTING HDC BREACHES");
val2.State.repairableHp = rd.repairableHp;
logger.LogInfo((object)val2.Breaches.Count);
logger.LogInfo((object)rd.breachStates.Count);
if (val2.Breaches.Count == rd.breachStates.Count)
{
logger.LogInfo((object)"Equal number of breaches!. We are happy!");
}
for (int j = 0; j < val2.Breaches.Count; j++)
{
val2.Breaches[j].SetCondition(rd.breachStates[j].condition);
}
CompositeWeaponModule[] array2 = Object.FindObjectsByType<CompositeWeaponModule>((FindObjectsSortMode)0);
if (rd.weaponMods == null || rd.weaponMods.Count <= 0)
{
return;
}
CompositeWeaponModule[] array3 = array2;
foreach (CompositeWeaponModule val3 in array3)
{
int num = -1;
for (int l = 0; l < rd.weaponMods.Count; l++)
{
if (!rd.weaponMods[l].ContainsKey(((Object)val3).name))
{
continue;
}
num = l;
foreach (GUIDUnion item in rd.weaponMods[l][((Object)val3).name])
{
foreach (CarryablesSocket connectedSocket in ((CellModule)val3).ConnectedSockets)
{
if (!Object.op_Implicit((Object)(object)connectedSocket.Payload))
{
? val4 = connectedSocket;
AbstractCloneStarObject obj2 = ObjectFactory.InstantiateSpaceObjectByGUID(item, Vector3.zero, Quaternion.identity, (Dictionary<byte, object>)null);
((CarryablesSocket)val4).TryInsertCarryable((CarryableObject)(object)((obj2 is CarryableObject) ? obj2 : null));
break;
}
}
}
break;
}
if (num != -1)
{
rd.weaponMods.RemoveAt(num);
}
}
}
}
public static string ship_save_path = Path.Combine(Application.dataPath, "save_ship_data.json");
public static string resources_save_path = Path.Combine(Application.dataPath, "resources_ship_data.json");
public static bool hasInitialized = false;
private static ResourceData rd;
public static ShipLoadout previousSave;
public static FabricatorModule fd;
public static ManualLogSource logger;
private static float originalStartingHp;
public static void IntializeMod()
{
//IL_0006: Unknown result type (might be due to invalid IL or missing references)
//IL_0010: Expected O, but got Unknown
//IL_0025: Unknown result type (might be due to invalid IL or missing references)
//IL_002b: Expected O, but got Unknown
//IL_00ba: Unknown result type (might be due to invalid IL or missing references)
//IL_00c1: Expected O, but got Unknown
//IL_00c9: Unknown result type (might be due to invalid IL or missing references)
//IL_00d0: Expected O, but got Unknown
logger = new ManualLogSource("Save Game");
Logger.Sources.Add((ILogSource)(object)logger);
Harmony val = new Harmony("savegame");
val.PatchAll();
originalStartingHp = 0f;
fd = null;
if (File.Exists(ship_save_path))
{
logger.LogInfo((object)"Ship Save Found!");
previousSave = ShipLoadout.LoadFromFile(ship_save_path);
}
else
{
logger.LogInfo((object)"No Ship Save Found!");
previousSave = null;
}
if (File.Exists(resources_save_path))
{
logger.LogInfo((object)"Resource Save Found!");
using StreamReader streamReader = File.OpenText(resources_save_path);
JsonTextReader val2 = new JsonTextReader((TextReader)streamReader);
try
{
JObject val3 = (JObject)JToken.ReadFrom((JsonReader)(object)val2);
rd = ((JToken)val3).ToObject<ResourceData>();
logger.LogInfo((object)rd.numAlloys);
logger.LogInfo((object)rd.numBiomass);
}
finally
{
((IDisposable)val2)?.Dispose();
}
}
else
{
logger.LogInfo((object)"No Resource Save Found!");
previousSave = null;
}
hasInitialized = true;
logger.LogInfo((object)"Plugin Save Game is loaded!");
}
public static bool ShouldUseSave()
{
//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_0033: Unknown result type (might be due to invalid IL or missing references)
//IL_0038: Unknown result type (might be due to invalid IL or missing references)
Scene activeScene = SceneManager.GetActiveScene();
if (((Scene)(ref activeScene)).name != "MainMenu" && !GameSessionManager.InHub)
{
SaveGamePlugin saveGamePlugin = Object.FindAnyObjectByType<SaveGamePlugin>();
activeScene = SceneManager.GetActiveScene();
if (((Scene)(ref activeScene)).name != "MainMenu" && !GameSessionManager.InHub && (Object)(object)saveGamePlugin != (Object)null)
{
if (saveGamePlugin.shouldUsePrevSave)
{
if (previousSave != null)
{
return true;
}
logger.LogError((object)"Tried to load save but none was found.");
return false;
}
logger.LogInfo((object)("Not using previous save: shouldUsePrevSave: " + saveGamePlugin.shouldUsePrevSave));
return false;
}
Debug.LogError((object)"Butt was not found");
return false;
}
return false;
}
}
public class ResourceData
{
public int numAlloys;
public int numBiomass;
public List<GUIDUnion> unlockedItems;
public List<GUIDUnion> relics;
public float currShipHP;
public float repairableHp;
public List<BreachState> breachStates;
public int fabricatorLevel;
public List<Dictionary<string, List<GUIDUnion>>> weaponMods;
public ResourceData(int numAlloys, int numBiomass, List<GUIDUnion> unlockedItems, List<GUIDUnion> relics, float currShipHP, float repairableHp, List<BreachState> breachStates, int fabricatorLevel, List<Dictionary<string, List<GUIDUnion>>> weaponMods)
{
this.numAlloys = numAlloys;
this.numBiomass = numBiomass;
this.unlockedItems = unlockedItems;
this.relics = relics;
this.currShipHP = currShipHP;
this.repairableHp = repairableHp;
this.breachStates = breachStates;
this.fabricatorLevel = fabricatorLevel;
this.weaponMods = weaponMods;
}
}
[BepInPlugin("org.bepinex.plugins.save_game", "Save Game", "1.0.0.0")]
internal class SaveGamePlugin : BaseUnityPlugin
{
public GameObject ship;
public bool shouldUsePrevSave;
public bool canSaveData;
public string usingSave;
public bool dataWasSaved;
public Coroutine coroutine;
public KeyCode saveKey;
public KeyCode loadKey;
private void Awake()
{
//IL_0049: Unknown result type (might be due to invalid IL or missing references)
//IL_004e: Unknown result type (might be due to invalid IL or missing references)
//IL_0087: Unknown result type (might be due to invalid IL or missing references)
//IL_008c: Unknown result type (might be due to invalid IL or missing references)
if (!SaveGamePatches.hasInitialized)
{
SaveGamePatches.IntializeMod();
}
saveKey = (KeyCode)Enum.Parse(typeof(KeyCode), ((BaseUnityPlugin)this).Config.Bind<string>("General", "SaveKey", "L", "The key you want to press to save ship.Make sure it is captialized.").Value);
loadKey = (KeyCode)Enum.Parse(typeof(KeyCode), ((BaseUnityPlugin)this).Config.Bind<string>("General", "LoadKey", "M", "The key you want to press to toggle whether you use the current ship save. Make sure it is captialized.").Value);
coroutine = null;
usingSave = "Not using previous save";
shouldUsePrevSave = false;
dataWasSaved = false;
canSaveData = false;
}
private void Update()
{
//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_0035: Unknown result type (might be due to invalid IL or missing references)
//IL_0408: Unknown result type (might be due to invalid IL or missing references)
//IL_00d8: Unknown result type (might be due to invalid IL or missing references)
//IL_0308: Unknown result type (might be due to invalid IL or missing references)
//IL_030f: Expected O, but got Unknown
//IL_0345: Unknown result type (might be due to invalid IL or missing references)
//IL_034c: Expected O, but got Unknown
//IL_0205: Unknown result type (might be due to invalid IL or missing references)
//IL_0233: Unknown result type (might be due to invalid IL or missing references)
Scene activeScene = SceneManager.GetActiveScene();
if (((Scene)(ref activeScene)).name == "MainMenu" || GameSessionManager.InHub)
{
canSaveData = false;
}
if (UnityInput.Current.GetKeyDown(saveKey) && canSaveData)
{
if ((Object)(object)ship != (Object)null)
{
PlayerShip component = ship.GetComponent<PlayerShip>();
if ((Object)(object)component != (Object)null)
{
RelicSocketController[] array = Object.FindObjectsByType<RelicSocketController>((FindObjectsSortMode)0);
List<GUIDUnion> list = new List<GUIDUnion>();
RelicSocketController[] array2 = array;
foreach (RelicSocketController val in array2)
{
CarryableObject payload = ((CarryablesSocket)val.RelicSocket).Payload;
if (Object.op_Implicit((Object)(object)payload))
{
SaveGamePatches.logger.LogInfo((object)((Object)payload).name);
list.Add(((AbstractCloneStarObject)payload).assetGuid);
}
}
HullDamageController val2 = Object.FindAnyObjectByType<HullDamageController>();
List<BreachState> list2 = new List<BreachState>();
foreach (HullBreach breach in val2.Breaches)
{
list2.Add(breach.State);
}
List<Dictionary<string, List<GUIDUnion>>> list3 = new List<Dictionary<string, List<GUIDUnion>>>();
CompositeWeaponModule[] array3 = Object.FindObjectsByType<CompositeWeaponModule>((FindObjectsSortMode)0);
CompositeWeaponModule[] array4 = array3;
foreach (CompositeWeaponModule val3 in array4)
{
Dictionary<string, List<GUIDUnion>> dictionary = new Dictionary<string, List<GUIDUnion>>();
dictionary[((Object)val3).name] = new List<GUIDUnion>();
SaveGamePatches.logger.LogInfo((object)((Object)val3).name);
if (((CellModule)val3).CarryablesSockets != null)
{
Debug.LogError((object)((CellModule)val3).ConnectedSockets.Count);
foreach (CarryablesSocket connectedSocket in ((CellModule)val3).ConnectedSockets)
{
if (Object.op_Implicit((Object)(object)connectedSocket.Payload))
{
dictionary[((Object)val3).name].Add(((AbstractCloneStarObject)connectedSocket.Payload).assetGuid);
SaveGamePatches.logger.LogInfo((object)((Object)connectedSocket.Payload).name);
SaveGamePatches.logger.LogInfo((object)((AbstractCloneStarObject)connectedSocket.Payload).assetGuid);
}
}
if (dictionary[((Object)val3).name].Count > 0)
{
list3.Add(dictionary);
}
}
else
{
Debug.LogError((object)"No sockets");
}
}
ResourceData resourceData = new ResourceData(GameSessionSuppliesManager.Instance.AlloyAmount, GameSessionSuppliesManager.Instance.BiomassAmount, SaveGamePatches.fd.SessionBasedUnlockPool, list, val2.State.ShipHp, val2.State.repairableHp, list2, Object.FindObjectOfType<FabricatorModule>().CurrentTier, list3);
SaveGamePatches.logger.LogInfo((object)"Saving PlayerShip Loadout");
ShipLoadout val4 = new ShipLoadout(component);
val4.SaveToFile(SaveGamePatches.ship_save_path);
SaveGamePatches.logger.LogInfo((object)("Player ship saved to " + SaveGamePatches.ship_save_path));
using (StreamWriter streamWriter = File.CreateText(SaveGamePatches.resources_save_path))
{
JsonTextWriter val5 = new JsonTextWriter((TextWriter)streamWriter);
try
{
((JToken)JObject.FromObject((object)resourceData)).WriteTo((JsonWriter)(object)val5, Array.Empty<JsonConverter>());
}
finally
{
((IDisposable)val5)?.Dispose();
}
}
SaveGamePatches.logger.LogInfo((object)("Resources saved to " + SaveGamePatches.resources_save_path));
dataWasSaved = true;
if (coroutine != null)
{
((MonoBehaviour)this).StopCoroutine(coroutine);
}
coroutine = ((MonoBehaviour)this).StartCoroutine(HideTextAfterDelay());
}
else
{
SaveGamePatches.logger.LogInfo((object)"No player ship object saved to 'Save Game Mod'.");
}
}
else
{
SaveGamePatches.logger.LogInfo((object)"No ship object saved to 'Save Game Mod'.");
}
}
else
{
if (!UnityInput.Current.GetKeyDown(loadKey))
{
return;
}
if (SaveGamePatches.previousSave != null)
{
shouldUsePrevSave = !shouldUsePrevSave;
if (shouldUsePrevSave)
{
usingSave = "Using previous save";
}
else
{
usingSave = "Not using previous save";
}
SaveGamePatches.logger.LogInfo((object)("Using previous save is now " + shouldUsePrevSave));
}
else
{
SaveGamePatches.logger.LogInfo((object)"Previous Save is null!");
}
}
}
private void OnGUI()
{
//IL_000b: Unknown result type (might be due to invalid IL or missing references)
//IL_0010: Unknown result type (might be due to invalid IL or missing references)
//IL_0019: Unknown result type (might be due to invalid IL or missing references)
//IL_001f: 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)
//IL_0032: Unknown result type (might be due to invalid IL or missing references)
//IL_003b: Expected O, but got Unknown
//IL_0042: Unknown result type (might be due to invalid IL or missing references)
//IL_0047: Unknown result type (might be due to invalid IL or missing references)
//IL_0075: Unknown result type (might be due to invalid IL or missing references)
//IL_00bb: Unknown result type (might be due to invalid IL or missing references)
GUIStyle val = new GUIStyle(GUI.skin.label)
{
fontSize = 30
};
val.normal.textColor = Color.white;
val.alignment = (TextAnchor)0;
val.fontStyle = (FontStyle)1;
GUIStyle val2 = val;
if (GameSessionManager.InHub)
{
Scene activeScene = SceneManager.GetActiveScene();
if (((Scene)(ref activeScene)).name != "MainMenu")
{
GUI.Label(new Rect(45f, 50f, 500f, 500f), usingSave, val2);
}
}
if (dataWasSaved)
{
val2.alignment = (TextAnchor)0;
GUI.Label(new Rect((float)(Screen.width / 2 - 50), (float)(Screen.height / 2 + 10), 500f, 500f), "Ship Saved!", val2);
}
}
private IEnumerator HideTextAfterDelay()
{
yield return (object)new WaitForSeconds(3f);
dataWasSaved = false;
}
}
public static class PluginInfo
{
public const string PLUGIN_GUID = "save_game";
public const string PLUGIN_NAME = "save_game";
public const string PLUGIN_VERSION = "0.1.0";
}