internal Texture2D _resizeTexture(Texture2D t, int w, int h)
        {
            Texture2D tx = MB_Utility.resampleTexture(t, w, h);

            _temporaryTextures.Add(tx);
            return(tx);
        }
        internal Texture2D _createTextureCopy(Texture2D t)
        {
            Texture2D tx = MB_Utility.createTextureCopy(t);

            _temporaryTextures.Add(tx);
            return(tx);
        }
Exemplo n.º 3
0
        /**
         * pass in System.IO.File.WriteAllBytes for parameter fileSaveFunction. This is necessary because on Web Player file saving
         * functions only exist for Editor classes
         */
        public void SaveAtlasToAssetDatabase(Texture2D atlas, string texPropertyName, int atlasNum, Material resMat)
        {
            string prefabPth = AssetDatabase.GetAssetPath(resMat);

            if (prefabPth == null || prefabPth.Length == 0)
            {
                Debug.LogError("Could save atlas. Could not find result material in AssetDatabase.");
                return;
            }
            string baseName       = Path.GetFileNameWithoutExtension(prefabPth);
            string folderPath     = prefabPth.Substring(0, prefabPth.Length - baseName.Length - 4);
            string fullFolderPath = Application.dataPath + folderPath.Substring("Assets".Length, folderPath.Length - "Assets".Length);

            string pth = fullFolderPath + baseName + "-" + texPropertyName + "-atlas" + atlasNum + ".png";

            Debug.Log("Created atlas for: " + texPropertyName + " at " + pth);
            //need to create a copy because sometimes the packed atlases are not in ARGB32 format
            Texture2D newTex = MB_Utility.createTextureCopy(atlas);
            int       size   = Mathf.Max(newTex.height, newTex.width);

            byte[] bytes = newTex.EncodeToPNG();
            Editor.DestroyImmediate(newTex);


            System.IO.File.WriteAllBytes(pth, bytes);

            AssetDatabase.Refresh();

            string relativePath = folderPath + baseName + "-" + texPropertyName + "-atlas" + atlasNum + ".png";

            SetTextureSize((Texture2D)(AssetDatabase.LoadAssetAtPath(relativePath, typeof(Texture2D))), size);
            SetMaterialTextureProperty(resMat, texPropertyName, relativePath);
        }
Exemplo n.º 4
0
        public static void UpdateSkinnedMeshApproximateBoundsFromBoundsStatic(List <GameObject> objectsInCombined, SkinnedMeshRenderer smr)
        {
            Bounds b    = new Bounds();
            Bounds bigB = new Bounds();

            if (MB_Utility.GetBounds(objectsInCombined[0], out b))
            {
                bigB = b;
            }
            else
            {
                Debug.LogError("Could not get bounds. Not updating skinned mesh bounds");
                return;
            }
            for (int i = 1; i < objectsInCombined.Count; i++)
            {
                if (MB_Utility.GetBounds(objectsInCombined[i], out b))
                {
                    bigB.Encapsulate(b);
                }
                else
                {
                    Debug.LogError("Could not get bounds. Not updating skinned mesh bounds");
                    return;
                }
            }
            smr.localBounds = bigB;
        }
        void AddMeshBaker(MB3_TextureBaker tb, string key, List <Renderer> gaws)
        {
            int numVerts = 0;

            for (int i = 0; i < gaws.Count; i++)
            {
                Mesh m = MB_Utility.GetMesh(gaws[i].gameObject);
                if (m != null)
                {
                    numVerts += m.vertexCount;
                }
            }

            GameObject nmb = new GameObject("MeshBaker-" + key);

            nmb.transform.position = Vector3.zero;
            MB3_MeshBakerCommon newMeshBaker;

            if (numVerts >= 65535)
            {
                newMeshBaker = nmb.AddComponent <MB3_MultiMeshBaker>();
                newMeshBaker.useObjsToMeshFromTexBaker = false;
            }
            else
            {
                newMeshBaker = nmb.AddComponent <MB3_MeshBaker>();
                newMeshBaker.useObjsToMeshFromTexBaker = false;
            }
            newMeshBaker.textureBakeResults = tb.textureBakeResults;
            newMeshBaker.transform.parent   = tb.transform;
            for (int i = 0; i < gaws.Count; i++)
            {
                newMeshBaker.GetObjectsToCombine().Add(gaws[i].gameObject);
            }
        }
            internal Matrix4x4[] GetBindposes(Renderer r, out bool isSkinnedMeshWithBones)
            {
                MeshChannels mc;
                Mesh         m = MB_Utility.GetMesh(r.gameObject);

                if (!meshID2MeshChannels.TryGetValue(m.GetInstanceID(), out mc))
                {
                    mc = new MeshChannels();
                    meshID2MeshChannels.Add(m.GetInstanceID(), mc);
                }

                if (mc.bindPoses == null)
                {
                    mc.bindPoses = _getBindPoses(r, out isSkinnedMeshWithBones);
                }
                else
                {
                    if (r is SkinnedMeshRenderer &&
                        mc.bindPoses.Length > 0)
                    {
                        isSkinnedMeshWithBones = true;
                    }
                    else
                    {
                        isSkinnedMeshWithBones = false;
                        if (r is SkinnedMeshRenderer)
                        {
                            Debug.Assert(m.blendShapeCount > 0, "Skinned Mesh Renderer " + r + " had no bones and no blend shapes");
                        }
                    }
                }

                return(mc.bindPoses);
            }
