public static void InitUpdate() { string prodVersion = ExporterWindow.exportationOptions.ProductionVersion.ToString(); if (prodVersion.IndexOf(".", StringComparison.OrdinalIgnoreCase) < 0) { prodVersion += ".0"; } string updateMsg = (exportationOptions.DefaultUpdateOptions == (int)BabylonUpdateOptions.PreviewRelease) ? "Are you sure you want to update libraries using the github preview release version?" : "Are you sure you want to update libraries using the github stable release version " + prodVersion + "?"; if (ExporterWindow.ShowMessage(updateMsg, "Babylon.js", "Update")) { EditorUtility.DisplayProgressBar("Babylon.js", "Updating github editor toolkit library files...", 1); string libPath = Path.Combine(Application.dataPath, "Babylon/Library/"); string bjsPath = (exportationOptions.DefaultUpdateOptions == (int)BabylonUpdateOptions.PreviewRelease) ? "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/preview%20release/babylon.js" : "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/babylon." + prodVersion + ".js"; string bjsTsPath = (exportationOptions.DefaultUpdateOptions == (int)BabylonUpdateOptions.PreviewRelease) ? "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/preview%20release/babylon.d.ts" : "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/babylon." + prodVersion + ".d.ts"; string c2dPath = (exportationOptions.DefaultUpdateOptions == (int)BabylonUpdateOptions.PreviewRelease) ? "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/preview%20release/canvas2D/babylon.canvas2d.js" : "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/babylon." + prodVersion + ".canvas2d.js"; string c2dTsPath = (exportationOptions.DefaultUpdateOptions == (int)BabylonUpdateOptions.PreviewRelease) ? "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/preview%20release/canvas2D/babylon.canvas2d.d.ts" : "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/babylon." + prodVersion + ".canvas2d.d.ts"; string cannonPath = (exportationOptions.DefaultUpdateOptions == (int)BabylonUpdateOptions.PreviewRelease) ? "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/preview%20release/cannon.js" : "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/cannon.js"; string oimoPath = (exportationOptions.DefaultUpdateOptions == (int)BabylonUpdateOptions.PreviewRelease) ? "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/preview%20release/Oimo.js" : "https://raw.githubusercontent.com/BabylonJS/Babylon.js/master/dist/Oimo.js"; try { EditorUtility.DisplayProgressBar("Babylon.js", "Updating babylon.bjs...", 0.10f); Tools.DownloadFile(bjsPath, Path.Combine(libPath, "babylon.bjs")); EditorUtility.DisplayProgressBar("Babylon.js", "Updating babylon.d.ts...", 0.20f); Tools.DownloadFile(bjsTsPath, Path.Combine(libPath, "babylon.d.ts")); EditorUtility.DisplayProgressBar("Babylon.js", "Updating canvas2d.bjs...", 0.30f); Tools.DownloadFile(c2dPath, Path.Combine(libPath, "canvas2d.bjs")); EditorUtility.DisplayProgressBar("Babylon.js", "Updating canvas2d.d.ts...", 0.40f); Tools.DownloadFile(c2dTsPath, Path.Combine(libPath, "canvas2d.d.ts")); EditorUtility.DisplayProgressBar("Babylon.js", "Updating cannon.bjs...", 0.50f); Tools.DownloadFile(cannonPath, Path.Combine(libPath, "cannon.bjs")); EditorUtility.DisplayProgressBar("Babylon.js", "Updating oimo.bjs...", 0.60f); Tools.DownloadFile(oimoPath, Path.Combine(libPath, "oimo.bjs")); EditorUtility.DisplayProgressBar("Babylon.js", "Updating navmesh.bjs...", 0.70f); Tools.DownloadFile("https://raw.githubusercontent.com/BabylonJS/Extensions/master/SceneManager/dist/babylon.navigation.mesh.js", Path.Combine(libPath, "navmesh.bjs")); EditorUtility.DisplayProgressBar("Babylon.js", "Updating manager.bjs...", 0.80f); Tools.DownloadFile("https://raw.githubusercontent.com/BabylonJS/Extensions/master/SceneManager/dist/babylon.scenemanager.js", Path.Combine(libPath, "manager.bjs")); EditorUtility.DisplayProgressBar("Babylon.js", "Updating manager.d.ts...", 0.90f); Tools.DownloadFile("https://raw.githubusercontent.com/BabylonJS/Extensions/master/SceneManager/dist/babylon.scenemanager.d.ts", Path.Combine(libPath, "manager.d.ts")); } catch (System.Exception ex) { UnityEngine.Debug.LogException(ex); } finally { EditorUtility.DisplayProgressBar("Babylon.js", "Refresing assets database...", 1.0f); AssetDatabase.Refresh(); EditorUtility.ClearProgressBar(); } } }
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 OnGUI() { GUILayout.Label("Heightmap File", EditorStyles.boldLabel); EditorGUI.BeginDisabledGroup(true); heightmapLabel = EditorGUILayout.TextField(String.Empty, heightmapLabel); EditorGUI.EndDisabledGroup(); if (GUILayout.Button("Load Heightmap Data")) { LoadHeightmap(); } EditorGUILayout.Space(); exportFormat = (BabylonHeightmapFormat)EditorGUILayout.EnumPopup("Export Format:", exportFormat, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); // .. EditorGUILayout.BeginHorizontal(); enableResolution = EditorGUILayout.Toggle("Scale Resolution:", enableResolution); if (enableResolution == false) { exportResolution = heightmapResolution; } EditorGUI.BeginDisabledGroup(enableResolution == false); exportResolution = (int)EditorGUILayout.Slider("", exportResolution, 0, heightmapResolution); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); exportScaling = (BabylonTextureScale)EditorGUILayout.EnumPopup("Map Image Scaling:", (BabylonTextureScale)exportScaling, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); EditorGUI.EndDisabledGroup(); // .. EditorGUILayout.BeginHorizontal(); keepGeneratorOpen = EditorGUILayout.Toggle("Keep Generator Open:", keepGeneratorOpen); int vertexCount = (exportResolution * exportResolution); string vertextLabel = String.Format("Estimated Mesh Density - {0}", (vertexCount > 0) ? vertexCount.ToString("#,#") : "0"); GUILayout.Label(vertextLabel, EditorStyles.boldLabel); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); // .. if (heightmapTexture == null) { heightmapTexture = new Texture2D(500, 500, TextureFormat.RGBA32, false); heightmapTexture.Clear(Color.black); } if (heightmapTexture != null) { GUI.DrawTexture(new Rect(10.0f, 180.0f, 500.0f, 500.0f), heightmapTexture, ScaleMode.ScaleToFit); } GUILayout.Space(510.0f); if (GUILayout.Button("Export Heightmap")) { if (heightmapTexture != null && !String.IsNullOrEmpty(heightmapFile)) { ExportHeightmap(); } else { ExporterWindow.ShowMessage("No heightmap data generated."); } } }
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); } }
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(); } }
public void OnGUI() { GUILayout.Label("Choose the Cubemap you want to split into 6 images", EditorStyles.boldLabel); EditorGUILayout.Space(); splitCube = EditorGUILayout.ObjectField("Cubemap:", splitCube, typeof(Cubemap), false) as Cubemap; EditorGUILayout.Space(); EditorGUILayout.Space(); if (GUILayout.Button("Split Cubemap")) { if (splitCube) { Split(); } if (!splitCube) { ExporterWindow.ShowMessage("You must select a cubemap"); } } }
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))); } }
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))); } }
public void OnGUI() { // Update texture atlas window EditorGUILayout.Space(); skinMeshRenderer = EditorGUILayout.ObjectField("Skin Mesh Renderer:", skinMeshRenderer, typeof(SkinnedMeshRenderer), true) as SkinnedMeshRenderer; EditorGUILayout.Space(); bakeTextureMaps = EditorGUILayout.Toggle("Bake Texture Maps:", bakeTextureMaps); EditorGUILayout.Space(); bakeAlphaEncoding = EditorGUILayout.Toggle("Bake Image Alpha:", bakeAlphaEncoding); EditorGUILayout.Space(); EditorGUI.BeginDisabledGroup(true); EditorGUI.EndDisabledGroup(); textureAtlasSize = (int)EditorGUILayout.Slider("Texture Atlas Size:", textureAtlasSize, 128, 8192); EditorGUILayout.Space(); EditorGUI.BeginDisabledGroup(true); textureAtlasShader = EditorGUILayout.ObjectField("Texture Atlas Shader:", textureAtlasShader, typeof(Shader), true) as Shader; EditorGUILayout.Space(); textureAtlasFormat = (BabylonImageFormat)EditorGUILayout.EnumPopup("Texture Atlas Format:", textureAtlasFormat, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); EditorGUI.EndDisabledGroup(); textureImageScaling = (BabylonTextureScale)EditorGUILayout.EnumPopup("Texture Image Scale:", textureImageScaling, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); maxTextureImageSize = (int)EditorGUILayout.Slider("Texture Image Max:", maxTextureImageSize, 0, 4096); EditorGUILayout.Space(); linearInterpolation = EditorGUILayout.Toggle("Use Linear Interpolation:", linearInterpolation); EditorGUILayout.Space(); updateSkinRenderer = EditorGUILayout.Toggle("Update Skin Renderers:", updateSkinRenderer); EditorGUILayout.Space(); EditorGUILayout.Space(); if (GUILayout.Button("Bake Texture Atlas Skin")) { if (skinMeshRenderer) { Bake(); } if (!skinMeshRenderer) { ExporterWindow.ShowMessage("You must select a skin mesh renderer"); } } }
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))); } }
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(); } }
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(); } }
public void OnGUI() { EditorGUILayout.Space(); babylonParticles = EditorGUILayout.ObjectField("Babylon Particle System:", babylonParticles, typeof(ParticleSystems), true) as ParticleSystems; EditorGUILayout.Space(); shurikenParticles = EditorGUILayout.ObjectField("Shuriken Particle System:", shurikenParticles, typeof(ParticleSystem), true) as ParticleSystem; EditorGUILayout.Space(); defaultColor = EditorGUILayout.ColorField("Default Particle Color:", defaultColor); EditorGUILayout.Space(); updateSpeedModifier = (float)EditorGUILayout.Slider("Start Speed Modifier:", updateSpeedModifier, 0.0f, 1.0f); EditorGUILayout.Space(); emitRateModifier = (float)EditorGUILayout.Slider("Emit Rate Modifier:", emitRateModifier, 0.0f, 100.0f); EditorGUILayout.Space(); convertCurveValues = (BabylonCurveValues)EditorGUILayout.EnumPopup("Convert Curve Values:", convertCurveValues, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); exportShurikenData = EditorGUILayout.Toggle("Custom Shuriken Data:", exportShurikenData); EditorGUILayout.Space(); keepGeneratorOpen = EditorGUILayout.Toggle("Keep Generator Open:", keepGeneratorOpen); EditorGUILayout.Space(); EditorGUILayout.Space(); if (GUILayout.Button("Parse Shuriken Particle System")) { if (shurikenParticles && babylonParticles) { Parse(); } if (!shurikenParticles) { ExporterWindow.ShowMessage("You must select a shuriken particle system"); } else if (!babylonParticles) { ExporterWindow.ShowMessage("You must select a babylon particle system"); } } }
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; } } } }
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); }
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); }
public void OnGUI() { EditorGUILayout.Space(); cubemapTool = (BabylonCubemapTool)EditorGUILayout.EnumPopup("Cubemap Texture Tool:", cubemapTool, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); if (cubemapTool == BabylonCubemapTool.PixelPerfectTools) { splitLabel = "Open Pixel Perfect"; if (this.maxSize.y != 94.0f) { this.maxSize = new Vector2(500.0f, 94.0f); this.minSize = this.maxSize; } } else if (cubemapTool == BabylonCubemapTool.ReflectionProbes) { splitLabel = "Bake Reflection Probe"; if (this.maxSize.y != 222.0f) { this.maxSize = new Vector2(500.0f, 222.0f); this.minSize = this.maxSize; } } else { splitLabel = "Bake Cubemap Faces"; if (this.maxSize.y != 248.0f) { this.maxSize = new Vector2(500.0f, 248.0f); this.minSize = this.maxSize; } } if (cubemapTool == BabylonCubemapTool.CubemapSplitter || cubemapTool == BabylonCubemapTool.ReflectionProbes) { imageLibrary = (BabylonImageLibrary)EditorGUILayout.EnumPopup("Default Image Library:", imageLibrary, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); convertCube = EditorGUILayout.ObjectField("Source Cubemap Image:", convertCube, typeof(Cubemap), false) as Cubemap; EditorGUILayout.Space(); } if (cubemapTool == BabylonCubemapTool.CubemapSplitter) { imageFormat = (BabylonImageFormat)EditorGUILayout.EnumPopup("Output Image Format:", imageFormat, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); } if (cubemapTool == BabylonCubemapTool.ReflectionProbes) { reflectionType = (BabylonProbeFormat)EditorGUILayout.EnumPopup("Reflection Probe Size:", reflectionType, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); } if (cubemapTool == BabylonCubemapTool.CubemapSplitter) { createSkyboxMaterial = EditorGUILayout.Toggle("Create Skybox Material:", createSkyboxMaterial); EditorGUILayout.Space(); } keepGeneratorOpen = EditorGUILayout.Toggle("Keep Generator Open:", keepGeneratorOpen); EditorGUILayout.Space(); EditorGUILayout.Space(); if (GUILayout.Button(splitLabel)) { if (cubemapTool == BabylonCubemapTool.PixelPerfectTools) { bool jpeg = (imageFormat == BabylonImageFormat.JPEG); string splitter = (ExporterWindow.PixelPrefect + "?jpeg=" + jpeg.ToString().ToLower()); Application.OpenURL(splitter); this.Close(); } else { if (convertCube) { Bake(); } if (!convertCube) { ExporterWindow.ShowMessage("You must select a cubemap"); } } } }
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(); } }
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(); } }
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"); } } } }
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"); } }
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; } }
public void OnGUI() { GUILayout.Label("BabylonJS Toolkit - Version: " + ExporterWindow.ToolkitVersion, EditorStyles.boldLabel); EditorGUI.BeginDisabledGroup(true); exportationOptions.DefaultProjectFolder = EditorGUILayout.TextField("", exportationOptions.DefaultProjectFolder); EditorGUI.EndDisabledGroup(); if (GUILayout.Button("Select Project Folder")) { SelectFolder(); } if (GUILayout.Button("Save Export Settings")) { SaveSettings(); ShowMessage("Export settings saved."); } scrollPosMain = EditorGUILayout.BeginScrollView(scrollPosMain, GUILayout.ExpandWidth(false), GUILayout.ExpandHeight(true)); EditorGUILayout.Space(); exportationOptions.DefaultBuildPath = EditorGUILayout.TextField(" Project Build Path", exportationOptions.DefaultBuildPath); EditorGUILayout.Space(); exportationOptions.DefaultScenePath = EditorGUILayout.TextField(" Project Scene Path", exportationOptions.DefaultScenePath); EditorGUILayout.Space(); exportationOptions.DefaultScriptPath = EditorGUILayout.TextField(" Project Script Path", exportationOptions.DefaultScriptPath); EditorGUILayout.Space(); exportationOptions.DefaultIndexPage = EditorGUILayout.TextField(" Project Index Page", exportationOptions.DefaultIndexPage); EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); exportationOptions.ExportPhysics = EditorGUILayout.Toggle(" Enable Physics Engine", exportationOptions.ExportPhysics); exportationOptions.DefaultPhysicsEngine = (int)(BabylonPhysicsEngine)EditorGUILayout.EnumPopup("Default Physics Engine", (BabylonPhysicsEngine)exportationOptions.DefaultPhysicsEngine, GUILayout.ExpandWidth(true)); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); GUILayout.Label(" Light Rotation Offset"); exportationOptions.LightRotationOffset = EditorGUILayout.Vector3Field("", exportationOptions.LightRotationOffset, GUILayout.ExpandWidth(false)); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); exportationOptions.LightIntensityFactor = EditorGUILayout.Slider(" Light Intensity Factor", exportationOptions.LightIntensityFactor, 0, 10.0f); EditorGUILayout.Space(); exportationOptions.ReflectionDefaultLevel = EditorGUILayout.Slider(" Default Reflection Level", exportationOptions.ReflectionDefaultLevel, 0, 1.0f); EditorGUILayout.Space(); exportationOptions.DefaultImageFormat = (int)(BabylonImageFormat)EditorGUILayout.EnumPopup(" Prefered Texture Format", (BabylonImageFormat)exportationOptions.DefaultImageFormat, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); exportationOptions.DefaultQualityLevel = (int)EditorGUILayout.Slider(" Texture Image Quality", exportationOptions.DefaultQualityLevel, 0, 100); EditorGUILayout.Space(); showCollision = EditorGUILayout.Foldout(showCollision, "Scene Collision Options"); if (showCollision) { EditorGUILayout.Space(); exportationOptions.ExportCollisions = EditorGUILayout.Toggle(" Enable Collisions", exportationOptions.ExportCollisions); EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); GUILayout.Label(" Camera Ellipsoid"); exportationOptions.CameraEllipsoid = EditorGUILayout.Vector3Field("", exportationOptions.CameraEllipsoid, GUILayout.ExpandWidth(false)); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); GUILayout.Label(" Default Scene Gravity"); exportationOptions.Gravity = EditorGUILayout.Vector3Field("", exportationOptions.Gravity, GUILayout.ExpandWidth(false)); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); exportationOptions.DefaultColliderDetail = (int)(BabylonColliderDetail)EditorGUILayout.EnumPopup(" Default Collider Detail", (BabylonColliderDetail)exportationOptions.DefaultColliderDetail, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); exportationOptions.WorkerCollisions = EditorGUILayout.Toggle(" Enable Worker Collisions", exportationOptions.WorkerCollisions); EditorGUILayout.Space(); } showShader = EditorGUILayout.Foldout(showShader, "Shader Program Options"); if (showShader) { EditorGUILayout.Space(); exportationOptions.EmbeddedShaders = EditorGUILayout.Toggle(" Embed Shader Files", exportationOptions.EmbeddedShaders); EditorGUILayout.Space(); exportationOptions.DefaultShaderFolder = EditorGUILayout.TextField(" Output Src Shader Path", exportationOptions.DefaultShaderFolder); EditorGUILayout.Space(); } showLighting = EditorGUILayout.Foldout(showLighting, "Lightmap Baking Options"); if (showLighting) { EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(); exportationOptions.ExportLightmaps = EditorGUILayout.Toggle(" Export Lightmaps", exportationOptions.ExportLightmaps); exportationOptions.DefaultLightmapBaking = (int)(BabylonLightmapBaking)EditorGUILayout.EnumPopup(" Synchronous Baking", (BabylonLightmapBaking)exportationOptions.DefaultLightmapBaking, GUILayout.ExpandWidth(true)); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); exportationOptions.DefaultLightmapMode = (int)(BabylonLightmapMode)EditorGUILayout.EnumPopup(" Light Mapper Mode", (BabylonLightmapMode)exportationOptions.DefaultLightmapMode, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); exportationOptions.DefaultCoordinatesIndex = (int)EditorGUILayout.Slider(" Coordinates Index", exportationOptions.DefaultCoordinatesIndex, 0, 1); EditorGUILayout.Space(); EditorGUILayout.BeginHorizontal(GUILayout.ExpandWidth(true)); exportationOptions.ExportShadows = EditorGUILayout.Toggle(" Enable Shadow Map", exportationOptions.ExportShadows); GUILayout.Label(" Default Shadow Map Size"); exportationOptions.ShadowMapSize = EditorGUILayout.IntField("", exportationOptions.ShadowMapSize, GUILayout.Width(50)); EditorGUILayout.EndHorizontal(); EditorGUILayout.Space(); exportationOptions.DefaultLightFilter = (int)(BabylonLightingFilter)EditorGUILayout.EnumPopup(" Shadow Map Filter", (BabylonLightingFilter)exportationOptions.DefaultLightFilter, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); exportationOptions.ShadowMapBias = EditorGUILayout.Slider(" Shadow Map Bias", exportationOptions.ShadowMapBias, 0, 1.0f); EditorGUILayout.Space(); exportationOptions.ShadowBlurScale = EditorGUILayout.Slider(" Shadow Blur Scale", exportationOptions.ShadowBlurScale, 0, 5.0f); EditorGUILayout.Space(); } showPreview = EditorGUILayout.Foldout(showPreview, "Default Exporting Options"); if (showPreview) { EditorGUILayout.Space(); exportationOptions.AttachUnityEditor = EditorGUILayout.Toggle(" Attach Unity Editor", exportationOptions.AttachUnityEditor); EditorGUILayout.Space(); exportationOptions.HostPreviewPage = EditorGUILayout.Toggle(" Host Preview Server", exportationOptions.HostPreviewPage); EditorGUILayout.Space(); exportationOptions.ShowDebugControls = EditorGUILayout.Toggle(" Show Debug Controls", exportationOptions.ShowDebugControls); EditorGUILayout.Space(); exportationOptions.DefaultServerPort = EditorGUILayout.IntField(" Default Server Port", exportationOptions.DefaultServerPort); EditorGUILayout.Space(); exportationOptions.DefaultPreviewWindow = (int)(BabylonPreviewWindow)EditorGUILayout.EnumPopup(" Default Preview Window", (BabylonPreviewWindow)exportationOptions.DefaultPreviewWindow, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); exportationOptions.BuildJavaScript = EditorGUILayout.Toggle(" Build Javascript Files", exportationOptions.BuildJavaScript); EditorGUILayout.Space(); exportationOptions.CompileTypeScript = EditorGUILayout.Toggle(" Build Typescript Files", exportationOptions.CompileTypeScript); EditorGUILayout.Space(); exportationOptions.DefaultTypeSriptPath = EditorGUILayout.TextField(" Typescript Compiler", exportationOptions.DefaultTypeSriptPath); EditorGUILayout.Space(); exportationOptions.DefaultNodeRuntimePath = EditorGUILayout.TextField(" Node Runtime System", exportationOptions.DefaultNodeRuntimePath); EditorGUILayout.Space(); exportationOptions.ProductionVersion = EditorGUILayout.FloatField(" Stable Babylon Version", exportationOptions.ProductionVersion); EditorGUILayout.Space(); exportationOptions.DefaultUpdateOptions = (int)(BabylonUpdateOptions)EditorGUILayout.EnumPopup(" Github Update Version", (BabylonUpdateOptions)exportationOptions.DefaultUpdateOptions, GUILayout.ExpandWidth(true)); EditorGUILayout.Space(); } EditorGUILayout.EndScrollView(); EditorGUILayout.Space(); // Exporter buttons if (GUILayout.Button("Build Script")) { if (ExporterWindow.ShowMessage("Are you sure you want to build the project script files?", "Babylon.js", "Build")) { Build(true); } } if (GUILayout.Button("Export Scene")) { Export(false); } if (GUILayout.Button("Export & Preview")) { Export(true); } if (ExporterWindow.exportationOptions.HostPreviewPage == true) { if (GUILayout.Button("Start Preview Server")) { StartServer(); } } if (GUILayout.Button("Launch Preview Window")) { Execute(); } EditorGUILayout.Space(); }
public void Export(bool preview) { try { // Validate lightmap bake in progress if (exportationOptions.ExportLightmaps && exportationOptions.DefaultLightmapBaking == (int)BabylonLightmapBaking.Enabled && Lightmapping.isRunning) { ShowMessage("There is a bake already in progress."); return; } // Validate default project folder selected if (String.IsNullOrEmpty(exportationOptions.DefaultProjectFolder)) { ShowMessage("No default project file selected."); return; } // Validate default project folder exists if (!Directory.Exists(exportationOptions.DefaultProjectFolder)) { if (ExporterWindow.ShowMessage("Create default project folder: " + exportationOptions.DefaultProjectFolder, "Babylon.js - Project not found", "Create")) { Directory.CreateDirectory(exportationOptions.DefaultProjectFolder); } else { return; } } // Get validate scene path info string[] sceneInfo = GetSceneInfomation(true); string sceneName = sceneInfo[0]; string scenePath = sceneInfo[1]; string scriptPath = sceneInfo[2]; string outputFile = sceneInfo[3]; string projectScript = sceneInfo[4]; if (!ExporterWindow.ShowMessage("Export current scene to babylon: " + sceneName, "Babylon.js", "Export")) { return; } // Save current scene info SaveSettings(); ExporterWindow.logs.Clear(); Stopwatch watch = new Stopwatch(); watch.Start(); ReportProgress(0, "Exporting " + scenePath); // Auto lightmap baking if (exportationOptions.ExportLightmaps && exportationOptions.DefaultLightmapBaking == (int)BabylonLightmapBaking.Enabled) { ReportProgress(1, "Baking lightmap textures... This may take a while."); Lightmapping.GIWorkflowMode workflow = Lightmapping.giWorkflowMode; Lightmapping.giWorkflowMode = Lightmapping.GIWorkflowMode.OnDemand; Lightmapping.Bake(); Lightmapping.giWorkflowMode = workflow; } // Save all open scenes ReportProgress(1, "Saving open scene information..."); UnityEditor.SceneManagement.EditorSceneManager.SaveOpenScenes(); // Build project preview if (preview) { Tools.GenerateProjectIndexPage(exportationOptions.DefaultProjectFolder, exportationOptions.ShowDebugControls, exportationOptions.DefaultScenePath, Path.GetFileName(outputFile), exportationOptions.DefaultScriptPath, Path.GetFileName(projectScript)); if (exportationOptions.BuildJavaScript || exportationOptions.CompileTypeScript) { Build(false, sceneInfo); } } // Build current scene BabylonSceneController sceneController = Tools.GetSceneController(); var sceneBuilder = new SceneBuilder(scenePath, sceneName, exportationOptions, sceneController, scriptPath); sceneBuilder.ConvertFromUnity(); ReportProgress(1, "Generating babylon scene... This may take a while."); sceneBuilder.WriteToBabylonFile(outputFile); watch.Stop(); ReportProgress(1, string.Format("Exportation done in {0:0.00}s", watch.Elapsed.TotalSeconds)); EditorUtility.ClearProgressBar(); sceneBuilder.GenerateStatus(logs); string done = preview ? "Preview" : "OK"; bool ok = ShowMessage("Scene exportation complete.", "Babylon.js", done); if (preview && ok) { Preview(); } } catch (Exception ex) { EditorUtility.ClearProgressBar(); ShowMessage("A problem occurred: " + ex.Message + ex.StackTrace, "Error"); } }
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); } } }
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(); } }
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(); } }
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 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(); } }