Esempio n. 1
0
        public new static FbxExporter Create(FbxObject pContainer, string pName)
        {
            global::System.IntPtr cPtr = FbxWrapperNativePINVOKE.FbxExporter_Create__SWIG_1(FbxObject.getCPtr(pContainer), pName);
            FbxExporter           ret  = (cPtr == global::System.IntPtr.Zero) ? null : new FbxExporter(cPtr, false);

            return(ret);
        }
Esempio n. 2
0
            public static void Export(string path, IImported imported, bool eulerFilter, float filterPrecision,
                                      bool allNodes, bool skins, bool animation, bool blendShape, bool castToBone, float boneSize, float scaleFactor, int versionIndex, bool isAscii)
            {
                var file = new FileInfo(path);
                var dir  = file.Directory;

                if (!dir.Exists)
                {
                    dir.Create();
                }

                var currentDir = Directory.GetCurrentDirectory();

                Directory.SetCurrentDirectory(dir.FullName);

                var name = Path.GetFileName(path);

                using (var exporter = new FbxExporter(name, imported, allNodes, skins, castToBone, boneSize, scaleFactor, versionIndex, isAscii))
                {
                    exporter.Initialize();
                    exporter.ExportAll(blendShape, animation, eulerFilter, filterPrecision);
                }

                Directory.SetCurrentDirectory(currentDir);
            }
Esempio n. 3
0
        public new static FbxExporter Create(FbxManager pManager, string pName)
        {
            global::System.IntPtr cPtr = fbx_wrapperPINVOKE.FbxExporter_Create__SWIG_0(FbxManager.getCPtr(pManager), pName);
            FbxExporter           ret  = (cPtr == global::System.IntPtr.Zero) ? null : new FbxExporter(cPtr, false);

            return(ret);
        }
Esempio n. 4
0
    public void WriteToFile(string Filename)
    {
        int  Major, Minor, Revision;
        bool Status = true;

        int  FileFormat  = -1;
        bool bEmbedMedia = false;

        // Create an exporter.
        FbxExporter Exporter = FbxExporter.Create(SdkManager, "");

        // set file format
        // Write in fall back format if pEmbedMedia is true
        FileFormat = SdkManager.GetIOPluginRegistry().GetNativeWriterFormat();
        FbxIOSettings IOS_REF = SdkManager.GetIOSettings();

        // Set the export states. By default, the export states are always set to
        // true except for the option eEXPORT_TEXTURE_AS_EMBEDDED. The code below
        // shows how to change these states.


        IOS_REF.SetBoolProp(fbx_wrapper.EXP_FBX_MATERIAL, true);
        IOS_REF.SetBoolProp(fbx_wrapper.EXP_FBX_TEXTURE, true);
        IOS_REF.SetBoolProp(fbx_wrapper.EXP_FBX_EMBEDDED, bEmbedMedia);
        IOS_REF.SetBoolProp(fbx_wrapper.EXP_FBX_SHAPE, true);
        IOS_REF.SetBoolProp(fbx_wrapper.EXP_FBX_GOBO, true);
        IOS_REF.SetBoolProp(fbx_wrapper.EXP_FBX_ANIMATION, true);
        IOS_REF.SetBoolProp(fbx_wrapper.EXP_FBX_GLOBAL_SETTINGS, true);

        string CompatibilitySetting = fbx_wrapper.FBX_2013_00_COMPATIBLE;

        if (!Exporter.SetFileExportVersion(new FbxString(CompatibilitySetting), FbxSceneRenamer.ERenamingMode.eNone))
        {
            Debug.LogWarning("Call to KFbxExporter::SetFileExportVersion(FBX_2013_00_COMPATIBLE) to export 2013 fbx file format failed.\n");
        }

        //// Initialize the exporter by providing a filename.
        if (!Exporter.Initialize(Filename, FileFormat, SdkManager.GetIOSettings()))
        {
            Debug.LogWarning("Call to KFbxExporter::Initialize() failed.\n");
            string errorString = Exporter.GetStatus().GetErrorString();
            Debug.LogWarning("Error returned:" + errorString);
            return;
        }

        //FbxManager.GetFileFormatVersion(Major, Minor, Revision);

        // Export the scene.
        Status = Exporter.Export(Scene);

        if (!Status)
        {
            string errorString = Exporter.GetStatus().GetErrorString();
            Debug.LogWarning("Error returned:" + errorString);
        }
        Clear();

        return;
    }
