PropManager.cs 22 KB

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