MeidoPhotoStudio.cs 17 KB

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