Tanoda
SerializePose.cs
Go to the documentation of this file.
1using System;
2using System.Collections;
3using System.Collections.Generic;
4using System.IO;
5using System.Runtime.Serialization;
6using System.Runtime.Serialization.Formatters.Binary;
7using UnityEngine;
8
9public class SerializePose : MonoBehaviour
10{
11 [Serializable]
12 public struct Pose
13 {
16 }
17 public byte[] PoseToByteArray(GameObject go, bool limitToMixamoRig = true)
18 {
19 var m_objs = go.GetComponentsInChildren<Transform>();
20 var m_positions = new List<SerializableVector3>();
21 var m_rotations = new List<SerializableQuaternion>();
22
23 for (int i = 0; i < m_objs.Length; i++)
24 {
25 if (limitToMixamoRig && i != 0 && !m_objs[i].name.StartsWith("mixamorig")) continue;
26
27 m_positions.Add(m_objs[i].localPosition);
28 m_rotations.Add(m_objs[i].localRotation);
29 }
30 var pose = new Pose() { pos = m_positions.ToArray(), rot = m_rotations.ToArray() };
31
32 byte[] bytes;
33 IFormatter formatter = new BinaryFormatter();
34 using (MemoryStream stream = new MemoryStream())
35 {
36 formatter.Serialize(stream, pose);
37 bytes = stream.ToArray();
38 }
39
40 return bytes;
41 }
42 public byte[] TransformToByteArray(GameObject go, bool local = true)
43 {
44 var t = go.GetComponent<Transform>();
45 var m_position = new SerializableVector3[1];
46 var m_rotation = new SerializableQuaternion[1];
47
48 m_position[0] = (local ? t.localPosition : t.position);
49 m_rotation[0] = (local ? t.localRotation : t.rotation);
50 var pose = new Pose() { pos = m_position, rot = m_rotation };
51
52 byte[] bytes;
53 IFormatter formatter = new BinaryFormatter();
54 using (MemoryStream stream = new MemoryStream())
55 {
56 formatter.Serialize(stream, pose);
57 bytes = stream.ToArray();
58 }
59
60 return bytes;
61 }
62
63 public void ByteArrayToPose(byte[] data, GameObject go, bool limitToMixamoRig = true)
64 {
65 IFormatter formatter = new BinaryFormatter();
66 using (MemoryStream stream = new MemoryStream(data))
67 {
68 var pose = (Pose)formatter.Deserialize(stream);
69 var m_objs = go.GetComponentsInChildren<Transform>();
70 int minLength = Mathf.Min(pose.pos.Length, m_objs.Length);
71 int j = 0;
72 for (int i = 0; i < minLength; i += 0)
73 {
74 if (limitToMixamoRig && i != 0 && !m_objs[i].name.StartsWith("mixamorig"))
75 {
76 i++;
77 continue;
78 }
79
80 m_objs[i].localPosition = pose.pos[j];
81 m_objs[i].localRotation = pose.rot[j];
82 i++;
83 j++;
84 }
85
86 }
87 }
88}
void ByteArrayToPose(byte[] data, GameObject go, bool limitToMixamoRig=true)
byte[] PoseToByteArray(GameObject go, bool limitToMixamoRig=true)
byte[] TransformToByteArray(GameObject go, bool local=true)
Since unity doesn't flag the Vector3 as serializable, we need to create our own version....
Definition: SolveIK.cs:459
SerializableVector3[] pos
SerializableQuaternion[] rot