PropManager.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564
  1. using System;
  2. using System.IO;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using UnityEngine;
  6. using UnityEngine.Rendering;
  7. using BepInEx.Configuration;
  8. namespace COM3D2.MeidoPhotoStudio.Plugin
  9. {
  10. using static MenuFileUtility;
  11. internal class PropManager : IManager, ISerializable
  12. {
  13. public const string header = "PROP";
  14. private static readonly ConfigEntry<bool> modItemsOnly;
  15. public static bool ModItemsOnly => modItemsOnly.Value;
  16. private MeidoManager meidoManager;
  17. private static bool cubeActive = true;
  18. public static bool CubeActive
  19. {
  20. get => cubeActive;
  21. set
  22. {
  23. if (value != cubeActive)
  24. {
  25. cubeActive = value;
  26. CubeActiveChange?.Invoke(null, EventArgs.Empty);
  27. }
  28. }
  29. }
  30. private static bool cubeSmall;
  31. public static bool CubeSmall
  32. {
  33. get => cubeSmall;
  34. set
  35. {
  36. if (value != cubeSmall)
  37. {
  38. cubeSmall = value;
  39. CubeSmallChange?.Invoke(null, EventArgs.Empty);
  40. }
  41. }
  42. }
  43. private static event EventHandler CubeActiveChange;
  44. private static event EventHandler CubeSmallChange;
  45. private List<DragPointDogu> doguList = new List<DragPointDogu>();
  46. public int DoguCount => doguList.Count;
  47. public event EventHandler DoguListChange;
  48. public event EventHandler DoguSelectChange;
  49. public string[] PropNameList
  50. {
  51. get
  52. {
  53. return doguList.Count == 0
  54. ? new[] { Translation.Get("systemMessage", "noProps") }
  55. : doguList.Select(dogu => dogu.Name).ToArray();
  56. }
  57. }
  58. public int CurrentDoguIndex { get; private set; } = 0;
  59. public DragPointDogu CurrentDogu => DoguCount == 0 ? null : doguList[CurrentDoguIndex];
  60. static PropManager()
  61. {
  62. modItemsOnly = Configuration.Config.Bind<bool>(
  63. "Prop", "ModItemsOnly",
  64. false,
  65. "Disable waiting for and loading base game clothing"
  66. );
  67. }
  68. public PropManager(MeidoManager meidoManager)
  69. {
  70. this.meidoManager = meidoManager;
  71. this.meidoManager.BeginCallMeidos += DetachProps;
  72. this.meidoManager.EndCallMeidos += OnEndCall;
  73. }
  74. public void Serialize(BinaryWriter binaryWriter)
  75. {
  76. binaryWriter.Write(header);
  77. binaryWriter.Write(doguList.Count);
  78. foreach (DragPointDogu dogu in doguList)
  79. {
  80. binaryWriter.Write(dogu.assetName);
  81. AttachPointInfo info = dogu.attachPointInfo;
  82. info.Serialize(binaryWriter);
  83. binaryWriter.WriteVector3(dogu.MyObject.position);
  84. binaryWriter.WriteQuaternion(dogu.MyObject.rotation);
  85. binaryWriter.WriteVector3(dogu.MyObject.localScale);
  86. }
  87. }
  88. public void Deserialize(BinaryReader binaryReader)
  89. {
  90. Dictionary<string, string> modToModPath = null;
  91. ClearDogu();
  92. int numberOfProps = binaryReader.ReadInt32();
  93. for (int i = 0; i < numberOfProps; i++)
  94. {
  95. string assetName = binaryReader.ReadString();
  96. bool result = false;
  97. if (assetName.EndsWith(".menu") && assetName.Contains('#') && modToModPath == null)
  98. {
  99. modToModPath = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
  100. foreach (string mod in Menu.GetModFiles()) modToModPath.Add(Path.GetFileName(mod), mod);
  101. }
  102. result = SpawnFromAssetString(assetName, modToModPath);
  103. AttachPointInfo info = AttachPointInfo.Deserialize(binaryReader);
  104. Vector3 position = binaryReader.ReadVector3();
  105. Quaternion rotation = binaryReader.ReadQuaternion();
  106. Vector3 scale = binaryReader.ReadVector3();
  107. if (result)
  108. {
  109. DragPointDogu dogu = doguList[i];
  110. Transform obj = dogu.MyObject;
  111. obj.position = position;
  112. obj.rotation = rotation;
  113. obj.localScale = scale;
  114. dogu.attachPointInfo = info;
  115. }
  116. }
  117. CurrentDoguIndex = 0;
  118. GameMain.Instance.StartCoroutine(DeserializeAttach());
  119. }
  120. private System.Collections.IEnumerator DeserializeAttach()
  121. {
  122. yield return new WaitForEndOfFrame();
  123. foreach (DragPointDogu dogu in doguList)
  124. {
  125. AttachPointInfo info = dogu.attachPointInfo;
  126. if (info.AttachPoint != AttachPoint.None)
  127. {
  128. Meido parent = meidoManager.GetMeido(info.MaidIndex);
  129. if (parent != null)
  130. {
  131. Transform obj = dogu.MyObject;
  132. Vector3 position = obj.position;
  133. Vector3 scale = obj.localScale;
  134. Quaternion rotation = obj.rotation;
  135. Transform point = parent.IKManager.GetAttachPointTransform(info.AttachPoint);
  136. dogu.MyObject.SetParent(point, true);
  137. info = new AttachPointInfo(
  138. info.AttachPoint,
  139. parent.Maid.status.guid,
  140. parent.Slot
  141. );
  142. obj.position = position;
  143. obj.localScale = scale;
  144. obj.rotation = rotation;
  145. }
  146. }
  147. }
  148. }
  149. public void Activate()
  150. {
  151. CubeSmallChange += OnCubeSmall;
  152. CubeActiveChange += OnCubeActive;
  153. }
  154. public void Deactivate()
  155. {
  156. ClearDogu();
  157. CubeSmallChange -= OnCubeSmall;
  158. CubeActiveChange -= OnCubeActive;
  159. }
  160. public void Update() { }
  161. private GameObject GetDeploymentObject()
  162. {
  163. return GameObject.Find("Deployment Object Parent")
  164. ?? new GameObject("Deployment Object Parent");
  165. }
  166. public bool SpawnModItemProp(ModItem modItem)
  167. {
  168. GameObject dogu = MenuFileUtility.LoadModel(modItem);
  169. string name = modItem.MenuFile;
  170. if (modItem.IsOfficialMod) name = Path.GetFileName(name);
  171. if (dogu != null) AttachDragPoint(dogu, modItem.ToString(), name, new Vector3(0f, 0f, 0.5f));
  172. return dogu != null;
  173. }
  174. public bool SpawnMyRoomProp(MyRoomItem item)
  175. {
  176. MyRoomCustom.PlacementData.Data data = MyRoomCustom.PlacementData.GetData(item.ID);
  177. GameObject dogu = GameObject.Instantiate(data.GetPrefab());
  178. string name = Translation.Get("myRoomPropNames", item.PrefabName);
  179. if (dogu != null)
  180. {
  181. GameObject finalDogu = new GameObject();
  182. dogu.transform.SetParent(finalDogu.transform, true);
  183. finalDogu.transform.SetParent(GetDeploymentObject().transform, false);
  184. AttachDragPoint(finalDogu, item.ToString(), name, new Vector3(0f, 0f, 0.5f));
  185. }
  186. else Utility.LogInfo($"Could not load MyRoomCreative prop '{item.PrefabName}'");
  187. return dogu != null;
  188. }
  189. public bool SpawnBG(string assetName)
  190. {
  191. if (assetName.StartsWith("BG_")) assetName = assetName.Substring(3);
  192. GameObject obj = GameMain.Instance.BgMgr.CreateAssetBundle(assetName)
  193. ?? Resources.Load<GameObject>("BG/" + assetName)
  194. ?? Resources.Load<GameObject>("BG/2_0/" + assetName);
  195. if (obj != null)
  196. {
  197. GameObject dogu = GameObject.Instantiate(obj);
  198. string name = Translation.Get("bgNames", assetName);
  199. dogu.transform.localScale = Vector3.one * 0.1f;
  200. AttachDragPoint(dogu, $"BG_{assetName}", name, new Vector3(0f, 0f, 0.5f));
  201. }
  202. return obj != null;
  203. }
  204. public bool SpawnObject(string assetName)
  205. {
  206. // TODO: Add a couple more things to ignore list
  207. GameObject dogu = null;
  208. string doguName = Translation.Get("propNames", assetName, false);
  209. Vector3 doguPosition = new Vector3(0f, 0f, 0.5f);
  210. if (assetName.EndsWith(".menu"))
  211. {
  212. dogu = MenuFileUtility.LoadModel(assetName);
  213. string handItem = Utility.HandItemToOdogu(assetName);
  214. if (Translation.Has("propNames", handItem)) doguName = Translation.Get("propNames", handItem);
  215. }
  216. else if (assetName.StartsWith("mirror"))
  217. {
  218. Material mirrorMaterial = new Material(Shader.Find("Mirror"));
  219. dogu = GameObject.CreatePrimitive(PrimitiveType.Plane);
  220. Renderer mirrorRenderer = dogu.GetComponent<Renderer>();
  221. mirrorRenderer.material = mirrorMaterial;
  222. mirrorRenderer.enabled = true;
  223. MirrorReflection2 mirrorReflection = dogu.AddComponent<MirrorReflection2>();
  224. mirrorReflection.m_TextureSize = 2048;
  225. Vector3 localPosition = new Vector3(0f, 0.96f, 0f);
  226. dogu.transform.Rotate(dogu.transform.right, 90f);
  227. switch (assetName)
  228. {
  229. case "mirror1":
  230. dogu.transform.localScale = new Vector3(0.2f, 0.4f, 0.2f);
  231. break;
  232. case "mirror2":
  233. dogu.transform.localScale = new Vector3(0.1f, 0.4f, 0.2f);
  234. break;
  235. case "mirror3":
  236. localPosition.y = 0.85f;
  237. dogu.transform.localScale = new Vector3(0.03f, 0.18f, 0.124f);
  238. break;
  239. }
  240. dogu.transform.localPosition = localPosition;
  241. }
  242. else if (assetName.IndexOf(':') >= 0)
  243. {
  244. string[] assetParts = assetName.Split(':');
  245. GameObject obj = GameMain.Instance.BgMgr.CreateAssetBundle(assetParts[0])
  246. ?? Resources.Load<GameObject>("BG/" + assetParts[0]);
  247. try
  248. {
  249. GameObject bg = GameObject.Instantiate(obj);
  250. int num = int.Parse(assetParts[1]);
  251. dogu = bg.transform.GetChild(num).gameObject;
  252. dogu.transform.SetParent(null);
  253. GameObject.Destroy(bg);
  254. }
  255. catch { }
  256. }
  257. else
  258. {
  259. GameObject obj = GameMain.Instance.BgMgr.CreateAssetBundle(assetName)
  260. ?? Resources.Load<GameObject>("Prefab/" + assetName);
  261. try
  262. {
  263. dogu = GameObject.Instantiate<GameObject>(obj);
  264. dogu.transform.localPosition = Vector3.zero;
  265. MeshRenderer[] meshRenderers = dogu.GetComponentsInChildren<MeshRenderer>();
  266. for (int i = 0; i < meshRenderers.Length; i++)
  267. {
  268. if (meshRenderers[i] != null
  269. && meshRenderers[i].gameObject.name.ToLower().IndexOf("castshadow") < 0
  270. ) meshRenderers[i].shadowCastingMode = ShadowCastingMode.Off;
  271. }
  272. Collider collider = dogu.transform.GetComponent<Collider>();
  273. if (collider != null) collider.enabled = false;
  274. foreach (Transform transform in dogu.transform)
  275. {
  276. collider = transform.GetComponent<Collider>();
  277. if (collider != null)
  278. {
  279. collider.enabled = false;
  280. }
  281. }
  282. }
  283. catch { }
  284. #region particle system experiment
  285. // if (asset.StartsWith("Particle/"))
  286. // {
  287. // ParticleSystem particleSystem = go.GetComponent<ParticleSystem>();
  288. // if (particleSystem != null)
  289. // {
  290. // ParticleSystem.MainModule main;
  291. // main = particleSystem.main;
  292. // main.loop = true;
  293. // main.duration = Mathf.Infinity;
  294. // ParticleSystem[] particleSystems = particleSystem.GetComponents<ParticleSystem>();
  295. // foreach (ParticleSystem part in particleSystems)
  296. // {
  297. // ParticleSystem.EmissionModule emissionModule = part.emission;
  298. // ParticleSystem.Burst[] bursts = new ParticleSystem.Burst[emissionModule.burstCount];
  299. // emissionModule.GetBursts(bursts);
  300. // for (int i = 0; i < bursts.Length; i++)
  301. // {
  302. // bursts[i].cycleCount = Int32.MaxValue;
  303. // }
  304. // emissionModule.SetBursts(bursts);
  305. // main = part.main;
  306. // main.loop = true;
  307. // main.duration = Mathf.Infinity;
  308. // }
  309. // }
  310. // }
  311. #endregion
  312. }
  313. if (dogu != null)
  314. {
  315. AttachDragPoint(dogu, assetName, doguName, doguPosition);
  316. return true;
  317. }
  318. else
  319. {
  320. Utility.LogInfo($"Could not spawn object '{assetName}'");
  321. }
  322. return false;
  323. }
  324. private bool SpawnFromAssetString(string assetName, Dictionary<string, string> modDict = null)
  325. {
  326. bool result = false;
  327. if (assetName.EndsWith(".menu"))
  328. {
  329. if (assetName.Contains('#'))
  330. {
  331. string[] assetParts = assetName.Split('#');
  332. string menuFile = modDict == null ? Menu.GetModPathFileName(assetParts[0]) : modDict[assetParts[0]];
  333. ModItem item = ModItem.OfficialMod(menuFile);
  334. item.BaseMenuFile = assetParts[1];
  335. result = SpawnModItemProp(item);
  336. }
  337. else if (assetName.StartsWith("handitem")) result = SpawnObject(assetName);
  338. else result = SpawnModItemProp(ModItem.Mod(assetName));
  339. }
  340. else if (assetName.StartsWith("MYR_"))
  341. {
  342. string[] assetParts = assetName.Split('#');
  343. int id = int.Parse(assetParts[0].Substring(4));
  344. string prefabName;
  345. if (assetParts.Length == 2 && !string.IsNullOrEmpty(assetParts[1])) prefabName = assetParts[1];
  346. else
  347. {
  348. // deserialize modifiedMM and maybe MM 23.0+.
  349. MyRoomCustom.PlacementData.Data data = MyRoomCustom.PlacementData.GetData(id);
  350. prefabName = !string.IsNullOrEmpty(data.resourceName) ? data.resourceName : data.assetName;
  351. }
  352. result = SpawnMyRoomProp(new MyRoomItem() { ID = id, PrefabName = prefabName });
  353. }
  354. else if (assetName.StartsWith("BG_")) result = SpawnBG(assetName);
  355. else result = SpawnObject(assetName);
  356. return result;
  357. }
  358. private void AttachDragPoint(GameObject dogu, string assetName, string name, Vector3 position)
  359. {
  360. // TODO: Figure out why some props aren't centred properly
  361. // Doesn't happen in MM but even after copy pasting the code, it doesn't work :/
  362. dogu.name = name;
  363. dogu.transform.position = position;
  364. DragPointDogu dragDogu = DragPoint.Make<DragPointDogu>(
  365. PrimitiveType.Cube, Vector3.one * 0.12f, DragPoint.LightBlue
  366. );
  367. dragDogu.Initialize(() => dogu.transform.position, () => Vector3.zero);
  368. dragDogu.Set(dogu.transform);
  369. dragDogu.AddGizmo(scale: 0.45f, mode: CustomGizmo.GizmoMode.World);
  370. dragDogu.ConstantScale = true;
  371. dragDogu.Delete += DeleteDogu;
  372. dragDogu.Select += SelectDogu;
  373. dragDogu.DragPointScale = CubeSmall ? DragPointGeneral.smallCube : 1f;
  374. dragDogu.assetName = assetName;
  375. doguList.Add(dragDogu);
  376. OnDoguListChange();
  377. }
  378. public void SetCurrentDogu(int doguIndex)
  379. {
  380. if (doguIndex >= 0 && doguIndex < DoguCount)
  381. {
  382. this.CurrentDoguIndex = doguIndex;
  383. this.DoguSelectChange?.Invoke(this, EventArgs.Empty);
  384. }
  385. }
  386. public void RemoveDogu(int doguIndex)
  387. {
  388. if (doguIndex >= 0 && doguIndex < DoguCount)
  389. {
  390. DestroyDogu(doguList[doguIndex]);
  391. doguList.RemoveAt(doguIndex);
  392. CurrentDoguIndex = Utility.Bound(CurrentDoguIndex, 0, DoguCount - 1);
  393. OnDoguListChange();
  394. }
  395. }
  396. public void CopyDogu(int doguIndex)
  397. {
  398. if (doguIndex >= 0 && doguIndex < DoguCount)
  399. {
  400. SpawnFromAssetString(doguList[doguIndex].assetName);
  401. }
  402. }
  403. public void AttachProp(
  404. int doguIndex, AttachPoint attachPoint, Meido meido, bool worldPositionStays = true
  405. )
  406. {
  407. if (doguList.Count == 0 || doguIndex >= doguList.Count || doguIndex < 0) return;
  408. AttachProp(doguList[doguIndex], attachPoint, meido, worldPositionStays);
  409. }
  410. private void AttachProp(
  411. DragPointDogu dragDogu, AttachPoint attachPoint, Meido meido, bool worldPositionStays = true
  412. )
  413. {
  414. GameObject dogu = dragDogu.MyGameObject;
  415. Transform attachPointTransform = meido?.IKManager.GetAttachPointTransform(attachPoint);
  416. // ?? GetDeploymentObject().transform;
  417. dragDogu.attachPointInfo = new AttachPointInfo(
  418. attachPoint: meido == null ? AttachPoint.None : attachPoint,
  419. maidGuid: meido == null ? String.Empty : meido.Maid.status.guid,
  420. maidIndex: meido == null ? -1 : meido.Slot
  421. );
  422. Vector3 position = dogu.transform.position;
  423. Quaternion rotation = dogu.transform.rotation;
  424. Vector3 scale = dogu.transform.localScale;
  425. dogu.transform.SetParent(attachPointTransform, worldPositionStays);
  426. if (worldPositionStays)
  427. {
  428. dogu.transform.position = position;
  429. dogu.transform.rotation = rotation;
  430. }
  431. else
  432. {
  433. dogu.transform.localPosition = Vector3.zero;
  434. dogu.transform.rotation = Quaternion.identity;
  435. }
  436. dogu.transform.localScale = scale;
  437. if (meido == null) Utility.FixGameObjectScale(dogu);
  438. }
  439. private void DetachProps(object sender, EventArgs args)
  440. {
  441. foreach (DragPointDogu dogu in doguList)
  442. {
  443. if (dogu.attachPointInfo.AttachPoint != AttachPoint.None)
  444. {
  445. dogu.MyObject.SetParent(null, /*GetDeploymentObject().transform*/ true);
  446. }
  447. }
  448. }
  449. private void ClearDogu()
  450. {
  451. for (int i = DoguCount - 1; i >= 0; i--)
  452. {
  453. DestroyDogu(doguList[i]);
  454. }
  455. doguList.Clear();
  456. CurrentDoguIndex = 0;
  457. }
  458. private void OnEndCall(object sender, EventArgs args) => ReattachProps(useGuid: true);
  459. private void ReattachProps(bool useGuid, bool forceStay = false)
  460. {
  461. foreach (DragPointDogu dragDogu in doguList)
  462. {
  463. AttachPointInfo info = dragDogu.attachPointInfo;
  464. Meido meido = useGuid
  465. ? this.meidoManager.GetMeido(info.MaidGuid)
  466. : this.meidoManager.GetMeido(info.MaidIndex);
  467. bool worldPositionStays = forceStay || meido == null;
  468. AttachProp(dragDogu, dragDogu.attachPointInfo.AttachPoint, meido, worldPositionStays);
  469. }
  470. }
  471. private void DeleteDogu(object sender, EventArgs args)
  472. {
  473. DragPointDogu dogu = (DragPointDogu)sender;
  474. RemoveDogu(doguList.FindIndex(dragDogu => dragDogu == dogu));
  475. }
  476. private void DestroyDogu(DragPointDogu dogu)
  477. {
  478. if (dogu == null) return;
  479. dogu.Delete -= DeleteDogu;
  480. dogu.Select -= SelectDogu;
  481. GameObject.Destroy(dogu.gameObject);
  482. }
  483. private void SelectDogu(object sender, EventArgs args)
  484. {
  485. DragPointDogu dogu = (DragPointDogu)sender;
  486. SetCurrentDogu(doguList.IndexOf(dogu));
  487. }
  488. private void OnCubeSmall(object sender, EventArgs args)
  489. {
  490. foreach (DragPointDogu dogu in doguList)
  491. {
  492. dogu.DragPointScale = CubeSmall ? DragPointGeneral.smallCube : 1f;
  493. }
  494. }
  495. private void OnCubeActive(object sender, EventArgs args)
  496. {
  497. foreach (DragPointDogu dragPoint in doguList)
  498. {
  499. dragPoint.gameObject.SetActive(CubeActive);
  500. }
  501. }
  502. private void OnDoguListChange()
  503. {
  504. this.DoguListChange?.Invoke(this, EventArgs.Empty);
  505. }
  506. }
  507. }