ReportProgress() public static method

public static ReportProgress ( float value, string message = "" ) : void
value float
message string
return void
示例#1
0
        public void Bake()
        {
            // Validate Project Platform
            if (!Unity3D2Babylon.Tools.ValidateProjectPlatform())
            {
                return;
            }

            try
            {
                atlasMaterial  = null;
                mainTextures   = null;
                bumpTextures   = null;
                bumpFilename   = String.Empty;
                hasBumpTexture = false;

                CreateTextureAtlas();
                PackTextureAtlasNormals();

                ExporterWindow.ReportProgress(1, "Saving assets to disk...");
                AssetDatabase.SaveAssets();
            }
            catch (Exception ex)
            {
                UnityEngine.Debug.LogException(ex);
            }
            finally
            {
                ExporterWindow.ReportProgress(1, "Refresing assets database...");
                AssetDatabase.Refresh();
                ExporterWindow.ReportProgress(1, "Texture atlas baking complete.");
                EditorUtility.ClearProgressBar();
            }
            this.Close();
        }
        public void LoadHeightmap()
        {
            // Validate Project Platform
            if (!Unity3D2Babylon.Tools.ValidateProjectPlatform())
            {
                return;
            }
            string filename = EditorUtility.OpenFilePanelWithFilters("Select Heightmap Image", String.Empty, IMAGE_FORMATS);

            if (String.IsNullOrEmpty(filename))
            {
                return;
            }
            // ..
            ResetHeightmap();
            heightmapFile  = Tools.GetNativePath(filename);
            heightmapLabel = Path.GetFileName(heightmapFile);
            // ..
            ExporterWindow.ReportProgress(1, "Loading heightmap image data... This may take a while.");
            string heightmapExt = Path.GetExtension(heightmapFile);
            bool   heightmapRaw = (heightmapExt.Equals(".raw", StringComparison.OrdinalIgnoreCase) || heightmapExt.Equals(".r16", StringComparison.OrdinalIgnoreCase));

            try {
                try {
                    bool    readResult       = false;
                    int     readWidth        = 0;
                    int     readHeight       = 0;
                    int     readBitsPerPixel = 0;
                    Color[] pixels           = Tools.ReadRawHeightmapImage(heightmapFile, heightmapRaw, ref readResult, ref readWidth, ref readHeight, ref readBitsPerPixel);
                    if (readResult == true && pixels != null)
                    {
                        int resolution = (int)(Math.Sqrt(pixels.Length));
                        exportResolution    = resolution;
                        heightmapResolution = resolution;
                        // ..
                        Texture2D workTexture = new Texture2D(resolution, resolution, TextureFormat.RGBAFloat, false);
                        workTexture.SetPixels(pixels);
                        workTexture.Apply();
                        workTexture.MakeGrayscale();
                        // ..
                        if (heightmapRaw)
                        {
                            workTexture = Tools.FlipTexture(workTexture);
                        }
                        heightmapTexture = workTexture;
                    }
                } catch (Exception ex) {
                    UnityEngine.Debug.LogException(ex);
                }
            }
            catch (Exception ex)
            {
                UnityEngine.Debug.LogException(ex);
            }
            finally
            {
                ExporterWindow.ReportProgress(1, "Heightmap conversion complete.");
                EditorUtility.ClearProgressBar();
            }
        }
示例#3
0
        private BabylonSkeleton ConvertUnitySkeletonToBabylon(Transform[] bones, Matrix4x4[] bindPoses, Transform transform, GameObject gameObject, float progress)
        {
            ExporterWindow.ReportProgress(progress, "Exporting Skeleton: " + gameObject.name);
            BabylonSkeleton babylonSkeleton = new BabylonSkeleton();

            babylonSkeleton.name = gameObject.name;
            babylonSkeleton.id   = Math.Abs(GetID(transform.gameObject).GetHashCode());
            babylonSkeleton.needInitialSkinMatrix = false;

            // Prefilled to keep order and track parents.
            var transformToBoneMap = new Dictionary <Transform, BabylonBone>();

            for (var i = 0; i < bones.Length; i++)
            {
                var unityBone = bones[i];
                ExporterWindow.ReportProgress(progress, "Exporting bone: " + unityBone.name + " at index " + i);

                var babylonBone = new BabylonBone();
                babylonBone.name  = unityBone.name;
                babylonBone.index = i;

                transformToBoneMap.Add(unityBone, babylonBone);
            }

            // Attaches Matrix and parent.
            for (var i = 0; i < bones.Length; i++)
            {
                var       unityBone   = bones[i];
                var       babylonBone = transformToBoneMap[unityBone];
                Matrix4x4 localTransform;

                // Unity BindPose is already inverse so take the inverse again :-)
                if (transformToBoneMap.ContainsKey(unityBone.parent))
                {
                    var babylonParentBone = transformToBoneMap[unityBone.parent];
                    babylonBone.parentBoneIndex = babylonParentBone.index;
                    localTransform = bindPoses[babylonBone.parentBoneIndex] * bindPoses[i].inverse;
                }
                else
                {
                    babylonBone.parentBoneIndex = -1;
                    localTransform = bindPoses[i].inverse;
                }

                transformToBoneMap[unityBone].matrix = new[] {
                    localTransform[0, 0], localTransform[1, 0], localTransform[2, 0], localTransform[3, 0],
                    localTransform[0, 1], localTransform[1, 1], localTransform[2, 1], localTransform[3, 1],
                    localTransform[0, 2], localTransform[1, 2], localTransform[2, 2], localTransform[3, 2],
                    localTransform[0, 3], localTransform[1, 3], localTransform[2, 3], localTransform[3, 3]
                };
            }

            // Reorder and attach the skeleton.
            babylonSkeleton.bones = transformToBoneMap.Values.OrderBy(b => b.index).ToArray();
            babylonScene.SkeletonsList.Add(babylonSkeleton);

            return(babylonSkeleton);
        }
        private void ConvertUnityLightToBabylon(Light light, float progress)
        {
            if (!light.isActiveAndEnabled || light.alreadyLightmapped)
            {
                return;
            }

            ExporterWindow.ReportProgress(progress, "Exporting light: " + light.name);

            BabylonLight babylonLight = new BabylonLight
            {
                name = light.name,
                id = GetID(light.gameObject),
                parentId = GetParentID(light.transform)
            };
            
            switch (light.type)
            {
                case LightType.Spot:
                    babylonLight.type = 2;
                    break;
                case LightType.Directional:
                    babylonLight.type = 1;
                    break;
                case LightType.Point:
                    babylonLight.type = 0;
                    babylonLight.range = light.range;
                    break;
                case LightType.Area:
                    // TODO
                    break;
            }

            babylonLight.position = light.transform.localPosition.ToFloat();

            var direction = new Vector3(0, 0, 1);
            var transformedDirection = light.transform.TransformDirection(direction);
            babylonLight.direction = transformedDirection.ToFloat();

            babylonLight.diffuse = light.color.ToFloat();

            babylonLight.intensity = light.intensity;

            babylonLight.angle = light.spotAngle * (float)Math.PI / 180;
            babylonLight.exponent = 1.0f;

            babylonScene.LightsList.Add(babylonLight);

            // Animations
            ExportAnimations(light.transform, babylonLight);

            // Shadows
            if ((light.type == LightType.Directional || light.type == LightType.Spot) && light.shadows != LightShadows.None)
            {
                GenerateShadowsGenerator(light);
            }
        }
示例#5
0
 public void Bake()
 {
     // Validate Project Platform
     if (generateSkybox == false && generateRadiance == false)
     {
         ExporterWindow.ShowMessage("You must select generate skybox and/or radiance");
         return;
     }
     if (!Unity3D2Babylon.Tools.ValidateProjectPlatform())
     {
         return;
     }
     try
     {
         string inputFile = AssetDatabase.GetAssetPath(convertCube);
         string inputExt  = Path.GetExtension(inputFile);
         if (skyboxOption == BabylonSkyboxOption.SixSidedCubemap)
         {
             Split(inputFile, inputExt, true);
             Filter(inputFile, inputExt, false, true);
         }
         else if (skyboxOption == BabylonSkyboxOption.DirectDrawSurface)
         {
             Filter(inputFile, inputExt, true, true);
         }
     }
     catch (Exception ex)
     {
         UnityEngine.Debug.LogException(ex);
     }
     finally
     {
         ExporterWindow.ReportProgress(1, "Refresing assets database...");
         AssetDatabase.Refresh();
     }
     ExporterWindow.ReportProgress(1, "Cubemap conversion complete.");
     EditorUtility.ClearProgressBar();
     if (this.keepGeneratorOpen)
     {
         ExporterWindow.ShowMessage("Cubemap optimzation complete.", "Babylon.js");
     }
     else
     {
         this.Close();
     }
 }
示例#6
0
 private void PackTextureAtlasEmissions()
 {
     if (atlasMaterial != null && !String.IsNullOrEmpty(emissionFilename))
     {
         ExporterWindow.ReportProgress(1, "Generating emissive color maps... This may take a while.");
         bool      bilinearScaling   = (textureImageScaling == BabylonTextureScale.Bilinear);
         Texture2D emissionMeshAtlas = new Texture2D(128, 128, TextureFormat.RGBA32, false);
         Tools.PackTextureAtlas(emissionMeshAtlas, emissionTextures.ToArray(), textureAtlasSize, maxTextureImageSize, bilinearScaling, false);
         Texture2D emissionMeshBuffer = emissionMeshAtlas.Copy();
         emissionMeshBuffer.WriteImage(emissionFilename, textureAtlasFormat);
         AssetDatabase.ImportAsset(emissionFilename, ImportAssetOptions.ForceUpdate);
         // Import As Emission Map
         var importTool = new BabylonTextureImporter(emissionFilename);
         importTool.textureImporter.textureType        = TextureImporterType.Default;
         importTool.textureImporter.convertToNormalmap = false;
         importTool.ForceUpdate();
         atlasMaterial.SetTexture("_EmissionMap", (Texture2D)AssetDatabase.LoadAssetAtPath(emissionFilename, typeof(Texture2D)));
     }
 }
示例#7
0
 private void PackTextureAtlasNormals()
 {
     if (atlasMaterial != null && !String.IsNullOrEmpty(bumpFilename))
     {
         ExporterWindow.ReportProgress(1, "Generating normal map atlas... This may take a while.");
         //bool jpeg = (textureAtlasFormat == BabylonImageFormat.JPEG);
         bool      bilinearScaling = (textureImageScaling == BabylonTextureScale.Bilinear);
         Texture2D bumpMeshAtlas   = new Texture2D(128, 128, TextureFormat.RGBA32, false);
         Tools.PackTextureAtlas(bumpMeshAtlas, bumpTextures.ToArray(), textureAtlasSize, maxTextureImageSize, bilinearScaling, false, removeAlphaEncoding);
         Texture2D bumpMeshBuffer = bumpMeshAtlas.Copy();
         bumpMeshBuffer.WriteImage(bumpFilename, textureAtlasFormat);
         AssetDatabase.ImportAsset(bumpFilename, ImportAssetOptions.ForceUpdate);
         // Import As Normal Map
         var importTool = new BabylonTextureImporter(bumpFilename);
         importTool.textureImporter.textureType        = TextureImporterType.NormalMap;
         importTool.textureImporter.convertToNormalmap = false;
         importTool.ForceUpdate();
         atlasMaterial.SetTexture("_BumpMap", (Texture2D)AssetDatabase.LoadAssetAtPath(bumpFilename, typeof(Texture2D)));
     }
 }
示例#8
0
        private void ConvertUnityCameraToBabylon(Camera camera, float progress)
        {
            ExporterWindow.ReportProgress(progress, "Exporting camera: " + camera.name);

            BabylonCamera babylonCamera = new BabylonCamera
            {
                name     = camera.name,
                id       = GetID(camera.gameObject),
                fov      = camera.fieldOfView * (float)Math.PI / 180,
                minZ     = camera.nearClipPlane,
                maxZ     = camera.farClipPlane,
                parentId = GetParentID(camera.transform),
                position = camera.transform.localPosition.ToFloat()
            };

            var target            = new Vector3(0, 0, 1);
            var transformedTarget = camera.transform.TransformDirection(target);

            babylonCamera.target = (camera.transform.position + transformedTarget).ToFloat();

            babylonScene.CamerasList.Add(babylonCamera);

            if (Camera.main == camera)
            {
                babylonScene.activeCameraID = babylonCamera.id;
                babylonScene.clearColor     = camera.backgroundColor.ToFloat();
            }

            // Animations
            ExportAnimations(camera.transform, babylonCamera);

            // Collisions
            if (exportationOptions.ExportCollisions)
            {
                babylonCamera.checkCollisions = true;
                babylonCamera.applyGravity    = true;
                babylonCamera.ellipsoid       = exportationOptions.CameraEllipsoid.ToFloat();
            }
        }
示例#9
0
 private void PackTextureAtlasSpeculars()
 {
     if (atlasMaterial != null && !String.IsNullOrEmpty(specularFilename))
     {
         ExporterWindow.ReportProgress(1, "Generating specular gloss maps... This may take a while.");
         bool      bilinearScaling   = (textureImageScaling == BabylonTextureScale.Bilinear);
         Texture2D specularMeshAtlas = new Texture2D(128, 128, TextureFormat.RGBA32, false);
         Tools.PackTextureAtlas(specularMeshAtlas, specularTextures.ToArray(), textureAtlasSize, maxTextureImageSize, bilinearScaling, false);
         Texture2D specularMeshBuffer = specularMeshAtlas.Copy();
         specularMeshBuffer.WriteImage(specularFilename, textureAtlasFormat);
         AssetDatabase.ImportAsset(specularFilename, ImportAssetOptions.ForceUpdate);
         // Import As Specular Map
         var importTool = new BabylonTextureImporter(specularFilename);
         importTool.textureImporter.textureType        = TextureImporterType.Default;
         importTool.textureImporter.convertToNormalmap = false;
         importTool.ForceUpdate();
         atlasMaterial.SetFloat("_Gloss", 0.5f);         // Default Texture Atlas Scaling
         atlasMaterial.SetFloat("_Glossiness", 0.5f);    // Default Texture Atlas Scaling
         atlasMaterial.SetFloat("_GlossMapScale", 0.5f); // Default Texture Atlas Scaling
         atlasMaterial.SetTexture("_SpecGlossMap", (Texture2D)AssetDatabase.LoadAssetAtPath(specularFilename, typeof(Texture2D)));
     }
 }
 void SwitchSandbox()
 {
     if (sandboxType == SandboxType.Custom && String.IsNullOrEmpty(ExporterWindow.exportationOptions.CustomWindowsSandbox))
     {
         ExporterWindow.ShowMessage("You must enter a custom sandbox.", "Babylon.js");
         return;
     }
     this.logs.Clear();
     ExporterWindow.ReportProgress(1, "Switching windows sandbox... This may take a while.");
     string sandbox = (sandboxType == SandboxType.Custom) ? ExporterWindow.exportationOptions.CustomWindowsSandbox : "RETAIL";
     string command = "\"" + Path.Combine(Application.dataPath, "Babylon/Plugins/Windows/SwitchSandbox.cmd") + "\"";
     this.logs.Add("Switching windows sandbox to: " + sandbox);
     int result = Tools.ExecuteProcess(command, sandbox, ref this.logs);
     EditorUtility.ClearProgressBar();
     if (result != 0)
     {
         ExporterWindow.ShowMessage("Failed to switch windows sandbox.", "Babylon.js");
     }
     if (this.keepGeneratorOpen == false)
     {
         this.Close();
     }
 }
 private void DumpSkyboxTextures(ref BabylonTexture skytex, ref Texture2D frontTexture, ref Texture2D backTexture, ref Texture2D leftTexture, ref Texture2D rightTexture, ref Texture2D upTexture, ref Texture2D downTexture)
 {
     if (frontTexture != null && backTexture != null && leftTexture != null && rightTexture != null && upTexture != null && downTexture != null)
     {
         ExporterWindow.ReportProgress(1, "Exporting skybox environment textures... This may take a while.");
         string frontTextureExt = "_pz.jpg";
         string backTextureExt  = "_nz.jpg";
         string leftTextureExt  = "_px.jpg";
         string rightTextureExt = "_nx.jpg";
         string upTextureExt    = "_py.jpg";
         string downTextureExt  = "_ny.jpg";
         Tools.SetTextureWrapMode(skytex, frontTexture);
         var faceTextureFile = AssetDatabase.GetAssetPath(frontTexture);
         var faceTextureExt  = Path.GetExtension(faceTextureFile);
         var faceImportTool  = new BabylonTextureImporter(faceTextureFile);
         if (faceTextureExt.Equals(".png", StringComparison.OrdinalIgnoreCase) || faceTextureExt.Equals(".jpg", StringComparison.OrdinalIgnoreCase) || faceTextureExt.Equals(".jpeg", StringComparison.OrdinalIgnoreCase))
         {
             frontTextureExt = "_pz" + faceTextureExt;
             var frontTextureName = String.Format("{0}_pz{1}", skytex.name, faceTextureExt);
             var frontTexturePath = Path.Combine(babylonScene.OutputPath, frontTextureName);
             faceImportTool.SetReadable();
             CopyTextureFace(frontTexturePath, frontTextureName, frontTexture);
         }
         else
         {
             UnityEngine.Debug.LogWarning("SKYBOX: Unsupported cube face texture type of " + faceTextureExt + " for " + Path.GetFileName(faceTextureFile));
         }
         faceTextureFile = AssetDatabase.GetAssetPath(backTexture);
         faceTextureExt  = Path.GetExtension(faceTextureFile);
         faceImportTool  = new BabylonTextureImporter(faceTextureFile);
         if (faceTextureExt.Equals(".png", StringComparison.OrdinalIgnoreCase) || faceTextureExt.Equals(".jpg", StringComparison.OrdinalIgnoreCase) || faceTextureExt.Equals(".jpeg", StringComparison.OrdinalIgnoreCase))
         {
             backTextureExt = "_nz" + faceTextureExt;
             var backTextureName = String.Format("{0}_nz{1}", skytex.name, faceTextureExt);
             var backTexturePath = Path.Combine(babylonScene.OutputPath, backTextureName);
             faceImportTool.SetReadable();
             CopyTextureFace(backTexturePath, backTextureName, backTexture);
         }
         else
         {
             UnityEngine.Debug.LogWarning("SKYBOX: Unsupported cube face texture type of " + faceTextureExt + " for " + Path.GetFileName(faceTextureFile));
         }
         faceTextureFile = AssetDatabase.GetAssetPath(leftTexture);
         faceTextureExt  = Path.GetExtension(faceTextureFile);
         faceImportTool  = new BabylonTextureImporter(faceTextureFile);
         if (faceTextureExt.Equals(".png", StringComparison.OrdinalIgnoreCase) || faceTextureExt.Equals(".jpg", StringComparison.OrdinalIgnoreCase) || faceTextureExt.Equals(".jpeg", StringComparison.OrdinalIgnoreCase))
         {
             leftTextureExt = "_px" + faceTextureExt;
             var leftTextureName = String.Format("{0}_px{1}", skytex.name, faceTextureExt);
             var leftTexturePath = Path.Combine(babylonScene.OutputPath, leftTextureName);
             faceImportTool.SetReadable();
             CopyTextureFace(leftTexturePath, leftTextureName, leftTexture);
         }
         else
         {
             UnityEngine.Debug.LogWarning("SKYBOX: Unsupported cube face texture type of " + faceTextureExt + " for " + Path.GetFileName(faceTextureFile));
         }
         faceTextureFile = AssetDatabase.GetAssetPath(rightTexture);
         faceTextureExt  = Path.GetExtension(faceTextureFile);
         faceImportTool  = new BabylonTextureImporter(faceTextureFile);
         if (faceTextureExt.Equals(".png", StringComparison.OrdinalIgnoreCase) || faceTextureExt.Equals(".jpg", StringComparison.OrdinalIgnoreCase) || faceTextureExt.Equals(".jpeg", StringComparison.OrdinalIgnoreCase))
         {
             rightTextureExt = "_nx" + faceTextureExt;
             var rightTextureName = String.Format("{0}_nx{1}", skytex.name, faceTextureExt);
             var rightTexturePath = Path.Combine(babylonScene.OutputPath, rightTextureName);
             faceImportTool.SetReadable();
             CopyTextureFace(rightTexturePath, rightTextureName, rightTexture);
         }
         else
         {
             UnityEngine.Debug.LogWarning("SKYBOX: Unsupported cube face texture type of " + faceTextureExt + " for " + Path.GetFileName(faceTextureFile));
         }
         faceTextureFile = AssetDatabase.GetAssetPath(upTexture);
         faceTextureExt  = Path.GetExtension(faceTextureFile);
         faceImportTool  = new BabylonTextureImporter(faceTextureFile);
         if (faceTextureExt.Equals(".png", StringComparison.OrdinalIgnoreCase) || faceTextureExt.Equals(".jpg", StringComparison.OrdinalIgnoreCase) || faceTextureExt.Equals(".jpeg", StringComparison.OrdinalIgnoreCase))
         {
             upTextureExt = "_py" + faceTextureExt;
             var upTextureName = String.Format("{0}_py{1}", skytex.name, faceTextureExt);
             var upTexturePath = Path.Combine(babylonScene.OutputPath, upTextureName);
             faceImportTool.SetReadable();
             CopyTextureFace(upTexturePath, upTextureName, upTexture);
         }
         else
         {
             UnityEngine.Debug.LogWarning("SKYBOX: Unsupported cube face texture type of " + faceTextureExt + " for " + Path.GetFileName(faceTextureFile));
         }
         faceTextureFile = AssetDatabase.GetAssetPath(downTexture);
         faceTextureExt  = Path.GetExtension(faceTextureFile);
         faceImportTool  = new BabylonTextureImporter(faceTextureFile);
         if (faceTextureExt.Equals(".png", StringComparison.OrdinalIgnoreCase) || faceTextureExt.Equals(".jpg", StringComparison.OrdinalIgnoreCase) || faceTextureExt.Equals(".jpeg", StringComparison.OrdinalIgnoreCase))
         {
             downTextureExt = "_ny" + faceTextureExt;
             var downTextureName = String.Format("{0}_ny{1}", skytex.name, faceTextureExt);
             var downTexturePath = Path.Combine(babylonScene.OutputPath, downTextureName);
             faceImportTool.SetReadable();
             CopyTextureFace(downTexturePath, downTexturePath, downTexture);
         }
         else
         {
             UnityEngine.Debug.LogWarning("SKYBOX: Unsupported cube face texture type of " + faceTextureExt + " for " + Path.GetFileName(faceTextureFile));
         }
         skytex.extensions = new string[] { leftTextureExt, upTextureExt, frontTextureExt, rightTextureExt, downTextureExt, backTextureExt };
     }
 }
