//posibilities // using fixOutOfBoundsUVs or not // public static void ConfigureMutiMaterialsFromObjsToCombine(MB3_TextureBaker mom, SerializedProperty resultMaterials, SerializedObject textureBaker) { if (mom.GetObjectsToCombine().Count == 0) { Debug.LogError("You need to add some objects to combine before building the multi material list."); return; } if (resultMaterials.arraySize > 0) { Debug.LogError("You already have some source to combined material mappings configured. You must remove these before doing this operation."); return; } if (mom.textureBakeResults == null) { Debug.LogError("Texture Bake Result asset must be set before using this operation."); return; } Dictionary <MB3_TextureBakerEditorInternal.MultiMatSubmeshInfo, List <List <Material> > > shader2Material_map = new Dictionary <MB3_TextureBakerEditorInternal.MultiMatSubmeshInfo, List <List <Material> > >(); Dictionary <Material, Mesh> obUVobject2mesh_map = new Dictionary <Material, Mesh>(); //validate that the objects to be combined are valid for (int i = 0; i < mom.GetObjectsToCombine().Count; i++) { GameObject go = mom.GetObjectsToCombine()[i]; if (go == null) { Debug.LogError("Null object in list of objects to combine at position " + i); return; } Renderer r = go.GetComponent <Renderer>(); if (r == null || (!(r is MeshRenderer) && !(r is SkinnedMeshRenderer))) { Debug.LogError("GameObject at position " + i + " in list of objects to combine did not have a renderer"); return; } if (r.sharedMaterial == null) { Debug.LogError("GameObject at position " + i + " in list of objects to combine has a null material"); return; } } //first pass put any meshes with obUVs on their own submesh if not fixing OB uvs if (mom.doMultiMaterialSplitAtlasesIfOBUVs) { for (int i = 0; i < mom.GetObjectsToCombine().Count; i++) { GameObject go = mom.GetObjectsToCombine()[i]; Mesh m = MB_Utility.GetMesh(go); MB_Utility.MeshAnalysisResult dummyMar = new MB_Utility.MeshAnalysisResult(); Renderer r = go.GetComponent <Renderer>(); for (int j = 0; j < r.sharedMaterials.Length; j++) { if (MB_Utility.hasOutOfBoundsUVs(m, ref dummyMar, j)) { if (!obUVobject2mesh_map.ContainsKey(r.sharedMaterials[j])) { Debug.LogWarning("Object " + go + " submesh " + j + " uses UVs outside the range 0,0..1,1 to generate tiling. This object has been mapped to its own submesh in the combined mesh. It can share a submesh with other objects that use different materials if you use the fix out of bounds UVs feature which will bake the tiling"); obUVobject2mesh_map.Add(r.sharedMaterials[j], m); } } } } } //second pass put other materials without OB uvs in a shader to material map for (int i = 0; i < mom.GetObjectsToCombine().Count; i++) { Renderer r = mom.GetObjectsToCombine()[i].GetComponent <Renderer>(); for (int j = 0; j < r.sharedMaterials.Length; j++) { if (!obUVobject2mesh_map.ContainsKey(r.sharedMaterials[j])) { //if not already added if (r.sharedMaterials[j] == null) { continue; } List <List <Material> > binsOfMatsThatUseShader = null; MB3_TextureBakerEditorInternal.MultiMatSubmeshInfo newKey = new MB3_TextureBakerEditorInternal.MultiMatSubmeshInfo(r.sharedMaterials[j].shader, r.sharedMaterials[j]); if (!shader2Material_map.TryGetValue(newKey, out binsOfMatsThatUseShader)) { binsOfMatsThatUseShader = new List <List <Material> >(); binsOfMatsThatUseShader.Add(new List <Material>()); shader2Material_map.Add(newKey, binsOfMatsThatUseShader); } if (!binsOfMatsThatUseShader[0].Contains(r.sharedMaterials[j])) { binsOfMatsThatUseShader[0].Add(r.sharedMaterials[j]); } } } } int numResMats = shader2Material_map.Count; //third pass for each shader grouping check how big the atlas would be and group into bins that would fit in an atlas if (mom.doMultiMaterialSplitAtlasesIfTooBig) { if (mom.packingAlgorithm == MB2_PackingAlgorithmEnum.UnitysPackTextures) { Debug.LogWarning("Unity texture packer does not support splitting atlases if too big. Atlases will not be split."); } else { numResMats = 0; foreach (MB3_TextureBakerEditorInternal.MultiMatSubmeshInfo sh in shader2Material_map.Keys) { List <List <Material> > binsOfMatsThatUseShader = shader2Material_map[sh]; List <Material> allMatsThatUserShader = binsOfMatsThatUseShader[0];//at this point everything is in the same list binsOfMatsThatUseShader.RemoveAt(0); MB3_TextureCombiner combiner = mom.CreateAndConfigureTextureCombiner(); combiner.saveAtlasesAsAssets = false; if (allMatsThatUserShader.Count > 1) { combiner.fixOutOfBoundsUVs = mom.fixOutOfBoundsUVs; } else { combiner.fixOutOfBoundsUVs = false; } // Do the texture pack List <AtlasPackingResult> packingResults = new List <AtlasPackingResult>(); Material tempMat = new Material(sh.shader); MB_AtlasesAndRects atlasesAndRects = new MB_AtlasesAndRects(); combiner.CombineTexturesIntoAtlases(null, atlasesAndRects, tempMat, mom.GetObjectsToCombine(), allMatsThatUserShader, null, packingResults, onlyPackRects: true, splitAtlasWhenPackingIfTooBig: true); for (int i = 0; i < packingResults.Count; i++) { List <MB_MaterialAndUVRect> matsData = (List <MB_MaterialAndUVRect>)packingResults[i].data; List <Material> mats = new List <Material>(); for (int j = 0; j < matsData.Count; j++) { Material mat = matsData[j].material; if (!mats.Contains(mat)) { mats.Add(mat); } } binsOfMatsThatUseShader.Add(mats); } numResMats += binsOfMatsThatUseShader.Count; } } } //build the result materials if (shader2Material_map.Count == 0 && obUVobject2mesh_map.Count == 0) { Debug.LogError("Found no materials in list of objects to combine"); } mom.resultMaterials = new MB_MultiMaterial[numResMats + obUVobject2mesh_map.Count]; string pth = AssetDatabase.GetAssetPath(mom.textureBakeResults); string baseName = Path.GetFileNameWithoutExtension(pth); string folderPath = pth.Substring(0, pth.Length - baseName.Length - 6); int k = 0; foreach (MB3_TextureBakerEditorInternal.MultiMatSubmeshInfo sh in shader2Material_map.Keys) { foreach (List <Material> matsThatUse in shader2Material_map[sh]) { MB_MultiMaterial mm = mom.resultMaterials[k] = new MB_MultiMaterial(); mm.sourceMaterials = matsThatUse; if (mm.sourceMaterials.Count == 1) { mm.considerMeshUVs = false; } else { mm.considerMeshUVs = mom.fixOutOfBoundsUVs; } string matName = folderPath + baseName + "-mat" + k + ".mat"; Material newMat = new Material(Shader.Find("Diffuse")); if (matsThatUse.Count > 0 && matsThatUse[0] != null) { MB3_TextureBaker.ConfigureNewMaterialToMatchOld(newMat, matsThatUse[0]); } AssetDatabase.CreateAsset(newMat, matName); mm.combinedMaterial = (Material)AssetDatabase.LoadAssetAtPath(matName, typeof(Material)); k++; } } foreach (Material m in obUVobject2mesh_map.Keys) { MB_MultiMaterial mm = mom.resultMaterials[k] = new MB_MultiMaterial(); mm.sourceMaterials = new List <Material>(); mm.sourceMaterials.Add(m); mm.considerMeshUVs = false; string matName = folderPath + baseName + "-mat" + k + ".mat"; Material newMat = new Material(Shader.Find("Diffuse")); MB3_TextureBaker.ConfigureNewMaterialToMatchOld(newMat, m); AssetDatabase.CreateAsset(newMat, matName); mm.combinedMaterial = (Material)AssetDatabase.LoadAssetAtPath(matName, typeof(Material)); k++; } MBVersionEditor.UpdateIfDirtyOrScript(textureBaker); }
public static void ConfigureTextureArraysFromObjsToCombine(MB3_TextureBaker mom, SerializedProperty resultMaterialsTexArrays, SerializedObject textureBaker) { if (mom.GetObjectsToCombine().Count == 0) { Debug.LogError("You need to add some objects to combine before building the texture array result materials."); return; } if (resultMaterialsTexArrays.arraySize > 0) { Debug.LogError("You already have some texture array result materials configured. You must remove these before doing this operation."); return; } if (mom.textureBakeResults == null) { Debug.LogError("Texture Bake Result asset must be set before using this operation."); return; } //validate that the objects to be combined are valid for (int i = 0; i < mom.GetObjectsToCombine().Count; i++) { GameObject go = mom.GetObjectsToCombine()[i]; if (go == null) { Debug.LogError("Null object in list of objects to combine at position " + i); return; } if (MB_Utility.GetMesh(go) == null) { Debug.LogError("Could not get mesh for object in list of objects to combine at position " + i); return; } Renderer r = go.GetComponent <Renderer>(); if (r == null || (!(r is MeshRenderer) && !(r is SkinnedMeshRenderer))) { Debug.LogError("GameObject at position " + i + " in list of objects to combine did not have a renderer"); return; } if (r.sharedMaterial == null) { Debug.LogError("GameObject at position " + i + " in list of objects to combine has a null material"); return; } } //Will sort into "result material" // slices Dictionary <MB3_TextureBakerEditorInternal.MultiMatSubmeshInfo, List <Slice> > shader2ResultMat_map = new Dictionary <MB3_TextureBakerEditorInternal.MultiMatSubmeshInfo, List <Slice> >(); // first pass split by shader and analyse meshes. List <GameObject> objsToCombine = mom.GetObjectsToCombine(); for (int meshIdx = 0; meshIdx < objsToCombine.Count; meshIdx++) { GameObject srcGo = objsToCombine[meshIdx]; Mesh mesh = MB_Utility.GetMesh(srcGo); Renderer r = MB_Utility.GetRenderer(srcGo); if (mom.LOG_LEVEL >= MB2_LogLevel.trace) { Debug.Log("1st Pass 'Split By Shader' Processing Mesh: " + mesh + " Num submeshes: " + r.sharedMaterials.Length); } for (int submeshIdx = 0; submeshIdx < r.sharedMaterials.Length; submeshIdx++) { if (r.sharedMaterials[submeshIdx] == null) { continue; } MB3_TextureBakerEditorInternal.MultiMatSubmeshInfo newKey = new MB3_TextureBakerEditorInternal.MultiMatSubmeshInfo(r.sharedMaterials[submeshIdx].shader, r.sharedMaterials[submeshIdx]); // Initially we fill the list of srcMaterials with garbage MB_MaterialAndUVRects. Will get proper ones when we atlas pack. MB_MaterialAndUVRect submeshMaterial = new MB_MaterialAndUVRect( r.sharedMaterials[submeshIdx], new Rect(0, 0, 0, 0), // garbage value false, //garbage value new Rect(0, 0, 0, 0), // garbage value new Rect(0, 0, 0, 0), // garbage value new Rect(0, 0, 1, 1), // garbage value MB_TextureTilingTreatment.unknown, // garbage value r.name); submeshMaterial.objectsThatUse = new List <GameObject>(); submeshMaterial.objectsThatUse.Add(r.gameObject); if (!shader2ResultMat_map.ContainsKey(newKey)) { // this is a new shader create a new result material Slice srcMaterials = new Slice { atlasRects = new List <MB_MaterialAndUVRect>(), numAtlasRects = 1, }; srcMaterials.atlasRects.Add(submeshMaterial); List <Slice> binsOfMatsThatUseShader = new List <Slice>(); binsOfMatsThatUseShader.Add(srcMaterials); if (mom.LOG_LEVEL >= MB2_LogLevel.trace) { Debug.Log(" Adding Source Material: " + submeshMaterial.material); } shader2ResultMat_map.Add(newKey, binsOfMatsThatUseShader); } else { // there is a result material that uses this shader. Add this source material Slice srcMaterials = shader2ResultMat_map[newKey][0]; // There should only be one list of source materials if (srcMaterials.atlasRects.Find(x => x.material == submeshMaterial.material) == null) { if (mom.LOG_LEVEL >= MB2_LogLevel.trace) { Debug.Log(" Adding Source Material: " + submeshMaterial.material); } srcMaterials.atlasRects.Add(submeshMaterial); } } } } int resMatCount = 0; foreach (MB3_TextureBakerEditorInternal.MultiMatSubmeshInfo resultMat in shader2ResultMat_map.Keys) { // at this point there there should be only one slice with all the source materials resMatCount++; // For each result material, all source materials are in the first slice. // We will now split these using a texture packer. Each "atlas" generated by the packer will be a slice. { // All source materials should be in the first slice at this point. List <Slice> slices = shader2ResultMat_map[resultMat]; List <Slice> newSlices = new List <Slice>(); Slice firstSlice = slices[0]; List <Material> allMatsThatUserShader = new List <Material>(); List <GameObject> objsThatUseFirstSlice = new List <GameObject>(); for (int i = 0; i < firstSlice.atlasRects.Count; i++) { allMatsThatUserShader.Add(firstSlice.atlasRects[i].material); if (!objsThatUseFirstSlice.Contains(firstSlice.atlasRects[i].objectsThatUse[0])) { objsThatUseFirstSlice.Add(firstSlice.atlasRects[i].objectsThatUse[0]); } } MB3_TextureCombiner combiner = mom.CreateAndConfigureTextureCombiner(); combiner.packingAlgorithm = MB2_PackingAlgorithmEnum.MeshBakerTexturePacker; combiner.saveAtlasesAsAssets = false; combiner.fixOutOfBoundsUVs = true; combiner.doMergeDistinctMaterialTexturesThatWouldExceedAtlasSize = true; List <AtlasPackingResult> packingResults = new List <AtlasPackingResult>(); Material tempMat = new Material(resultMat.shader); if (mom.LOG_LEVEL >= MB2_LogLevel.debug) { Debug.Log("======== 2nd pass. Use atlas packer to split the first slice into multiple if it exceeds atlas size. "); } combiner.CombineTexturesIntoAtlases(null, null, tempMat, mom.GetObjectsToCombine(), allMatsThatUserShader, null, packingResults, onlyPackRects: true, splitAtlasWhenPackingIfTooBig: true); if (mom.LOG_LEVEL >= MB2_LogLevel.debug) { Debug.Log("======== Completed packing with texture packer. numPackingResults: " + packingResults.Count); } newSlices.Clear(); // The texture packing just split the atlas into multiple atlases. Each atlas will become a "slice". for (int newSliceIdx = 0; newSliceIdx < packingResults.Count; newSliceIdx++) { List <MB_MaterialAndUVRect> sourceMats = new List <MB_MaterialAndUVRect>(); List <MB_MaterialAndUVRect> packedMatRects = (List <MB_MaterialAndUVRect>)packingResults[newSliceIdx].data; HashSet <Rect> distinctAtlasRects = new HashSet <Rect>(); for (int packedMatRectIdx = 0; packedMatRectIdx < packedMatRects.Count; packedMatRectIdx++) { MB_MaterialAndUVRect muvr = packedMatRects[packedMatRectIdx]; distinctAtlasRects.Add(muvr.atlasRect); { Rect encapsulatingRect = muvr.GetEncapsulatingRect(); Vector2 sizeInAtlas_px = new Vector2( packingResults[newSliceIdx].atlasX * encapsulatingRect.width, packingResults[newSliceIdx].atlasY * encapsulatingRect.height); } sourceMats.Add(muvr); } Slice slice = new Slice() { atlasRects = sourceMats, packingResult = packingResults[newSliceIdx], numAtlasRects = distinctAtlasRects.Count, }; newSlices.Add(slice); } // Replace first slice with split version. if (mom.LOG_LEVEL >= MB2_LogLevel.debug) { Debug.Log("First slice exceeded atlas size splitting it into " + newSlices.Count + " slices"); } slices.RemoveAt(0); for (int i = 0; i < newSlices.Count; i++) { slices.Insert(i, newSlices[i]); } } } // build the texture array result materials if (shader2ResultMat_map.Count == 0) { Debug.LogError("Found no materials in list of objects to combine"); } mom.resultMaterialsTexArray = new MB_MultiMaterialTexArray[shader2ResultMat_map.Count]; int k = 0; foreach (MB3_TextureBakerEditorInternal.MultiMatSubmeshInfo resMatKey in shader2ResultMat_map.Keys) { List <Slice> srcSlices = shader2ResultMat_map[resMatKey]; MB_MultiMaterialTexArray mm = mom.resultMaterialsTexArray[k] = new MB_MultiMaterialTexArray(); for (int sliceIdx = 0; sliceIdx < srcSlices.Count; sliceIdx++) { Slice slice = srcSlices[sliceIdx]; MB_TexArraySlice resSlice = new MB_TexArraySlice(); List <Material> usedMats = new List <Material>(); for (int srcMatIdx = 0; srcMatIdx < slice.atlasRects.Count; srcMatIdx++) { MB_MaterialAndUVRect matAndUVRect = slice.atlasRects[srcMatIdx]; List <GameObject> objsThatUse = matAndUVRect.objectsThatUse; for (int objsThatUseIdx = 0; objsThatUseIdx < objsThatUse.Count; objsThatUseIdx++) { GameObject obj = objsThatUse[objsThatUseIdx]; if (!resSlice.ContainsMaterialAndMesh(slice.atlasRects[srcMatIdx].material, MB_Utility.GetMesh(obj))) { resSlice.sourceMaterials.Add( new MB_TexArraySliceRendererMatPair() { renderer = obj, sourceMaterial = slice.atlasRects[srcMatIdx].material } ); } } } { // Should we use considerUVs bool doConsiderUVs = false; // If there is more than one atlas rectangle in a slice then use considerUVs if (slice.numAtlasRects > 1) { doConsiderUVs = true; } else { // There is only one source material, could be: // - lots of tiling (don't want consider UVs) // - We are extracting a small part of a large atlas (want considerUVs) if (slice.packingResult.atlasX >= mom.maxAtlasSize || slice.packingResult.atlasY >= mom.maxAtlasSize) { doConsiderUVs = false; // lots of tiling } else { doConsiderUVs = true; // extracting a small part of an atlas } } resSlice.considerMeshUVs = doConsiderUVs; } mm.slices.Add(resSlice); } // Enforce integrity. If a material appears in more than one slice then all those slices must be considerUVs=true { // collect all distinct materials HashSet <Material> distinctMats = new HashSet <Material>(); Dictionary <Material, int> mat2sliceCount = new Dictionary <Material, int>(); for (int sliceIdx = 0; sliceIdx < mm.slices.Count; sliceIdx++) { for (int sliceMatIdx = 0; sliceMatIdx < mm.slices[sliceIdx].sourceMaterials.Count; sliceMatIdx++) { Material mat = mm.slices[sliceIdx].sourceMaterials[sliceMatIdx].sourceMaterial; distinctMats.Add(mat); mat2sliceCount[mat] = 0; } } // Count the number of slices that use each material. foreach (Material mat in distinctMats) { for (int sliceIdx = 0; sliceIdx < mm.slices.Count; sliceIdx++) { if (mm.slices[sliceIdx].ContainsMaterial(mat)) { mat2sliceCount[mat] = mat2sliceCount[mat] + 1; } } } // Check that considerUVs is true for any materials that appear more than once foreach (Material mat in distinctMats) { if (mat2sliceCount[mat] > 1) { for (int sliceIdx = 0; sliceIdx < mm.slices.Count; sliceIdx++) { if (mm.slices[sliceIdx].ContainsMaterial(mat)) { if (mom.LOG_LEVEL >= MB2_LogLevel.debug && mm.slices[sliceIdx].considerMeshUVs) { Debug.Log("There was a material " + mat + " that was used by more than one slice and considerUVs was false. sliceIdx:" + sliceIdx); } mm.slices[sliceIdx].considerMeshUVs = true; } } } } } // Cleanup. remove "Renderer"s from source materials that do not use considerUVs and delete extra { // put any slices with consider UVs first List <MB_TexArraySlice> newSlices = new List <MB_TexArraySlice>(); for (int sliceIdx = 0; sliceIdx < mm.slices.Count; sliceIdx++) { if (mm.slices[sliceIdx].considerMeshUVs == true) { newSlices.Add(mm.slices[sliceIdx]); } } // for any slices without considerUVs, remove "renderer" and truncate for (int sliceIdx = 0; sliceIdx < mm.slices.Count; sliceIdx++) { MB_TexArraySlice slice = mm.slices[sliceIdx]; if (slice.considerMeshUVs == false) { newSlices.Add(slice); HashSet <Material> distinctMats = slice.GetDistinctMaterials(); slice.sourceMaterials.Clear(); foreach (Material mat in distinctMats) { slice.sourceMaterials.Add(new MB_TexArraySliceRendererMatPair() { sourceMaterial = mat }); } } } mm.slices = newSlices; } string pth = AssetDatabase.GetAssetPath(mom.textureBakeResults); string baseName = Path.GetFileNameWithoutExtension(pth); string folderPath = pth.Substring(0, pth.Length - baseName.Length - 6); string matName = folderPath + baseName + "-mat" + k + ".mat"; Material existingAsset = AssetDatabase.LoadAssetAtPath <Material>(matName); if (!existingAsset) { Material newMat = new Material(Shader.Find("Standard")); // Don't try to configure the material we need the user to pick a shader that has TextureArrays AssetDatabase.CreateAsset(newMat, matName); } mm.combinedMaterial = (Material)AssetDatabase.LoadAssetAtPath(matName, typeof(Material)); k++; } MBVersionEditor.UpdateIfDirtyOrScript(textureBaker); textureBaker.Update(); }