This repository has been archived by the owner on Jun 25, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
BBModelImporter.cs
370 lines (329 loc) · 14.8 KB
/
BBModelImporter.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
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
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;
using UnityEditor.EditorTools;
using System;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.IO;
public class BBModelImporter : EditorWindow
{
public string file = "";
public Material modelMaterial;
public bool use_anims;
[MenuItem("BlockBench utils/Load .bbmodel asset")]
public static void OnClick()
{
BBModelImporter window = EditorWindow.GetWindow<BBModelImporter>();
window.Show();
}
private void OnGUI()
{
if (GUILayout.Button("Select file"))
{
file = EditorUtility.OpenFilePanelWithFilters("Import BBmodel", "C:/", new string[] { "BlockBench model file", "bbmodel" });
}
EditorGUILayout.LabelField($"Current file path: {file}");
modelMaterial = (Material)EditorGUILayout.ObjectField("Model material", modelMaterial, typeof(Material), true);
use_anims = EditorGUILayout.Toggle("Load included animations", use_anims);
if (file != "" && GUILayout.Button("Generate model"))
{
string json_string = File.ReadAllText(file);
JObject jObject = JObject.Parse(json_string);
BBFile bbFile = jObject.ToObject<BBFile>();
Dictionary<string, GameObject> cubes = new Dictionary<string, GameObject>();
if (Directory.Exists($"Assets/BlockBenchExport/Meshes/{bbFile.name}"))
{
string[] filenames = Directory.GetFiles($"Assets/BlockBenchExport/Meshes/{bbFile.name}");
foreach (var item in filenames)
{
File.Delete(item);
}
}
foreach (Cube cube in bbFile.elements)
{
GameObject cb = GenerateGameObjectByCube(cube, bbFile, modelMaterial);
cubes.Add(cube.uuid, cb);
}
GameObject mgo = new GameObject(bbFile.name);
if (UnityEditor.Selection.activeGameObject != null) mgo.transform.parent = UnityEditor.Selection.activeGameObject.transform;
var bones = IterateOverGroup(mgo, bbFile.outliner, cubes);
if (use_anims)
{
foreach (var item in bbFile.animations)
{
Directory.CreateDirectory($"Assets/BlockBenchExport/Animations/{bbFile.name}");
AssetDatabase.CreateAsset(GenerateClipFromAnim(item, 60, mgo, bones), $"Assets/BlockBenchExport/Animations/{bbFile.name}/{item.name.Replace(".", "-")}.anim");
}
}
}
}
public static Dictionary<string, GameObject> IterateOverGroup(GameObject parent, JArray objects, Dictionary<string, GameObject> cubes, Dictionary<string, GameObject> inputGroupObjs = null)
{
if (inputGroupObjs == null)
{
inputGroupObjs = new Dictionary<string, GameObject>();
}
foreach (var item in objects.Children())
{
if (item.Type == JTokenType.String)
{
cubes[item.ToString()].transform.parent = parent.transform;
}
else
{
JObject jobject = item.ToObject<JObject>();
string name = jobject["name"].ToString();
float[] origin = jobject["origin"].ToObject<float[]>();
float[] rotation;
if (jobject.ContainsKey("rotation")) rotation = jobject["rotation"].ToObject<float[]>();
else rotation = new float[] { 0, 0, 0 };
JArray objs = jobject["children"].ToObject<JArray>();
GameObject groupObject = new GameObject(name);
groupObject.transform.parent = parent.transform;
groupObject.transform.position = new Vector3(origin[0]/16, origin[1]/16, origin[2]/16);
inputGroupObjs.Add(item["uuid"].ToString(), groupObject);
IterateOverGroup(groupObject, objs, cubes, inputGroupObjs);
groupObject.transform.rotation = Quaternion.Euler(rotation[0], rotation[1], rotation[2]);
}
}
return inputGroupObjs;
}
public static AnimationClip GenerateClipFromAnim(Anim input, int framerate, GameObject rootGroup, Dictionary<string, GameObject> groups)
{
AnimationClip clip = new AnimationClip();
clip.name = input.name.Replace(".", " ");
clip.frameRate = framerate;
foreach (var item in input.animators.Keys)
{
BBAnimator animator = input.animators[item];
Dictionary<string, List<Keyframe>> rotationKeyframes = new Dictionary<string, List<Keyframe>>();
rotationKeyframes.Add("x", new List<Keyframe>());
rotationKeyframes.Add("y", new List<Keyframe>());
rotationKeyframes.Add("z", new List<Keyframe>());
Dictionary<string, List<Keyframe>> positionKeyframes = new Dictionary<string, List<Keyframe>>();
positionKeyframes.Add("x", new List<Keyframe>());
positionKeyframes.Add("y", new List<Keyframe>());
positionKeyframes.Add("z", new List<Keyframe>());
foreach (var kf in animator.keyframes)
{
if (kf.channel == "rotation")
{
rotationKeyframes["x"].Add(new Keyframe(kf.time, kf.data_points[0]["x"]));
rotationKeyframes["y"].Add(new Keyframe(kf.time, kf.data_points[0]["y"]));
rotationKeyframes["z"].Add(new Keyframe(kf.time, kf.data_points[0]["z"]));
}
else if (kf.channel == "position")
{
positionKeyframes["x"].Add(new Keyframe(kf.time, groups[item].transform.localPosition.x + (kf.data_points[0]["x"] / 16)));
positionKeyframes["y"].Add(new Keyframe(kf.time, groups[item].transform.localPosition.y + (kf.data_points[0]["y"] / 16)));
positionKeyframes["z"].Add(new Keyframe(kf.time, groups[item].transform.localPosition.z + (kf.data_points[0]["z"] / 16)));
}
}
AnimationCurve rot_x_curve = new AnimationCurve(rotationKeyframes["x"].ToArray());
AnimationCurve rot_y_curve = new AnimationCurve(rotationKeyframes["y"].ToArray());
AnimationCurve rot_z_curve = new AnimationCurve(rotationKeyframes["z"].ToArray());
AnimationCurve pos_x_curve = new AnimationCurve(positionKeyframes["x"].ToArray());
AnimationCurve pos_y_curve = new AnimationCurve(positionKeyframes["y"].ToArray());
AnimationCurve pos_z_curve = new AnimationCurve(positionKeyframes["z"].ToArray());
clip.SetCurve(AnimationUtility.CalculateTransformPath(groups[item].transform, rootGroup.transform), typeof(Transform), "localEulerAnglesRaw.x", rot_x_curve);
clip.SetCurve(AnimationUtility.CalculateTransformPath(groups[item].transform, rootGroup.transform), typeof(Transform), "localEulerAnglesRaw.y", rot_y_curve);
clip.SetCurve(AnimationUtility.CalculateTransformPath(groups[item].transform, rootGroup.transform), typeof(Transform), "localEulerAnglesRaw.z", rot_z_curve);
clip.SetCurve(AnimationUtility.CalculateTransformPath(groups[item].transform, rootGroup.transform), typeof(Transform), "m_LocalPosition.x", pos_x_curve);
clip.SetCurve(AnimationUtility.CalculateTransformPath(groups[item].transform, rootGroup.transform), typeof(Transform), "m_LocalPosition.y", pos_y_curve);
clip.SetCurve(AnimationUtility.CalculateTransformPath(groups[item].transform, rootGroup.transform), typeof(Transform), "m_LocalPosition.z", pos_z_curve);
}
return clip;
}
public static GameObject GenerateGameObjectByCube(Cube inCube, BBFile inBBfile, Material modelMaterial)
{
int uv_widht = inBBfile.resolution.width;
int uv_height = inBBfile.resolution.height;
Mesh cubeMesh = new Mesh();
float[] x_uv_values = { inCube.from[0], inCube.to[0] };
float[] y_uv_values = { inCube.from[1], inCube.to[1] };
float[] z_uv_values = { inCube.from[2], inCube.to[2] };
Vector3 pivot = new Vector3(inCube.from[0] + inCube.to[0], inCube.from[1] + inCube.to[1], inCube.from[2] + inCube.to[2]) / 32;
List<int> tris = new List<int>();
List<Vector3> verts = new List<Vector3>();
List<Vector2> uvs = new List<Vector2>();
int cVert = 0;
for (int i = 0; i < 6; i++)
{
float[] cuvs = new float[4];
switch (i)
{
case 0:
cuvs = inCube.faces.north.uv;
break;
case 1:
cuvs = inCube.faces.south.uv;
break;
case 2:
cuvs = inCube.faces.up.uv;
break;
case 3:
cuvs = inCube.faces.down.uv;
break;
case 4:
cuvs = inCube.faces.east.uv;
break;
case 5:
cuvs = inCube.faces.west.uv;
break;
}
for (int j = 0; j < 6; j++)
{
Vector3 cVec = VoxelData.voxelVerts[VoxelData.voxelTris[i, j]];
verts.Add(
new Vector3(
Mathf.Lerp(inCube.from[0], inCube.to[0], cVec.x)/16,
Mathf.Lerp(inCube.from[1], inCube.to[1], cVec.y)/16,
Mathf.Lerp(inCube.from[2], inCube.to[2], cVec.z)/16
) - pivot
);
tris.Add(cVert);
cVert++;
}
foreach (var item in VoxelData.voxelUvs)
{
uvs.Add(
new Vector2(
Mathf.Lerp(cuvs[0], cuvs[2], item.x) / uv_widht,
Mathf.Lerp(uv_height - cuvs[3], uv_height - cuvs[1], item.y) / uv_height
)
);
}
}
cubeMesh.vertices = verts.ToArray();
cubeMesh.triangles = tris.ToArray();
cubeMesh.uv = uvs.ToArray();
cubeMesh.RecalculateNormals();
cubeMesh.RecalculateBounds();
cubeMesh.RecalculateTangents();
if(!Directory.Exists("Assets/BlockBenchExport")) AssetDatabase.CreateFolder("Assets","BlockBenchExport");
if (!Directory.Exists("Assets/BlockBenchExport/Meshes")) AssetDatabase.CreateFolder("Assets/BlockBenchExport", "Meshes");
if (!Directory.Exists($"Assets/BlockBenchExport/Meshes/{inBBfile.name}")) AssetDatabase.CreateFolder("Assets/BlockBenchExport/Meshes", inBBfile.name);
int cubesCount = Directory.GetFiles($"Assets/BlockBenchExport/Meshes/{inBBfile.name}", "*.asset").Length;
AssetDatabase.CreateAsset(cubeMesh,$"Assets/BlockBenchExport/Meshes/{inBBfile.name}/{cubesCount}.asset");
GameObject go = new GameObject(inCube.name);
MeshRenderer mr = go.AddComponent<MeshRenderer>();
if (modelMaterial != null) mr.material = modelMaterial;
MeshFilter mf = go.AddComponent<MeshFilter>();
go.transform.localPosition = pivot;
mf.mesh = cubeMesh;
return go;
}
[Serializable]
public class BBFile
{
public ResolutionStruct resolution;
public Cube[] elements;
public JArray outliner;
public string name;
public Anim[] animations;
}
public class Anim
{
public float length;
public string name;
public Dictionary<string, BBAnimator> animators;
}
public class BBAnimator
{
public BBKeyframe[] keyframes;
}
public class BBKeyframe
{
public string channel;
public Dictionary<string, float>[] data_points;
public float time;
public string interpolation;
}
[Serializable]
public struct ResolutionStruct
{
public int width;
public int height;
}
[Serializable]
public struct FacesStruct
{
public FaceStruct north;
public FaceStruct east;
public FaceStruct south;
public FaceStruct west;
public FaceStruct up;
public FaceStruct down;
}
[Serializable]
public struct FaceStruct
{
public float[] uv;
}
[Serializable]
public class Cube
{
public string name;
public float[] from;
public float[] to;
public FacesStruct faces;
public string uuid;
}
[Serializable]
public class Group
{
public string name;
public float[] origin;
public string uuid;
public JArray children;
}
public class GroupConverter : JsonConverter<Group>
{
public override Group ReadJson(JsonReader reader, Type objectType, Group existingValue, bool hasExistingValue, JsonSerializer serializer)
{
if (objectType == "".GetType())
{
return null;
}
var token = JToken.Load(reader);
return token.ToObject<Group>(serializer);
}
public override void WriteJson(JsonWriter writer, Group value, JsonSerializer serializer)
{
throw new NotImplementedException();
}
public override bool CanWrite => false;
}
}
// Code was taken from https://github.com/b3agz/Code-A-Game-Like-Minecraft-In-Unity/blob/master/01-the-first-voxel/Assets/Scripts/VoxelData.cs
public static class VoxelData
{
public static readonly Vector3[] voxelVerts = new Vector3[8] {
new Vector3(0.0f, 0.0f, 0.0f),
new Vector3(1.0f, 0.0f, 0.0f),
new Vector3(1.0f, 1.0f, 0.0f),
new Vector3(0.0f, 1.0f, 0.0f),
new Vector3(0.0f, 0.0f, 1.0f),
new Vector3(1.0f, 0.0f, 1.0f),
new Vector3(1.0f, 1.0f, 1.0f),
new Vector3(0.0f, 1.0f, 1.0f),
};
public static readonly int[,] voxelTris = new int[6, 6] {
{0, 3, 1, 1, 3, 2}, // Back Face
{5, 6, 4, 4, 6, 7}, // Front Face
{3, 7, 2, 2, 7, 6}, // Top Face
{1, 5, 0, 0, 5, 4}, // Bottom Face
{4, 7, 0, 0, 7, 3}, // Left Face
{1, 2, 5, 5, 2, 6} // Right Face
};
public static readonly Vector2[] voxelUvs = new Vector2[6] {
new Vector2 (0.0f, 0.0f),
new Vector2 (0.0f, 1.0f),
new Vector2 (1.0f, 0.0f),
new Vector2 (1.0f, 0.0f),
new Vector2 (0.0f, 1.0f),
new Vector2 (1.0f, 1.0f)
};
}