示例#12
0
        public void ConvertFromUnity()
        {
            ExporterWindow.ReportProgress(0, "Starting Babylon.js exportation process...");

            gameObjects = Object.FindObjectsOfType(typeof(GameObject)) as GameObject[];

            if (gameObjects.Length == 0)
            {
                ExporterWindow.ShowMessage("No gameobject! - Please add at least a gameobject to export");
                return;
            }

            var itemsCount = gameObjects.Length;

            var index = 0;

            //Dictionary to store prefabs and their instances
            Dictionary <GameObject, List <BabylonAbstractMesh> > dicPrefabs = new Dictionary <GameObject, List <BabylonAbstractMesh> >();

            foreach (var gameObject in gameObjects)
            {
                var progress = ((float)index / itemsCount);
                index++;

                /*
                 *  The order of processing is important here.
                 *  We will only check if this is a mesh prefab if it is not a light or camera
                 */

                // Light
                var light = gameObject.GetComponent <Light>();
                if (light != null)
                {
                    ConvertUnityLightToBabylon(light, progress);
                    continue;
                }

                // Camera
                var camera = gameObject.GetComponent <Camera>();
                if (camera != null)
                {
                    ConvertUnityCameraToBabylon(camera, progress);
                    continue;
                }

                // Check if this is a prefab instance
                GameObject gobjPrefab = (GameObject)PrefabUtility.GetPrefabParent(gameObject);
                if (gobjPrefab != null)
                {
                    //Add prefab to dictionary if it doesn't already exist
                    if (!dicPrefabs.ContainsKey(gobjPrefab))
                    {
                        dicPrefabs[gobjPrefab] = new List <BabylonAbstractMesh>();
                    }

                    List <BabylonAbstractMesh> lstInstances = dicPrefabs[gobjPrefab];
                    BabylonAbstractMesh        instance     = ConvertUnityMeshToInstance(gameObject);
                    lstInstances.Add(instance);
                    continue;
                }

                // Static meshes
                var meshFilter = gameObject.GetComponent <MeshFilter>();
                if (meshFilter != null)
                {
                    ConvertUnityMeshToBabylon(meshFilter.sharedMesh, meshFilter.transform, gameObject, progress);
                    continue;
                }

                // Skinned meshes
                var skinnedMesh = gameObject.GetComponent <SkinnedMeshRenderer>();
                if (skinnedMesh != null)
                {
                    ConvertUnityMeshToBabylon(skinnedMesh.sharedMesh, skinnedMesh.transform, gameObject, progress);
                    continue;
                }

                // Empty
                ConvertUnityEmptyObjectToBabylon(gameObject);
            }

            index      = 0;
            itemsCount = dicPrefabs.Count;

            //Convert prefabs
            foreach (KeyValuePair <GameObject, List <BabylonAbstractMesh> > pair in dicPrefabs)
            {
                var progress = ((float)index / itemsCount);
                index++;

                List <BabylonAbstractMesh> lstValue = pair.Value;
                GameObject            prefab        = pair.Key;
                BabylonAbstractMesh[] lstInstance   = lstValue.ToArray();

                // Static meshes
                var meshFilter = prefab.GetComponent <MeshFilter>();
                if (meshFilter != null)
                {
                    ConvertUnityMeshToBabylon(meshFilter.sharedMesh, meshFilter.transform, prefab, progress, lstInstance);
                    continue;
                }

                // Skinned meshes
                var skinnedMesh = prefab.GetComponent <SkinnedMeshRenderer>();
                if (skinnedMesh != null)
                {
                    ConvertUnityMeshToBabylon(skinnedMesh.sharedMesh, skinnedMesh.transform, prefab, progress, lstInstance);
                    continue;
                }

                // Empty
                ConvertUnityEmptyObjectToBabylon(prefab, lstInstance);
            }

            // Materials
            foreach (var mat in materialsDictionary)
            {
                babylonScene.MaterialsList.Add(mat.Value);
            }

            foreach (var multiMat in multiMatDictionary)
            {
                babylonScene.MultiMaterialsList.Add(multiMat.Value);
            }

            // Collisions
            if (exportationOptions.ExportCollisions)
            {
                babylonScene.gravity = exportationOptions.Gravity.ToFloat();
            }
        }
示例#13
0
        private void ConvertUnityCameraToBabylon(Camera camera, GameObject gameObject, float progress, ref UnityMetaData metaData, ref List <BabylonExport.Entities.BabylonParticleSystem> particleSystems, ref List <UnityFlareSystem> lensFlares, ref string componentTags)
        {
            ExporterWindow.ReportProgress(progress, "Exporting camera: " + camera.name);

            BabylonUniversalCamera babylonCamera = new BabylonUniversalCamera
            {
                name     = camera.name,
                id       = GetID(camera.gameObject),
                fov      = camera.fieldOfView * (float)Math.PI / 180,
                minZ     = camera.nearClipPlane,
                maxZ     = camera.farClipPlane,
                parentId = GetParentID(camera.transform),
                position = camera.transform.localPosition.ToFloat()
            };

            metaData.type = "Camera";
            metaData.properties.Add("hdr", camera.hdr);
            metaData.properties.Add("clearFlags", camera.clearFlags.ToString());
            metaData.properties.Add("cullingMask", camera.cullingMask);
            metaData.properties.Add("stereoEnabled", camera.stereoEnabled);
            metaData.properties.Add("useOcclusionCulling", camera.useOcclusionCulling);
            babylonCamera.tags = componentTags;

            var target            = new Vector3(0, 0, 1);
            var transformedTarget = camera.transform.TransformDirection(target);

            babylonCamera.target = (camera.transform.position + transformedTarget).ToFloat();
            babylonCamera.isStereoscopicSideBySide = camera.stereoEnabled;
            if (camera.orthographic)
            {
                float size = camera.orthographicSize;
                babylonCamera.orthoTop    = size;
                babylonCamera.orthoBottom = -size;
                babylonCamera.orthoLeft   = -size;
                babylonCamera.orthoRight  = size;
                babylonCamera.mode        = 1;
            }
            else
            {
                babylonCamera.mode = 0;
            }

            babylonCamera.metadata = metaData;
            babylonScene.CamerasList.Add(babylonCamera);

            if (Camera.main == camera)
            {
                babylonScene.activeCameraID = babylonCamera.id;
                babylonScene.clearColor     = camera.backgroundColor.ToFloat();
            }

            // Animations
            ExportAnimations(camera.transform, babylonCamera);

            // Collisions
            if (exportationOptions.ExportCollisions)
            {
                babylonCamera.checkCollisions = true;
                babylonCamera.applyGravity    = (exportationOptions.Gravity.X == 0 && exportationOptions.Gravity.Y == 0 && exportationOptions.Gravity.Z == 0) ? false : true;
                babylonCamera.ellipsoid       = exportationOptions.CameraEllipsoid.ToFloat();
            }

            // Lens Flares
            ParseLensFlares(gameObject, babylonCamera.id, ref lensFlares);

            // Particles Systems
            ParseParticleSystems(gameObject, babylonCamera.id, ref particleSystems);
        }
示例#14
0
        private static void ExportTransformAnimationClipData(GameObject source, Transform transform, BabylonIAnimatable animatable, UnityEditor.AnimationState animationState, ref List <AnimationClip> states, ref UnityMetaData metaData, Animator animator)
        {
            ExporterWindow.ReportProgress(1, "Exporting transform clips: " + transform.gameObject.name);
            int                     frameRate       = 0;
            int                     firstClipEnd    = 0;
            int                     totalFrameCount = 0;
            List <string>           stateNameCache  = new List <string>();
            List <BabylonAnimation> animations      = new List <BabylonAnimation>();

            var positionX = new List <BabylonAnimationKey>();
            var positionY = new List <BabylonAnimationKey>();
            var positionZ = new List <BabylonAnimationKey>();

            var rotationX = new List <BabylonAnimationKey>();
            var rotationY = new List <BabylonAnimationKey>();
            var rotationZ = new List <BabylonAnimationKey>();
            var rotationW = new List <BabylonAnimationKey>();

            var scaleX = new List <BabylonAnimationKey>();
            var scaleY = new List <BabylonAnimationKey>();
            var scaleZ = new List <BabylonAnimationKey>();

            int   frameOffest   = 0;
            float playbackSpeed = (animationState != null) ? animationState.playbackSpeed : 1.0f;

            foreach (var state in states)
            {
                if (state == null)
                {
                    continue;
                }
                AnimationClip clip = state as AnimationClip;
                if (frameRate <= 0)
                {
                    frameRate = (int)clip.frameRate;
                }
                //var frameTime = 1.0f / frameRate;
                int clipFrameCount = (int)(clip.length * frameRate);
                if (firstClipEnd <= 0)
                {
                    firstClipEnd = (clipFrameCount - 1);
                }
                var settings = AnimationUtility.GetAnimationClipSettings(clip);
                BabylonLoopBehavior behavior = (settings.loopTime) ? BabylonLoopBehavior.Cycle : BabylonLoopBehavior.Constant;
                if (settings.loopTime && settings.loopBlend)
                {
                    behavior = BabylonLoopBehavior.Relative;
                }
                ExporterWindow.ReportProgress(1, "Transforming: " + transform.gameObject.name + " - " + clip.name);
                // Set Animation State Meta Data
                if (!stateNameCache.Contains(clip.name))
                {
                    stateNameCache.Add(clip.name);
                    // Animation Clip Information
                    Dictionary <string, object> animStateInfo = new Dictionary <string, object>();
                    animStateInfo.Add("type", "transform");
                    animStateInfo.Add("name", clip.name);
                    animStateInfo.Add("start", frameOffest);
                    animStateInfo.Add("stop", (frameOffest + clipFrameCount - 1));
                    animStateInfo.Add("rate", frameRate);
                    animStateInfo.Add("behavior", (int)behavior);
                    animStateInfo.Add("playback", playbackSpeed);
                    metaData.animationClips.Add(animStateInfo);
                }

                // Animation Curve Bindings
                var curveBindings = AnimationUtility.GetCurveBindings(clip);
                foreach (var binding in curveBindings)
                {
                    var curve = AnimationUtility.GetEditorCurve(clip, binding);
                    switch (binding.propertyName)
                    {
                    //Position
                    case "m_LocalPosition.x":
                        IEnumerable <BabylonAnimationKey> px_keys = curve.keys.Select(keyFrame => new BabylonAnimationKey {
                            frame  = (int)((keyFrame.time * frameRate) + frameOffest),
                            values = new[] { keyFrame.value }
                        });
                        positionX.AddRange(px_keys);
                        break;

                    case "m_LocalPosition.y":
                        IEnumerable <BabylonAnimationKey> py_keys = curve.keys.Select(keyFrame => new BabylonAnimationKey {
                            frame  = (int)((keyFrame.time * frameRate) + frameOffest),
                            values = new[] { keyFrame.value }
                        });
                        positionY.AddRange(py_keys);
                        break;

                    case "m_LocalPosition.z":
                        IEnumerable <BabylonAnimationKey> pz_keys = curve.keys.Select(keyFrame => new BabylonAnimationKey {
                            frame  = (int)((keyFrame.time * frameRate) + frameOffest),
                            values = new[] { keyFrame.value }
                        });
                        positionZ.AddRange(pz_keys);
                        break;

                    // Rotation
                    case "localEulerAnglesRaw.x":
                        IEnumerable <BabylonAnimationKey> rx_keys = curve.keys.Select(keyFrame => new BabylonAnimationKey {
                            frame  = (int)((keyFrame.time * frameRate) + frameOffest),
                            values = new[] { keyFrame.value *(float)Math.PI / 180 }
                        });
                        rotationX.AddRange(rx_keys);
                        break;

                    case "localEulerAnglesRaw.y":
                        IEnumerable <BabylonAnimationKey> ry_keys = curve.keys.Select(keyFrame => new BabylonAnimationKey {
                            frame  = (int)((keyFrame.time * frameRate) + frameOffest),
                            values = new[] { keyFrame.value *(float)Math.PI / 180 }
                        });
                        rotationY.AddRange(ry_keys);
                        break;

                    case "localEulerAnglesRaw.z":
                        IEnumerable <BabylonAnimationKey> rz_keys = curve.keys.Select(keyFrame => new BabylonAnimationKey {
                            frame  = (int)((keyFrame.time * frameRate) + frameOffest),
                            values = new[] { keyFrame.value *(float)Math.PI / 180 }
                        });
                        rotationZ.AddRange(rz_keys);
                        break;

                    case "localEulerAnglesRaw.w":
                        IEnumerable <BabylonAnimationKey> rw_keys = curve.keys.Select(keyFrame => new BabylonAnimationKey {
                            frame  = (int)((keyFrame.time * frameRate) + frameOffest),
                            values = new[] { keyFrame.value *(float)Math.PI / 180 }
                        });
                        rotationW.AddRange(rw_keys);
                        break;

                    // Scaling
                    case "m_LocalScale.x":
                        IEnumerable <BabylonAnimationKey> sx_keys = curve.keys.Select(keyFrame => new BabylonAnimationKey {
                            frame  = (int)((keyFrame.time * frameRate) + frameOffest),
                            values = new[] { keyFrame.value }
                        });
                        scaleX.AddRange(sx_keys);
                        break;

                    case "m_LocalScale.y":
                        IEnumerable <BabylonAnimationKey> sy_keys = curve.keys.Select(keyFrame => new BabylonAnimationKey {
                            frame  = (int)((keyFrame.time * frameRate) + frameOffest),
                            values = new[] { keyFrame.value }
                        });
                        scaleY.AddRange(sy_keys);
                        break;

                    case "m_LocalScale.z":
                        IEnumerable <BabylonAnimationKey> sz_keys = curve.keys.Select(keyFrame => new BabylonAnimationKey {
                            frame  = (int)((keyFrame.time * frameRate) + frameOffest),
                            values = new[] { keyFrame.value }
                        });
                        scaleZ.AddRange(sz_keys);
                        break;

                    default:
                        continue;
                    }
                }
                frameOffest     += clipFrameCount;
                totalFrameCount += clipFrameCount;
            }

            // Position properties
            string property = "none";

            if (positionX.Count > 0)
            {
                property = "position.x";
                animations.Add(new BabylonAnimation
                {
                    dataType       = (int)BabylonAnimation.DataType.Float,
                    name           = property + " animation",
                    keys           = positionX.ToArray(),
                    framePerSecond = frameRate,
                    enableBlending = false,
                    blendingSpeed  = 0.0f,
                    loopBehavior   = (int)BabylonAnimation.LoopBehavior.Relative,
                    property       = property
                });
            }
            property = "none";
            if (positionY.Count > 0)
            {
                property = "position.y";
                animations.Add(new BabylonAnimation
                {
                    dataType       = (int)BabylonAnimation.DataType.Float,
                    name           = property + " animation",
                    keys           = positionY.ToArray(),
                    framePerSecond = frameRate,
                    enableBlending = false,
                    blendingSpeed  = 0.0f,
                    loopBehavior   = (int)BabylonAnimation.LoopBehavior.Relative,
                    property       = property
                });
            }
            property = "none";
            if (positionZ.Count > 0)
            {
                property = "position.z";
                animations.Add(new BabylonAnimation
                {
                    dataType       = (int)BabylonAnimation.DataType.Float,
                    name           = property + " animation",
                    keys           = positionZ.ToArray(),
                    framePerSecond = frameRate,
                    enableBlending = false,
                    blendingSpeed  = 0.0f,
                    loopBehavior   = (int)BabylonAnimation.LoopBehavior.Relative,
                    property       = property
                });
            }

            // Rotation properties
            property = "none";
            if (rotationX.Count > 0)
            {
                property = "rotation.x";
                animations.Add(new BabylonAnimation
                {
                    dataType       = (int)BabylonAnimation.DataType.Float,
                    name           = property + " animation",
                    keys           = rotationX.ToArray(),
                    framePerSecond = frameRate,
                    enableBlending = false,
                    blendingSpeed  = 0.0f,
                    loopBehavior   = (int)BabylonAnimation.LoopBehavior.Relative,
                    property       = property
                });
            }
            property = "none";
            if (rotationY.Count > 0)
            {
                property = "rotation.y";
                animations.Add(new BabylonAnimation
                {
                    dataType       = (int)BabylonAnimation.DataType.Float,
                    name           = property + " animation",
                    keys           = rotationY.ToArray(),
                    framePerSecond = frameRate,
                    enableBlending = false,
                    blendingSpeed  = 0.0f,
                    loopBehavior   = (int)BabylonAnimation.LoopBehavior.Relative,
                    property       = property
                });
            }
            property = "none";
            if (rotationZ.Count > 0)
            {
                property = "rotation.z";
                animations.Add(new BabylonAnimation
                {
                    dataType       = (int)BabylonAnimation.DataType.Float,
                    name           = property + " animation",
                    keys           = rotationZ.ToArray(),
                    framePerSecond = frameRate,
                    enableBlending = false,
                    blendingSpeed  = 0.0f,
                    loopBehavior   = (int)BabylonAnimation.LoopBehavior.Relative,
                    property       = property
                });
            }
            property = "none";
            if (rotationW.Count > 0)
            {
                property = "rotation.w";
                animations.Add(new BabylonAnimation
                {
                    dataType       = (int)BabylonAnimation.DataType.Float,
                    name           = property + " animation",
                    keys           = rotationW.ToArray(),
                    framePerSecond = frameRate,
                    enableBlending = false,
                    blendingSpeed  = 0.0f,
                    loopBehavior   = (int)BabylonAnimation.LoopBehavior.Relative,
                    property       = property
                });
            }

            // Scale properties
            property = "none";
            if (scaleX.Count > 0)
            {
                property = "scaling.x";
                animations.Add(new BabylonAnimation
                {
                    dataType       = (int)BabylonAnimation.DataType.Float,
                    name           = property + " animation",
                    keys           = scaleX.ToArray(),
                    framePerSecond = frameRate,
                    enableBlending = false,
                    blendingSpeed  = 0.0f,
                    loopBehavior   = (int)BabylonAnimation.LoopBehavior.Relative,
                    property       = property
                });
            }
            property = "none";
            if (scaleY.Count > 0)
            {
                property = "scaling.y";
                animations.Add(new BabylonAnimation
                {
                    dataType       = (int)BabylonAnimation.DataType.Float,
                    name           = property + " animation",
                    keys           = scaleY.ToArray(),
                    framePerSecond = frameRate,
                    enableBlending = false,
                    blendingSpeed  = 0.0f,
                    loopBehavior   = (int)BabylonAnimation.LoopBehavior.Relative,
                    property       = property
                });
            }
            property = "none";
            if (scaleZ.Count > 0)
            {
                property = "scaling.z";
                animations.Add(new BabylonAnimation
                {
                    dataType       = (int)BabylonAnimation.DataType.Float,
                    name           = property + " animation",
                    keys           = scaleZ.ToArray(),
                    framePerSecond = frameRate,
                    enableBlending = false,
                    blendingSpeed  = 0.0f,
                    loopBehavior   = (int)BabylonAnimation.LoopBehavior.Relative,
                    property       = property
                });
            }
            if (animations.Count > 0)
            {
                animatable.animations = animations.ToArray();
            }
        }
