-
Notifications
You must be signed in to change notification settings - Fork 9
/
VRMLoader.cs
229 lines (187 loc) · 7.2 KB
/
VRMLoader.cs
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
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.UI;
using VGltf;
using VGltf.Unity;
namespace VGltfExamples.VRMExample
{
public sealed class VRMLoader : MonoBehaviour
{
[SerializeField] InputField filePathInput;
[SerializeField] Button loadButton;
[SerializeField] Button unloadButton;
[SerializeField] InputField outputFilePathInput;
[SerializeField] Button exportButton;
[SerializeField] public RuntimeAnimatorController RuntimeAnimatorController;
sealed class VRMResource : IDisposable
{
public IImporterContext Context;
public GameObject Go;
public void Dispose()
{
if (Go != null)
{
GameObject.Destroy(Go);
}
Context?.Dispose();
}
}
readonly List<VRMResource> _vrmResources = new List<VRMResource>();
void Start()
{
loadButton.onClick.AddListener(UIOnLoadButtonClick);
unloadButton.onClick.AddListener(UIOnUnloadButtonClick);
exportButton.onClick.AddListener(UIOnExportButtonClicked);
}
// Update is called once per frame
void Update()
{
}
void OnDestroy()
{
foreach (var disposable in _vrmResources)
{
disposable.Dispose();
}
}
async UniTask<VRMResource> LoadVRM()
{
var filePath = filePathInput.text;
// Read the glTF container (unity-independent)
var gltfContainer = default(GltfContainer);
using (var sr = Common.StreamReaderFactory.Create(filePath)) // get-path can be called on only main-thread...
{
gltfContainer = await Task.Run(() =>
{
return GltfContainer.FromGlb(sr);
});
}
var res = new VRMResource();
try
{
// Create a GameObject that points to the glTF scene.
// The GameObject of the glTF's child Node will be created under this object.
var go = new GameObject();
res.Go = go;
// For some reason, VRM0 inverts the coordinate system of glTF in the Z axis.
var config = new Importer.Config
{
FlipZAxisInsteadOfXAsix = true,
};
// Create a glTF Importer for Unity.
// The resources will be cached in the internal Context of this Importer.
// Resources can be released by calling Dispose of the Importer (or the internal Context).
var timeSlicer = new Common.TimeSlicer();
using (var gltfImporter = new Importer(gltfContainer, timeSlicer, config))
{
var bridge = new VRM0ImporterBridge();
// VRM has GameObjects packed flat in glTF nodes, and there is no root Go, so it is solved by hook.
gltfImporter.AddHook(new VGltf.Ext.Vrm0.Unity.Hooks.ImporterHook(go, bridge));
// Load the Scene.
res.Context = await gltfImporter.ImportSceneNodes(System.Threading.CancellationToken.None);
}
}
catch (Exception)
{
res.Dispose();
throw;
}
return res;
}
// UI
void UIOnLoadButtonClick()
{
UIOnLoadButtonClickAsync().Forget();
}
async UniTaskVoid UIOnLoadButtonClickAsync()
{
var p0 = Common.MemoryProfile.Now;
DebugLogProfile(p0);
var res = await LoadVRM();
_vrmResources.Insert(0, res);
// Start animations
var anim = res.Go.GetComponentInChildren<Animator>();
anim.runtimeAnimatorController = RuntimeAnimatorController;
var p1 = Common.MemoryProfile.Now;
DebugLogProfile(p1, p0);
}
void UIOnUnloadButtonClick()
{
if (_vrmResources.Count == 0)
{
return;
}
var p0 = Common.MemoryProfile.Now;
DebugLogProfile(p0);
var head = _vrmResources[0];
_vrmResources.RemoveAt(0);
head.Dispose();
var p1 = Common.MemoryProfile.Now;
DebugLogProfile(p1, p0);
}
void UIOnExportButtonClicked()
{
UIOnExportButtonClickedAsync().Forget();
}
async UniTaskVoid UIOnExportButtonClickedAsync()
{
if (_vrmResources.Count == 0)
{
return;
}
var head = _vrmResources[0];
var anim = head.Go.GetComponentInChildren<Animator>();
var animCtrl = anim.runtimeAnimatorController;
anim.runtimeAnimatorController = null; // Make the model to the rest pose
GltfContainer gltfContainer = null;
try
{
// For some reason, VRM0 inverts the coordinate system of glTF in the Z axis.
var config = new Exporter.Config
{
FlipZAxisInsteadOfXAsix = true,
};
using (var gltfExporter = new Exporter(config))
{
var bridge = new VRM0ExporterBridge();
gltfExporter.AddHook(new VGltf.Ext.Vrm0.Unity.Hooks.ExporterHook(bridge));
// In some implementations of VRM, specifying multiple shape keys in the blendshape proxy may not work correctly, so they should be unified.
using (var unifier = new VGltf.Ext.Vrm0.Unity.Filter.BlendshapeUnifier())
{
unifier.Unify(head.Go);
gltfExporter.ExportGameObjectAsScene(unifier.Go);
}
gltfContainer = gltfExporter.IntoGlbContainer();
}
}
finally
{
anim.runtimeAnimatorController = animCtrl;
}
var filePath = outputFilePathInput.text;
await Task.Run(() =>
{
using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
GltfContainer.ToGlb(fs, gltfContainer);
}
Debug.Log("exported");
});
}
void DebugLogProfile(Common.MemoryProfile now, Common.MemoryProfile prev = null)
{
Debug.Log($"----------");
Debug.Log($"(totalReservedMB, totalAllocatedMB, totalUnusedReservedMB)");
Debug.Log($"({now.TotalReservedMB}MB, {now.TotalAllocatedMB}MB, {now.TotalUnusedReservedMB}MB");
if (prev != null)
{
Debug.Log($"delta ({now.TotalReservedMB - prev.TotalReservedMB}MB, {now.TotalAllocatedMB - prev.TotalAllocatedMB}MB, {now.TotalUnusedReservedMB - prev.TotalUnusedReservedMB}MB)");
}
}
}
}