public void Init() { SdkManager = FbxManager.Create(); FbxIOSettings ios = FbxIOSettings.Create(SdkManager, "IOSRoot"); SdkManager.SetIOSettings(ios); }
void TaskOnClick() { // Build the fbx scene file path // (player/player_data/emptySceneFromRuntime.fbx) string fbxFilePath = Application.dataPath; fbxFilePath = Path.Combine(fbxFilePath, "emptySceneFromRuntime.fbx"); fbxFilePath = Path.GetFullPath(fbxFilePath); Debug.Log(string.Format("The file that will be written is {0}", fbxFilePath)); using (var fbxManager = FbxManager.Create()) { FbxIOSettings fbxIOSettings = FbxIOSettings.Create(fbxManager, Globals.IOSROOT); // Configure the IO settings. fbxManager.SetIOSettings(fbxIOSettings); // Create the exporter var fbxExporter = FbxExporter.Create(fbxManager, "Exporter"); // Initialize the exporter. int fileFormat = fbxManager.GetIOPluginRegistry().FindWriterIDByDescription("FBX ascii (*.fbx)"); bool status = fbxExporter.Initialize(fbxFilePath, fileFormat, fbxIOSettings); // Check that initialization of the fbxExporter was successful if (!status) { Debug.LogError(string.Format("failed to initialize exporter, reason: {0}", fbxExporter.GetStatus().GetErrorString())); return; } // Create a scene var fbxScene = FbxScene.Create(fbxManager, "Scene"); // create scene info FbxDocumentInfo fbxSceneInfo = FbxDocumentInfo.Create(fbxManager, "SceneInfo"); // set some scene info values fbxSceneInfo.mTitle = "fromRuntime"; fbxSceneInfo.mSubject = "Exported from a Unity runtime"; fbxSceneInfo.mAuthor = "Unity Technologies"; fbxSceneInfo.mRevision = "1.0"; fbxSceneInfo.mKeywords = "export runtime"; fbxSceneInfo.mComment = "This is to demonstrate the capability of exporting from a Unity runtime, using the FBX SDK C# bindings"; fbxScene.SetSceneInfo(fbxSceneInfo); // Export the scene to the file. status = fbxExporter.Export(fbxScene); // cleanup fbxScene.Destroy(); fbxExporter.Destroy(); } }
public void EmptyExportImportTest() { int N = 10; long total = 0; for (int i = 0; i < N; i++) { m_stopwatch.Reset(); m_stopwatch.Start(); FbxIOSettings ioSettings = FbxIOSettings.Create(m_fbxManager, Globals.IOSROOT); m_fbxManager.SetIOSettings(ioSettings); FbxExporter exporter = FbxExporter.Create(m_fbxManager, ""); string filename = "test.fbx"; bool exportStatus = exporter.Initialize(filename, -1, m_fbxManager.GetIOSettings()); // Check that export status is True Assert.IsTrue(exportStatus); // Create an empty scene to export FbxScene scene = FbxScene.Create(m_fbxManager, "myScene"); // Export the scene to the file. exporter.Export(scene); exporter.Destroy(); // Import to make sure file is valid FbxImporter importer = FbxImporter.Create(m_fbxManager, ""); bool importStatus = importer.Initialize(filename, -1, m_fbxManager.GetIOSettings()); Assert.IsTrue(importStatus); // Create a new scene so it can be populated FbxScene newScene = FbxScene.Create(m_fbxManager, "myScene2"); importer.Import(newScene); importer.Destroy(); m_stopwatch.Stop(); total += m_stopwatch.ElapsedMilliseconds; // Delete the file once the test is complete File.Delete(filename); } CheckAgainstNative("EmptyExportImport", total / (float)N, N, 4); }
/// <summary> /// Export all the objects in the set. /// Return the number of objects in the set that we exported. /// </summary> public int ExportAll(IEnumerable <UnityEngine.Object> unityExportSet) { // Create the FBX manager using (var fbxManager = FbxManager.Create()) { FbxIOSettings fbxIOSettings = FbxIOSettings.Create(fbxManager, Globals.IOSROOT); // Configure the IO settings. fbxManager.SetIOSettings(fbxIOSettings); // Create the exporter var fbxExporter = FbxExporter.Create(fbxManager, "Exporter"); // Initialize the exporter. int fileFormat = fbxManager.GetIOPluginRegistry().FindWriterIDByDescription("FBX ascii (*.fbx)"); bool status = fbxExporter.Initialize(LastFilePath, fileFormat, fbxIOSettings); // Check that initialization of the fbxExporter was successful if (!status) { Debug.LogError(string.Format("failed to initialize exporter, reason:D {0}", fbxExporter.GetStatus().GetErrorString())); return(0); } // By default, FBX exports in its most recent version. You might want to specify // an older version for compatibility with other applications. fbxExporter.SetFileExportVersion("FBX201400"); // Create a scene var fbxScene = FbxScene.Create(fbxManager, "Scene"); // create scene info FbxDocumentInfo fbxSceneInfo = FbxDocumentInfo.Create(fbxManager, "SceneInfo"); // set some scene info values fbxSceneInfo.mTitle = Title; fbxSceneInfo.mSubject = Subject; fbxSceneInfo.mAuthor = "Unity Technologies"; fbxSceneInfo.mRevision = "1.0"; fbxSceneInfo.mKeywords = Keywords; fbxSceneInfo.mComment = Comments; fbxScene.SetSceneInfo(fbxSceneInfo); // Export the scene to the file. status = fbxExporter.Export(fbxScene); // cleanup fbxScene.Destroy(); fbxExporter.Destroy(); return(status == true ? NumNodes : 0); } }
public void TestInitializeInvalidIOSettings() { string filename = GetRandomFilename(m_testFolder); // Initialize the exporter. Pass it zombie IO settings. var ioSettings = FbxIOSettings.Create(Manager, ""); ioSettings.Destroy(); Assert.That(() => { m_exporter.Initialize(filename, -1, ioSettings); }, Throws.Exception.TypeOf <System.ArgumentNullException>()); }
public FbxExportGlobals(string outputFile) { m_outputFile = outputFile; m_sanitizedFileName = System.Text.RegularExpressions.Regex.Replace( Path.GetFileNameWithoutExtension(m_outputFile), @"[^a-zA-Z0-9_]", "_"); m_outputDir = Path.GetDirectoryName(outputFile); m_manager = FbxManager.Create(); m_ioSettings = FbxIOSettings.Create(m_manager, Globals.IOSROOT); m_manager.SetIOSettings(m_ioSettings); m_exporter = FbxExporter.Create(m_manager, ""); }
public virtual void Init () { foreach (string file in Directory.GetFiles (this.filePath, MakeFileName("*"))) { File.Delete (file); } // create fbx manager. m_fbxManager = FbxManager.Create (); // configure IO settings. m_fbxManager.SetIOSettings (FbxIOSettings.Create (m_fbxManager, Globals.IOSROOT)); }
public void TestIOSettings() { FbxIOSettings ioSettings = m_fbxManager.GetIOSettings(); Assert.IsNull(ioSettings); using (FbxIOSettings ioSettings1 = FbxIOSettings.Create(m_fbxManager, "")) { m_fbxManager.SetIOSettings(ioSettings1); FbxIOSettings ioSettings2 = m_fbxManager.GetIOSettings(); Assert.IsNotNull(ioSettings2); } }
void Init() { SdkManager = FbxManager.Create(); FbxIOSettings ios = FbxIOSettings.Create(SdkManager, "IOSRoot"); SdkManager.SetIOSettings(ios); // EXP_FBX = "Material"; //public string EXP_ADV_OPT_GRP = "Material"; //public string IOSN_EXPORT = "Export"; //public string IOSN_FBX = "Fbx"; //public string IOSN_MATERIAL = "Material"; //public string EXP_FBX_MATERIAL = EXP_FBX + " | " + IOSN_MATERIAL; }
public (GameObject, List <string> warnings, ImportMaterialCollector) Import() { FbxManager fbxManager = FbxManager.Create(); FbxIOSettings ioSettings = FbxIOSettings.Create(fbxManager, Globals.IOSROOT); fbxManager.SetIOSettings(ioSettings); FbxImporter fbxImporter = FbxImporter.Create(fbxManager, ""); if (!fbxImporter.Initialize(m_path, -1, ioSettings)) { warnings.Add("Failed to initialize FBX importer"); return(null, warnings, null); } FbxScene scene = FbxScene.Create(fbxManager, "scene"); fbxImporter.Import(scene); FbxNode root = scene.GetRootNode(); SetPivots(root); root.ConvertPivotAnimationRecursive(null, FbxNode.EPivotSet.eDestinationPivot, 30); long totalVerts = GetTotalVerts(root); long completedVerts = 0; float fbxUnitToTiltUnit; { var unit = scene.GetGlobalSettings().GetSystemUnit(); if (Path.GetExtension(m_path).ToLower() == ".obj") { // Obj doesn't specify units. We'd rather assume m, but fbx assumes cm. unit = FbxSystemUnit.m; } fbxUnitToTiltUnit = (float)unit.GetConversionFactorTo(FbxSystemUnit.m) * App.METERS_TO_UNITS; } GameObject go = ImportNodes( root, fbxUnitToTiltUnit, ref completedVerts, totalVerts); Debug.Assert(completedVerts == totalVerts); fbxImporter.Destroy(); ioSettings.Destroy(); fbxManager.Destroy(); return(go, warnings.Distinct().ToList(), m_collector); }
private void FbxImportAndTestBlendshapes(string fbxPath) { // Create the FBX manager using (var fbxManager = FbxManager.Create()) { FbxIOSettings fbxIOSettings = FbxIOSettings.Create(fbxManager, Globals.IOSROOT); // Configure the IO settings. fbxManager.SetIOSettings(fbxIOSettings); // Create the importer var fbxImporter = FbxImporter.Create(fbxManager, "Importer"); // Initialize the importer. int fileFormat = -1; bool status = fbxImporter.Initialize(fbxPath, fileFormat, fbxIOSettings); FbxStatus fbxStatus = fbxImporter.GetStatus(); Assert.That(status, Is.True, fbxStatus.GetErrorString()); Assert.That(fbxImporter.IsFBX(), "file does not contain FBX data"); // Import options. Determine what kind of data is to be imported. // The default is true, but here we set the options explictly. fbxIOSettings.SetBoolProp(Globals.IMP_FBX_MATERIAL, false); fbxIOSettings.SetBoolProp(Globals.IMP_FBX_TEXTURE, false); fbxIOSettings.SetBoolProp(Globals.IMP_FBX_ANIMATION, false); fbxIOSettings.SetBoolProp(Globals.IMP_FBX_EXTRACT_EMBEDDED_DATA, false); fbxIOSettings.SetBoolProp(Globals.IMP_FBX_GLOBAL_SETTINGS, true); // Create a scene var fbxScene = FbxScene.Create(fbxManager, "Scene"); // Import the scene to the file. status = fbxImporter.Import(fbxScene); fbxStatus = fbxImporter.GetStatus(); Assert.That(status, Is.True, fbxStatus.GetErrorString()); // Get blendshapes and check that the FbxShapes all have names var rootNode = fbxScene.GetRootNode(); TestFbxShapeNamesNotEmpty(rootNode); } }
// Export scene sample protected void ExportScene(string fileName) { using (FbxManager fbxManager = FbxManager.Create()) { // configure IO settings. fbxManager.SetIOSettings(FbxIOSettings.Create(fbxManager, Globals.IOSROOT)); // Export the scene using (Autodesk.Fbx.FbxExporter exporter = Autodesk.Fbx.FbxExporter.Create(fbxManager, "myExporter")) { // Initialize the exporter. bool status = exporter.Initialize(fileName, -1, fbxManager.GetIOSettings()); // Create a new scene to export FbxScene scene = FbxScene.Create(fbxManager, "myScene"); // Export the scene to the file. exporter.Export(scene); } } }
// Import scene sample protected void ImportScene(string fileName) { using (FbxManager fbxManager = FbxManager.Create()) { // configure IO settings. fbxManager.SetIOSettings(FbxIOSettings.Create(fbxManager, Globals.IOSROOT)); // Import the scene to make sure file is valid using (FbxImporter importer = FbxImporter.Create(fbxManager, "myImporter")) { // Initialize the importer. bool status = importer.Initialize(fileName, -1, fbxManager.GetIOSettings()); // Create a new scene so it can be populated by the imported file. FbxScene scene = FbxScene.Create(fbxManager, "myScene"); // Import the contents of the file into the scene. importer.Import(scene); } } }
/// <summary> /// Export all the objects in the set. /// Return the number of objects in the set that we exported. /// </summary> public int ExportAll(IEnumerable <UnityEngine.Object> unityExportSet) { // Create the FBX manager using (var fbxManager = FbxManager.Create()) { // Configure the IO settings. fbxManager.SetIOSettings(FbxIOSettings.Create(fbxManager, Globals.IOSROOT)); // Create the exporter var fbxExporter = FbxExporter.Create(fbxManager, "Exporter"); // Initialize the exporter. int fileFormat = fbxManager.GetIOPluginRegistry().FindWriterIDByDescription("FBX ascii (*.fbx)"); bool status = fbxExporter.Initialize(LastFilePath, fileFormat, fbxManager.GetIOSettings()); // Check that initialization of the fbxExporter was successful if (!status) { return(0); } // By default, FBX exports in its most recent version. You might want to specify // an older version for compatibility with other applications. fbxExporter.SetFileExportVersion("FBX201400"); // Create a scene var fbxScene = FbxScene.Create(fbxManager, "Scene"); // create scene info FbxDocumentInfo fbxSceneInfo = FbxDocumentInfo.Create(fbxManager, "SceneInfo"); // set some scene info values fbxSceneInfo.mTitle = Title; fbxSceneInfo.mSubject = Subject; fbxSceneInfo.mAuthor = "Unity Technologies"; fbxSceneInfo.mRevision = "1.0"; fbxSceneInfo.mKeywords = Keywords; fbxSceneInfo.mComment = Comments; fbxScene.SetSceneInfo(fbxSceneInfo); var fbxSettings = fbxScene.GetGlobalSettings(); fbxSettings.SetSystemUnit(FbxSystemUnit.m); // Unity unit is meters // TODO: Uni-15896 //fbxSettings.SetAxisSystem(FbxAxisSystem.OpenGL); // Unity axes are Y-up, odd parity, right-handed FbxNode fbxRootNode = fbxScene.GetRootNode(); // export set of object foreach (var obj in unityExportSet) { var unityGo = GetGameObject(obj); if (unityGo) { this.ExportComponents(unityGo, fbxScene, fbxRootNode); } } fbxSceneInfo.mComment = string.Format("Mesh Count : {0}, Triangle Count: {1}, Vertex Count: {2} ", NumMeshes, NumTriangles, NumVertices); // Export the scene to the file. status = fbxExporter.Export(fbxScene); // cleanup fbxScene.Destroy(); fbxExporter.Destroy(); return(status == true ? NumNodes : 0); } }
/// <summary> /// Import all from scene. /// Return the number of objects we imported. /// </summary> public int ImportAll(IEnumerable <UnityEngine.Object> unitySelectionSet) { // Create the FBX manager using (var fbxManager = FbxManager.Create()) { FbxIOSettings fbxIOSettings = FbxIOSettings.Create(fbxManager, Globals.IOSROOT); // Configure the IO settings. fbxManager.SetIOSettings(fbxIOSettings); // Get the version number of the FBX files generated by the // version of FBX SDK that you are using. int sdkMajor = -1, sdkMinor = -1, sdkRevision = -1; FbxManager.GetFileFormatVersion(out sdkMajor, out sdkMinor, out sdkRevision); // Create the importer var fbxImporter = FbxImporter.Create(fbxManager, "Importer"); // Initialize the importer. int fileFormat = -1; bool status = fbxImporter.Initialize(LastFilePath, fileFormat, fbxIOSettings); FbxStatus fbxStatus = fbxImporter.GetStatus(); // Get the version number of the FBX file format. int fileMajor = -1, fileMinor = -1, fileRevision = -1; fbxImporter.GetFileVersion(out fileMajor, out fileMinor, out fileRevision); // Check that initialization of the fbxImporter was successful if (!status) { Debug.LogError(string.Format("failed to initialize FbxImporter, error returned {0}", fbxStatus.GetErrorString())); if (fbxStatus.GetCode() == FbxStatus.EStatusCode.eInvalidFileVersion) { Debug.LogError(string.Format("Invalid file version detected\nSDK version: {0}.{1}.{2}\nFile version: {3}.{4}.{5}", sdkMajor, sdkMinor, sdkRevision, fileMajor, fileMinor, fileRevision)); } return(0); } MsgLine.Add("Import Scene Report"); MsgLine.Add(kBorderLine); MsgLine.Add(kPadding + string.Format("FilePath: {0}", LastFilePath)); MsgLine.Add(kPadding + string.Format("SDK version: {0}.{1}.{2}", sdkMajor, sdkMinor, sdkRevision)); if (!fbxImporter.IsFBX()) { Debug.LogError(string.Format("file does not contain FBX data {0}", LastFilePath)); return(0); } MsgLine.Add(kPadding + string.Format("File version: {0}.{1}.{2}", fileMajor, fileMinor, fileRevision)); MsgLine.Add(kBorderLine); MsgLine.Add("Animation"); MsgLine.Add(kBorderLine); int numAnimStack = fbxImporter.GetAnimStackCount(); MsgLine.Add(kPadding + string.Format("number of stacks: {0}", numAnimStack)); MsgLine.Add(kPadding + string.Format("active animation stack: \"{0}\"\n", fbxImporter.GetActiveAnimStackName())); for (int i = 0; i < numAnimStack; i++) { #if UNI_18972 FbxTakeInfo fbxTakeInfo = fbxImporter.GetTakeInfo(i); MsgLine.Add(kPadding + string.Format("Animation Stack ({0})", i)); MsgLine.Add(kPadding + string.Format("name: \"{0}\"", fbxTakeInfo.mName) + string.kNewLine); MsgLine.Add(kPadding + string.Format("description: \"{0}\"", fbxTakeInfo.mDescription)); MsgLine.Add(kPadding + string.Format("import name: \"{0}\"", fbxTakeInfo.mImportName)); MsgLine.Add(kPadding + string.Format("import state: \"{0}\"", fbxTakeInfo.mSelect)); #endif } // Import options. Determine what kind of data is to be imported. // The default is true, but here we set the options explictly. fbxIOSettings.SetBoolProp(Globals.IMP_FBX_MATERIAL, false); fbxIOSettings.SetBoolProp(Globals.IMP_FBX_TEXTURE, false); fbxIOSettings.SetBoolProp(Globals.IMP_FBX_ANIMATION, false); fbxIOSettings.SetBoolProp(Globals.IMP_FBX_EXTRACT_EMBEDDED_DATA, false); fbxIOSettings.SetBoolProp(Globals.IMP_FBX_GLOBAL_SETTINGS, true); // Create a scene var fbxScene = FbxScene.Create(fbxManager, "Scene"); // Import the scene to the file. status = fbxImporter.Import(fbxScene); fbxStatus = fbxImporter.GetStatus(); if (status == false) { if (fbxStatus.GetCode() == FbxStatus.EStatusCode.ePasswordError) { Debug.LogError(string.Format("failed to import, file is password protected ({0})", fbxStatus.GetErrorString())); } else { Debug.LogError(string.Format("failed to import file ({0})", fbxStatus.GetErrorString())); } } else { // import data into scene ProcessScene(fbxScene, unitySelectionSet); } // cleanup fbxScene.Destroy(); fbxImporter.Destroy(); return(status == true ? NumNodes : 0); } }
/// <summary> /// Import all from scene. /// Return the number of objects we imported. /// </summary> public int ImportAll() { // Create the FBX manager using (var fbxManager = FbxManager.Create()) { FbxIOSettings fbxIOSettings = FbxIOSettings.Create(fbxManager, Globals.IOSROOT); // Configure the IO settings. fbxManager.SetIOSettings(fbxIOSettings); // Get the version number of the FBX files generated by the // version of FBX SDK that you are using. int sdkMajor = -1, sdkMinor = -1, sdkRevision = -1; FbxManager.GetFileFormatVersion(out sdkMajor, out sdkMinor, out sdkRevision); // Create the importer var fbxImporter = FbxImporter.Create(fbxManager, "Importer"); // Initialize the importer. int fileFormat = -1; bool status = fbxImporter.Initialize(LastFilePath, fileFormat, fbxIOSettings); FbxStatus fbxStatus = fbxImporter.GetStatus(); // Get the version number of the FBX file format. int fileMajor = -1, fileMinor = -1, fileRevision = -1; fbxImporter.GetFileVersion(out fileMajor, out fileMinor, out fileRevision); // Check that initialization of the fbxImporter was successful if (!status) { Debug.LogError(string.Format("failed to initialize FbxImporter, error returned {0}", fbxStatus.GetErrorString())); if (fbxStatus.GetCode() == FbxStatus.EStatusCode.eInvalidFileVersion) { Debug.LogError(string.Format("Invalid file version detected\nSDK version: {0}.{1}.{2}\nFile version: {3}.{4}.{5}", sdkMajor, sdkMinor, sdkRevision, fileMajor, fileMinor, fileRevision)); } return(0); } // Import options. Determine what kind of data is to be imported. // The default is true, but here we set the options explictly. fbxIOSettings.SetBoolProp(Globals.IMP_FBX_MATERIAL, false); fbxIOSettings.SetBoolProp(Globals.IMP_FBX_TEXTURE, false); fbxIOSettings.SetBoolProp(Globals.IMP_FBX_ANIMATION, false); fbxIOSettings.SetBoolProp(Globals.IMP_FBX_EXTRACT_EMBEDDED_DATA, false); fbxIOSettings.SetBoolProp(Globals.IMP_FBX_GLOBAL_SETTINGS, true); // Create a scene var fbxScene = FbxScene.Create(fbxManager, "Scene"); // Import the scene to the file. status = fbxImporter.Import(fbxScene); if (status == false) { Debug.LogError(string.Format("failed to import file ({0})", fbxImporter.GetStatus().GetErrorString())); } else { // import data into scene ProcessScene(fbxScene); } // cleanup fbxScene.Destroy(); fbxImporter.Destroy(); return(status == true ? NumNodes : 0); } }
public static void ExportMesh(Mesh mesh, string directory, string fileName) { var filePath = Path.Combine(directory, fileName); // Make a temporary copy of the mesh to modify it Mesh tempMesh = Object.Instantiate(mesh); tempMesh.name = mesh.name; // If meters, divide by 100 since default is cm. Assume centered at origin. if (fbxUnit == FbxSystemUnit.m) { Vector3[] vertices = tempMesh.vertices; for (int i = 0; i < vertices.Length; ++i) { vertices[i] /= 100.0f; } tempMesh.vertices = vertices; } // You could handle other SystemUnits here // FBX Manager FbxManager manager = FbxManager.Create(); manager.SetIOSettings(FbxIOSettings.Create(manager, Globals.IOSROOT)); // FBX Exporter FbxExporter fbxExporter = FbxExporter.Create(manager, "Exporter"); // Binary int fileFormat = -1; // Ascii if (saveFbxAsAscii) { fileFormat = manager.GetIOPluginRegistry().FindWriterIDByDescription("FBX ascii (*.fbx)"); } fbxExporter.Initialize(filePath, fileFormat, manager.GetIOSettings()); fbxExporter.SetFileExportVersion("FBX201400"); // FBX Scene FbxScene fbxScene = FbxScene.Create(manager, "Scene"); FbxDocumentInfo sceneInfo = FbxDocumentInfo.Create(manager, "SceneInfo"); // Set up scene info sceneInfo.mTitle = fbxFileTitle; sceneInfo.mSubject = fbxFileSubject; sceneInfo.mComment = fbxFileComment; sceneInfo.mAuthor = fbxFileAuthor; sceneInfo.mRevision = fbxFileRevision; sceneInfo.mKeywords = fbxFileKeywords; sceneInfo.Original_ApplicationName.Set(fbxFileApplication); sceneInfo.LastSaved_ApplicationName.Set(fbxFileApplication); fbxScene.SetSceneInfo(sceneInfo); // Set up Global settings FbxGlobalSettings globalSettings = fbxScene.GetGlobalSettings(); globalSettings.SetSystemUnit(fbxUnit); globalSettings.SetAxisSystem(fbxAxisSystem); FbxNode modelNode = FbxNode.Create(fbxScene, tempMesh.name); // Add mesh to a node in the scene // TODO Wat??? // using (ModelExporter modelExporter = new ModelExporter()) // { // if (!modelExporter.ExportMesh(tempMesh, modelNode)) // Debug.LogError("Problem Exporting Mesh"); // } // add the model to the scene fbxScene.GetRootNode().AddChild(modelNode); // Finally actually save the scene bool sceneSuccess = fbxExporter.Export(fbxScene); AssetDatabase.Refresh(); // clean up temporary model if (Application.isPlaying) { Object.Destroy(tempMesh); } else { Object.DestroyImmediate(tempMesh); } }
static bool LoadFBX(ImportContext context, string virtualFileName, out List <MeshData> geometries) { geometries = null; var settings = context.settings; ImportFBX.LoadNativeLibrary(); FbxManager manager = null; FbxIOSettings setting = null; FbxImporter importer = null; FbxScene scene = null; try { manager = FbxManager.Create(); setting = FbxIOSettings.Create(manager, "IOSRoot"); manager.SetIOSettings(setting); importer = FbxImporter.Create(manager, ""); var realFileName = VirtualPathUtility.GetRealPathByVirtual(virtualFileName); //VirtualFileStream stream = null; //ToDo : FromStream bool status; if (!string.IsNullOrEmpty(realFileName) && File.Exists(realFileName)) { status = importer.Initialize(realFileName, -1, setting); } else { return(false); //throw new NotImplementedException(); //ToDo : .... //stream = VirtualFile.Open( settings.virtualFileName ); //FbxStream fbxStream = null; //SWIGTYPE_p_void streamData = null; //status = impoter.Initialize( fbxStream, streamData, -1, setting ); } if (!status) { return(false); } scene = FbxScene.Create(manager, "scene1"); status = importer.Import(scene); if (!status) { return(false); } //convert axis if (context.settings.component.ForceFrontXAxis) { //Через такой конструктор не получится создать такие же оси как EPreDefinedAxisSystem.eMax - Front Axis имеет обратное направление, а направление задать нельзя. //new FbxAxisSystem( FbxAxisSystem.EUpVector.eZAxis, FbxAxisSystem.EFrontVector.eParityOdd, FbxAxisSystem.ECoordSystem.eRightHanded ); //FromFBX Docs: //The enum values ParityEven and ParityOdd denote the first one and the second one of the remain two axes in addition to the up axis. //For example if the up axis is X, the remain two axes will be Y And Z, so the ParityEven is Y, and the ParityOdd is Z ; //We desire to convert the scene from Y-Up to Z-Up. Using the predefined axis system: Max (UpVector = +Z, FrontVector = -Y, CoordSystem = +X (RightHanded)) var maxAxisSystem = new FbxAxisSystem(FbxAxisSystem.EPreDefinedAxisSystem.eMax); if (!scene.GetGlobalSettings().GetAxisSystem().eq(maxAxisSystem)) { maxAxisSystem.ConvertScene(scene); //No conversion will take place if the scene current axis system is equal to the new one. So condition can be removed. } } //convert units if (!scene.GetGlobalSettings().GetSystemUnit().eq(FbxSystemUnit.m)) { FbxSystemUnit.m.ConvertScene(scene); } var additionalTransform = new Matrix4(settings.component.Rotation.Value.ToMatrix3() * Matrix3.FromScale(settings.component.Scale), settings.component.Position); var options = new ImportOptions { NormalsOptions = NormalsAndTangentsLoadOptions.FromFileIfPresentOrCalculate, TangentsOptions = NormalsAndTangentsLoadOptions.FromFileIfPresentOrCalculate, ImportPostProcessFlags = ImportPostProcessFlags.FixInfacingNormals }; options.ImportPostProcessFlags |= ImportPostProcessFlags.SmoothNormals | ImportPostProcessFlags.SmoothTangents; if (context.settings.component.FlipUVs) { options.ImportPostProcessFlags |= ImportPostProcessFlags.FlipUVs; } //if( importContext.settings.component.MergeMeshGeometries ) // options.ImportPostProcessFlags |= ImportPostProcessFlags.MergeGeometriesByMaterials; var sceneLoader = new SceneLoader(); sceneLoader.Load(scene, manager, options, additionalTransform); geometries = sceneLoader.Geometries; //foreach( var geometry in sceneLoader.Geometries ) // ImportGeometry( context, destinationMesh, geometry ); ////check is it a billboard //MeshGetIsBillboard( context, destinationMesh ); //stream?.Dispose(); } finally { //Особенности удаления. //Создается через функцию: impoter = FbxImporter.Create(manager, ""); //В таких случаях(создание не через конструктор, а возврат указателя из функции) SWIG задает флажок что объект не владеет ссылкой, поэтому Dispose ничего не делает. //Хотя в SWIG можно задать в конфигурации: %newobject FbxImporter::Create; Тогда объект будет владеть ссылкой. Но все равно в С++ наследники FbxObject не имеют public destructor //поэтому в Dispose вставлен: throw new MethodAccessException("C++ destructor does not have public access"). Поэтому удалять только через Destroy. try { scene?.Destroy(); } catch { } try { importer?.Destroy(); } catch { } try { setting?.Destroy(); } catch { } try { manager?.Destroy(); } catch { } } return(true); }
//--------------------------------------------------------------------------------------------------------- /// <summary> /// Открытие файла /// </summary> //--------------------------------------------------------------------------------------------------------- public void OpenFile(TreeView model_tree_view) { if (mIsLoading) { return; } String path = XFileDialog.OpenUseExtension("Открыть 3D файл", OpenFileFilter); if (path == null) { return; } StopAnimation(); // Create the FBX SDK manager FbxManager lSdkManager = FbxManager.Create(); // Create an IOSettings object. FbxIOSettings ios = FbxIOSettings.Create(lSdkManager, Globals.IOSROOT); lSdkManager.SetIOSettings(ios); // ... Configure the FbxIOSettings object ... // Create an importer. FbxImporter lImporter = FbxImporter.Create(lSdkManager, ""); // Initialize the importer. bool lImportStatus = lImporter.Initialize(path, -1, lSdkManager.GetIOSettings()); mIsLoading = true; Task.Run(() => { var loader = new Importer(); //loader.Configuration.AssimpPostProcessSteps = //loader.Configuration.AssimpPostProcessSteps | //Assimp.PostProcessSteps.OptimizeGraph; return(loader.Load(path)); }).ContinueWith((result) => { mIsLoading = false; if (result.IsCompleted) { HelixToolkitScene helix_toolkit_scene = result.Result; if (helix_toolkit_scene == null) { return; } mSceneRoot = helix_toolkit_scene.Root; mSceneAnimations = helix_toolkit_scene.Animations; Animations.Clear(); GroupModel.Clear(); if (helix_toolkit_scene != null) { if (helix_toolkit_scene.Root != null) { foreach (var node in helix_toolkit_scene.Root.Traverse()) { if (node is MaterialGeometryNode m) { if (m.Material is PBRMaterialCore pbr) { pbr.RenderEnvironmentMap = RenderEnvironmentMap; } else if (m.Material is PhongMaterialCore phong) { phong.RenderEnvironmentMap = RenderEnvironmentMap; } } } } GroupModel.AddNode(helix_toolkit_scene.Root); if (helix_toolkit_scene.HasAnimation) { var dict = helix_toolkit_scene.Animations.CreateAnimationUpdaters(); foreach (var animation in dict.Values) { Animations.Add(animation); } } foreach (var node in helix_toolkit_scene.Root.Traverse()) { //node.Tag = new AttachedNodeViewModel(node); } } Boolean is_y_up = threeViewer.IsModelUpDirectionY(); checkBoxYUpModel.IsChecked = is_y_up; if (is_y_up) { } model_tree_view.ItemsSource = mSceneRoot.Items; //Scene = new CScene3D() } else if (result.IsFaulted && result.Exception != null) { MessageBox.Show(result.Exception.Message); } }, TaskScheduler.FromCurrentSynchronizationContext()); }
public static bool ExportToFBX(Component_Mesh sourceMesh, string realFileName, out string error) { //!!!!как для Vegetation. оверрайдить в Component_Mesh? //get mesh data var operations = new List <Component_RenderingPipeline.RenderSceneData.MeshDataRenderOperation>(); foreach (var geometry in sourceMesh.GetComponents <Component_MeshGeometry>()) { if (geometry.Enabled) { geometry.CompileDataOfThisObject(out var operation); if (operation != null) { operations.Add(operation); } } } //foreach( var geometry in mesh.Result.MeshData.RenderOperations ) //{ //} FbxManager manager = null; FbxIOSettings setting = null; FbxExporter exporter = null; FbxScene scene = null; try { //init FBX manager manager = FbxManager.Create(); setting = FbxIOSettings.Create(manager, "IOSRoot"); manager.SetIOSettings(setting); scene = FbxScene.Create(manager, "scene"); scene.GetGlobalSettings().SetAxisSystem(new FbxAxisSystem(FbxAxisSystem.EPreDefinedAxisSystem.eMax)); scene.GetGlobalSettings().SetSystemUnit(new FbxSystemUnit(100)); //init FBX scene for (int nOper = 0; nOper < operations.Count; nOper++) { var oper = operations[nOper]; //get data Vector3F[] positions = null; Vector3F[] normals = null; var texCoords = new List <Vector2F[]>(); ColorValue[] colors = null; Vector3F[] tangents = null; Vector3F[] binormals = null; //Position { if (oper.VertexStructure.GetElementBySemantic(VertexElementSemantic.Position, out VertexElement element) && element.Type == VertexElementType.Float3) { var buffer = oper.VertexBuffers[element.Source]; positions = buffer.ExtractChannel <Vector3F>(element.Offset); } } //Normal { if (oper.VertexStructure.GetElementBySemantic(VertexElementSemantic.Normal, out VertexElement element) && element.Type == VertexElementType.Float3) { var buffer = oper.VertexBuffers[element.Source]; normals = buffer.ExtractChannel <Vector3F>(element.Offset); } } //TexCoord for (var channel = VertexElementSemantic.TextureCoordinate0; channel <= VertexElementSemantic.TextureCoordinate3; channel++) { if (oper.VertexStructure.GetElementBySemantic(channel, out VertexElement element) && element.Type == VertexElementType.Float2) { var buffer = oper.VertexBuffers[element.Source]; texCoords.Add(buffer.ExtractChannel <Vector2F>(element.Offset)); } } //Color { if (oper.VertexStructure.GetElementBySemantic(VertexElementSemantic.Color0, out VertexElement element)) { if (element.Type == VertexElementType.Float4) { var buffer = oper.VertexBuffers[element.Source]; var values = buffer.ExtractChannel <Vector4F>(element.Offset); colors = new ColorValue[positions.Length]; int destIndex = 0; foreach (var p in values) { colors[destIndex++] = p.ToColorValue(); } } else if (element.Type == VertexElementType.ColorABGR) { //!!!!check var buffer = oper.VertexBuffers[element.Source]; var values = buffer.ExtractChannel <uint>(element.Offset); colors = new ColorValue[positions.Length]; int destIndex = 0; foreach (var p in values) { colors[destIndex++] = new ColorValue(ColorByte.FromABGR(p)); } } else if (element.Type == VertexElementType.ColorARGB) { //!!!!check var buffer = oper.VertexBuffers[element.Source]; var values = buffer.ExtractChannel <uint>(element.Offset); colors = new ColorValue[positions.Length]; int destIndex = 0; foreach (var p in values) { colors[destIndex++] = new ColorValue(ColorByte.FromARGB(p)); } } } } //Tangent, Binormal if (normals != null) { if (oper.VertexStructure.GetElementBySemantic(VertexElementSemantic.Tangent, out VertexElement element) && element.Type == VertexElementType.Float4) { var buffer = oper.VertexBuffers[element.Source]; var tangents4 = buffer.ExtractChannel <Vector4F>(element.Offset); tangents = new Vector3F[tangents4.Length]; binormals = new Vector3F[tangents4.Length]; int destIndex = 0; foreach (var p in tangents4) { tangents[destIndex] = p.ToVector3F(); binormals[destIndex] = Vector3F.Cross(p.ToVector3F(), normals[destIndex]) * p.W; destIndex++; } } } //indices int[] indices = null; if (oper.IndexBuffer != null) { indices = oper.IndexBuffer.Indices; } //create geometry var geometryName = "Geometry " + nOper.ToString(); var mesh = FbxMesh.Create(scene, geometryName); mesh.InitControlPoints(positions.Length); FbxLayerElementNormal elementNormals = null; if (normals != null) { elementNormals = mesh.CreateElementNormal(); elementNormals.SetMappingMode(FbxLayerElement.EMappingMode.eByControlPoint); elementNormals.SetReferenceMode(FbxLayerElement.EReferenceMode.eDirect); } FbxLayerElementVertexColor elementColors = null; if (colors != null) { elementColors = mesh.CreateElementVertexColor(); elementColors.SetMappingMode(FbxLayerElement.EMappingMode.eByControlPoint); elementColors.SetReferenceMode(FbxLayerElement.EReferenceMode.eDirect); } FbxLayerElementTangent elementTangents = null; if (tangents != null) { elementTangents = mesh.CreateElementTangent(); elementTangents.SetMappingMode(FbxLayerElement.EMappingMode.eByControlPoint); elementTangents.SetReferenceMode(FbxLayerElement.EReferenceMode.eDirect); } FbxLayerElementBinormal elementBinormals = null; if (binormals != null) { elementBinormals = mesh.CreateElementBinormal(); elementBinormals.SetMappingMode(FbxLayerElement.EMappingMode.eByControlPoint); elementBinormals.SetReferenceMode(FbxLayerElement.EReferenceMode.eDirect); } var uvElements = new List <FbxLayerElementUV>(); for (int uvIndex = 0; uvIndex < texCoords.Count; uvIndex++) { var pUVElement = mesh.CreateElementUV("texcoord" + uvIndex.ToString()); pUVElement.SetMappingMode(FbxLayerElement.EMappingMode.eByControlPoint); pUVElement.SetReferenceMode(FbxLayerElement.EReferenceMode.eDirect); uvElements.Add(pUVElement); } for (int n = 0; n < positions.Length; n++) { mesh.SetControlPointAt(ToFbxVector4(positions[n]), n); if (normals != null) { elementNormals.GetDirectArray().Add(ToFbxVector4(normals[n])); } for (int uvIndex = 0; uvIndex < texCoords.Count; uvIndex++) { var texCoord = texCoords[uvIndex][n]; texCoord.Y = 1.0f - texCoord.Y; uvElements[uvIndex].GetDirectArray().Add(ToFbxVector2(texCoord)); } if (colors != null) { elementColors.GetDirectArray().Add(ToFbxColor(colors[n])); } if (tangents != null) { elementTangents.GetDirectArray().Add(ToFbxVector4(tangents[n])); } if (binormals != null) { elementBinormals.GetDirectArray().Add(ToFbxVector4(binormals[n])); } } if (normals != null) { mesh.GetLayer(0).SetNormals(elementNormals); } if (colors != null) { mesh.GetLayer(0).SetVertexColors(elementColors); } if (tangents != null) { mesh.GetLayer(0).SetTangents(elementTangents); } if (binormals != null) { mesh.GetLayer(0).SetBinormals(elementBinormals); } int polygonCount = indices.Length / 3; for (int i = 0; i < polygonCount; i++) { mesh.BeginPolygon(-1, -1, -1, false); for (int j = 0; j < 3; j++) { int currentIndex = i * 3 + j; int vertexIndex = indices[currentIndex]; mesh.AddPolygon(vertexIndex); } mesh.EndPolygon(); } var node = FbxNode.Create(scene, geometryName); node.SetNodeAttribute(mesh); scene.GetRootNode().AddChild(mesh.GetNode()); } //save exporter = FbxExporter.Create(manager, ""); if (!exporter.Initialize(realFileName, -1, manager.GetIOSettings())) { error = "Can't initialize FBX exporter."; return(false); } if (!exporter.Export(scene)) { error = "Export to FBX failed."; return(false); } } finally { try { scene?.Destroy(); } catch { } try { exporter?.Destroy(); } catch { } try { setting?.Destroy(); } catch { } try { manager?.Destroy(); } catch { } } foreach (var op in operations) { op.DisposeBuffers(); } error = ""; return(true); }
void Run() { FbxManager manager = FbxManager.Create(); FbxIOSettings setting = FbxIOSettings.Create(manager, "IOSRoot"); //fbxiosettingspath.h //PostProcessSteps.CalculateTangentSpace = #define EXP_TANGENTSPACE EXP_GEOMETRY "|" IOSN_TANGENTS_BINORMALS //PostProcessSteps.JoinIdenticalVertices = #define IOSN_DXF_WELD_VERTICES "WeldVertices" //PostProcessSteps.Triangulate = #define IOSN_TRIANGULATE "Triangulate" //PostProcessSteps.RemoveComponent = //PostProcessSteps.GenerateSmoothNormals = //setting.AddProperty() setting.SetBoolProp("Import|AdvOptGrp|Dxf|WeldVertices", true); setting.SetBoolProp("Triangulate", true); manager.SetIOSettings(setting); FbxImporter impoter = FbxImporter.Create(manager, ""); bool status = impoter.Initialize(@"1.fbx", -1, setting); Log.Info(status); if (!status) { return; } FbxScene scene = FbxScene.Create(manager, "scene1"); status = impoter.Import(scene); Log.Info(status); int numTrack = scene.GetSrcObjectCount(FbxCriteria.ObjectType(FbxAnimStack.ClassId)); Log.Info("num stack " + numTrack); FbxObject obj = scene.GetSrcObject(FbxCriteria.ObjectType(FbxAnimStack.ClassId), 0); FbxAnimStack stack = FbxAnimStack.Cast(obj); if (stack == null) { Log.Error("can not get anim stack!"); return; } FbxCriteria cri = FbxCriteria.ObjectTypeStrict(FbxAnimLayer.ClassId); int numLayer = stack.GetMemberCount(cri); Log.Info("anim layer count : " + numLayer); FbxAnimLayer layer = null; if (numLayer > 0) { FbxObject layerobj = stack.GetMember(cri, 0); layer = FbxAnimLayer.Cast(layerobj); if (layer == null) { Log.Error("anim layer is null!"); return; } Log.Info("anim layer name " + layer.GetName()); } Log.Info("node count " + scene.GetNodeCount()); for (int i = 0; i < scene.GetNodeCount(); i++) { FbxNode node = scene.GetNode(i); Log.Info("node " + i + " " + node.GetName() + " ChildCount:" + node.GetChildCount()); //---------------- //node.LclTranslation.IsAnimated //---------------- //ToDo : if (node.LclTranslation.IsAnimated(layer)) { FbxAnimCurveNode curveNode = node.LclTranslation.GetCurveNode(layer); if (curveNode == null) { Log.Error("curve node is null"); } else { for (int c = 0; c < curveNode.GetCurveCount(0); c++) { FbxAnimCurve curve = curveNode.GetCurve(0, (uint)c); if (curve != null) { Log.Info("curve " + curve.GetName()); Log.Info("key count " + curve.KeyGetCount()); FbxAnimCurveKey key = curve.KeyGet(0); FbxTime t = key.GetTime(); Log.Info("key " + t.GetTimeString() + " value " + key.GetValue()); } } } } if (node.GetNodeAttribute() != null) { Log.Info("got attribu"); FbxNodeAttribute att = node.GetNodeAttribute(); PrintAttribute(manager, att); } else { Log.Info("att count " + node.GetNodeAttributeCount()); for (int j = 0; j < node.GetNodeAttributeCount(); j++) { FbxNodeAttribute att = node.GetNodeAttributeByIndex(j); PrintAttribute(manager, att); } } FbxVector4 rot = node.GetPostRotation(FbxNode.EPivotSet.eSourcePivot); FbxQuaternion q; } }
/// <summary> /// Export all the objects in the set. /// Return the number of objects in the set that we exported. /// </summary> public int ExportAll(IEnumerable <UnityEngine.Object> unityExportSet) { // Create the FBX manager using (var fbxManager = FbxManager.Create()) { // Configure the IO settings. fbxManager.SetIOSettings(FbxIOSettings.Create(fbxManager, Globals.IOSROOT)); // Create the exporter var fbxExporter = FbxExporter.Create(fbxManager, "Exporter"); // Initialize the exporter. int fileFormat = fbxManager.GetIOPluginRegistry().FindWriterIDByDescription("FBX ascii (*.fbx)"); bool status = fbxExporter.Initialize(LastFilePath, fileFormat, fbxManager.GetIOSettings()); // Check that initialization of the fbxExporter was successful if (!status) { return(0); } // By default, FBX exports in its most recent version. You might want to specify // an older version for compatibility with other applications. fbxExporter.SetFileExportVersion("FBX201400"); // Create a scene var fbxScene = FbxScene.Create(fbxManager, "Scene"); // create scene info FbxDocumentInfo fbxSceneInfo = FbxDocumentInfo.Create(fbxManager, "SceneInfo"); // set some scene info values fbxSceneInfo.mTitle = Title; fbxSceneInfo.mSubject = Subject; fbxSceneInfo.mAuthor = "Unity Technologies"; fbxSceneInfo.mRevision = "1.0"; fbxSceneInfo.mKeywords = Keywords; fbxSceneInfo.mComment = Comments; fbxScene.SetSceneInfo(fbxSceneInfo); FbxNode fbxRootNode = fbxScene.GetRootNode(); // export set of object foreach (var obj in unityExportSet) { var unityGo = GetGameObject(obj); if (unityGo) { this.ExportComponents(unityGo, fbxScene, fbxRootNode); } } // Export the scene to the file. status = fbxExporter.Export(fbxScene); // cleanup fbxScene.Destroy(); fbxExporter.Destroy(); if (!status) { return(0); } } return(NumNodes); }
/// <summary> /// Export all the objects in the set. /// Return the number of objects in the set that we exported. /// </summary> public int ExportAll(IEnumerable <UnityEngine.Object> unityExportSet) { // Create the FBX manager; it cleans everything up at the end of the using block. using (var fbxManager = FbxManager.Create()) { // Configure the IO settings. fbxManager.SetIOSettings(FbxIOSettings.Create(fbxManager, Globals.IOSROOT)); // Create the exporter var fbxExporter = FbxExporter.Create(fbxManager, "Exporter"); // Initialize the exporter. int fileFormat = fbxManager.GetIOPluginRegistry().FindWriterIDByDescription("FBX ascii (*.fbx)"); bool status = fbxExporter.Initialize(LastFilePath, fileFormat, fbxManager.GetIOSettings()); // Check that initialization of the fbxExporter was successful if (!status) { return(0); } // Set compatibility to 2014 fbxExporter.SetFileExportVersion("FBX201400"); // Create a scene var fbxScene = FbxScene.Create(fbxManager, "Scene"); // create scene info FbxDocumentInfo fbxSceneInfo = FbxDocumentInfo.Create(fbxManager, "SceneInfo"); // set some scene info values fbxSceneInfo.mTitle = Title; fbxSceneInfo.mSubject = Subject; fbxSceneInfo.mAuthor = "Unity Technologies"; fbxSceneInfo.mRevision = "1.0"; fbxSceneInfo.mKeywords = Keywords; fbxSceneInfo.mComment = Comments; fbxScene.SetSceneInfo(fbxSceneInfo); var fbxSettings = fbxScene.GetGlobalSettings(); fbxSettings.SetSystemUnit(FbxSystemUnit.m); // Unity unit is meters // While Unity is Y-up, Z-forward, left-handed, the FBX SDK can't convert to // right-handed. So we just lie and say that we're right-handed like Maya. fbxSettings.SetAxisSystem(FbxAxisSystem.MayaYUp); FbxNode fbxRootNode = fbxScene.GetRootNode(); // export set of objects foreach (var obj in unityExportSet) { var unityGo = GetGameObject(obj); if (!unityGo) { continue; } ExportComponents(unityGo, fbxScene, fbxRootNode); } // Export the scene to the file. status = fbxExporter.Export(fbxScene); return(status == true ? NumNodes : 0); } }
/// <summary> /// Export all the objects in the set. /// Return the number of objects in the set that we exported. /// </summary> public int ExportAll(IEnumerable <UnityEngine.Object> unityExportSet) { // Create the FBX manager using (var fbxManager = FbxManager.Create()) { // Configure the IO settings. fbxManager.SetIOSettings(FbxIOSettings.Create(fbxManager, Globals.IOSROOT)); // Create the exporter var fbxExporter = FbxExporter.Create(fbxManager, "Exporter"); // Initialize the exporter. int fileFormat = fbxManager.GetIOPluginRegistry().FindWriterIDByDescription("FBX ascii (*.fbx)"); bool status = fbxExporter.Initialize(LastFilePath, fileFormat, fbxManager.GetIOSettings()); // Check that initialization of the fbxExporter was successful if (!status) { return(0); } // By default, FBX exports in its most recent version. You might want to specify // an older version for compatibility with other applications. fbxExporter.SetFileExportVersion("FBX201400"); // Create a scene var fbxScene = FbxScene.Create(fbxManager, "Scene"); // create scene info FbxDocumentInfo fbxSceneInfo = FbxDocumentInfo.Create(fbxManager, "SceneInfo"); // set some scene info values fbxSceneInfo.mTitle = Title; fbxSceneInfo.mSubject = Subject; fbxSceneInfo.mAuthor = "Unity Technologies"; fbxSceneInfo.mRevision = "1.0"; fbxSceneInfo.mKeywords = Keywords; fbxSceneInfo.mComment = Comments; fbxScene.SetSceneInfo(fbxSceneInfo); var fbxSettings = fbxScene.GetGlobalSettings(); /// Set system units : Unity unit is meters fbxSettings.SetSystemUnit(FbxSystemUnit.m); /// Set axis system : Unity Y Up, Z Forward, X Right (left-handed with odd parity) /// The Maya axis system has Y up, Z forward, X Left (right handed system with odd parity). /// We export right-handed for Maya because ConvertScene can't switch handedness: /// https://forums.autodesk.com/t5/fbx-forum/get-confused-with-fbxaxissystem-convertscene/td-p/4265472 /// NOTE: models will flipped about the -X axis. fbxSettings.SetAxisSystem(FbxAxisSystem.MayaYUp); FbxNode fbxRootNode = fbxScene.GetRootNode(); // export set of object foreach (var obj in unityExportSet) { var unityGo = GetGameObject(obj); if (unityGo) { this.ExportComponents(unityGo, fbxScene, fbxRootNode); } } // Export animations ExportAllAnimation(fbxScene); // Set the scene's ambient lighting. SetAmbientLighting(fbxScene); // Export the scene to the file. status = fbxExporter.Export(fbxScene); // cleanup fbxScene.Destroy(); fbxExporter.Destroy(); if (!status) { return(0); } } return(NumNodes); }
public virtual void TestBasics() { using (var iobase = CreateObject()) { iobase.Initialize("/no/such/file.fbx"); } using (var iobase = CreateObject()) { iobase.Initialize("/no/such/file.fbx", -1); } using (var iobase = CreateObject()) { iobase.Initialize("/no/such/file.fbx", -1, FbxIOSettings.Create(Manager, "")); } using (var iobase = CreateObject()) { iobase.Initialize("/no/such/file.fbx", -1, null); } using (var iobase = CreateObject()) { Assert.IsFalse(iobase.GetStatus().Error()); iobase.Initialize("/no/such/file.fbx"); Assert.AreEqual("/no/such/file.fbx", iobase.GetFileName()); } }
//static bool ContainsMeshesRecursive( Node node ) //{ // if( node.HasMeshes ) // return true; // foreach( var child in node.Children ) // { // if( ContainsMeshesRecursive( child ) ) // return true; // } // return false; //} public static void DoImport(Settings settings, out string error) { error = "(NO ERROR MESSAGE)"; LoadNativeLibrary(); FbxManager manager = null; FbxIOSettings setting = null; FbxImporter importer = null; FbxScene scene = null; try { manager = FbxManager.Create(); setting = FbxIOSettings.Create(manager, "IOSRoot"); manager.SetIOSettings(setting); importer = FbxImporter.Create(manager, ""); var realFileName = VirtualPathUtility.GetRealPathByVirtual(settings.virtualFileName); //VirtualFileStream stream = null; //ToDo : FromStream bool status; if (!string.IsNullOrEmpty(realFileName) && File.Exists(realFileName)) { status = importer.Initialize(realFileName, -1, setting); } else { error = "File is not exists."; return; //throw new NotImplementedException(); //ToDo : .... //stream = VirtualFile.Open( settings.virtualFileName ); //FbxStream fbxStream = null; //SWIGTYPE_p_void streamData = null; //status = impoter.Initialize( fbxStream, streamData, -1, setting ); } if (!status) { return; } scene = FbxScene.Create(manager, "scene1"); status = importer.Import(scene); if (!status) { return; } error = ""; var importContext = new ImportContext(); importContext.manager = manager; importContext.scene = scene; importContext.settings = settings; importContext.directoryName = Path.GetDirectoryName(settings.virtualFileName); ImportScene(importContext); ////create meshes (Scene mode) //if( settings.component.Mode.Value == Component_Import3D.ModeEnum.Scene /*&& scene.HasMeshes && scene.MeshCount != 0 */) //{ // importContext.meshesGroup = settings.component.GetComponentByName( "Meshes" ) as Component_Mesh; // if( importContext.meshesGroup == null ) // { // importContext.meshesGroup = settings.component.CreateComponent<Component>( -1, false ); // importContext.meshesGroup.Name = "Meshes"; // } // else // importContext.meshesGroup.Enabled = false; //} ////enable groups //if( importContext.meshesGroup != null ) // importContext.meshesGroup.Enabled = true; //if( importContext.sceneObjectsGroup != null ) // importContext.sceneObjectsGroup.Enabled = true; //stream?.Dispose(); } finally { //Особенности удаления. //Создается через функцию: impoter = FbxImporter.Create(manager, ""); //В таких случаях(создание не через конструктор, а возврат указателя из функции) SWIG задает флажок что объект не владеет ссылкой, поэтому Dispose ничего не делает. //Хотя в SWIG можно задать в конфигурации: %newobject FbxImporter::Create; Тогда объект будет владеть ссылкой. Но все равно в С++ наследники FbxObject не имеют public destructor //поэтому в Dispose вставлен: throw new MethodAccessException("C++ destructor does not have public access"). Поэтому удалять только через Destroy. try { scene?.Destroy(); } catch { } try { importer?.Destroy(); } catch { } try { setting?.Destroy(); } catch { } try { manager?.Destroy(); } catch { } } }
public static void PackAnimations(string path, GameObject meshObject) { List <AnimationClip> clips = new List <AnimationClip>(); List <ModelImporterClipAnimation> clipDatas = new List <ModelImporterClipAnimation>(); var info = new DirectoryInfo(path); var fileInfo = info.GetFiles(); foreach (var file in fileInfo) { if (file.Extension == ".fbx" || file.Extension == ".FBX") { string relativePath = path + "/" + file.Name; AnimationClip clip = AssetDatabase.LoadAssetAtPath <AnimationClip>(relativePath); //Debug.Log(relativePath); if (clip != null) { clips.Add(clip); } if (alwaysFalse) { ModelImporter importer = AssetDatabase.LoadAssetAtPath <ModelImporter>(relativePath); if (importer != null) { clipDatas.AddRange(importer.clipAnimations); } } } } Debug.Log(clips.Count); //---getting all curves/keyframes--- if (alwaysFalse) { AnimationClip collectiveClip = new AnimationClip(); Dictionary <string, Container> collectiveCurves = new Dictionary <string, Container>(); float timeOffset = 0f; float maxTime = 0f; for (int i = 0; i < clips.Count; i++) { var bindings = AnimationUtility.GetCurveBindings(clips[i]); Debug.Log("Clip[i] Count of bindings: " + bindings.Length); foreach (var binding in bindings) { Debug.Log(binding.propertyName + ": Path: " + binding.path); if (!collectiveCurves.ContainsKey(binding.propertyName)) { collectiveCurves.Add(binding.propertyName, new Container(binding.type, binding.path)); } var curveToWriteTo = collectiveCurves[binding.propertyName]; var curveToReadFrom = AnimationUtility.GetEditorCurve(clips[i], binding); //Debug.Log("Keys: " + curve.keys.Length); maxTime = Mathf.Max(maxTime, curveToReadFrom.GetLastKey().time); for (int frame = 0; frame < curveToReadFrom.length; frame++) { var keyFrame = curveToReadFrom.keys[frame]; keyFrame.time += timeOffset; curveToWriteTo.curve.AddKey(keyFrame); } //collectiveClip.SetCurve() } timeOffset += maxTime; } foreach (var kvp in collectiveCurves) { collectiveClip.SetCurve(kvp.Value.path, kvp.Value.typeOf, kvp.Key, kvp.Value.curve); } } //---instantiating go and adding animation component GameObject clone = Instantiate(meshObject); clone.name = meshObject.name; if (alwaysFalse) { var anim = clone.AddComponent <Animation>(); AnimationUtility.SetAnimationClips(anim, clips.ToArray()); } if (true) { var anim = clone.GetComponent <Animator>(); if (!anim) { anim = clone.AddComponent <Animator>(); } var controller = AnimatorController.CreateAnimatorControllerAtPath(path + "/temp.controller"); foreach (var clip in clips) { controller.AddMotion(clip); } anim.runtimeAnimatorController = controller; } if (alwaysFalse) { var fbxManager = FbxManager.Create(); var settings = fbxManager.GetIOSettings(); var exporter = FbxExporter.Create(fbxManager, "name"); //exporter. } if (true) { ModelExporter.ExportObject(path + "/combined.fbx", clone); } if (alwaysFalse) { using (FbxManager fbxManager = FbxManager.Create()) { // configure IO settings. var settings = FbxIOSettings.Create(fbxManager, Globals.IOSROOT); fbxManager.SetIOSettings(settings); // Export the scene using (FbxExporter exporter = FbxExporter.Create(fbxManager, "myExporter")) { // Initialize the exporter. bool status = exporter.Initialize("combindObjects", -1, fbxManager.GetIOSettings()); // Create a new scene to export FbxScene scene = FbxScene.Create(fbxManager, "myScene"); //FbxObject obj = FbxObject.Create(fbxManager, "combinedThings"); // Export the scene to the file. exporter.Export(scene); } } } //AssetDatabase.CreateAsset(collectiveClip, path + "/combined.anim"); //AssetDatabase.SaveAssets(); //Animation newAnimation = GetComponent<Animation>(); //Debug.Log(newAnimation.name); //AnimationUtility.SetAnimationClips(newAnimation, clips.ToArray()); //AssetDatabase.CreateAsset(newAnimation, path + "/combined.fbx"); //AssetDatabase.CreateAsset(clips, path + "/testasset.fbx"); }
public void TestWriteEmptyFbxFile() { /* * Runtime test that writes an fbx scene file in the directory where the * player is (temp folder while running tests) */ // Build the fbx scene file path // (player/player_data/emptySceneFromRuntime.fbx) string fbxFilePath = Application.dataPath; fbxFilePath = Path.Combine(fbxFilePath, "emptySceneFromRuntime.fbx"); // The file should not exist. We are running the test from the Test // Runner, which should always create a new player with its own fresh // data directory FileInfo fbxFileInfo = new FileInfo(fbxFilePath); Assert.That(!fbxFileInfo.Exists, string.Format("\"{0}\" already exists but the test did not create it yet", fbxFilePath)); using (var fbxManager = FbxManager.Create()) { FbxIOSettings fbxIOSettings = FbxIOSettings.Create(fbxManager, Globals.IOSROOT); // Configure the IO settings. fbxManager.SetIOSettings(fbxIOSettings); // Create the exporter var fbxExporter = FbxExporter.Create(fbxManager, "Exporter"); // Initialize the exporter. int fileFormat = fbxManager.GetIOPluginRegistry().FindWriterIDByDescription("FBX ascii (*.fbx)"); bool status = fbxExporter.Initialize(fbxFilePath, fileFormat, fbxIOSettings); Assert.That(status, string.Format("failed to initialize exporter, reason:D {0}", fbxExporter.GetStatus().GetErrorString())); // Create a scene var fbxScene = FbxScene.Create(fbxManager, "Scene"); // create scene info FbxDocumentInfo fbxSceneInfo = FbxDocumentInfo.Create(fbxManager, "SceneInfo"); // set some scene info values fbxSceneInfo.mTitle = "emptySceneFromRuntime"; fbxSceneInfo.mSubject = "Exported from a Unity runtime while testing in play mode"; fbxSceneInfo.mAuthor = "Unity Technologies"; fbxSceneInfo.mRevision = "1.0"; fbxSceneInfo.mKeywords = "export fbx runtime player play mode"; fbxSceneInfo.mComment = "This is to test the capability of exporting from a Unity runtime, using the FBX SDK C# bindings"; fbxScene.SetSceneInfo(fbxSceneInfo); // Export the scene to the file. status = fbxExporter.Export(fbxScene); Assert.That(status, string.Format("Failed to export scene, reason: {0}", fbxExporter.GetStatus().GetErrorString())); // cleanup fbxScene.Destroy(); fbxExporter.Destroy(); } // Test that the file exists fbxFileInfo = new FileInfo(fbxFilePath); Assert.That(fbxFileInfo.Exists, string.Format("\"{0}\" was not created", fbxFilePath)); }
void Run() { FbxManager manager = FbxManager.Create(); FbxIOSettings setting = FbxIOSettings.Create(manager, "IOSRoot"); manager.SetIOSettings(setting); FbxImporter impoter = FbxImporter.Create(manager, ""); bool status = impoter.Initialize(@"D:\develop\FbxWrapper\1.fbx", -1, setting); Log.Info(status); if (!status) { return; } FbxScene scene = FbxScene.Create(manager, "scene1"); status = impoter.Import(scene); Log.Info(status); int numTrack = scene.GetSrcObjectCount(FbxAnimStack.ClassId); Log.Info("num stack " + numTrack); FbxObject obj = scene.GetSrcObject(FbxAnimStack.ClassId, 0); FbxAnimStack stack = FbxAnimStack.Cast(obj); if (stack == null) { Log.Error("can not get anim stack!"); return; } FbxCriteria cri = FbxCriteria.ObjectTypeStrict(FbxAnimLayer.ClassId); int numLayer = stack.GetMemberCount(cri); Log.Info("anim layer count : " + numLayer); FbxAnimLayer layer = null; if (numLayer > 0) { FbxObject layerobj = stack.GetMember(cri, 0); layer = FbxAnimLayer.Cast(layerobj); if (layer == null) { Log.Error("anim layer is null!"); return; } Log.Info("anim layer name " + layer.GetName()); } Log.Info("node count " + scene.GetNodeCount()); for (int i = 0; i < scene.GetNodeCount(); i++) { FbxNode node = scene.GetNode(i); Log.Info("node " + i + " " + node.GetName()); if (node.LclTranslation.IsAnimated(layer)) { FbxAnimCurveNode curveNode = node.LclTranslation.GetCurveNode(layer); if (curveNode == null) { Log.Error("curve node is null"); } else { for (int c = 0; c < curveNode.GetCurveCount(0); c++) { FbxAnimCurve curve = curveNode.GetCurve(0, (uint)c); if (curve != null) { Log.Info("curve " + curve.GetName()); Log.Info("key count " + curve.KeyGetCount()); FbxAnimCurveKey key = curve.KeyGet(0); FbxTime t = key.GetTime(); Log.Info("key " + t.GetTimeString() + " value " + key.GetValue()); } } } } if (node.GetNodeAttribute() != null) { Log.Info("got attribu"); FbxNodeAttribute att = node.GetNodeAttribute(); PrintAttribute(att); } else { Log.Info("att count " + node.GetNodeAttributeCount()); for (int j = 0; j < node.GetNodeAttributeCount(); j++) { FbxNodeAttribute att = node.GetNodeAttributeByIndex(j); PrintAttribute(att); } } FbxVector4 rot = node.GetPostRotation(FbxNode.EPivotSet.eSourcePivot); FbxQuaternion q; } }
/// <summary> /// Export all the objects in the set. /// Return the number of objects in the set that we exported. /// </summary> public int ExportAll(IEnumerable <UnityEngine.Object> unityExportSet) { // Create the FBX manager using (var fbxManager = FbxManager.Create()) { // Configure IO settings. fbxManager.SetIOSettings(FbxIOSettings.Create(fbxManager, Globals.IOSROOT)); // Create the exporter var fbxExporter = FbxExporter.Create(fbxManager, "Exporter"); // Initialize the exporter. int fileFormat = fbxManager.GetIOPluginRegistry().FindWriterIDByDescription("FBX ascii (*.fbx)"); bool status = fbxExporter.Initialize(LastFilePath, fileFormat, fbxManager.GetIOSettings()); // Check that initialization of the fbxExporter was successful if (!status) { return(0); } // By default, FBX exports in its most recent version. You might want to specify // an older version for compatibility with other applications. fbxExporter.SetFileExportVersion("FBX201400"); // Create a scene var fbxScene = FbxScene.Create(fbxManager, "Scene"); // create scene info FbxDocumentInfo fbxSceneInfo = FbxDocumentInfo.Create(fbxManager, "SceneInfo"); // set some scene info values fbxSceneInfo.mTitle = Title; fbxSceneInfo.mSubject = Subject; fbxSceneInfo.mAuthor = "Unity Technologies"; fbxSceneInfo.mRevision = "1.0"; fbxSceneInfo.mKeywords = Keywords; fbxSceneInfo.mComment = Comments; fbxScene.SetSceneInfo(fbxSceneInfo); var fbxSettings = fbxScene.GetGlobalSettings(); fbxSettings.SetSystemUnit(FbxSystemUnit.m); // Unity unit is meters // The Unity axis system has Y up, Z forward, X to the right. // Export as Maya axis system. fbxSettings.SetAxisSystem(FbxAxisSystem.MayaYUp); FbxNode fbxRootNode = fbxScene.GetRootNode(); // export set of objects foreach (var obj in unityExportSet) { var unityGo = GetGameObject(obj); if (unityGo) { var unityGoIOSettings = unityGo.GetComponent <FbxSharp.IOSettings> (); if (unityGoIOSettings) { if (unityGoIOSettings.SystemUnit == FbxSharp.SystemUnitType.m) { fbxSettings.SetSystemUnit(FbxSystemUnit.m); } if (unityGoIOSettings.AxisSystem == FbxSharp.AxisSystemType.Unity) { Debug.Log("setting unity axis system"); fbxSettings.SetAxisSystem(UnityAxisSystem); } } this.ExportComponents(unityGo, fbxScene, fbxRootNode); } } // Export the scene to the file. status = fbxExporter.Export(fbxScene); // cleanup fbxScene.Destroy(); fbxExporter.Destroy(); return(status == true ? NumNodes : 0); } }