示例#15
0
        private void ConvertUnityLightToBabylon(Light light, GameObject gameObject, float progress, ref UnityMetaData metaData, ref List <BabylonExport.Entities.BabylonParticleSystem> particleSystems, ref List <UnityFlareSystem> lensFlares, ref string componentTags)
        {
            // No Inactive Or Baking Lights
            if (light.isActiveAndEnabled == false || light.type == LightType.Area || light.lightmappingMode == LightmappingMode.Baked)
            {
                return;
            }

            ExporterWindow.ReportProgress(progress, "Exporting light: " + light.name);
            BabylonLight babylonLight = new BabylonLight
            {
                name     = light.name,
                id       = GetID(light.gameObject),
                parentId = GetParentID(light.transform)
            };

            metaData.type     = "Light";
            babylonLight.tags = componentTags;

            switch (light.type)
            {
            case LightType.Point:
                babylonLight.type  = 0;
                babylonLight.range = light.range;
                break;

            case LightType.Directional:
                babylonLight.type = 1;
                break;

            case LightType.Spot:
                babylonLight.type = 2;
                break;
            }

            babylonLight.position = light.transform.localPosition.ToFloat();

            var direction            = new Vector3(0, 0, 1);
            var transformedDirection = light.transform.TransformDirection(direction);

            transformedDirection[0] += exportationOptions.LightRotationOffset.X;
            transformedDirection[1] += exportationOptions.LightRotationOffset.Y;
            transformedDirection[2] += exportationOptions.LightRotationOffset.Z;
            babylonLight.direction   = transformedDirection.ToFloat();

            babylonLight.diffuse = light.color.ToFloat();

            babylonLight.intensity = light.intensity * exportationOptions.LightIntensityFactor;

            babylonLight.angle    = light.spotAngle * (float)Math.PI / 180;
            babylonLight.exponent = 1.0f;

            babylonLight.metadata = metaData;
            babylonScene.LightsList.Add(babylonLight);

            // Animations
            ExportAnimations(light.transform, babylonLight);

            // Lens Flares
            ParseLensFlares(gameObject, babylonLight.id, ref lensFlares);

            // Particles Systems
            ParseParticleSystems(gameObject, babylonLight.id, ref particleSystems);

            // Shadow Maps
            if (exportationOptions.ExportShadows)
            {
                if ((light.type == LightType.Directional || light.type == LightType.Spot) && light.shadows != LightShadows.None)
                {
                    GenerateShadowsGenerator(light, progress);
                }
            }
        }
 private void ExportMainCameraSkyboxToBabylon()
 {
     if (RenderSettings.sun != null)
     {
         var direction            = new Vector3(0, 0, 1);
         var transformedDirection = RenderSettings.sun.transform.TransformDirection(direction);
         SceneBuilder.SunlightDirection   = transformedDirection.ToFloat();
         SceneBuilder.SunlightIndentifier = GetID(RenderSettings.sun.gameObject);
     }
     if (Camera.main != null)
     {
         babylonScene.clearColor = Camera.main.backgroundColor.ToFloat(1.0f);
         if ((Camera.main.clearFlags & CameraClearFlags.Skybox) == CameraClearFlags.Skybox)
         {
             if (RenderSettings.skybox != null)
             {
                 bool           dds    = false;
                 BabylonTexture skytex = null;
                 if (RenderSettings.skybox.shader.name == "Skybox/Cubemap")
                 {
                     skytex                 = new BabylonCubeTexture();
                     skytex.name            = String.Format("{0}_Skybox", SceneName);
                     skytex.coordinatesMode = 5;
                     Cubemap cubeMap = RenderSettings.skybox.GetTexture("_Tex") as Cubemap;
                     if (cubeMap != null)
                     {
                         var srcTexturePath = AssetDatabase.GetAssetPath(cubeMap);
                         var srcTextureExt  = Path.GetExtension(srcTexturePath);
                         if (srcTextureExt.Equals(".dds", StringComparison.OrdinalIgnoreCase))
                         {
                             ExporterWindow.ReportProgress(1, "Exporting skybox direct draw surface... This may take a while.");
                             // ..
                             // Export Draw Surface Skybox Textures
                             // ..
                             dds               = true;
                             skytex.name      += ".dds";
                             skytex.extensions = null;
                             ((BabylonCubeTexture)skytex).prefiltered = true;
                             CopyCubemapTexture(skytex.name, cubeMap, skytex);
                         }
                         else
                         {
                             ExporterWindow.ReportProgress(1, "Baking skybox environment textures... This may take a while.");
                             var imageFormat = (BabylonImageFormat)ExporterWindow.exportationOptions.ImageEncodingOptions;
                             // ..
                             // Export Tone Mapped Cubemap To 6-Sided Skybox Textures
                             // ..
                             bool   jpeg            = (imageFormat == BabylonImageFormat.JPG);
                             string faceTextureExt  = (jpeg) ? ".jpg" : ".png";
                             string frontTextureExt = "_pz" + faceTextureExt;
                             string backTextureExt  = "_nz" + faceTextureExt;
                             string leftTextureExt  = "_px" + faceTextureExt;
                             string rightTextureExt = "_nx" + faceTextureExt;
                             string upTextureExt    = "_py" + faceTextureExt;
                             string downTextureExt  = "_ny" + faceTextureExt;
                             skytex.extensions = new string[] { leftTextureExt, upTextureExt, frontTextureExt, rightTextureExt, downTextureExt, backTextureExt };
                             Tools.SetTextureWrapMode(skytex, cubeMap);
                             var outputFile   = Path.Combine(babylonScene.OutputPath, skytex.name + faceTextureExt);
                             var splitterOpts = new BabylonSplitterOptions();
                             Tools.ExportSkybox(cubeMap, outputFile, splitterOpts, imageFormat);
                         }
                     }
                 }
                 else if (RenderSettings.skybox.shader.name == "Skybox/6 Sided" || RenderSettings.skybox.shader.name == "Mobile/Skybox")
                 {
                     skytex                 = new BabylonCubeTexture();
                     skytex.name            = String.Format("{0}_Skybox", SceneName);
                     skytex.coordinatesMode = 5;
                     // ..
                     // 6-Sided Skybox Textures (Tone Mapped Image Formats Only)
                     // ..
                     var frontTexture = RenderSettings.skybox.GetTexture("_FrontTex") as Texture2D;
                     var backTexture  = RenderSettings.skybox.GetTexture("_BackTex") as Texture2D;
                     var leftTexture  = RenderSettings.skybox.GetTexture("_LeftTex") as Texture2D;
                     var rightTexture = RenderSettings.skybox.GetTexture("_RightTex") as Texture2D;
                     var upTexture    = RenderSettings.skybox.GetTexture("_UpTex") as Texture2D;
                     var downTexture  = RenderSettings.skybox.GetTexture("_DownTex") as Texture2D;
                     DumpSkyboxTextures(ref skytex, ref frontTexture, ref backTexture, ref leftTexture, ref rightTexture, ref upTexture, ref downTexture);
                 }
                 else if (RenderSettings.skybox.name.Equals("Default-Skybox"))
                 {
                     skytex                 = new BabylonCubeTexture();
                     skytex.name            = String.Format("{0}_Skybox", SceneName);
                     skytex.coordinatesMode = 5;
                     // ..
                     // 6-Sided Skybox Textures (Toolkit Skybox Template Images)
                     // ..
                     string skyboxPath   = "Assets/Babylon/Template/Skybox/";
                     var    frontTexture = AssetDatabase.LoadAssetAtPath <Texture2D>(skyboxPath + "DefaultSkybox_pz.png");
                     var    backTexture  = AssetDatabase.LoadAssetAtPath <Texture2D>(skyboxPath + "DefaultSkybox_nz.png");
                     var    leftTexture  = AssetDatabase.LoadAssetAtPath <Texture2D>(skyboxPath + "DefaultSkybox_px.png");
                     var    rightTexture = AssetDatabase.LoadAssetAtPath <Texture2D>(skyboxPath + "DefaultSkybox_nx.png");
                     var    upTexture    = AssetDatabase.LoadAssetAtPath <Texture2D>(skyboxPath + "DefaultSkybox_py.png");
                     var    downTexture  = AssetDatabase.LoadAssetAtPath <Texture2D>(skyboxPath + "DefaultSkybox_ny.png");
                     DumpSkyboxTextures(ref skytex, ref frontTexture, ref backTexture, ref leftTexture, ref rightTexture, ref upTexture, ref downTexture);
                 }
                 else
                 {
                     UnityEngine.Debug.LogWarning("SKYBOX: " + RenderSettings.skybox.shader.name + " shader type is unsupported. Skybox and reflections will be disabled.");
                 }
                 if (skytex != null)
                 {
                     float  size = (SceneController != null) ? SceneController.skyboxOptions.skyboxMeshSize : 1000;
                     string tags = (SceneController != null) ? SceneController.skyboxOptions.skyboxMeshTags : String.Empty;
                     // ..
                     // PBR Skybox Material Support
                     // ..
                     bool  pbr    = (SceneController != null) ? SceneController.skyboxOptions.directDrawSurface.physicalBased : false;
                     float pbr_ms = (SceneController != null) ? SceneController.skyboxOptions.directDrawSurface.microSurface : 1.0f;
                     float pbr_cc = (SceneController != null) ? SceneController.skyboxOptions.directDrawSurface.cameraContrast : 1.0f;
                     float pbr_ce = (SceneController != null) ? SceneController.skyboxOptions.directDrawSurface.cameraExposure : 1.0f;
                     float pbr_di = (SceneController != null) ? SceneController.skyboxOptions.directDrawSurface.directIntensity : 1.0f;
                     float pbr_ei = (SceneController != null) ? SceneController.skyboxOptions.directDrawSurface.emissiveIntensity : 1.0f;
                     float pbr_si = (SceneController != null) ? SceneController.skyboxOptions.directDrawSurface.specularIntensity : 1.0f;
                     float pbr_ri = (SceneController != null) ? SceneController.skyboxOptions.directDrawSurface.environmentIntensity : 1.0f;
                     var   skybox = new BabylonMesh();
                     skybox.id = Guid.NewGuid().ToString();
                     skybox.infiniteDistance   = true;
                     skybox.numBoneInfluencers = Tools.GetMaxBoneInfluencers();
                     if (!String.IsNullOrEmpty(tags))
                     {
                         skybox.tags = tags;
                     }
                     skybox.name = "SceneSkyboxMesh";
                     Mesh boxMesh = Tools.CreateBoxMesh(size, size, size);
                     Tools.GenerateBabylonMeshData(boxMesh, skybox);
                     BabylonMaterial skyboxMaterial = null;
                     if (dds == true && pbr == true)
                     {
                         var skyboxMaterialPbr = new BabylonSystemMaterial {
                             name                      = "SceneSkyboxMaterial",
                             id                        = Guid.NewGuid().ToString(),
                             backFaceCulling           = false,
                             disableLighting           = true,
                             albedo                    = Color.white.ToFloat(),
                             ambient                   = Color.black.ToFloat(),
                             emissive                  = Color.black.ToFloat(),
                             metallic                  = null,
                             roughness                 = null,
                             sideOrientation           = 1,
                             reflectivity              = Color.white.ToFloat(),
                             reflection                = Color.white.ToFloat(),
                             microSurface              = pbr_ms,
                             cameraContrast            = pbr_cc,
                             cameraExposure            = pbr_ce,
                             directIntensity           = pbr_di,
                             emissiveIntensity         = pbr_ei,
                             specularIntensity         = pbr_si,
                             environmentIntensity      = pbr_ri,
                             maxSimultaneousLights     = 4,
                             useSpecularOverAlpha      = false,
                             useRadianceOverAlpha      = false,
                             usePhysicalLightFalloff   = false,
                             useAlphaFromAlbedoTexture = false,
                             useEmissiveAsIllumination = false,
                             reflectionTexture         = skytex
                         };
                         skyboxMaterial = skyboxMaterialPbr;
                     }
                     else
                     {
                         var skyboxMaterialStd = new BabylonDefaultMaterial {
                             name              = "SceneSkyboxMaterial",
                             id                = Guid.NewGuid().ToString(),
                             backFaceCulling   = false,
                             disableLighting   = true,
                             diffuse           = Color.black.ToFloat(),
                             specular          = Color.black.ToFloat(),
                             ambient           = Color.clear.ToFloat(),
                             reflectionTexture = skytex
                         };
                         skyboxMaterial = skyboxMaterialStd;
                     }
                     if (skyboxMaterial != null)
                     {
                         skybox.materialId = skyboxMaterial.id;
                         babylonScene.MeshesList.Add(skybox);
                         babylonScene.MaterialsList.Add(skyboxMaterial);
                         babylonScene.AddTextureCube("SceneSkyboxMaterial");
                     }
                 }
             }
         }
     }
 }
示例#17
0
        public void Filter(string inputFile, string inputExt, bool createSkybox, bool createRadiance)
        {
            string faceExt        = ".dds";
            int    cubeSize       = convertCube.height;
            string outputFile     = inputFile.Replace(inputExt, faceExt);
            string outputSkybox   = outputFile.Replace(".dds", "_sky.dds");
            string outputRadiance = outputFile.Replace(".dds", "_env.dds");

            if (inputExt.Equals(".hdr", StringComparison.OrdinalIgnoreCase) || inputExt.Equals(".exr", StringComparison.OrdinalIgnoreCase))
            {
                string hdrTexturePath = null;
                if (inputExt.Equals(".exr", StringComparison.OrdinalIgnoreCase))
                {
                    ExporterWindow.ReportProgress(1, "Parsing source cubemap texture... This may take a while.");
                    hdrTexturePath = (Path.GetTempFileName() + ".hdr");
                    string     srcTexturePath = Tools.GetNativePath(inputFile);
                    FileStream sourceStream   = new FileStream(srcTexturePath, FileMode.Open, FileAccess.Read);
                    try
                    {
                        bool    readResult       = false;
                        int     readWidth        = 0;
                        int     readHeight       = 0;
                        int     readBitsPerPixel = 0;
                        Color[] pixels           = Tools.ReadFreeImage(sourceStream, ref readResult, ref readWidth, ref readHeight, ref readBitsPerPixel, Tools.ColorCorrection.NoCorrection);
                        if (readResult == true && pixels != null)
                        {
                            var tempTexture = new Texture2D(readWidth, readHeight, TextureFormat.RGBAFloat, false);
                            tempTexture.SetPixels(pixels);
                            tempTexture.Apply();
                            tempTexture.WriteImageHDR(hdrTexturePath);
                        }
                        else
                        {
                            UnityEngine.Debug.LogError("Failed to convert exr/hdr file");
                        }
                    } catch (Exception ex) {
                        UnityEngine.Debug.LogException(ex);
                    } finally {
                        sourceStream.Close();
                    }
                    inputFile = hdrTexturePath;
                    inputExt  = Path.GetExtension(inputFile);
                }
                if (createSkybox == true && generateSkybox == true)
                {
                    ExporterWindow.ReportProgress(1, "Baking skybox cubemap texture... This may take a while.");
                    Tools.ConvertCubemap(inputFile, outputSkybox, cubeSize, filterOutput, filterLighting, false, glossScale, gloassBias, excludeBase, numberOfCpus, inputGammaNumerator, inputGammaDenominator, outputGammaNumerator, outputGammaDenominator);
                    AssetDatabase.ImportAsset(outputSkybox, ImportAssetOptions.ForceUpdate);
                }
                if (createRadiance == true && generateRadiance == true)
                {
                    ExporterWindow.ReportProgress(1, "Baking radiance cubemap texture... This may take a while.");
                    Tools.ConvertCubemap(inputFile, outputRadiance, (int)radianceSize, filterOutput, filterLighting, true, glossScale, gloassBias, excludeBase, numberOfCpus, inputGammaNumerator, inputGammaDenominator, outputGammaNumerator, outputGammaDenominator);
                    AssetDatabase.ImportAsset(outputRadiance, ImportAssetOptions.ForceUpdate);
                }
                if (!String.IsNullOrEmpty(hdrTexturePath) && File.Exists(hdrTexturePath))
                {
                    try{ File.Delete(hdrTexturePath); } catch {}
                }
                if (createSkybox == true && generateSkybox == true && createSkyboxMaterial == true)
                {
                    ExporterWindow.ReportProgress(1, "Generating skybox material assets... This may take a while.");
                    AssetDatabase.Refresh();
                    Material skyboxMaterial = new Material(Shader.Find("Skybox/Cubemap"));
                    if (skyboxMaterial != null)
                    {
                        Cubemap ddsTexture = (Cubemap)AssetDatabase.LoadAssetAtPath(outputSkybox, typeof(Cubemap));
                        if (ddsTexture != null)
                        {
                            skyboxMaterial.SetTexture("_Tex", ddsTexture);
                        }

                        string outputMaterialName = Path.GetFileNameWithoutExtension(outputFile);
                        string outputMaterialPath = Path.GetDirectoryName(outputFile);
                        string outputMaterialFile = outputMaterialPath + "/" + outputMaterialName + ".mat";
                        AssetDatabase.CreateAsset(skyboxMaterial, outputMaterialFile);
                    }
                    else
                    {
                        UnityEngine.Debug.LogError("CMFT: Failed to locate 'Skybox/Cubemap' shader material");
                    }
                }
            }
            else
            {
                UnityEngine.Debug.LogError("CMFT: Unsupported cubemap file type " + inputExt);
            }
        }