Esempio n. 5
0
 public bool Equals(FbxExporter other)
 {
     if (object.ReferenceEquals(other, null))
     {
         return(false);
     }
     return(this.swigCPtr.Handle.Equals(other.swigCPtr.Handle));
 }
Esempio n. 6
0
            public static void OnExport()
            {
                try {
                    // Create the FBX manager
                    using (var fbxManager = FbxManager.Create())
                    {
                        var fbxScene = BuildScene(fbxManager);
                        if (fbxScene == null)
                        {
                            return;
                        }

                        // Create the exporter
                        var fbxExporter = FbxExporter.Create(fbxManager, "Exporter");

                        // Find a random temp file
                        var path     = "";
                        var attempts = 0;
                        do
                        {
                            path = System.IO.Path.Combine(System.IO.Path.GetTempPath(), System.IO.Path.GetRandomFileName() + ".fbx");
                            attempts++;
                        } while (System.IO.File.Exists(path) && attempts < 100);
                        if (attempts >= 100)
                        {
                            return;
                        }

                        // Initialize the exporter.
                        if (!fbxExporter.Initialize(path))
                        {
                            return;
                        }

                        // Set the progress callback.
                        fbxExporter.SetProgressCallback(ExportProgressCallback);

                        // Export the scene to the file.
                        if (!fbxExporter.Export(fbxScene))
                        {
                            if (fbxExporter.GetStatus().Error())
                            {
                                Debug.LogWarning("FBX Export failed: " + fbxExporter.GetStatus());
                            }
                            else
                            {
                                Debug.Log("FBX Export canceled by user.");
                            }
                        }
                    }
                } finally {
                    // You must clear the progress bar when you're done,
                    // otherwise it never goes away and many actions in Unity
                    // are blocked (e.g. you can't quit).
                    EditorUtility.ClearProgressBar();
                }
            }
    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();
        }
    }
Esempio n. 8
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())
                {
                    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);
                }
            }
Esempio n. 9
0
        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);
        }
Esempio n. 10
0
        public new static FbxExporter Create(FbxObject pContainer, string pName)
        {
            global::System.IntPtr cPtr = NativeMethods.FbxExporter_Create__SWIG_1(FbxObject.getCPtr(pContainer), pName);
            FbxExporter           ret  = (cPtr == global::System.IntPtr.Zero) ? null : new FbxExporter(cPtr, false);

            if (NativeMethods.SWIGPendingException.Pending)
            {
                throw NativeMethods.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Esempio n. 11
0
        public FbxWriter CreateWriter(FbxManager pManager, FbxExporter pExporter, int pPluginID)
        {
            global::System.IntPtr cPtr = FbxWrapperNativePINVOKE.FbxIOPluginRegistry_CreateWriter(swigCPtr, FbxManager.getCPtr(pManager), FbxExporter.getCPtr(pExporter), pPluginID);
            FbxWriter             ret  = (cPtr == global::System.IntPtr.Zero) ? null : new FbxWriter(cPtr, false);

            if (FbxWrapperNativePINVOKE.SWIGPendingException.Pending)
            {
                throw FbxWrapperNativePINVOKE.SWIGPendingException.Retrieve();
            }
            return(ret);
        }
Esempio n. 12
0
        public override void TestBasics()
        {
            base.TestBasics();

            using (FbxImporter newImporter = CreateObject("MyImporter"))
            {
                // import a null document.
                Assert.IsFalse(newImporter.Import(null));

                // set a callback function
                newImporter.SetProgressCallback(null);
                newImporter.SetProgressCallback((float a, string b) => true);
                newImporter.SetProgressCallback(null);
            }

            // Export an empty scene to a temp file, then import.
            var filename = GetRandomFile();

            try {
                using (var exporter = FbxExporter.Create(Manager, "exporter")) {
                    using (var scene = FbxScene.Create(Manager, "exported scene")) {
                        Assert.IsTrue(exporter.Initialize(filename));
                        Assert.IsTrue(exporter.Export(scene));
                    }
                }
                var scene_in = FbxScene.Create(Manager, "imported scene");
                using (var importer = FbxImporter.Create(Manager, "import")) {
                    Assert.IsTrue(importer.Initialize(filename));
                    Assert.IsTrue(importer.Import(scene_in));
                    Assert.IsTrue(importer.IsFBX());

                    int sdkMajor = -1, sdkMinor = -1, sdkRevision = -1;
                    FbxManager.GetFileFormatVersion(out sdkMajor, out sdkMinor, out sdkRevision);
                    int fileMajor = -1, fileMinor = -1, fileRevision = -1;
                    importer.GetFileVersion(out fileMajor, out fileMinor, out fileRevision);
                    Assert.AreNotSame(fileMajor, -1);
                    Assert.AreNotSame(fileMinor, -1);
                    Assert.AreNotSame(fileRevision, -1);
                    Assert.AreEqual(sdkMajor, fileMajor);
                    Assert.AreEqual(sdkMinor, fileMinor);
                    Assert.AreEqual(sdkRevision, fileRevision);

                    Assert.IsEmpty(importer.GetActiveAnimStackName());
                    Assert.AreEqual(importer.GetAnimStackCount(), 0);

                    // test GetFileHeaderInfo()
                    TestGetter(importer.GetFileHeaderInfo());
                    Assert.IsNotNull(importer.GetFileHeaderInfo());
                }
                // we actually don't care about the scene itself!
            } finally {
                System.IO.File.Delete(filename);
            }
        }
        public override void Export(ObjectSet model, string filePath)
        {
            if (filePath.EndsWith(".fbx", StringComparison.OrdinalIgnoreCase))
            {
                FbxExporter.ExportToFile(model, filePath);
            }

            else
            {
                base.Export(model, filePath);
            }
        }
Esempio n. 14
0
 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, "");
 }
