Meido.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596
  1. using System;
  2. using System.IO;
  3. using System.Collections;
  4. using System.Collections.Generic;
  5. using System.Linq;
  6. using System.Xml.Linq;
  7. using UnityEngine;
  8. using static TBody;
  9. namespace COM3D2.MeidoPhotoStudio.Plugin
  10. {
  11. internal class Meido : ISerializable
  12. {
  13. private const int maxMaids = 12;
  14. public static readonly PoseInfo DefaultPose =
  15. new PoseInfo(Constants.PoseGroupList[0], Constants.PoseDict[Constants.PoseGroupList[0]][0]);
  16. public static readonly string defaultFaceBlendSet = "通常";
  17. public static readonly string[] faceKeys = new string[24]
  18. {
  19. "eyeclose", "eyeclose2", "eyeclose3", "eyebig", "eyeclose6", "eyeclose5", "hitomih",
  20. "hitomis", "mayuha", "mayuw", "mayuup", "mayuv", "mayuvhalf", "moutha", "mouths",
  21. "mouthc", "mouthi", "mouthup", "mouthdw", "mouthhe", "mouthuphalf", "tangout",
  22. "tangup", "tangopen"
  23. };
  24. public static readonly string[] faceToggleKeys = new string[12]
  25. {
  26. // blush, shade, nose up, tears, drool, teeth
  27. "hoho2", "shock", "nosefook", "namida", "yodare", "toothoff",
  28. // cry 1, cry 2, cry 3, blush 1, blush 2, blush 3
  29. "tear1", "tear2", "tear3", "hohos", "hoho", "hohol"
  30. };
  31. public enum Curl
  32. {
  33. front, back, shift
  34. }
  35. private bool initialized;
  36. public event EventHandler<MeidoUpdateEventArgs> UpdateMeido;
  37. public int StockNo { get; }
  38. public Maid Maid { get; private set; }
  39. public TBody Body => Maid.body0;
  40. public MeidoDragPointManager IKManager { get; private set; }
  41. public Texture2D Portrait { get; private set; }
  42. public PoseInfo CachedPose { get; private set; } = DefaultPose;
  43. public string FaceBlendSet { get; private set; } = defaultFaceBlendSet;
  44. public int Slot { get; private set; }
  45. public bool Loading { get; private set; }
  46. public string FirstName => Maid.status.firstName;
  47. public string LastName => Maid.status.lastName;
  48. public bool Busy => Maid.IsBusy && Loading;
  49. public bool CurlingFront => Maid.IsItemChange("skirt", "めくれスカート")
  50. || Maid.IsItemChange("onepiece", "めくれスカート");
  51. public bool CurlingBack => Maid.IsItemChange("skirt", "めくれスカート後ろ")
  52. || Maid.IsItemChange("onepiece", "めくれスカート後ろ");
  53. public bool PantsuShift => Maid.IsItemChange("panz", "パンツずらし")
  54. || Maid.IsItemChange("mizugi", "パンツずらし");
  55. private bool freeLook;
  56. public bool FreeLook
  57. {
  58. get => freeLook;
  59. set
  60. {
  61. if (this.freeLook == value) return;
  62. this.freeLook = value;
  63. Body.trsLookTarget = this.freeLook ? null : GameMain.Instance.MainCamera.transform;
  64. OnUpdateMeido();
  65. }
  66. }
  67. public bool Stop
  68. {
  69. get
  70. {
  71. if (!Body.isLoadedBody) return true;
  72. else return !Maid.GetAnimation().isPlaying;
  73. }
  74. set
  75. {
  76. if (!Body.isLoadedBody || value == Stop) return;
  77. else
  78. {
  79. if (value) Maid.GetAnimation().Stop();
  80. else this.SetPose(this.CachedPose.Pose);
  81. OnUpdateMeido();
  82. }
  83. }
  84. }
  85. public bool IK
  86. {
  87. get => IKManager.Active;
  88. set
  89. {
  90. if (value == IKManager.Active) return;
  91. else IKManager.Active = value;
  92. }
  93. }
  94. public bool Bone
  95. {
  96. get => IKManager.IsBone;
  97. set
  98. {
  99. if (value == Bone) return;
  100. else IKManager.IsBone = value;
  101. OnUpdateMeido();
  102. }
  103. }
  104. public float[] BlendValuesBackup { get; private set; }
  105. public float[] BlendValues { get; private set; }
  106. public Quaternion DefaultEyeRotL { get; private set; }
  107. public Quaternion DefaultEyeRotR { get; private set; }
  108. public Meido(int stockMaidIndex)
  109. {
  110. this.StockNo = stockMaidIndex;
  111. this.Maid = GameMain.Instance.CharacterMgr.GetStockMaid(stockMaidIndex);
  112. this.Portrait = Maid.GetThumIcon();
  113. Maid.boAllProcPropBUSY = false;
  114. IKManager = new MeidoDragPointManager(this);
  115. IKManager.SelectMaid += (s, args) => OnUpdateMeido((MeidoUpdateEventArgs)args);
  116. }
  117. public void BeginLoad()
  118. {
  119. FreeLook = false;
  120. Maid.Visible = true;
  121. Body.boHeadToCam = true;
  122. Body.boEyeToCam = true;
  123. Body.SetBoneHitHeightY(-1000f);
  124. }
  125. public void Load(int slot)
  126. {
  127. Slot = slot;
  128. Loading = true;
  129. if (!Body.isLoadedBody)
  130. {
  131. Maid.DutPropAll();
  132. Maid.AllProcPropSeqStart();
  133. }
  134. GameMain.Instance.StartCoroutine(Load());
  135. }
  136. private IEnumerator Load()
  137. {
  138. while (Maid.IsBusy) yield return null;
  139. yield return new WaitForEndOfFrame();
  140. OnBodyLoad();
  141. }
  142. public void Unload()
  143. {
  144. if (Body.isLoadedBody)
  145. {
  146. Body.jbMuneL.enabled = true;
  147. Body.jbMuneR.enabled = true;
  148. }
  149. Body.MuneYureL(1f);
  150. Body.MuneYureR(1f);
  151. Body.SetMaskMode(MaskMode.None);
  152. Body.SetBoneHitHeightY(0f);
  153. Maid.Visible = false;
  154. IKManager.Destroy();
  155. }
  156. public void Deactivate()
  157. {
  158. Unload();
  159. Maid.SetPos(Vector3.zero);
  160. Maid.SetRot(Vector3.zero);
  161. Maid.SetPosOffset(Vector3.zero);
  162. Body.transform.localScale = Vector3.one;
  163. Maid.DelPrefabAll();
  164. Maid.ActiveSlotNo = -1;
  165. }
  166. public void SetPose(PoseInfo poseInfo)
  167. {
  168. CachedPose = poseInfo;
  169. SetPose(poseInfo.Pose);
  170. }
  171. public void SetPose(string pose)
  172. {
  173. if (!Body.isLoadedBody) return;
  174. if (pose.StartsWith(Constants.customPosePath))
  175. {
  176. byte[] poseBuffer = File.ReadAllBytes(pose);
  177. string hash = Path.GetFileName(pose).GetHashCode().ToString();
  178. Body.CrossFade(hash, poseBuffer, loop: true, fade: 0f);
  179. }
  180. else
  181. {
  182. string[] poseComponents = pose.Split(',');
  183. pose = poseComponents[0] + ".anm";
  184. Maid.CrossFade(pose, loop: true, val: 0f);
  185. Maid.GetAnimation().Play();
  186. if (poseComponents.Length > 1)
  187. {
  188. Maid.GetAnimation()[pose].time = float.Parse(poseComponents[1]);
  189. Maid.GetAnimation()[pose].speed = 0f;
  190. }
  191. }
  192. Maid.SetAutoTwistAll(true);
  193. SetMune();
  194. }
  195. public void CopyPose(Meido fromMeido)
  196. {
  197. byte[] poseBinary = fromMeido.SerializePose();
  198. string tag = $"copy_{fromMeido.Maid.status.guid}";
  199. Body.CrossFade(tag, poseBinary, false, true, false, 0f);
  200. Maid.SetAutoTwistAll(true);
  201. Maid.transform.rotation = fromMeido.Maid.transform.rotation;
  202. SetMune();
  203. }
  204. public void SetMune(bool drag = false)
  205. {
  206. bool momiOrPaizuri = CachedPose.Pose.Contains("_momi") || CachedPose.Pose.Contains("paizuri_");
  207. float onL = (drag || momiOrPaizuri) ? 0f : 1f;
  208. Body.MuneYureL(onL);
  209. Body.MuneYureR(onL);
  210. Body.jbMuneL.enabled = !drag;
  211. Body.jbMuneR.enabled = !drag;
  212. }
  213. public void SetHandPreset(string filename, bool right)
  214. {
  215. XDocument handDocument = XDocument.Load(filename);
  216. XElement handElement = handDocument.Element("FingerData");
  217. if (handElement.IsEmpty || handElement.Element("GameVersion").IsEmpty
  218. || handElement.Element("RightData").IsEmpty || handElement.Element("BinaryData").IsEmpty
  219. ) return;
  220. Stop = true;
  221. bool rightData = bool.Parse(handElement.Element("RightData").Value);
  222. string base64Data = handElement.Element("BinaryData").Value;
  223. byte[] handData = Convert.FromBase64String(base64Data);
  224. IKManager.DeserializeHand(handData, right, rightData != right);
  225. }
  226. public byte[] SerializePose(bool frameBinary = false)
  227. {
  228. CacheBoneDataArray cache = GetCacheBoneData();
  229. return frameBinary ? cache.GetFrameBinary(true, true) : cache.GetAnmBinary(true, true);
  230. }
  231. public void SetFaceBlendSet(string blendSet)
  232. {
  233. FaceBlendSet = blendSet;
  234. Maid.boMabataki = false;
  235. TMorph morph = Body.Face.morph;
  236. morph.EyeMabataki = 0f;
  237. morph.MulBlendValues(blendSet, 1f);
  238. morph.FixBlendValues_Face();
  239. OnUpdateMeido();
  240. }
  241. public void SetFaceBlendValue(string hash, float value)
  242. {
  243. TMorph morph = Body.Face.morph;
  244. if (hash == "nosefook")
  245. {
  246. morph.boNoseFook = value > 0f;
  247. Maid.boNoseFook = morph.boNoseFook;
  248. }
  249. else
  250. {
  251. bool gp01FBFace = morph.bodyskin.PartsVersion >= 120;
  252. float[] blendValues = hash.StartsWith("eyeclose") && !(gp01FBFace && (hash == "eyeclose3"))
  253. ? this.BlendValuesBackup
  254. : this.BlendValues;
  255. hash = Utility.GP01FbFaceHash(morph, hash);
  256. try
  257. {
  258. blendValues[(int)morph.hash[hash]] = value;
  259. }
  260. catch { }
  261. }
  262. Maid.boMabataki = false;
  263. morph.EyeMabataki = 0f;
  264. morph.FixBlendValues_Face();
  265. }
  266. public void SetMaskMode(MaskMode maskMode)
  267. {
  268. bool invisibleBody = !Body.GetMask(SlotID.body);
  269. Body.SetMaskMode(maskMode);
  270. if (invisibleBody) SetBodyMask(false);
  271. }
  272. public void SetBodyMask(bool enabled)
  273. {
  274. Hashtable table = Utility.GetFieldValue<TBody, Hashtable>(Body, "m_hFoceHide");
  275. foreach (SlotID bodySlot in MaidDressingPane.bodySlots)
  276. {
  277. table[bodySlot] = enabled;
  278. }
  279. if (Body.goSlot[19].m_strModelFileName.Contains("melala_body"))
  280. {
  281. table[SlotID.accHana] = enabled;
  282. }
  283. Body.FixMaskFlag();
  284. Body.FixVisibleFlag(false);
  285. }
  286. public void SetCurling(Curl curling, bool enabled)
  287. {
  288. string[] name = curling == Curl.shift
  289. ? new[] { "panz", "mizugi" }
  290. : new[] { "skirt", "onepiece" };
  291. if (enabled)
  292. {
  293. string action = curling == Curl.shift
  294. ? "パンツずらし" : curling == Curl.front
  295. ? "めくれスカート" : "めくれスカート後ろ";
  296. Maid.ItemChangeTemp(name[0], action);
  297. Maid.ItemChangeTemp(name[1], action);
  298. }
  299. else
  300. {
  301. Maid.ResetProp(name[0]);
  302. Maid.ResetProp(name[1]);
  303. }
  304. Maid.AllProcProp();
  305. }
  306. private CacheBoneDataArray GetCacheBoneData()
  307. {
  308. CacheBoneDataArray cache = this.Maid.gameObject.GetComponent<CacheBoneDataArray>();
  309. if (cache == null)
  310. {
  311. cache = this.Maid.gameObject.AddComponent<CacheBoneDataArray>();
  312. cache.CreateCache(this.Maid.body0.GetBone("Bip01"));
  313. }
  314. return cache;
  315. }
  316. private void OnBodyLoad()
  317. {
  318. if (!initialized)
  319. {
  320. TMorph faceMorph = Body.Face.morph;
  321. BlendValuesBackup = Utility.GetFieldValue<TMorph, float[]>(faceMorph, "BlendValuesBackup");
  322. BlendValues = Utility.GetFieldValue<TMorph, float[]>(faceMorph, "BlendValues");
  323. DefaultEyeRotL = Body.quaDefEyeL;
  324. DefaultEyeRotR = Body.quaDefEyeR;
  325. initialized = true;
  326. }
  327. IKManager.Initialize();
  328. IK = true;
  329. Stop = false;
  330. Bone = false;
  331. Loading = false;
  332. }
  333. public void OnUpdateMeido(MeidoUpdateEventArgs args = null)
  334. {
  335. this.UpdateMeido?.Invoke(this, args ?? MeidoUpdateEventArgs.Empty);
  336. }
  337. public void Serialize(BinaryWriter binaryWriter)
  338. {
  339. using (MemoryStream memoryStream = new MemoryStream())
  340. using (BinaryWriter tempWriter = new BinaryWriter(memoryStream))
  341. {
  342. // transform
  343. tempWriter.WriteVector3(Maid.transform.position);
  344. tempWriter.WriteQuaternion(Maid.transform.rotation);
  345. tempWriter.WriteVector3(Maid.transform.localScale);
  346. // pose
  347. byte[] poseBuffer = SerializePose(true);
  348. tempWriter.Write(poseBuffer.Length);
  349. tempWriter.Write(poseBuffer);
  350. CachedPose.Serialize(tempWriter);
  351. // eye direction
  352. tempWriter.WriteQuaternion(Body.quaDefEyeL * Quaternion.Inverse(DefaultEyeRotL));
  353. tempWriter.WriteQuaternion(Body.quaDefEyeR * Quaternion.Inverse(DefaultEyeRotR));
  354. // free look
  355. tempWriter.Write(FreeLook);
  356. tempWriter.WriteVector3(Body.offsetLookTarget);
  357. // face
  358. SerializeFace(tempWriter);
  359. // body visible
  360. tempWriter.Write(Body.GetMask(SlotID.body));
  361. // clothing
  362. foreach (SlotID clothingSlot in MaidDressingPane.clothingSlots)
  363. {
  364. bool value = true;
  365. if (clothingSlot == SlotID.wear)
  366. {
  367. if (MaidDressingPane.wearSlots.Any(slot => Body.GetSlotLoaded(slot)))
  368. {
  369. value = MaidDressingPane.wearSlots.Any(slot => Body.GetMask(slot));
  370. }
  371. }
  372. else if (clothingSlot == SlotID.megane)
  373. {
  374. SlotID[] slots = new[] { SlotID.megane, SlotID.accHead };
  375. if (slots.Any(slot => Body.GetSlotLoaded(slot)))
  376. {
  377. value = slots.Any(slot => Body.GetMask(slot));
  378. }
  379. }
  380. else if (Body.GetSlotLoaded(clothingSlot))
  381. {
  382. value = Body.GetMask(clothingSlot);
  383. }
  384. tempWriter.Write(value);
  385. }
  386. // zurashi and mekure
  387. tempWriter.Write(CurlingFront);
  388. tempWriter.Write(CurlingBack);
  389. tempWriter.Write(PantsuShift);
  390. binaryWriter.Write(memoryStream.Length);
  391. binaryWriter.Write(memoryStream.ToArray());
  392. }
  393. }
  394. private void SerializeFace(BinaryWriter binaryWriter)
  395. {
  396. binaryWriter.Write("MPS_FACE");
  397. TMorph morph = Maid.body0.Face.morph;
  398. bool gp01FBFace = morph.bodyskin.PartsVersion >= 120;
  399. foreach (string hash in faceKeys)
  400. {
  401. float[] blendValues = hash.StartsWith("eyeclose") && !(gp01FBFace && (hash == "eyeclose3"))
  402. ? this.BlendValuesBackup
  403. : this.BlendValues;
  404. string faceKey = Utility.GP01FbFaceHash(morph, hash);
  405. try
  406. {
  407. float value = blendValues[(int)morph.hash[faceKey]];
  408. binaryWriter.Write(hash);
  409. binaryWriter.Write(value);
  410. }
  411. catch { }
  412. }
  413. foreach (string hash in faceToggleKeys)
  414. {
  415. bool value = this.BlendValues[(int)morph.hash[hash]] > 0f;
  416. if (hash == "nosefook") value = morph.boNoseFook;
  417. binaryWriter.Write(hash);
  418. binaryWriter.Write(value);
  419. }
  420. binaryWriter.Write("END_FACE");
  421. }
  422. public void Deserialize(BinaryReader binaryReader) => Deserialize(binaryReader, false);
  423. public void Deserialize(BinaryReader binaryReader, bool mmScene)
  424. {
  425. Maid.GetAnimation().Stop();
  426. binaryReader.ReadInt64(); // meido buffer length
  427. // transform
  428. Maid.transform.position = binaryReader.ReadVector3();
  429. Maid.transform.rotation = binaryReader.ReadQuaternion();
  430. Maid.transform.localScale = binaryReader.ReadVector3();
  431. // pose
  432. if (mmScene) IKManager.Deserialize(binaryReader);
  433. else
  434. {
  435. int poseBufferLength = binaryReader.ReadInt32();
  436. byte[] poseBuffer = binaryReader.ReadBytes(poseBufferLength);
  437. GetCacheBoneData().SetFrameBinary(poseBuffer);
  438. }
  439. CachedPose = PoseInfo.Deserialize(binaryReader);
  440. // eye direction
  441. Body.quaDefEyeL = DefaultEyeRotL * binaryReader.ReadQuaternion();
  442. Body.quaDefEyeR = DefaultEyeRotR * binaryReader.ReadQuaternion();
  443. // free look
  444. FreeLook = binaryReader.ReadBoolean();
  445. Vector3 lookTarget = binaryReader.ReadVector3();
  446. if (FreeLook) Body.offsetLookTarget = lookTarget;
  447. // face
  448. DeserializeFace(binaryReader);
  449. // body visible
  450. SetBodyMask(binaryReader.ReadBoolean());
  451. // clothing
  452. foreach (SlotID clothingSlot in MaidDressingPane.clothingSlots)
  453. {
  454. bool value = binaryReader.ReadBoolean();
  455. if (clothingSlot == SlotID.wear)
  456. {
  457. Body.SetMask(SlotID.wear, value);
  458. Body.SetMask(SlotID.mizugi, value);
  459. Body.SetMask(SlotID.onepiece, value);
  460. }
  461. else if (clothingSlot == SlotID.megane)
  462. {
  463. Body.SetMask(SlotID.megane, value);
  464. Body.SetMask(SlotID.accHead, value);
  465. }
  466. else if (Body.GetSlotLoaded(clothingSlot))
  467. {
  468. Body.SetMask(clothingSlot, value);
  469. }
  470. }
  471. // zurashi and mekure
  472. bool curlingFront = binaryReader.ReadBoolean();
  473. bool curlingBack = binaryReader.ReadBoolean();
  474. if (CurlingFront != curlingFront) SetCurling(Curl.front, curlingFront);
  475. if (CurlingBack != curlingBack) SetCurling(Curl.back, curlingBack);
  476. SetCurling(Curl.shift, binaryReader.ReadBoolean());
  477. // OnUpdateMeido();
  478. }
  479. private void DeserializeFace(BinaryReader binaryReader)
  480. {
  481. binaryReader.ReadString(); // read face header
  482. TMorph morph = Maid.body0.Face.morph;
  483. bool gp01FBFace = morph.bodyskin.PartsVersion >= 120;
  484. HashSet<string> faceKeys = new HashSet<string>(Meido.faceKeys);
  485. string header;
  486. while ((header = binaryReader.ReadString()) != "END_FACE")
  487. {
  488. if (faceKeys.Contains(header))
  489. {
  490. float[] blendValues = header.StartsWith("eyeclose") && !(gp01FBFace && (header == "eyeclose3"))
  491. ? this.BlendValuesBackup
  492. : this.BlendValues;
  493. string hash = Utility.GP01FbFaceHash(morph, header);
  494. try
  495. {
  496. float value = binaryReader.ReadSingle();
  497. blendValues[(int)morph.hash[hash]] = value;
  498. }
  499. catch { }
  500. }
  501. else
  502. {
  503. bool value = binaryReader.ReadBoolean();
  504. if (header == "nosefook") this.Maid.boNoseFook = value;
  505. else this.BlendValues[(int)morph.hash[header]] = value ? 1f : 0f;
  506. }
  507. }
  508. Maid.boMabataki = false;
  509. morph.EyeMabataki = 0f;
  510. morph.FixBlendValues_Face();
  511. }
  512. }
  513. public struct PoseInfo
  514. {
  515. public string PoseGroup { get; }
  516. public string Pose { get; }
  517. public bool CustomPose { get; }
  518. public PoseInfo(string poseGroup, string pose, bool customPose = false)
  519. {
  520. this.PoseGroup = poseGroup;
  521. this.Pose = pose;
  522. this.CustomPose = customPose;
  523. }
  524. public void Serialize(BinaryWriter binaryWriter)
  525. {
  526. binaryWriter.Write(PoseGroup);
  527. binaryWriter.Write(Pose);
  528. binaryWriter.Write(CustomPose);
  529. }
  530. public static PoseInfo Deserialize(BinaryReader binaryReader)
  531. {
  532. return new PoseInfo
  533. (
  534. binaryReader.ReadString(),
  535. binaryReader.ReadString(),
  536. binaryReader.ReadBoolean()
  537. );
  538. }
  539. }
  540. }