Exemplo n.º 7
0
        internal static Texture2D _copyTexturesIntoAtlas(Texture2D[] texToPack, int padding, Rect[] rs, int w, int h, MB3_TextureCombiner combiner)
        {
            Texture2D ta = new Texture2D(w, h, TextureFormat.ARGB32, true);

            MB_Utility.setSolidColor(ta, Color.clear);
            for (int i = 0; i < rs.Length; i++)
            {
                Rect      r      = rs[i];
                Texture2D t      = texToPack[i];
                Texture2D tmpTex = null;
                int       x      = Mathf.RoundToInt(r.x * w);
                int       y      = Mathf.RoundToInt(r.y * h);
                int       ww     = Mathf.RoundToInt(r.width * w);
                int       hh     = Mathf.RoundToInt(r.height * h);
                if (t.width != ww && t.height != hh)
                {
                    tmpTex = t = MB_Utility.resampleTexture(t, ww, hh);
                }
                ta.SetPixels(x, y, ww, hh, t.GetPixels());
                if (tmpTex != null)
                {
                    MB_Utility.Destroy(tmpTex);
                }
            }
            ta.Apply();
            return(ta);
        }
Exemplo n.º 8
0
        public override bool AddDeleteGameObjectsByID(GameObject[] gos, int[] deleteGOinstanceIDs, bool disableRendererInSource = true)
        {
            //Profile.Start//Profile("MB2_MultiMeshCombiner.AddDeleteGameObjects1");
            //PART 1 ==== Validate
            if (_usingTemporaryTextureBakeResult && gos != null && gos.Length > 0)
            {
                MB_Utility.Destroy(_textureBakeResults);
                _textureBakeResults = null;
                _usingTemporaryTextureBakeResult = false;
            }

            //if all objects use the same material we can create a temporary _textureBakeResults
            if (_textureBakeResults == null && gos != null && gos.Length > 0 && gos[0] != null)
            {
                if (!_CreateTemporaryTextrueBakeResult(gos, GetMaterialsOnTargetRenderer()))
                {
                    return(false);
                }
            }

            if (!_validate(gos, deleteGOinstanceIDs))
            {
                return(false);
            }
            _distributeAmongBakers(gos, deleteGOinstanceIDs);
            if (LOG_LEVEL >= MB2_LogLevel.debug)
            {
                MB2_Log.LogDebug("MB2_MultiMeshCombiner.AddDeleteGameObjects numCombinedMeshes: " + meshCombiners.Count + " added:" + gos + " deleted:" + deleteGOinstanceIDs + " disableRendererInSource:" + disableRendererInSource + " maxVertsPerCombined:" + _maxVertsInMesh);
            }
            return(_bakeStep1(gos, deleteGOinstanceIDs, disableRendererInSource));
        }