示例#18
0
        private BabylonMesh ConvertUnityMeshToBabylon(Mesh mesh, Transform transform, GameObject gameObject, float progress, ref UnityMetaData metaData, ref List <BabylonExport.Entities.BabylonParticleSystem> particleSystems, ref List <UnityFlareSystem> lensFlares, ref string componentTags, BabylonMesh collisionMesh = null, Collider collider = null)
        {
            BabylonMesh babylonMesh = new BabylonMesh();

            metaData.type = "Mesh";
            if (!String.IsNullOrEmpty(componentTags))
            {
                babylonMesh.tags = componentTags;
            }

            ExporterWindow.ReportProgress(progress, "Exporting mesh: " + gameObject.name);

            babylonMesh.name = gameObject.name;
            babylonMesh.id   = GetID(transform.gameObject);

            var renderer = gameObject.GetComponent <Renderer>();

            if (renderer != null)
            {
                babylonMesh.receiveShadows = renderer.receiveShadows;
            }

            babylonMesh.parentId = GetParentID(transform);

            babylonMesh.position = transform.localPosition.ToFloat();

            babylonMesh.rotation    = new float[3];
            babylonMesh.rotation[0] = transform.localRotation.eulerAngles.x * (float)Math.PI / 180;
            babylonMesh.rotation[1] = transform.localRotation.eulerAngles.y * (float)Math.PI / 180;
            babylonMesh.rotation[2] = transform.localRotation.eulerAngles.z * (float)Math.PI / 180;

            babylonMesh.scaling         = transform.localScale.ToFloat();
            babylonMesh.checkCollisions = false;

            // Collision mesh (With detail mesh fallback)
            string collisionMeshId = null;

            if (collider != null)
            {
                if (collisionMesh != null)
                {
                    collisionMeshId               = collisionMesh.id;
                    collisionMesh.parentId        = babylonMesh.id;
                    collisionMesh.visibility      = collider.isTrigger ? 0.25f : 0.5f;
                    collisionMesh.checkCollisions = (exportationOptions.ExportCollisions && collider.isTrigger == false);
                }
                else
                {
                    babylonMesh.checkCollisions = exportationOptions.ExportCollisions;
                }
            }
            metaData.properties["collisionMeshId"] = collisionMeshId;

            if (mesh != null)
            {
                Tools.GenerateBabylonMeshData(mesh, babylonMesh, babylonScene, transform);
                int index = 0;
                if (mesh.boneWeights.Length == mesh.vertexCount)
                {
                    babylonMesh.matricesIndices = new int[mesh.vertexCount];
                    babylonMesh.matricesWeights = new float[mesh.vertexCount * 4];
                    index = 0;
                    foreach (BoneWeight bw in mesh.boneWeights)
                    {
                        babylonMesh.matricesIndices[index]         = (bw.boneIndex3 << 24) | (bw.boneIndex2 << 16) | (bw.boneIndex1 << 8) | bw.boneIndex0;
                        babylonMesh.matricesWeights[index * 4 + 0] = bw.weight0;
                        babylonMesh.matricesWeights[index * 4 + 1] = bw.weight1;
                        babylonMesh.matricesWeights[index * 4 + 2] = bw.weight2;
                        babylonMesh.matricesWeights[index * 4 + 3] = bw.weight3;
                        var totalWeight = bw.weight0 + bw.weight1 + bw.weight2 + bw.weight3;
                        if (Mathf.Abs(totalWeight - 1.0f) > 0.01f)
                        {
                            throw new Exception("Total bone weights is not normalized for: " + mesh);
                        }
                        index++;
                    }
                }
                index = 0;
                if (renderer != null && renderer.sharedMaterial != null)
                {
                    // Validate Multi Materials
                    if (mesh.subMeshCount > 1)
                    {
                        BabylonMultiMaterial bMultiMat;

                        string multiMatName = "";
                        for (int i = 0; i < renderer.sharedMaterials.Length; i++)
                        {
                            multiMatName += renderer.sharedMaterials[i].name;
                        }


                        if (!multiMatDictionary.ContainsKey(multiMatName))
                        {
                            bMultiMat = new BabylonMultiMaterial
                            {
                                materials = new string[mesh.subMeshCount],
                                id        = Guid.NewGuid().ToString(),
                                name      = multiMatName
                            };

                            for (int i = 0; i < renderer.sharedMaterials.Length; i++)
                            {
                                var             sharedMaterial = renderer.sharedMaterials[i];
                                BabylonMaterial babylonMaterial;

                                babylonMaterial = DumpMaterial(sharedMaterial, renderer.lightmapIndex, renderer.lightmapScaleOffset);

                                bMultiMat.materials[i] = babylonMaterial.id;
                            }
                            if (mesh.subMeshCount > 1)
                            {
                                multiMatDictionary.Add(bMultiMat.name, bMultiMat);
                            }
                        }
                        else
                        {
                            bMultiMat = multiMatDictionary[multiMatName];
                        }

                        babylonMesh.materialId = bMultiMat.id;
                        babylonMesh.subMeshes  = new BabylonSubMesh[mesh.subMeshCount];

                        var offset = 0;
                        for (int materialIndex = 0; materialIndex < mesh.subMeshCount; materialIndex++)
                        {
                            var unityTriangles = mesh.GetTriangles(materialIndex);
                            babylonMesh.subMeshes[materialIndex] = new BabylonSubMesh
                            {
                                verticesStart = 0,
                                verticesCount = mesh.vertexCount,
                                materialIndex = materialIndex,
                                indexStart    = offset,
                                indexCount    = unityTriangles.Length
                            };
                            offset += unityTriangles.Length;
                        }
                    }
                    else
                    {
                        babylonMesh.materialId = DumpMaterial(renderer.sharedMaterial, renderer.lightmapIndex, renderer.lightmapScaleOffset).id;
                    }
                }

                babylonMesh.metadata = metaData;
                babylonScene.MeshesList.Add(babylonMesh);

                // Animations
                ExportAnimations(transform, babylonMesh);
                if (IsRotationQuaternionAnimated(babylonMesh))
                {
                    babylonMesh.rotationQuaternion = transform.localRotation.ToFloat();
                }

                // Lens Flares
                ParseLensFlares(gameObject, babylonMesh.id, ref lensFlares);

                // Particles Systems
                ParseParticleSystems(gameObject, babylonMesh.id, ref particleSystems);

                // Babylon Physics
                if (exportationOptions.ExportPhysics)
                {
                    var physics = gameObject.GetComponent <BabylonPhysicsState>();
                    if (physics != null)
                    {
                        babylonMesh.physicsMass        = physics.mass;
                        babylonMesh.physicsFriction    = physics.friction;
                        babylonMesh.physicsRestitution = physics.restitution;
                        babylonMesh.physicsImpostor    = (int)physics.imposter;
                    }
                }
            }
            return(babylonMesh);
        }
示例#19
0
        private void ConvertUnityMeshToBabylon(Mesh mesh, Transform transform, GameObject gameObject, float progress)
        {
            BabylonMesh babylonMesh = new BabylonMesh();
            var         renderer    = gameObject.GetComponent <Renderer>();

            ExporterWindow.ReportProgress(progress, "Exporting mesh: " + gameObject.name);

            babylonMesh.name = gameObject.name;
            babylonMesh.id   = GetID(transform.gameObject);

            if (renderer != null)
            {
                babylonMesh.receiveShadows = renderer.receiveShadows;
            }

            babylonMesh.parentId = GetParentID(transform);

            babylonMesh.position = transform.localPosition.ToFloat();

            babylonMesh.rotation    = new float[3];
            babylonMesh.rotation[0] = transform.localRotation.eulerAngles.x * (float)Math.PI / 180;
            babylonMesh.rotation[1] = transform.localRotation.eulerAngles.y * (float)Math.PI / 180;
            babylonMesh.rotation[2] = transform.localRotation.eulerAngles.z * (float)Math.PI / 180;

            babylonMesh.scaling = transform.localScale.ToFloat();

            if (mesh != null)
            {
                babylonMesh.positions = new float[mesh.vertexCount * 3];

                for (int i = 0; i < mesh.vertices.Length; i++)
                {
                    babylonMesh.positions[i * 3]       = mesh.vertices[i].x;
                    babylonMesh.positions[(i * 3) + 1] = mesh.vertices[i].y;
                    babylonMesh.positions[(i * 3) + 2] = mesh.vertices[i].z;

                    // Computing world extends
                    var worldPosition = transform.TransformPoint(mesh.vertices[i]);

                    if (worldPosition.x > babylonScene.MaxVector.X)
                    {
                        babylonScene.MaxVector.X = worldPosition.x;
                    }
                    if (worldPosition.y > babylonScene.MaxVector.Y)
                    {
                        babylonScene.MaxVector.Y = worldPosition.y;
                    }
                    if (worldPosition.z > babylonScene.MaxVector.Z)
                    {
                        babylonScene.MaxVector.Z = worldPosition.z;
                    }

                    if (worldPosition.x < babylonScene.MinVector.X)
                    {
                        babylonScene.MinVector.X = worldPosition.x;
                    }
                    if (worldPosition.y < babylonScene.MinVector.Y)
                    {
                        babylonScene.MinVector.Y = worldPosition.y;
                    }
                    if (worldPosition.z < babylonScene.MinVector.Z)
                    {
                        babylonScene.MinVector.Z = worldPosition.z;
                    }
                }

                babylonMesh.normals = new float[mesh.vertexCount * 3];

                for (int i = 0; i < mesh.normals.Length; i++)
                {
                    babylonMesh.normals[i * 3]       = mesh.normals[i].x;
                    babylonMesh.normals[(i * 3) + 1] = mesh.normals[i].y;
                    babylonMesh.normals[(i * 3) + 2] = mesh.normals[i].z;
                }

                babylonMesh.uvs = new float[mesh.vertexCount * 2];

                for (int i = 0; i < mesh.uv.Length; i++)
                {
                    babylonMesh.uvs[i * 2]       = mesh.uv[i].x;
                    babylonMesh.uvs[(i * 2) + 1] = mesh.uv[i].y;
                }

                babylonMesh.uvs2 = new float[mesh.vertexCount * 2];

                if (mesh.uv2 != null && mesh.uv2.Length > 0)
                {
                    for (int i = 0; i < mesh.uv2.Length; i++)
                    {
                        babylonMesh.uvs2[i * 2]       = mesh.uv2[i].x;
                        babylonMesh.uvs2[(i * 2) + 1] = mesh.uv2[i].y;
                    }
                }
                else
                {
                    for (int i = 0; i < mesh.uv.Length; i++)
                    {
                        babylonMesh.uvs2[i * 2]       = mesh.uv[i].x;
                        babylonMesh.uvs2[(i * 2) + 1] = mesh.uv[i].y;
                    }
                }

                babylonMesh.indices = new int[mesh.triangles.Length];

                for (int i = 0; i < mesh.triangles.Length; i += 3)
                {
                    babylonMesh.indices[i]     = mesh.triangles[i + 2];
                    babylonMesh.indices[i + 1] = mesh.triangles[i + 1];
                    babylonMesh.indices[i + 2] = mesh.triangles[i];
                }

                if (renderer != null && renderer.sharedMaterial != null)
                {
                    if (mesh.subMeshCount > 1) // Multimaterials
                    {
                        BabylonMultiMaterial bMultiMat;
                        if (!multiMatDictionary.ContainsKey(renderer.sharedMaterial.name))
                        {
                            bMultiMat = new BabylonMultiMaterial
                            {
                                materials = new string[mesh.subMeshCount],
                                id        = Guid.NewGuid().ToString(),
                                name      = renderer.sharedMaterial.name
                            };

                            for (int i = 0; i < renderer.sharedMaterials.Length; i++)
                            {
                                var             sharedMaterial = renderer.sharedMaterials[i];
                                BabylonMaterial babylonMaterial;

                                babylonMaterial = DumpMaterial(sharedMaterial, renderer);

                                bMultiMat.materials[i] = babylonMaterial.id;
                            }
                            if (mesh.subMeshCount > 1)
                            {
                                multiMatDictionary.Add(bMultiMat.name, bMultiMat);
                            }
                        }
                        else
                        {
                            bMultiMat = multiMatDictionary[renderer.sharedMaterial.name];
                        }

                        babylonMesh.materialId = bMultiMat.id;
                        babylonMesh.subMeshes  = new BabylonSubMesh[mesh.subMeshCount];

                        var offset = 0;
                        for (int materialIndex = 0; materialIndex < mesh.subMeshCount; materialIndex++)
                        {
                            var unityTriangles = mesh.GetTriangles(materialIndex);

                            babylonMesh.subMeshes[materialIndex] = new BabylonSubMesh
                            {
                                verticesStart = 0,
                                verticesCount = mesh.vertexCount,
                                materialIndex = materialIndex,
                                indexStart    = offset,
                                indexCount    = unityTriangles.Length
                            };

                            offset += unityTriangles.Length;
                        }
                    }
                    else
                    {
                        babylonMesh.materialId = DumpMaterial(renderer.sharedMaterial, renderer).id;
                    }
                }

                babylonScene.MeshesList.Add(babylonMesh);

                // Animations
                ExportAnimations(transform, babylonMesh);

                if (IsRotationQuaternionAnimated(babylonMesh))
                {
                    babylonMesh.rotationQuaternion = transform.localRotation.ToFloat();
                }

                // Collisions
                if (exportationOptions.ExportCollisions)
                {
                    var collider = gameObject.GetComponent <Collider>();

                    if (collider != null)
                    {
                        babylonMesh.checkCollisions = true;
                    }
                }
            }
        }
示例#20
0
        public void CreateTextureAtlas()
        {
            if (skinMeshRenderer != null && skinMeshRenderer.sharedMaterials != null && skinMeshRenderer.sharedMaterials.Length > 1)
            {
                string filename = EditorUtility.SaveFilePanelInProject("Texture Atlas Skin", "", "asset", "Bake Skin Mesh Renderer Texture Atlas");
                if (!String.IsNullOrEmpty(filename))
                {
                    ExporterWindow.ReportProgress(1, "Baking texture atlas skin... This may take a while.");
                    string filepath  = Path.GetDirectoryName(filename);
                    string filelabel = Path.GetFileNameWithoutExtension(filename);
                    Tools.ValidateAssetFolders(filepath.TrimEnd('/'));

                    // Texture atlas file info
                    bool   jpeg         = (textureAtlasFormat == BabylonImageFormat.JPEG);
                    string atlasExt     = (jpeg) ? "jpg" : "png";
                    string atlasName    = String.Format("{0}_Atlas", filelabel);
                    string atlasFile    = String.Format("{0}/Textures/{1}.{2}", filepath.TrimEnd('/'), atlasName, atlasExt);
                    string bumpName     = String.Format("{0}_Normal", filelabel);
                    string bumpFile     = String.Format("{0}/Textures/{1}.{2}", filepath.TrimEnd('/'), bumpName, atlasExt);
                    string materialName = String.Format("{0}_Material", filelabel);
                    string materialFile = String.Format("{0}/Materials/{1}.asset", filepath.TrimEnd('/'), materialName);

                    // Create atlas textures
                    mainTextures = new List <Texture2D>();
                    bumpTextures = new List <Texture2D>();
                    foreach (var material in skinMeshRenderer.sharedMaterials)
                    {
                        Texture2D colorTexture  = null;
                        Texture2D normalTexture = null;
                        if (material.mainTexture != null)
                        {
                            Texture2D primaryTexture = material.mainTexture as Texture2D;
                            primaryTexture.ForceReadable();
                            colorTexture = primaryTexture.Copy();
                            if (bakeTextureNormals)
                            {
                                if (material.HasProperty("_BumpMap"))
                                {
                                    Texture2D bumpTexture = material.GetTexture("_BumpMap") as Texture2D;
                                    if (bumpTexture != null && bumpTexture.width == colorTexture.width && bumpTexture.height == colorTexture.height)
                                    {
                                        // Format texture import settings
                                        string bumpTexturePath = AssetDatabase.GetAssetPath(bumpTexture);
                                        var    importTool      = new BabylonTextureImporter(bumpTexturePath);
                                        var    importType      = importTool.textureImporter.textureType;
                                        try
                                        {
                                            importTool.textureImporter.isReadable  = true;
                                            importTool.textureImporter.textureType = TextureImporterType.Default;
                                            importTool.ForceUpdate();
                                            normalTexture  = bumpTexture.Copy();
                                            hasBumpTexture = true;
                                        }
                                        catch (Exception ex)
                                        {
                                            UnityEngine.Debug.LogException(ex);
                                        }
                                        finally
                                        {
                                            // Restore texture importer type
                                            importTool.textureImporter.textureType = importType;
                                            importTool.ForceUpdate();
                                        }
                                    }
                                }
                            }
                        }
                        if (colorTexture == null)
                        {
                            colorTexture = new Texture2D(128, 128, TextureFormat.RGBA32, false);
                            colorTexture.Clear(material.color);
                            normalTexture = null;
                        }
                        if (normalTexture == null)
                        {
                            normalTexture = Tools.CreateBlankNormalMap(colorTexture.width, colorTexture.height);
                        }
                        // Buffer baked material info
                        mainTextures.Add(colorTexture);
                        bumpTextures.Add(normalTexture);
                    }

                    // Encode atlas textures
                    bool      bilinearScaling    = (textureImageScaling == BabylonTextureScale.Bilinear);
                    Texture2D skinnedMeshAtlas   = new Texture2D(128, 128, TextureFormat.RGBA32, false);
                    Rect[]    atlasPackingResult = Tools.PackTextureAtlas(skinnedMeshAtlas, mainTextures.ToArray(), textureAtlasSize, maxTextureImageSize, bilinearScaling, false, removeAlphaEncoding);
                    Texture2D skinnedMeshBuffer  = skinnedMeshAtlas.Copy();
                    skinnedMeshBuffer.WriteImage(atlasFile, textureAtlasFormat);
                    AssetDatabase.ImportAsset(atlasFile, ImportAssetOptions.ForceUpdate);

                    // Create atlas material
                    if (textureAtlasShader == null)
                    {
                        textureAtlasShader = Shader.Find("BabylonJS/System/Standard Material");
                    }
                    atlasMaterial             = new Material(textureAtlasShader);
                    atlasMaterial.name        = materialName;
                    atlasMaterial.mainTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(atlasFile, typeof(Texture2D));
                    AssetDatabase.CreateAsset(atlasMaterial, materialFile);
                    if (bakeTextureNormals && hasBumpTexture)
                    {
                        bumpFilename = bumpFile;
                    }

                    // Texture atlas uv coordinates
                    Mesh           mesh    = skinMeshRenderer.sharedMesh;
                    int            numSubs = mesh.subMeshCount;
                    int            uvCount = mesh.uv.Length;
                    List <Vector2> uvList  = new List <Vector2>();
                    if (atlasPackingResult != null && atlasPackingResult.Length > 0)
                    {
                        for (int ctr = 0; ctr < numSubs; ctr++)
                        {
                            Mesh      sub = mesh.GetSubmesh(ctr);
                            Vector2[] uvs = Tools.GetTextureAtlasCoordinates(sub.uv, ctr, atlasPackingResult, linearInterpolation);
                            uvList.AddRange(uvs);
                        }
                        if (uvList.Count != uvCount)
                        {
                            throw new Exception("Skin vertex count mismatch. Failed to convert uv coordinates.");
                        }
                    }
                    else
                    {
                        UnityEngine.Debug.LogError("Null atlas packing result rects");
                    }

                    // Create new mesh asset
                    Mesh newmesh = mesh.Copy();
                    if (uvList.Count > 0)
                    {
                        newmesh.uv = uvList.ToArray();
                    }

                    // Save new mesh asset
                    string label    = Tools.FirstUpper(materialName.Replace("_Material", ""));
                    string meshName = String.Format("{0}_{1}_Mesh", label, skinMeshRenderer.name);
                    string meshFile = String.Format("{0}/Geometry/{1}.asset", filepath.TrimEnd('/'), meshName);
                    AssetDatabase.CreateAsset(newmesh, meshFile);
                    if (updateSkinRenderer)
                    {
                        skinMeshRenderer.sharedMesh      = (Mesh)AssetDatabase.LoadAssetAtPath(meshFile, typeof(Mesh));
                        skinMeshRenderer.sharedMaterials = new Material[] { (Material)AssetDatabase.LoadAssetAtPath(materialFile, typeof(Material)) };
                    }
                }
            }
            else
            {
                ExporterWindow.ShowMessage("At least 2 materials required for texture atlas skin");
            }
        }
