EnvironmentManagerSerializer.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using UnityEngine;
  5. namespace COM3D2.MeidoPhotoStudio.Plugin
  6. {
  7. public class EnvironmentManagerSerializer : Serializer<EnvironmentManager>
  8. {
  9. private const short version = 1;
  10. private static SimpleSerializer<TransformDTO> TransformDtoSerializer => Serialization.GetSimple<TransformDTO>();
  11. public override void Serialize(EnvironmentManager manager, BinaryWriter writer)
  12. {
  13. writer.Write(EnvironmentManager.header);
  14. writer.WriteVersion(version);
  15. writer.Write(manager.CurrentBgAsset);
  16. var bgTransform = GetBgTransform(manager);
  17. var transformDto = bgTransform ? new TransformDTO(bgTransform) : new TransformDTO();
  18. TransformDtoSerializer.Serialize(transformDto, writer);
  19. }
  20. public override void Deserialize(EnvironmentManager manager, BinaryReader reader, SceneMetadata metadata)
  21. {
  22. _ = reader.ReadVersion();
  23. var bgAsset = reader.ReadString();
  24. var transformDto = TransformDtoSerializer.Deserialize(reader, metadata);
  25. var creativeBg = Utility.IsGuidString(bgAsset);
  26. List<string> bgList = creativeBg
  27. ? Constants.MyRoomCustomBGList.ConvertAll(kvp => kvp.Key)
  28. : Constants.BGList;
  29. var assetIndex = bgList.FindIndex(
  30. asset => asset.Equals(bgAsset, StringComparison.InvariantCultureIgnoreCase)
  31. );
  32. var validBg = assetIndex >= 0;
  33. if (validBg) bgAsset = bgList[assetIndex];
  34. else
  35. {
  36. Utility.LogWarning($"Could not load BG '{bgAsset}'");
  37. creativeBg = false;
  38. bgAsset = EnvironmentManager.defaultBg;
  39. }
  40. manager.ChangeBackground(bgAsset, creativeBg);
  41. if (!validBg) return;
  42. var bg = GetBgTransform(manager);
  43. if (!bg) return;
  44. bg.position = transformDto.Position;
  45. bg.rotation = transformDto.Rotation;
  46. bg.localScale = transformDto.LocalScale;
  47. }
  48. private static Transform GetBgTransform(EnvironmentManager manager)
  49. => Utility.GetFieldValue<EnvironmentManager, Transform>(manager, "bg");
  50. }
  51. }