Exemplo n.º 9
0
        public bool ValidateSkinnedMeshes(List <GameObject> objs)
        {
            for (int i = 0; i < objs.Count; i++)
            {
                Renderer r = MB_Utility.GetRenderer(objs[i]);
                if (r is SkinnedMeshRenderer)
                {
                    Transform[] bones = ((SkinnedMeshRenderer)r).bones;
                    if (bones.Length == 0)
                    {
                        Debug.LogWarning("SkinnedMesh " + i + " (" + objs[i] + ") in the list of objects to combine has no bones. Check that 'optimize game object' is not checked in the 'Rig' tab of the asset importer. Mesh Baker cannot combine optimized skinned meshes because the bones are not available.");
                    }
//					UnityEngine.Object parentObject = EditorUtility.GetPrefabParent(r.gameObject);
//					string path = AssetDatabase.GetAssetPath(parentObject);
//					Debug.Log (path);
//					AssetImporter ai = AssetImporter.GetAtPath( path );
//					Debug.Log ("bbb " + ai);
//					if (ai != null && ai is ModelImporter){
//						Debug.Log ("valing 2");
//						ModelImporter modelImporter = (ModelImporter) ai;
//						if(modelImporter.optimizeMesh){
//							Debug.LogError("SkinnedMesh " + i + " (" + objs[i] + ") in the list of objects to combine is optimized. Mesh Baker cannot combine optimized skinned meshes because the bones are not available.");
//						}
//					}
                }
            }
            return(true);
        }
Exemplo n.º 10
0
        public static bool GetBounds(GameObject go, out Bounds b)
        {
            if (go == null)
            {
                Debug.LogError("go paramater was null");
                b = new Bounds(Vector3.zero, Vector3.zero);
                return(false);
            }
            Renderer renderer = MB_Utility.GetRenderer(go);

            if (renderer == null)
            {
                Debug.LogError("GetBounds must be called on an object with a Renderer");
                b = new Bounds(Vector3.zero, Vector3.zero);
                return(false);
            }
            if (renderer is MeshRenderer)
            {
                b = renderer.bounds;
                return(true);
            }
            if (renderer is SkinnedMeshRenderer)
            {
                b = renderer.bounds;
                return(true);
            }
            Debug.LogError("GetBounds must be called on an object with a MeshRender or a SkinnedMeshRenderer.");
            b = new Bounds(Vector3.zero, Vector3.zero);
            return(false);
        }
Exemplo n.º 11
0
 public override bool AddDeleteGameObjectsByID(GameObject[] gos, int[] deleteGOinstanceIDs, bool disableRendererInSource = true)
 {
     if (this._usingTemporaryTextureBakeResult && gos != null && gos.Length > 0)
     {
         MB_Utility.Destroy(this._textureBakeResults);
         this._textureBakeResults = null;
         this._usingTemporaryTextureBakeResult = false;
     }
     if (this._textureBakeResults == null && gos != null && gos.Length > 0 && gos[0] != null && !this._CheckIfAllObjsToAddUseSameMaterialsAndCreateTemporaryTextrueBakeResult(gos))
     {
         return(false);
     }
     if (!this._validate(gos, deleteGOinstanceIDs))
     {
         return(false);
     }
     this._distributeAmongBakers(gos, deleteGOinstanceIDs);
     if (this.LOG_LEVEL >= MB2_LogLevel.debug)
     {
         MB2_Log.LogDebug(string.Concat(new object[]
         {
             "MB2_MultiMeshCombiner.AddDeleteGameObjects numCombinedMeshes: ",
             this.meshCombiners.Count,
             " added:",
             gos,
             " deleted:",
             deleteGOinstanceIDs,
             " disableRendererInSource:",
             disableRendererInSource,
             " maxVertsPerCombined:",
             this._maxVertsInMesh
         }), new object[0]);
     }
     return(this._bakeStep1(gos, deleteGOinstanceIDs, disableRendererInSource));
 }