示例#21
0
        private void ConvertUnityLightToBabylon(Light light, GameObject gameObject, float progress, ref UnityMetaData metaData, ref List <UnityFlareSystem> lensFlares, ref string componentTags)
        {
            // Note: No Inactive Or Full Baking Lights Exported
            if (light.isActiveAndEnabled == false || light.type == LightType.Area || light.lightmapBakeType == LightmapBakeType.Baked)
            {
                return;
            }

            ExporterWindow.ReportProgress(progress, "Exporting light: " + light.name);
            BabylonLight babylonLight = (light.type == LightType.Directional) ? new BabylonDirectionalLight() : new BabylonLight();

            babylonLight.name     = light.name;
            babylonLight.id       = GetID(light.gameObject);
            babylonLight.parentId = GetParentID(light.transform);

            metaData.type     = "Light";
            babylonLight.tags = componentTags;

            switch (light.type)
            {
            case LightType.Point:
                babylonLight.type  = 0;
                babylonLight.range = light.range;
                break;

            case LightType.Directional:
                babylonLight.type = 1;
                break;

            case LightType.Spot:
                babylonLight.type = 2;
                break;
            }

            babylonLight.position = light.transform.localPosition.ToFloat();

            var direction             = new Vector3(0, 0, 1);
            var transformedDirection  = light.transform.TransformDirection(direction);
            var defaultRotationOffset = (SceneController != null) ? SceneController.lightingOptions.rotationOffset : ExporterWindow.DefaultRotationOffset;

            transformedDirection[0] += defaultRotationOffset.x;
            transformedDirection[1] += defaultRotationOffset.y;
            transformedDirection[2] += defaultRotationOffset.z;
            babylonLight.direction   = transformedDirection.ToFloat();

            babylonLight.diffuse = light.color.ToFloat();

            float defaultIntenistyFactor = (SceneController != null) ? SceneController.lightingOptions.intensityScale : ExporterWindow.DefaultIntensityScale;

            babylonLight.intensity = light.intensity * defaultIntenistyFactor;

            babylonLight.angle    = light.spotAngle * (float)Math.PI / 180;
            babylonLight.exponent = 1.0f;

            // Animations
            ExportTransformAnimationClips(light.transform, babylonLight, ref metaData);

            // Tagging
            if (!String.IsNullOrEmpty(babylonLight.tags))
            {
                babylonLight.tags = babylonLight.tags.Trim();
            }

            babylonLight.metadata = metaData;
            babylonScene.LightsList.Add(babylonLight);

            // Lens Flares
            ParseLensFlares(gameObject, babylonLight.id, ref lensFlares);

            // Realtime Shadow Maps (Scene Controller Required)
            if ((light.type == LightType.Directional || light.type == LightType.Point || light.type == LightType.Spot) && light.shadows != LightShadows.None)
            {
                GenerateShadowsGenerator(babylonLight, light, progress);
            }
            if (!exportationOptions.ExportMetadata)
            {
                babylonLight.metadata = null;
            }
        }
