MeidoPhotoStudio.cs 20 KB

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