Exemplo n.º 12
0
        public void CreateColoredTexToReplaceNull(string propName, int propIdx, bool considerMeshUVs, MB3_TextureCombiner combiner, Color col)
        {
            MeshBakerMaterialTexture matTex = ts[propIdx];

            matTex.t = combiner._createTemporaryTexture(propName, 16, 16, TextureFormat.ARGB32, true);
            MB_Utility.setSolidColor(matTex.GetTexture2D(), col);
        }
        //used to track temporary textures that were created so they can be destroyed
        public Texture2D _createTemporaryTexture(int w, int h, TextureFormat texFormat, bool mipMaps)
        {
            Texture2D t = new Texture2D(w, h, texFormat, mipMaps);

            MB_Utility.setSolidColor(t, Color.clear);
            _temporaryTextures.Add(t);
            return(t);
        }
Exemplo n.º 14
0
        public static bool BakeMeshesInPlace(MB3_MeshCombinerSingle mom, List <GameObject> objsToMesh, string saveFolder, bool clearBuffersAfterBake, ProgressUpdateDelegate updateProgressBar)
        {
            if (MB3_MeshCombiner.EVAL_VERSION)
            {
                return(false);
            }
            if (saveFolder.Length < 6)
            {
                Debug.LogError("Please select a folder for meshes.");
                return(false);
            }
            if (!Directory.Exists(Application.dataPath + saveFolder.Substring(6)))
            {
                Debug.Log((Application.dataPath + saveFolder.Substring(6)));
                Debug.Log(Path.GetFullPath(Application.dataPath + saveFolder.Substring(6)));
                Debug.LogError("The selected Folder For Meshes does not exist or is not inside the projects Assets folder. Please 'Choose Folder For Bake In Place Meshes' that is inside the project's assets folder.");
                return(false);
            }

            MB3_EditorMethods editorMethods = new MB3_EditorMethods();

            mom.DestroyMeshEditor(editorMethods);

            MB_RenderType originalRenderType = mom.renderType;
            bool          success            = false;

            string[] objNames = GenerateNames(objsToMesh);
            for (int i = 0; i < objsToMesh.Count; i++)
            {
                if (objsToMesh[i] == null)
                {
                    Debug.LogError("The " + i + "th object on the list of objects to combine is 'None'. Use Command-Delete on Mac OS X; Delete or Shift-Delete on Windows to remove this one element.");
                    return(false);
                }

                Mesh m = new Mesh();
                success = BakeOneMesh(mom, m, objsToMesh[i]);
                if (success)
                {
                    string newMeshFilePath = saveFolder + "/" + objNames[i];
                    Debug.Log("Creating mesh asset at " + newMeshFilePath + " for mesh " + m + " numVerts " + m.vertexCount);
                    AssetDatabase.CreateAsset(mom.GetMesh(), newMeshFilePath);
                }
                if (updateProgressBar != null)
                {
                    updateProgressBar("Created mesh saving mesh on " + objsToMesh[i].name + " to asset " + objNames[i], .6f);
                }
            }
            mom.renderType = originalRenderType;
            MB_Utility.Destroy(mom.resultSceneObject);
            if (clearBuffersAfterBake)
            {
                mom.ClearBuffers();
            }
            return(success);
        }
Exemplo n.º 15
0
        internal Texture2D _createTextureCopy(string propertyName, Texture2D t)
        {
            Texture2D tx = MB_Utility.createTextureCopy(t);

            tx.name = string.Format("tmpCopy{0}_{1}x{2}", _temporaryTextures.Count, tx.width, tx.height);
            TemporaryTexture txx = new TemporaryTexture(propertyName, tx);

            _temporaryTextures.Add(txx);
            return(tx);
        }