Esempio n. 15
0
 public void Dispose()
 {
     if (m_exporter != null)
     {
         m_exporter.Destroy(); m_exporter = null;
     }
     if (m_ioSettings != null)
     {
         m_ioSettings.Destroy(); m_ioSettings = null;
     }
     if (m_manager != null)
     {
         m_manager.Destroy(); m_manager = null;
     }
 }
Esempio n. 16
0
        public static void SaveGameObjectAsFBX(GameObject go, string fileName)
        {
            if (!isInitialized)
            {
                Initialize();
            }
            FbxExporter.ExportOptions options = FbxExporter.ExportOptions.defaultValue;
            /// Make sure it is in meter.
            options.scale_factor = 100f;
            FbxExporter exporter = new FbxExporter(options);

            exporter.CreateScene(fileName);
            exporter.AddNode(go);
            var ret = exporter.Write(FBX_PATH + fileName + ".fbx", FbxExporter.Format.FbxBinary);

            exporter.Release();
        }
        protected void ExportScene(string fileName)
        {
            // Export the scene
            using (FbxExporter exporter = FbxExporter.Create(FbxManager, "myExporter")) {
                // Initialize the exporter.
                bool status = exporter.Initialize(fileName, -1, FbxManager.GetIOSettings());

                // Check that export status is True
                Assert.IsTrue(status);

                // Create a new scene so it can be populated by the imported file.
                FbxScene scene = CreateScene(FbxManager);

                CheckScene(scene);

                // Export the scene to the file.
                exporter.Export(scene);

                // Check if file exists
                Assert.IsTrue(File.Exists(fileName));
            }
        }
Esempio n. 18
0
    private bool DoExport(string path, GameObject[] objects, FbxExporter.Format format)
    {
        _save_mode = FbxExporter.ExportOptions.defaultValue;
        _exporter  = new FbxExporter(_save_mode);
        _exporter.CreateScene(System.IO.Path.GetFileName(path));

        foreach (var obj in objects)
        {
            _exporter.AddNode(obj);
        }

        if (_exporter.WriteAsync(path, format))
        {
            Debug.Log("Export started: " + path);
            return(true);
        }
        else
        {
            Debug.Log("Export failed: " + path);
            return(false);
        }
    }
        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");
        }
Esempio n. 20
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);
        }
    }
Esempio n. 21
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 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);
                }
            }