示例#22
0
        public void Bake()
        {
            // Validate Project Platform
            if (!Unity3D2Babylon.Tools.ValidateProjectPlatform())
            {
                return;
            }

            try
            {
                string inputFile = AssetDatabase.GetAssetPath(convertCube);
                string inputExt  = Path.GetExtension(inputFile);
                if (cubemapTool == BabylonCubemapTool.ReflectionProbes)
                {
                    if (inputExt.Equals(".hdr", StringComparison.OrdinalIgnoreCase) || inputExt.Equals(".exr", StringComparison.OrdinalIgnoreCase))
                    {
                        ExporterWindow.ReportProgress(1, "Baking cubemap reflection probe... This may take a while.");
                        string            outputFile           = inputFile.Replace(inputExt, "Probe.hdr");
                        int               reflectionResolution = (int)reflectionType;
                        FREE_IMAGE_FORMAT srcType = FREE_IMAGE_FORMAT.FIF_HDR;
                        if (inputExt.Equals(".hdr", StringComparison.OrdinalIgnoreCase))
                        {
                            srcType = FREE_IMAGE_FORMAT.FIF_HDR;
                        }
                        else if (inputExt.Equals(".exr", StringComparison.OrdinalIgnoreCase))
                        {
                            srcType = FREE_IMAGE_FORMAT.FIF_EXR;
                        }
                        FREE_IMAGE_FILTER rescaleFilter = FREE_IMAGE_FILTER.FILTER_LANCZOS3;
                        int        rescaleWidth         = reflectionResolution * 4;
                        int        rescaleHeight        = rescaleWidth / 2;
                        FileStream destStream           = new FileStream(outputFile, FileMode.Create, FileAccess.Write);
                        FileStream sourceStream         = new FileStream(inputFile, FileMode.Open, FileAccess.Read);
                        try
                        {
                            Tools.ConvertFreeImage(sourceStream, srcType, destStream, FREE_IMAGE_FORMAT.FIF_HDR, FREE_IMAGE_TYPE.FIT_UNKNOWN, true, FREE_IMAGE_COLOR_DEPTH.FICD_AUTO, FREE_IMAGE_LOAD_FLAGS.DEFAULT, FREE_IMAGE_SAVE_FLAGS.DEFAULT, 0.0, false, false, rescaleWidth, rescaleHeight, rescaleFilter);
                        } catch (Exception ex) {
                            UnityEngine.Debug.LogException(ex);
                        } finally {
                            destStream.Close();
                            sourceStream.Close();
                        }
                        if (System.IO.File.Exists(outputFile))
                        {
                            AssetDatabase.ImportAsset(outputFile, ImportAssetOptions.ForceUpdate);
                            var importTool = new BabylonTextureImporter(outputFile);
                            importTool.textureImporter.textureShape = TextureImporterShape.TextureCube;
                            importTool.textureImporter.isReadable   = true;
                            importTool.ForceUpdate();
                        }
                    }
                    else
                    {
                        ExporterWindow.ShowMessage("You must select a high dynamic range cubemap");
                    }
                }
                else if (cubemapTool == BabylonCubemapTool.CubemapSplitter)
                {
                    ExporterWindow.ReportProgress(1, "Baking cubemap texture faces... This may take a while.");
                    bool   jpeg         = (imageFormat == BabylonImageFormat.JPEG);
                    string faceExt      = (jpeg) ? ".jpg" : ".png";
                    var    splitterOpts = new BabylonSplitterOptions();
                    var    outputFile   = inputFile.Replace(inputExt, faceExt);
                    Tools.ExportCubemap(convertCube, outputFile, imageFormat, splitterOpts);
                    if (createSkyboxMaterial == true)
                    {
                        ExporterWindow.ReportProgress(1, "Generating skybox material assets... This may take a while.");
                        AssetDatabase.Refresh();
                        Material skyboxMaterial = new Material(Shader.Find("Mobile/Skybox"));
                        if (skyboxMaterial != null)
                        {
                            string frontFilename = outputFile.Replace(faceExt, ("_pz" + faceExt));
                            AssetDatabase.ImportAsset(frontFilename, ImportAssetOptions.ForceUpdate);
                            Texture2D frontTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(frontFilename, typeof(Texture2D));
                            if (frontTexture != null)
                            {
                                skyboxMaterial.SetTexture("_FrontTex", frontTexture);
                            }

                            string backFilename = outputFile.Replace(faceExt, ("_nz" + faceExt));
                            AssetDatabase.ImportAsset(backFilename, ImportAssetOptions.ForceUpdate);
                            Texture2D backTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(backFilename, typeof(Texture2D));
                            if (backTexture != null)
                            {
                                skyboxMaterial.SetTexture("_BackTex", backTexture);
                            }

                            string leftFilename = outputFile.Replace(faceExt, ("_px" + faceExt));
                            AssetDatabase.ImportAsset(leftFilename, ImportAssetOptions.ForceUpdate);
                            Texture2D leftTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(leftFilename, typeof(Texture2D));
                            if (leftTexture != null)
                            {
                                skyboxMaterial.SetTexture("_LeftTex", leftTexture);
                            }

                            string rightFilename = outputFile.Replace(faceExt, ("_nx" + faceExt));
                            AssetDatabase.ImportAsset(rightFilename, ImportAssetOptions.ForceUpdate);
                            Texture2D rightTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(rightFilename, typeof(Texture2D));
                            if (rightTexture != null)
                            {
                                skyboxMaterial.SetTexture("_RightTex", rightTexture);
                            }

                            string upFilename = outputFile.Replace(faceExt, ("_py" + faceExt));
                            AssetDatabase.ImportAsset(upFilename, ImportAssetOptions.ForceUpdate);
                            Texture2D upTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(upFilename, typeof(Texture2D));
                            if (upTexture != null)
                            {
                                skyboxMaterial.SetTexture("_UpTex", upTexture);
                            }

                            string downFilename = outputFile.Replace(faceExt, ("_ny" + faceExt));
                            AssetDatabase.ImportAsset(downFilename, ImportAssetOptions.ForceUpdate);
                            Texture2D downTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(downFilename, typeof(Texture2D));
                            if (downTexture != null)
                            {
                                skyboxMaterial.SetTexture("_DownTex", downTexture);
                            }

                            string outputMaterialName = Path.GetFileNameWithoutExtension(inputFile);
                            string outputMaterialPath = Path.GetDirectoryName(inputFile);
                            string outputMaterialFile = outputMaterialPath + "/" + outputMaterialName + ".mat";
                            AssetDatabase.CreateAsset(skyboxMaterial, outputMaterialFile);
                        }
                        else
                        {
                            throw new Exception("Failed to create 'Mobile/Skybox' material");
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                UnityEngine.Debug.LogException(ex);
            }
            finally
            {
                ExporterWindow.ReportProgress(1, "Refresing assets database...");
                AssetDatabase.Refresh();
            }
            ExporterWindow.ReportProgress(1, "Cubemap conversion complete.");
            EditorUtility.ClearProgressBar();
            if (this.keepGeneratorOpen)
            {
                ExporterWindow.ShowMessage("Cubemap optimzation complete.", "Babylon.js");
            }
            else
            {
                this.Close();
            }
        }
示例#23
0
 private void ConvertUnitySkyboxToBabylon(Camera camera, float progress)
 {
     // Note: Only Support Main Camera Skyboxes
     if (Camera.main == camera && (camera.clearFlags & CameraClearFlags.Skybox) == CameraClearFlags.Skybox)
     {
         // Note: Only Support Tone Mapped Skyboxes
         if (RenderSettings.skybox != null)
         {
             BabylonTexture skytex = null;
             if (RenderSettings.skybox.shader.name == "Skybox/Cubemap")
             {
                 var cubeMap = RenderSettings.skybox.GetTexture("_Tex") as Cubemap;
                 if (cubeMap != null)
                 {
                     var cubeTextureFile = AssetDatabase.GetAssetPath(cubeMap);
                     var cubeTextureExt  = Path.GetExtension(cubeTextureFile);
                     if (!cubeTextureExt.Equals(".dds", StringComparison.OrdinalIgnoreCase))
                     {
                         ExporterWindow.ReportProgress(progress, "Baking skybox environment textures... This may take a while.");
                         var faceTextureExt    = ".jpg";
                         var faceTextureFormat = BabylonImageFormat.JPEG;
                         if (exportationOptions.ImageEncodingOptions == (int)BabylonImageFormat.PNG)
                         {
                             faceTextureExt    = ".png";
                             faceTextureFormat = BabylonImageFormat.PNG;
                         }
                         string frontTextureExt = "_pz" + faceTextureExt;
                         string backTextureExt  = "_nz" + faceTextureExt;
                         string leftTextureExt  = "_px" + faceTextureExt;
                         string rightTextureExt = "_nx" + faceTextureExt;
                         string upTextureExt    = "_py" + faceTextureExt;
                         string downTextureExt  = "_ny" + faceTextureExt;
                         skytex                 = new BabylonTexture();
                         skytex.name            = String.Format("{0}_Skybox", SceneName);
                         skytex.isCube          = true;
                         skytex.coordinatesMode = 5;
                         skytex.extensions      = new string[] { leftTextureExt, upTextureExt, frontTextureExt, rightTextureExt, downTextureExt, backTextureExt };
                         Tools.SetTextureWrapMode(skytex, cubeMap);
                         var outputFile   = Path.Combine(babylonScene.OutputPath, skytex.name + faceTextureExt);
                         var splitterOpts = new BabylonSplitterOptions();
                         this.skyboxTextures = Tools.ExportCubemap(cubeMap, outputFile, faceTextureFormat, splitterOpts);
                     }
                     else
                     {
                         UnityEngine.Debug.LogWarning("SKYBOX: Unsupported cubemap texture type of " + cubeTextureExt + " for " + Path.GetFileName(cubeTextureFile));
                         return;
                     }
                 }
             }
             else if (RenderSettings.skybox.shader.name == "Skybox/6 Sided" || RenderSettings.skybox.shader.name == "Mobile/Skybox")
             {
                 // 6-Sided Skybox Textures (Tone Mapped Image Formats Only)
                 var frontTexture = RenderSettings.skybox.GetTexture("_FrontTex") as Texture2D;
                 var backTexture  = RenderSettings.skybox.GetTexture("_BackTex") as Texture2D;
                 var leftTexture  = RenderSettings.skybox.GetTexture("_LeftTex") as Texture2D;
                 var rightTexture = RenderSettings.skybox.GetTexture("_RightTex") as Texture2D;
                 var upTexture    = RenderSettings.skybox.GetTexture("_UpTex") as Texture2D;
                 var downTexture  = RenderSettings.skybox.GetTexture("_DownTex") as Texture2D;
                 if (frontTexture != null && backTexture != null && leftTexture != null && rightTexture != null && upTexture != null && downTexture != null)
                 {
                     ExporterWindow.ReportProgress(progress, "Exporting skybox environment textures... This may take a while.");
                     string frontTextureExt = "_pz.jpg";
                     string backTextureExt  = "_nz.jpg";
                     string leftTextureExt  = "_px.jpg";
                     string rightTextureExt = "_nx.jpg";
                     string upTextureExt    = "_py.jpg";
                     string downTextureExt  = "_ny.jpg";
                     skytex                 = new BabylonTexture();
                     skytex.name            = String.Format("{0}_Skybox", SceneName);
                     skytex.isCube          = true;
                     skytex.coordinatesMode = 5;
                     Tools.SetTextureWrapMode(skytex, frontTexture);
                     List <Tools.TextureInfo> faces = new List <Tools.TextureInfo>();
                     var faceTextureFile            = AssetDatabase.GetAssetPath(frontTexture);
                     var faceTextureExt             = Path.GetExtension(faceTextureFile);
                     var faceImportTool             = new BabylonTextureImporter(faceTextureFile);
                     if (faceTextureExt.Equals(".png", StringComparison.OrdinalIgnoreCase) || faceTextureExt.Equals(".jpg", StringComparison.OrdinalIgnoreCase) || faceTextureExt.Equals(".jpeg", StringComparison.OrdinalIgnoreCase))
                     {
                         frontTextureExt = "_pz" + faceTextureExt;
                         var frontTextureName = String.Format("{0}_pz{1}", skytex.name, faceTextureExt);
                         var frontTexturePath = Path.Combine(babylonScene.OutputPath, frontTextureName);
                         faceImportTool.SetReadable();
                         CopyTextureFace(frontTexturePath, frontTextureName, frontTexture);
                         faces.Add(new Tools.TextureInfo {
                             filename = frontTexturePath, texture = frontTexture.Copy()
                         });
                     }
                     else
                     {
                         UnityEngine.Debug.LogWarning("SKYBOX: Unsupported cube face texture type of " + faceTextureExt + " for " + Path.GetFileName(faceTextureFile));
                     }
                     faceTextureFile = AssetDatabase.GetAssetPath(backTexture);
                     faceTextureExt  = Path.GetExtension(faceTextureFile);
                     faceImportTool  = new BabylonTextureImporter(faceTextureFile);
                     if (faceTextureExt.Equals(".png", StringComparison.OrdinalIgnoreCase) || faceTextureExt.Equals(".jpg", StringComparison.OrdinalIgnoreCase) || faceTextureExt.Equals(".jpeg", StringComparison.OrdinalIgnoreCase))
                     {
                         backTextureExt = "_nz" + faceTextureExt;
                         var backTextureName = String.Format("{0}_nz{1}", skytex.name, faceTextureExt);
                         var backTexturePath = Path.Combine(babylonScene.OutputPath, backTextureName);
                         faceImportTool.SetReadable();
                         CopyTextureFace(backTexturePath, backTextureName, backTexture);
                         faces.Add(new Tools.TextureInfo {
                             filename = backTexturePath, texture = backTexture.Copy()
                         });
                     }
                     else
                     {
                         UnityEngine.Debug.LogWarning("SKYBOX: Unsupported cube face texture type of " + faceTextureExt + " for " + Path.GetFileName(faceTextureFile));
                     }
                     faceTextureFile = AssetDatabase.GetAssetPath(leftTexture);
                     faceTextureExt  = Path.GetExtension(faceTextureFile);
                     faceImportTool  = new BabylonTextureImporter(faceTextureFile);
                     if (faceTextureExt.Equals(".png", StringComparison.OrdinalIgnoreCase) || faceTextureExt.Equals(".jpg", StringComparison.OrdinalIgnoreCase) || faceTextureExt.Equals(".jpeg", StringComparison.OrdinalIgnoreCase))
                     {
                         leftTextureExt = "_px" + faceTextureExt;
                         var leftTextureName = String.Format("{0}_px{1}", skytex.name, faceTextureExt);
                         var leftTexturePath = Path.Combine(babylonScene.OutputPath, leftTextureName);
                         faceImportTool.SetReadable();
                         CopyTextureFace(leftTexturePath, leftTextureName, leftTexture);
                         faces.Add(new Tools.TextureInfo {
                             filename = leftTexturePath, texture = leftTexture.Copy()
                         });
                     }
                     else
                     {
                         UnityEngine.Debug.LogWarning("SKYBOX: Unsupported cube face texture type of " + faceTextureExt + " for " + Path.GetFileName(faceTextureFile));
                     }
                     faceTextureFile = AssetDatabase.GetAssetPath(rightTexture);
                     faceTextureExt  = Path.GetExtension(faceTextureFile);
                     faceImportTool  = new BabylonTextureImporter(faceTextureFile);
                     if (faceTextureExt.Equals(".png", StringComparison.OrdinalIgnoreCase) || faceTextureExt.Equals(".jpg", StringComparison.OrdinalIgnoreCase) || faceTextureExt.Equals(".jpeg", StringComparison.OrdinalIgnoreCase))
                     {
                         rightTextureExt = "_nx" + faceTextureExt;
                         var rightTextureName = String.Format("{0}_nx{1}", skytex.name, faceTextureExt);
                         var rightTexturePath = Path.Combine(babylonScene.OutputPath, rightTextureName);
                         faceImportTool.SetReadable();
                         CopyTextureFace(rightTexturePath, rightTextureName, rightTexture);
                         faces.Add(new Tools.TextureInfo {
                             filename = rightTexturePath, texture = rightTexture.Copy()
                         });
                     }
                     else
                     {
                         UnityEngine.Debug.LogWarning("SKYBOX: Unsupported cube face texture type of " + faceTextureExt + " for " + Path.GetFileName(faceTextureFile));
                     }
                     faceTextureFile = AssetDatabase.GetAssetPath(upTexture);
                     faceTextureExt  = Path.GetExtension(faceTextureFile);
                     faceImportTool  = new BabylonTextureImporter(faceTextureFile);
                     if (faceTextureExt.Equals(".png", StringComparison.OrdinalIgnoreCase) || faceTextureExt.Equals(".jpg", StringComparison.OrdinalIgnoreCase) || faceTextureExt.Equals(".jpeg", StringComparison.OrdinalIgnoreCase))
                     {
                         upTextureExt = "_py" + faceTextureExt;
                         var upTextureName = String.Format("{0}_py{1}", skytex.name, faceTextureExt);
                         var upTexturePath = Path.Combine(babylonScene.OutputPath, upTextureName);
                         faceImportTool.SetReadable();
                         CopyTextureFace(upTexturePath, upTextureName, upTexture);
                         faces.Add(new Tools.TextureInfo {
                             filename = upTexturePath, texture = upTexture.Copy()
                         });
                     }
                     else
                     {
                         UnityEngine.Debug.LogWarning("SKYBOX: Unsupported cube face texture type of " + faceTextureExt + " for " + Path.GetFileName(faceTextureFile));
                     }
                     faceTextureFile = AssetDatabase.GetAssetPath(downTexture);
                     faceTextureExt  = Path.GetExtension(faceTextureFile);
                     faceImportTool  = new BabylonTextureImporter(faceTextureFile);
                     if (faceTextureExt.Equals(".png", StringComparison.OrdinalIgnoreCase) || faceTextureExt.Equals(".jpg", StringComparison.OrdinalIgnoreCase) || faceTextureExt.Equals(".jpeg", StringComparison.OrdinalIgnoreCase))
                     {
                         downTextureExt = "_ny" + faceTextureExt;
                         var downTextureName = String.Format("{0}_ny{1}", skytex.name, faceTextureExt);
                         var downTexturePath = Path.Combine(babylonScene.OutputPath, downTextureName);
                         faceImportTool.SetReadable();
                         CopyTextureFace(downTexturePath, downTexturePath, downTexture);
                         faces.Add(new Tools.TextureInfo {
                             filename = downTexturePath, texture = downTexture.Copy()
                         });
                     }
                     else
                     {
                         UnityEngine.Debug.LogWarning("SKYBOX: Unsupported cube face texture type of " + faceTextureExt + " for " + Path.GetFileName(faceTextureFile));
                     }
                     skytex.extensions   = new string[] { leftTextureExt, upTextureExt, frontTextureExt, rightTextureExt, downTextureExt, backTextureExt };
                     this.skyboxTextures = (faces.Count > 0) ? faces.ToArray() : null;
                 }
             }
             if (skytex != null)
             {
                 skytex.level = (SceneController != null) ? SceneController.skyboxOptions.skyTextureLevel : 1.0f;
                 string meshTags     = (SceneController != null) ? SceneController.skyboxOptions.meshTags : String.Empty;
                 float  skyboxSize   = (SceneController != null) ? SceneController.skyboxOptions.skyMeshSize : 1000;
                 bool   skyboxSphere = (SceneController != null) ? (SceneController.skyboxOptions.meshType == BabylonSkyboxType.Sphere) : false;
                 // Babylon Skybox Mesh
                 var skybox = new BabylonMesh();
                 skybox.id = Guid.NewGuid().ToString();
                 skybox.infiniteDistance   = true;
                 skybox.numBoneInfluencers = Tools.GetMaxBoneInfluencers();
                 if (!String.IsNullOrEmpty(meshTags))
                 {
                     skybox.tags = meshTags;
                 }
                 if (skyboxSphere)
                 {
                     skybox.name = "sceneSkyboxSphere";
                     Mesh sphereMesh = Tools.CreateSphereMesh(skyboxSize * 0.5f, 48, 48);
                     Tools.GenerateBabylonMeshData(sphereMesh, skybox);
                 }
                 else
                 {
                     skybox.name = "sceneSkyboxCube";
                     Mesh boxMesh = Tools.CreateBoxMesh(skyboxSize, skyboxSize, skyboxSize);
                     Tools.GenerateBabylonMeshData(boxMesh, skybox);
                 }
                 // Babylon Default Skybox
                 var skyboxMaterial = new BabylonDefaultMaterial();
                 skyboxMaterial.name              = "sceneSkyboxMaterial";
                 skyboxMaterial.id                = Guid.NewGuid().ToString();
                 skyboxMaterial.backFaceCulling   = false;
                 skyboxMaterial.disableLighting   = true;
                 skyboxMaterial.diffuse           = Color.black.ToFloat();
                 skyboxMaterial.specular          = Color.black.ToFloat();
                 skyboxMaterial.ambient           = Color.clear.ToFloat();
                 skyboxMaterial.reflectionTexture = skytex;
                 // Babylon Skybox Material
                 skybox.materialId = skyboxMaterial.id;
                 babylonScene.MeshesList.Add(skybox);
                 babylonScene.MaterialsList.Add(skyboxMaterial);
                 babylonScene.AddTextureCube("sceneSkyboxMaterial");
             }
         }
     }
 }
示例#24
0
        private void ConvertUnityCameraToBabylon(Camera camera, GameObject gameObject, float progress, ref UnityMetaData metaData, ref List <UnityFlareSystem> lensFlares, ref string componentTags)
        {
            ExporterWindow.ReportProgress(progress, "Exporting camera: " + camera.name);

            BabylonUniversalCamera babylonCamera = new BabylonUniversalCamera
            {
                name     = camera.name,
                id       = GetID(camera.gameObject),
                fov      = camera.fieldOfView * (float)Math.PI / 180,
                minZ     = camera.nearClipPlane,
                maxZ     = camera.farClipPlane,
                parentId = GetParentID(camera.transform),
                position = camera.transform.localPosition.ToFloat()
            };

            if (camera.transform.parent != null)
            {
                babylonCamera.rotation    = new float[3];
                babylonCamera.rotation[0] = camera.transform.localRotation.eulerAngles.x * (float)Math.PI / 180;
                babylonCamera.rotation[1] = camera.transform.localRotation.eulerAngles.y * (float)Math.PI / 180;
                babylonCamera.rotation[2] = camera.transform.localRotation.eulerAngles.z * (float)Math.PI / 180;
            }
            else
            {
                var target            = new Vector3(0, 0, 1);
                var transformedTarget = camera.transform.TransformDirection(target);
                babylonCamera.target = (camera.transform.position + transformedTarget).ToFloat();
            }

            if (camera.orthographic)
            {
                babylonCamera.tags += " [ORTHOGRAPHIC]";
                babylonCamera.mode  = 1;
            }
            else
            {
                babylonCamera.mode = 0;
            }

            bool preventDefault  = false;
            bool virtualJoystick = false;

            bool   trackPosition = false;
            float  positionScale = 1.0f;
            string displayName   = "";

            int   horizontalRes        = 1280;
            int   verticalRes          = 800;
            float horizontalScreen     = 0.1497f;
            float verticalScreen       = 0.0935f;
            float screenCenter         = 0.0468f;
            float cameraBridge         = 0.005f;
            float eyeToScreen          = 0.0410f;
            float interpupillary       = 0.0640f;
            float lensSeparation       = 0.0635f;
            float lensCenterOffset     = 0.1520f;
            float postProcessScale     = 1.7146f;
            bool  compensateDistortion = true;

            float  ratio             = 1.0f;
            float  exposure          = 1.0f;
            float  gaussCoeff        = 0.3f;
            float  gaussMean         = 1.0f;
            float  gaussStandDev     = 0.8f;
            float  gaussMultiplier   = 4.0f;
            float  brightThreshold   = 0.8f;
            float  minimumLuminance  = 1.0f;
            float  maximumLuminance  = 1e20f;
            float  luminanceIncrease = 0.5f;
            float  luminanceDecrease = 0.5f;
            bool   stereoSideBySide  = false;
            int    cameraRigInput    = 0;
            float  cameraMoveSpeed   = 1.0f;
            float  cameraRotateSpeed = 0.005f;
            string cameraRigType     = "UniversalCamera";
            var    rigger            = gameObject.GetComponent <CameraRig>();

            if (rigger != null && rigger.isActiveAndEnabled)
            {
                cameraRigType                    = rigger.cameraType.ToString();
                cameraRigInput                   = (int)rigger.cameraInput;
                cameraMoveSpeed                  = rigger.inputMoveSpeed;
                cameraRotateSpeed                = rigger.inputRotateSpeed;
                babylonCamera.speed              = rigger.cameraSpeed;
                babylonCamera.inertia            = rigger.inertiaScaleFactor;
                babylonCamera.interaxialDistance = rigger.interaxialDistance;
                preventDefault                   = rigger.preventDefaultEvents;
                stereoSideBySide                 = rigger.stereoscopicSideBySide;
                virtualJoystick                  = (rigger.cameraType == BabylonCameraOptions.VirtualJoysticksCamera);

                trackPosition = rigger.virtualRealityWebPlatform.trackPosition;
                positionScale = rigger.virtualRealityWebPlatform.positionScale;
                displayName   = rigger.virtualRealityWebPlatform.displayName;;

                horizontalRes        = rigger.virtualRealityHeadsetOptions.horizontalResolution;
                verticalRes          = rigger.virtualRealityHeadsetOptions.verticalResolution;
                horizontalScreen     = rigger.virtualRealityHeadsetOptions.horizontalScreen;
                verticalScreen       = rigger.virtualRealityHeadsetOptions.verticalScreen;
                screenCenter         = rigger.virtualRealityHeadsetOptions.screenCenter;
                cameraBridge         = rigger.virtualRealityHeadsetOptions.cameraBridge;
                eyeToScreen          = rigger.virtualRealityHeadsetOptions.eyeToScreen;
                interpupillary       = rigger.virtualRealityHeadsetOptions.interpupillary;
                lensSeparation       = rigger.virtualRealityHeadsetOptions.lensSeparation;
                lensCenterOffset     = rigger.virtualRealityHeadsetOptions.lensCenterOffset;
                postProcessScale     = rigger.virtualRealityHeadsetOptions.postProcessScale;
                compensateDistortion = rigger.virtualRealityHeadsetOptions.compensateDistortion;

                ratio             = rigger.highDynamicRenderingPipeline.ratio;
                exposure          = rigger.highDynamicRenderingPipeline.exposure;
                gaussCoeff        = rigger.highDynamicRenderingPipeline.gaussCoeff;
                gaussMean         = rigger.highDynamicRenderingPipeline.gaussMean;
                gaussStandDev     = rigger.highDynamicRenderingPipeline.gaussStandDev;
                gaussMultiplier   = rigger.highDynamicRenderingPipeline.gaussMultiplier;
                brightThreshold   = rigger.highDynamicRenderingPipeline.brightThreshold;
                minimumLuminance  = rigger.highDynamicRenderingPipeline.minimumLuminance;
                maximumLuminance  = rigger.highDynamicRenderingPipeline.maximumLuminance;
                luminanceIncrease = rigger.highDynamicRenderingPipeline.luminanceIncrease;
                luminanceDecrease = rigger.highDynamicRenderingPipeline.luminanceDecrease;
            }
            SceneBuilder.Metadata.properties["virtualJoystickAttached"] = virtualJoystick;

            metaData.type = "Camera";
            metaData.properties.Add("cameraType", cameraRigType);
            metaData.properties.Add("cameraInput", cameraRigInput);
            metaData.properties.Add("clearFlags", camera.clearFlags.ToString());
            metaData.properties.Add("clearColor", camera.backgroundColor.ToFloat());
            metaData.properties.Add("cullingMask", camera.cullingMask);
            metaData.properties.Add("isOrthographic", camera.orthographic);
            metaData.properties.Add("orthographicSize", camera.orthographicSize);
            metaData.properties.Add("cameraMoveSpeed", cameraMoveSpeed);
            metaData.properties.Add("cameraRotateSpeed", cameraRotateSpeed);
            metaData.properties.Add("useOcclusionCulling", camera.useOcclusionCulling);
            metaData.properties.Add("preventDefaultEvents", preventDefault);
            metaData.properties.Add("stereoscopicSideBySide", stereoSideBySide);

            metaData.properties.Add("wvrTrackPosition", trackPosition);
            metaData.properties.Add("wvrPositionScale", positionScale);
            metaData.properties.Add("wvrDisplayName", displayName);

            metaData.properties.Add("vrHorizontalRes", horizontalRes);
            metaData.properties.Add("vrVerticalRes", verticalRes);
            metaData.properties.Add("vrHorizontalScreen", horizontalScreen);
            metaData.properties.Add("vrVerticalScreen", verticalScreen);
            metaData.properties.Add("vrScreenCenter", screenCenter);
            metaData.properties.Add("vrCameraBridge", cameraBridge);
            metaData.properties.Add("vrEyeToScreen", eyeToScreen);
            metaData.properties.Add("vrInterpupillary", interpupillary);
            metaData.properties.Add("vrLensSeparation", lensSeparation);
            metaData.properties.Add("vrLensCenterOffset", lensCenterOffset);
            metaData.properties.Add("vrPostProcessScale", postProcessScale);
            metaData.properties.Add("vrCompensateDistortion", compensateDistortion);

            metaData.properties.Add("hdr", camera.allowHDR);
            metaData.properties.Add("hdrPipeline", null);
            metaData.properties.Add("hdrRatio", ratio);
            metaData.properties.Add("hdrExposure", exposure);
            metaData.properties.Add("hdrGaussCoeff", gaussCoeff);
            metaData.properties.Add("hdrGaussMean", gaussMean);
            metaData.properties.Add("hdrGaussStandDev", gaussStandDev);
            metaData.properties.Add("hdrGaussMultiplier", gaussMultiplier);
            metaData.properties.Add("hdrBrightThreshold", brightThreshold);
            metaData.properties.Add("hdrMinimumLuminance", minimumLuminance);
            metaData.properties.Add("hdrMaximumLuminance", maximumLuminance);
            metaData.properties.Add("hdrLuminanceIncrease", luminanceIncrease);
            metaData.properties.Add("hdrLuminanceDecrease", luminanceDecrease);

            babylonCamera.isStereoscopicSideBySide = stereoSideBySide;
            babylonCamera.type = cameraRigType;
            babylonCamera.tags = componentTags;

            // Animations
            ExportTransformAnimationClips(camera.transform, babylonCamera, ref metaData);

            // Tagging
            if (!String.IsNullOrEmpty(babylonCamera.tags))
            {
                babylonCamera.tags = babylonCamera.tags.Trim();
            }

            babylonCamera.metadata = metaData;
            babylonScene.CamerasList.Add(babylonCamera);

            if (Camera.main == camera)
            {
                babylonScene.activeCameraID = babylonCamera.id;
                babylonScene.clearColor     = camera.backgroundColor.ToFloat();
            }

            // Collisions
            if (exportationOptions.ExportCollisions)
            {
                // TODO: Move To Camera Rig Options and Otherwise defaults
                babylonCamera.checkCollisions = true;
                if (SceneController != null)
                {
                    babylonCamera.applyGravity = (SceneController.sceneOptions.defaultGravity.y == 0.0f && SceneController.sceneOptions.defaultGravity.y == 0.0f && SceneController.sceneOptions.defaultGravity.z == 0.0f) ? false : true;
                    babylonCamera.ellipsoid    = SceneController.sceneOptions.defaultEllipsoid.ToFloat();
                }
            }

            // Lens Flares
            ParseLensFlares(gameObject, babylonCamera.id, ref lensFlares);

            // Particles Systems
            if (!exportationOptions.ExportMetadata)
            {
                babylonCamera.metadata = null;
            }
        }
示例#25
0
        private BabylonMesh ConvertUnityTerrainToBabylon(Terrain terrain, GameObject gameObject, float progress, ref UnityMetaData metaData, ref List <BabylonExport.Entities.BabylonParticleSystem> particleSystems, ref List <UnityFlareSystem> lensFlares, ref string componentTags)
        {
            ExporterWindow.ReportProgress(progress, "Exporting terrain: " + gameObject.name);
            var transform = gameObject.transform;

            float[] position = transform.localPosition.ToFloat();
            float[] rotation = new float[3];
            rotation[0] = transform.localRotation.eulerAngles.x * (float)Math.PI / 180;
            rotation[1] = transform.localRotation.eulerAngles.y * (float)Math.PI / 180;
            rotation[2] = transform.localRotation.eulerAngles.z * (float)Math.PI / 180;
            float[] scaling = transform.localScale.ToFloat();

            BabylonMesh babylonMesh = new BabylonMesh {
                name = gameObject.name, id = GetID(gameObject)
            };

            metaData.type = "Terrain";
            if (!String.IsNullOrEmpty(componentTags))
            {
                babylonMesh.tags = componentTags;
            }
            babylonMesh.tags += " [TERRAIN]";
            if (!String.IsNullOrEmpty(babylonMesh.tags))
            {
                babylonMesh.tags = babylonMesh.tags.Trim();
            }
            babylonMesh.parentId                   = GetParentID(transform);
            babylonMesh.position                   = Vector3.zero.ToFloat();
            babylonMesh.rotation                   = rotation;
            babylonMesh.scaling                    = scaling;
            babylonMesh.isVisible                  = true;
            babylonMesh.visibility                 = 1;
            babylonMesh.checkCollisions            = false;
            metaData.properties["collisionMeshId"] = null;

            var generator = gameObject.GetComponent <BabylonTerrainGenerator>();

            if (generator != null && terrain != null)
            {
                // TODO: Terrain tree information
                object treeInstances  = null;
                object treePrototypes = null;

                // Terrain metadata infomation
                Vector3 terrainSize = terrain.terrainData.size;
                metaData.properties.Add("width", terrainSize.x);
                metaData.properties.Add("length", terrainSize.z);
                metaData.properties.Add("height", terrainSize.y);
                metaData.properties.Add("position", position);
                metaData.properties.Add("rotation", rotation);
                metaData.properties.Add("scaling", scaling);
                metaData.properties.Add("thickness", terrain.terrainData.thickness);
                metaData.properties.Add("detailWidth", terrain.terrainData.detailWidth);
                metaData.properties.Add("detailHeight", terrain.terrainData.detailHeight);
                metaData.properties.Add("heightmapWidth", terrain.terrainData.heightmapWidth);
                metaData.properties.Add("heightmapHeight", terrain.terrainData.heightmapHeight);
                metaData.properties.Add("wavingGrassAmount", terrain.terrainData.wavingGrassAmount);
                metaData.properties.Add("wavingGrassSpeed", terrain.terrainData.wavingGrassSpeed);
                metaData.properties.Add("wavingGrassStrength", terrain.terrainData.wavingGrassStrength);
                metaData.properties.Add("wavingGrassTint", terrain.terrainData.wavingGrassTint.ToFloat());
                metaData.properties.Add("treeInstanceCount", terrain.terrainData.treeInstanceCount);
                metaData.properties.Add("treeInstances", treeInstances);
                metaData.properties.Add("treePrototypes", treePrototypes);
                metaData.properties.Add("physicsState", generator.physicsActive);
                metaData.properties.Add("physicsMass", generator.physicsMass);
                metaData.properties.Add("physicsFriction", generator.physicsFriction);
                metaData.properties.Add("physicsRestitution", generator.physicsRestitution);
                metaData.properties.Add("physicsImpostor", (int)generator.physicsImpostor);
                metaData.properties.Add("groundTessellation", generator.groundTessellation);

                // Generate detailed mesh
                ExporterWindow.ReportProgress(progress, "Generating terrain mesh: " + gameObject.name);
                BabylonTerrainData terrainMeshData = Unity3D2Babylon.Tools.CreateTerrainData(terrain.terrainData, (int)generator.terrainResolution, transform.localPosition, true);
                Tools.GenerateBabylonMeshTerrainData(terrainMeshData, babylonMesh, false, babylonScene, transform);
                if (generator.surfaceMaterial != null)
                {
                    babylonMesh.materialId = DumpMaterial(generator.surfaceMaterial, terrain.lightmapIndex, terrain.lightmapScaleOffset, generator.coordinatesIndex).id;
                }

                // Generate collision heightmap
                var terrainCollider = gameObject.GetComponent <TerrainCollider>();
                if (terrainCollider != null && terrainCollider.enabled)
                {
                    ExporterWindow.ReportProgress(progress, "Generating terrain heightmap: " + gameObject.name);
                    float minheight = float.MaxValue;
                    float maxheight = float.MinValue;
                    int   hwidth    = terrain.terrainData.heightmapWidth;
                    int   hheight   = terrain.terrainData.heightmapHeight;
                    float[,] rawHeights = terrain.terrainData.GetHeights(0, 0, hwidth, hheight);
                    Texture2D heightMap = new Texture2D(hwidth, hheight, TextureFormat.ARGB32, false);
                    for (int y = 0; y < hheight; y++)
                    {
                        for (int x = 0; x < hwidth; x++)
                        {
                            float inverted = rawHeights[y, x];
                            minheight = Mathf.Min(minheight, inverted);
                            maxheight = Mathf.Max(maxheight, inverted);
                        }
                    }
                    List <Color32> pixels = new List <Color32>();
                    for (int y = 0; y < hheight; y++)
                    {
                        for (int x = 0; x < hwidth; x++)
                        {
                            float inverted = rawHeights[y, x];
                            if (generator.heightmapStrength > 0)
                            {
                                float threadhold = minheight + generator.floorThreashold;
                                if (inverted > threadhold)
                                {
                                    inverted += (generator.heightmapStrength / 10.0f);
                                }
                            }
                            byte[] packed = BitConverter.GetBytes(inverted);
                            if (packed != null && packed.Length >= 4)
                            {
                                pixels.Add(new Color32(packed[0], packed[1], packed[2], packed[3]));
                            }
                        }
                    }
                    heightMap.SetPixels32(pixels.ToArray());
                    heightMap.Apply();
                    byte[] heightmapBytes = heightMap.EncodeToPNG();
                    metaData.properties.Add("heightmapBase64", ("data:image/png;base64," + Convert.ToBase64String(heightmapBytes)));
                }
            }
            else
            {
                UnityEngine.Debug.LogWarning("No valid terrain or generator found for: " + gameObject.name);
            }

            babylonMesh.metadata = metaData;
            babylonScene.MeshesList.Add(babylonMesh);
            SceneBuilder.Metadata.properties["hasTerrainMeshes"] = true;

            // Animations
            ExportAnimations(transform, babylonMesh);
            if (IsRotationQuaternionAnimated(babylonMesh))
            {
                babylonMesh.rotationQuaternion = transform.localRotation.ToFloat();
            }

            // Lens Flares
            ParseLensFlares(gameObject, babylonMesh.id, ref lensFlares);

            // Particles Systems
            ParseParticleSystems(gameObject, babylonMesh.id, ref particleSystems);

            return(babylonMesh);
        }
示例#26
0
        public void Parse()
        {
            // Validate Project Platform
            if (!Unity3D2Babylon.Tools.ValidateProjectPlatform())
            {
                return;
            }

            try
            {
                ExporterWindow.ReportProgress(1, "Generating particle system data... This may take a while.");
                System.Threading.Thread.Sleep(500);
                bool starting = (convertCurveValues == BabylonCurveValues.StartCurveValue);
                var  renderer = shurikenParticles.GetComponent <Renderer>();
                if (renderer != null)
                {
                    babylonParticles.textureImage = renderer.sharedMaterial.mainTexture as Texture2D;
                }
                babylonParticles.loopPlay = shurikenParticles.main.loop;
                babylonParticles.duration = shurikenParticles.main.duration;
                babylonParticles.capacity = shurikenParticles.main.maxParticles;

                // Bursting
                babylonParticles.emitBurst = null;
                if (shurikenParticles.emission.burstCount > 0)
                {
                    ParticleSystem.Burst[] bursts = new ParticleSystem.Burst[shurikenParticles.emission.burstCount];
                    shurikenParticles.emission.GetBursts(bursts);
                    var burstList = new List <BabylonParticleBusrt>();
                    foreach (var burst in bursts)
                    {
                        burstList.Add(new BabylonParticleBusrt()
                        {
                            time     = burst.time,
                            minCount = burst.minCount,
                            maxCount = burst.maxCount
                        });
                    }
                    if (burstList.Count > 0)
                    {
                        babylonParticles.emitBurst = burstList.ToArray();
                    }
                }

                // TODO: Direction

                // TODO: Volume

                // Gravity
                if (shurikenParticles.main.gravityModifier.mode == ParticleSystemCurveMode.Constant)
                {
                    babylonParticles.gravityMultiplier = shurikenParticles.main.gravityModifier.constant;
                }
                else if (shurikenParticles.main.gravityModifier.mode == ParticleSystemCurveMode.TwoConstants)
                {
                    babylonParticles.gravityMultiplier = (starting) ? shurikenParticles.main.gravityModifier.constantMin : shurikenParticles.main.gravityModifier.constantMax;
                }
                else if (shurikenParticles.main.gravityModifier.mode == ParticleSystemCurveMode.Curve)
                {
                    int curves = (starting) ? 0 : shurikenParticles.main.gravityModifier.curve.keys.Length - 1;
                    babylonParticles.gravityMultiplier = shurikenParticles.main.gravityModifier.curve.keys[curves].value;
                }
                else if (shurikenParticles.main.gravityModifier.mode == ParticleSystemCurveMode.TwoCurves)
                {
                    int curves = (starting) ? 0 : shurikenParticles.main.gravityModifier.curveMin.keys.Length - 1;
                    babylonParticles.gravityMultiplier = shurikenParticles.main.gravityModifier.curveMin.keys[curves].value;
                }
                else
                {
                    babylonParticles.gravityMultiplier = 1.0f;
                }

                // Delay
                if (shurikenParticles.main.startDelay.mode == ParticleSystemCurveMode.Constant)
                {
                    babylonParticles.delayTime = shurikenParticles.main.startDelay.constant;
                }
                else if (shurikenParticles.main.startDelay.mode == ParticleSystemCurveMode.TwoConstants)
                {
                    babylonParticles.delayTime = (starting) ? shurikenParticles.main.startDelay.constantMin : shurikenParticles.main.startDelay.constantMax;
                }
                else if (shurikenParticles.main.startDelay.mode == ParticleSystemCurveMode.Curve)
                {
                    int curves = (starting) ? 0 : shurikenParticles.main.startDelay.curve.keys.Length - 1;
                    babylonParticles.delayTime = shurikenParticles.main.startDelay.curve.keys[curves].value;
                }
                else if (shurikenParticles.main.startDelay.mode == ParticleSystemCurveMode.TwoCurves)
                {
                    int curves = (starting) ? 0 : shurikenParticles.main.startDelay.curveMin.keys.Length - 1;
                    babylonParticles.delayTime = shurikenParticles.main.startDelay.curveMin.keys[curves].value;
                }
                else
                {
                    babylonParticles.delayTime = 0.0f;
                }

                // Speed
                if (shurikenParticles.main.startSpeed.mode == ParticleSystemCurveMode.Constant)
                {
                    babylonParticles.startSpeed = shurikenParticles.main.startSpeed.constant * this.updateSpeedModifier;
                }
                else if (shurikenParticles.main.startSpeed.mode == ParticleSystemCurveMode.TwoConstants)
                {
                    float constant = (starting) ? shurikenParticles.main.startSpeed.constantMin : shurikenParticles.main.startSpeed.constantMax;
                    babylonParticles.startSpeed = constant * this.updateSpeedModifier;
                }
                else if (shurikenParticles.main.startSpeed.mode == ParticleSystemCurveMode.Curve)
                {
                    int curves = (starting) ? 0 : shurikenParticles.main.startSpeed.curve.keys.Length - 1;
                    babylonParticles.startSpeed = shurikenParticles.main.startSpeed.curve.keys[curves].value * this.updateSpeedModifier;
                }
                else if (shurikenParticles.main.startSpeed.mode == ParticleSystemCurveMode.TwoCurves)
                {
                    int curves = (starting) ? 0 : shurikenParticles.main.startSpeed.curveMin.keys.Length - 1;
                    babylonParticles.startSpeed = shurikenParticles.main.startSpeed.curveMin.keys[curves].value * this.updateSpeedModifier;
                }
                else
                {
                    babylonParticles.startSpeed = 0.01f;
                }

                // Emission
                babylonParticles.emitPower = new Vector2(1.0f, 1.0f);
                if (shurikenParticles.emission.rateOverTime.mode == ParticleSystemCurveMode.Constant)
                {
                    babylonParticles.emitRate = shurikenParticles.emission.rateOverTime.constant * this.emitRateModifier;
                }
                else if (shurikenParticles.emission.rateOverTime.mode == ParticleSystemCurveMode.TwoConstants)
                {
                    float constant = (starting) ? shurikenParticles.emission.rateOverTime.constantMin : shurikenParticles.emission.rateOverTime.constantMax;
                    babylonParticles.emitRate = constant * this.emitRateModifier;
                }
                else if (shurikenParticles.emission.rateOverTime.mode == ParticleSystemCurveMode.Curve)
                {
                    int curves = (starting) ? 0 : shurikenParticles.emission.rateOverTime.curve.keys.Length - 1;
                    babylonParticles.emitRate = shurikenParticles.emission.rateOverTime.curve.keys[curves].value * this.emitRateModifier;
                }
                else if (shurikenParticles.emission.rateOverTime.mode == ParticleSystemCurveMode.TwoCurves)
                {
                    int curves = (starting) ? 0 : shurikenParticles.emission.rateOverTime.curveMin.keys.Length - 1;
                    babylonParticles.emitRate = shurikenParticles.emission.rateOverTime.curveMin.keys[curves].value * this.emitRateModifier;
                }
                else
                {
                    babylonParticles.emitRate = 10.0f;
                }

                // Lifetime
                if (shurikenParticles.main.startLifetime.mode == ParticleSystemCurveMode.Constant)
                {
                    babylonParticles.lifeTime.x = shurikenParticles.main.startLifetime.constant;
                    babylonParticles.lifeTime.y = shurikenParticles.main.startLifetime.constant;
                }
                else if (shurikenParticles.main.startLifetime.mode == ParticleSystemCurveMode.TwoConstants)
                {
                    babylonParticles.lifeTime.x = shurikenParticles.main.startLifetime.constantMin;
                    babylonParticles.lifeTime.y = shurikenParticles.main.startLifetime.constantMax;
                }
                else if (shurikenParticles.main.startLifetime.mode == ParticleSystemCurveMode.Curve)
                {
                    int curves = shurikenParticles.main.startLifetime.curve.keys.Length - 1;
                    babylonParticles.lifeTime.x = shurikenParticles.main.startLifetime.curve.keys[0].value;
                    babylonParticles.lifeTime.y = shurikenParticles.main.startLifetime.curve.keys[curves].value;
                }
                else if (shurikenParticles.main.startLifetime.mode == ParticleSystemCurveMode.TwoCurves)
                {
                    int curves = shurikenParticles.main.startLifetime.curveMin.keys.Length - 1;
                    babylonParticles.lifeTime.x = shurikenParticles.main.startLifetime.curveMin.keys[0].value;
                    babylonParticles.lifeTime.y = shurikenParticles.main.startLifetime.curveMin.keys[curves].value;
                }
                else
                {
                    babylonParticles.lifeTime.x = 1.0f;
                    babylonParticles.lifeTime.y = 1.0f;
                }

                // Sizing
                if (shurikenParticles.main.startSize.mode == ParticleSystemCurveMode.Constant)
                {
                    babylonParticles.particleSize.x = shurikenParticles.main.startSize.constant;
                    babylonParticles.particleSize.y = shurikenParticles.main.startSize.constant;
                }
                else if (shurikenParticles.main.startSize.mode == ParticleSystemCurveMode.TwoConstants)
                {
                    babylonParticles.particleSize.x = shurikenParticles.main.startSize.constantMin;
                    babylonParticles.particleSize.y = shurikenParticles.main.startSize.constantMax;
                }
                else if (shurikenParticles.main.startSize.mode == ParticleSystemCurveMode.Curve)
                {
                    int curves = shurikenParticles.main.startSize.curve.keys.Length - 1;
                    babylonParticles.particleSize.x = shurikenParticles.main.startSize.curve.keys[0].value;
                    babylonParticles.particleSize.y = shurikenParticles.main.startSize.curve.keys[curves].value;
                }
                else if (shurikenParticles.main.startSize.mode == ParticleSystemCurveMode.TwoCurves)
                {
                    int curves = shurikenParticles.main.startSize.curveMin.keys.Length - 1;
                    babylonParticles.particleSize.x = shurikenParticles.main.startSize.curveMin.keys[0].value;
                    babylonParticles.particleSize.y = shurikenParticles.main.startSize.curveMin.keys[curves].value;
                }
                else
                {
                    babylonParticles.particleSize.x = 1.0f;
                    babylonParticles.particleSize.y = 1.0f;
                }

                // Rotation
                if (shurikenParticles.main.startRotation.mode == ParticleSystemCurveMode.Constant)
                {
                    babylonParticles.angularSpeed.x = shurikenParticles.main.startRotation.constant;
                    babylonParticles.angularSpeed.y = shurikenParticles.main.startRotation.constant;
                }
                else if (shurikenParticles.main.startRotation.mode == ParticleSystemCurveMode.TwoConstants)
                {
                    babylonParticles.angularSpeed.x = shurikenParticles.main.startRotation.constantMin;
                    babylonParticles.angularSpeed.y = shurikenParticles.main.startRotation.constantMax;
                }
                else if (shurikenParticles.main.startRotation.mode == ParticleSystemCurveMode.Curve)
                {
                    int curves = shurikenParticles.main.startRotation.curve.keys.Length - 1;
                    babylonParticles.angularSpeed.x = shurikenParticles.main.startRotation.curve.keys[0].value;
                    babylonParticles.angularSpeed.y = shurikenParticles.main.startRotation.curve.keys[curves].value;
                }
                else if (shurikenParticles.main.startRotation.mode == ParticleSystemCurveMode.TwoCurves)
                {
                    int curves = shurikenParticles.main.startRotation.curveMin.keys.Length - 1;
                    babylonParticles.angularSpeed.x = shurikenParticles.main.startRotation.curveMin.keys[0].value;
                    babylonParticles.angularSpeed.y = shurikenParticles.main.startRotation.curveMax.keys[curves].value;
                }
                else
                {
                    babylonParticles.angularSpeed.x = 0.0f;
                    babylonParticles.angularSpeed.y = 0.0f;
                }

                // Color
                if (shurikenParticles.main.startColor.mode == ParticleSystemGradientMode.Color)
                {
                    babylonParticles.color1 = shurikenParticles.main.startColor.color;
                    babylonParticles.color2 = shurikenParticles.main.startColor.color;
                }
                else if (shurikenParticles.main.startColor.mode == ParticleSystemGradientMode.TwoColors)
                {
                    babylonParticles.color1 = shurikenParticles.main.startColor.colorMin;
                    babylonParticles.color2 = shurikenParticles.main.startColor.colorMax;
                }
                else if (shurikenParticles.main.startColor.mode == ParticleSystemGradientMode.Gradient || shurikenParticles.main.startColor.mode == ParticleSystemGradientMode.RandomColor)
                {
                    int gradients = shurikenParticles.main.startColor.gradient.colorKeys.Length - 1;
                    babylonParticles.color1 = shurikenParticles.main.startColor.gradient.colorKeys[0].color;
                    babylonParticles.color2 = shurikenParticles.main.startColor.gradient.colorKeys[gradients].color;
                }
                else if (shurikenParticles.main.startColor.mode == ParticleSystemGradientMode.TwoGradients)
                {
                    int gradients = shurikenParticles.main.startColor.gradientMin.colorKeys.Length - 1;
                    babylonParticles.color1 = shurikenParticles.main.startColor.gradientMin.colorKeys[0].color;
                    babylonParticles.color2 = shurikenParticles.main.startColor.gradientMin.colorKeys[gradients].color;
                }
                else
                {
                    babylonParticles.color1 = defaultColor;
                    babylonParticles.color2 = defaultColor;
                }

                // Shuriken
                if (this.exportShurikenData)
                {
                    // TODO: Parse Shuriken Particle System Metadata
                }
            }
            catch (Exception ex)
            {
                UnityEngine.Debug.LogException(ex);
            }
            finally
            {
                ExporterWindow.ReportProgress(1, "Refresing assets database...");
                AssetDatabase.Refresh();
            }
            System.Threading.Thread.Sleep(500);
            ExporterWindow.ReportProgress(1, "Particle system generation complete.");
            EditorUtility.ClearProgressBar();
            if (this.keepGeneratorOpen)
            {
                ExporterWindow.ShowMessage("Particle system generation complete.", "Babylon.js");
            }
            else
            {
                this.Close();
            }
        }
示例#27
0
        public void ConvertFromUnity()
        {
            ExporterWindow.ReportProgress(0, "Starting Babylon.js exportation process...");

            gameObjects = Object.FindObjectsOfType(typeof(GameObject)) as GameObject[];

            if (gameObjects.Length == 0)
            {
                ExporterWindow.ShowMessage("No gameobject! - Please add at least a gameobject to export");
                return;
            }

            var itemsCount = gameObjects.Length;

            var index = 0;

            foreach (var gameObject in gameObjects)
            {
                var progress = ((float)index / itemsCount);
                index++;
                // Static meshes
                var meshFilter = gameObject.GetComponent <MeshFilter>();
                if (meshFilter != null)
                {
                    ConvertUnityMeshToBabylon(meshFilter.sharedMesh, meshFilter.transform, gameObject, progress);
                    continue;
                }

                // Skinned meshes
                var skinnedMesh = gameObject.GetComponent <SkinnedMeshRenderer>();
                if (skinnedMesh != null)
                {
                    var babylonMesh = ConvertUnityMeshToBabylon(skinnedMesh.sharedMesh, skinnedMesh.transform, gameObject, progress);
                    var skeleton    = ConvertUnitySkeletonToBabylon(skinnedMesh.bones, skinnedMesh.sharedMesh.bindposes, skinnedMesh.transform, gameObject, progress);
                    babylonMesh.skeletonId = skeleton.id;

                    ExportSkeletonAnimation(skinnedMesh, babylonMesh, skeleton);
                    continue;
                }

                // Light
                var light = gameObject.GetComponent <Light>();
                if (light != null)
                {
                    ConvertUnityLightToBabylon(light, progress);
                    continue;
                }

                // Camera
                var camera = gameObject.GetComponent <Camera>();
                if (camera != null)
                {
                    ConvertUnityCameraToBabylon(camera, progress);
                    ConvertUnitySkyboxToBabylon(camera, progress);
                    continue;
                }

                // Empty
                ConvertUnityEmptyObjectToBabylon(gameObject);
            }

            // Materials
            foreach (var mat in materialsDictionary)
            {
                babylonScene.MaterialsList.Add(mat.Value);
            }

            foreach (var multiMat in multiMatDictionary)
            {
                babylonScene.MultiMaterialsList.Add(multiMat.Value);
            }

            // Collisions
            if (exportationOptions.ExportCollisions)
            {
                babylonScene.gravity = exportationOptions.Gravity.ToFloat();
            }
        }
示例#28
0
        private static void ExportSkeletonAnimationClipData(GameObject source, BabylonSkeleton skeleton, SkinnedMeshRenderer skinnedMesh, BabylonMesh babylonMesh, UnityEditor.AnimationState animationState, ref List <AnimationClip> states, ref UnityMetaData metaData, Animator animator)
        {
            ExporterWindow.ReportProgress(1, "Exporting skeleton clips: " + skinnedMesh.name);
            //string sourceId = GetID(source);
            int frameRate       = 0;
            int firstClipEnd    = 0;
            int totalFrameCount = 0;

            Transform[]   bones          = skinnedMesh.bones;
            List <string> stateNameCache = new List <string>();

            if (!AnimationMode.InAnimationMode())
            {
                AnimationMode.StartAnimationMode();
            }
            //var anims = new List<BabylonAnimation>();
            //var pxkeys = new List<BabylonAnimationKey>();
            float playbackSpeed      = (animationState != null) ? animationState.playbackSpeed : 1.0f;
            float clampFeetPositions = (animationState != null) ? animationState.clampFeetPositions : 0.0f;
            BabylonAnimationBaking bakeRootTransforms = (animationState != null) ? animationState.bakeRootTransforms : BabylonAnimationBaking.GameBlend;

            foreach (var bone in skeleton.bones)
            {
                int       frameOffest = 0;
                var       keys        = new List <BabylonAnimationKey>();
                Transform transform   = bones.Single(b => b.name == bone.name);
                foreach (var state in states)
                {
                    if (state == null)
                    {
                        continue;
                    }
                    AnimationClip clip = state as AnimationClip;
                    if (frameRate <= 0)
                    {
                        frameRate = (int)clip.frameRate;
                    }
                    var frameTime      = 1.0f / frameRate;
                    int clipFrameCount = (int)(clip.length * frameRate);
                    if (firstClipEnd <= 0)
                    {
                        firstClipEnd = (clipFrameCount - 1);
                    }
                    var settings = AnimationUtility.GetAnimationClipSettings(clip);
                    BabylonLoopBehavior behavior = (settings.loopTime) ? BabylonLoopBehavior.Cycle : BabylonLoopBehavior.Constant;
                    if (settings.loopTime && settings.loopBlend)
                    {
                        behavior = BabylonLoopBehavior.Relative;
                    }
                    ExporterWindow.ReportProgress(1, "Sampling: " + babylonMesh.name + " - " + bone.name + " - " + clip.name);
                    // Set Animation State Meta Data
                    if (!stateNameCache.Contains(clip.name))
                    {
                        stateNameCache.Add(clip.name);
                        // Animation Clip Information
                        Dictionary <string, object> animStateInfo = new Dictionary <string, object>();
                        animStateInfo.Add("type", "skeleton");
                        animStateInfo.Add("name", clip.name);
                        animStateInfo.Add("start", frameOffest);
                        animStateInfo.Add("stop", (frameOffest + clipFrameCount - 1));
                        animStateInfo.Add("rate", frameRate);
                        animStateInfo.Add("behavior", (int)behavior);
                        animStateInfo.Add("playback", playbackSpeed);
                        metaData.animationClips.Add(animStateInfo);
                    }
                    AnimationMode.BeginSampling();
                    for (var i = 0; i < clipFrameCount; i++)
                    {
                        Matrix4x4 local;
                        int       frameIndex = (i + frameOffest);
                        float     originalPX = transform.localPosition.x;
                        float     originalPY = transform.localPosition.y;
                        float     originalPZ = transform.localPosition.z;
                        float     originalRY = transform.localRotation.eulerAngles.y;
                        clip.SampleAnimation(source, i * frameTime);
                        if (transform == skinnedMesh.rootBone)
                        {
                            float      positionX  = transform.localPosition.x;
                            float      positionY  = transform.localPosition.y;
                            float      positionZ  = transform.localPosition.z;
                            Quaternion rotationQT = transform.localRotation;
                            if (settings.loopBlendOrientation || settings.keepOriginalOrientation)
                            {
                                if (settings.keepOriginalOrientation)
                                {
                                    // Original Rotation - ???
                                    rotationQT = Quaternion.Euler(rotationQT.eulerAngles.x, originalRY, rotationQT.eulerAngles.z);
                                }
                                else
                                {
                                    // Body Orientation - ???
                                    rotationQT = Quaternion.Euler(rotationQT.eulerAngles.x, settings.orientationOffsetY, rotationQT.eulerAngles.z);
                                }
                            }
                            if (settings.loopBlendPositionY || settings.keepOriginalPositionY)
                            {
                                if (settings.keepOriginalPositionY)
                                {
                                    // Original Position Y
                                    positionY = originalPY;
                                }
                                else if (settings.heightFromFeet)
                                {
                                    // Feet Position Y
                                    positionY = (settings.level + clampFeetPositions);
                                }
                                else
                                {
                                    // Center Of Mass
                                    positionY = 0.0f;
                                }
                            }
                            if (settings.loopBlendPositionXZ || settings.keepOriginalPositionXZ)
                            {
                                if (settings.keepOriginalPositionXZ)
                                {
                                    // Original Position XZ
                                    positionX = originalPX;
                                    positionZ = originalPZ;
                                }
                                else
                                {
                                    // Center Of Mass
                                    positionX = 0.0f;
                                    positionZ = 0.0f;
                                }
                            }
                            if (bakeRootTransforms == BabylonAnimationBaking.GameBlend)
                            {
                                positionX = 0.0f;
                                positionZ = 0.0f;
                            }
                            local = Matrix4x4.TRS(new Vector3(positionX, positionY, positionZ), rotationQT, transform.localScale);
                        }
                        else
                        {
                            // DEPRECIATED: local = (transform.parent.localToWorldMatrix.inverse * transform.localToWorldMatrix);
                            local = Matrix4x4.TRS(transform.localPosition, transform.localRotation, transform.localScale);
                        }
                        float[] matrix = new[] {
                            local[0, 0], local[1, 0], local[2, 0], local[3, 0],
                            local[0, 1], local[1, 1], local[2, 1], local[3, 1],
                            local[0, 2], local[1, 2], local[2, 2], local[3, 2],
                            local[0, 3], local[1, 3], local[2, 3], local[3, 3]
                        };
                        var key = new BabylonAnimationKey
                        {
                            frame  = frameIndex,
                            values = matrix
                        };
                        keys.Add(key);
                    }
                    AnimationMode.EndSampling();
                    frameOffest     += clipFrameCount;
                    totalFrameCount += clipFrameCount;
                }
                var babylonAnimation = new BabylonAnimation
                {
                    name           = bone.name + "Animation",
                    property       = "_matrix",
                    dataType       = (int)BabylonAnimation.DataType.Matrix,
                    loopBehavior   = (int)BabylonAnimation.LoopBehavior.Relative,
                    enableBlending = false,
                    blendingSpeed  = 0.0f,
                    framePerSecond = frameRate,
                    keys           = keys.ToArray()
                };
                bone.animation = babylonAnimation;
            }
            if (AnimationMode.InAnimationMode())
            {
                AnimationMode.StopAnimationMode();
            }

            /*
             * //
             * // TODO: Format Custom Curve Keys
             * //
             * string property = "none";
             * if (pxkeys.Count > 0)
             * {
             *  property = "metadata.state.animPosition.x";
             *  anims.Add(new BabylonAnimation
             *  {
             *      dataType = (int)BabylonAnimation.DataType.Float,
             *      name = property + " animation",
             *      keys = pxkeys.ToArray(),
             *      framePerSecond = frameRate,
             *      enableBlending = false,
             *      blendingSpeed = 0.0f,
             *      loopBehavior = (int)BabylonAnimation.LoopBehavior.Cycle,
             *      property = property
             *  });
             * }
             * //
             * // Cache Babylon Animation Keys
             * //
             * if (anims.Count > 0)
             * {
             *  List<BabylonAnimation> sourceAnimiamtions = null;
             *  if (SceneBuilder.AnimationCurveKeys.ContainsKey(sourceId)) {
             *      sourceAnimiamtions = SceneBuilder.AnimationCurveKeys[sourceId];
             *  } else {
             *      sourceAnimiamtions = new List<BabylonAnimation>();
             *      SceneBuilder.AnimationCurveKeys.Add(sourceId, sourceAnimiamtions);
             *  }
             *  foreach (var anim in anims) {
             *      sourceAnimiamtions.Add(anim);
             *  }
             * }
             */
        }
        public void ExportHeightmap()
        {
            // Validate Project Platform
            if (!Unity3D2Babylon.Tools.ValidateProjectPlatform())
            {
                return;
            }
            if (heightmapTexture == null || String.IsNullOrEmpty(heightmapFile))
            {
                return;
            }
            // ..
            bool   exportRaw  = (exportFormat == BabylonHeightmapFormat.RAW);
            string exportExt  = (exportRaw) ? "raw" : "png";
            string exportDir  = Path.GetDirectoryName(heightmapFile);
            string exportFile = Path.GetFileNameWithoutExtension(heightmapFile);
            // ..
            string filename = EditorUtility.SaveFilePanel("Export Heightmap Image", exportDir, exportFile, exportExt);

            if (String.IsNullOrEmpty(filename))
            {
                return;
            }
            if (File.Exists(filename))
            {
                if (!ExporterWindow.ShowMessage("Overwrite the selected file?", "Babylon.js", "Overwrite", "Cancel"))
                {
                    return;
                }
            }
            // ..
            try {
                ExporterWindow.ReportProgress(1, "Baking heightmap image data... This may take a while.");
                Texture2D exportTexture = heightmapTexture.Copy(heightmapTexture.format);
                if (enableResolution == true && exportResolution != heightmapResolution)
                {
                    int saveResolution = exportResolution;
                    if (saveResolution <= 0)
                    {
                        saveResolution = 1;
                    }
                    exportTexture.Scale(saveResolution, saveResolution, (exportScaling == BabylonTextureScale.Bilinear));
                }
                if (exportRaw)
                {
                    exportTexture = Tools.FlipTexture(exportTexture);
                }
                if (exportRaw)
                {
                    exportTexture.WriteImageRAW16(filename);
                }
                else
                {
                    exportTexture.WriteImagePNG16(filename, true);
                }
            }
            catch (Exception ex)
            {
                UnityEngine.Debug.LogException(ex);
            }
            finally
            {
                ExporterWindow.ReportProgress(1, "Refresing assets database...");
                AssetDatabase.Refresh();
                ExporterWindow.ReportProgress(1, "Heightmap conversion complete.");
                EditorUtility.ClearProgressBar();
            }
            if (this.keepGeneratorOpen)
            {
                ExporterWindow.ShowMessage("Heightmap exportation complete.", "Babylon.js");
            }
            else
            {
                this.Close();
            }
        }
示例#30
0
        public void Split(string inputFile, string inputExt, bool createSkybox)
        {
            bool   jpeg         = (skyboxSplitter == BabylonImageFormat.JPG);
            string faceExt      = (jpeg) ? ".jpg" : ".png";
            var    splitterOpts = new BabylonSplitterOptions();
            var    outputFile   = inputFile.Replace(inputExt, faceExt);

            if (createSkybox == true && generateSkybox == true)
            {
                ExporterWindow.ReportProgress(1, "Splitting cubemap texture faces... This may take a while.");
                Tools.ExportSkybox(convertCube, outputFile, splitterOpts, skyboxSplitter);
            }
            if (createSkybox == true && generateSkybox == true && createSkyboxMaterial == true)
            {
                ExporterWindow.ReportProgress(1, "Generating skybox material assets... This may take a while.");
                AssetDatabase.Refresh();
                Material skyboxMaterial = new Material(Shader.Find("Skybox/6 Sided"));
                if (skyboxMaterial != null)
                {
                    string frontFilename = outputFile.Replace(faceExt, ("_pz" + faceExt));
                    AssetDatabase.ImportAsset(frontFilename, ImportAssetOptions.ForceUpdate);
                    Texture2D frontTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(frontFilename, typeof(Texture2D));
                    if (frontTexture != null)
                    {
                        skyboxMaterial.SetTexture("_FrontTex", frontTexture);
                    }

                    string backFilename = outputFile.Replace(faceExt, ("_nz" + faceExt));
                    AssetDatabase.ImportAsset(backFilename, ImportAssetOptions.ForceUpdate);
                    Texture2D backTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(backFilename, typeof(Texture2D));
                    if (backTexture != null)
                    {
                        skyboxMaterial.SetTexture("_BackTex", backTexture);
                    }

                    string leftFilename = outputFile.Replace(faceExt, ("_px" + faceExt));
                    AssetDatabase.ImportAsset(leftFilename, ImportAssetOptions.ForceUpdate);
                    Texture2D leftTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(leftFilename, typeof(Texture2D));
                    if (leftTexture != null)
                    {
                        skyboxMaterial.SetTexture("_LeftTex", leftTexture);
                    }

                    string rightFilename = outputFile.Replace(faceExt, ("_nx" + faceExt));
                    AssetDatabase.ImportAsset(rightFilename, ImportAssetOptions.ForceUpdate);
                    Texture2D rightTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(rightFilename, typeof(Texture2D));
                    if (rightTexture != null)
                    {
                        skyboxMaterial.SetTexture("_RightTex", rightTexture);
                    }

                    string upFilename = outputFile.Replace(faceExt, ("_py" + faceExt));
                    AssetDatabase.ImportAsset(upFilename, ImportAssetOptions.ForceUpdate);
                    Texture2D upTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(upFilename, typeof(Texture2D));
                    if (upTexture != null)
                    {
                        skyboxMaterial.SetTexture("_UpTex", upTexture);
                    }

                    string downFilename = outputFile.Replace(faceExt, ("_ny" + faceExt));
                    AssetDatabase.ImportAsset(downFilename, ImportAssetOptions.ForceUpdate);
                    Texture2D downTexture = (Texture2D)AssetDatabase.LoadAssetAtPath(downFilename, typeof(Texture2D));
                    if (downTexture != null)
                    {
                        skyboxMaterial.SetTexture("_DownTex", downTexture);
                    }

                    string outputMaterialName = Path.GetFileNameWithoutExtension(outputFile);
                    string outputMaterialPath = Path.GetDirectoryName(outputFile);
                    string outputMaterialFile = outputMaterialPath + "/" + outputMaterialName + ".mat";
                    AssetDatabase.CreateAsset(skyboxMaterial, outputMaterialFile);
                }
                else
                {
                    UnityEngine.Debug.LogError("CMFT: Failed to locate 'Skybox/6 Sided' shader material");
                }
            }
        }