Hooks.cs 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using Harmony;
  2. using MessagePack;
  3. using System;
  4. using System.Collections.Generic;
  5. using System.IO;
  6. using System.Linq;
  7. using System.Reflection;
  8. using System.Text;
  9. namespace ExtensibleSaveFormat
  10. {
  11. public static class Hooks
  12. {
  13. public static void InstallHooks()
  14. {
  15. var harmony = HarmonyInstance.Create("com.bepis.bepinex.extensiblesaveformat");
  16. MethodInfo original = AccessTools.Method(typeof(ChaFile), "SaveFile", new[] { typeof(BinaryWriter), typeof(bool) });
  17. HarmonyMethod postfix = new HarmonyMethod(typeof(Hooks).GetMethod("SaveFileHook"));
  18. harmony.Patch(original, null, postfix);
  19. original = AccessTools.Method(typeof(ChaFile), "LoadFile", new[] { typeof(BinaryReader), typeof(bool), typeof(bool) });
  20. postfix = new HarmonyMethod(typeof(Hooks).GetMethod("LoadFileHook"));
  21. harmony.Patch(original, null, postfix);
  22. }
  23. public static void SaveFileHook(ChaFile __instance, bool __result, BinaryWriter bw, bool savePng)
  24. {
  25. if (!__result)
  26. return;
  27. if (!ExtensibleSaveFormat.TryGetExtendedFormat(__instance, out Dictionary<string, object> extendedData))
  28. return;
  29. byte[] bytes = MessagePackSerializer.Serialize(extendedData);
  30. bw.Write((int)bytes.Length);
  31. bw.Write(bytes);
  32. }
  33. public static void LoadFileHook(ChaFile __instance, bool __result, BinaryReader br, bool noLoadPNG, bool noLoadStatus)
  34. {
  35. if (!__result)
  36. return;
  37. try
  38. {
  39. int length = br.ReadInt32();
  40. if (length > 0)
  41. {
  42. byte[] bytes = br.ReadBytes(length);
  43. ExtensibleSaveFormat.internalDictionary[__instance] = MessagePackSerializer.Deserialize<Dictionary<string, object>>(bytes);
  44. return;
  45. }
  46. }
  47. catch (EndOfStreamException) { }
  48. //initialize a new dictionary since it doesn't exist
  49. ExtensibleSaveFormat.internalDictionary[__instance] = new Dictionary<string, object>();
  50. }
  51. }
  52. }