Esempio n. 22
0
 internal static global::System.Runtime.InteropServices.HandleRef getCPtr(FbxExporter obj)
 {
     return((obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr);
 }
Esempio n. 23
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);
            }
Esempio n. 24
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();
                    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);
                }
            }
Esempio n. 25
0
    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));
    }
Esempio n. 26
0
        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);
        }
Esempio n. 27
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; 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);
                }
            }
Esempio n. 28
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)
            {
                Verbose = true;

                // Create the FBX manager
                using (var fbxManager = FbxManager.Create())
                {
                    // Configure fbx IO settings.
                    fbxManager.SetIOSettings(FbxIOSettings.Create(fbxManager, Globals.IOSROOT));

                    // Export texture as embedded
                    fbxManager.GetIOSettings().SetBoolProp(Globals.EXP_FBX_EMBEDDED, true);

                    // 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");

                    // set up the scene info
                    FbxDocumentInfo fbxSceneInfo = FbxDocumentInfo.Create(fbxManager, "SceneInfo");
                    fbxSceneInfo.mTitle    = Title;
                    fbxSceneInfo.mSubject  = Subject;
                    fbxSceneInfo.mAuthor   = "Unity Technologies";
                    fbxSceneInfo.mRevision = "1.0";
                    fbxSceneInfo.mKeywords = Keywords;
                    fbxSceneInfo.mComment  = Comments;
                    fbxScene.SetSceneInfo(fbxSceneInfo);

                    // Set up the axes (Y up, Z forward, X to the right) and units (meters)
                    var fbxSettings = fbxScene.GetGlobalSettings();
                    fbxSettings.SetSystemUnit(FbxSystemUnit.m);

                    // The Unity axis system has Y up, Z forward, X to the right (left handed system with odd parity).
                    // The Maya axis system has Y up, Z forward, X to the left (right handed system with odd parity).
                    // We need to 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
                    fbxSettings.SetAxisSystem(FbxAxisSystem.MayaYUp);

                    // export set of object
                    FbxNode fbxRootNode = fbxScene.GetRootNode();
                    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();

                    return(status == true ? NumNodes : 0);
                }
            }
        protected override void Initialize()
        {
            AddExportHandler <ObjectSet>(filePath =>
            {
                if (filePath.EndsWith(".fbx", StringComparison.OrdinalIgnoreCase))
                {
                    Data.TryFixParentBoneInfos(SourceConfiguration?.BoneDatabase);
                    FbxExporter.ExportToFile(Data, filePath);
                }

                else
                {
                    var configuration = ConfigurationList.Instance.CurrentConfiguration;

                    var objectDatabase  = configuration?.ObjectDatabase;
                    var textureDatabase = configuration?.TextureDatabase;
                    var boneDatabase    = configuration?.BoneDatabase;

                    Data.Save(filePath, objectDatabase, textureDatabase, boneDatabase);
                }
            });
            AddExportHandler <Scene>(filePath =>
            {
                Data.TryFixParentBoneInfos(SourceConfiguration?.BoneDatabase);
                AssimpExporter.ExportToFile(Data, filePath);
            });
            AddReplaceHandler <ObjectSet>(filePath =>
            {
                var configuration = ConfigurationList.Instance.CurrentConfiguration;

                var objectDatabase  = configuration?.ObjectDatabase;
                var textureDatabase = configuration?.TextureDatabase;

                var objectSet = new ObjectSet();
                objectSet.Load(filePath, objectDatabase, textureDatabase);
                return(objectSet);
            });
            AddReplaceHandler <Scene>(filePath =>
            {
                if (Data.Objects.Count > 1)
                {
                    return(AssimpImporter.ImportFromFile(filePath));
                }

                return(AssimpImporter.ImportFromFileWithSingleObject(filePath));
            });

            AddCustomHandler("Copy object set info to clipboard", () =>
            {
                uint objectSetId = 39;
                uint objectId    = 0xFFFFFFFF;

                var objectDatabase = ConfigurationList.Instance.CurrentConfiguration?.ObjectDatabase;

                if (objectDatabase != null && objectDatabase.ObjectSets.Count > 0)
                {
                    objectSetId = objectDatabase.ObjectSets.Max(x => x.Id) + 1;
                    objectId    = objectDatabase.ObjectSets.SelectMany(x => x.Objects).Max(x => x.Id) + 1;
                }

                else
                {
                    using (var inputDialog = new InputDialog
                    {
                        WindowTitle = "Enter base id for objects",
                        Input = Math.Max(0, Data.Objects.Max(x => x.Id) + 1).ToString()
                    })
                    {
                        while (inputDialog.ShowDialog() == DialogResult.OK)
                        {
                            bool result = uint.TryParse(inputDialog.Input, out objectId);

                            if (!result || objectId == 0xFFFFFFFF)
                            {
                                MessageBox.Show("Please enter a correct id number.", Program.Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
                            }

                            else
                            {
                                break;
                            }
                        }
                    }
                }

                if (objectId == 0xFFFFFFFF)
                {
                    return;
                }

                string baseName = Path.ChangeExtension(Name, null);
                if (Data.Format.IsClassic() && baseName.EndsWith("_obj", StringComparison.OrdinalIgnoreCase))
                {
                    baseName = baseName.Substring(0, baseName.Length - 4);
                }

                var objectSetInfo = new ObjectSetInfo
                {
                    Name            = baseName.ToUpperInvariant(),
                    Id              = objectSetId,
                    FileName        = Name,
                    TextureFileName = baseName + (Data.Format.IsClassic() ? "_tex.bin" : ".txd"),
                    ArchiveFileName = Parent is FarcArchiveNode ? Parent.Name : baseName + ".farc"
                };

                foreach (var obj in Data.Objects)
                {
                    objectSetInfo.Objects.Add(new ObjectInfo
                    {
                        Id   = objectId++,
                        Name = obj.Name.ToUpperInvariant()
                    });
                }

                using (var stringWriter = new StringWriter())
                    using (var xmlWriter = XmlWriter.Create(stringWriter,
                                                            new XmlWriterSettings {
                        Indent = true, OmitXmlDeclaration = true
                    }))
                    {
                        sObjectSetInfoSerializer.Serialize(xmlWriter, objectSetInfo,
                                                           new XmlSerializerNamespaces(new[] { XmlQualifiedName.Empty }));

                        Clipboard.SetText(stringWriter.ToString());
                    }
            });

            AddCustomHandlerSeparator();

            AddDirtyCustomHandler("Combine all objects into one", () =>
            {
                if (Data.Objects.Count <= 1)
                {
                    return(false);
                }

                var combinedObject = new Object {
                    Name = "Combined object"
                };
                var indexMap = new Dictionary <int, int>();

                foreach (var obj in Data.Objects)
                {
                    if (obj.Skin != null)
                    {
                        if (combinedObject.Skin == null)
                        {
                            combinedObject.Skin = new Skin();
                            combinedObject.Skin.Bones.AddRange(obj.Skin.Bones);
                        }

                        else
                        {
                            for (int i = 0; i < obj.Skin.Bones.Count; i++)
                            {
                                var bone      = obj.Skin.Bones[i];
                                int boneIndex = combinedObject.Skin.Bones.FindIndex(
                                    x => x.Name.Equals(bone.Name, StringComparison.OrdinalIgnoreCase));

                                if (boneIndex == -1)
                                {
                                    indexMap[i] = combinedObject.Skin.Bones.Count;
                                    combinedObject.Skin.Bones.Add(bone);
                                }

                                else
                                {
                                    indexMap[i] = boneIndex;
                                }
                            }

                            foreach (var subMesh in obj.Meshes.SelectMany(x => x.SubMeshes))
                            {
                                if (subMesh.BoneIndices?.Length >= 1)
                                {
                                    for (int i = 0; i < subMesh.BoneIndices.Length; i++)
                                    {
                                        subMesh.BoneIndices[i] = ( ushort )indexMap[subMesh.BoneIndices[i]];
                                    }
                                }
                            }
                        }

                        combinedObject.Skin.Blocks.AddRange(obj.Skin.Blocks);
                    }

                    foreach (var subMesh in obj.Meshes.SelectMany(x => x.SubMeshes))
                    {
                        subMesh.MaterialIndex += ( uint )combinedObject.Materials.Count;
                    }

                    combinedObject.Meshes.AddRange(obj.Meshes);
                    combinedObject.Materials.AddRange(obj.Materials);
                }

                Data.Objects.Clear();
                Data.Objects.Add(combinedObject);

                return(true);
            }, Keys.None, CustomHandlerFlags.Repopulate | CustomHandlerFlags.ClearMementos);

            AddCustomHandlerSeparator();

            AddDirtyCustomHandler("Convert all bones to osage", () =>
            {
                foreach (var obj in Data.Objects)
                {
                    var movingBone = obj.Skin?.Bones.FirstOrDefault(x => x.Name == "kl_mune_b_wj");
                    if (movingBone == null)
                    {
                        continue;
                    }

                    var nameMap       = new Dictionary <string, string>();
                    var stringBuilder = new StringBuilder();

                    foreach (var bone in obj.Skin.Bones)
                    {
                        // Ignore bones if they are already OSG or EXP.
                        // Also ignore the moving bone and its parents.

                        // Ignore j_kao_wj for now because it f***s miku's headphones up
                        if (bone.Name == "j_kao_wj")
                        {
                            continue;
                        }

                        var boneToCompare = movingBone;

                        do
                        {
                            if (boneToCompare == bone)
                            {
                                break;
                            }

                            boneToCompare = boneToCompare.Parent;
                        } while (boneToCompare != null);

                        if (boneToCompare == bone)
                        {
                            continue;
                        }

                        if (obj.Skin.Blocks.Any(x =>
                        {
                            switch (x)
                            {
                            case OsageBlock osgBlock:
                                return(osgBlock.Nodes.Any(y => y.Name == bone.Name));

                            case ExpressionBlock expBlock:
                                return(expBlock.Name == bone.Name);

                            default:
                                return(false);
                            }
                        }))
                        {
                            continue;
                        }

                        if (bone.Parent == null)
                        {
                            bone.Parent = movingBone;
                        }

                        Matrix4x4.Invert(bone.InverseBindPoseMatrix, out var bindPoseMatrix);
                        var matrix = Matrix4x4.Multiply(bindPoseMatrix, bone.Parent.InverseBindPoseMatrix);

                        Matrix4x4.Decompose(matrix, out var scale, out var rotation, out var translation);

                        rotation = Quaternion.Normalize(rotation);

                        string newName = bone.Name;

                        if (newName.EndsWith("_wj", StringComparison.OrdinalIgnoreCase))
                        {
                            newName = newName.Remove(newName.Length - 3);
                        }

                        newName += "_ragdoll";

                        nameMap.Add(bone.Name, newName);

                        bone.Name = newName;

                        string baseName = newName;

                        var osageBlock = new OsageBlock
                        {
                            ExternalName = $"c_{baseName}_osg",
                            Name         = $"e_{baseName}",
                            ParentName   = bone.Parent.Name,
                            Position     = translation,
                            Rotation     = rotation.ToEulerAngles(),
                            Scale        = scale
                        };

                        osageBlock.Nodes.Add(new OsageNode {
                            Name = bone.Name, Length = 0.08f
                        });
                        obj.Skin.Blocks.Add(osageBlock);

                        stringBuilder.AppendFormat(
                            "{0}.node.0.coli_r=0.030000\r\n" +
                            "{0}.node.0.hinge_ymax=179.000000\r\n" +
                            "{0}.node.0.hinge_ymin=-179.000000\r\n" +
                            "{0}.node.0.hinge_zmax=179.000000\r\n" +
                            "{0}.node.0.hinge_zmin=-179.000000\r\n" +
                            "{0}.node.0.inertial_cancel=1.000000\r\n" +
                            "{0}.node.0.weight=3.000000\r\n" +
                            "{0}.node.length=1\r\n" +
                            "{0}.root.force=0.010000\r\n" +
                            "{0}.root.force_gain=0.300000\r\n" +
                            "{0}.root.friction=1.000000\r\n" +
                            "{0}.root.init_rot_y=0.000000\r\n" +
                            "{0}.root.init_rot_z=0.000000\r\n" +
                            "{0}.root.rot_y=0.000000\r\n" +
                            "{0}.root.rot_z=0.000000\r\n" +
                            "{0}.root.stiffness=0.100000\r\n" +
                            "{0}.root.wind_afc=0.500000\r\n",
                            osageBlock.ExternalName);
                    }
Esempio n. 30
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);

                    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);
            }