Meido.cs 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592
  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
  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. OnBodyLoad();
  140. }
  141. public void Unload()
  142. {
  143. if (Body.isLoadedBody)
  144. {
  145. Body.jbMuneL.enabled = true;
  146. Body.jbMuneR.enabled = true;
  147. }
  148. Body.MuneYureL(1f);
  149. Body.MuneYureR(1f);
  150. Body.SetMaskMode(MaskMode.None);
  151. Body.SetBoneHitHeightY(0f);
  152. Maid.Visible = false;
  153. IKManager.Destroy();
  154. }
  155. public void Deactivate()
  156. {
  157. Unload();
  158. Maid.SetPos(Vector3.zero);
  159. Maid.SetRot(Vector3.zero);
  160. Maid.SetPosOffset(Vector3.zero);
  161. Body.transform.localScale = Vector3.one;
  162. Maid.DelPrefabAll();
  163. Maid.ActiveSlotNo = -1;
  164. }
  165. public void SetPose(PoseInfo poseInfo)
  166. {
  167. CachedPose = poseInfo;
  168. SetPose(poseInfo.Pose);
  169. }
  170. public void SetPose(string pose)
  171. {
  172. if (!Body.isLoadedBody) return;
  173. if (pose.StartsWith(Constants.customPosePath))
  174. {
  175. byte[] poseBuffer = File.ReadAllBytes(pose);
  176. string hash = Path.GetFileName(pose).GetHashCode().ToString();
  177. Body.CrossFade(hash, poseBuffer, loop: true, fade: 0f);
  178. }
  179. else
  180. {
  181. string[] poseComponents = pose.Split(',');
  182. pose = poseComponents[0] + ".anm";
  183. Maid.CrossFade(pose, loop: true, val: 0f);
  184. Maid.GetAnimation().Play();
  185. if (poseComponents.Length > 1)
  186. {
  187. Maid.GetAnimation()[pose].time = float.Parse(poseComponents[1]);
  188. Maid.GetAnimation()[pose].speed = 0f;
  189. }
  190. }
  191. Maid.SetAutoTwistAll(true);
  192. SetMune();
  193. }
  194. public void CopyPose(Meido fromMeido)
  195. {
  196. byte[] poseBinary = fromMeido.SerializePose();
  197. string tag = $"copy_{fromMeido.Maid.status.guid}";
  198. Body.CrossFade(tag, poseBinary, false, true, false, 0f);
  199. Maid.SetAutoTwistAll(true);
  200. Maid.transform.rotation = fromMeido.Maid.transform.rotation;
  201. SetMune();
  202. }
  203. public void SetMune(bool drag = false)
  204. {
  205. bool momiOrPaizuri = CachedPose.Pose.Contains("_momi") || CachedPose.Pose.Contains("paizuri_");
  206. float onL = (drag || momiOrPaizuri) ? 0f : 1f;
  207. Body.MuneYureL(onL);
  208. Body.MuneYureR(onL);
  209. Body.jbMuneL.enabled = !drag;
  210. Body.jbMuneR.enabled = !drag;
  211. }
  212. public void SetHandPreset(string filename, bool right)
  213. {
  214. XDocument handDocument = XDocument.Load(filename);
  215. XElement handElement = handDocument.Element("FingerData");
  216. if (handElement.IsEmpty || handElement.Element("GameVersion").IsEmpty
  217. || handElement.Element("RightData").IsEmpty || handElement.Element("BinaryData").IsEmpty
  218. ) return;
  219. Stop = true;
  220. bool rightData = bool.Parse(handElement.Element("RightData").Value);
  221. string base64Data = handElement.Element("BinaryData").Value;
  222. byte[] handData = Convert.FromBase64String(base64Data);
  223. IKManager.DeserializeHand(handData, right, rightData != right);
  224. }
  225. public byte[] SerializePose(bool frameBinary = false)
  226. {
  227. CacheBoneDataArray cache = GetCacheBoneData();
  228. return frameBinary ? cache.GetFrameBinary(true, true) : cache.GetAnmBinary(true, true);
  229. }
  230. public void SetFaceBlendSet(string blendSet)
  231. {
  232. FaceBlendSet = blendSet;
  233. Maid.boMabataki = false;
  234. TMorph morph = Body.Face.morph;
  235. morph.EyeMabataki = 0f;
  236. morph.MulBlendValues(blendSet, 1f);
  237. morph.FixBlendValues_Face();
  238. OnUpdateMeido();
  239. }
  240. public void SetFaceBlendValue(string hash, float value)
  241. {
  242. TMorph morph = Body.Face.morph;
  243. if (hash == "nosefook")
  244. {
  245. morph.boNoseFook = value > 0f;
  246. Maid.boNoseFook = morph.boNoseFook;
  247. }
  248. else
  249. {
  250. bool gp01FBFace = morph.bodyskin.PartsVersion >= 120;
  251. float[] blendValues = hash.StartsWith("eyeclose") && !(gp01FBFace && (hash == "eyeclose3"))
  252. ? this.BlendValuesBackup
  253. : this.BlendValues;
  254. hash = Utility.GP01FbFaceHash(morph, hash);
  255. try
  256. {
  257. blendValues[(int)morph.hash[hash]] = value;
  258. }
  259. catch { }
  260. }
  261. Maid.boMabataki = false;
  262. morph.EyeMabataki = 0f;
  263. morph.FixBlendValues_Face();
  264. }
  265. public void SetMaskMode(MaskMode maskMode)
  266. {
  267. bool invisibleBody = !Body.GetMask(SlotID.body);
  268. Body.SetMaskMode(maskMode);
  269. if (invisibleBody) SetBodyMask(false);
  270. }
  271. public void SetBodyMask(bool enabled)
  272. {
  273. Hashtable table = Utility.GetFieldValue<TBody, Hashtable>(Body, "m_hFoceHide");
  274. foreach (SlotID bodySlot in MaidDressingPane.bodySlots)
  275. {
  276. table[bodySlot] = enabled;
  277. }
  278. if (Body.goSlot[19].m_strModelFileName.Contains("melala_body"))
  279. {
  280. table[SlotID.accHana] = enabled;
  281. }
  282. Body.FixMaskFlag();
  283. Body.FixVisibleFlag(false);
  284. }
  285. public void SetCurling(Curl curling, bool enabled)
  286. {
  287. string[] name = curling == Curl.shift
  288. ? new[] { "panz", "mizugi" }
  289. : new[] { "skirt", "onepiece" };
  290. if (enabled)
  291. {
  292. string action = curling == Curl.shift
  293. ? "パンツずらし" : curling == Curl.front
  294. ? "めくれスカート" : "めくれスカート後ろ";
  295. Maid.ItemChangeTemp(name[0], action);
  296. Maid.ItemChangeTemp(name[1], action);
  297. }
  298. else
  299. {
  300. Maid.ResetProp(name[0]);
  301. Maid.ResetProp(name[1]);
  302. }
  303. Maid.AllProcProp();
  304. }
  305. private CacheBoneDataArray GetCacheBoneData()
  306. {
  307. CacheBoneDataArray cache = this.Maid.gameObject.GetComponent<CacheBoneDataArray>();
  308. if (cache == null)
  309. {
  310. cache = this.Maid.gameObject.AddComponent<CacheBoneDataArray>();
  311. cache.CreateCache(this.Maid.body0.GetBone("Bip01"));
  312. }
  313. return cache;
  314. }
  315. private void OnBodyLoad()
  316. {
  317. if (!initialized)
  318. {
  319. TMorph faceMorph = Body.Face.morph;
  320. BlendValuesBackup = Utility.GetFieldValue<TMorph, float[]>(faceMorph, "BlendValuesBackup");
  321. BlendValues = Utility.GetFieldValue<TMorph, float[]>(faceMorph, "BlendValues");
  322. DefaultEyeRotL = Body.quaDefEyeL;
  323. DefaultEyeRotR = Body.quaDefEyeR;
  324. initialized = true;
  325. }
  326. IKManager.Initialize();
  327. IK = true;
  328. Stop = false;
  329. Bone = false;
  330. Loading = false;
  331. }
  332. public void OnUpdateMeido(MeidoUpdateEventArgs args = null)
  333. {
  334. this.UpdateMeido?.Invoke(this, args ?? MeidoUpdateEventArgs.Empty);
  335. }
  336. public void Serialize(BinaryWriter binaryWriter)
  337. {
  338. using (MemoryStream memoryStream = new MemoryStream())
  339. using (BinaryWriter tempWriter = new BinaryWriter(memoryStream))
  340. {
  341. // transform
  342. tempWriter.WriteVector3(Maid.transform.position);
  343. tempWriter.WriteQuaternion(Maid.transform.rotation);
  344. tempWriter.WriteVector3(Maid.transform.localScale);
  345. // pose
  346. byte[] poseBuffer = SerializePose(true);
  347. tempWriter.Write(poseBuffer.Length);
  348. tempWriter.Write(poseBuffer);
  349. CachedPose.Serialize(tempWriter);
  350. // eye direction
  351. tempWriter.WriteQuaternion(Body.quaDefEyeL * Quaternion.Inverse(DefaultEyeRotL));
  352. tempWriter.WriteQuaternion(Body.quaDefEyeR * Quaternion.Inverse(DefaultEyeRotR));
  353. // free look
  354. tempWriter.Write(FreeLook);
  355. tempWriter.WriteVector3(Body.offsetLookTarget);
  356. // face
  357. SerializeFace(tempWriter);
  358. // body visible
  359. tempWriter.Write(Body.GetMask(SlotID.body));
  360. // clothing
  361. foreach (SlotID clothingSlot in MaidDressingPane.clothingSlots)
  362. {
  363. bool value = true;
  364. if (clothingSlot == SlotID.wear)
  365. {
  366. if (MaidDressingPane.wearSlots.Any(slot => Body.GetSlotLoaded(slot)))
  367. {
  368. value = MaidDressingPane.wearSlots.Any(slot => Body.GetMask(slot));
  369. }
  370. }
  371. else if (clothingSlot == SlotID.megane)
  372. {
  373. SlotID[] slots = new[] { SlotID.megane, SlotID.accHead };
  374. if (slots.Any(slot => Body.GetSlotLoaded(slot)))
  375. {
  376. value = slots.Any(slot => Body.GetMask(slot));
  377. }
  378. }
  379. else if (Body.GetSlotLoaded(clothingSlot))
  380. {
  381. value = Body.GetMask(clothingSlot);
  382. }
  383. tempWriter.Write(value);
  384. }
  385. // zurashi and mekure
  386. tempWriter.Write(CurlingFront);
  387. tempWriter.Write(CurlingBack);
  388. tempWriter.Write(PantsuShift);
  389. binaryWriter.Write(memoryStream.Length);
  390. binaryWriter.Write(memoryStream.ToArray());
  391. }
  392. }
  393. private void SerializeFace(BinaryWriter binaryWriter)
  394. {
  395. binaryWriter.Write("MPS_FACE");
  396. TMorph morph = Maid.body0.Face.morph;
  397. bool gp01FBFace = morph.bodyskin.PartsVersion >= 120;
  398. foreach (string hash in faceKeys)
  399. {
  400. float[] blendValues = hash.StartsWith("eyeclose") && !(gp01FBFace && (hash == "eyeclose3"))
  401. ? this.BlendValuesBackup
  402. : this.BlendValues;
  403. string faceKey = Utility.GP01FbFaceHash(morph, hash);
  404. try
  405. {
  406. float value = blendValues[(int)morph.hash[hash]];
  407. binaryWriter.Write(hash);
  408. binaryWriter.Write(value);
  409. }
  410. catch { }
  411. }
  412. foreach (string hash in faceToggleKeys)
  413. {
  414. bool value = this.BlendValues[(int)morph.hash[hash]] > 0f;
  415. if (hash == "nosefook") value = morph.boNoseFook;
  416. binaryWriter.Write(hash);
  417. binaryWriter.Write(value);
  418. }
  419. binaryWriter.Write("END_FACE");
  420. }
  421. public void Deserialize(BinaryReader binaryReader, bool mmScene = false)
  422. {
  423. Maid.GetAnimation().Stop();
  424. binaryReader.ReadInt64(); // meido buffer length
  425. // transform
  426. Maid.transform.position = binaryReader.ReadVector3();
  427. Maid.transform.rotation = binaryReader.ReadQuaternion();
  428. Maid.transform.localScale = binaryReader.ReadVector3();
  429. // pose
  430. if (mmScene) IKManager.Deserialize(binaryReader);
  431. else
  432. {
  433. int poseBufferLength = binaryReader.ReadInt32();
  434. byte[] poseBuffer = binaryReader.ReadBytes(poseBufferLength);
  435. GetCacheBoneData().SetFrameBinary(poseBuffer);
  436. }
  437. CachedPose = PoseInfo.Deserialize(binaryReader);
  438. // eye direction
  439. Body.quaDefEyeL = DefaultEyeRotL * binaryReader.ReadQuaternion();
  440. Body.quaDefEyeR = DefaultEyeRotR * binaryReader.ReadQuaternion();
  441. // free look
  442. FreeLook = binaryReader.ReadBoolean();
  443. Vector3 lookTarget = binaryReader.ReadVector3();
  444. if (FreeLook) Body.offsetLookTarget = lookTarget;
  445. // face
  446. DeserializeFace(binaryReader);
  447. // body visible
  448. SetBodyMask(binaryReader.ReadBoolean());
  449. // clothing
  450. foreach (SlotID clothingSlot in MaidDressingPane.clothingSlots)
  451. {
  452. bool value = binaryReader.ReadBoolean();
  453. if (clothingSlot == SlotID.wear)
  454. {
  455. Body.SetMask(SlotID.wear, value);
  456. Body.SetMask(SlotID.mizugi, value);
  457. Body.SetMask(SlotID.onepiece, value);
  458. }
  459. else if (clothingSlot == SlotID.megane)
  460. {
  461. Body.SetMask(SlotID.megane, value);
  462. Body.SetMask(SlotID.accHead, value);
  463. }
  464. else if (Body.GetSlotLoaded(clothingSlot))
  465. {
  466. Body.SetMask(clothingSlot, value);
  467. }
  468. }
  469. // zurashi and mekure
  470. bool curlingFront = binaryReader.ReadBoolean();
  471. bool curlingBack = binaryReader.ReadBoolean();
  472. if (CurlingFront != curlingFront) SetCurling(Curl.front, curlingFront);
  473. if (CurlingBack != curlingBack) SetCurling(Curl.back, curlingBack);
  474. SetCurling(Curl.shift, binaryReader.ReadBoolean());
  475. // OnUpdateMeido();
  476. }
  477. private void DeserializeFace(BinaryReader binaryReader)
  478. {
  479. binaryReader.ReadString(); // read face header
  480. TMorph morph = Maid.body0.Face.morph;
  481. bool gp01FBFace = morph.bodyskin.PartsVersion >= 120;
  482. HashSet<string> faceKeys = new HashSet<string>(Meido.faceKeys);
  483. string header;
  484. while ((header = binaryReader.ReadString()) != "END_FACE")
  485. {
  486. if (faceKeys.Contains(header))
  487. {
  488. float[] blendValues = header.StartsWith("eyeclose") && !(gp01FBFace && (header == "eyeclose3"))
  489. ? this.BlendValuesBackup
  490. : this.BlendValues;
  491. string hash = Utility.GP01FbFaceHash(morph, header);
  492. try
  493. {
  494. float value = binaryReader.ReadSingle();
  495. blendValues[(int)morph.hash[hash]] = value;
  496. }
  497. catch { }
  498. }
  499. else
  500. {
  501. bool value = binaryReader.ReadBoolean();
  502. if (header == "nosefook") this.Maid.boNoseFook = value;
  503. else this.BlendValues[(int)morph.hash[header]] = value ? 1f : 0f;
  504. }
  505. }
  506. Maid.boMabataki = false;
  507. morph.EyeMabataki = 0f;
  508. morph.FixBlendValues_Face();
  509. }
  510. }
  511. public struct PoseInfo
  512. {
  513. public string PoseGroup { get; }
  514. public string Pose { get; }
  515. public bool CustomPose { get; }
  516. public PoseInfo(string poseGroup, string pose, bool customPose = false)
  517. {
  518. this.PoseGroup = poseGroup;
  519. this.Pose = pose;
  520. this.CustomPose = customPose;
  521. }
  522. public void Serialize(BinaryWriter binaryWriter)
  523. {
  524. binaryWriter.Write(PoseGroup);
  525. binaryWriter.Write(Pose);
  526. binaryWriter.Write(CustomPose);
  527. }
  528. public static PoseInfo Deserialize(BinaryReader binaryReader)
  529. {
  530. return new PoseInfo
  531. (
  532. binaryReader.ReadString(),
  533. binaryReader.ReadString(),
  534. binaryReader.ReadBoolean()
  535. );
  536. }
  537. }
  538. }