MeidoPhotoStudio.cs 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458
  1. using System;
  2. using System.IO;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using UnityEngine;
  6. using UnityEngine.SceneManagement;
  7. using Ionic.Zlib;
  8. using BepInEx;
  9. namespace COM3D2.MeidoPhotoStudio.Plugin
  10. {
  11. [BepInPlugin(pluginGuid, pluginName, pluginVersion)]
  12. public class MeidoPhotoStudio : BaseUnityPlugin
  13. {
  14. private static CameraMain mainCamera = GameMain.Instance.MainCamera;
  15. private static event EventHandler<ScreenshotEventArgs> ScreenshotEvent;
  16. private const string pluginGuid = "com.habeebweeb.com3d2.meidophotostudio";
  17. public const string pluginName = "MeidoPhotoStudio";
  18. public const string pluginVersion = "0.0.0";
  19. public const int sceneVersion = 1100;
  20. public const int kankyoMagic = -765;
  21. public static string pluginString = $"{pluginName} {pluginVersion}";
  22. private WindowManager windowManager;
  23. private SceneManager sceneManager;
  24. private MeidoManager meidoManager;
  25. private EnvironmentManager environmentManager;
  26. private MessageWindowManager messageWindowManager;
  27. private LightManager lightManager;
  28. private PropManager propManager;
  29. private EffectManager effectManager;
  30. private Constants.Scene currentScene;
  31. private bool initialized = false;
  32. private bool active = false;
  33. private bool uiActive = false;
  34. private void Awake()
  35. {
  36. ScreenshotEvent += OnScreenshotEvent;
  37. DontDestroyOnLoad(this);
  38. }
  39. private void Start()
  40. {
  41. Constants.Initialize();
  42. Translation.Initialize(Translation.CurrentLanguage);
  43. UnityEngine.SceneManagement.SceneManager.sceneLoaded += OnSceneLoaded;
  44. }
  45. public byte[] SerializeScene(bool kankyo = false)
  46. {
  47. if (meidoManager.Busy) return null;
  48. byte[] compressedData;
  49. using (MemoryStream memoryStream = new MemoryStream())
  50. using (DeflateStream deflateStream = new DeflateStream(memoryStream, CompressionMode.Compress))
  51. using (BinaryWriter binaryWriter = new BinaryWriter(deflateStream, System.Text.Encoding.UTF8))
  52. {
  53. binaryWriter.Write("MPS_SCENE");
  54. binaryWriter.Write(sceneVersion);
  55. binaryWriter.Write(kankyo ? kankyoMagic : meidoManager.ActiveMeidoList.Count);
  56. effectManager.Serialize(binaryWriter);
  57. environmentManager.Serialize(binaryWriter, kankyo);
  58. lightManager.Serialize(binaryWriter);
  59. if (!kankyo)
  60. {
  61. messageWindowManager.Serialize(binaryWriter);
  62. // meidomanager has to be serialized before propmanager because reattached props will be in the
  63. // wrong place after a maid's pose is deserialized.
  64. meidoManager.Serialize(binaryWriter);
  65. }
  66. propManager.Serialize(binaryWriter);
  67. binaryWriter.Write("END");
  68. deflateStream.Close();
  69. compressedData = memoryStream.ToArray();
  70. }
  71. return compressedData;
  72. }
  73. public static byte[] DecompressScene(string filePath)
  74. {
  75. if (!File.Exists(filePath))
  76. {
  77. Utility.LogWarning($"Scene file '{filePath}' does not exist.");
  78. return null;
  79. }
  80. byte[] compressedData;
  81. using (FileStream fileStream = File.OpenRead(filePath))
  82. {
  83. if (Utility.IsPngFile(fileStream))
  84. {
  85. if (!Utility.SeekPngEnd(fileStream))
  86. {
  87. Utility.LogWarning($"'{filePath}' is not a PNG file");
  88. return null;
  89. }
  90. if (fileStream.Position == fileStream.Length)
  91. {
  92. Utility.LogWarning($"'{filePath}' contains no scene data");
  93. return null;
  94. }
  95. int dataLength = (int)(fileStream.Length - fileStream.Position);
  96. compressedData = new byte[dataLength];
  97. fileStream.Read(compressedData, 0, dataLength);
  98. }
  99. else
  100. {
  101. compressedData = new byte[fileStream.Length];
  102. fileStream.Read(compressedData, 0, compressedData.Length);
  103. }
  104. }
  105. return DeflateStream.UncompressBuffer(compressedData);
  106. }
  107. public void ApplyScene(string filePath)
  108. {
  109. if (meidoManager.Busy) return;
  110. byte[] sceneBinary = DecompressScene(filePath);
  111. if (sceneBinary == null) return;
  112. string header = string.Empty;
  113. string previousHeader = string.Empty;
  114. using (MemoryStream memoryStream = new MemoryStream(sceneBinary))
  115. using (BinaryReader binaryReader = new BinaryReader(memoryStream, System.Text.Encoding.UTF8))
  116. {
  117. try
  118. {
  119. if (binaryReader.ReadString() != "MPS_SCENE")
  120. {
  121. Utility.LogWarning($"'{filePath}' is not a {pluginName} scene");
  122. return;
  123. }
  124. if (binaryReader.ReadInt32() > sceneVersion)
  125. {
  126. Utility.LogWarning($"'{filePath}' is made in a newer version of {pluginName}");
  127. return;
  128. }
  129. binaryReader.ReadInt32(); // Number of Maids
  130. while ((header = binaryReader.ReadString()) != "END")
  131. {
  132. switch (header)
  133. {
  134. case MessageWindowManager.header:
  135. messageWindowManager.Deserialize(binaryReader);
  136. break;
  137. case EnvironmentManager.header:
  138. environmentManager.Deserialize(binaryReader);
  139. break;
  140. case MeidoManager.header:
  141. meidoManager.Deserialize(binaryReader);
  142. break;
  143. case PropManager.header:
  144. propManager.Deserialize(binaryReader);
  145. break;
  146. case LightManager.header:
  147. lightManager.Deserialize(binaryReader);
  148. break;
  149. case EffectManager.header:
  150. effectManager.Deserialize(binaryReader);
  151. break;
  152. default: throw new Exception($"Unknown header '{header}'");
  153. }
  154. previousHeader = header;
  155. }
  156. }
  157. catch (Exception e)
  158. {
  159. Utility.LogError(
  160. $"Failed to deserialize scene '{filePath}' because {e.Message}"
  161. + $"\nCurrent header: '{header}'. Last header: '{previousHeader}'"
  162. );
  163. return;
  164. }
  165. }
  166. }
  167. public static void TakeScreenshot(ScreenshotEventArgs args) => ScreenshotEvent?.Invoke(null, args);
  168. public static void TakeScreenshot(string path = "", int superSize = -1, bool hideMaids = false)
  169. {
  170. TakeScreenshot(new ScreenshotEventArgs() { Path = path, SuperSize = superSize, HideMaids = hideMaids });
  171. }
  172. private void OnScreenshotEvent(object sender, ScreenshotEventArgs args)
  173. {
  174. StartCoroutine(Screenshot(args));
  175. }
  176. private void Update()
  177. {
  178. if (currentScene == Constants.Scene.Daily)
  179. {
  180. if (Input.GetKeyDown(KeyCode.F6))
  181. {
  182. if (active) Deactivate();
  183. else Activate();
  184. }
  185. if (active)
  186. {
  187. if (!Input.GetKey(KeyCode.Q) && !Utility.GetModKey(Utility.ModKey.Control)
  188. && Input.GetKeyDown(KeyCode.S)
  189. ) TakeScreenshot();
  190. meidoManager.Update();
  191. environmentManager.Update();
  192. windowManager.Update();
  193. effectManager.Update();
  194. sceneManager.Update();
  195. }
  196. }
  197. }
  198. private IEnumerator Screenshot(ScreenshotEventArgs args)
  199. {
  200. // Hide UI and dragpoints
  201. GameObject editUI = GameObject.Find("/UI Root/Camera");
  202. GameObject fpsViewer =
  203. UTY.GetChildObject(GameMain.Instance.gameObject, "SystemUI Root/FpsCounter", false);
  204. GameObject sysDialog =
  205. UTY.GetChildObject(GameMain.Instance.gameObject, "SystemUI Root/SystemDialog", false);
  206. GameObject sysShortcut =
  207. UTY.GetChildObject(GameMain.Instance.gameObject, "SystemUI Root/SystemShortcut", false);
  208. editUI.SetActive(false);
  209. fpsViewer.SetActive(false);
  210. sysDialog.SetActive(false);
  211. sysShortcut.SetActive(false);
  212. uiActive = false;
  213. List<Meido> activeMeidoList = this.meidoManager.ActiveMeidoList;
  214. bool[] isIK = new bool[activeMeidoList.Count];
  215. bool[] isVisible = new bool[activeMeidoList.Count];
  216. for (int i = 0; i < activeMeidoList.Count; i++)
  217. {
  218. Meido meido = activeMeidoList[i];
  219. isIK[i] = meido.IK;
  220. isVisible[i] = meido.Maid.Visible;
  221. if (meido.IK) meido.IK = false;
  222. if (args.HideMaids) meido.Maid.Visible = false;
  223. }
  224. bool[] isCubeActive = {
  225. MeidoDragPointManager.CubeActive,
  226. PropManager.CubeActive,
  227. LightManager.CubeActive,
  228. EnvironmentManager.CubeActive
  229. };
  230. MeidoDragPointManager.CubeActive = false;
  231. PropManager.CubeActive = false;
  232. LightManager.CubeActive = false;
  233. EnvironmentManager.CubeActive = false;
  234. GizmoRender.UIVisible = false;
  235. yield return new WaitForEndOfFrame();
  236. // Take Screenshot
  237. int[] defaultSuperSize = new[] { 1, 2, 4 };
  238. int selectedSuperSize = args.SuperSize < 1
  239. ? defaultSuperSize[(int)GameMain.Instance.CMSystem.ScreenShotSuperSize]
  240. : args.SuperSize;
  241. string path = string.IsNullOrEmpty(args.Path)
  242. ? Utility.ScreenshotFilename()
  243. : args.Path;
  244. Application.CaptureScreenshot(path, selectedSuperSize);
  245. GameMain.Instance.SoundMgr.PlaySe("se022.ogg", false);
  246. yield return new WaitForEndOfFrame();
  247. // Show UI and dragpoints
  248. uiActive = true;
  249. editUI.SetActive(true);
  250. fpsViewer.SetActive(GameMain.Instance.CMSystem.ViewFps);
  251. sysDialog.SetActive(true);
  252. sysShortcut.SetActive(true);
  253. for (int i = 0; i < activeMeidoList.Count; i++)
  254. {
  255. Meido meido = activeMeidoList[i];
  256. if (isIK[i]) meido.IK = true;
  257. if (args.HideMaids && isVisible[i]) meido.Maid.Visible = true;
  258. }
  259. MeidoDragPointManager.CubeActive = isCubeActive[0];
  260. PropManager.CubeActive = isCubeActive[1];
  261. LightManager.CubeActive = isCubeActive[2];
  262. EnvironmentManager.CubeActive = isCubeActive[3];
  263. GizmoRender.UIVisible = true;
  264. }
  265. private void OnGUI()
  266. {
  267. if (uiActive)
  268. {
  269. windowManager.DrawWindows();
  270. if (DropdownHelper.Visible) DropdownHelper.HandleDropdown();
  271. if (Modal.Visible) Modal.Draw();
  272. }
  273. }
  274. private void OnSceneLoaded(Scene scene, LoadSceneMode sceneMode)
  275. {
  276. currentScene = (Constants.Scene)scene.buildIndex;
  277. if (active) Deactivate();
  278. ResetCalcNearClip();
  279. }
  280. private void Initialize()
  281. {
  282. if (initialized) return;
  283. initialized = true;
  284. meidoManager = new MeidoManager();
  285. environmentManager = new EnvironmentManager(meidoManager);
  286. messageWindowManager = new MessageWindowManager();
  287. lightManager = new LightManager();
  288. propManager = new PropManager(meidoManager);
  289. effectManager = new EffectManager();
  290. sceneManager = new SceneManager(this);
  291. MaidSwitcherPane maidSwitcherPane = new MaidSwitcherPane(meidoManager);
  292. SceneWindow sceneWindow = new SceneWindow(sceneManager);
  293. windowManager = new WindowManager()
  294. {
  295. [Constants.Window.Main] = new MainWindow(meidoManager, propManager, lightManager)
  296. {
  297. [Constants.Window.Call] = new CallWindowPane(meidoManager),
  298. [Constants.Window.Pose] = new PoseWindowPane(meidoManager, maidSwitcherPane),
  299. [Constants.Window.Face] = new FaceWindowPane(meidoManager, maidSwitcherPane),
  300. [Constants.Window.BG] = new BGWindowPane(
  301. environmentManager, lightManager, effectManager, sceneWindow
  302. ),
  303. [Constants.Window.BG2] = new BG2WindowPane(meidoManager, propManager)
  304. },
  305. [Constants.Window.Message] = new MessageWindow(messageWindowManager),
  306. [Constants.Window.Save] = sceneWindow
  307. };
  308. meidoManager.BeginCallMeidos += (s, a) => uiActive = false;
  309. meidoManager.EndCallMeidos += (s, a) => uiActive = true;
  310. }
  311. private void Activate()
  312. {
  313. if (!GameMain.Instance.SysDlg.IsDecided) return;
  314. if (!initialized) Initialize();
  315. SetNearClipPlane();
  316. uiActive = true;
  317. active = true;
  318. meidoManager.Activate();
  319. environmentManager.Activate();
  320. propManager.Activate();
  321. lightManager.Activate();
  322. effectManager.Activate();
  323. windowManager.Activate();
  324. messageWindowManager.Activate();
  325. GameObject dailyPanel = GameObject.Find("UI Root").transform.Find("DailyPanel").gameObject;
  326. dailyPanel.SetActive(false);
  327. }
  328. private void Deactivate()
  329. {
  330. if (meidoManager.Busy || SceneManager.Busy) return;
  331. SystemDialog sysDialog = GameMain.Instance.SysDlg;
  332. if (sysDialog.IsDecided)
  333. {
  334. uiActive = false;
  335. active = false;
  336. string exitMessage = string.Format(Translation.Get("systemMessage", "exitConfirm"), pluginName);
  337. sysDialog.Show(exitMessage, SystemDialog.TYPE.OK_CANCEL,
  338. f_dgOk: () =>
  339. {
  340. sysDialog.Close();
  341. ResetCalcNearClip();
  342. meidoManager.Deactivate();
  343. environmentManager.Deactivate();
  344. propManager.Deactivate();
  345. lightManager.Deactivate();
  346. effectManager.Deactivate();
  347. messageWindowManager.Deactivate();
  348. windowManager.Deactivate();
  349. Modal.Close();
  350. GameObject dailyPanel = GameObject.Find("UI Root")?.transform.Find("DailyPanel")?.gameObject;
  351. dailyPanel?.SetActive(true);
  352. Configuration.Config.Save();
  353. },
  354. f_dgCancel: () =>
  355. {
  356. sysDialog.Close();
  357. uiActive = true;
  358. active = true;
  359. }
  360. );
  361. }
  362. }
  363. private void SetNearClipPlane()
  364. {
  365. mainCamera.StopAllCoroutines();
  366. mainCamera.m_bCalcNearClip = false;
  367. mainCamera.camera.nearClipPlane = 0.01f;
  368. }
  369. private void ResetCalcNearClip()
  370. {
  371. if (mainCamera.m_bCalcNearClip) return;
  372. mainCamera.StopAllCoroutines();
  373. mainCamera.m_bCalcNearClip = true;
  374. mainCamera.Start();
  375. }
  376. }
  377. public class ScreenshotEventArgs : EventArgs
  378. {
  379. public string Path { get; set; } = string.Empty;
  380. public int SuperSize { get; set; } = -1;
  381. public bool HideMaids { get; set; } = false;
  382. }
  383. }