Meido.cs 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953
  1. using System;
  2. using System.Collections;
  3. using System.Collections.Generic;
  4. using System.IO;
  5. using System.Linq;
  6. using System.Reflection;
  7. using System.Xml.Linq;
  8. using UnityEngine;
  9. using static TBody;
  10. using Object = UnityEngine.Object;
  11. namespace MeidoPhotoStudio.Plugin;
  12. public class Meido
  13. {
  14. public static readonly string DefaultFaceBlendSet = "通常";
  15. public static readonly string[] FaceKeys =
  16. new string[24]
  17. {
  18. "eyeclose", "eyeclose2", "eyeclose3", "eyebig", "eyeclose6", "eyeclose5", "hitomih",
  19. "hitomis", "mayuha", "mayuw", "mayuup", "mayuv", "mayuvhalf", "moutha", "mouths",
  20. "mouthc", "mouthi", "mouthup", "mouthdw", "mouthhe", "mouthuphalf", "tangout",
  21. "tangup", "tangopen",
  22. };
  23. public static readonly string[] FaceToggleKeys =
  24. new string[12]
  25. {
  26. // blush, shade, nose up, tears, drool, teeth
  27. "hoho2", "shock", "nosefook", "namida", "yodare", "toothoff",
  28. // cry 1, cry 2, cry 3, blush 1, blush 2, blush 3
  29. "tear1", "tear2", "tear3", "hohos", "hoho", "hohol",
  30. };
  31. #pragma warning disable SA1308
  32. // TODO: Refactor reflection to using private members directly
  33. private readonly FieldInfo m_eMaskMode = Utility.GetFieldInfo<TBody>("m_eMaskMode");
  34. #pragma warning restore SA1308
  35. private bool initialized;
  36. private float[] blendSetValueBackup;
  37. private bool freeLook;
  38. public Meido(int stockMaidIndex)
  39. {
  40. StockNo = stockMaidIndex;
  41. Maid = GameMain.Instance.CharacterMgr.GetStockMaid(stockMaidIndex);
  42. IKManager = new(this);
  43. IKManager.SelectMaid += (_, args) =>
  44. OnUpdateMeido(args);
  45. }
  46. public event EventHandler<GravityEventArgs> GravityMove;
  47. public event EventHandler<MeidoUpdateEventArgs> UpdateMeido;
  48. public enum Curl
  49. {
  50. Front,
  51. Back,
  52. Shift,
  53. }
  54. public enum Mask
  55. {
  56. All,
  57. Underwear,
  58. Nude,
  59. }
  60. public MaskMode CurrentMaskMode =>
  61. !Body.isLoadedBody ? default : (MaskMode)m_eMaskMode.GetValue(Body);
  62. public DragPointGravity HairGravityControl { get; private set; }
  63. public DragPointGravity SkirtGravityControl { get; private set; }
  64. public Quaternion DefaultEyeRotL { get; private set; }
  65. public Quaternion DefaultEyeRotR { get; private set; }
  66. public bool Active { get; private set; }
  67. public bool IsEditMaid { get; set; }
  68. public PoseInfo CachedPose { get; private set; } = PoseInfo.DefaultPose;
  69. public string CurrentFaceBlendSet { get; private set; } = DefaultFaceBlendSet;
  70. public int Slot { get; private set; }
  71. public bool Loading { get; private set; }
  72. public int StockNo { get; }
  73. public Maid Maid { get; }
  74. public MeidoDragPointManager IKManager { get; }
  75. public TBody Body =>
  76. Maid.body0;
  77. public Texture2D Portrait =>
  78. Maid.GetThumIcon();
  79. public string FirstName =>
  80. Maid.status.firstName;
  81. public string LastName =>
  82. Maid.status.lastName;
  83. public bool Busy =>
  84. Maid.IsBusy || Loading;
  85. public bool CurlingFront =>
  86. Maid.IsItemChange("skirt", "めくれスカート") || Maid.IsItemChange("onepiece", "めくれスカート");
  87. public bool CurlingBack =>
  88. Maid.IsItemChange("skirt", "めくれスカート後ろ") || Maid.IsItemChange("onepiece", "めくれスカート後ろ");
  89. public bool PantsuShift =>
  90. Maid.IsItemChange("panz", "パンツずらし") || Maid.IsItemChange("mizugi", "パンツずらし");
  91. public bool HairGravityActive
  92. {
  93. get => HairGravityControl.Active;
  94. set
  95. {
  96. if (HairGravityControl.Valid)
  97. HairGravityControl.gameObject.SetActive(value);
  98. }
  99. }
  100. public bool SkirtGravityActive
  101. {
  102. get => SkirtGravityControl.Active;
  103. set
  104. {
  105. if (SkirtGravityControl.Valid)
  106. SkirtGravityControl.gameObject.SetActive(value);
  107. }
  108. }
  109. public bool FreeLook
  110. {
  111. get => freeLook;
  112. set
  113. {
  114. if (freeLook == value)
  115. return;
  116. freeLook = value;
  117. Body.trsLookTarget = freeLook ? null : GameMain.Instance.MainCamera.transform;
  118. OnUpdateMeido();
  119. }
  120. }
  121. public bool HeadToCam
  122. {
  123. get => Body.isLoadedBody && Body.boHeadToCam;
  124. set
  125. {
  126. if (!Body.isLoadedBody || HeadToCam == value)
  127. return;
  128. Body.HeadToCamPer = 0f;
  129. Body.boHeadToCam = value;
  130. if (!HeadToCam && !EyeToCam)
  131. FreeLook = false;
  132. OnUpdateMeido();
  133. }
  134. }
  135. public bool EyeToCam
  136. {
  137. get => Body.isLoadedBody && Body.boEyeToCam;
  138. set
  139. {
  140. if (!Body.isLoadedBody || EyeToCam == value)
  141. return;
  142. Body.boEyeToCam = value;
  143. if (!HeadToCam && !EyeToCam)
  144. FreeLook = false;
  145. OnUpdateMeido();
  146. }
  147. }
  148. public bool Stop
  149. {
  150. get => !Body.isLoadedBody || !Maid.GetAnimation().isPlaying;
  151. set
  152. {
  153. if (!Body.isLoadedBody || value == Stop)
  154. return;
  155. if (value)
  156. {
  157. Maid.GetAnimation().Stop();
  158. }
  159. else
  160. {
  161. Body.boEyeToCam = true;
  162. Body.boHeadToCam = true;
  163. SetPose(CachedPose);
  164. }
  165. OnUpdateMeido();
  166. }
  167. }
  168. public bool IK
  169. {
  170. get => IKManager.Active;
  171. set
  172. {
  173. if (value == IKManager.Active)
  174. return;
  175. IKManager.Active = value;
  176. }
  177. }
  178. public bool Bone
  179. {
  180. get => IKManager.IsBone;
  181. set
  182. {
  183. if (value == Bone)
  184. return;
  185. IKManager.IsBone = value;
  186. OnUpdateMeido();
  187. }
  188. }
  189. public void Load(int slot)
  190. {
  191. if (Busy)
  192. return;
  193. Slot = slot;
  194. if (Active)
  195. return;
  196. FreeLook = false;
  197. Maid.Visible = true;
  198. Body.boHeadToCam = true;
  199. Body.boEyeToCam = true;
  200. Body.SetBoneHitHeightY(-1000f);
  201. if (!Body.isLoadedBody)
  202. {
  203. Maid.DutPropAll();
  204. Maid.AllProcPropSeqStart();
  205. }
  206. StartLoad(OnBodyLoad);
  207. }
  208. public void Unload()
  209. {
  210. if (Body.isLoadedBody && Maid.Visible)
  211. {
  212. DetachAllMpnAttach();
  213. Body.jbMuneL.enabled = true;
  214. Body.jbMuneR.enabled = true;
  215. Body.quaDefEyeL = DefaultEyeRotL;
  216. Body.quaDefEyeR = DefaultEyeRotR;
  217. if (HairGravityControl)
  218. {
  219. HairGravityControl.Move -= OnGravityEvent;
  220. HairGravityActive = false;
  221. }
  222. if (SkirtGravityControl)
  223. {
  224. SkirtGravityControl.Move -= OnGravityEvent;
  225. SkirtGravityActive = false;
  226. }
  227. ApplyGravity(Vector3.zero, skirt: false);
  228. ApplyGravity(Vector3.zero, skirt: true);
  229. SetFaceBlendSet(DefaultFaceBlendSet);
  230. }
  231. AllProcPropSeqStartPatcher.SequenceStart -= ReinitializeBody;
  232. Body.MuneYureL(1f);
  233. Body.MuneYureR(1f);
  234. Body.SetMaskMode(MaskMode.None);
  235. Body.SetBoneHitHeightY(0f);
  236. Maid.Visible = false;
  237. IKManager.Destroy();
  238. Active = false;
  239. }
  240. public void Deactivate()
  241. {
  242. Unload();
  243. if (HairGravityControl)
  244. Object.Destroy(HairGravityControl.gameObject);
  245. if (SkirtGravityControl)
  246. Object.Destroy(SkirtGravityControl.gameObject);
  247. Maid.SetPos(Vector3.zero);
  248. Maid.SetRot(Vector3.zero);
  249. Maid.SetPosOffset(Vector3.zero);
  250. Body.transform.localScale = Vector3.one;
  251. Maid.ResetAll();
  252. Maid.MabatakiUpdateStop = false;
  253. Maid.ActiveSlotNo = -1;
  254. }
  255. public void SetPose(PoseInfo poseInfo)
  256. {
  257. if (!Body.isLoadedBody)
  258. return;
  259. var pose = poseInfo.Pose;
  260. var custom = poseInfo.CustomPose;
  261. if (custom)
  262. {
  263. var poseFilename = Path.GetFileNameWithoutExtension(pose);
  264. try
  265. {
  266. var poseBuffer = File.ReadAllBytes(pose);
  267. var hash = Path.GetFileName(pose).GetHashCode().ToString();
  268. Body.CrossFade(hash, poseBuffer, loop: true, fade: 0f);
  269. }
  270. catch (Exception e) when (e is DirectoryNotFoundException or FileNotFoundException)
  271. {
  272. Utility.LogWarning($"Could not open '{poseFilename}' because {e.Message}");
  273. Constants.InitializeCustomPoses();
  274. SetDefaultPose();
  275. OnUpdateMeido();
  276. return;
  277. }
  278. catch (Exception e)
  279. {
  280. Utility.LogWarning($"Could not apply pose '{poseFilename}' because {e.Message}");
  281. SetDefaultPose();
  282. OnUpdateMeido();
  283. return;
  284. }
  285. SetMune(true, left: true);
  286. SetMune(true, left: false);
  287. }
  288. else
  289. {
  290. var poseComponents = pose.Split(',');
  291. var poseFilename = poseComponents[0] + ".anm";
  292. var tag = Maid.CrossFade(poseFilename, loop: true, val: 0f);
  293. if (string.IsNullOrEmpty(tag))
  294. {
  295. Utility.LogWarning($"Pose could not be loaded: {poseFilename}");
  296. SetDefaultPose();
  297. return;
  298. }
  299. Maid.GetAnimation().Play();
  300. if (poseComponents.Length > 1)
  301. {
  302. var animation = Maid.GetAnimation()[poseFilename];
  303. var time = float.Parse(poseComponents[1]);
  304. animation.time = time;
  305. animation.speed = 0f;
  306. }
  307. SetPoseMune(poseFilename);
  308. }
  309. Maid.SetAutoTwistAll(true);
  310. CachedPose = poseInfo;
  311. void SetDefaultPose() =>
  312. SetPose(PoseInfo.DefaultPose);
  313. void SetPoseMune(string pose)
  314. {
  315. var momiOrPaizuri = pose.Contains("_momi") || pose.Contains("paizuri_");
  316. SetMune(!momiOrPaizuri, left: true);
  317. SetMune(!momiOrPaizuri, left: false);
  318. }
  319. }
  320. public KeyValuePair<bool, bool> SetFrameBinary(byte[] poseBuffer) =>
  321. GetCacheBoneData().SetFrameBinary(poseBuffer);
  322. public void CopyPose(Meido fromMeido)
  323. {
  324. Stop = true;
  325. SetFrameBinary(fromMeido.SerializePose(frameBinary: true));
  326. SetMune(fromMeido.Body.GetMuneYureL() is not 0f, left: true);
  327. SetMune(fromMeido.Body.GetMuneYureR() is not 0f, left: false);
  328. }
  329. public void SetMune(bool enabled, bool left = false)
  330. {
  331. var value = enabled ? 1f : 0f;
  332. if (left)
  333. {
  334. Body.MuneYureL(value);
  335. Body.jbMuneL.enabled = enabled;
  336. }
  337. else
  338. {
  339. Body.MuneYureR(value);
  340. Body.jbMuneR.enabled = enabled;
  341. }
  342. }
  343. public void SetHandPreset(string filename, bool right)
  344. {
  345. var faceFilename = Path.GetFileNameWithoutExtension(filename);
  346. try
  347. {
  348. var handDocument = XDocument.Load(filename);
  349. var handElement = handDocument.Element("FingerData");
  350. if (handElement?.Elements().Any(element => element?.IsEmpty ?? true) ?? true)
  351. {
  352. Utility.LogWarning($"{faceFilename}: Could not apply hand preset because it is invalid.");
  353. return;
  354. }
  355. Stop = true;
  356. var rightData = bool.Parse(handElement.Element("RightData").Value);
  357. var base64Data = handElement.Element("BinaryData").Value;
  358. var handData = Convert.FromBase64String(base64Data);
  359. IKManager.DeserializeHand(handData, right, rightData != right);
  360. }
  361. catch (System.Xml.XmlException e)
  362. {
  363. Utility.LogWarning($"{faceFilename}: Hand preset data is malformed because {e.Message}");
  364. }
  365. catch (Exception e) when (e is DirectoryNotFoundException or FileNotFoundException)
  366. {
  367. Utility.LogWarning($"{faceFilename}: Could not open hand preset because {e.Message}");
  368. Constants.InitializeHandPresets();
  369. }
  370. catch (Exception e)
  371. {
  372. Utility.LogWarning($"{faceFilename}: Could not parse hand preset because {e.Message}");
  373. }
  374. }
  375. public byte[] SerializePose(bool frameBinary = false)
  376. {
  377. var cache = GetCacheBoneData();
  378. var muneL = Body.GetMuneYureL() is 0f;
  379. var muneR = Body.GetMuneYureR() is 0f;
  380. return frameBinary
  381. ? cache.GetFrameBinary(muneL, muneR)
  382. : cache.GetAnmBinary(true, true);
  383. }
  384. public Dictionary<string, float> SerializeFace()
  385. {
  386. var faceData = new Dictionary<string, float>();
  387. foreach (var hash in FaceKeys.Concat(FaceToggleKeys))
  388. {
  389. try
  390. {
  391. var value = GetFaceBlendValue(hash);
  392. faceData.Add(hash, value);
  393. }
  394. catch
  395. {
  396. // Ignored
  397. }
  398. }
  399. return faceData;
  400. }
  401. public void SetFaceBlendSet(string blendSet)
  402. {
  403. if (blendSet.StartsWith(Constants.CustomFacePath))
  404. {
  405. var blendSetFileName = Path.GetFileNameWithoutExtension(blendSet);
  406. try
  407. {
  408. var faceDocument = XDocument.Load(blendSet, LoadOptions.SetLineInfo);
  409. var faceDataElement = faceDocument.Element("FaceData");
  410. if (faceDataElement?.IsEmpty ?? true)
  411. {
  412. Utility.LogWarning($"{blendSetFileName}: Could not apply face preset because it is invalid.");
  413. return;
  414. }
  415. var hashKeys = new HashSet<string>(FaceKeys.Concat(FaceToggleKeys));
  416. foreach (var element in faceDataElement.Elements())
  417. {
  418. System.Xml.IXmlLineInfo info = element;
  419. var line = info.HasLineInfo() ? info.LineNumber : -1;
  420. string key;
  421. if ((key = (string)element.Attribute("name")) is null)
  422. {
  423. Utility.LogWarning($"{blendSetFileName}: Could not read face blend key at line {line}.");
  424. continue;
  425. }
  426. if (!hashKeys.Contains(key))
  427. {
  428. Utility.LogWarning($"{blendSetFileName}: Invalid face blend key '{key}' at line {line}.");
  429. continue;
  430. }
  431. if (float.TryParse(element.Value, out var value))
  432. {
  433. try
  434. {
  435. SetFaceBlendValue(key, value);
  436. }
  437. catch
  438. {
  439. // Ignored.
  440. }
  441. }
  442. else
  443. {
  444. Utility.LogWarning(
  445. $"{blendSetFileName}: Could not parse value '{element.Value}' of '{key}' at line {line}");
  446. }
  447. }
  448. }
  449. catch (System.Xml.XmlException e)
  450. {
  451. Utility.LogWarning($"{blendSetFileName}: Face preset data is malformed because {e.Message}");
  452. return;
  453. }
  454. catch (Exception e) when (e is DirectoryNotFoundException or FileNotFoundException)
  455. {
  456. Utility.LogWarning($"{blendSetFileName}: Could not open face preset because {e.Message}");
  457. Constants.InitializeCustomFaceBlends();
  458. return;
  459. }
  460. catch (Exception e)
  461. {
  462. Utility.LogWarning($"{blendSetFileName}: Could not parse face preset because {e.Message}");
  463. return;
  464. }
  465. }
  466. else
  467. {
  468. ApplyBackupBlendSet();
  469. CurrentFaceBlendSet = blendSet;
  470. BackupBlendSetValues();
  471. Maid.FaceAnime(blendSet, 0f);
  472. var morph = Body.Face.morph;
  473. foreach (var faceKey in FaceKeys)
  474. {
  475. var hash = Utility.GP01FbFaceHash(morph, faceKey);
  476. if (!morph.Contains(hash))
  477. continue;
  478. var blendIndex = (int)morph.hash[hash];
  479. var value = faceKey is "nosefook"
  480. ? Maid.boNoseFook || morph.boNoseFook ? 1f : 0f
  481. : morph.dicBlendSet[CurrentFaceBlendSet][blendIndex];
  482. morph.SetBlendValues(blendIndex, value);
  483. }
  484. morph.FixBlendValues();
  485. }
  486. StopBlink();
  487. OnUpdateMeido();
  488. }
  489. public void SetFaceBlendValue(string faceKey, float value)
  490. {
  491. var morph = Body.Face.morph;
  492. var hash = Utility.GP01FbFaceHash(morph, faceKey);
  493. if (!morph.Contains(hash))
  494. return;
  495. var blendIndex = (int)morph.hash[hash];
  496. if (faceKey is "nosefook")
  497. Maid.boNoseFook = morph.boNoseFook = value > 0f;
  498. else
  499. morph.dicBlendSet[CurrentFaceBlendSet][blendIndex] = value;
  500. morph.SetBlendValues(blendIndex, value);
  501. morph.FixBlendValues();
  502. }
  503. public float GetFaceBlendValue(string hash)
  504. {
  505. var morph = Body.Face.morph;
  506. if (hash is "nosefook")
  507. return (Maid.boNoseFook || morph.boNoseFook) ? 1f : 0f;
  508. hash = Utility.GP01FbFaceHash(morph, hash);
  509. return morph.dicBlendSet[CurrentFaceBlendSet][(int)morph.hash[hash]];
  510. }
  511. public void StopBlink()
  512. {
  513. Maid.MabatakiUpdateStop = true;
  514. Body.Face.morph.EyeMabataki = 0f;
  515. Utility.SetFieldValue(Maid, "MabatakiVal", 0f);
  516. }
  517. public void SetMaskMode(Mask maskMode) =>
  518. SetMaskMode(maskMode is Mask.Nude ? MaskMode.Nude : (MaskMode)maskMode);
  519. public void SetMaskMode(MaskMode maskMode)
  520. {
  521. var invisibleBody = !Body.GetMask(SlotID.body);
  522. Body.SetMaskMode(maskMode);
  523. if (invisibleBody)
  524. SetBodyMask(false);
  525. }
  526. public void SetBodyMask(bool enabled)
  527. {
  528. var table = Utility.GetFieldValue<TBody, Hashtable>(Body, "m_hFoceHide");
  529. foreach (var bodySlot in MaidDressingPane.BodySlots)
  530. table[bodySlot] = enabled;
  531. Body.FixMaskFlag();
  532. Body.FixVisibleFlag(false);
  533. }
  534. public void SetCurling(Curl curling, bool enabled)
  535. {
  536. var name = curling is Curl.Shift
  537. ? new[] { "panz", "mizugi" }
  538. : new[] { "skirt", "onepiece" };
  539. if (enabled)
  540. {
  541. var action = curling switch
  542. {
  543. Curl.Shift => "パンツずらし",
  544. Curl.Front => "めくれスカート",
  545. _ => "めくれスカート後ろ",
  546. };
  547. Maid.ItemChangeTemp(name[0], action);
  548. Maid.ItemChangeTemp(name[1], action);
  549. }
  550. else
  551. {
  552. Maid.ResetProp(name[0]);
  553. Maid.ResetProp(name[1]);
  554. }
  555. Maid.AllProcProp();
  556. HairGravityControl.Control.OnChangeMekure();
  557. SkirtGravityControl.Control.OnChangeMekure();
  558. }
  559. public void SetMpnProp(MpnAttachProp prop, bool detach)
  560. {
  561. if (detach)
  562. Maid.ResetProp(prop.Tag, false);
  563. else
  564. Maid.SetProp(prop.Tag, prop.MenuFile, 0, true);
  565. Maid.AllProcProp();
  566. }
  567. public void DetachAllMpnAttach()
  568. {
  569. Maid.ResetProp(MPN.kousoku_lower, false);
  570. Maid.ResetProp(MPN.kousoku_upper, false);
  571. Maid.AllProcProp();
  572. }
  573. public void ApplyGravity(Vector3 position, bool skirt = false)
  574. {
  575. var dragPoint = skirt ? SkirtGravityControl : HairGravityControl;
  576. if (dragPoint.Valid)
  577. dragPoint.Control.transform.localPosition = position;
  578. }
  579. private void StartLoad(Action callback)
  580. {
  581. if (Loading)
  582. return;
  583. GameMain.Instance.StartCoroutine(Load(callback));
  584. }
  585. private IEnumerator Load(Action callback)
  586. {
  587. Loading = true;
  588. while (Maid.IsBusy)
  589. yield return null;
  590. yield return new WaitForEndOfFrame();
  591. callback();
  592. Loading = false;
  593. }
  594. private void OnBodyLoad()
  595. {
  596. if (!initialized)
  597. {
  598. DefaultEyeRotL = Body.quaDefEyeL;
  599. DefaultEyeRotR = Body.quaDefEyeR;
  600. initialized = true;
  601. }
  602. if (blendSetValueBackup is null)
  603. BackupBlendSetValues();
  604. if (!HairGravityControl)
  605. InitializeGravityControls();
  606. HairGravityControl.Move += OnGravityEvent;
  607. SkirtGravityControl.Move += OnGravityEvent;
  608. if (MeidoPhotoStudio.EditMode)
  609. AllProcPropSeqStartPatcher.SequenceStart += ReinitializeBody;
  610. IKManager.Initialize();
  611. SetFaceBlendSet(DefaultFaceBlendSet);
  612. IK = true;
  613. Stop = false;
  614. Bone = false;
  615. Active = true;
  616. }
  617. private void ReinitializeBody(object sender, ProcStartEventArgs args)
  618. {
  619. if (Loading || !Body.isLoadedBody)
  620. return;
  621. if (args.Maid.status.guid != Maid.status.guid)
  622. return;
  623. var gravityControlProps =
  624. new[]
  625. {
  626. MPN.skirt, MPN.onepiece, MPN.mizugi, MPN.panz, MPN.set_maidwear, MPN.set_mywear, MPN.set_underwear,
  627. MPN.hairf, MPN.hairr, MPN.hairs, MPN.hairt,
  628. };
  629. Action action = null;
  630. // Change body
  631. if (Maid.GetProp(MPN.body).boDut)
  632. {
  633. IKManager.Destroy();
  634. action += ReinitializeBody;
  635. }
  636. // Change face
  637. if (Maid.GetProp(MPN.head).boDut)
  638. {
  639. SetFaceBlendSet(DefaultFaceBlendSet);
  640. action += ReinitializeFace;
  641. }
  642. // Gravity control clothing/hair change
  643. if (gravityControlProps.Any(prop => Maid.GetProp(prop).boDut))
  644. {
  645. if (HairGravityControl)
  646. Object.Destroy(HairGravityControl.gameObject);
  647. if (SkirtGravityControl)
  648. Object.Destroy(SkirtGravityControl.gameObject);
  649. action += ReinitializeGravity;
  650. }
  651. // Clothing/accessory changes
  652. // Includes null_mpn too but any button click results in null_mpn bodut I think
  653. action ??= Default;
  654. StartLoad(action);
  655. void ReinitializeBody()
  656. {
  657. IKManager.Initialize();
  658. Stop = false;
  659. // Maid animation needs to be set again for custom parts edit
  660. var uiRoot = GameObject.Find("UI Root");
  661. var customPartsWindow = UTY.GetChildObject(uiRoot, "Window/CustomPartsWindow")
  662. .GetComponent<SceneEditWindow.CustomPartsWindow>();
  663. Utility.SetFieldValue(customPartsWindow, "animation", Maid.GetAnimation());
  664. }
  665. void ReinitializeFace()
  666. {
  667. DefaultEyeRotL = Body.quaDefEyeL;
  668. DefaultEyeRotR = Body.quaDefEyeR;
  669. BackupBlendSetValues();
  670. }
  671. void ReinitializeGravity()
  672. {
  673. InitializeGravityControls();
  674. OnUpdateMeido();
  675. }
  676. void Default() =>
  677. OnUpdateMeido();
  678. }
  679. private void BackupBlendSetValues()
  680. {
  681. var values = Body.Face.morph.dicBlendSet[CurrentFaceBlendSet];
  682. blendSetValueBackup = new float[values.Length];
  683. values.CopyTo(blendSetValueBackup, 0);
  684. }
  685. private void ApplyBackupBlendSet()
  686. {
  687. blendSetValueBackup.CopyTo(Body.Face.morph.dicBlendSet[CurrentFaceBlendSet], 0);
  688. Maid.boNoseFook = false;
  689. }
  690. private CacheBoneDataArray GetCacheBoneData()
  691. {
  692. var cache = Maid.gameObject.GetComponent<CacheBoneDataArray>();
  693. if (!cache)
  694. {
  695. cache = Maid.gameObject.AddComponent<CacheBoneDataArray>();
  696. CreateCache();
  697. }
  698. if (!cache.bone_data?.transform)
  699. {
  700. Utility.LogDebug("Cache bone_data is null");
  701. CreateCache();
  702. }
  703. void CreateCache() =>
  704. cache.CreateCache(Body.GetBone("Bip01"));
  705. return cache;
  706. }
  707. private void InitializeGravityControls()
  708. {
  709. HairGravityControl = MakeGravityControl(skirt: false);
  710. SkirtGravityControl = MakeGravityControl(skirt: true);
  711. }
  712. private DragPointGravity MakeGravityControl(bool skirt = false)
  713. {
  714. var gravityDragpoint = DragPoint.Make<DragPointGravity>(PrimitiveType.Cube, Vector3.one * 0.12f);
  715. var control = DragPointGravity.MakeGravityControl(Maid, skirt);
  716. gravityDragpoint.Initialize(() => control.transform.position, () => Vector3.zero);
  717. gravityDragpoint.Set(control.transform);
  718. gravityDragpoint.gameObject.SetActive(false);
  719. return gravityDragpoint;
  720. }
  721. private void OnUpdateMeido(MeidoUpdateEventArgs args = null) =>
  722. UpdateMeido?.Invoke(this, args ?? MeidoUpdateEventArgs.Empty);
  723. private void OnGravityEvent(object sender, EventArgs args) =>
  724. OnGravityChange((DragPointGravity)sender);
  725. private void OnGravityChange(DragPointGravity dragPoint)
  726. {
  727. var args =
  728. new GravityEventArgs(dragPoint == SkirtGravityControl, dragPoint.MyObject.transform.localPosition);
  729. GravityMove?.Invoke(this, args);
  730. }
  731. }