PropManager.cs 21 KB

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