Meido.cs 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  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. SetMune(false, left: true);
  273. SetMune(false, left: false);
  274. }
  275. else
  276. {
  277. string[] poseComponents = pose.Split(',');
  278. pose = poseComponents[0] + ".anm";
  279. Maid.CrossFade(pose, loop: true, val: 0f);
  280. Maid.GetAnimation().Play();
  281. if (poseComponents.Length > 1)
  282. {
  283. Maid.GetAnimation()[pose].time = float.Parse(poseComponents[1]);
  284. Maid.GetAnimation()[pose].speed = 0f;
  285. }
  286. SetPoseMune();
  287. }
  288. Maid.SetAutoTwistAll(true);
  289. }
  290. public void CopyPose(Meido fromMeido)
  291. {
  292. byte[] poseBinary = fromMeido.SerializePose();
  293. string tag = $"copy_{fromMeido.Maid.status.guid}";
  294. Body.CrossFade(tag, poseBinary, false, true, false, 0f);
  295. Maid.SetAutoTwistAll(true);
  296. Maid.transform.rotation = fromMeido.Maid.transform.rotation;
  297. SetPoseMune();
  298. }
  299. public void SetMune(bool enabled, bool left = false)
  300. {
  301. float value = enabled ? 1f : 0f;
  302. if (left)
  303. {
  304. Body.MuneYureL(value);
  305. Body.jbMuneL.enabled = enabled;
  306. }
  307. else
  308. {
  309. Body.MuneYureR(value);
  310. Body.jbMuneR.enabled = enabled;
  311. }
  312. }
  313. private void SetPoseMune()
  314. {
  315. bool momiOrPaizuri = CachedPose.Pose.Contains("_momi") || CachedPose.Pose.Contains("paizuri_");
  316. SetMune(!momiOrPaizuri, left: true);
  317. SetMune(!momiOrPaizuri, left: false);
  318. }
  319. public void SetHandPreset(string filename, bool right)
  320. {
  321. string faceFilename = Path.GetFileNameWithoutExtension(filename);
  322. try
  323. {
  324. XDocument handDocument = XDocument.Load(filename);
  325. XElement handElement = handDocument.Element("FingerData");
  326. if (handElement?.Elements().Any(element => element?.IsEmpty ?? true) ?? true)
  327. {
  328. Utility.LogWarning($"{faceFilename}: Could not apply hand preset because it is invalid.");
  329. return;
  330. }
  331. Stop = true;
  332. bool rightData = bool.Parse(handElement.Element("RightData").Value);
  333. string base64Data = handElement.Element("BinaryData").Value;
  334. byte[] handData = Convert.FromBase64String(base64Data);
  335. IKManager.DeserializeHand(handData, right, rightData != right);
  336. }
  337. catch (System.Xml.XmlException e)
  338. {
  339. Utility.LogWarning($"{faceFilename}: Hand preset data is malformed because {e.Message}");
  340. }
  341. catch (Exception e) when (e is DirectoryNotFoundException || e is FileNotFoundException)
  342. {
  343. Utility.LogWarning($"{faceFilename}: Could not open hand preset because {e.Message}");
  344. Constants.InitializeHandPresets();
  345. }
  346. catch (Exception e)
  347. {
  348. Utility.LogWarning($"{faceFilename}: Could not parse hand preset because {e.Message}");
  349. }
  350. }
  351. public byte[] SerializePose(bool frameBinary = false)
  352. {
  353. CacheBoneDataArray cache = GetCacheBoneData();
  354. bool muneL = Body.GetMuneYureL() == 0f;
  355. bool muneR = Body.GetMuneYureR() == 0f;
  356. return frameBinary ? cache.GetFrameBinary(muneL, muneR) : cache.GetAnmBinary(true, true);
  357. }
  358. public Dictionary<string, float> SerializeFace()
  359. {
  360. Dictionary<string, float> faceData = new Dictionary<string, float>();
  361. foreach (string hash in faceKeys.Concat(faceToggleKeys))
  362. {
  363. try
  364. {
  365. float value = GetFaceBlendValue(hash);
  366. faceData.Add(hash, value);
  367. }
  368. catch { }
  369. }
  370. return faceData;
  371. }
  372. public void SetFaceBlendSet(string blendSet, bool custom = false)
  373. {
  374. if (custom)
  375. {
  376. string blendSetFileName = Path.GetFileNameWithoutExtension(blendSet);
  377. try
  378. {
  379. XDocument faceDocument = XDocument.Load(blendSet, LoadOptions.SetLineInfo);
  380. XElement faceDataElement = faceDocument.Element("FaceData");
  381. if (faceDataElement?.IsEmpty ?? true)
  382. {
  383. Utility.LogWarning($"{blendSetFileName}: Could not apply face preset because it is invalid.");
  384. return;
  385. }
  386. HashSet<string> hashKeys = new HashSet<string>(faceKeys.Concat(faceToggleKeys));
  387. foreach (XElement element in faceDataElement.Elements())
  388. {
  389. System.Xml.IXmlLineInfo info = element;
  390. int line = info.HasLineInfo() ? info.LineNumber : -1;
  391. string key;
  392. if ((key = (string)element.Attribute("name")) == null)
  393. {
  394. Utility.LogWarning($"{blendSetFileName}: Could not read face blend key at line {line}.");
  395. continue;
  396. }
  397. if (!hashKeys.Contains(key))
  398. {
  399. Utility.LogWarning($"{blendSetFileName}: Invalid face blend key '{key}' at line {line}.");
  400. continue;
  401. }
  402. if (float.TryParse(element.Value, out float value))
  403. {
  404. try { SetFaceBlendValue(key, value); }
  405. catch { }
  406. }
  407. else Utility.LogWarning(
  408. $"{blendSetFileName}: Could not parse value '{element.Value}' of '{key}' at line {line}"
  409. );
  410. }
  411. }
  412. catch (System.Xml.XmlException e)
  413. {
  414. Utility.LogWarning($"{blendSetFileName}: Face preset data is malformed because {e.Message}");
  415. return;
  416. }
  417. catch (Exception e) when (e is DirectoryNotFoundException || e is FileNotFoundException)
  418. {
  419. Utility.LogWarning($"{blendSetFileName}: Could not open face preset because {e.Message}");
  420. Constants.InitializeCustomFaceBlends();
  421. return;
  422. }
  423. catch (Exception e)
  424. {
  425. Utility.LogWarning($"{blendSetFileName}: Could not parse face preset because {e.Message}");
  426. return;
  427. }
  428. }
  429. else
  430. {
  431. ApplyBackupBlendSet();
  432. CurrentFaceBlendSet = blendSet;
  433. BackupBlendSetValues();
  434. Maid.FaceAnime(blendSet, 0f);
  435. }
  436. StopBlink();
  437. OnUpdateMeido();
  438. }
  439. public void SetFaceBlendValue(string hash, float value)
  440. {
  441. TMorph morph = Body.Face.morph;
  442. if (hash == "nosefook") Maid.boNoseFook = morph.boNoseFook = value > 0f;
  443. else
  444. {
  445. hash = Utility.GP01FbFaceHash(morph, hash);
  446. try { morph.dicBlendSet[CurrentFaceBlendSet][(int)morph.hash[hash]] = value; }
  447. catch { }
  448. }
  449. }
  450. public float GetFaceBlendValue(string hash)
  451. {
  452. TMorph morph = Body.Face.morph;
  453. if (hash == "nosefook") return (Maid.boNoseFook || morph.boNoseFook) ? 1f : 0f;
  454. hash = Utility.GP01FbFaceHash(morph, hash);
  455. return morph.dicBlendSet[CurrentFaceBlendSet][(int)morph.hash[hash]];
  456. }
  457. public void StopBlink()
  458. {
  459. Maid.MabatakiUpdateStop = true;
  460. Body.Face.morph.EyeMabataki = 0f;
  461. Utility.SetFieldValue(Maid, "MabatakiVal", 0f);
  462. }
  463. public void SetMaskMode(MaskMode maskMode)
  464. {
  465. bool invisibleBody = !Body.GetMask(SlotID.body);
  466. Body.SetMaskMode(maskMode);
  467. if (invisibleBody) SetBodyMask(false);
  468. }
  469. public void SetBodyMask(bool enabled)
  470. {
  471. Hashtable table = Utility.GetFieldValue<TBody, Hashtable>(Body, "m_hFoceHide");
  472. foreach (SlotID bodySlot in MaidDressingPane.bodySlots)
  473. {
  474. table[bodySlot] = enabled;
  475. }
  476. if (Body.goSlot[19].m_strModelFileName.Contains("melala_body"))
  477. {
  478. table[SlotID.accHana] = enabled;
  479. }
  480. Body.FixMaskFlag();
  481. Body.FixVisibleFlag(false);
  482. }
  483. public void SetCurling(Curl curling, bool enabled)
  484. {
  485. string[] name = curling == Curl.shift
  486. ? new[] { "panz", "mizugi" }
  487. : new[] { "skirt", "onepiece" };
  488. if (enabled)
  489. {
  490. string action = curling == Curl.shift
  491. ? "パンツずらし" : curling == Curl.front
  492. ? "めくれスカート" : "めくれスカート後ろ";
  493. Maid.ItemChangeTemp(name[0], action);
  494. Maid.ItemChangeTemp(name[1], action);
  495. }
  496. else
  497. {
  498. Maid.ResetProp(name[0]);
  499. Maid.ResetProp(name[1]);
  500. }
  501. Maid.AllProcProp();
  502. HairGravityControl.Control.OnChangeMekure();
  503. SkirtGravityControl.Control.OnChangeMekure();
  504. }
  505. public void SetMpnProp(MpnAttachProp prop, bool detach)
  506. {
  507. if (detach) Maid.ResetProp(prop.Tag, false);
  508. else Maid.SetProp(prop.Tag, prop.MenuFile, 0, true);
  509. Maid.AllProcProp();
  510. }
  511. public void DetachAllMpnAttach()
  512. {
  513. Maid.ResetProp(MPN.kousoku_lower, false);
  514. Maid.ResetProp(MPN.kousoku_upper, false);
  515. Maid.AllProcProp();
  516. }
  517. public void ApplyGravity(Vector3 position, bool skirt = false)
  518. {
  519. DragPointGravity dragPoint = skirt ? SkirtGravityControl : HairGravityControl;
  520. if (dragPoint.Valid) dragPoint.Control.transform.localPosition = position;
  521. }
  522. private void BackupBlendSetValues()
  523. {
  524. float[] values = Body.Face.morph.dicBlendSet[CurrentFaceBlendSet];
  525. BlendSetValueBackup = new float[values.Length];
  526. values.CopyTo(BlendSetValueBackup, 0);
  527. }
  528. private void ApplyBackupBlendSet()
  529. {
  530. BlendSetValueBackup.CopyTo(Body.Face.morph.dicBlendSet[CurrentFaceBlendSet], 0);
  531. Maid.boNoseFook = false;
  532. }
  533. private CacheBoneDataArray GetCacheBoneData()
  534. {
  535. CacheBoneDataArray cache = Maid.gameObject.GetComponent<CacheBoneDataArray>();
  536. if (cache == null)
  537. {
  538. cache = Maid.gameObject.AddComponent<CacheBoneDataArray>();
  539. cache.CreateCache(Body.GetBone("Bip01"));
  540. }
  541. return cache;
  542. }
  543. private void InitializeGravityControls()
  544. {
  545. HairGravityControl = MakeGravityControl(skirt: false);
  546. SkirtGravityControl = MakeGravityControl(skirt: true);
  547. }
  548. private DragPointGravity MakeGravityControl(bool skirt = false)
  549. {
  550. DragPointGravity gravityDragpoint = DragPoint.Make<DragPointGravity>(
  551. PrimitiveType.Cube, Vector3.one * 0.12f
  552. );
  553. GravityTransformControl control = DragPointGravity.MakeGravityControl(Maid, skirt);
  554. gravityDragpoint.Initialize(() => control.transform.position, () => Vector3.zero);
  555. gravityDragpoint.Set(control.transform);
  556. gravityDragpoint.gameObject.SetActive(false);
  557. return gravityDragpoint;
  558. }
  559. private void OnUpdateMeido(MeidoUpdateEventArgs args = null)
  560. {
  561. UpdateMeido?.Invoke(this, args ?? MeidoUpdateEventArgs.Empty);
  562. }
  563. private void OnGravityEvent(object sender, EventArgs args) => OnGravityChange((DragPointGravity)sender);
  564. private void OnGravityChange(DragPointGravity dragPoint)
  565. {
  566. GravityEventArgs args = new GravityEventArgs(
  567. dragPoint == SkirtGravityControl, dragPoint.MyObject.transform.localPosition
  568. );
  569. GravityMove?.Invoke(this, args);
  570. }
  571. public void Serialize(BinaryWriter binaryWriter)
  572. {
  573. using (MemoryStream memoryStream = new MemoryStream())
  574. using (BinaryWriter tempWriter = new BinaryWriter(memoryStream))
  575. {
  576. // transform
  577. tempWriter.WriteVector3(Maid.transform.position);
  578. tempWriter.WriteQuaternion(Maid.transform.rotation);
  579. tempWriter.WriteVector3(Maid.transform.localScale);
  580. // pose
  581. byte[] poseBuffer = SerializePose(true);
  582. tempWriter.Write(poseBuffer.Length);
  583. tempWriter.Write(poseBuffer);
  584. CachedPose.Serialize(tempWriter);
  585. // eye direction
  586. tempWriter.WriteQuaternion(Body.quaDefEyeL * Quaternion.Inverse(DefaultEyeRotL));
  587. tempWriter.WriteQuaternion(Body.quaDefEyeR * Quaternion.Inverse(DefaultEyeRotR));
  588. // free look
  589. tempWriter.Write(FreeLook);
  590. if (FreeLook)
  591. {
  592. tempWriter.WriteVector3(Body.offsetLookTarget);
  593. tempWriter.WriteVector3(Utility.GetFieldValue<TBody, Vector3>(Body, "HeadEulerAngle"));
  594. }
  595. // Head/eye to camera
  596. tempWriter.Write(HeadToCam);
  597. tempWriter.Write(EyeToCam);
  598. // face
  599. SerializeFace(tempWriter);
  600. // body visible
  601. tempWriter.Write(Body.GetMask(SlotID.body));
  602. // clothing
  603. foreach (SlotID clothingSlot in MaidDressingPane.clothingSlots)
  604. {
  605. bool value = true;
  606. if (clothingSlot == SlotID.wear)
  607. {
  608. if (MaidDressingPane.wearSlots.Any(slot => Body.GetSlotLoaded(slot)))
  609. {
  610. value = MaidDressingPane.wearSlots.Any(slot => Body.GetMask(slot));
  611. }
  612. }
  613. else if (clothingSlot == SlotID.megane)
  614. {
  615. SlotID[] slots = new[] { SlotID.megane, SlotID.accHead };
  616. if (slots.Any(slot => Body.GetSlotLoaded(slot)))
  617. {
  618. value = slots.Any(slot => Body.GetMask(slot));
  619. }
  620. }
  621. else if (Body.GetSlotLoaded(clothingSlot))
  622. {
  623. value = Body.GetMask(clothingSlot);
  624. }
  625. tempWriter.Write(value);
  626. }
  627. // hair/skirt gravity
  628. tempWriter.Write(HairGravityActive);
  629. if (HairGravityActive) tempWriter.WriteVector3(HairGravityControl.Control.transform.localPosition);
  630. tempWriter.Write(SkirtGravityActive);
  631. if (SkirtGravityActive) tempWriter.WriteVector3(SkirtGravityControl.Control.transform.localPosition);
  632. // zurashi and mekure
  633. tempWriter.Write(CurlingFront);
  634. tempWriter.Write(CurlingBack);
  635. tempWriter.Write(PantsuShift);
  636. bool hasKousokuUpper = Body.GetSlotLoaded(SlotID.kousoku_upper);
  637. tempWriter.Write(hasKousokuUpper);
  638. if (hasKousokuUpper) tempWriter.Write(Maid.GetProp(MPN.kousoku_upper).strTempFileName);
  639. bool hasKousokuLower = Body.GetSlotLoaded(SlotID.kousoku_lower);
  640. tempWriter.Write(hasKousokuLower);
  641. if (hasKousokuLower) tempWriter.Write(Maid.GetProp(MPN.kousoku_lower).strTempFileName);
  642. binaryWriter.Write(memoryStream.Length);
  643. binaryWriter.Write(memoryStream.ToArray());
  644. }
  645. }
  646. private void SerializeFace(BinaryWriter binaryWriter)
  647. {
  648. binaryWriter.Write("MPS_FACE");
  649. foreach (string hash in faceKeys.Concat(faceToggleKeys))
  650. {
  651. try
  652. {
  653. float value = GetFaceBlendValue(hash);
  654. binaryWriter.Write(hash);
  655. binaryWriter.Write(value);
  656. }
  657. catch { }
  658. }
  659. binaryWriter.Write("END_FACE");
  660. }
  661. public void Deserialize(BinaryReader binaryReader) => Deserialize(binaryReader, meidoDataVersion, false);
  662. public void Deserialize(BinaryReader binaryReader, int dataVersion, bool mmScene)
  663. {
  664. Maid.GetAnimation().Stop();
  665. DetachAllMpnAttach();
  666. binaryReader.ReadInt64(); // meido buffer length
  667. // transform
  668. Maid.transform.position = binaryReader.ReadVector3();
  669. Maid.transform.rotation = binaryReader.ReadQuaternion();
  670. Maid.transform.localScale = binaryReader.ReadVector3();
  671. // pose
  672. KeyValuePair<bool, bool> muneSetting = new KeyValuePair<bool, bool>(true, true);
  673. if (mmScene) IKManager.Deserialize(binaryReader);
  674. else
  675. {
  676. int poseBufferLength = binaryReader.ReadInt32();
  677. byte[] poseBuffer = binaryReader.ReadBytes(poseBufferLength);
  678. muneSetting = GetCacheBoneData().SetFrameBinary(poseBuffer);
  679. }
  680. SetMune(!muneSetting.Key, left: true);
  681. SetMune(!muneSetting.Value, left: false);
  682. CachedPose = PoseInfo.Deserialize(binaryReader);
  683. // eye direction
  684. Body.quaDefEyeL = binaryReader.ReadQuaternion() * DefaultEyeRotL;
  685. Body.quaDefEyeR = binaryReader.ReadQuaternion() * DefaultEyeRotR;
  686. // free look
  687. FreeLook = binaryReader.ReadBoolean();
  688. if (FreeLook)
  689. {
  690. Body.offsetLookTarget = binaryReader.ReadVector3();
  691. // Head angle cannot be resolved with just the offsetLookTarget
  692. if (!mmScene)
  693. {
  694. Utility.SetFieldValue(Body, "HeadEulerAngleG", Vector3.zero);
  695. Utility.SetFieldValue(Body, "HeadEulerAngle", binaryReader.ReadVector3());
  696. }
  697. }
  698. // Head/eye to camera
  699. HeadToCam = binaryReader.ReadBoolean();
  700. EyeToCam = binaryReader.ReadBoolean();
  701. // face
  702. DeserializeFace(binaryReader);
  703. // body visible
  704. SetBodyMask(binaryReader.ReadBoolean());
  705. // clothing
  706. foreach (SlotID clothingSlot in MaidDressingPane.clothingSlots)
  707. {
  708. bool value = binaryReader.ReadBoolean();
  709. if (mmScene) continue;
  710. if (clothingSlot == SlotID.wear)
  711. {
  712. Body.SetMask(SlotID.wear, value);
  713. Body.SetMask(SlotID.mizugi, value);
  714. Body.SetMask(SlotID.onepiece, value);
  715. }
  716. else if (clothingSlot == SlotID.megane)
  717. {
  718. Body.SetMask(SlotID.megane, value);
  719. Body.SetMask(SlotID.accHead, value);
  720. }
  721. else if (Body.GetSlotLoaded(clothingSlot))
  722. {
  723. Body.SetMask(clothingSlot, value);
  724. }
  725. }
  726. // hair/skirt gravity
  727. bool hairGravityActive = binaryReader.ReadBoolean();
  728. if (hairGravityActive)
  729. {
  730. HairGravityActive = true;
  731. ApplyGravity(binaryReader.ReadVector3(), skirt: false);
  732. }
  733. bool skirtGravityActive = binaryReader.ReadBoolean();
  734. if (skirtGravityActive)
  735. {
  736. SkirtGravityActive = true;
  737. ApplyGravity(binaryReader.ReadVector3(), skirt: true);
  738. }
  739. // zurashi and mekure
  740. bool curlingFront = binaryReader.ReadBoolean();
  741. bool curlingBack = binaryReader.ReadBoolean();
  742. bool curlingPantsu = binaryReader.ReadBoolean();
  743. if (!mmScene)
  744. {
  745. if (CurlingFront != curlingFront) SetCurling(Curl.front, curlingFront);
  746. if (CurlingBack != curlingBack) SetCurling(Curl.back, curlingBack);
  747. SetCurling(Curl.shift, curlingPantsu);
  748. }
  749. bool hasKousokuUpper = binaryReader.ReadBoolean();
  750. if (hasKousokuUpper)
  751. {
  752. try
  753. {
  754. SetMpnProp(new MpnAttachProp(MPN.kousoku_upper, binaryReader.ReadString()), false);
  755. }
  756. catch { }
  757. }
  758. bool hasKousokuLower = binaryReader.ReadBoolean();
  759. if (hasKousokuLower)
  760. {
  761. try
  762. {
  763. SetMpnProp(new MpnAttachProp(MPN.kousoku_lower, binaryReader.ReadString()), false);
  764. }
  765. catch { }
  766. }
  767. // OnUpdateMeido();
  768. }
  769. private void DeserializeFace(BinaryReader binaryReader)
  770. {
  771. StopBlink();
  772. binaryReader.ReadString(); // read face header
  773. string header;
  774. while ((header = binaryReader.ReadString()) != "END_FACE")
  775. {
  776. SetFaceBlendValue(header, binaryReader.ReadSingle());
  777. }
  778. }
  779. }
  780. public class GravityEventArgs : EventArgs
  781. {
  782. public Vector3 LocalPosition { get; }
  783. public bool IsSkirt { get; }
  784. public GravityEventArgs(bool isSkirt, Vector3 localPosition)
  785. {
  786. LocalPosition = localPosition;
  787. IsSkirt = isSkirt;
  788. }
  789. }
  790. public struct PoseInfo
  791. {
  792. public string PoseGroup { get; }
  793. public string Pose { get; }
  794. public bool CustomPose { get; }
  795. public PoseInfo(string poseGroup, string pose, bool customPose = false)
  796. {
  797. PoseGroup = poseGroup;
  798. Pose = pose;
  799. CustomPose = customPose;
  800. }
  801. public void Serialize(BinaryWriter binaryWriter)
  802. {
  803. binaryWriter.Write(PoseGroup);
  804. binaryWriter.Write(Pose);
  805. binaryWriter.Write(CustomPose);
  806. }
  807. public static PoseInfo Deserialize(BinaryReader binaryReader)
  808. {
  809. return new PoseInfo
  810. (
  811. binaryReader.ReadString(),
  812. binaryReader.ReadString(),
  813. binaryReader.ReadBoolean()
  814. );
  815. }
  816. }
  817. }