Add gltf export

This commit is contained in:
ousttrue
2020-10-13 18:18:36 +09:00
parent 7c03033e04
commit bed3886b4e
2 changed files with 61 additions and 7 deletions

View File

@@ -500,5 +500,26 @@ namespace UniGLTF
return Glb.ToBytes(json, buffers[0].GetBytes());
}
public (string, List<glTFBuffer>) ToGltf(string gltfPath)
{
var f = new JsonFormatter();
// fix buffer path
if (buffers.Count == 1)
{
var withoutExt = Path.GetFileNameWithoutExtension(gltfPath);
buffers[0].uri = $"{withoutExt}.bin";
}
else
{
throw new NotImplementedException();
}
f.GenSerialize(this);
var json = f.ToString().ParseAsJson().ToString(" ");
RemoveUnusedExtensions(json);
return (json, buffers);
}
}
}

View File

@@ -12,26 +12,41 @@ namespace UniGLTF
{
public class gltfExporter : IDisposable
{
const string CONVERT_HUMANOID_KEY = UniGLTFVersion.MENU + "/Export";
const string MENU_EXPORT_GLB_KEY = UniGLTFVersion.MENU + "/Export(glb)";
const string MENU_EXPORT_GLTF_KEY = UniGLTFVersion.MENU + "/Export(gltf)";
#if UNITY_EDITOR
[MenuItem(CONVERT_HUMANOID_KEY, true, 1)]
[MenuItem(MENU_EXPORT_GLTF_KEY, true, 1)]
[MenuItem(MENU_EXPORT_GLB_KEY, true, 1)]
private static bool ExportValidate()
{
return Selection.activeObject != null && Selection.activeObject is GameObject;
}
[MenuItem(CONVERT_HUMANOID_KEY, false, 1)]
private static void ExportFromMenu()
[MenuItem(MENU_EXPORT_GLTF_KEY, false, 1)]
private static void ExportGltfFromMenu()
{
ExportFromMenu(false);
}
[MenuItem(MENU_EXPORT_GLB_KEY, false, 1)]
private static void ExportGlbFromMenu()
{
ExportFromMenu(true);
}
private static void ExportFromMenu(bool isGlb)
{
var go = Selection.activeObject as GameObject;
var ext = isGlb ? "glb" : "gltf";
if (go.transform.position == Vector3.zero &&
go.transform.rotation == Quaternion.identity &&
go.transform.localScale == Vector3.one)
{
var path = EditorUtility.SaveFilePanel(
"Save glb", "", go.name + ".glb", "glb");
$"Save {ext}", "", go.name + $".{ext}", $"{ext}");
if (string.IsNullOrEmpty(path))
{
return;
@@ -43,8 +58,26 @@ namespace UniGLTF
exporter.Prepare(go);
exporter.Export(MeshExportSettings.Default);
}
var bytes = gltf.ToGlbBytes();
File.WriteAllBytes(path, bytes);
if (isGlb)
{
var bytes = gltf.ToGlbBytes();
File.WriteAllBytes(path, bytes);
}
else
{
var (json, buffers) = gltf.ToGltf(path);
// without BOM
var encoding = new System.Text.UTF8Encoding(false);
File.WriteAllText(path, json, encoding);
// write to local folder
var dir = Path.GetDirectoryName(path);
foreach (var b in buffers)
{
var bufferPath = Path.Combine(dir, b.uri);
File.WriteAllBytes(bufferPath, b.GetBytes().ToArray());
}
}
if (path.StartsWithUnityAssetPath())
{