SceneManager.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368
  1. using System;
  2. using System.IO;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using UnityEngine;
  6. using BepInEx.Configuration;
  7. namespace COM3D2.MeidoPhotoStudio.Plugin
  8. {
  9. using Input = InputManager;
  10. internal class SceneManager : IManager
  11. {
  12. public static bool Busy { get; private set; }
  13. public bool Initialized { get; private set; }
  14. public static readonly Vector2 sceneDimensions = new Vector2(480, 270);
  15. private readonly MeidoPhotoStudio meidoPhotoStudio;
  16. private int SortDirection => SortDescending ? -1 : 1;
  17. public bool KankyoMode { get; set; }
  18. private static readonly ConfigEntry<bool> sortDescending;
  19. public bool SortDescending
  20. {
  21. get => sortDescending.Value;
  22. set => sortDescending.Value = value;
  23. }
  24. public List<Scene> SceneList { get; } = new List<Scene>();
  25. public int CurrentDirectoryIndex { get; private set; } = -1;
  26. public string CurrentDirectoryName => CurrentDirectoryList[CurrentDirectoryIndex];
  27. public List<string> CurrentDirectoryList
  28. => KankyoMode ? Constants.KankyoDirectoryList : Constants.SceneDirectoryList;
  29. public string CurrentBasePath => KankyoMode ? Constants.kankyoPath : Constants.scenesPath;
  30. public string CurrentScenesDirectory
  31. => CurrentDirectoryIndex == 0 ? CurrentBasePath : Path.Combine(CurrentBasePath, CurrentDirectoryName);
  32. private static readonly ConfigEntry<SortMode> currentSortMode;
  33. public SortMode CurrentSortMode
  34. {
  35. get => currentSortMode.Value;
  36. private set => currentSortMode.Value = value;
  37. }
  38. public int CurrentSceneIndex { get; private set; } = -1;
  39. public Scene CurrentScene => SceneList.Count == 0 ? null : SceneList[CurrentSceneIndex];
  40. public enum SortMode
  41. {
  42. Name, DateCreated, DateModified
  43. }
  44. static SceneManager()
  45. {
  46. sortDescending = Configuration.Config.Bind(
  47. "SceneManager", "SortDescending",
  48. false,
  49. "Sort scenes descending (Z-A)"
  50. );
  51. currentSortMode = Configuration.Config.Bind(
  52. "SceneManager", "SortMode",
  53. SortMode.Name,
  54. "Scene sorting mode"
  55. );
  56. Input.Register(MpsKey.OpenSceneManager, KeyCode.F8, "Hide/show scene manager");
  57. Input.Register(MpsKey.SaveScene, KeyCode.S, "Quick save scene");
  58. Input.Register(MpsKey.LoadScene, KeyCode.A, "Load quick saved scene");
  59. }
  60. public SceneManager(MeidoPhotoStudio meidoPhotoStudio) => this.meidoPhotoStudio = meidoPhotoStudio;
  61. public void Activate() { }
  62. public void Initialize()
  63. {
  64. if (!Initialized)
  65. {
  66. Initialized = true;
  67. SelectDirectory(0);
  68. }
  69. }
  70. public void Deactivate() => ClearSceneList();
  71. public void Update()
  72. {
  73. if (Input.Control)
  74. {
  75. if (Input.GetKeyDown(MpsKey.SaveScene)) QuickSaveScene();
  76. else if (Input.GetKeyDown(MpsKey.LoadScene)) QuickLoadScene();
  77. }
  78. }
  79. public void DeleteDirectory()
  80. {
  81. if (Directory.Exists(CurrentScenesDirectory)) Directory.Delete(CurrentScenesDirectory, true);
  82. CurrentDirectoryList.RemoveAt(CurrentDirectoryIndex);
  83. CurrentDirectoryIndex = Mathf.Clamp(CurrentDirectoryIndex, 0, CurrentDirectoryList.Count - 1);
  84. UpdateSceneList();
  85. }
  86. public void OverwriteScene() => SaveScene(overwrite: true);
  87. public void ToggleKankyoMode()
  88. {
  89. KankyoMode = !KankyoMode;
  90. CurrentDirectoryIndex = 0;
  91. UpdateSceneList();
  92. }
  93. public void SaveScene(bool overwrite = false)
  94. {
  95. if (Busy) return;
  96. if (!Directory.Exists(CurrentScenesDirectory)) Directory.CreateDirectory(CurrentScenesDirectory);
  97. meidoPhotoStudio.StartCoroutine(SaveSceneToFile(overwrite));
  98. }
  99. public void SelectDirectory(int directoryIndex)
  100. {
  101. directoryIndex = Mathf.Clamp(directoryIndex, 0, CurrentDirectoryList.Count - 1);
  102. if (directoryIndex == CurrentDirectoryIndex) return;
  103. CurrentDirectoryIndex = directoryIndex;
  104. UpdateSceneList();
  105. }
  106. public void SelectScene(int sceneIndex)
  107. {
  108. CurrentSceneIndex = Mathf.Clamp(sceneIndex, 0, SceneList.Count - 1);
  109. CurrentScene.GetNumberOfMaids();
  110. }
  111. public void AddDirectory(string directoryName)
  112. {
  113. directoryName = Utility.SanitizePathPortion(directoryName);
  114. if (!CurrentDirectoryList.Contains(directoryName, StringComparer.InvariantCultureIgnoreCase))
  115. {
  116. string finalPath = Path.Combine(CurrentBasePath, directoryName);
  117. string fullPath = Path.GetFullPath(finalPath);
  118. if (!fullPath.StartsWith(CurrentBasePath))
  119. {
  120. string baseDirectoryName = KankyoMode ? Constants.kankyoDirectory : Constants.sceneDirectory;
  121. Utility.LogError($"Could not add directory to {baseDirectoryName}. Path is invalid: '{fullPath}'");
  122. return;
  123. }
  124. CurrentDirectoryList.Add(directoryName);
  125. Directory.CreateDirectory(finalPath);
  126. UpdateDirectoryList();
  127. CurrentDirectoryIndex = CurrentDirectoryList.IndexOf(directoryName);
  128. UpdateSceneList();
  129. }
  130. }
  131. public void Refresh()
  132. {
  133. if (!Directory.Exists(CurrentScenesDirectory)) CurrentDirectoryIndex = 0;
  134. Constants.InitializeScenes();
  135. UpdateSceneList();
  136. }
  137. public void SortScenes(SortMode sortMode)
  138. {
  139. CurrentSortMode = sortMode;
  140. Comparison<Scene> comparator;
  141. switch (CurrentSortMode)
  142. {
  143. case SortMode.DateModified: comparator = SortByDateModified; break;
  144. case SortMode.DateCreated: comparator = SortByDateCreated; break;
  145. default: comparator = SortByName; break;
  146. }
  147. SceneList.Sort(comparator);
  148. }
  149. public void DeleteScene()
  150. {
  151. if (CurrentScene.FileInfo.Exists)
  152. {
  153. CurrentScene.FileInfo.Delete();
  154. }
  155. SceneList.RemoveAt(CurrentSceneIndex);
  156. CurrentSceneIndex = Mathf.Clamp(CurrentSceneIndex, 0, SceneList.Count - 1);
  157. }
  158. public void LoadScene()
  159. {
  160. meidoPhotoStudio.ApplyScene(CurrentScene.FileInfo.FullName);
  161. }
  162. private int SortByName(Scene a, Scene b)
  163. {
  164. return SortDirection * LexicographicStringComparer.Comparison(a.FileInfo.Name, b.FileInfo.Name);
  165. }
  166. private int SortByDateCreated(Scene a, Scene b)
  167. {
  168. return SortDirection * DateTime.Compare(a.FileInfo.CreationTime, b.FileInfo.CreationTime);
  169. }
  170. private int SortByDateModified(Scene a, Scene b)
  171. {
  172. return SortDirection * DateTime.Compare(a.FileInfo.LastWriteTime, b.FileInfo.LastWriteTime);
  173. }
  174. private void UpdateSceneList()
  175. {
  176. ClearSceneList();
  177. if (!Directory.Exists(CurrentScenesDirectory))
  178. {
  179. Directory.CreateDirectory(CurrentScenesDirectory);
  180. }
  181. foreach (string filename in Directory.GetFiles(CurrentScenesDirectory))
  182. {
  183. if (Path.GetExtension(filename) == ".png") SceneList.Add(new Scene(filename));
  184. }
  185. SortScenes(CurrentSortMode);
  186. CurrentSceneIndex = Mathf.Clamp(CurrentSceneIndex, 0, SceneList.Count - 1);
  187. }
  188. private void UpdateDirectoryList()
  189. {
  190. string baseDirectoryName = KankyoMode ? Constants.kankyoDirectory : Constants.sceneDirectory;
  191. CurrentDirectoryList.Sort((a, b)
  192. => a.Equals(baseDirectoryName, StringComparison.InvariantCultureIgnoreCase) ? -1 : a.CompareTo(b));
  193. }
  194. private void ClearSceneList()
  195. {
  196. foreach (Scene scene in SceneList) scene.Destroy();
  197. SceneList.Clear();
  198. }
  199. private void QuickSaveScene()
  200. {
  201. if (Busy) return;
  202. byte[] data = meidoPhotoStudio.SerializeScene(kankyo: false);
  203. if (data == null) return;
  204. File.WriteAllBytes(Path.Combine(Constants.configPath, "mpstempscene"), data);
  205. }
  206. private void QuickLoadScene()
  207. {
  208. if (Busy) return;
  209. meidoPhotoStudio.ApplyScene(Path.Combine(Constants.configPath, "mpstempscene"));
  210. }
  211. private System.Collections.IEnumerator SaveSceneToFile(bool overwrite = false)
  212. {
  213. Busy = true;
  214. byte[] sceneData = meidoPhotoStudio.SerializeScene(KankyoMode);
  215. if (sceneData != null)
  216. {
  217. string screenshotPath = Utility.TempScreenshotFilename();
  218. MeidoPhotoStudio.TakeScreenshot(screenshotPath, 1, KankyoMode);
  219. do yield return new WaitForSecondsRealtime(0.2f);
  220. while (!File.Exists(screenshotPath));
  221. string scenePrefix = KankyoMode ? "mpskankyo" : "mpsscene";
  222. string fileName = $"{scenePrefix}{DateTime.Now:yyyyMMddHHmmss}.png";
  223. string savePath = Path.Combine(CurrentScenesDirectory, fileName);
  224. if (overwrite && CurrentScene != null)
  225. {
  226. savePath = CurrentScene.FileInfo.FullName;
  227. }
  228. else overwrite = false;
  229. Texture2D screenshot = new Texture2D(1, 1, TextureFormat.ARGB32, false);
  230. screenshot.LoadImage(File.ReadAllBytes(screenshotPath));
  231. int sceneWidth = (int)sceneDimensions.x;
  232. int sceneHeight = (int)sceneDimensions.y;
  233. Utility.ResizeToFit(screenshot, sceneWidth, sceneHeight);
  234. using (FileStream fileStream = File.Create(savePath))
  235. {
  236. byte[] encodedPng = screenshot.EncodeToPNG();
  237. fileStream.Write(encodedPng, 0, encodedPng.Length);
  238. fileStream.Write(sceneData, 0, sceneData.Length);
  239. }
  240. UnityEngine.Object.DestroyImmediate(screenshot);
  241. if (overwrite)
  242. {
  243. File.SetCreationTime(savePath, CurrentScene.FileInfo.CreationTime);
  244. CurrentScene.Destroy();
  245. SceneList.RemoveAt(CurrentSceneIndex);
  246. }
  247. SceneList.Add(new Scene(savePath));
  248. SortScenes(CurrentSortMode);
  249. }
  250. Busy = false;
  251. }
  252. public class Scene
  253. {
  254. public const int initialNumberOfMaids = -2;
  255. public Texture2D Thumbnail { get; }
  256. public FileInfo FileInfo { get; set; }
  257. public int NumberOfMaids { get; private set; } = initialNumberOfMaids;
  258. public Scene(string filePath)
  259. {
  260. FileInfo = new FileInfo(filePath);
  261. Thumbnail = new Texture2D(1, 1, TextureFormat.ARGB32, false);
  262. Thumbnail.LoadImage(File.ReadAllBytes(FileInfo.FullName));
  263. }
  264. public void GetNumberOfMaids()
  265. {
  266. if (NumberOfMaids != initialNumberOfMaids) return;
  267. string filePath = FileInfo.FullName;
  268. byte[] sceneData = MeidoPhotoStudio.DecompressScene(filePath);
  269. if (sceneData == null) return;
  270. using (MemoryStream memoryStream = new MemoryStream(sceneData))
  271. using (BinaryReader binaryReader = new BinaryReader(memoryStream, System.Text.Encoding.UTF8))
  272. {
  273. try
  274. {
  275. if (binaryReader.ReadString() != "MPS_SCENE")
  276. {
  277. Utility.LogWarning($"'{filePath}' is not a {MeidoPhotoStudio.pluginName} scene");
  278. return;
  279. }
  280. if (binaryReader.ReadInt32() > MeidoPhotoStudio.sceneVersion)
  281. {
  282. Utility.LogWarning(
  283. $"'{filePath}' is made in a newer version of {MeidoPhotoStudio.pluginName}"
  284. );
  285. return;
  286. }
  287. NumberOfMaids = binaryReader.ReadInt32();
  288. }
  289. catch (Exception e)
  290. {
  291. Utility.LogWarning($"Failed to deserialize scene '{filePath}' because {e.Message}");
  292. return;
  293. }
  294. }
  295. }
  296. public void Destroy()
  297. {
  298. if (Thumbnail != null) UnityEngine.Object.DestroyImmediate(Thumbnail);
  299. }
  300. }
  301. }
  302. }