MeidoPhotoStudio.cs 20 KB

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