예제 #1
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;
    }
예제 #2
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);
        }
        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));
            }
        }
예제 #4
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);
        }
    }
예제 #5
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);
        }
        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");
        }