PropManager.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574
  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()
  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. Activate();
  69. }
  70. public void Serialize(BinaryWriter binaryWriter)
  71. {
  72. binaryWriter.Write(header);
  73. binaryWriter.Write(propDataVersion);
  74. binaryWriter.Write(doguList.Count);
  75. foreach (DragPointDogu dogu in doguList)
  76. {
  77. binaryWriter.WriteVector3(dogu.MyObject.position);
  78. binaryWriter.WriteQuaternion(dogu.MyObject.rotation);
  79. binaryWriter.WriteVector3(dogu.MyObject.localScale);
  80. dogu.attachPointInfo.Serialize(binaryWriter);
  81. binaryWriter.Write(dogu.ShadowCasting);
  82. binaryWriter.Write(dogu.assetName);
  83. }
  84. }
  85. public void Deserialize(BinaryReader binaryReader)
  86. {
  87. Dictionary<string, string> modToModPath = null;
  88. ClearDogu();
  89. int version = binaryReader.ReadInt32();
  90. int numberOfProps = binaryReader.ReadInt32();
  91. int doguIndex = 0;
  92. for (int i = 0; i < numberOfProps; i++)
  93. {
  94. Vector3 position = binaryReader.ReadVector3();
  95. Quaternion rotation = binaryReader.ReadQuaternion();
  96. Vector3 scale = binaryReader.ReadVector3();
  97. AttachPointInfo info = AttachPointInfo.Deserialize(binaryReader);
  98. bool shadowCasting = binaryReader.ReadBoolean();
  99. string assetName = binaryReader.ReadString();
  100. if (assetName.EndsWith(".menu") && assetName.Contains('#') && modToModPath == null)
  101. {
  102. modToModPath = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase);
  103. foreach (string mod in Menu.GetModFiles()) modToModPath.Add(Path.GetFileName(mod), mod);
  104. }
  105. if (SpawnFromAssetString(assetName, modToModPath))
  106. {
  107. DragPointDogu dogu = doguList[doguIndex++];
  108. Transform obj = dogu.MyObject;
  109. obj.position = position;
  110. obj.rotation = rotation;
  111. obj.localScale = scale;
  112. dogu.attachPointInfo = info;
  113. dogu.ShadowCasting = shadowCasting;
  114. }
  115. }
  116. CurrentDoguIndex = 0;
  117. GameMain.Instance.StartCoroutine(DeserializeAttach());
  118. }
  119. private System.Collections.IEnumerator DeserializeAttach()
  120. {
  121. yield return new WaitForEndOfFrame();
  122. foreach (DragPointDogu dogu in doguList)
  123. {
  124. AttachPointInfo info = dogu.attachPointInfo;
  125. if (info.AttachPoint != AttachPoint.None)
  126. {
  127. Meido parent = meidoManager.GetMeido(info.MaidIndex);
  128. if (parent != null)
  129. {
  130. Transform obj = dogu.MyObject;
  131. Vector3 position = obj.position;
  132. Vector3 scale = obj.localScale;
  133. Quaternion rotation = obj.rotation;
  134. Transform point = parent.IKManager.GetAttachPointTransform(info.AttachPoint);
  135. dogu.MyObject.SetParent(point, true);
  136. info = new AttachPointInfo(
  137. info.AttachPoint,
  138. parent.Maid.status.guid,
  139. parent.Slot
  140. );
  141. dogu.attachPointInfo = info;
  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 = 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 = 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. dogu.transform.localPosition = localPosition;
  228. switch (assetName)
  229. {
  230. case "mirror1":
  231. dogu.transform.localScale = new Vector3(0.2f, 0.4f, 0.2f);
  232. break;
  233. case "mirror2":
  234. dogu.transform.localScale = new Vector3(0.1f, 0.4f, 0.2f);
  235. break;
  236. case "mirror3":
  237. localPosition.y = 0.85f;
  238. dogu.transform.localScale = new Vector3(0.03f, 0.18f, 0.124f);
  239. break;
  240. default:
  241. GameObject.Destroy(dogu);
  242. dogu = null;
  243. break;
  244. }
  245. }
  246. else if (assetName.IndexOf(':') >= 0)
  247. {
  248. string[] assetParts = assetName.Split(':');
  249. GameObject obj = GameMain.Instance.BgMgr.CreateAssetBundle(assetParts[0])
  250. ?? Resources.Load<GameObject>("BG/" + assetParts[0]);
  251. try
  252. {
  253. GameObject bg = GameObject.Instantiate(obj);
  254. int num = int.Parse(assetParts[1]);
  255. dogu = bg.transform.GetChild(num).gameObject;
  256. dogu.transform.SetParent(null);
  257. GameObject.Destroy(bg);
  258. }
  259. catch { }
  260. }
  261. else
  262. {
  263. GameObject obj = GameMain.Instance.BgMgr.CreateAssetBundle(assetName)
  264. ?? Resources.Load<GameObject>("Prefab/" + assetName)
  265. ?? Resources.Load<GameObject>("BG/" + assetName);
  266. try
  267. {
  268. dogu = GameObject.Instantiate<GameObject>(obj);
  269. dogu.transform.localPosition = Vector3.zero;
  270. MeshRenderer[] meshRenderers = dogu.GetComponentsInChildren<MeshRenderer>();
  271. for (int i = 0; i < meshRenderers.Length; i++)
  272. {
  273. if (meshRenderers[i])
  274. {
  275. string name = meshRenderers[i].gameObject.name;
  276. if (name.IndexOf("castshadow", StringComparison.OrdinalIgnoreCase) < 0)
  277. {
  278. meshRenderers[i].shadowCastingMode = ShadowCastingMode.Off;
  279. }
  280. }
  281. }
  282. Collider collider = dogu.transform.GetComponent<Collider>();
  283. if (collider != null) collider.enabled = false;
  284. foreach (Transform transform in dogu.transform)
  285. {
  286. collider = transform.GetComponent<Collider>();
  287. if (collider != null)
  288. {
  289. collider.enabled = false;
  290. }
  291. }
  292. }
  293. catch { }
  294. #region particle system experiment
  295. // if (asset.StartsWith("Particle/"))
  296. // {
  297. // ParticleSystem particleSystem = go.GetComponent<ParticleSystem>();
  298. // if (particleSystem != null)
  299. // {
  300. // ParticleSystem.MainModule main;
  301. // main = particleSystem.main;
  302. // main.loop = true;
  303. // main.duration = Mathf.Infinity;
  304. // ParticleSystem[] particleSystems = particleSystem.GetComponents<ParticleSystem>();
  305. // foreach (ParticleSystem part in particleSystems)
  306. // {
  307. // ParticleSystem.EmissionModule emissionModule = part.emission;
  308. // ParticleSystem.Burst[] bursts = new ParticleSystem.Burst[emissionModule.burstCount];
  309. // emissionModule.GetBursts(bursts);
  310. // for (int i = 0; i < bursts.Length; i++)
  311. // {
  312. // bursts[i].cycleCount = Int32.MaxValue;
  313. // }
  314. // emissionModule.SetBursts(bursts);
  315. // main = part.main;
  316. // main.loop = true;
  317. // main.duration = Mathf.Infinity;
  318. // }
  319. // }
  320. // }
  321. #endregion particle system experiment
  322. }
  323. if (dogu != null)
  324. {
  325. AttachDragPoint(dogu, assetName, doguName, doguPosition);
  326. return true;
  327. }
  328. Utility.LogInfo($"Could not spawn object '{assetName}'");
  329. return false;
  330. }
  331. private bool SpawnFromAssetString(string assetName, Dictionary<string, string> modDict = null)
  332. {
  333. bool result;
  334. if (assetName.EndsWith(".menu"))
  335. {
  336. if (assetName.Contains('#'))
  337. {
  338. string[] assetParts = assetName.Split('#');
  339. string menuFile = modDict == null ? Menu.GetModPathFileName(assetParts[0]) : modDict[assetParts[0]];
  340. ModItem item = ModItem.OfficialMod(menuFile);
  341. item.BaseMenuFile = assetParts[1];
  342. result = SpawnModItemProp(item);
  343. }
  344. else if (assetName.StartsWith("handitem")) result = SpawnObject(assetName);
  345. else result = SpawnModItemProp(ModItem.Mod(assetName));
  346. }
  347. else if (assetName.StartsWith("MYR_"))
  348. {
  349. string[] assetParts = assetName.Split('#');
  350. int id = int.Parse(assetParts[0].Substring(4));
  351. string prefabName;
  352. if (assetParts.Length == 2 && !string.IsNullOrEmpty(assetParts[1])) prefabName = assetParts[1];
  353. else
  354. {
  355. // deserialize modifiedMM and maybe MM 23.0+.
  356. MyRoomCustom.PlacementData.Data data = MyRoomCustom.PlacementData.GetData(id);
  357. prefabName = !string.IsNullOrEmpty(data.resourceName) ? data.resourceName : data.assetName;
  358. }
  359. result = SpawnMyRoomProp(new MyRoomItem() { ID = id, PrefabName = prefabName });
  360. }
  361. else if (assetName.StartsWith("BG_")) result = SpawnBG(assetName);
  362. else result = SpawnObject(assetName);
  363. return result;
  364. }
  365. private void AttachDragPoint(GameObject dogu, string assetName, string name, Vector3 position)
  366. {
  367. // TODO: Figure out why some props aren't centred properly
  368. // Doesn't happen in MM but even after copy pasting the code, it doesn't work :/
  369. dogu.name = name;
  370. dogu.transform.position = position;
  371. DragPointDogu dragDogu = DragPoint.Make<DragPointDogu>(PrimitiveType.Cube, Vector3.one * 0.12f);
  372. dragDogu.Initialize(() => dogu.transform.position, () => Vector3.zero);
  373. dragDogu.Set(dogu.transform);
  374. dragDogu.AddGizmo(scale: 0.45f, mode: CustomGizmo.GizmoMode.World);
  375. dragDogu.ConstantScale = true;
  376. dragDogu.Delete += DeleteDogu;
  377. dragDogu.Select += SelectDogu;
  378. dragDogu.DragPointScale = CubeSmall ? DragPointGeneral.smallCube : 1f;
  379. dragDogu.assetName = assetName;
  380. doguList.Add(dragDogu);
  381. OnDoguListChange();
  382. }
  383. public void SetCurrentDogu(int doguIndex)
  384. {
  385. if (doguIndex >= 0 && doguIndex < DoguCount)
  386. {
  387. CurrentDoguIndex = doguIndex;
  388. DoguSelectChange?.Invoke(this, EventArgs.Empty);
  389. }
  390. }
  391. public void RemoveDogu(int doguIndex)
  392. {
  393. if (doguIndex >= 0 && doguIndex < DoguCount)
  394. {
  395. DestroyDogu(doguList[doguIndex]);
  396. doguList.RemoveAt(doguIndex);
  397. CurrentDoguIndex = Utility.Bound(CurrentDoguIndex, 0, DoguCount - 1);
  398. OnDoguListChange();
  399. }
  400. }
  401. public void CopyDogu(int doguIndex)
  402. {
  403. if (doguIndex >= 0 && doguIndex < DoguCount)
  404. {
  405. SpawnFromAssetString(doguList[doguIndex].assetName);
  406. }
  407. }
  408. public void AttachProp(
  409. int doguIndex, AttachPoint attachPoint, Meido meido, bool worldPositionStays = true
  410. )
  411. {
  412. if (doguList.Count == 0 || doguIndex >= doguList.Count || doguIndex < 0) return;
  413. AttachProp(doguList[doguIndex], attachPoint, meido, worldPositionStays);
  414. }
  415. private void AttachProp(
  416. DragPointDogu dragDogu, AttachPoint attachPoint, Meido meido, bool worldPositionStays = true
  417. )
  418. {
  419. GameObject dogu = dragDogu.MyGameObject;
  420. Transform attachPointTransform = meido?.IKManager.GetAttachPointTransform(attachPoint);
  421. // ?? GetDeploymentObject().transform;
  422. dragDogu.attachPointInfo = new AttachPointInfo(
  423. attachPoint: meido == null ? AttachPoint.None : attachPoint,
  424. maidGuid: meido == null ? string.Empty : meido.Maid.status.guid,
  425. maidIndex: meido == null ? -1 : meido.Slot
  426. );
  427. Vector3 position = dogu.transform.position;
  428. Quaternion rotation = dogu.transform.rotation;
  429. Vector3 scale = dogu.transform.localScale;
  430. dogu.transform.SetParent(attachPointTransform, worldPositionStays);
  431. if (worldPositionStays)
  432. {
  433. dogu.transform.position = position;
  434. dogu.transform.rotation = rotation;
  435. }
  436. else
  437. {
  438. dogu.transform.localPosition = Vector3.zero;
  439. dogu.transform.rotation = Quaternion.identity;
  440. }
  441. dogu.transform.localScale = scale;
  442. if (meido == null) Utility.FixGameObjectScale(dogu);
  443. }
  444. private void DetachProps(object sender, EventArgs args)
  445. {
  446. foreach (DragPointDogu dogu in doguList)
  447. {
  448. if (dogu.attachPointInfo.AttachPoint != AttachPoint.None)
  449. {
  450. dogu.MyObject.SetParent(null, /*GetDeploymentObject().transform*/ true);
  451. }
  452. }
  453. }
  454. private void ClearDogu()
  455. {
  456. for (int i = DoguCount - 1; i >= 0; i--)
  457. {
  458. DestroyDogu(doguList[i]);
  459. }
  460. doguList.Clear();
  461. CurrentDoguIndex = 0;
  462. }
  463. private void OnEndCall(object sender, EventArgs args) => ReattachProps(useGuid: true);
  464. private void ReattachProps(bool useGuid, bool forceStay = false)
  465. {
  466. foreach (DragPointDogu dragDogu in doguList)
  467. {
  468. AttachPointInfo info = dragDogu.attachPointInfo;
  469. Meido meido = useGuid
  470. ? meidoManager.GetMeido(info.MaidGuid)
  471. : meidoManager.GetMeido(info.MaidIndex);
  472. bool worldPositionStays = forceStay || meido == null;
  473. AttachProp(dragDogu, dragDogu.attachPointInfo.AttachPoint, meido, worldPositionStays);
  474. }
  475. }
  476. private void DeleteDogu(object sender, EventArgs args)
  477. {
  478. DragPointDogu dogu = (DragPointDogu)sender;
  479. RemoveDogu(doguList.FindIndex(dragDogu => dragDogu == dogu));
  480. }
  481. private void DestroyDogu(DragPointDogu dogu)
  482. {
  483. if (dogu == null) return;
  484. dogu.Delete -= DeleteDogu;
  485. dogu.Select -= SelectDogu;
  486. GameObject.Destroy(dogu.gameObject);
  487. }
  488. private void SelectDogu(object sender, EventArgs args)
  489. {
  490. DragPointDogu dogu = (DragPointDogu)sender;
  491. SetCurrentDogu(doguList.IndexOf(dogu));
  492. }
  493. private void OnCubeSmall(object sender, EventArgs args)
  494. {
  495. foreach (DragPointDogu dogu in doguList)
  496. {
  497. dogu.DragPointScale = CubeSmall ? DragPointGeneral.smallCube : 1f;
  498. }
  499. }
  500. private void OnCubeActive(object sender, EventArgs args)
  501. {
  502. foreach (DragPointDogu dragPoint in doguList)
  503. {
  504. dragPoint.gameObject.SetActive(CubeActive);
  505. }
  506. }
  507. private void OnDoguListChange() => DoguListChange?.Invoke(this, EventArgs.Empty);
  508. }
  509. }