MeidoPhotoStudio.cs 19 KB

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