Exemplo n.º 16
0
        internal Texture2D _resizeTexture(string propertyName, Texture2D t, int w, int h)
        {
            Texture2D tx = MB_Utility.resampleTexture(t, w, h);

            tx.name = string.Format("tmpResampled{0}_{1}x{2}", _temporaryTextures.Count, w, h);
            TemporaryTexture txx = new TemporaryTexture(propertyName, tx);

            _temporaryTextures.Add(txx);
            return(tx);
        }
Exemplo n.º 17
0
        public static bool bake(MB3_MeshBakerCommon mom)
        {
            bool createdDummyTextureBakeResults = false;
            bool success = false;

            try
            {
                if (mom.meshCombiner.outputOption == MB2_OutputOptions.bakeIntoSceneObject ||
                    mom.meshCombiner.outputOption == MB2_OutputOptions.bakeIntoPrefab)
                {
                    success = MB3_MeshBakerEditorFunctions.BakeIntoCombined(mom, out createdDummyTextureBakeResults);
                }
                else
                {
                    //bake meshes in place
                    if (mom is MB3_MeshBaker)
                    {
                        if (MB3_MeshCombiner.EVAL_VERSION)
                        {
                            Debug.LogError("Bake Meshes In Place is disabled in the evaluation version.");
                        }
                        else
                        {
                            MB2_ValidationLevel vl = Application.isPlaying ? MB2_ValidationLevel.quick : MB2_ValidationLevel.robust;
                            if (!MB3_MeshBakerRoot.DoCombinedValidate(mom, MB_ObjsToCombineTypes.prefabOnly, new MB3_EditorMethods(), vl))
                            {
                                return(false);
                            }

                            List <GameObject> objsToMesh = mom.GetObjectsToCombine();
                            success = MB3_BakeInPlace.BakeMeshesInPlace((MB3_MeshCombinerSingle)((MB3_MeshBaker)mom).meshCombiner, objsToMesh, mom.bakeAssetsInPlaceFolderPath, mom.clearBuffersAfterBake, updateProgressBar);
                        }
                    }
                    else
                    {
                        Debug.LogError("Multi-mesh Baker components cannot be used for Bake In Place. Use an ordinary Mesh Baker object instead.");
                    }
                }
                mom.meshCombiner.CheckIntegrity();
            }
            catch (Exception e)
            {
                Debug.LogError(e);
            }
            finally
            {
                if (createdDummyTextureBakeResults && mom.textureBakeResults != null)
                {
                    MB_Utility.Destroy(mom.textureBakeResults);
                    mom.textureBakeResults = null;
                }
                EditorUtility.ClearProgressBar();
            }
            return(success);
        }
Exemplo n.º 18
0
        //used to track temporary textures that were created so they can be destroyed
        public Texture2D _createTemporaryTexture(string propertyName, int w, int h, TextureFormat texFormat, bool mipMaps)
        {
            Texture2D t = new Texture2D(w, h, texFormat, mipMaps);

            t.name = string.Format("tmp{0}_{1}x{2}", _temporaryTextures.Count, w, h);
            MB_Utility.setSolidColor(t, Color.clear);
            TemporaryTexture txx = new TemporaryTexture(propertyName, t);

            _temporaryTextures.Add(txx);
            return(t);
        }
Exemplo n.º 19
0
 internal void _destroyAllTemporaryTextures()
 {
     if (LOG_LEVEL >= MB2_LogLevel.debug)
     {
         Debug.Log("Destroying " + _temporaryTextures.Count + " temporary textures");
     }
     for (int i = 0; i < _temporaryTextures.Count; i++)
     {
         MB_Utility.Destroy(_temporaryTextures[i].texture);
     }
     _temporaryTextures.Clear();
 }
 public override void DestroyMesh()
 {
     for (int i = 0; i < meshCombiners.Count; i++)
     {
         if (meshCombiners[i].combinedMesh.targetRenderer != null)
         {
             MB_Utility.Destroy(meshCombiners[i].combinedMesh.targetRenderer.gameObject);
         }
         meshCombiners[i].combinedMesh.ClearMesh();
     }
     obj2MeshCombinerMap.Clear();
     meshCombiners.Clear();
 }
