diff --git a/package/com.unity.formats.usd/Editor/Scripts/Behaviors/UsdAssetEditor.cs b/package/com.unity.formats.usd/Editor/Scripts/Behaviors/UsdAssetEditor.cs index cbe64eb53..d951246e3 100644 --- a/package/com.unity.formats.usd/Editor/Scripts/Behaviors/UsdAssetEditor.cs +++ b/package/com.unity.formats.usd/Editor/Scripts/Behaviors/UsdAssetEditor.cs @@ -221,7 +221,10 @@ private void DrawSimpleInspector(UsdAsset usdAsset) EditorGUILayout.BeginHorizontal(); EditorGUILayout.PrefixLabel("USD File"); - usdAsset.usdFullPath = EditorGUILayout.TextField(usdAsset.usdFullPath, EditorStyles.textField); + GUI.enabled = false; + EditorGUILayout.TextField(usdAsset.usdFullPath, EditorStyles.textField); + GUI.enabled = true; + if (GUILayout.Button("...")) { string lastDir; diff --git a/package/com.unity.formats.usd/Editor/Scripts/Behaviors/UsdMenu.cs b/package/com.unity.formats.usd/Editor/Scripts/Behaviors/UsdMenu.cs index b5bc055f4..214705f14 100644 --- a/package/com.unity.formats.usd/Editor/Scripts/Behaviors/UsdMenu.cs +++ b/package/com.unity.formats.usd/Editor/Scripts/Behaviors/UsdMenu.cs @@ -21,50 +21,8 @@ namespace Unity.Formats.USD { - public class UsdMenu : MonoBehaviour + public static class UsdMenu { - public static Scene InitForSave(string defaultName, string fileExtension = "usd,usda,usdc") - { - var filePath = EditorUtility.SaveFilePanel("Export USD File", "", defaultName, fileExtension); - - if (filePath == null || filePath.Length == 0) - { - return null; - } - - var fileDir = Path.GetDirectoryName(filePath); - - if (!Directory.Exists(fileDir)) - { - var di = Directory.CreateDirectory(fileDir); - if (!di.Exists) - { - Debug.LogError("Failed to create directory: " + fileDir); - return null; - } - } - - InitUsd.Initialize(); - var scene = Scene.Create(filePath); - scene.Time = 0; - scene.StartTime = 0; - scene.EndTime = 0; - return scene; - } - - public static Scene InitForOpen() - { - string path = EditorUtility.OpenFilePanel("Import USD File", "", "usd,usda,usdc,abc"); - if (path == null || path.Length == 0) - { - return null; - } - - InitUsd.Initialize(); - var stage = pxr.UsdStage.Open(path, pxr.UsdStage.InitialLoadSet.LoadNone); - return Scene.Open(stage); - } - [MenuItem("USD/Export Selected with Children", true)] static bool EnableMenuExportSelectedWithChildren() { @@ -74,7 +32,10 @@ static bool EnableMenuExportSelectedWithChildren() [MenuItem("USD/Export Selected with Children", priority = 50)] static void MenuExportSelectedWithChildren() { - ExportSelected(BasisTransformation.SlowAndSafe); + var go = Selection.gameObjects.First(); + var filePath = EditorUtility.SaveFilePanel("Export USD File", "", go.name, "usd,usda,usdc"); + var scene = ExportHelpers.InitForSave(filePath); + ExportHelpers.ExportGameObjects(Selection.gameObjects, scene,BasisTransformation.SlowAndSafe); } [MenuItem("USD/Export Transform Overrides", true)] @@ -87,7 +48,8 @@ static bool EnableMenuExportTransforms() static public void MenuExportTransforms() { var root = Selection.activeGameObject.GetComponentInParent(); - var overs = InitForSave(Path.GetFileNameWithoutExtension(root.usdFullPath) + "_overs"); + var filePath = EditorUtility.SaveFilePanel("Export USD File", "", Path.GetFileNameWithoutExtension(root.usdFullPath) + "_overs", "usd,usda,usdc"); + var overs = ExportHelpers.InitForSave(filePath); root.ExportOverrides(overs); } @@ -167,188 +129,42 @@ static void MenuExportLoadFromUsd() { } #endif - static private pxr.SdfPath GetDefaultRoot(Scene scene) - { - // We can't safely assume the default prim is the model root, because Alembic files will - // always have a default prim set arbitrarily. - - // If there is only one root prim, reference this prim. - var children = scene.Stage.GetPseudoRoot().GetChildren().ToList(); - if (children.Count == 1) - { - return children[0].GetPath(); - } - - // Otherwise there are 0 or many root prims, in this case the best option is to reference - // them all, to avoid confusion. - return pxr.SdfPath.AbsoluteRootPath(); - } - - static void ExportSelected(BasisTransformation basisTransform, - string fileExtension = "usd,usda,usdc", - bool exportMonoBehaviours = false) - { - Scene scene = null; - - foreach (GameObject go in Selection.gameObjects) - { - if (scene == null) - { - scene = InitForSave(go.name, fileExtension); - if (scene == null) - { - return; - } - } - - try - { - SceneExporter.Export(go, scene, basisTransform, - exportUnvarying: true, zeroRootTransform: false, - exportMonoBehaviours: exportMonoBehaviours); - } - catch (System.Exception ex) - { - Debug.LogException(ex); - continue; - } - } - - if (scene != null) - { - scene.Save(); - scene.Close(); - } - } [MenuItem("USD/Import as GameObjects", priority = 0)] public static void MenuImportAsGameObjects() { - var scene = InitForOpen(); + var scene = ImportHelpers.InitForOpen(); if (scene == null) { return; } - ImportSceneAsGameObject(scene); + ImportHelpers.ImportSceneAsGameObject(scene, Selection.activeGameObject); scene.Close(); } - public static GameObject ImportSceneAsGameObject(Scene scene, SceneImportOptions importOptions = null) - { - string path = scene.FilePath; - - // Time-varying data is not supported and often scenes are written without "Default" time - // values, which makes setting an arbitrary time safer (because if only default was authored - // the time will be ignored and values will resolve to default time automatically). - scene.Time = 1.0; - - if (importOptions == null) - { - importOptions = new SceneImportOptions(); - importOptions.changeHandedness = BasisTransformation.SlowAndSafe; - importOptions.materialImportMode = MaterialImportMode.ImportDisplayColor; - importOptions.usdRootPath = GetDefaultRoot(scene); - } - - GameObject root = new GameObject(GetObjectName(importOptions.usdRootPath, path)); - - if (Selection.gameObjects.Length > 0) - { - root.transform.SetParent(Selection.gameObjects[0].transform); - } - - try - { - UsdToGameObject(root, scene, importOptions); - return root; - } - catch (SceneImporter.ImportException) - { - GameObject.DestroyImmediate(root); - return null; - } - } - [MenuItem("USD/Import as Prefab", priority = 1)] public static void MenuImportAsPrefab() { - var scene = InitForOpen(); + var scene = ImportHelpers.InitForOpen(); if (scene == null) { return; } - string path = scene.FilePath; - - // Time-varying data is not supported and often scenes are written without "Default" time - // values, which makes setting an arbitrary time safer (because if only default was authored - // the time will be ignored and values will resolve to default time automatically). - scene.Time = 1.0; - - var importOptions = new SceneImportOptions(); - importOptions.projectAssetPath = GetSelectedAssetPath(); - importOptions.changeHandedness = BasisTransformation.SlowAndSafe; - importOptions.materialImportMode = MaterialImportMode.ImportDisplayColor; - importOptions.usdRootPath = GetDefaultRoot(scene); - - var invalidChars = Path.GetInvalidFileNameChars(); - var prefabName = string.Join("_", GetPrefabName(path).Split(invalidChars, - System.StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.'); - string prefabPath = importOptions.projectAssetPath + prefabName + ".prefab"; - prefabPath = AssetDatabase.GenerateUniqueAssetPath(prefabPath); - string clipName = Path.GetFileNameWithoutExtension(path); - - var go = new GameObject(GetObjectName(importOptions.usdRootPath, path)); - try - { - UsdToGameObject(go, scene, importOptions); - SceneImporter.SavePrefab(go, prefabPath, clipName, importOptions); - } - finally - { - GameObject.DestroyImmediate(go); - scene.Close(); - } + ImportHelpers.ImportAsPrefab(scene); } [MenuItem("USD/Import as Timeline Clip", priority = 2)] public static void MenuImportAsTimelineClip() { - var scene = InitForOpen(); + var scene = ImportHelpers.InitForOpen(); if (scene == null) { return; } - string path = scene.FilePath; - - var invalidChars = Path.GetInvalidFileNameChars(); - var prefabName = string.Join("_", GetPrefabName(path).Split(invalidChars, - System.StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.'); - - string prefabPath = GetSelectedAssetPath() + prefabName + ".prefab"; - prefabPath = AssetDatabase.GenerateUniqueAssetPath(prefabPath); - string clipName = Path.GetFileNameWithoutExtension(path); - - var importOptions = new SceneImportOptions(); - importOptions.projectAssetPath = GetSelectedAssetPath(); - importOptions.changeHandedness = BasisTransformation.FastWithNegativeScale; - importOptions.materialImportMode = MaterialImportMode.ImportDisplayColor; - importOptions.usdRootPath = GetDefaultRoot(scene); - - var go = new GameObject(GetObjectName(importOptions.usdRootPath, path)); - - try - { - // Ensure we have at least one GameObject with the import settings. - XformImporter.BuildSceneRoot(scene, go.transform, importOptions); - SceneImporter.SavePrefab(go, prefabPath, clipName, importOptions); - } - finally - { - GameObject.DestroyImmediate(go); - } + ImportHelpers.ImportAsTimelineClip(scene); } [MenuItem("USD/Unload Subtree", true)] @@ -418,69 +234,5 @@ public static void MenuLoadSubtree() return; } } - - /// - /// Returns the selected object path or "Assets/" if no object is selected. - /// - public static string GetSelectedAssetPath() - { - Object[] selectedAsset = Selection.GetFiltered(typeof(Object), SelectionMode.Assets); - foreach (Object obj in selectedAsset) - { - var path = AssetDatabase.GetAssetPath(obj.GetInstanceID()); - if (string.IsNullOrEmpty(path)) - { - continue; - } - - if (File.Exists(path)) - { - path = Path.GetDirectoryName(path); - } - - if (!path.EndsWith("/")) - { - path += "/"; - } - - return path; - } - - return "Assets/"; - } - - public static GameObject UsdToGameObject(GameObject parent, - Scene scene, - SceneImportOptions importOptions) - { - try - { - SceneImporter.ImportUsd(parent, scene, new PrimMap(), importOptions); - } - finally - { - scene.Close(); - } - - return parent; - } - - private static string GetObjectName(pxr.SdfPath rootPrimName, string path) - { - return pxr.UsdCs.TfIsValidIdentifier(rootPrimName.GetName()) - ? rootPrimName.GetName() - : GetObjectName(path); - } - - private static string GetObjectName(string path) - { - return UnityTypeConverter.MakeValidIdentifier(Path.GetFileNameWithoutExtension(path)); - } - - private static string GetPrefabName(string path) - { - var fileName = GetObjectName(path); - return fileName + "_prefab"; - } } } diff --git a/package/com.unity.formats.usd/Runtime/Scripts/IO/Scene/ExportHelpers.cs b/package/com.unity.formats.usd/Runtime/Scripts/IO/Scene/ExportHelpers.cs new file mode 100644 index 000000000..91c79a230 --- /dev/null +++ b/package/com.unity.formats.usd/Runtime/Scripts/IO/Scene/ExportHelpers.cs @@ -0,0 +1,60 @@ +using System.IO; +using UnityEditor; +using UnityEngine; +using USD.NET; + +namespace Unity.Formats.USD +{ + public static class ExportHelpers + { + public static Scene InitForSave(string filePath) + { + if (string.IsNullOrEmpty(filePath)) + { + return null; + } + + var fileDir = Path.GetDirectoryName(filePath); + + if (!Directory.Exists(fileDir)) + { + var di = Directory.CreateDirectory(fileDir); + if (!di.Exists) + { + Debug.LogError("Failed to create directory: " + fileDir); + return null; + } + } + + InitUsd.Initialize(); + var scene = Scene.Create(filePath); + scene.Time = 0; + scene.StartTime = 0; + scene.EndTime = 0; + return scene; + } + + public static void ExportGameObjects(GameObject[] objects, Scene scene, BasisTransformation basisTransform, + bool exportMonoBehaviours = false) + { + if (scene == null) + return; + + foreach (GameObject go in objects) + { + try + { + SceneExporter.Export(go, scene, basisTransform, + exportUnvarying: true, zeroRootTransform: false, + exportMonoBehaviours: exportMonoBehaviours); + } + catch (System.Exception ex) + { + Debug.LogException(ex); + } + } + scene.Save(); + scene.Close(); + } + } +} diff --git a/package/com.unity.formats.usd/Runtime/Scripts/IO/Scene/ExportHelpers.cs.meta b/package/com.unity.formats.usd/Runtime/Scripts/IO/Scene/ExportHelpers.cs.meta new file mode 100644 index 000000000..979c8c1d0 --- /dev/null +++ b/package/com.unity.formats.usd/Runtime/Scripts/IO/Scene/ExportHelpers.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: ff4b0fbbfd3e41f782b9e9f03f813653 +timeCreated: 1613596650 \ No newline at end of file diff --git a/package/com.unity.formats.usd/Runtime/Scripts/IO/Scene/ImportHelpers.cs b/package/com.unity.formats.usd/Runtime/Scripts/IO/Scene/ImportHelpers.cs new file mode 100644 index 000000000..1865b9faf --- /dev/null +++ b/package/com.unity.formats.usd/Runtime/Scripts/IO/Scene/ImportHelpers.cs @@ -0,0 +1,227 @@ +using System; +using System.IO; +using System.Linq; +using pxr; +#if UNITY_EDITOR +using UnityEditor; +#endif +using UnityEngine; +using USD.NET; +using USD.NET.Unity; +using Object = UnityEngine.Object; + +namespace Unity.Formats.USD +{ + public static class ImportHelpers + { + public static GameObject ImportSceneAsGameObject(Scene scene, GameObject parent = null, SceneImportOptions importOptions = null) + { + if (scene == null || scene.Stage == null) + { + Debug.LogError("The USD Scene needs to be opened before being imported."); + return null; + } + + string path = scene.FilePath; + + // Time-varying data is not supported and often scenes are written without "Default" time + // values, which makes setting an arbitrary time safer (because if only default was authored + // the time will be ignored and values will resolve to default time automatically). + scene.Time = 1.0; + + if (importOptions == null) + { + importOptions = new SceneImportOptions(); + importOptions.usdRootPath = GetDefaultRoot(scene); + } + + GameObject root = new GameObject(GetObjectName(importOptions.usdRootPath, path)); + + if (parent != null) + { + root.transform.SetParent(parent.transform); + } + + try + { + UsdToGameObject(root, scene, importOptions); + return root; + } + catch (SceneImporter.ImportException) + { +#if UNITY_EDITOR + Object.DestroyImmediate(root); +#else + Object.Destroy(root); +#endif + return null; + } + } + +#if UNITY_EDITOR + public static string ImportAsPrefab(Scene scene) + { + string path = scene.FilePath; + + // Time-varying data is not supported and often scenes are written without "Default" time + // values, which makes setting an arbitrary time safer (because if only default was authored + // the time will be ignored and values will resolve to default time automatically). + scene.Time = 1.0; + + var importOptions = new SceneImportOptions(); + importOptions.projectAssetPath = GetSelectedAssetPath(); + importOptions.usdRootPath = GetDefaultRoot(scene); + + string prefabPath = GetPrefabPath(path, importOptions.projectAssetPath); + string clipName = Path.GetFileNameWithoutExtension(path); + + var go = new GameObject(GetObjectName(importOptions.usdRootPath, path)); + try + { + UsdToGameObject(go, scene, importOptions); + SceneImporter.SavePrefab(go, prefabPath, clipName, importOptions); + return prefabPath; + } + finally + { + Object.DestroyImmediate(go); + scene.Close(); + } + } + + public static string ImportAsTimelineClip(Scene scene) + { + string path = scene.FilePath; + + var importOptions = new SceneImportOptions(); + importOptions.projectAssetPath = GetSelectedAssetPath(); + importOptions.usdRootPath = GetDefaultRoot(scene); + importOptions.changeHandedness = BasisTransformation.FastWithNegativeScale; + + string prefabPath = GetPrefabPath(path, importOptions.projectAssetPath); + string clipName = Path.GetFileNameWithoutExtension(path); + + var go = new GameObject(GetObjectName(importOptions.usdRootPath, path)); + try + { + // Ensure we have at least one GameObject with the import settings. + XformImporter.BuildSceneRoot(scene, go.transform, importOptions); + SceneImporter.SavePrefab(go, prefabPath, clipName, importOptions); + return prefabPath; + } + finally + { + GameObject.DestroyImmediate(go); + scene.Close(); + } + } + + /// + /// Returns the selected object path or "Assets/" if no object is selected. + /// + static string GetSelectedAssetPath() + { + Object[] selectedAsset = Selection.GetFiltered(typeof(Object), SelectionMode.Assets); + foreach (Object obj in selectedAsset) + { + var path = AssetDatabase.GetAssetPath(obj.GetInstanceID()); + if (string.IsNullOrEmpty(path)) + { + continue; + } + + if (File.Exists(path)) + { + path = Path.GetDirectoryName(path); + } + + if (!path.EndsWith("/")) + { + path += "/"; + } + + return path; + } + + return "Assets/"; + } +#endif + + public static Scene InitForOpen(string path = "", UsdStage.InitialLoadSet loadSet = pxr.UsdStage.InitialLoadSet.LoadNone) + { +#if UNITY_EDITOR + if (String.IsNullOrEmpty(path) && !UnityEngine.Application.isPlaying) + path = EditorUtility.OpenFilePanel("Import USD File", "", "usd,usda,usdc,abc"); +#endif + + if (String.IsNullOrEmpty(path)) + return null; + + InitUsd.Initialize(); + // var editingStage = new EditingStage(path); + var stage = pxr.UsdStage.Open(path, loadSet); + return Scene.Open(stage); + } + + static pxr.SdfPath GetDefaultRoot(Scene scene) + { + // We can't safely assume the default prim is the model root, because Alembic files will + // always have a default prim set arbitrarily. + + // If there is only one root prim, reference this prim. + var children = scene.Stage.GetPseudoRoot().GetChildren().ToList(); + if (children.Count == 1) + { + return children[0].GetPath(); + } + + // Otherwise there are 0 or many root prims, in this case the best option is to reference + // them all, to avoid confusion. + return pxr.SdfPath.AbsoluteRootPath(); + } + + static GameObject UsdToGameObject(GameObject parent, + Scene scene, + SceneImportOptions importOptions) + { + try + { + SceneImporter.ImportUsd(parent, scene, new PrimMap(), importOptions); + } + finally + { + scene.Close(); + } + + return parent; + } + + static string GetObjectName(pxr.SdfPath rootPrimName, string path) + { + return pxr.UsdCs.TfIsValidIdentifier(rootPrimName.GetName()) + ? rootPrimName.GetName() + : GetObjectName(path); + } + + static string GetObjectName(string path) + { + return UnityTypeConverter.MakeValidIdentifier(Path.GetFileNameWithoutExtension(path)); + } + + static string GetPrefabName(string path) + { + var fileName = GetObjectName(path); + return fileName + "_prefab"; + } + + static string GetPrefabPath(string usdPath, string dataPath) + { + var invalidChars = Path.GetInvalidFileNameChars(); + var prefabName = string.Join("_", GetPrefabName(usdPath).Split(invalidChars, + System.StringSplitOptions.RemoveEmptyEntries)).TrimEnd('.'); + string prefabPath = dataPath + prefabName + ".prefab"; + prefabPath = AssetDatabase.GenerateUniqueAssetPath(prefabPath); + return prefabPath; + } + } +} diff --git a/package/com.unity.formats.usd/Runtime/Scripts/IO/Scene/ImportHelpers.cs.meta b/package/com.unity.formats.usd/Runtime/Scripts/IO/Scene/ImportHelpers.cs.meta new file mode 100644 index 000000000..9c6056866 --- /dev/null +++ b/package/com.unity.formats.usd/Runtime/Scripts/IO/Scene/ImportHelpers.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 5e226d4ad64f4497ab11ca8ff7ec3e54 +timeCreated: 1613595700 \ No newline at end of file diff --git a/package/com.unity.formats.usd/Runtime/Scripts/IO/Scene/UsdzExporter.cs b/package/com.unity.formats.usd/Runtime/Scripts/IO/Scene/UsdzExporter.cs index 56c2a6ac9..ce5c337e3 100644 --- a/package/com.unity.formats.usd/Runtime/Scripts/IO/Scene/UsdzExporter.cs +++ b/package/com.unity.formats.usd/Runtime/Scripts/IO/Scene/UsdzExporter.cs @@ -46,7 +46,7 @@ public static void ExportUsdz(string usdzFilePath, Directory.SetCurrentDirectory(tmpDirPath); // Create the tmp .usd scene, into which the data will be exported. - Scene scene = InitForSave(usdcFileName); + Scene scene = ExportHelpers.InitForSave(Path.Combine(tmpDirPath,usdcFileName)); Vector3 localScale = root.transform.localScale; try @@ -91,27 +91,5 @@ public static void ExportUsdz(string usdzFilePath, tmpDir.Delete(recursive: true); } } - - internal static Scene InitForSave(string filePath) - { - string fileDir = Path.GetDirectoryName(filePath); - - if (!string.IsNullOrEmpty(fileDir) && !Directory.Exists(fileDir)) - { - var di = Directory.CreateDirectory(fileDir); - if (!di.Exists) - { - Debug.LogError("Failed to create directory: " + fileDir); - return null; - } - } - - InitUsd.Initialize(); - Scene scene = Scene.Create(filePath); - scene.Time = 0; - scene.StartTime = 0; - scene.EndTime = 0; - return scene; - } } } diff --git a/package/com.unity.formats.usd/Runtime/Scripts/Timeline/UsdRecorderBehaviour.cs b/package/com.unity.formats.usd/Runtime/Scripts/Timeline/UsdRecorderBehaviour.cs index 84a32b107..6ea27aa62 100644 --- a/package/com.unity.formats.usd/Runtime/Scripts/Timeline/UsdRecorderBehaviour.cs +++ b/package/com.unity.formats.usd/Runtime/Scripts/Timeline/UsdRecorderBehaviour.cs @@ -82,7 +82,7 @@ public void BeginRecording(double currentTime, GameObject root) // Set the current working directory to the tmp directory to export with relative paths. Directory.SetCurrentDirectory(tmpDirPath); - Clip.UsdScene = UsdzExporter.InitForSave(usdcFileName); + Clip.UsdScene = ExportHelpers.InitForSave(Path.Combine(tmpDirPath,usdcFileName)); } else { diff --git a/package/com.unity.formats.usd/Tests/Editor/BaseFixture.cs b/package/com.unity.formats.usd/Tests/Editor/BaseFixture.cs new file mode 100644 index 000000000..b38db8099 --- /dev/null +++ b/package/com.unity.formats.usd/Tests/Editor/BaseFixture.cs @@ -0,0 +1,23 @@ +using System.Collections.Generic; +using System.IO; +using NUnit.Framework; +using UnityEditor; +using Scene = USD.NET.Scene; + +namespace Unity.Formats.USD.Tests +{ + public class BaseFixtureEditor : BaseFixture + { + readonly public List m_assetsToDelete = new List(); + + + [TearDown] + public void DeleteAssetsFiles() + { + foreach (var file in m_assetsToDelete) + { + AssetDatabase.DeleteAsset(file); + } + } + } +} diff --git a/package/com.unity.formats.usd/Tests/Editor/BaseFixture.cs.meta b/package/com.unity.formats.usd/Tests/Editor/BaseFixture.cs.meta new file mode 100644 index 000000000..02b9ff5e9 --- /dev/null +++ b/package/com.unity.formats.usd/Tests/Editor/BaseFixture.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 0f03ea67818747198d5ce9f9aed1974a +timeCreated: 1614199416 \ No newline at end of file diff --git a/package/com.unity.formats.usd/Tests/Editor/EditorTests.cs b/package/com.unity.formats.usd/Tests/Editor/EditorTests.cs index 71803a46c..cf43a216e 100644 --- a/package/com.unity.formats.usd/Tests/Editor/EditorTests.cs +++ b/package/com.unity.formats.usd/Tests/Editor/EditorTests.cs @@ -19,7 +19,7 @@ public void SetUp() var usdPath = Path.GetFullPath(AssetDatabase.GUIDToAssetPath(m_usdGUID)); var stage = pxr.UsdStage.Open(usdPath, pxr.UsdStage.InitialLoadSet.LoadNone); var scene = Scene.Open(stage); - m_usdRoot = USD.UsdMenu.ImportSceneAsGameObject(scene); + m_usdRoot = ImportHelpers.ImportSceneAsGameObject(scene); scene.Close(); } @@ -73,7 +73,7 @@ public void SetUp() var scene = Scene.Open(stage); var importOptions = new SceneImportOptions(); importOptions.materialImportMode = MaterialImportMode.ImportPreviewSurface; - m_usdRoot = USD.UsdMenu.ImportSceneAsGameObject(scene, importOptions); + m_usdRoot = ImportHelpers.ImportSceneAsGameObject(scene, importOptions: importOptions); scene.Close(); } diff --git a/package/com.unity.formats.usd/Tests/Editor/FBXHandednessModeTests.cs b/package/com.unity.formats.usd/Tests/Editor/FBXHandednessModeTests.cs index bc933f907..3c97d89c3 100644 --- a/package/com.unity.formats.usd/Tests/Editor/FBXHandednessModeTests.cs +++ b/package/com.unity.formats.usd/Tests/Editor/FBXHandednessModeTests.cs @@ -45,7 +45,7 @@ private GameObject LoadUSD(Object usdObject, BasisTransformation changeHandednes importOptions.changeHandedness = changeHandedness; importOptions.scale = 0.01f; importOptions.materialImportMode = MaterialImportMode.ImportDisplayColor; - var usdRoot = USD.UsdMenu.ImportSceneAsGameObject(scene, importOptions); + var usdRoot = ImportHelpers.ImportSceneAsGameObject(scene, importOptions: importOptions); scene.Close(); return usdRoot; } @@ -118,7 +118,7 @@ public void TestLeftHandedUsdMeshImport(BasisTransformation basisTransformation) break; case BasisTransformation.None: case BasisTransformation.FastWithNegativeScale: - // When comparing the mesh, importing with FastWithNegativeScale and None + // When comparing the mesh, importing with FastWithNegativeScale and None // will give the same result. bakedLeftHandedMesh = bakedLeftHandedCube_none; break; @@ -148,7 +148,7 @@ public void TestLeftHandedUsdMeshImport(BasisTransformation basisTransformation) for(int i = 0; i < cubeMesh.vertices.Length; i++) { Assert.IsTrue(CheckVector3Equality(leftHandedCubeMesh.vertices[i], cubeMesh.vertices[i]), - string.Format("Vertex at index {0} of left and right handed cube mesh are not equal, expected equal:\nExpected:{1}\nActual:{2}", + string.Format("Vertex at index {0} of left and right handed cube mesh are not equal, expected equal:\nExpected:{1}\nActual:{2}", i, cubeMesh.vertices[i], leftHandedCubeMesh.vertices[i])); } NUnit.Framework.Assert.That(cubeMesh.triangles, Is.Not.EqualTo(leftHandedCubeMesh.triangles)); @@ -158,19 +158,19 @@ public void TestLeftHandedUsdMeshImport(BasisTransformation basisTransformation) { // check that normals are flipped Assert.IsTrue(CheckVector3Equality(leftHandedCubeMesh.normals[i], -cubeMesh.normals[i]), - string.Format("Normal at index {0} of left and right handed cube mesh are not equal, expected equal\nExpected:{1}\nActual:{2}", + string.Format("Normal at index {0} of left and right handed cube mesh are not equal, expected equal\nExpected:{1}\nActual:{2}", i, -cubeMesh.normals[i], leftHandedCubeMesh.normals[i])); } // Check that the imported left handed cube matches the baked cube. var bakedCubeMesh = bakedLeftHandedMesh as Mesh; Assert.IsNotNull(bakedCubeMesh); - + NUnit.Framework.Assert.That(leftHandedCubeMesh.vertices.Length, Is.EqualTo(bakedCubeMesh.vertices.Length)); for (int i = 0; i < bakedCubeMesh.vertices.Length; i++) { Assert.IsTrue(CheckVector3Equality(leftHandedCubeMesh.vertices[i], bakedCubeMesh.vertices[i]), - string.Format("Vertex at index {0} of left handed and baked cube mesh are not equal, expected equal:\nExpected:{1}\nActual:{2}", + string.Format("Vertex at index {0} of left handed and baked cube mesh are not equal, expected equal:\nExpected:{1}\nActual:{2}", i, bakedCubeMesh.vertices[i], leftHandedCubeMesh.vertices[i])); } NUnit.Framework.Assert.That(bakedCubeMesh.triangles, Is.EqualTo(leftHandedCubeMesh.triangles)); @@ -184,4 +184,4 @@ public void TestLeftHandedUsdMeshImport(BasisTransformation basisTransformation) } } } -} \ No newline at end of file +} diff --git a/package/com.unity.formats.usd/Tests/Editor/ImportHelpersTests.cs b/package/com.unity.formats.usd/Tests/Editor/ImportHelpersTests.cs new file mode 100644 index 000000000..9ca726db1 --- /dev/null +++ b/package/com.unity.formats.usd/Tests/Editor/ImportHelpersTests.cs @@ -0,0 +1,102 @@ +using System.IO; +using NUnit.Framework; +using UnityEditor; +using UnityEngine; +using USD.NET; +using USD.NET.Unity; +using Object = UnityEngine.Object; + +namespace Unity.Formats.USD.Tests +{ + public class ImportHelpersTests : BaseFixtureEditor + { + Scene CreateTestAsset(string fileName) + { + var dummyUsdPath = CreateTmpUsdFile(fileName); + var scene = ImportHelpers.InitForOpen(dummyUsdPath); + scene.Write("/root", new XformSample()); + scene.Write("/root/sphere", new SphereSample()); + scene.Save(); + return scene; + } + + [Test] + public void ImportAsPrefabTest_ContentOk() + { + var scene = CreateTestAsset("dummyUsd.usda"); + var assetPath = ImportHelpers.ImportAsPrefab(scene); + Assert.IsNull(scene.Stage, "Scene was not closed after import."); + + m_assetsToDelete.Add(assetPath); + + Assert.IsTrue(File.Exists(assetPath)); + var allObjects = AssetDatabase.LoadAllAssetsAtPath(assetPath); + Assert.NotZero(allObjects.Length); + bool playableAssetFound = false; + int goCount = 0; + int materialCount = 0; + foreach (Object thisObject in allObjects) + { + string myType = thisObject.GetType().Name; + if (myType == "UsdPlayableAsset") + { + playableAssetFound = true; + } + else if (myType == "GameObject") + { + goCount += 1; + } + else if (myType == "Material") + { + materialCount += 1; + } + } + + Assert.IsTrue(playableAssetFound, "No PlayableAssset was found in the prefab."); + Assert.AreEqual(2, goCount, "Wrong GameObjects count in the prefab."); + // The 3 default materials + 1 material per meshRender + Assert.AreEqual(4, materialCount, "Wrong Materials count in the prefab"); + } + + [Test] + public void ImportAsTimelineClipTest_ContentOk() + { + // Import as timeline clip should not create a hierarchy, only the root and the playable + var scene = CreateTestAsset("dummyUsd.usda"); + var assetPath = ImportHelpers.ImportAsTimelineClip(scene); + Assert.IsNull(scene.Stage, "Scene was not closed after import."); + m_assetsToDelete.Add(assetPath); + + Assert.IsTrue(File.Exists(assetPath)); + var allObjects = AssetDatabase.LoadAllAssetsAtPath(assetPath); + Assert.NotZero(allObjects.Length); + bool playableAssetFound = false; + int goCount = 0; + int materialCount = 0; + foreach (Object thisObject in allObjects) + { + Debug.Log(thisObject.name); + Debug.Log(thisObject.GetType().Name); + string myType = thisObject.GetType().Name; + if (myType == "UsdPlayableAsset") + { + playableAssetFound = true; + } + else if (myType == "GameObject") + { + goCount += 1; + } + else if (myType == "Material") + { + materialCount += 1; + } + } + + Assert.IsTrue(playableAssetFound, "No PlayableAssset was found in the prefab."); + Assert.AreEqual(1, goCount, "Wrong GameObjects count in the prefab."); + // Only 3 default materials and no meshRenderer + Assert.AreEqual(3, materialCount, "Wrong Materials count in the prefab"); + + } + } +} diff --git a/package/com.unity.formats.usd/Tests/Editor/ImportHelpersTests.cs.meta b/package/com.unity.formats.usd/Tests/Editor/ImportHelpersTests.cs.meta new file mode 100644 index 000000000..6ea218e27 --- /dev/null +++ b/package/com.unity.formats.usd/Tests/Editor/ImportHelpersTests.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 143351b19be54bd09af574fbf90d8132 +timeCreated: 1614118256 \ No newline at end of file diff --git a/package/com.unity.formats.usd/Tests/Editor/USDPayloadComponentTests.cs b/package/com.unity.formats.usd/Tests/Editor/USDPayloadComponentTests.cs index 61ccb5481..bc141bf5d 100644 --- a/package/com.unity.formats.usd/Tests/Editor/USDPayloadComponentTests.cs +++ b/package/com.unity.formats.usd/Tests/Editor/USDPayloadComponentTests.cs @@ -11,7 +11,7 @@ namespace Unity.Formats.USD.Tests public class USDPayloadComponentTests { const string k_USDGUID = "5f0268198d3d7484cb1877bec2c5d31f"; // GUID of test_collections.usda - + private GameObject m_usdRoot; private UsdAsset m_usdAsset; @@ -22,7 +22,7 @@ public void Setup() var usdPath = Path.GetFullPath(AssetDatabase.GUIDToAssetPath(k_USDGUID)); var stage = pxr.UsdStage.Open(usdPath, pxr.UsdStage.InitialLoadSet.LoadNone); var scene = Scene.Open(stage); - m_usdRoot = USD.UsdMenu.ImportSceneAsGameObject(scene); + m_usdRoot = ImportHelpers.ImportSceneAsGameObject(scene); scene.Close(); m_usdAsset = m_usdRoot.GetComponent(); @@ -193,4 +193,4 @@ public IEnumerator IsLoaded_IsFalse_WhenIsUnloadedFromComponent() Assume.That(usdPayload.IsLoaded, Is.False, "UsdPayload.IsLoaded should be set to false."); } } -} \ No newline at end of file +} diff --git a/package/com.unity.formats.usd/Tests/Editor/Unity.Formats.USD.Tests.Editor.asmdef b/package/com.unity.formats.usd/Tests/Editor/Unity.Formats.USD.Tests.Editor.asmdef index 2670d4d8f..93fcad839 100644 --- a/package/com.unity.formats.usd/Tests/Editor/Unity.Formats.USD.Tests.Editor.asmdef +++ b/package/com.unity.formats.usd/Tests/Editor/Unity.Formats.USD.Tests.Editor.asmdef @@ -2,7 +2,8 @@ "name": "Unity.Formats.USD.Tests.Editor", "references": [ "Unity.Formats.USD.Runtime", - "Unity.Formats.USD.Editor" + "Unity.Formats.USD.Editor", + "Unity.Formats.USD.Tests" ], "optionalUnityReferences": [ "TestAssemblies" @@ -15,4 +16,4 @@ "USD.NET.dll", "USD.NET.Unity.dll" ] -} \ No newline at end of file +} diff --git a/package/com.unity.formats.usd/Tests/Editor/UsdAssetReloadTests.cs b/package/com.unity.formats.usd/Tests/Editor/UsdAssetReloadTests.cs index 9e14416e7..21288c81c 100644 --- a/package/com.unity.formats.usd/Tests/Editor/UsdAssetReloadTests.cs +++ b/package/com.unity.formats.usd/Tests/Editor/UsdAssetReloadTests.cs @@ -18,7 +18,7 @@ public class UsdAssetReloadTests string testFilePath; string testFileModifiedPath; - + GameObject m_usdRoot; UsdAsset m_usdAsset; @@ -29,7 +29,7 @@ public void Setup() testFilePath = Path.GetFullPath(AssetDatabase.GUIDToAssetPath(k_USDGUID)); var stage = pxr.UsdStage.Open(testFilePath, pxr.UsdStage.InitialLoadSet.LoadNone); var scene = Scene.Open(stage); - m_usdRoot = UsdMenu.ImportSceneAsGameObject(scene); + m_usdRoot = ImportHelpers.ImportSceneAsGameObject(scene); scene.Close(); m_usdAsset = m_usdRoot.GetComponent(); @@ -46,7 +46,7 @@ public void TearDown() // Restore test files. ResetTestFile(); } - + [UnityTest] public IEnumerator UsdAsset_Reload_FileHasChanged_NewValuesAreRetrieved() { @@ -55,21 +55,21 @@ public IEnumerator UsdAsset_Reload_FileHasChanged_NewValuesAreRetrieved() m_usdAsset.GetScene().Read("/TestPrim", xform); var translate = xform.transform.GetColumn(3); Assert.AreEqual(new Vector4(1, 1, 1, 1), translate); - + yield return new WaitForSecondsRealtime(1f); // Simulate the fact that the usd file was changed on disk. UpdateTestFile(); // Refresh the asset. m_usdAsset.Reload(false); - + // Ensure the new attribute's values can be retrieved. m_usdAsset.GetScene().Read("/TestPrim", xform); translate = xform.transform.GetColumn(3); Assert.AreEqual(new Vector4(2, 2, 2, 1), translate); yield return new WaitForSecondsRealtime(1f); } - + [UnityTest] public IEnumerator UsdAsset_Reload_FileHasChangedAndForceRebuild_NewValuesAreRetrieved() { @@ -82,17 +82,17 @@ public IEnumerator UsdAsset_Reload_FileHasChangedAndForceRebuild_NewValuesAreRet yield return new WaitForSecondsRealtime(1f); // Simulate the fact that the usd file was changed on disk. UpdateTestFile(); - + // Reload the asset. m_usdAsset.Reload(true); - + // Ensure the new attribute's values can be retrieved. m_usdAsset.GetScene().Read("/TestPrim", xform); translate = xform.transform.GetColumn(3); Assert.AreEqual(new Vector4(2, 2, 2, 1), translate); yield return new WaitForSecondsRealtime(1f); } - + [Test] public void UsdAsset_Reload_FileDidNotChange_ValuesDoNotChange() { @@ -104,7 +104,7 @@ public void UsdAsset_Reload_FileDidNotChange_ValuesDoNotChange() // Refresh the asset. m_usdAsset.Reload(false); - + // Ensure that nothing changed. m_usdAsset.GetScene().Read("/TestPrim", xform); translate = xform.transform.GetColumn(3); @@ -114,7 +114,7 @@ public void UsdAsset_Reload_FileDidNotChange_ValuesDoNotChange() void UpdateTestFile() { testFileModifiedPath = Path.GetFullPath(AssetDatabase.GUIDToAssetPath(k_USDModifiedGUID)); - + File.WriteAllBytes(testFilePath, File.ReadAllBytes(testFileModifiedPath)); } @@ -125,4 +125,4 @@ void ResetTestFile() File.WriteAllBytes(testFilePath, File.ReadAllBytes(originFile)); } } -} \ No newline at end of file +} diff --git a/package/com.unity.formats.usd/Tests/Runtime/BaseFixture.cs b/package/com.unity.formats.usd/Tests/Runtime/BaseFixture.cs new file mode 100644 index 000000000..a5748d039 --- /dev/null +++ b/package/com.unity.formats.usd/Tests/Runtime/BaseFixture.cs @@ -0,0 +1,37 @@ +using System.Collections.Generic; +using System.IO; +using NUnit.Framework; +using Scene = USD.NET.Scene; + +namespace Unity.Formats.USD.Tests +{ + public class BaseFixture + { + public readonly List m_filesToDelete = new List(); + + [SetUp] + public void Setup() + { + InitUsd.Initialize(); + } + + public string CreateTmpUsdFile(string fileName) + { + var filePath = System.IO.Path.Combine(UnityEngine.Application.dataPath, fileName); + var scene = Scene.Create(filePath); + scene.Save(); + scene.Close(); + m_filesToDelete.Add(filePath); + return filePath; + } + + [TearDown] + public void DeleteTmpFiles() + { + foreach (var file in m_filesToDelete) + { + File.Delete(file); + } + } + } +} diff --git a/package/com.unity.formats.usd/Tests/Runtime/BaseFixture.cs.meta b/package/com.unity.formats.usd/Tests/Runtime/BaseFixture.cs.meta new file mode 100644 index 000000000..0964f3027 --- /dev/null +++ b/package/com.unity.formats.usd/Tests/Runtime/BaseFixture.cs.meta @@ -0,0 +1,3 @@ +fileFormatVersion: 2 +guid: 48c5f62571914f7b9581bb424e75429c +timeCreated: 1614183414 \ No newline at end of file diff --git a/package/com.unity.formats.usd/Tests/Runtime/ExportHelpersTests.cs b/package/com.unity.formats.usd/Tests/Runtime/ExportHelpersTests.cs new file mode 100644 index 000000000..ae9921685 --- /dev/null +++ b/package/com.unity.formats.usd/Tests/Runtime/ExportHelpersTests.cs @@ -0,0 +1,102 @@ +using System.IO; +using NUnit.Framework; +using UnityEngine; +using USD.NET; + +namespace Unity.Formats.USD.Tests +{ + public class ExportHelpersTests : BaseFixture + { + [Test] + public void InitForSave_EmptyFile() + { + var scene = ExportHelpers.InitForSave(""); + Assert.IsNull(scene); + } + + [Test] + public void InitForSave_NullFile() + { + var scene = ExportHelpers.InitForSave(null); + Assert.IsNull(scene); + } + + [Test] + public void InitForSave_ValidPath() + { + var filePath = System.IO.Path.Combine(Application.dataPath, "dummyUsd.usd"); + m_filesToDelete.Add(filePath); + var scene = ExportHelpers.InitForSave(filePath); + Assert.IsNotNull(scene); + Assert.IsNotNull(scene.Stage); + scene.Close(); + } + + [Test] + public void ExportGameObjects_NullScene() + { + var filePath = CreateTmpUsdFile("dummyUsd.usda"); + var scene = Scene.Open(filePath); + scene.Close(); + var fileInfoBefore = new FileInfo(filePath); + + Assert.DoesNotThrow(delegate() + { + ExportHelpers.ExportGameObjects(null, null, BasisTransformation.SlowAndSafe); + }); + var fileInfoAfter = new FileInfo(filePath); + Assert.AreEqual(fileInfoBefore.Length, fileInfoAfter.Length); + } + + [Test] + public void ExportGameObjects_EmptyList() + { + var filePath = CreateTmpUsdFile("dummyUsd.usda"); + var scene = Scene.Open(filePath); + var fileInfoBefore = new FileInfo(filePath); + Assert.DoesNotThrow(delegate() + { + ExportHelpers.ExportGameObjects(new GameObject [] {}, scene, BasisTransformation.SlowAndSafe); + }); + var fileInfoAfter = new FileInfo(filePath); + Assert.AreEqual(fileInfoBefore.Length, fileInfoAfter.Length); + scene.Close(); + } + + [Test] + public void ExportGameObjects_InvalidGO() + { + + var filePath = CreateTmpUsdFile("dummyUsd.usda"); + var scene = Scene.Open(filePath); + Assert.DoesNotThrow(delegate() + { + ExportHelpers.ExportGameObjects(new GameObject[] {null}, scene, BasisTransformation.SlowAndSafe); + }); + UnityEngine.TestTools.LogAssert.Expect(LogType.Exception, "NullReferenceException: Object reference not set to an instance of an object"); + } + + [Test] + public void ExportGameObjects_ValidGO() + { + var filePath = CreateTmpUsdFile("dummyUsd.usda"); + var scene = Scene.Open(filePath); + ExportHelpers.ExportGameObjects(new [] {new GameObject("test")}, scene, BasisTransformation.SlowAndSafe); + scene = Scene.Open(filePath); + var paths = scene.Stage.GetAllPaths(); + Debug.Log(scene.Stage.GetRootLayer().ExportToString()); + Assert.AreEqual(2, paths.Count); + scene.Close(); + } + + [Test] + public void ExportGameObjects_SceneClosedAfterExport() + { + + var filePath = CreateTmpUsdFile("dummyUsd.usda"); + var scene = Scene.Open(filePath); + ExportHelpers.ExportGameObjects(new [] {new GameObject("test")}, scene, BasisTransformation.SlowAndSafe); + Assert.IsNull(scene.Stage); + } + } +} diff --git a/package/com.unity.formats.usd/Tests/Runtime/ExportHelpersTests.cs.meta b/package/com.unity.formats.usd/Tests/Runtime/ExportHelpersTests.cs.meta new file mode 100644 index 000000000..d75c31087 --- /dev/null +++ b/package/com.unity.formats.usd/Tests/Runtime/ExportHelpersTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 1c2d9cd48bd0ff74da194631282f5733 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/package/com.unity.formats.usd/Tests/Runtime/ImportHelpersTests.cs b/package/com.unity.formats.usd/Tests/Runtime/ImportHelpersTests.cs new file mode 100644 index 000000000..0e9422349 --- /dev/null +++ b/package/com.unity.formats.usd/Tests/Runtime/ImportHelpersTests.cs @@ -0,0 +1,91 @@ +using System; +using NUnit.Framework; +using UnityEngine; +using UnityEngine.SceneManagement; +using USD.NET.Unity; +using Scene = USD.NET.Scene; + +namespace Unity.Formats.USD.Tests +{ + public class ImportHelpersTests : BaseFixture + { + Scene CreateTmpUsdWithData(string fileName) + { + var dummyUsdPath = CreateTmpUsdFile(fileName); + var scene = ImportHelpers.InitForOpen(dummyUsdPath); + scene.Write("/root", new XformSample()); + scene.Write("/root/sphere", new SphereSample()); + scene.Save(); + return scene; + } + + [Test] + public void InitForOpenTest_ValidPath_Succeeds() + { + var dummyUsdPath = CreateTmpUsdFile("dummyUsd.usda"); + var scene = ImportHelpers.InitForOpen(dummyUsdPath); + Assert.NotNull(scene); + Assert.NotNull(scene.Stage); + scene.Close(); + } + + [Test] + public void InitForOpenTest_EmptyPath() + { + var scene = ImportHelpers.InitForOpen(""); + Assert.IsNull(scene); + } + + [Test] + public void InitForOpenTest_InvalidPath_ThrowsAndLogs() + { + var ex = Assert.Throws( + delegate { ImportHelpers.InitForOpen("/this/is/an/invalid/path.usd"); }, "Opening a non existing file should throw an NullReferenceException"); + Assert.That(ex.Message, Is.EqualTo("Null stage")); + UnityEngine.TestTools.LogAssert.Expect(LogType.Exception, "ApplicationException: USD ERROR: Failed to open layer @/this/is/an/invalid/path.usd@"); + } + + [Test] + public void ImportAsGameObjects_ImportAtRoot() + { + var scene = CreateTmpUsdWithData("dummyUsd.usda"); + var root = ImportHelpers.ImportSceneAsGameObject(scene); + bool usdRootIsRoot = Array.Find(SceneManager.GetActiveScene().GetRootGameObjects(), r => r == root); + Assert.IsTrue(usdRootIsRoot, "UsdAsset GameObject is not a root GameObject."); + } + + [Test] + public void ImportAsGameObjects_ImportUnderParent() + { + var root = new GameObject("thisIsTheRoot"); + var scene = CreateTmpUsdWithData("dummyUsd.usda"); + var usdRoot = ImportHelpers.ImportSceneAsGameObject(scene, root); + Assert.AreEqual(root.transform, usdRoot.transform.root, "UsdAsset is not a children of the given parent."); + } + + [Test] + public void ImportAsGameObjects_SceneClosedAfterImport() + { + var scene = CreateTmpUsdWithData("dummyUsd.usda"); + var root = ImportHelpers.ImportSceneAsGameObject(scene); + Assert.IsNull(scene.Stage, "Scene was not closed after import."); + } + + [Test] + public void ImportAsGameObjects_ImportClosedScene_LogsError() + { + var rootGOsBefore = SceneManager.GetActiveScene().GetRootGameObjects(); + var scene = CreateTmpUsdWithData("dummyUsd.usda"); + scene.Close(); + var root = ImportHelpers.ImportSceneAsGameObject(scene); + Assert.IsNull(root); + UnityEngine.TestTools.LogAssert.Expect(LogType.Error, "The USD Scene needs to be opened before being imported."); + } + + [Test] + [Ignore("TODO")] + public void ImportAsGameObjects_CleanupAfterError() + { + } + } +} diff --git a/package/com.unity.formats.usd/Tests/Runtime/ImportHelpersTests.cs.meta b/package/com.unity.formats.usd/Tests/Runtime/ImportHelpersTests.cs.meta new file mode 100644 index 000000000..507c57c3d --- /dev/null +++ b/package/com.unity.formats.usd/Tests/Runtime/ImportHelpersTests.cs.meta @@ -0,0 +1,11 @@ +fileFormatVersion: 2 +guid: 76b0426308aaf2749bf68b2b913a1a52 +MonoImporter: + externalObjects: {} + serializedVersion: 2 + defaultReferences: [] + executionOrder: 0 + icon: {instanceID: 0} + userData: + assetBundleName: + assetBundleVariant: diff --git a/package/com.unity.formats.usd/Tests/Runtime/RuntimeTests.cs b/package/com.unity.formats.usd/Tests/Runtime/RuntimeTests.cs index 709da56d1..04b5498a9 100644 --- a/package/com.unity.formats.usd/Tests/Runtime/RuntimeTests.cs +++ b/package/com.unity.formats.usd/Tests/Runtime/RuntimeTests.cs @@ -11,10 +11,8 @@ namespace Unity.Formats.USD.Tests { - public class SanityTest + public class SanityTest : BaseFixture { - List filesToDelete = new List(); - class MyCustomData : SampleBase { public string aString; @@ -31,8 +29,6 @@ public void SetUp() [Test] public void CanWriteCustomData() { - string usdFile = System.IO.Path.Combine(UnityEngine.Application.dataPath, "sceneFile.usda"); - filesToDelete.Add(usdFile); // Populate Values. var value = new MyCustomData(); value.aString = "IT'S ALIIIIIIIIIIIIIVE!"; @@ -40,14 +36,15 @@ public void CanWriteCustomData() value.aBoundingBox = new UnityEngine.Bounds(); // Writing the value. - var scene = Scene.Create(usdFile); + string usdFile = CreateTmpUsdFile("sceneFile.usda"); + var scene = ImportHelpers.InitForOpen(usdFile); scene.Time = 1.0; scene.Write("/someValue", value); Debug.Log(scene.Stage.GetRootLayer().ExportToString()); scene.Save(); scene.Close(); - Assert.IsTrue(File.Exists(usdFile)); + Assert.IsTrue(File.Exists(usdFile), "File not found."); // Reading the value. Debug.Log(usdFile); @@ -56,25 +53,9 @@ public void CanWriteCustomData() scene.Time = 1.0; scene.Read("/someValue", newValue); - Assert.AreEqual(value.aString, newValue.aString); + Assert.AreEqual(value.aString, newValue.aString, "Serialized data don't match the original data."); scene.Close(); } - - [TearDown] - public void TearDown() - { - foreach (var file in filesToDelete) - { - try - { - File.Delete(file); - } - catch (Exception) - { - // ignored - } - } - } } } diff --git a/package/com.unity.formats.usd/Tests/Runtime/Unity.Formats.USD.Tests.asmdef b/package/com.unity.formats.usd/Tests/Runtime/Unity.Formats.USD.Tests.asmdef index f5bbe47a3..4d4c097e2 100644 --- a/package/com.unity.formats.usd/Tests/Runtime/Unity.Formats.USD.Tests.asmdef +++ b/package/com.unity.formats.usd/Tests/Runtime/Unity.Formats.USD.Tests.asmdef @@ -2,10 +2,9 @@ "name": "Unity.Formats.USD.Tests", "references": [ "Unity.Formats.USD.Runtime", - "Unity.Timeline" - ], - "optionalUnityReferences": [ - "TestAssemblies" + "Unity.Timeline", + "UnityEngine.TestRunner", + "UnityEditor.TestRunner" ], "includePlatforms": [ "Editor", @@ -17,8 +16,14 @@ "allowUnsafeCode": false, "overrideReferences": true, "precompiledReferences": [ - "USD.NET.dll" + "USD.NET.dll", + "USD.NET.Unity.dll", + "nunit.framework.dll" ], "autoReferenced": true, - "defineConstraints": [] + "defineConstraints": [ + "UNITY_INCLUDE_TESTS" + ], + "versionDefines": [], + "noEngineReferences": false } \ No newline at end of file