-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathUnityVMDReader.cs
More file actions
866 lines (734 loc) · 39.9 KB
/
UnityVMDReader.cs
File metadata and controls
866 lines (734 loc) · 39.9 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
using System;
using System.Collections.Generic;
using System.Linq;
using System.IO;
using UnityEngine;
using System.Threading.Tasks;
namespace UnityVMDReader
{
//注意!VMDファイルではShiftJISが用いられているが、UnityでShiftJISを使うには一工夫必要!!
//Unity ShiftJISで検索すること
public class VMDReader
{
//人ボーンのキーフレームのボーンごとの集合
public class BoneKeyFrameGroup
{
readonly Quaternion ZeroQuaternion = new Quaternion(0, 0, 0, 0);
public enum BoneNames
{
全ての親, センター, グルーブ, 左足IK, 左つま先IK, 右足IK, 右つま先IK, 下半身, 上半身, 上半身2,
首, 頭, 左目, 右目, 両目, 左肩, 左腕, 左腕捩れ, 左ひじ, 左手首,
右肩, 右腕, 右腕捩れ, 右ひじ, 右手首, 左足, 左ひざ, 左足首, 左つま先, 右足,
右ひざ, 右足首, 右つま先, 左親指1, 左親指2, 左人指1, 左人指2, 左人指3, 左中指1, 左中指2,
左中指3, 左薬指1, 左薬指2, 左薬指3, 左小指1, 左小指2, 左小指3, 右親指1, 右親指2, 右人指1,
右人指2, 右人指3, 右中指1, 右中指2, 右中指3, 右薬指1, 右薬指2, 右薬指3, 右小指1, 右小指2,
右小指3, None
}
public static List<string> StringBoneNames
{
get
{
if (boneStringNames == null)
{
boneStringNames = Enum.GetNames(typeof(BoneNames)).ToList();
boneStringNames.Remove(BoneNames.None.ToString());
}
return boneStringNames;
}
set { }
}
private static List<string> boneStringNames;
public BoneNames Name { get; private set; }
//全てのBoneKeyFrames
public List<VMD.BoneKeyFrame> BoneKeyFrames = new List<VMD.BoneKeyFrame>();
//Positionデータを保持したBoneKeyFramesのリスト
public List<VMD.BoneKeyFrame> BonePositionKeyFrames = new List<VMD.BoneKeyFrame>();
//Rotationデータを保持したBoneKeyFramesのリスト
public List<VMD.BoneKeyFrame> BoneRotationKeyFrames = new List<VMD.BoneKeyFrame>();
int frameNumberCash = 0;
public VMD.BoneKeyFrame CurrentKeyFrame { get; private set; }
public VMD.BoneKeyFrame.Interpolation Interpolation { get; private set; }
public VMD.BoneKeyFrame NextKeyFrame { get; private set; }
public VMD.BoneKeyFrame LastPositionKeyFrame { get; private set; }
public VMD.BoneKeyFrame LastRotationKeyFrame { get; private set; }
public VMD.BoneKeyFrame NextPositionKeyFrame { get; private set; }
public VMD.BoneKeyFrame NextRotationKeyFrame { get; private set; }
public BoneKeyFrameGroup(BoneNames name)
{
Name = name;
}
public VMD.BoneKeyFrame GetKeyFrame(int frameNumber)
{
if (frameNumber == frameNumberCash + 1)
{
frameNumberCash = frameNumber;
return GetKeyFrameUsingCash(frameNumber);
}
frameNumberCash = frameNumber;
return GetKeyFrameWithoutCash(frameNumber);
}
private VMD.BoneKeyFrame GetKeyFrameUsingCash(int frameNumber)
{
CurrentKeyFrame = BoneKeyFrames.Find(x => x.FrameNumber == frameNumber);
if (CurrentKeyFrame == null && (NextPositionKeyFrame != null || NextRotationKeyFrame != null))
{
return null;
}
if (CurrentKeyFrame != null && CurrentKeyFrame.Position != Vector3.zero)
{
LastPositionKeyFrame = CurrentKeyFrame;
NextPositionKeyFrame = BonePositionKeyFrames.Find(x => x.FrameNumber > frameNumber);
}
if (CurrentKeyFrame != null && CurrentKeyFrame.Rotation != ZeroQuaternion)
{
LastRotationKeyFrame = CurrentKeyFrame;
NextRotationKeyFrame = BoneRotationKeyFrames.Find(x => x.FrameNumber > frameNumber);
}
if (NextPositionKeyFrame == null && NextRotationKeyFrame == null)
{
NextKeyFrame = null;
}
else if (NextPositionKeyFrame != null && NextRotationKeyFrame != null)
{
NextKeyFrame = NextRotationKeyFrame.FrameNumber < NextPositionKeyFrame.FrameNumber ? NextRotationKeyFrame : NextPositionKeyFrame;
}
else if (NextPositionKeyFrame == null)
{
NextKeyFrame = NextRotationKeyFrame;
}
else if (NextRotationKeyFrame == null)
{
NextKeyFrame = NextPositionKeyFrame;
}
if (NextKeyFrame != null)
{
Interpolation = NextKeyFrame.BoneInterpolation;
}
else
{
Interpolation = null;
}
return CurrentKeyFrame;
}
private VMD.BoneKeyFrame GetKeyFrameWithoutCash(int frameNumber)
{
CurrentKeyFrame = BoneKeyFrames.Find(x => x.FrameNumber == frameNumber);
LastPositionKeyFrame = BonePositionKeyFrames.FindLast(x => x.FrameNumber <= frameNumber);
LastRotationKeyFrame = BoneRotationKeyFrames.FindLast(x => x.FrameNumber <= frameNumber);
NextPositionKeyFrame = BonePositionKeyFrames.Find(x => x.FrameNumber > frameNumber);
NextRotationKeyFrame = BoneRotationKeyFrames.Find(x => x.FrameNumber > frameNumber);
if (NextPositionKeyFrame == null && NextRotationKeyFrame == null)
{
NextKeyFrame = null;
}
else if (NextPositionKeyFrame != null && NextRotationKeyFrame != null)
{
NextKeyFrame = NextRotationKeyFrame.FrameNumber < NextPositionKeyFrame.FrameNumber ? NextRotationKeyFrame : NextPositionKeyFrame;
}
else if (NextPositionKeyFrame == null)
{
NextKeyFrame = NextRotationKeyFrame;
}
else if (NextRotationKeyFrame == null)
{
NextKeyFrame = NextPositionKeyFrame;
}
if (NextKeyFrame != null)
{
Interpolation = NextKeyFrame.BoneInterpolation;
}
else
{
Interpolation = null;
}
return CurrentKeyFrame;
}
public void AddKeyFrame(VMD.BoneKeyFrame vmdBoneFrame)
{
BoneKeyFrames.Add(vmdBoneFrame);
if (vmdBoneFrame.Position != Vector3.zero) { BonePositionKeyFrames.Add(vmdBoneFrame); }
if (vmdBoneFrame.Rotation != ZeroQuaternion) { BoneRotationKeyFrames.Add(vmdBoneFrame); }
}
public void OrderByFrame()
{
BoneKeyFrames = BoneKeyFrames.OrderBy(x => x.FrameNumber).ToList();
BonePositionKeyFrames = BonePositionKeyFrames.OrderBy(x => x.FrameNumber).ToList();
BoneRotationKeyFrames = BoneRotationKeyFrames.OrderBy(x => x.FrameNumber).ToList();
}
}
public class FaceKeyFrameGroup
{
public string MorphName { get; private set; }
public List<VMD.FaceKeyFrame> FaceKeyFrames { get; private set; } = new List<VMD.FaceKeyFrame>();
int frameNumberCash = 0;
VMD.FaceKeyFrame CurrentMorphKeyFrame = null;
public VMD.FaceKeyFrame LastMorphKeyFrame = null;
public VMD.FaceKeyFrame NextMorphKeyFrame = null;
public FaceKeyFrameGroup(string morphName)
{
MorphName = morphName;
}
public VMD.FaceKeyFrame GetKeyFrame(int frameNumber)
{
if (frameNumber == frameNumberCash + 1)
{
frameNumberCash = frameNumber;
return GetKeyFrameUsingCash(frameNumber);
}
frameNumberCash = frameNumber;
return GetKeyFrameWithoutCash(frameNumber);
}
VMD.FaceKeyFrame GetKeyFrameUsingCash(int frameNumber)
{
if (NextMorphKeyFrame == null)
{
return null;
}
if (frameNumber == NextMorphKeyFrame.FrameNumber)
{
LastMorphKeyFrame = NextMorphKeyFrame;
CurrentMorphKeyFrame = NextMorphKeyFrame;
NextMorphKeyFrame = FaceKeyFrames.Find(x => x.FrameNumber > frameNumber);
return CurrentMorphKeyFrame;
}
CurrentMorphKeyFrame = null;
return CurrentMorphKeyFrame;
}
VMD.FaceKeyFrame GetKeyFrameWithoutCash(int frameNumber)
{
CurrentMorphKeyFrame = FaceKeyFrames.FindLast(x => x.FrameNumber == frameNumber);
LastMorphKeyFrame = FaceKeyFrames.FindLast(x => x.FrameNumber < frameNumber);
NextMorphKeyFrame = FaceKeyFrames.Find(x => x.FrameNumber > frameNumber);
return CurrentMorphKeyFrame;
}
}
public VMD RawVMD { get; private set; }
public int FrameCount { get; private set; } = -1;
//ボーンごとに分けたキーフレームの集合をボーンの番号順にリストに入れる、これはコンストラクタで初期化される
public List<BoneKeyFrameGroup> BoneKeyFrameGroups = new List<BoneKeyFrameGroup>();
//表情ごとに分けたキーフレームの集合を表情の番号順にリストに入れる、これはコンストラクタで初期化される
public Dictionary<string, FaceKeyFrameGroup> FaceKeyFrameGroups = new Dictionary<string, FaceKeyFrameGroup>();
void InitializeBoneKeyFrameGroups()
{
BoneKeyFrameGroups.Clear();
for (int i = 0; i < BoneKeyFrameGroup.StringBoneNames.Count; i++)
{
if ((BoneKeyFrameGroup.BoneNames)i == BoneKeyFrameGroup.BoneNames.None) { continue; }
BoneKeyFrameGroups.Add(new BoneKeyFrameGroup((BoneKeyFrameGroup.BoneNames)i));
}
}
public VMDReader()
{
InitializeBoneKeyFrameGroups();
RawVMD = new VMD();
}
public VMDReader(string filePath)
{
InitializeBoneKeyFrameGroups();
ReadVMD(filePath);
}
public void ReadVMD(string filePath)
{
RawVMD = new VMD(filePath);
//人ボーンのキーフレームをグループごとに分けてBoneKeyFrameGroupsに入れる
foreach (VMD.BoneKeyFrame boneKeyFrame in RawVMD.BoneKeyFrames)
{
if (!BoneKeyFrameGroup.StringBoneNames.Contains(boneKeyFrame.Name)) { continue; }
BoneKeyFrameGroups[BoneKeyFrameGroup.StringBoneNames.IndexOf(boneKeyFrame.Name)].AddKeyFrame(boneKeyFrame);
}
//いちおうフレームごとに並べておく
BoneKeyFrameGroups.ForEach(x => x.OrderByFrame());
//人ボーンのフレームが見当たらなかったらこれ以上しない
if (BoneKeyFrameGroups.All(x => x.BoneKeyFrames.Count == 0)) { return; }
//ついでに最終フレームも求めておく
FrameCount = BoneKeyFrameGroups.Where(x => x.BoneKeyFrames.Count > 0).Max(x => x.BoneKeyFrames.Last().FrameNumber);
//全表情ボーンをフレームごとに並び替えておく
RawVMD.FaceKeyFrames.OrderBy(x => x.FrameNumber);
//表情ボーンのキーフレームをグループごとに分けてFaceKeyFrameGroupsに入れる
foreach (VMD.FaceKeyFrame faceKeyFrame in RawVMD.FaceKeyFrames)
{
string morphName = faceKeyFrame.MorphName;
if (morphName == null) { continue; }
if (!FaceKeyFrameGroups.Keys.Contains(morphName))
{
FaceKeyFrameGroups.Add(morphName, new FaceKeyFrameGroup(faceKeyFrame.MorphName));
}
FaceKeyFrameGroups[morphName].FaceKeyFrames.Add(faceKeyFrame);
}
}
public static async Task<VMDReader> ReadVMDAsync(string filePath)
{
return await Task.Run(() =>
{
VMDReader vmdReader = new VMDReader(filePath);
return vmdReader;
});
}
public BoneKeyFrameGroup GetBoneKeyFrameGroup(BoneKeyFrameGroup.BoneNames boneName)
{
return BoneKeyFrameGroups[(int)boneName];
}
//普通にnullも返ってくる
public VMD.BoneKeyFrame GetBoneKeyFrame(BoneKeyFrameGroup.BoneNames boneName, int frameNumber)
{
return BoneKeyFrameGroups[(int)boneName].GetKeyFrame(frameNumber);
}
public static Vector3 InterporatePosition(VMDReader vmdReader, BoneKeyFrameGroup.BoneNames boneName, int frameNumber)
{
VMDReader.BoneKeyFrameGroup vmdBoneFrameGroup = vmdReader.GetBoneKeyFrameGroup(boneName);
VMD.BoneKeyFrame lastFrame = vmdBoneFrameGroup.LastPositionKeyFrame;
VMD.BoneKeyFrame nextFrame = vmdBoneFrameGroup.NextPositionKeyFrame;
if (lastFrame != null && nextFrame != null)
{
float xInterpolationRate = vmdBoneFrameGroup.Interpolation.GetInterpolationValue(VMD.BoneKeyFrame.Interpolation.BezierCurveNames.X, frameNumber, lastFrame.FrameNumber, nextFrame.FrameNumber);
float yInterpolationRate = vmdBoneFrameGroup.Interpolation.GetInterpolationValue(VMD.BoneKeyFrame.Interpolation.BezierCurveNames.Y, frameNumber, lastFrame.FrameNumber, nextFrame.FrameNumber);
float zInterpolationRate = vmdBoneFrameGroup.Interpolation.GetInterpolationValue(VMD.BoneKeyFrame.Interpolation.BezierCurveNames.Z, frameNumber, lastFrame.FrameNumber, nextFrame.FrameNumber);
float xInterpolation = Mathf.Lerp(lastFrame.Position.x, nextFrame.Position.x, xInterpolationRate);
float yInterpolation = Mathf.Lerp(lastFrame.Position.y, nextFrame.Position.y, yInterpolationRate);
float zInterpolation = Mathf.Lerp(lastFrame.Position.z, nextFrame.Position.z, zInterpolationRate);
return new Vector3(xInterpolation, yInterpolation, zInterpolation);
}
else if (lastFrame == null && nextFrame != null)
{
float xInterpolationRate = vmdBoneFrameGroup.Interpolation.GetInterpolationValue(VMD.BoneKeyFrame.Interpolation.BezierCurveNames.X, frameNumber, 0, nextFrame.FrameNumber);
float yInterpolationRate = vmdBoneFrameGroup.Interpolation.GetInterpolationValue(VMD.BoneKeyFrame.Interpolation.BezierCurveNames.Y, frameNumber, 0, nextFrame.FrameNumber);
float zInterpolationRate = vmdBoneFrameGroup.Interpolation.GetInterpolationValue(VMD.BoneKeyFrame.Interpolation.BezierCurveNames.Z, frameNumber, 0, nextFrame.FrameNumber);
float xInterpolation = Mathf.Lerp(0, nextFrame.Position.x, xInterpolationRate);
float yInterpolation = Mathf.Lerp(0, nextFrame.Position.y, yInterpolationRate);
float zInterpolation = Mathf.Lerp(0, nextFrame.Position.z, zInterpolationRate);
return new Vector3(xInterpolation, yInterpolation, zInterpolation);
}
else if (nextFrame == null && lastFrame != null)
{
return lastFrame.Position;
}
return Vector3.zero;
}
public static Quaternion InterporateRotation(VMDReader vmdReader, BoneKeyFrameGroup.BoneNames boneName, int frameNumber)
{
VMDReader.BoneKeyFrameGroup vmdBoneFrameGroup = vmdReader.GetBoneKeyFrameGroup(boneName);
VMD.BoneKeyFrame lastFrame = vmdBoneFrameGroup.LastRotationKeyFrame;
VMD.BoneKeyFrame nextFrame = vmdBoneFrameGroup.NextRotationKeyFrame;
if (lastFrame != null && nextFrame != null)
{
float rotationInterpolationRate = vmdBoneFrameGroup.Interpolation.GetInterpolationValue(VMD.BoneKeyFrame.Interpolation.BezierCurveNames.Rotation, frameNumber, lastFrame.FrameNumber, nextFrame.FrameNumber);
return Quaternion.identity.PlusRotation(Quaternion.Slerp(lastFrame.Rotation, nextFrame.Rotation, rotationInterpolationRate));
}
else if (lastFrame == null && nextFrame != null)
{
float rotationInterpolationRate = vmdBoneFrameGroup.Interpolation.GetInterpolationValue(VMD.BoneKeyFrame.Interpolation.BezierCurveNames.Rotation, frameNumber, 0, nextFrame.FrameNumber);
return Quaternion.identity.PlusRotation(Quaternion.Slerp(Quaternion.identity, nextFrame.Rotation, rotationInterpolationRate));
}
else if (lastFrame != null && nextFrame == null)
{
return Quaternion.identity.PlusRotation(lastFrame.Rotation);
}
return Quaternion.identity;
}
}
public class VMD
{
//人ボーンのキーフレーム
public class BoneKeyFrame
{
//ボーン名
public string Name { get; private set; } = "";
//フレーム番号
public int FrameNumber { get; private set; }
//ボーンの位置、UnityでいうlocalPosition、ただし縮尺はUnityの空間の約10倍
public Vector3 Position { get; private set; }
//ボーンの回転、UnityでいうlocalRotation
public Quaternion Rotation { get; private set; }
//3次ベジェ曲線での補間
public class Interpolation
{
public class BezierCurvePoint
{
internal byte X = new byte();
internal byte Y = new byte();
}
internal BezierCurvePoint[] X = new BezierCurvePoint[] { new BezierCurvePoint(), new BezierCurvePoint() };
internal BezierCurvePoint[] Y = new BezierCurvePoint[] { new BezierCurvePoint(), new BezierCurvePoint() };
internal BezierCurvePoint[] Z = new BezierCurvePoint[] { new BezierCurvePoint(), new BezierCurvePoint() };
internal BezierCurvePoint[] Rotation = new BezierCurvePoint[] { new BezierCurvePoint(), new BezierCurvePoint() };
//コンストラクタにてX,Y,Z,Rotationを入れる
List<BezierCurvePoint[]> BezierCurves;
public enum BezierCurveNames { X, Y, Z, Rotation }
public Interpolation()
{
BezierCurves = new List<BezierCurvePoint[]>() { X, Y, Z, Rotation };
}
//P0,P1,P2,P3を通る3次のもので、
//P0 = (0,0)と P3 = (1,1)かつ、0 < x < 1で単調増加となるようなベジェ曲線が用いられている。
//P1とP2がVMDファイルから得られるので理論上曲線が求まるが、下では媒介変数表示と2分法を用いて値を近似している。
//edvakfさんのコードを参考にしました。
public float GetInterpolationValue(BezierCurveNames bazierCurveName, int currentFrame, int beginFrame, int endFrame)
{
BezierCurvePoint[] bezierCurve = BezierCurves[(int)bazierCurveName];
float x = (float)(currentFrame - beginFrame) / (float)(endFrame - beginFrame);
float t = 0.5f;
float s = 0.5f;
for (int i = 0; i < 15; i++)
{
//実は保存されているときには127*127である。それを比に落とし込む。
float zero = (3 * s * s * t * bezierCurve[0].X / 127) + (3 * s * t * t * bezierCurve[1].X / 127) + (t * t * t) - x;
if (Mathf.Abs(zero) < 0.00001f) { break; }
if (zero > 0) { t -= 1 / (4 * Mathf.Pow(2, i)); }
else { t += 1 / (4 * Mathf.Pow(2, i)); }
s = 1 - t;
}
//実は保存されているときには127*127である。それを比に落とし込む。
return (3 * s * s * t * bezierCurve[0].Y / 127) + (3 * s * t * t * bezierCurve[1].Y / 127) + (t * t * t);
}
}
public Interpolation BoneInterpolation = new Interpolation();
public BoneKeyFrame() { }
public BoneKeyFrame(BinaryReader binaryReader) { Read(binaryReader); }
public void Read(BinaryReader binaryReader)
{
byte[] nameBytes = binaryReader.ReadBytes(15);
Name = System.Text.Encoding.GetEncoding("shift_jis").GetString(nameBytes);
//ヌル文字除去
Name = Name.TrimEnd('\0').TrimEnd('?').TrimEnd('\0');
FrameNumber = binaryReader.ReadInt32();
//座標系の違いにより、x,zをマイナスにすることに注意
Position = Util.ReadVector3(binaryReader);
//座標系の違いにより、x,zをマイナスにすることに注意
Rotation = Util.ReadQuaternion(binaryReader);
//VMDでは3次ベジェ曲線において
//X軸の補間 パラメータP1(X_x1, X_y1),P2(X_x2, X_y2)
//Y軸の補間 パラメータP1(Y_x1, Y_y1),P2(Y_x2, Y_y2)
//Z軸の補間 パラメータP1(Z_x1, Z_y1),P2(Z_x2, Z_y2)
//回転の補間パラメータP1(R_x1, R_y1),P2(R_x2, R_y2)
//としたとき、インデックスでいうと0番目から4,8番目と4の倍数のところに
//X_x1, X_y1, X_x2, X_y2, Y_x1, Y_y1, ...と順番に入っている
//また、X_x1などの値はすべて1byteである
void parseInterpolation(Interpolation.BezierCurvePoint[] x)
{
x[0].X = binaryReader.ReadByte();
binaryReader.ReadBytes(3);
x[0].Y = binaryReader.ReadByte();
binaryReader.ReadBytes(3);
x[1].X = binaryReader.ReadByte();
binaryReader.ReadBytes(3);
x[1].Y = binaryReader.ReadByte();
binaryReader.ReadBytes(3);
}
parseInterpolation(BoneInterpolation.X);
parseInterpolation(BoneInterpolation.Y);
parseInterpolation(BoneInterpolation.Z);
parseInterpolation(BoneInterpolation.Rotation);
}
};
//表情のキーフレーム
public class FaceKeyFrame
{
//表情モーフ名
public string MorphName { get; private set; }
//表情モーフのウェイト
public float Weight { get; private set; }
//フレーム番号
public uint FrameNumber { get; private set; }
public FaceKeyFrame() { }
public FaceKeyFrame(BinaryReader binaryReader) { Read(binaryReader); }
public void Read(BinaryReader binaryReader)
{
byte[] nameBytes = binaryReader.ReadBytes(15);
MorphName = System.Text.Encoding.GetEncoding("shift_jis").GetString(nameBytes);
//ヌル文字除去
MorphName = MorphName.TrimEnd('\0').TrimEnd('?').TrimEnd('\0');
FrameNumber = binaryReader.ReadUInt32();
Weight = binaryReader.ReadSingle();
}
};
//カメラのキーフレーム
public class CameraKeyFrame
{
//フレーム番号
public int Frame { get; private set; }
//目標点とカメラの距離(目標点がカメラ前面でマイナス)
public float Distance { get; private set; }
//目標点の位置
public Vector3 Position { get; private set; }
//カメラの回転
public Quaternion Rotation { get; private set; }
//補間曲線
public Interpolation CameraInterpolation = new Interpolation();
//public byte[][] InterPolation { get; private set; } = new byte[6][];
//視野角
public float Angle;
//おそらくパースペクティブかどうか0or1、0でパースペクティブ
public bool Perspective;
//3次ベジェ曲線での補間
public class Interpolation
{
public class BezierCurvePoint
{
internal byte X = new byte();
internal byte Y = new byte();
}
internal BezierCurvePoint[] X = new BezierCurvePoint[] { new BezierCurvePoint(), new BezierCurvePoint() };
internal BezierCurvePoint[] Y = new BezierCurvePoint[] { new BezierCurvePoint(), new BezierCurvePoint() };
internal BezierCurvePoint[] Z = new BezierCurvePoint[] { new BezierCurvePoint(), new BezierCurvePoint() };
internal BezierCurvePoint[] Rotation = new BezierCurvePoint[] { new BezierCurvePoint(), new BezierCurvePoint() };
internal BezierCurvePoint[] Distance = new BezierCurvePoint[] { new BezierCurvePoint(), new BezierCurvePoint() };
internal BezierCurvePoint[] Angle = new BezierCurvePoint[] { new BezierCurvePoint(), new BezierCurvePoint() };
//コンストラクタにてX,Y,Z,Rotationを入れる
List<BezierCurvePoint[]> BezierCurves;
public enum BezierCurveNames { X, Y, Z, Rotation, Distance, Angle }
public Interpolation()
{
BezierCurves = new List<BezierCurvePoint[]>() { X, Y, Z, Rotation, Distance, Angle };
}
//P0,P1,P2,P3を通る3次のもので、
//P0 = (0,0)と P3 = (1,1)かつ、0 < x < 1で単調増加となるようなベジェ曲線が用いられている。
//P1とP2がVMDファイルから得られるので理論上曲線が求まるが、下では媒介変数表示と2分法を用いて値を近似している。
//edvakfさんのコードを参考にしました。
public float GetInterpolationValue(BezierCurveNames bazierCurveName, int currentFrame, int beginFrame, int endFrame)
{
BezierCurvePoint[] bezierCurve = BezierCurves[(int)bazierCurveName];
float x = (float)(currentFrame - beginFrame) / (float)(endFrame - beginFrame);
float t = 0.5f;
float s = 0.5f;
for (int i = 0; i < 15; i++)
{
//実は保存されているときには127*127である。それを比に落とし込む。
float zero = (3 * s * s * t * bezierCurve[0].X / 127) + (3 * s * t * t * bezierCurve[1].X / 127) + (t * t * t) - x;
if (Mathf.Abs(zero) < 0.00001f) { break; }
if (zero > 0) { t -= 1 / (4 * Mathf.Pow(2, i)); }
else { t += 1 / (4 * Mathf.Pow(2, i)); }
s = 1 - t;
}
//実は保存されているときには127*127である。それを比に落とし込む。
return (3 * s * s * t * bezierCurve[0].Y / 127) + (3 * s * t * t * bezierCurve[1].Y / 127) + (t * t * t);
}
}
public CameraKeyFrame() { }
public CameraKeyFrame(BinaryReader binaryReader) { Read(binaryReader); }
public void Read(BinaryReader binaryReader)
{
Frame = binaryReader.ReadInt32();
//目標点とカメラの距離(目標点がカメラ前面でマイナス)
Distance = binaryReader.ReadInt32();
//座標系、x,zをマイナスにすることに注意
Position = Util.ReadVector3(binaryReader);
//座標系、x,zをマイナスにすることに注意
Rotation = Util.ReadQuaternion(binaryReader);
void parseInterpolation(Interpolation.BezierCurvePoint[] x)
{
x[0].X = binaryReader.ReadByte();
x[0].Y = binaryReader.ReadByte();
x[1].X = binaryReader.ReadByte();
x[1].Y = binaryReader.ReadByte();
}
parseInterpolation(CameraInterpolation.X);
parseInterpolation(CameraInterpolation.Y);
parseInterpolation(CameraInterpolation.Z);
parseInterpolation(CameraInterpolation.Rotation);
parseInterpolation(CameraInterpolation.Distance);
parseInterpolation(CameraInterpolation.Angle);
Angle = binaryReader.ReadSingle();
Perspective = BitConverter.ToBoolean(binaryReader.ReadBytes(3), 0);
}
};
//照明のキーフレーム
public class LightKeyFrame
{
//フレーム番号
public int Frame { get; private set; }
//ライトの色、R,G,Bの順に格納されている、0から1
public float[] LightColor { get; private set; } = new float[3];
//ライトの位置
public Vector3 Position { get; private set; }
public LightKeyFrame() { }
public LightKeyFrame(BinaryReader binaryReader) { Read(binaryReader); }
public void Read(BinaryReader binaryReader)
{
Frame = binaryReader.ReadInt32();
//R,G,Bの順に格納されている、0から1
float[] LightColor = (from n in Enumerable.Range(0, 3) select binaryReader.ReadSingle()).ToArray();
//座標系の違いによりx,zをマイナスとする
Position = Util.ReadVector3(binaryReader);
}
};
//セルフ影のキーフレーム
public class SelfShadowKeyFrame
{
public int Frame { get; private set; }
//セルフシャドウの種類
public byte Type { get; private set; }
//セルフシャドウの距離
public float Distance { get; private set; }
public SelfShadowKeyFrame() { }
public SelfShadowKeyFrame(BinaryReader binaryReader) { Read(binaryReader); }
public void Read(BinaryReader binaryReader)
{
Frame = binaryReader.ReadInt32();
Type = binaryReader.ReadByte();
Distance = binaryReader.ReadSingle();
}
}
//IKのキーフレーム
public class IKKeyFrame
{
//IKの名前とそのIKが有効かどうか
public class VMDIKEnable
{
public string IKName;
public bool Enable;
};
public int Frame { get; private set; }
//
public bool Display { get; private set; }
public List<VMDIKEnable> IKEnable { get; private set; } = new List<VMDIKEnable>();
public IKKeyFrame() { }
public IKKeyFrame(BinaryReader binaryReader) { Read(binaryReader); }
public void Read(BinaryReader binaryReader)
{
byte[] buffer = new byte[20];
Frame = binaryReader.ReadInt32();
Display = BitConverter.ToBoolean(new byte[] { binaryReader.ReadByte() }, 0);
int ikCount = binaryReader.ReadInt32();
for (int i = 0; i < ikCount; i++)
{
binaryReader.Read(buffer, 0, 20);
VMDIKEnable vmdIKEnable = new VMDIKEnable
{
//Shift_JISでヌル文字除去
IKName = System.Text.Encoding.GetEncoding("shift_jis").GetString(buffer).TrimEnd('\0').TrimEnd('?').TrimEnd('\0'),
Enable = BitConverter.ToBoolean(new byte[] { binaryReader.ReadByte() }, 0)
};
IKEnable.Add(vmdIKEnable);
}
}
};
public string MotionName = "None";
public float Version = -1;
//最終フレーム
public int FrameCount = -1;
//人ボーンのキーフレームのリスト
public List<BoneKeyFrame> BoneKeyFrames = new List<BoneKeyFrame>();
//表情モーフのキーフレームのリスト
public List<FaceKeyFrame> FaceKeyFrames = new List<FaceKeyFrame>();
//カメラのキーフレームのリスト
public List<CameraKeyFrame> CameraFrames = new List<CameraKeyFrame>();
//照明のキーフレームのリスト
public List<LightKeyFrame> LightFrames = new List<LightKeyFrame>();
//セルフ影のキーフレームのリスト
public List<SelfShadowKeyFrame> SelfShadowKeyFrames = new List<SelfShadowKeyFrame>();
//IKのキーフレームのリスト
public List<IKKeyFrame> IKFrames = new List<IKKeyFrame>();
public VMD() { }
public VMD(string filePath) { LoadFromFile(filePath); }
public void LoadFromStream(BinaryReader binaryReader)
{
try
{
char[] buffer = new char[30];
//ファイルタイプの読み込み
string RightFileType = "Vocaloid Motion Data";
byte[] fileTypeBytes = binaryReader.ReadBytes(30);
string fileType = System.Text.Encoding.GetEncoding("shift_jis").GetString(fileTypeBytes).Substring(0, RightFileType.Length);
if (!fileType.Equals("Vocaloid Motion Data"))
{
Debug.Log("読み込もうとしたファイルはVMDファイルではありません");
}
//バージョンの読み込み、バージョンは後で使用していない
Version = BitConverter.ToSingle((from c in buffer select Convert.ToByte(c)).ToArray(), 0);
//モーション名の読み込み、Shift_JISで保存されている
byte[] nameBytes = binaryReader.ReadBytes(20);
MotionName = System.Text.Encoding.GetEncoding("shift_jis").GetString(nameBytes);
//ヌル文字除去
MotionName = MotionName.TrimEnd('\0').TrimEnd('?').TrimEnd('\0');
//人ボーンのキーフレームの読み込み
int boneFrameCount = binaryReader.ReadInt32();
for (int i = 0; i < boneFrameCount; i++)
{
BoneKeyFrames.Add(new BoneKeyFrame(binaryReader));
}
//表情モーフのキーフレームの読み込み
int faceFrameCount = binaryReader.ReadInt32();
for (int i = 0; i < faceFrameCount; i++)
{
FaceKeyFrames.Add(new FaceKeyFrame(binaryReader));
}
FaceKeyFrames = FaceKeyFrames.OrderBy(x => x.FrameNumber).ToList();
//カメラのキーフレームの読み込み
int cameraFrameCount = binaryReader.ReadInt32();
for (int i = 0; i < cameraFrameCount; i++)
{
CameraFrames.Add(new CameraKeyFrame(binaryReader));
}
CameraFrames = CameraFrames.OrderBy(x => x.Frame).ToList();
//照明のキーフレームの読み込み
int lightFrameCount = binaryReader.ReadInt32();
for (int i = 0; i < lightFrameCount; i++)
{
LightFrames.Add(new LightKeyFrame(binaryReader));
}
LightFrames = LightFrames.OrderBy(x => x.Frame).ToList();
//vmdのバージョンによってはここで終わる
if (binaryReader.BaseStream.Position == binaryReader.BaseStream.Length) { return; }
//セルフシャドウの読み込み
int selfShadowFrameCount = binaryReader.ReadInt32();
for (int i = 0; i < selfShadowFrameCount; i++)
{
SelfShadowKeyFrames.Add(new SelfShadowKeyFrame(binaryReader));
}
SelfShadowKeyFrames = SelfShadowKeyFrames.OrderBy(x => x.Frame).ToList();
//vmdのバージョンによってはここで終わる
if (binaryReader.BaseStream.Position == binaryReader.BaseStream.Length) { return; }
//IKのキーフレームの読み込み
int ikFrameCount = binaryReader.ReadInt32();
for (int i = 0; i < ikFrameCount; i++)
{
IKFrames.Add(new IKKeyFrame(binaryReader));
}
//ここで終わってないとおかしい
if (binaryReader.BaseStream.Position != binaryReader.BaseStream.Length)
{
Debug.Log("データの最後に不明な部分があります");
}
return;
}
catch
{
Debug.Log("VMD読み込みエラー");
return;
}
}
public void LoadFromFile(string filePath)
{
using (FileStream fileStream = File.OpenRead(filePath))
using (BinaryReader binaryReader = new BinaryReader(fileStream))
{
LoadFromStream(binaryReader);
}
}
};
class Util
{
public static Vector3 ReadVector3(BinaryReader binaryReader)
{
float x = -binaryReader.ReadSingle();
float y = binaryReader.ReadSingle();
float z = -binaryReader.ReadSingle();
return new Vector3(x, y, z);
}
public static Quaternion ReadQuaternion(BinaryReader binaryReader)
{
float x = -binaryReader.ReadSingle();
float y = binaryReader.ReadSingle();
float z = -binaryReader.ReadSingle();
float w = binaryReader.ReadSingle();
return new Quaternion(x, y, z, w);
}
public static Quaternion ReadEulerQuaternion(BinaryReader binaryReader)
{
float x = -binaryReader.ReadSingle();
float y = binaryReader.ReadSingle();
float z = -binaryReader.ReadSingle();
return Quaternion.Euler(x, y, z);
}
}
}