Exemplo n.º 21
0
        /**
         *       pass in System.IO.File.WriteAllBytes for parameter fileSaveFunction. This is necessary because on Web Player file saving
         *       functions only exist for Editor classes
         */
        public void SaveAtlasToAssetDatabase(Texture2D atlas, ShaderTextureProperty texPropertyName, int atlasNum, Material resMat)
        {
            if (atlas == null)
            {
                SetMaterialTextureProperty(resMat, texPropertyName, null);
            }
            else
            {
                string prefabPth = AssetDatabase.GetAssetPath(resMat);
                if (prefabPth == null || prefabPth.Length == 0)
                {
                    Debug.LogError("Could save atlas. Could not find result material in AssetDatabase.");
                    return;
                }

                string baseName       = Path.GetFileNameWithoutExtension(prefabPth);
                string folderPath     = prefabPth.Substring(0, prefabPth.Length - baseName.Length - 4);
                string fullFolderPath = Application.dataPath + folderPath.Substring("Assets".Length, folderPath.Length - "Assets".Length);
                string pth            = fullFolderPath + baseName + "-" + texPropertyName.name + "-atlas" + atlasNum;
                string relativePath   = folderPath + baseName + "-" + texPropertyName.name + "-atlas" + atlasNum;
                //need to create a copy because sometimes the packed atlases are not in ARGB32 format
                Texture2D newTex = MB_Utility.createTextureCopy(atlas);
                int       size   = Mathf.Max(newTex.height, newTex.width);
                if (SAVE_FORMAT == saveTextureFormat.png)
                {
                    pth          += ".png";
                    relativePath += ".png";
                    byte[] bytes = newTex.EncodeToPNG();
                    System.IO.File.WriteAllBytes(pth, bytes);
                }
                else
                {
                    pth          += ".tga";
                    relativePath += ".tga";
                    if (File.Exists(pth))
                    {
                        File.Delete(pth);
                    }

                    //Create the file.
                    FileStream fs = File.Create(pth);
                    MB_TGAWriter.Write(newTex.GetPixels(), newTex.width, newTex.height, fs);
                }
                Editor.DestroyImmediate(newTex);
                AssetDatabase.Refresh();
                Debug.Log(String.Format("Wrote atlas for {0} to file:{1}", texPropertyName.name, pth));
                Texture2D txx = (Texture2D)(AssetDatabase.LoadAssetAtPath(relativePath, typeof(Texture2D)));
                SetTextureSize(txx, size);
                SetMaterialTextureProperty(resMat, texPropertyName, relativePath);
            }
        }
            internal BoneWeight[] GetBoneWeights(Renderer r, int numVertsInMeshBeingAdded)
            {
                MeshChannels mc;
                Mesh         m = MB_Utility.GetMesh(r.gameObject);

                if (!meshID2MeshChannels.TryGetValue(m.GetInstanceID(), out mc))
                {
                    mc = new MeshChannels();
                    meshID2MeshChannels.Add(m.GetInstanceID(), mc);
                }
                if (mc.boneWeights == null)
                {
                    mc.boneWeights = _getBoneWeights(r, numVertsInMeshBeingAdded);
                }
                return(mc.boneWeights);
            }
            internal Matrix4x4[] GetBindposes(Renderer r)
            {
                MeshChannels mc;
                Mesh         m = MB_Utility.GetMesh(r.gameObject);

                if (!meshID2MeshChannels.TryGetValue(m.GetInstanceID(), out mc))
                {
                    mc = new MeshChannels();
                    meshID2MeshChannels.Add(m.GetInstanceID(), mc);
                }
                if (mc.bindPoses == null)
                {
                    mc.bindPoses = _getBindPoses(r);
                }
                return(mc.bindPoses);
            }
