Meido.cs 33 KB

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