Meido.cs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996
  1. using System;
  2. using System.IO;
  3. using System.Collections;
  4. using System.Linq;
  5. using System.Xml.Linq;
  6. using UnityEngine;
  7. using static TBody;
  8. using System.Collections.Generic;
  9. namespace COM3D2.MeidoPhotoStudio.Plugin
  10. {
  11. public class Meido : ISerializable
  12. {
  13. private bool initialized;
  14. private float[] BlendSetValueBackup;
  15. public DragPointGravity HairGravityControl { get; private set; }
  16. public DragPointGravity SkirtGravityControl { get; private set; }
  17. public bool HairGravityActive
  18. {
  19. get => HairGravityControl.Valid && HairGravityControl.Active;
  20. set
  21. {
  22. if (HairGravityControl.Valid && value != HairGravityControl.Active)
  23. {
  24. HairGravityControl.gameObject.SetActive(value);
  25. }
  26. }
  27. }
  28. public bool SkirtGravityActive
  29. {
  30. get => SkirtGravityControl.Valid && SkirtGravityControl.Active;
  31. set
  32. {
  33. if (SkirtGravityControl.Valid && value != SkirtGravityControl.Active)
  34. {
  35. SkirtGravityControl.gameObject.SetActive(value);
  36. }
  37. }
  38. }
  39. public const int meidoDataVersion = 1000;
  40. public static readonly PoseInfo DefaultPose =
  41. new PoseInfo(Constants.PoseGroupList[0], Constants.PoseDict[Constants.PoseGroupList[0]][0]);
  42. public static readonly string defaultFaceBlendSet = "通常";
  43. public static readonly string[] faceKeys = new string[24]
  44. {
  45. "eyeclose", "eyeclose2", "eyeclose3", "eyebig", "eyeclose6", "eyeclose5", "hitomih",
  46. "hitomis", "mayuha", "mayuw", "mayuup", "mayuv", "mayuvhalf", "moutha", "mouths",
  47. "mouthc", "mouthi", "mouthup", "mouthdw", "mouthhe", "mouthuphalf", "tangout",
  48. "tangup", "tangopen"
  49. };
  50. public static readonly string[] faceToggleKeys = new string[12]
  51. {
  52. // blush, shade, nose up, tears, drool, teeth
  53. "hoho2", "shock", "nosefook", "namida", "yodare", "toothoff",
  54. // cry 1, cry 2, cry 3, blush 1, blush 2, blush 3
  55. "tear1", "tear2", "tear3", "hohos", "hoho", "hohol"
  56. };
  57. public enum Curl
  58. {
  59. front, back, shift
  60. }
  61. public event EventHandler<MeidoUpdateEventArgs> UpdateMeido;
  62. public int StockNo { get; }
  63. public Maid Maid { get; }
  64. public TBody Body => Maid.body0;
  65. public MeidoDragPointManager IKManager { get; }
  66. public Texture2D Portrait => Maid.GetThumIcon();
  67. public bool IsEditMaid { get; set; }
  68. public PoseInfo CachedPose { get; private set; } = 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 string FirstName => Maid.status.firstName;
  73. public string LastName => Maid.status.lastName;
  74. public bool Busy => Maid.IsBusy || Loading;
  75. public bool CurlingFront => Maid.IsItemChange("skirt", "めくれスカート")
  76. || Maid.IsItemChange("onepiece", "めくれスカート");
  77. public bool CurlingBack => Maid.IsItemChange("skirt", "めくれスカート後ろ")
  78. || Maid.IsItemChange("onepiece", "めくれスカート後ろ");
  79. public bool PantsuShift => Maid.IsItemChange("panz", "パンツずらし")
  80. || Maid.IsItemChange("mizugi", "パンツずらし");
  81. private bool freeLook;
  82. public bool FreeLook
  83. {
  84. get => freeLook;
  85. set
  86. {
  87. if (freeLook == value) return;
  88. freeLook = value;
  89. Body.trsLookTarget = freeLook ? null : GameMain.Instance.MainCamera.transform;
  90. OnUpdateMeido();
  91. }
  92. }
  93. public bool HeadToCam
  94. {
  95. get => Body.isLoadedBody && Body.boHeadToCam;
  96. set
  97. {
  98. if (!Body.isLoadedBody || HeadToCam == value) return;
  99. Body.HeadToCamPer = 0f;
  100. Body.boHeadToCam = value;
  101. if (!HeadToCam && !EyeToCam) FreeLook = false;
  102. OnUpdateMeido();
  103. }
  104. }
  105. public bool EyeToCam
  106. {
  107. get => Body.isLoadedBody && Body.boEyeToCam;
  108. set
  109. {
  110. if (!Body.isLoadedBody || EyeToCam == value) return;
  111. Body.boEyeToCam = value;
  112. if (!HeadToCam && !EyeToCam) FreeLook = false;
  113. OnUpdateMeido();
  114. }
  115. }
  116. public bool Stop
  117. {
  118. get => !Body.isLoadedBody || !Maid.GetAnimation().isPlaying;
  119. set
  120. {
  121. if (!Body.isLoadedBody || value == Stop) return;
  122. if (value) Maid.GetAnimation().Stop();
  123. else
  124. {
  125. Body.boEyeToCam = true;
  126. Body.boHeadToCam = true;
  127. SetPose(CachedPose.Pose);
  128. }
  129. OnUpdateMeido();
  130. }
  131. }
  132. public bool IK
  133. {
  134. get => IKManager.Active;
  135. set
  136. {
  137. if (value == IKManager.Active) return;
  138. IKManager.Active = value;
  139. }
  140. }
  141. public bool Bone
  142. {
  143. get => IKManager.IsBone;
  144. set
  145. {
  146. if (value == Bone) return;
  147. IKManager.IsBone = value;
  148. OnUpdateMeido();
  149. }
  150. }
  151. public event EventHandler<GravityEventArgs> GravityMove;
  152. public Quaternion DefaultEyeRotL { get; private set; }
  153. public Quaternion DefaultEyeRotR { get; private set; }
  154. public Meido(int stockMaidIndex)
  155. {
  156. StockNo = stockMaidIndex;
  157. Maid = GameMain.Instance.CharacterMgr.GetStockMaid(stockMaidIndex);
  158. IKManager = new MeidoDragPointManager(this);
  159. IKManager.SelectMaid += (s, args) => OnUpdateMeido(args);
  160. }
  161. public void Load(int slot)
  162. {
  163. if (Busy) return;
  164. Slot = slot;
  165. FreeLook = false;
  166. Maid.Visible = true;
  167. Body.boHeadToCam = true;
  168. Body.boEyeToCam = true;
  169. Body.SetBoneHitHeightY(-1000f);
  170. if (!Body.isLoadedBody)
  171. {
  172. Maid.DutPropAll();
  173. Maid.AllProcPropSeqStart();
  174. }
  175. StartLoad(OnBodyLoad);
  176. }
  177. private void StartLoad(Action callback)
  178. {
  179. if (Loading) return;
  180. GameMain.Instance.StartCoroutine(Load(callback));
  181. }
  182. private IEnumerator Load(Action callback)
  183. {
  184. Loading = true;
  185. while (Maid.IsBusy) yield return null;
  186. yield return new WaitForEndOfFrame();
  187. callback();
  188. Loading = false;
  189. }
  190. private void OnBodyLoad()
  191. {
  192. if (!initialized)
  193. {
  194. DefaultEyeRotL = Body.quaDefEyeL;
  195. DefaultEyeRotR = Body.quaDefEyeR;
  196. initialized = true;
  197. }
  198. if (BlendSetValueBackup == null) BackupBlendSetValues();
  199. if (!HairGravityControl) InitializeGravityControls();
  200. HairGravityControl.Move += OnGravityEvent;
  201. SkirtGravityControl.Move += OnGravityEvent;
  202. if (MeidoPhotoStudio.EditMode) AllProcPropSeqStartPatcher.SequenceStart += ReinitializeBody;
  203. IKManager.Initialize();
  204. IK = true;
  205. Stop = false;
  206. Bone = false;
  207. }
  208. private void ReinitializeBody(object sender, ProcStartEventArgs args)
  209. {
  210. if (Loading || !Body.isLoadedBody) return;
  211. if (args.maid.status.guid == Maid.status.guid)
  212. {
  213. MPN[] gravityControlProps = new[] {
  214. MPN.skirt, MPN.onepiece, MPN.mizugi, MPN.panz, MPN.set_maidwear, MPN.set_mywear, MPN.set_underwear,
  215. MPN.hairf, MPN.hairr, MPN.hairs, MPN.hairt
  216. };
  217. // Change body
  218. if (Maid.GetProp(MPN.body).boDut)
  219. {
  220. IKManager.Destroy();
  221. StartLoad(reinitializeBody);
  222. }
  223. // Change face
  224. else if (Maid.GetProp(MPN.head).boDut)
  225. {
  226. SetFaceBlendSet(defaultFaceBlendSet);
  227. StartLoad(reinitializeFace);
  228. }
  229. // Gravity control clothing/hair change
  230. else if (gravityControlProps.Any(prop => Maid.GetProp(prop).boDut))
  231. {
  232. if (HairGravityControl) GameObject.Destroy(HairGravityControl.gameObject);
  233. if (SkirtGravityControl) GameObject.Destroy(SkirtGravityControl.gameObject);
  234. StartLoad(reinitializeGravity);
  235. }
  236. // Clothing/accessory changes
  237. // Includes null_mpn too but any button click results in null_mpn bodut I think
  238. else StartLoad(() => OnUpdateMeido());
  239. void reinitializeBody()
  240. {
  241. IKManager.Initialize();
  242. Stop = false;
  243. // Maid animation needs to be set again for custom parts edit
  244. GameObject uiRoot = GameObject.Find("UI Root");
  245. var customPartsWindow = UTY.GetChildObject(uiRoot, "Window/CustomPartsWindow")
  246. .GetComponent<SceneEditWindow.CustomPartsWindow>();
  247. Utility.SetFieldValue(customPartsWindow, "animation", Maid.GetAnimation());
  248. }
  249. void reinitializeFace()
  250. {
  251. DefaultEyeRotL = Body.quaDefEyeL;
  252. DefaultEyeRotR = Body.quaDefEyeR;
  253. BackupBlendSetValues();
  254. }
  255. void reinitializeGravity()
  256. {
  257. InitializeGravityControls();
  258. OnUpdateMeido();
  259. }
  260. }
  261. }
  262. public void Unload()
  263. {
  264. if (Body.isLoadedBody && Maid.Visible)
  265. {
  266. DetachAllMpnAttach();
  267. Body.jbMuneL.enabled = true;
  268. Body.jbMuneR.enabled = true;
  269. Body.quaDefEyeL = DefaultEyeRotL;
  270. Body.quaDefEyeR = DefaultEyeRotR;
  271. if (HairGravityControl)
  272. {
  273. HairGravityControl.Move -= OnGravityEvent;
  274. HairGravityActive = false;
  275. }
  276. if (SkirtGravityControl)
  277. {
  278. SkirtGravityControl.Move -= OnGravityEvent;
  279. SkirtGravityActive = false;
  280. }
  281. ApplyGravity(Vector3.zero, skirt: false);
  282. ApplyGravity(Vector3.zero, skirt: true);
  283. SetFaceBlendSet(defaultFaceBlendSet);
  284. }
  285. AllProcPropSeqStartPatcher.SequenceStart -= ReinitializeBody;
  286. Body.MuneYureL(1f);
  287. Body.MuneYureR(1f);
  288. Body.SetMaskMode(MaskMode.None);
  289. Body.SetBoneHitHeightY(0f);
  290. Maid.Visible = false;
  291. IKManager.Destroy();
  292. }
  293. public void Deactivate()
  294. {
  295. Unload();
  296. if (HairGravityControl) GameObject.Destroy(HairGravityControl.gameObject);
  297. if (SkirtGravityControl) GameObject.Destroy(SkirtGravityControl.gameObject);
  298. Maid.SetPos(Vector3.zero);
  299. Maid.SetRot(Vector3.zero);
  300. Maid.SetPosOffset(Vector3.zero);
  301. Body.transform.localScale = Vector3.one;
  302. Maid.ResetAll();
  303. Maid.MabatakiUpdateStop = false;
  304. Maid.ActiveSlotNo = -1;
  305. }
  306. public void SetPose(PoseInfo poseInfo)
  307. {
  308. CachedPose = poseInfo;
  309. SetPose(poseInfo.Pose);
  310. }
  311. public void SetPose(string pose)
  312. {
  313. if (!Body.isLoadedBody) return;
  314. if (pose.StartsWith(Constants.customPosePath))
  315. {
  316. string poseFilename = Path.GetFileNameWithoutExtension(pose);
  317. try
  318. {
  319. byte[] poseBuffer = File.ReadAllBytes(pose);
  320. string hash = Path.GetFileName(pose).GetHashCode().ToString();
  321. Body.CrossFade(hash, poseBuffer, loop: true, fade: 0f);
  322. }
  323. catch (Exception e) when (e is DirectoryNotFoundException || e is FileNotFoundException)
  324. {
  325. Utility.LogWarning($"{poseFilename}: Could not open because {e.Message}");
  326. Constants.InitializeCustomPoses();
  327. return;
  328. }
  329. catch (Exception e)
  330. {
  331. Utility.LogWarning($"{poseFilename}: Could not apply pose because {e.Message}");
  332. return;
  333. }
  334. SetMune(true, left: true);
  335. SetMune(true, left: false);
  336. }
  337. else
  338. {
  339. string[] poseComponents = pose.Split(',');
  340. pose = poseComponents[0] + ".anm";
  341. Maid.CrossFade(pose, loop: true, val: 0f);
  342. Maid.GetAnimation().Play();
  343. if (poseComponents.Length > 1)
  344. {
  345. Maid.GetAnimation()[pose].time = float.Parse(poseComponents[1]);
  346. Maid.GetAnimation()[pose].speed = 0f;
  347. }
  348. SetPoseMune();
  349. }
  350. Maid.SetAutoTwistAll(true);
  351. }
  352. public void CopyPose(Meido fromMeido)
  353. {
  354. Stop = true;
  355. GetCacheBoneData().SetFrameBinary(fromMeido.SerializePose(frameBinary: true));
  356. SetMune(fromMeido.Body.GetMuneYureL() != 0f, left: true);
  357. SetMune(fromMeido.Body.GetMuneYureR() != 0f, left: false);
  358. }
  359. public void SetMune(bool enabled, bool left = false)
  360. {
  361. float value = enabled ? 1f : 0f;
  362. if (left)
  363. {
  364. Body.MuneYureL(value);
  365. Body.jbMuneL.enabled = enabled;
  366. }
  367. else
  368. {
  369. Body.MuneYureR(value);
  370. Body.jbMuneR.enabled = enabled;
  371. }
  372. }
  373. private void SetPoseMune()
  374. {
  375. bool momiOrPaizuri = CachedPose.Pose.Contains("_momi") || CachedPose.Pose.Contains("paizuri_");
  376. SetMune(!momiOrPaizuri, left: true);
  377. SetMune(!momiOrPaizuri, left: false);
  378. }
  379. public void SetHandPreset(string filename, bool right)
  380. {
  381. string faceFilename = Path.GetFileNameWithoutExtension(filename);
  382. try
  383. {
  384. XDocument handDocument = XDocument.Load(filename);
  385. XElement handElement = handDocument.Element("FingerData");
  386. if (handElement?.Elements().Any(element => element?.IsEmpty ?? true) ?? true)
  387. {
  388. Utility.LogWarning($"{faceFilename}: Could not apply hand preset because it is invalid.");
  389. return;
  390. }
  391. Stop = true;
  392. bool rightData = bool.Parse(handElement.Element("RightData").Value);
  393. string base64Data = handElement.Element("BinaryData").Value;
  394. byte[] handData = Convert.FromBase64String(base64Data);
  395. IKManager.DeserializeHand(handData, right, rightData != right);
  396. }
  397. catch (System.Xml.XmlException e)
  398. {
  399. Utility.LogWarning($"{faceFilename}: Hand preset data is malformed because {e.Message}");
  400. }
  401. catch (Exception e) when (e is DirectoryNotFoundException || e is FileNotFoundException)
  402. {
  403. Utility.LogWarning($"{faceFilename}: Could not open hand preset because {e.Message}");
  404. Constants.InitializeHandPresets();
  405. }
  406. catch (Exception e)
  407. {
  408. Utility.LogWarning($"{faceFilename}: Could not parse hand preset because {e.Message}");
  409. }
  410. }
  411. public byte[] SerializePose(bool frameBinary = false)
  412. {
  413. CacheBoneDataArray cache = GetCacheBoneData();
  414. bool muneL = Body.GetMuneYureL() == 0f;
  415. bool muneR = Body.GetMuneYureR() == 0f;
  416. return frameBinary ? cache.GetFrameBinary(muneL, muneR) : cache.GetAnmBinary(true, true);
  417. }
  418. public Dictionary<string, float> SerializeFace()
  419. {
  420. Dictionary<string, float> faceData = new Dictionary<string, float>();
  421. foreach (string hash in faceKeys.Concat(faceToggleKeys))
  422. {
  423. try
  424. {
  425. float value = GetFaceBlendValue(hash);
  426. faceData.Add(hash, value);
  427. }
  428. catch { }
  429. }
  430. return faceData;
  431. }
  432. public void SetFaceBlendSet(string blendSet)
  433. {
  434. if (blendSet.StartsWith(Constants.customFacePath))
  435. {
  436. string blendSetFileName = Path.GetFileNameWithoutExtension(blendSet);
  437. try
  438. {
  439. XDocument faceDocument = XDocument.Load(blendSet, LoadOptions.SetLineInfo);
  440. XElement faceDataElement = faceDocument.Element("FaceData");
  441. if (faceDataElement?.IsEmpty ?? true)
  442. {
  443. Utility.LogWarning($"{blendSetFileName}: Could not apply face preset because it is invalid.");
  444. return;
  445. }
  446. HashSet<string> hashKeys = new HashSet<string>(faceKeys.Concat(faceToggleKeys));
  447. foreach (XElement element in faceDataElement.Elements())
  448. {
  449. System.Xml.IXmlLineInfo info = element;
  450. int line = info.HasLineInfo() ? info.LineNumber : -1;
  451. string key;
  452. if ((key = (string)element.Attribute("name")) == null)
  453. {
  454. Utility.LogWarning($"{blendSetFileName}: Could not read face blend key at line {line}.");
  455. continue;
  456. }
  457. if (!hashKeys.Contains(key))
  458. {
  459. Utility.LogWarning($"{blendSetFileName}: Invalid face blend key '{key}' at line {line}.");
  460. continue;
  461. }
  462. if (float.TryParse(element.Value, out float value))
  463. {
  464. try { SetFaceBlendValue(key, value); }
  465. catch { }
  466. }
  467. else Utility.LogWarning(
  468. $"{blendSetFileName}: Could not parse value '{element.Value}' of '{key}' at line {line}"
  469. );
  470. }
  471. }
  472. catch (System.Xml.XmlException e)
  473. {
  474. Utility.LogWarning($"{blendSetFileName}: Face preset data is malformed because {e.Message}");
  475. return;
  476. }
  477. catch (Exception e) when (e is DirectoryNotFoundException || e is FileNotFoundException)
  478. {
  479. Utility.LogWarning($"{blendSetFileName}: Could not open face preset because {e.Message}");
  480. Constants.InitializeCustomFaceBlends();
  481. return;
  482. }
  483. catch (Exception e)
  484. {
  485. Utility.LogWarning($"{blendSetFileName}: Could not parse face preset because {e.Message}");
  486. return;
  487. }
  488. }
  489. else
  490. {
  491. ApplyBackupBlendSet();
  492. CurrentFaceBlendSet = blendSet;
  493. BackupBlendSetValues();
  494. Maid.FaceAnime(blendSet, 0f);
  495. }
  496. StopBlink();
  497. OnUpdateMeido();
  498. }
  499. public void SetFaceBlendValue(string hash, float value)
  500. {
  501. TMorph morph = Body.Face.morph;
  502. if (hash == "nosefook") Maid.boNoseFook = morph.boNoseFook = value > 0f;
  503. else
  504. {
  505. hash = Utility.GP01FbFaceHash(morph, hash);
  506. try { morph.dicBlendSet[CurrentFaceBlendSet][(int)morph.hash[hash]] = value; }
  507. catch { }
  508. }
  509. }
  510. public float GetFaceBlendValue(string hash)
  511. {
  512. TMorph morph = Body.Face.morph;
  513. if (hash == "nosefook") return (Maid.boNoseFook || morph.boNoseFook) ? 1f : 0f;
  514. hash = Utility.GP01FbFaceHash(morph, hash);
  515. return morph.dicBlendSet[CurrentFaceBlendSet][(int)morph.hash[hash]];
  516. }
  517. public void StopBlink()
  518. {
  519. Maid.MabatakiUpdateStop = true;
  520. Body.Face.morph.EyeMabataki = 0f;
  521. Utility.SetFieldValue(Maid, "MabatakiVal", 0f);
  522. }
  523. public void SetMaskMode(MaskMode maskMode)
  524. {
  525. bool invisibleBody = !Body.GetMask(SlotID.body);
  526. Body.SetMaskMode(maskMode);
  527. if (invisibleBody) SetBodyMask(false);
  528. }
  529. public void SetBodyMask(bool enabled)
  530. {
  531. Hashtable table = Utility.GetFieldValue<TBody, Hashtable>(Body, "m_hFoceHide");
  532. foreach (SlotID bodySlot in MaidDressingPane.bodySlots)
  533. {
  534. table[bodySlot] = enabled;
  535. }
  536. if (Body.goSlot[19].m_strModelFileName.Contains("melala_body"))
  537. {
  538. table[SlotID.accHana] = enabled;
  539. }
  540. Body.FixMaskFlag();
  541. Body.FixVisibleFlag(false);
  542. }
  543. public void SetCurling(Curl curling, bool enabled)
  544. {
  545. string[] name = curling == Curl.shift
  546. ? new[] { "panz", "mizugi" }
  547. : new[] { "skirt", "onepiece" };
  548. if (enabled)
  549. {
  550. string action = curling == Curl.shift
  551. ? "パンツずらし" : curling == Curl.front
  552. ? "めくれスカート" : "めくれスカート後ろ";
  553. Maid.ItemChangeTemp(name[0], action);
  554. Maid.ItemChangeTemp(name[1], action);
  555. }
  556. else
  557. {
  558. Maid.ResetProp(name[0]);
  559. Maid.ResetProp(name[1]);
  560. }
  561. Maid.AllProcProp();
  562. HairGravityControl.Control.OnChangeMekure();
  563. SkirtGravityControl.Control.OnChangeMekure();
  564. }
  565. public void SetMpnProp(MpnAttachProp prop, bool detach)
  566. {
  567. if (detach) Maid.ResetProp(prop.Tag, false);
  568. else Maid.SetProp(prop.Tag, prop.MenuFile, 0, true);
  569. Maid.AllProcProp();
  570. }
  571. public void DetachAllMpnAttach()
  572. {
  573. Maid.ResetProp(MPN.kousoku_lower, false);
  574. Maid.ResetProp(MPN.kousoku_upper, false);
  575. Maid.AllProcProp();
  576. }
  577. public void ApplyGravity(Vector3 position, bool skirt = false)
  578. {
  579. DragPointGravity dragPoint = skirt ? SkirtGravityControl : HairGravityControl;
  580. if (dragPoint.Valid) dragPoint.Control.transform.localPosition = position;
  581. }
  582. private void BackupBlendSetValues()
  583. {
  584. float[] values = Body.Face.morph.dicBlendSet[CurrentFaceBlendSet];
  585. BlendSetValueBackup = new float[values.Length];
  586. values.CopyTo(BlendSetValueBackup, 0);
  587. }
  588. private void ApplyBackupBlendSet()
  589. {
  590. BlendSetValueBackup.CopyTo(Body.Face.morph.dicBlendSet[CurrentFaceBlendSet], 0);
  591. Maid.boNoseFook = false;
  592. }
  593. private CacheBoneDataArray GetCacheBoneData()
  594. {
  595. CacheBoneDataArray cache = Maid.gameObject.GetComponent<CacheBoneDataArray>();
  596. void CreateCache() => cache.CreateCache(Body.GetBone("Bip01"));
  597. if (cache == null)
  598. {
  599. cache = Maid.gameObject.AddComponent<CacheBoneDataArray>();
  600. CreateCache();
  601. }
  602. if (cache.bone_data?.transform == null)
  603. {
  604. Utility.LogDebug("Cache bone_data is null");
  605. CreateCache();
  606. }
  607. return cache;
  608. }
  609. private void InitializeGravityControls()
  610. {
  611. HairGravityControl = MakeGravityControl(skirt: false);
  612. SkirtGravityControl = MakeGravityControl(skirt: true);
  613. }
  614. private DragPointGravity MakeGravityControl(bool skirt = false)
  615. {
  616. DragPointGravity gravityDragpoint = DragPoint.Make<DragPointGravity>(
  617. PrimitiveType.Cube, Vector3.one * 0.12f
  618. );
  619. GravityTransformControl control = DragPointGravity.MakeGravityControl(Maid, skirt);
  620. gravityDragpoint.Initialize(() => control.transform.position, () => Vector3.zero);
  621. gravityDragpoint.Set(control.transform);
  622. gravityDragpoint.gameObject.SetActive(false);
  623. return gravityDragpoint;
  624. }
  625. private void OnUpdateMeido(MeidoUpdateEventArgs args = null)
  626. {
  627. UpdateMeido?.Invoke(this, args ?? MeidoUpdateEventArgs.Empty);
  628. }
  629. private void OnGravityEvent(object sender, EventArgs args) => OnGravityChange((DragPointGravity)sender);
  630. private void OnGravityChange(DragPointGravity dragPoint)
  631. {
  632. GravityEventArgs args = new GravityEventArgs(
  633. dragPoint == SkirtGravityControl, dragPoint.MyObject.transform.localPosition
  634. );
  635. GravityMove?.Invoke(this, args);
  636. }
  637. public void Serialize(BinaryWriter binaryWriter)
  638. {
  639. using (MemoryStream memoryStream = new MemoryStream())
  640. using (BinaryWriter tempWriter = new BinaryWriter(memoryStream))
  641. {
  642. // transform
  643. tempWriter.WriteVector3(Maid.transform.position);
  644. tempWriter.WriteQuaternion(Maid.transform.rotation);
  645. tempWriter.WriteVector3(Maid.transform.localScale);
  646. // pose
  647. byte[] poseBuffer = SerializePose(true);
  648. tempWriter.Write(poseBuffer.Length);
  649. tempWriter.Write(poseBuffer);
  650. CachedPose.Serialize(tempWriter);
  651. // eye direction
  652. tempWriter.WriteQuaternion(Body.quaDefEyeL * Quaternion.Inverse(DefaultEyeRotL));
  653. tempWriter.WriteQuaternion(Body.quaDefEyeR * Quaternion.Inverse(DefaultEyeRotR));
  654. // free look
  655. tempWriter.Write(FreeLook);
  656. if (FreeLook)
  657. {
  658. tempWriter.WriteVector3(Body.offsetLookTarget);
  659. tempWriter.WriteVector3(Utility.GetFieldValue<TBody, Vector3>(Body, "HeadEulerAngle"));
  660. }
  661. // Head/eye to camera
  662. tempWriter.Write(HeadToCam);
  663. tempWriter.Write(EyeToCam);
  664. // face
  665. SerializeFace(tempWriter);
  666. // body visible
  667. tempWriter.Write(Body.GetMask(SlotID.body));
  668. // clothing
  669. foreach (SlotID clothingSlot in MaidDressingPane.clothingSlots)
  670. {
  671. bool value = true;
  672. if (clothingSlot == SlotID.wear)
  673. {
  674. if (MaidDressingPane.wearSlots.Any(slot => Body.GetSlotLoaded(slot)))
  675. {
  676. value = MaidDressingPane.wearSlots.Any(slot => Body.GetMask(slot));
  677. }
  678. }
  679. else if (clothingSlot == SlotID.megane)
  680. {
  681. SlotID[] slots = new[] { SlotID.megane, SlotID.accHead };
  682. if (slots.Any(slot => Body.GetSlotLoaded(slot)))
  683. {
  684. value = slots.Any(slot => Body.GetMask(slot));
  685. }
  686. }
  687. else if (Body.GetSlotLoaded(clothingSlot))
  688. {
  689. value = Body.GetMask(clothingSlot);
  690. }
  691. tempWriter.Write(value);
  692. }
  693. // hair/skirt gravity
  694. tempWriter.Write(HairGravityActive);
  695. if (HairGravityActive) tempWriter.WriteVector3(HairGravityControl.Control.transform.localPosition);
  696. tempWriter.Write(SkirtGravityActive);
  697. if (SkirtGravityActive) tempWriter.WriteVector3(SkirtGravityControl.Control.transform.localPosition);
  698. // zurashi and mekure
  699. tempWriter.Write(CurlingFront);
  700. tempWriter.Write(CurlingBack);
  701. tempWriter.Write(PantsuShift);
  702. bool hasKousokuUpper = Body.GetSlotLoaded(SlotID.kousoku_upper);
  703. tempWriter.Write(hasKousokuUpper);
  704. if (hasKousokuUpper) tempWriter.Write(Maid.GetProp(MPN.kousoku_upper).strTempFileName);
  705. bool hasKousokuLower = Body.GetSlotLoaded(SlotID.kousoku_lower);
  706. tempWriter.Write(hasKousokuLower);
  707. if (hasKousokuLower) tempWriter.Write(Maid.GetProp(MPN.kousoku_lower).strTempFileName);
  708. binaryWriter.Write(memoryStream.Length);
  709. binaryWriter.Write(memoryStream.ToArray());
  710. }
  711. }
  712. private void SerializeFace(BinaryWriter binaryWriter)
  713. {
  714. binaryWriter.Write("MPS_FACE");
  715. foreach (string hash in faceKeys.Concat(faceToggleKeys))
  716. {
  717. try
  718. {
  719. float value = GetFaceBlendValue(hash);
  720. binaryWriter.Write(hash);
  721. binaryWriter.Write(value);
  722. }
  723. catch { }
  724. }
  725. binaryWriter.Write("END_FACE");
  726. }
  727. public void Deserialize(BinaryReader binaryReader) => Deserialize(binaryReader, meidoDataVersion, false);
  728. public void Deserialize(BinaryReader binaryReader, int dataVersion, bool mmScene)
  729. {
  730. Maid.GetAnimation().Stop();
  731. DetachAllMpnAttach();
  732. binaryReader.ReadInt64(); // meido buffer length
  733. // transform
  734. Maid.transform.position = binaryReader.ReadVector3();
  735. Maid.transform.rotation = binaryReader.ReadQuaternion();
  736. Maid.transform.localScale = binaryReader.ReadVector3();
  737. IKManager.SetDragPointScale(Maid.transform.localScale.x);
  738. // pose
  739. KeyValuePair<bool, bool> muneSetting = new KeyValuePair<bool, bool>(true, true);
  740. if (mmScene) IKManager.Deserialize(binaryReader);
  741. else
  742. {
  743. int poseBufferLength = binaryReader.ReadInt32();
  744. byte[] poseBuffer = binaryReader.ReadBytes(poseBufferLength);
  745. muneSetting = GetCacheBoneData().SetFrameBinary(poseBuffer);
  746. }
  747. SetMune(!muneSetting.Key, left: true);
  748. SetMune(!muneSetting.Value, left: false);
  749. CachedPose = PoseInfo.Deserialize(binaryReader);
  750. // eye direction
  751. Body.quaDefEyeL = binaryReader.ReadQuaternion() * DefaultEyeRotL;
  752. Body.quaDefEyeR = binaryReader.ReadQuaternion() * DefaultEyeRotR;
  753. // free look
  754. FreeLook = binaryReader.ReadBoolean();
  755. if (FreeLook)
  756. {
  757. Body.offsetLookTarget = binaryReader.ReadVector3();
  758. // Head angle cannot be resolved with just the offsetLookTarget
  759. if (!mmScene)
  760. {
  761. Utility.SetFieldValue(Body, "HeadEulerAngleG", Vector3.zero);
  762. Utility.SetFieldValue(Body, "HeadEulerAngle", binaryReader.ReadVector3());
  763. }
  764. }
  765. // Head/eye to camera
  766. HeadToCam = binaryReader.ReadBoolean();
  767. EyeToCam = binaryReader.ReadBoolean();
  768. // face
  769. DeserializeFace(binaryReader);
  770. // body visible
  771. SetBodyMask(binaryReader.ReadBoolean());
  772. // clothing
  773. foreach (SlotID clothingSlot in MaidDressingPane.clothingSlots)
  774. {
  775. bool value = binaryReader.ReadBoolean();
  776. if (mmScene) continue;
  777. if (clothingSlot == SlotID.wear)
  778. {
  779. Body.SetMask(SlotID.wear, value);
  780. Body.SetMask(SlotID.mizugi, value);
  781. Body.SetMask(SlotID.onepiece, value);
  782. }
  783. else if (clothingSlot == SlotID.megane)
  784. {
  785. Body.SetMask(SlotID.megane, value);
  786. Body.SetMask(SlotID.accHead, value);
  787. }
  788. else if (Body.GetSlotLoaded(clothingSlot))
  789. {
  790. Body.SetMask(clothingSlot, value);
  791. }
  792. }
  793. // hair/skirt gravity
  794. bool hairGravityActive = binaryReader.ReadBoolean();
  795. if (hairGravityActive)
  796. {
  797. HairGravityActive = true;
  798. ApplyGravity(binaryReader.ReadVector3(), skirt: false);
  799. }
  800. bool skirtGravityActive = binaryReader.ReadBoolean();
  801. if (skirtGravityActive)
  802. {
  803. SkirtGravityActive = true;
  804. ApplyGravity(binaryReader.ReadVector3(), skirt: true);
  805. }
  806. // zurashi and mekure
  807. bool curlingFront = binaryReader.ReadBoolean();
  808. bool curlingBack = binaryReader.ReadBoolean();
  809. bool curlingPantsu = binaryReader.ReadBoolean();
  810. if (!mmScene)
  811. {
  812. if (CurlingFront != curlingFront) SetCurling(Curl.front, curlingFront);
  813. if (CurlingBack != curlingBack) SetCurling(Curl.back, curlingBack);
  814. SetCurling(Curl.shift, curlingPantsu);
  815. }
  816. bool hasKousokuUpper = binaryReader.ReadBoolean();
  817. if (hasKousokuUpper)
  818. {
  819. try
  820. {
  821. SetMpnProp(new MpnAttachProp(MPN.kousoku_upper, binaryReader.ReadString()), false);
  822. }
  823. catch { }
  824. }
  825. bool hasKousokuLower = binaryReader.ReadBoolean();
  826. if (hasKousokuLower)
  827. {
  828. try
  829. {
  830. SetMpnProp(new MpnAttachProp(MPN.kousoku_lower, binaryReader.ReadString()), false);
  831. }
  832. catch { }
  833. }
  834. // OnUpdateMeido();
  835. }
  836. private void DeserializeFace(BinaryReader binaryReader)
  837. {
  838. StopBlink();
  839. binaryReader.ReadString(); // read face header
  840. string header;
  841. while ((header = binaryReader.ReadString()) != "END_FACE")
  842. {
  843. SetFaceBlendValue(header, binaryReader.ReadSingle());
  844. }
  845. }
  846. }
  847. public class GravityEventArgs : EventArgs
  848. {
  849. public Vector3 LocalPosition { get; }
  850. public bool IsSkirt { get; }
  851. public GravityEventArgs(bool isSkirt, Vector3 localPosition)
  852. {
  853. LocalPosition = localPosition;
  854. IsSkirt = isSkirt;
  855. }
  856. }
  857. public struct PoseInfo
  858. {
  859. public string PoseGroup { get; }
  860. public string Pose { get; }
  861. public bool CustomPose { get; }
  862. public PoseInfo(string poseGroup, string pose, bool customPose = false)
  863. {
  864. PoseGroup = poseGroup;
  865. Pose = pose;
  866. CustomPose = customPose;
  867. }
  868. public void Serialize(BinaryWriter binaryWriter)
  869. {
  870. binaryWriter.Write(PoseGroup);
  871. binaryWriter.Write(Pose);
  872. binaryWriter.Write(CustomPose);
  873. }
  874. public static PoseInfo Deserialize(BinaryReader binaryReader)
  875. {
  876. return new PoseInfo
  877. (
  878. binaryReader.ReadString(),
  879. binaryReader.ReadString(),
  880. binaryReader.ReadBoolean()
  881. );
  882. }
  883. }
  884. }