Exemplo n.º 24
0
        static public Mesh BakeOneMesh(MB3_MeshCombinerSingle mom, string newMeshFilePath, GameObject objToBake)
        {
            Mesh outMesh = null;

            if (objToBake == null)
            {
                Debug.LogError("An object on the list of objects to combine is 'None'. Use Command-Delete on Mac OS X; Delete or Shift-Delete on Windows to remove this one element.");
                return(null);
            }

            MB3_EditorMethods editorMethods = new MB3_EditorMethods();

            GameObject[] objs = new GameObject[] { objToBake };
            Renderer     r    = MB_Utility.GetRenderer(objToBake);

            if (r is SkinnedMeshRenderer)
            {
                mom.renderType = MB_RenderType.skinnedMeshRenderer;
            }
            else if (r is MeshRenderer)
            {
                mom.renderType = MB_RenderType.meshRenderer;
            }
            else
            {
                Debug.LogError("Unsupported Renderer type on object. Must be SkinnedMesh or MeshFilter.");
                return(null);
            }
            if (newMeshFilePath == null && newMeshFilePath.Length != 0)              //todo check directory exists
            {
                Debug.LogError("File path was not in assets folder.");
                return(null);
            }
            if (mom.AddDeleteGameObjects(objs, null, false))
            {
                mom.Apply(MB3_MeshBakerEditorFunctions.UnwrapUV2);
                Mesh mf = MB_Utility.GetMesh(objToBake);
                if (mf != null)
                {
                    Debug.Log("Creating mesh for " + objToBake.name + " with adjusted UVs at: " + newMeshFilePath);
                    AssetDatabase.CreateAsset(mom.GetMesh(), newMeshFilePath);
                    outMesh = (Mesh)AssetDatabase.LoadAssetAtPath(newMeshFilePath, typeof(Mesh));
                }
            }
            mom.DestroyMeshEditor(editorMethods);
            return(outMesh);
        }
Exemplo n.º 25
0
        protected virtual bool _CheckIfAllObjsToAddUseSameMaterialsAndCreateTemporaryTextrueBakeResult(GameObject[] gos)
        {
            _usingTemporaryTextureBakeResult = false;
            Renderer r = MB_Utility.GetRenderer(gos[0]);

            if (r != null)
            {
                Material[] mats = MB_Utility.GetGOMaterials(gos[0]);
                for (int i = 0; i < gos.Length; i++)
                {
                    if (gos[i] == null)
                    {
                        Debug.LogError(string.Format("Game object {0} in list of objects to add was null", i));
                        return(false);
                    }
                    Material[] oMats = MB_Utility.GetGOMaterials(gos[i]);
                    if (oMats == null)
                    {
                        Debug.LogError(string.Format("Game object {0} in list of objects to add no renderer", i));
                        return(false);
                    }
                    for (int j = 0; j < oMats.Length; j++)
                    {
                        bool found = false;
                        for (int k = 0; k < mats.Length; k++)
                        {
                            if (oMats[j] == mats[k])
                            {
                                found = true;
                                break;
                            }
                        }
                        if (found == false)
                        {
                            Debug.LogError(string.Format("Material Bake Result is null and game object {0} in list of objects to add did not have a subset of the materials in on the first object. You need to bake textures or all objects must have a subset of materials on the first object.", i));
                            return(false);
                        }
                    }
                }
                _usingTemporaryTextureBakeResult = true;
                _textureBakeResults = MB2_TextureBakeResults.CreateForMaterialsOnRenderer(r);
                return(true);
            }
            return(false);
        }
Exemplo n.º 26
0
        internal void _destroyTemporaryTextures(string propertyName)
        {
            int numDestroyed = 0;

            for (int i = _temporaryTextures.Count - 1; i >= 0; i--)
            {
                if (_temporaryTextures[i].property.Equals(propertyName))
                {
                    numDestroyed++;
                    MB_Utility.Destroy(_temporaryTextures[i].texture);
                    _temporaryTextures.RemoveAt(i);
                }
            }
            if (LOG_LEVEL >= MB2_LogLevel.debug)
            {
                Debug.Log("Destroying " + numDestroyed + " temporary textures " + propertyName + " num remaining " + _temporaryTextures.Count);
            }
        }
