PropManager.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  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. public const int propDataVersion = 1000;
  15. private static readonly ConfigEntry<bool> modItemsOnly;
  16. public static bool ModItemsOnly => modItemsOnly.Value;
  17. private readonly MeidoManager meidoManager;
  18. private static bool cubeActive = true;
  19. public static bool CubeActive
  20. {
  21. get => cubeActive;
  22. set
  23. {
  24. if (value != cubeActive)
  25. {
  26. cubeActive = value;
  27. CubeActiveChange?.Invoke(null, EventArgs.Empty);
  28. }
  29. }
  30. }
  31. private static bool cubeSmall;
  32. public static bool CubeSmall
  33. {
  34. get => cubeSmall;
  35. set
  36. {
  37. if (value != cubeSmall)
  38. {
  39. cubeSmall = value;
  40. CubeSmallChange?.Invoke(null, EventArgs.Empty);
  41. }
  42. }
  43. }
  44. private static event EventHandler CubeActiveChange;
  45. private static event EventHandler CubeSmallChange;
  46. private readonly List<DragPointDogu> doguList = new List<DragPointDogu>();
  47. public int DoguCount => doguList.Count;
  48. public event EventHandler DoguListChange;
  49. public event EventHandler DoguSelectChange;
  50. public string[] PropNameList => doguList.Count == 0
  51. ? new[] { Translation.Get("systemMessage", "noProps") }
  52. : doguList.Select(dogu => dogu.Name).ToArray();
  53. public int CurrentDoguIndex { get; private set; }
  54. public DragPointDogu CurrentDogu => DoguCount == 0 ? null : doguList[CurrentDoguIndex];
  55. static PropManager()
  56. {
  57. modItemsOnly = Configuration.Config.Bind(
  58. "Prop", "ModItemsOnly",
  59. false,
  60. "Disable waiting for and loading base game clothing"
  61. );
  62. }
  63. public PropManager(MeidoManager meidoManager)
  64. {
  65. this.meidoManager = meidoManager;
  66. this.meidoManager.BeginCallMeidos += DetachProps;
  67. this.meidoManager.EndCallMeidos += OnEndCall;
  68. }
  69. public void Serialize(BinaryWriter binaryWriter)
  70. {
  71. binaryWriter.Write(header);
  72. binaryWriter.Write(propDataVersion);
  73. binaryWriter.Write(doguList.Count);
  74. foreach (DragPointDogu dogu in doguList)
  75. {
  76. binaryWriter.WriteVector3(dogu.MyObject.position);
  77. binaryWriter.WriteQuaternion(dogu.MyObject.rotation);
  78. binaryWriter.WriteVector3(dogu.MyObject.localScale);
  79. dogu.attachPointInfo.Serialize(binaryWriter);
  80. binaryWriter.Write(dogu.ShadowCasting);
  81. binaryWriter.Write(dogu.assetName);
  82. }
  83. }
  84. public void Deserialize(BinaryReader binaryReader)
  85. {
  86. Dictionary<string, string> modToModPath = null;
  87. ClearDogu();
  88. int version = binaryReader.ReadInt32();
  89. int numberOfProps = binaryReader.ReadInt32();
  90. int doguIndex = 0;
  91. for (int i = 0; i < numberOfProps; i++)
  92. {
  93. Vector3 position = binaryReader.ReadVector3();
  94. Quaternion rotation = binaryReader.ReadQuaternion();
  95. Vector3 scale = binaryReader.ReadVector3();
  96. AttachPointInfo info = AttachPointInfo.Deserialize(binaryReader);
  97. bool shadowCasting = binaryReader.ReadBoolean();
  98. string assetName = binaryReader.ReadString();
  99. if (assetName.EndsWith(".menu") && assetName.Contains('#') && modToModPath == null)
  100. {
  101. modToModPath = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
  102. foreach (string mod in Menu.GetModFiles()) modToModPath.Add(Path.GetFileName(mod), mod);
  103. }
  104. if (SpawnFromAssetString(assetName, modToModPath))
  105. {
  106. DragPointDogu dogu = doguList[doguIndex++];
  107. Transform obj = dogu.MyObject;
  108. obj.position = position;
  109. obj.rotation = rotation;
  110. obj.localScale = scale;
  111. dogu.attachPointInfo = info;
  112. dogu.ShadowCasting = shadowCasting;
  113. }
  114. }
  115. CurrentDoguIndex = 0;
  116. GameMain.Instance.StartCoroutine(DeserializeAttach());
  117. }
  118. private System.Collections.IEnumerator DeserializeAttach()
  119. {
  120. yield return new WaitForEndOfFrame();
  121. foreach (DragPointDogu dogu in doguList)
  122. {
  123. AttachPointInfo info = dogu.attachPointInfo;
  124. if (info.AttachPoint != AttachPoint.None)
  125. {
  126. Meido parent = meidoManager.GetMeido(info.MaidIndex);
  127. if (parent != null)
  128. {
  129. Transform obj = dogu.MyObject;
  130. Vector3 position = obj.position;
  131. Vector3 scale = obj.localScale;
  132. Quaternion rotation = obj.rotation;
  133. Transform point = parent.IKManager.GetAttachPointTransform(info.AttachPoint);
  134. dogu.MyObject.SetParent(point, true);
  135. info = new AttachPointInfo(
  136. info.AttachPoint,
  137. parent.Maid.status.guid,
  138. parent.Slot
  139. );
  140. dogu.attachPointInfo = info;
  141. obj.position = position;
  142. obj.localScale = scale;
  143. obj.rotation = rotation;
  144. }
  145. }
  146. }
  147. }
  148. public void Activate()
  149. {
  150. CubeSmallChange += OnCubeSmall;
  151. CubeActiveChange += OnCubeActive;
  152. }
  153. public void Deactivate()
  154. {
  155. ClearDogu();
  156. CubeSmallChange -= OnCubeSmall;
  157. CubeActiveChange -= OnCubeActive;
  158. }
  159. public void Update() { }
  160. private GameObject GetDeploymentObject()
  161. {
  162. return GameObject.Find("Deployment Object Parent")
  163. ?? new GameObject("Deployment Object Parent");
  164. }
  165. public bool SpawnModItemProp(ModItem modItem)
  166. {
  167. GameObject dogu = LoadModel(modItem);
  168. string name = modItem.MenuFile;
  169. if (modItem.IsOfficialMod) name = Path.GetFileName(name);
  170. if (dogu != null) AttachDragPoint(dogu, modItem.ToString(), name, new Vector3(0f, 0f, 0.5f));
  171. return dogu != null;
  172. }
  173. public bool SpawnMyRoomProp(MyRoomItem item)
  174. {
  175. MyRoomCustom.PlacementData.Data data = MyRoomCustom.PlacementData.GetData(item.ID);
  176. GameObject dogu = GameObject.Instantiate(data.GetPrefab());
  177. string name = Translation.Get("myRoomPropNames", item.PrefabName);
  178. if (dogu != null)
  179. {
  180. GameObject finalDogu = new GameObject();
  181. dogu.transform.SetParent(finalDogu.transform, true);
  182. finalDogu.transform.SetParent(GetDeploymentObject().transform, false);
  183. AttachDragPoint(finalDogu, item.ToString(), name, new Vector3(0f, 0f, 0.5f));
  184. }
  185. else Utility.LogInfo($"Could not load MyRoomCreative prop '{item.PrefabName}'");
  186. return dogu != null;
  187. }
  188. public bool SpawnBG(string assetName)
  189. {
  190. if (assetName.StartsWith("BG_")) assetName = assetName.Substring(3);
  191. GameObject obj = GameMain.Instance.BgMgr.CreateAssetBundle(assetName)
  192. ?? Resources.Load<GameObject>("BG/" + assetName)
  193. ?? Resources.Load<GameObject>("BG/2_0/" + assetName);
  194. if (obj != null)
  195. {
  196. GameObject dogu = GameObject.Instantiate(obj);
  197. string name = Translation.Get("bgNames", assetName);
  198. dogu.transform.localScale = Vector3.one * 0.1f;
  199. AttachDragPoint(dogu, $"BG_{assetName}", name, new Vector3(0f, 0f, 0.5f));
  200. }
  201. return obj != null;
  202. }
  203. public bool SpawnObject(string assetName)
  204. {
  205. // TODO: Add a couple more things to ignore list
  206. GameObject dogu = null;
  207. string doguName = Translation.Get("propNames", assetName, false);
  208. Vector3 doguPosition = new Vector3(0f, 0f, 0.5f);
  209. if (assetName.EndsWith(".menu"))
  210. {
  211. dogu = LoadModel(assetName);
  212. string handItem = Utility.HandItemToOdogu(assetName);
  213. if (Translation.Has("propNames", handItem)) doguName = Translation.Get("propNames", handItem);
  214. }
  215. else if (assetName.StartsWith("mirror"))
  216. {
  217. Material mirrorMaterial = new Material(Shader.Find("Mirror"));
  218. dogu = GameObject.CreatePrimitive(PrimitiveType.Plane);
  219. Renderer mirrorRenderer = dogu.GetComponent<Renderer>();
  220. mirrorRenderer.material = mirrorMaterial;
  221. mirrorRenderer.enabled = true;
  222. MirrorReflection2 mirrorReflection = dogu.AddComponent<MirrorReflection2>();
  223. mirrorReflection.m_TextureSize = 2048;
  224. Vector3 localPosition = new Vector3(0f, 0.96f, 0f);
  225. dogu.transform.Rotate(dogu.transform.right, 90f);
  226. switch (assetName)
  227. {
  228. case "mirror1":
  229. dogu.transform.localScale = new Vector3(0.2f, 0.4f, 0.2f);
  230. break;
  231. case "mirror2":
  232. dogu.transform.localScale = new Vector3(0.1f, 0.4f, 0.2f);
  233. break;
  234. case "mirror3":
  235. localPosition.y = 0.85f;
  236. dogu.transform.localScale = new Vector3(0.03f, 0.18f, 0.124f);
  237. break;
  238. }
  239. dogu.transform.localPosition = localPosition;
  240. }
  241. else if (assetName.IndexOf(':') >= 0)
  242. {
  243. string[] assetParts = assetName.Split(':');
  244. GameObject obj = GameMain.Instance.BgMgr.CreateAssetBundle(assetParts[0])
  245. ?? Resources.Load<GameObject>("BG/" + assetParts[0]);
  246. try
  247. {
  248. GameObject bg = GameObject.Instantiate(obj);
  249. int num = int.Parse(assetParts[1]);
  250. dogu = bg.transform.GetChild(num).gameObject;
  251. dogu.transform.SetParent(null);
  252. GameObject.Destroy(bg);
  253. }
  254. catch { }
  255. }
  256. else
  257. {
  258. GameObject obj = GameMain.Instance.BgMgr.CreateAssetBundle(assetName)
  259. ?? Resources.Load<GameObject>("Prefab/" + assetName)
  260. ?? Resources.Load<GameObject>("BG/" + 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])
  269. {
  270. string name = meshRenderers[i].gameObject.name;
  271. if (name.IndexOf("castshadow", StringComparison.OrdinalIgnoreCase) < 0)
  272. {
  273. meshRenderers[i].shadowCastingMode = ShadowCastingMode.Off;
  274. }
  275. }
  276. }
  277. Collider collider = dogu.transform.GetComponent<Collider>();
  278. if (collider != null) collider.enabled = false;
  279. foreach (Transform transform in dogu.transform)
  280. {
  281. collider = transform.GetComponent<Collider>();
  282. if (collider != null)
  283. {
  284. collider.enabled = false;
  285. }
  286. }
  287. }
  288. catch { }
  289. #region particle system experiment
  290. // if (asset.StartsWith("Particle/"))
  291. // {
  292. // ParticleSystem particleSystem = go.GetComponent<ParticleSystem>();
  293. // if (particleSystem != null)
  294. // {
  295. // ParticleSystem.MainModule main;
  296. // main = particleSystem.main;
  297. // main.loop = true;
  298. // main.duration = Mathf.Infinity;
  299. // ParticleSystem[] particleSystems = particleSystem.GetComponents<ParticleSystem>();
  300. // foreach (ParticleSystem part in particleSystems)
  301. // {
  302. // ParticleSystem.EmissionModule emissionModule = part.emission;
  303. // ParticleSystem.Burst[] bursts = new ParticleSystem.Burst[emissionModule.burstCount];
  304. // emissionModule.GetBursts(bursts);
  305. // for (int i = 0; i < bursts.Length; i++)
  306. // {
  307. // bursts[i].cycleCount = Int32.MaxValue;
  308. // }
  309. // emissionModule.SetBursts(bursts);
  310. // main = part.main;
  311. // main.loop = true;
  312. // main.duration = Mathf.Infinity;
  313. // }
  314. // }
  315. // }
  316. #endregion particle system experiment
  317. }
  318. if (dogu != null)
  319. {
  320. AttachDragPoint(dogu, assetName, doguName, doguPosition);
  321. return true;
  322. }
  323. Utility.LogInfo($"Could not spawn object '{assetName}'");
  324. return false;
  325. }
  326. private bool SpawnFromAssetString(string assetName, Dictionary<string, string> modDict = null)
  327. {
  328. bool result;
  329. if (assetName.EndsWith(".menu"))
  330. {
  331. if (assetName.Contains('#'))
  332. {
  333. string[] assetParts = assetName.Split('#');
  334. string menuFile = modDict == null ? Menu.GetModPathFileName(assetParts[0]) : modDict[assetParts[0]];
  335. ModItem item = ModItem.OfficialMod(menuFile);
  336. item.BaseMenuFile = assetParts[1];
  337. result = SpawnModItemProp(item);
  338. }
  339. else if (assetName.StartsWith("handitem")) result = SpawnObject(assetName);
  340. else result = SpawnModItemProp(ModItem.Mod(assetName));
  341. }
  342. else if (assetName.StartsWith("MYR_"))
  343. {
  344. string[] assetParts = assetName.Split('#');
  345. int id = int.Parse(assetParts[0].Substring(4));
  346. string prefabName;
  347. if (assetParts.Length == 2 && !string.IsNullOrEmpty(assetParts[1])) prefabName = assetParts[1];
  348. else
  349. {
  350. // deserialize modifiedMM and maybe MM 23.0+.
  351. MyRoomCustom.PlacementData.Data data = MyRoomCustom.PlacementData.GetData(id);
  352. prefabName = !string.IsNullOrEmpty(data.resourceName) ? data.resourceName : data.assetName;
  353. }
  354. result = SpawnMyRoomProp(new MyRoomItem() { ID = id, PrefabName = prefabName });
  355. }
  356. else if (assetName.StartsWith("BG_")) result = SpawnBG(assetName);
  357. else result = SpawnObject(assetName);
  358. return result;
  359. }
  360. private void AttachDragPoint(GameObject dogu, string assetName, string name, Vector3 position)
  361. {
  362. // TODO: Figure out why some props aren't centred properly
  363. // Doesn't happen in MM but even after copy pasting the code, it doesn't work :/
  364. dogu.name = name;
  365. dogu.transform.position = position;
  366. DragPointDogu dragDogu = DragPoint.Make<DragPointDogu>(PrimitiveType.Cube, Vector3.one * 0.12f);
  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. CurrentDoguIndex = doguIndex;
  383. 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. ? meidoManager.GetMeido(info.MaidGuid)
  466. : 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() => DoguListChange?.Invoke(this, EventArgs.Empty);
  503. }
  504. }