Hooks.cs 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  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. ExtensibleSaveFormat.writeEvent(__instance);
  28. if (!ExtensibleSaveFormat.TryGetExtendedFormat(__instance, out Dictionary<string, object> extendedData))
  29. return;
  30. byte[] bytes = MessagePackSerializer.Serialize(extendedData);
  31. bw.Write((int)bytes.Length);
  32. bw.Write(bytes);
  33. }
  34. public static void LoadFileHook(ChaFile __instance, bool __result, BinaryReader br, bool noLoadPNG, bool noLoadStatus)
  35. {
  36. if (!__result)
  37. return;
  38. try
  39. {
  40. int length = br.ReadInt32();
  41. if (length > 0)
  42. {
  43. byte[] bytes = br.ReadBytes(length);
  44. ExtensibleSaveFormat.internalDictionary[__instance] = MessagePackSerializer.Deserialize<Dictionary<string, object>>(bytes);
  45. return;
  46. }
  47. }
  48. catch (EndOfStreamException) { }
  49. //initialize a new dictionary since it doesn't exist
  50. ExtensibleSaveFormat.internalDictionary[__instance] = new Dictionary<string, object>();
  51. ExtensibleSaveFormat.readEvent(__instance);
  52. }
  53. }
  54. }