Exemplo n.º 27
0
        static public bool BakeOneMesh(MB3_MeshCombinerSingle mom, Mesh targMesh, GameObject objToBake)
        {
            if (objToBake == null)
            {
                Debug.LogError("An object on the list of objects to combine is 'None'. Use Command-Delete on Mac OS X; Delete or Shift-Delete on Windows to remove this one element.");
                return(false);
            }
            if (targMesh == null)
            {
                Debug.LogError("No mesh was provided.");
                return(false);
            }

            mom.SetMesh(targMesh);
            mom.ClearMesh();
            GameObject[] objs = new GameObject[] { objToBake };
            Renderer     r    = MB_Utility.GetRenderer(objToBake);

            if (r is SkinnedMeshRenderer)
            {
                mom.renderType = MB_RenderType.skinnedMeshRenderer;
            }
            else if (r is MeshRenderer)
            {
                mom.renderType = MB_RenderType.meshRenderer;
            }
            else
            {
                Debug.LogError("Unsupported Renderer type on object. Must be SkinnedMesh or MeshFilter.");
                return(false);
            }
            if (mom.AddDeleteGameObjects(objs, null, false))
            {
                mom.Apply(MB3_MeshBakerEditorFunctions.UnwrapUV2);
                Mesh mf = MB_Utility.GetMesh(objToBake);
                if (mf == null)
                {
                    Debug.LogError("Failed to create mesh for " + objToBake.name);
                    return(false);
                }
            }

            return(true);
        }
        public GameObject PrefabUtility_FindPrefabRoot(GameObject sourceObj)
        {
#if UNITY_2018_3_OR_NEWER
            if (sourceObj == null)
            {
                return(null);
            }
            if (MB_Utility.IsSceneInstance(sourceObj))
            {
                return(PrefabUtility.GetOutermostPrefabInstanceRoot(sourceObj));
            }
            else
            {
                return(sourceObj.transform.root.gameObject);
            }
#else
            return(PrefabUtility.FindPrefabRoot(sourceObj));
#endif
        }
 Vector3[] _getMeshNormals(Mesh m)
 {
     Vector3[] ns = m.normals;
     if (ns.Length == 0)
     {
         if (this.mc.LOG_LEVEL >= MB2_LogLevel.debug)
         {
             MB2_Log.LogDebug("Mesh " + m + " has no normals. Generating");
         }
         if (this.mc.LOG_LEVEL >= MB2_LogLevel.warn)
         {
             Debug.LogWarning("Mesh " + m + " didn't have normals. Generating normals.");
         }
         Mesh tempMesh = (Mesh)GameObject.Instantiate(m);
         tempMesh.RecalculateNormals();
         ns = tempMesh.normals;
         MB_Utility.Destroy(tempMesh);
     }
     return(ns);
 }
Exemplo n.º 30
0
        public static void UpdateSkinnedMeshApproximateBoundsFromBoundsStatic(List <GameObject> objectsInCombined, SkinnedMeshRenderer smr)
        {
            Bounds bounds      = default(Bounds);
            Bounds localBounds = default(Bounds);

            if (MB_Utility.GetBounds(objectsInCombined[0], out bounds))
            {
                localBounds = bounds;
                for (int i = 1; i < objectsInCombined.Count; i++)
                {
                    if (!MB_Utility.GetBounds(objectsInCombined[i], out bounds))
                    {
                        Debug.LogError("Could not get bounds. Not updating skinned mesh bounds");
                        return;
                    }
                    localBounds.Encapsulate(bounds);
                }
                smr.localBounds = localBounds;
                return;
            }
            Debug.LogError("Could not get bounds. Not updating skinned mesh bounds");
        }