// Returns a flat 3D polygonized mesh from 2D outer/inner contours public static Mesh PolygonizeContours( List<Contour> a_rDominantContoursList, float a_fScale, Vector3 a_f3PivotPoint, float a_fWidth, float a_fHeight ) { // The mesh to build Mesh oCombinedMesh = new Mesh( ); int iContourCount = a_rDominantContoursList.Count; //a_rDominantContoursList.Count; // Step 2: Ear clip outer contour CombineInstance[ ] oCombineMeshInstance = new CombineInstance[ iContourCount ]; for( int iContourIndex = 0; iContourIndex < iContourCount; ++iContourIndex ) { Vector3[ ] oVerticesArray; int[ ] oTrianglesArray; Vector2[ ] oUVs; Mesh oSubMesh = new Mesh( ); EarClipping( a_rDominantContoursList[ iContourIndex ], a_fScale, a_f3PivotPoint, a_fWidth, a_fHeight, out oVerticesArray, out oTrianglesArray, out oUVs ); oSubMesh.vertices = oVerticesArray; oSubMesh.uv = oUVs; oSubMesh.triangles = oTrianglesArray; oCombineMeshInstance[ iContourIndex ].mesh = oSubMesh; } // Step 3: Combine every sub meshes (merge, no transform) oCombinedMesh.CombineMeshes( oCombineMeshInstance, true, false ); // Return! return oCombinedMesh; }
public void Write(SceneWriter writer, object component) { Component script = component as Component; if (script == null) { throw new Exception(GetType() + " cannot export components of type " + component.GetType()); } MeshFilter[] meshFilters = script.GetComponentsInChildren<MeshFilter>(); CombineInstance[] combine = new CombineInstance[meshFilters.Length]; for ( int i = 0; i < meshFilters.Length; i++) { combine[i].mesh = meshFilters[i].sharedMesh; combine[i].transform = meshFilters[i].transform.localToWorldMatrix; } Mesh mesh = new Mesh(); mesh.CombineMeshes(combine); MeshRenderer mr = script.GetComponentInChildren<MeshRenderer>(); writer.WriteElement("sharedMaterials", mr.sharedMaterials); writer.WriteElement("triangles", mesh.triangles); writer.WriteElement("vertices", mesh.vertices); //writer.WriteElement("normals", mesh.normals); writer.WriteElement("uv", mesh.uv); Debug.Log(script.name + " batched " + combine.Length + " objects into a mesh of " + (mesh.triangles.Length / 3) + " triangles and " + mesh.vertices.Length + " vertices."); if (mesh.vertices.Length > short.MaxValue) { Debug.LogWarning("BATCHED TOO MANY TRIANGLES!!"); } }
static public int CombineMeshes(IntPtr l) { try { int argc = LuaDLL.lua_gettop(l); if (argc == 2) { UnityEngine.Mesh self = (UnityEngine.Mesh)checkSelf(l); UnityEngine.CombineInstance[] a1; checkArray(l, 2, out a1); self.CombineMeshes(a1); pushValue(l, true); return(1); } else if (argc == 3) { UnityEngine.Mesh self = (UnityEngine.Mesh)checkSelf(l); UnityEngine.CombineInstance[] a1; checkArray(l, 2, out a1); System.Boolean a2; checkType(l, 3, out a2); self.CombineMeshes(a1, a2); pushValue(l, true); return(1); } else if (argc == 4) { UnityEngine.Mesh self = (UnityEngine.Mesh)checkSelf(l); UnityEngine.CombineInstance[] a1; checkArray(l, 2, out a1); System.Boolean a2; checkType(l, 3, out a2); System.Boolean a3; checkType(l, 4, out a3); self.CombineMeshes(a1, a2, a3); pushValue(l, true); return(1); } else if (argc == 5) { UnityEngine.Mesh self = (UnityEngine.Mesh)checkSelf(l); UnityEngine.CombineInstance[] a1; checkArray(l, 2, out a1); System.Boolean a2; checkType(l, 3, out a2); System.Boolean a3; checkType(l, 4, out a3); System.Boolean a4; checkType(l, 5, out a4); self.CombineMeshes(a1, a2, a3, a4); pushValue(l, true); return(1); } pushValue(l, false); LuaDLL.lua_pushstring(l, "No matched override function CombineMeshes to call"); return(2); } catch (Exception e) { return(error(l, e)); } }
public static void CombineMeshes(Queue<CombineInstance> items , byte area , InputGeometryCompiler compiler) { const int MaxTris = 65000; List<CombineInstance> combineInstancesPart = new List<CombineInstance>(); byte[] areas = NMGen.CreateAreaBuffer(MaxTris, area); while (items.Count != 0) { int vertCount = 0; while (items.Count > 0 && (vertCount + items.Peek().mesh.vertexCount < MaxTris)) { vertCount += items.Peek().mesh.vertexCount; combineInstancesPart.Add(items.Dequeue()); } Mesh meshPart = new Mesh(); meshPart.CombineMeshes(combineInstancesPart.ToArray(), true, true); compiler.AddTriangles(meshPart.vertices, meshPart.vertexCount , meshPart.triangles, areas, meshPart.triangles.Length / 3); Object.DestroyImmediate(meshPart); combineInstancesPart.Clear(); } }
public Mesh FuseToChunkMesh(MeshFilter ChunkMesh, MeshFilter[] NewMeshes, Vector3 ChunkPos, bool Restart = true) { //store old positions foreach (MeshFilter filter in NewMeshes) { filter.transform.position -= ChunkPos; } ChunkMesh.transform.position = Vector3.zero; CombineInstance[] combine = new CombineInstance[NewMeshes.Length + 1]; List<MeshFilter> MeshList = new List<MeshFilter>(NewMeshes); for (int i = 0; i < combine.Length - 1; i++) { combine[i].mesh = MeshList[i].sharedMesh; combine[i].transform = MeshList[i].transform.localToWorldMatrix; DestroyImmediate(MeshList[i].gameObject); } MeshList.Add(ChunkMesh); combine[NewMeshes.Length].mesh = MeshList[NewMeshes.Length].sharedMesh; combine[NewMeshes.Length].transform = MeshList[NewMeshes.Length].transform.localToWorldMatrix; Mesh m = new Mesh(); m.CombineMeshes(combine, true, true); ChunkMesh.transform.position = ChunkPos; return m; }
public override Collider GetCollider(GameObject parent, Vector3 pos) { //Get mesh filters MeshFilter[] meshFilters = GetPrefab().GetComponentsInChildren<MeshFilter>(); CombineInstance[] meshes = new CombineInstance[meshFilters.Length]; //Add meshes to array for (int i = 0; i < meshes.Length; i++) { meshes[i].mesh = meshFilters[i].sharedMesh; meshes[i].transform = meshFilters[i].transform.localToWorldMatrix; } //Combine meshes Mesh mesh = new Mesh(); mesh.CombineMeshes(meshes); //Add position and rotate Vector3[] verticies = mesh.vertices; for (int i = 0; i < verticies.Length; i++) { verticies[i] += pos; verticies[i] = Quaternion.Euler(90, 0, 0) * verticies[i]; } mesh.vertices = verticies; //Create mesh collider MeshCollider coll = parent.AddComponent<MeshCollider>(); coll.sharedMesh = mesh; return coll; }
public static Mesh BaselessPyramid(Vector3 baseCenter, Vector3 apex, float radius, int segments, bool inverted = false) { var segmentAngle = Mathf.PI*2/segments; var currentAngle = 0f; var v = new Vector3[segments + 1]; v[0] = apex; for (var i = 1; i <= segments; i++) { v[i] = new Vector3(radius*Mathf.Sin(currentAngle), 0, radius*Mathf.Cos(currentAngle)) + baseCenter; if (inverted) currentAngle -= segmentAngle; else currentAngle += segmentAngle; } var combine = new CombineInstance[segments]; for (var i = 0; i < segments - 1; i++) { combine[i].mesh = Triangle(v[0], v[i + 1], v[i + 2]); } combine[combine.Length - 1].mesh = Triangle(v[0], v[v.Length - 1], v[1]); var mesh = new Mesh(); mesh.CombineMeshes(combine, true, false); return mesh; }
public Mesh[] CombinedMeshes(List<Mesh> meshObjectList) { List<Mesh> meshs = new List<Mesh>(); // combine meshes List<CombineInstance> combine = new List<CombineInstance>(); int i = 0; while (i < meshObjectList.Count) { CombineInstance instance = new CombineInstance(); instance.mesh = meshObjectList[i]; instance.transform = transform.localToWorldMatrix; combine.Add(instance); i++; } Mesh combinedMesh = new Mesh(); combinedMesh.CombineMeshes(combine.ToArray()); meshs.Add(combinedMesh); combine = new List<CombineInstance>(); return meshs.ToArray(); }
protected virtual void LateUpdate() { if(_hasRenderer) return; _hasRenderer = true; foreach (KeyValuePair<Material, List<PCTrail>> keyValuePair in _matToTrailList) { CombineInstance[] combineInstances = new CombineInstance[keyValuePair.Value.Count]; for (int i = 0; i < keyValuePair.Value.Count; i++) { combineInstances[i] = new CombineInstance { mesh = keyValuePair.Value[i].Mesh, subMeshIndex = 0, transform = Matrix4x4.identity }; } Mesh combinedMesh = new Mesh(); combinedMesh.CombineMeshes(combineInstances, true, false); _toClean.Add(combinedMesh); DrawMesh(combinedMesh, keyValuePair.Key); keyValuePair.Value.Clear(); } }
public static GameObject MergeMeshes(PaintJob[] jobs) { if (jobs.Length == 0) return null; List<CombineInstance> meshes = new List<CombineInstance>(); for (int i = 0; i < jobs.Length; ++i) { Mesh m = BakeDownMesh(jobs[i].meshFilter.sharedMesh, jobs[i].stream); CombineInstance ci = new CombineInstance(); ci.mesh = m; ci.transform = jobs[i].meshFilter.transform.localToWorldMatrix; meshes.Add(ci); } Mesh mesh = new Mesh(); mesh.CombineMeshes(meshes.ToArray()); GameObject go = new GameObject("Combined Mesh"); go.AddComponent<MeshRenderer>(); var mf = go.AddComponent<MeshFilter>(); mesh.Optimize(); mesh.RecalculateBounds(); mesh.UploadMeshData(false); mf.sharedMesh = mesh; for (int i = 0; i < meshes.Count; ++i) { GameObject.DestroyImmediate(meshes[i].mesh); } return go; }
public Mesh CreateMesh() { Mesh m = new Mesh { vertices = Vertices.ToArray(), uv = UV1.ToArray(), uv2 = UV2.ToArray(), triangles = Triangles.ToArray(), colors = Colors.ToArray() }; if(Submeshes.Count > 0) { CombineInstance[] instances = new CombineInstance[Submeshes.Count]; for(int i = 0; i < Submeshes.Count; i++) { CombineInstance ins = new CombineInstance { mesh = Submeshes[i].CreateMesh(), transform = Matrix4x4.identity }; instances[i] = ins; } m.CombineMeshes(instances, false); } m.RecalculateNormals(); m.RecalculateBounds(); m.Optimize(); return m; }
// Return a polygonized mesh from 2D outer/inner contours public static Mesh EarClipping( List<Contour> a_rDominantContoursList, float a_fExtrusionDepth, float a_fScale, Vector3 a_f3PivotPoint ) { // The mesh to build Mesh oCombinedMesh = new Mesh( ); int iContourCount = a_rDominantContoursList.Count; //a_rDominantContoursList.Count; // Step 2: Ear clip outer contour CombineInstance[ ] oCombineMeshInstance = new CombineInstance[ iContourCount ]; for( int iContourIndex = 0; iContourIndex < iContourCount; ++iContourIndex ) { Vector3[ ] oVerticesArray; List<int> oTrianglesList; EarClippingSubMesh( a_rDominantContoursList[ iContourIndex ], a_fScale, a_f3PivotPoint, out oVerticesArray, out oTrianglesList ); oCombineMeshInstance[ iContourIndex ].mesh = BuildExtrudedMeshFromPolygonizedContours( oVerticesArray, oTrianglesList, a_fExtrusionDepth ); // EarClippingSubMesh( a_rDominantContoursList[ iContourIndex ] ); } // Step 3: Combine every sub meshes (merge, no transform) oCombinedMesh.CombineMeshes( oCombineMeshInstance, true, false ); // Return! return oCombinedMesh; }
void Init () { Component[] meshFilters = GetComponentsInChildren<MeshFilter>(true); Dictionary<Material, List<CombineInstance>> combineMeshInstanceDictionary = new Dictionary<Material, List<CombineInstance>> (); foreach (var mesh in meshFilters) { var mat = mesh.GetComponent<Renderer>().sharedMaterial ; if( mat == null ) continue; if(!combineMeshInstanceDictionary.ContainsKey(mat) ) { combineMeshInstanceDictionary.Add( mat, new List<CombineInstance>()); } var instance = combineMeshInstanceDictionary[ mat ]; var cmesh = new CombineInstance(); cmesh.transform = mesh.transform.localToWorldMatrix; cmesh.mesh = ((MeshFilter) mesh).sharedMesh; instance.Add(cmesh); } gameObject.SetActive (false); gameObject.tag = "EditorOnly"; if( generatedObject == null) generatedObject = new GameObject (name); foreach (var item in generatedObject.GetComponentsInChildren<Transform>()) { if( item == generatedObject.transform ) continue; DestroyImmediate (item.gameObject); } generatedObject.isStatic = true; foreach (var dic in combineMeshInstanceDictionary) { var newObject = new GameObject(dic.Key.name); newObject.isStatic = true; var meshrenderer = newObject.AddComponent<MeshRenderer>(); var meshfilter = newObject.AddComponent<MeshFilter>(); meshrenderer.material = dic.Key; var mesh = new Mesh(); mesh.CombineMeshes(dic.Value.ToArray()); Unwrapping.GenerateSecondaryUVSet( mesh); meshfilter.sharedMesh = mesh; newObject.transform.parent = generatedObject.transform; Debug.Log(Application.loadedLevelName); System.IO.Directory.CreateDirectory( "Assets/" + Application.loadedLevelName + "/" + name ); AssetDatabase.CreateAsset(mesh, "Assets/" + Application.loadedLevelName+ "/" + name + "/" + dic.Key.name + ".asset"); } }
public static Bounds CreateProxies(GameObject go, PropTools.Prop prop) { List<Mesh> proxyMeshes = new List<Mesh>(); List<Material> proxyMaterials = new List<Material>(); GameObject cube = GameObject.CreatePrimitive(PrimitiveType.Cube); MeshFilter cubeMF = cube.GetComponent<MeshFilter>(); Mesh cubeMesh = cubeMF.sharedMesh; foreach (PropTools.Proxy proxy in prop.proxies) { Vector3[] verts = cubeMesh.vertices; for (int i = 0; i < verts.Length; i++) { verts[i].Scale(proxy.size); verts[i] += proxy.center; } Mesh proxyMesh = new Mesh(); proxyMesh.vertices = verts; proxyMesh.triangles = cubeMesh.triangles; proxyMesh.uv = cubeMesh.uv; proxyMesh.normals = cubeMesh.normals; Material proxyMat = new Material(Shader.Find("Diffuse")); proxyMat.color = proxy.color; proxyMat.hideFlags = HideFlags.HideInInspector | HideFlags.NotEditable; proxyMeshes.Add(proxyMesh); proxyMaterials.Add(proxyMat); } CombineInstance[] cI = new CombineInstance[proxyMeshes.Count]; for (int i = 0; i < proxyMeshes.Count; i++) { cI[i].mesh = proxyMeshes[i]; } Mesh combinedMesh = new Mesh(); combinedMesh.CombineMeshes(cI, false, false); combinedMesh.RecalculateBounds(); MeshFilter mf = go.AddComponent<MeshFilter>(); mf.hideFlags = HideFlags.HideInInspector | HideFlags.NotEditable; mf.sharedMesh = combinedMesh; MeshRenderer mr = go.AddComponent<MeshRenderer>(); mr.hideFlags = HideFlags.HideInInspector | HideFlags.NotEditable; mr.sharedMaterials = proxyMaterials.ToArray(); DestroyImmediate(cube); for (int i = 0; i < proxyMeshes.Count; i++) { DestroyImmediate(proxyMeshes[i]); } return combinedMesh.bounds; }
public static Mesh BiPyramid(float radius, int segments, float heignt) { var combine = new CombineInstance[2]; combine[0].mesh = BaselessPyramid(radius, segments, heignt); combine[1].mesh = BaselessPyramid(radius, segments, heignt, true); var mesh = new Mesh(); mesh.CombineMeshes(combine, true, false); return mesh; }
private void Start() { GameObject model = UnityEditor.AssetDatabase.LoadAssetAtPath(meshPath, typeof(GameObject)) as GameObject; GameObject prefab = UnityEditor.AssetDatabase.LoadAssetAtPath(prefabPath, typeof(GameObject)) as GameObject; // combine meshes MeshFilter[] meshFilters = model.GetComponentsInChildren<MeshFilter>(true); List<CombineInstance> combine = new List<CombineInstance>(); for (int i = 0; i < meshFilters.Length; i++) { Transform child = meshFilters[i].transform; CombineInstance combineInstance = new CombineInstance { mesh = meshFilters[i].sharedMesh, subMeshIndex = 0, transform = Matrix4x4.TRS(child.localPosition, child.localRotation, child.localScale) }; combine.Add(combineInstance); } // save mesh as asset Mesh mesh = new Mesh(); mesh.CombineMeshes(combine.ToArray(), false); mesh.Optimize(); // prefab string path = meshPath.Substring(0, meshPath.Length - 10) + "_Mesh.asset"; UnityEditor.AssetDatabase.CreateAsset(mesh, path); prefab.GetComponent<MeshFilter>().sharedMesh = (Mesh)UnityEditor.AssetDatabase.LoadAssetAtPath(path, typeof(Mesh)); // labels List<string> labels = UnityEditor.AssetDatabase.GetLabels(prefab).ToList(); labels.Add("CUBE"); labels.Add(CUBE.GetInfo(name).type.ToString()); UnityEditor.AssetDatabase.SetLabels(prefab, labels.ToArray()); // materials int materialCount = meshFilters.Length; Material[] alphaMats = new Material[materialCount]; for (int i = 0; i < materialCount; i++) { alphaMats[i] = VertexColor_Mat; } prefab.renderer.sharedMaterials = alphaMats; prefab.AddComponent<ColorVertices>().colors = new int[materialCount]; // delete model UnityEditor.AssetDatabase.DeleteAsset(meshPath); Debugger.Log("Imported " + name); // delete self Resources.UnloadUnusedAssets(); DestroyImmediate(gameObject); }
public static void MergeSkinnedMeshes(SkinnedMeshRenderer targetRenderer, SkinnedMeshRenderer[] meshesToMerge) { List<CombineInstance> combineInstances = new List<CombineInstance>(); List<BoneWeight> boneWeights = new List<BoneWeight>(); List<Transform> bones = new List<Transform>(); int boneOffset = 0; for (var i = 0; i < meshesToMerge.Length; ++i) { SkinnedMeshRenderer currentRenderer = meshesToMerge[i]; Mesh currentMesh = currentRenderer.sharedMesh; CombineInstance combineInstance = new CombineInstance(); combineInstance.mesh = currentMesh; combineInstances.Add(combineInstance); var currentBoneWeights = currentMesh.boneWeights; foreach (BoneWeight bw in currentBoneWeights) { BoneWeight bWeight = bw; bWeight.boneIndex0 += boneOffset; bWeight.boneIndex1 += boneOffset; bWeight.boneIndex2 += boneOffset; bWeight.boneIndex3 += boneOffset; boneWeights.Add(bWeight); } boneOffset += currentRenderer.bones.Length; Transform[] currentMeshBones = currentRenderer.bones; foreach (var bone in currentMeshBones) { bones.Add(bone); } } //List<Matrix4x4> bindposes = new List<Matrix4x4>(); //for (int i = 0; i < bones.Count; i++) //{ // bindposes.Add(bones[i].worldToLocalMatrix * targetRenderer.transform.worldToLocalMatrix); //} var resultingMesh = new Mesh(); resultingMesh.CombineMeshes(combineInstances.ToArray(), true, false); resultingMesh.boneWeights = boneWeights.ToArray(); //resultingMesh.bindposes = bindposes.ToArray(); resultingMesh.RecalculateBounds(); targetRenderer.sharedMesh = resultingMesh; targetRenderer.bones = bones.ToArray(); }
public static Mesh Combine(Mesh[] meshes) { CombineInstance[] combineInstances = new CombineInstance[meshes.Length]; for(int i = 0; i < meshes.Length; i++) { combineInstances[i].mesh = meshes[i]; } Mesh mesh = new Mesh(); mesh.CombineMeshes(combineInstances, false, false); return mesh; }
public static Mesh CombineMeshes(Matrix4x4 matrixTransform, params Mesh[] meshs) { /* * / List<Vector3> finalVerts = new List<Vector3>(); List<Vector2> finalUVs = new List<Vector2>(); List<int> finalTriangles = new List<int>(); for(int meshIndex = 0; meshIndex < meshs.Length; meshIndex++) { //Debug.Log ("combining"); //Debug.Log(meshs[meshIndex].vertices.Length); finalVerts.AddRange(meshs[meshIndex].vertices); finalUVs.AddRange(meshs[meshIndex].uv); finalTriangles.AddRange(meshs[meshIndex].triangles); } Mesh finalMesh = new Mesh(); finalMesh.vertices = finalVerts.ToArray(); finalMesh.uv = finalUVs.ToArray(); finalMesh.triangles = finalTriangles.ToArray(); Debug.Log("Final Vertice Count: " + finalMesh.vertices.Length); Debug.Log("Final UV Count: " + finalMesh.uv.Length); Debug.Log("Final Triangle Count: " + finalMesh.triangles.Length); /* */ CombineInstance[] combine = new CombineInstance[meshs.Length]; for(int meshIndex = 0; meshIndex < meshs.Length; meshIndex++) { combine[meshIndex].mesh = meshs[meshIndex]; combine[meshIndex].transform = matrixTransform; } /* if(mFilter) { mFilter.mesh.CombineMeshes(combine); mFilter.mesh.RecalculateBounds(); mFilter.mesh.RecalculateNormals(); } */ Mesh combinedMesh = new Mesh(); combinedMesh.CombineMeshes(combine); combinedMesh.RecalculateBounds(); combinedMesh.RecalculateNormals(); return combinedMesh; }
public static Mesh Combine(MeshInstance[] _combines) { Mesh mesh = new Mesh(); mesh.name = "Combined Mesh"; CombineInstance[] combineInsts = new CombineInstance[_combines.Length]; int i = 0; while (i < _combines.Length) { combineInsts[i].mesh = _combines[i].mesh; combineInsts[i].transform = _combines[i].transform; ++i; } mesh.CombineMeshes(combineInsts); return mesh; }
void Start () { meshFilter = GetComponent<MeshFilter>(); var combine = new CombineInstance[count]; for (int i = 0; i < count; i++) { var offset = Random.onUnitSphere * radius; combine[i].mesh = PGMesh.Triangle(offset + Random.onUnitSphere, offset + Random.onUnitSphere, offset + Random.onUnitSphere); } var mesh = new Mesh(); mesh.CombineMeshes(combine, true, false); meshFilter.sharedMesh = mesh; }
public static Bounds GetObjectBounds(GameObject obj) { MeshFilter[] filters = obj.GetComponentsInChildren<MeshFilter> (); CombineInstance[] instances = new CombineInstance[filters.Length]; for (int i = 0; i < filters.Length; i++) { instances[i].mesh = filters[i].sharedMesh; instances[i].transform = filters[i].transform.localToWorldMatrix; } Mesh newMesh = new Mesh (); newMesh.CombineMeshes (instances); newMesh.RecalculateBounds (); return newMesh.bounds; }
// Use this for initialization void Start () { Texture blueTex = transform.Find ("CubeBlue").GetComponent<MeshRenderer> ().sharedMaterial.mainTexture; Texture orgTex = transform.Find ("CubeOrg").GetComponent<MeshRenderer> ().sharedMaterial.mainTexture; Texture redTex = transform.Find ("CubeRed").GetComponent<MeshRenderer> ().sharedMaterial.mainTexture; Shader combineShader = Shader.Find("Custom/CombineShader"); Material combineMaterial = new Material (combineShader); combineMaterial.SetTexture ("_Red", redTex); combineMaterial.SetTexture ("_Blue", blueTex); combineMaterial.SetTexture ("_Org", orgTex); MeshFilter[] meshFilters = GetComponentsInChildren<MeshFilter> (); CombineInstance[] combine = new CombineInstance[meshFilters.Length]; List<Color> combineMeshColor = new List<Color> (); for (int i = 0; i < meshFilters.Length; i++) { combine[i].mesh = meshFilters[i].sharedMesh; combine[i].transform = meshFilters[i].transform.localToWorldMatrix; Vector2[] UVArray = meshFilters[i].sharedMesh.uv; float bodyPart = i / (float)meshFilters.Length; for(int uvindex = 0; uvindex < UVArray.Length; uvindex ++) { combineMeshColor.Add(new Color(bodyPart, bodyPart, bodyPart, bodyPart)); } meshFilters[i].gameObject.SetActive(false); } Mesh combineMesh = new Mesh (); combineMesh.CombineMeshes (combine, true); combineMesh.colors = combineMeshColor.ToArray (); combineMesh.name = gameObject.name; transform.gameObject.AddComponent<MeshRenderer> (); transform.gameObject.AddComponent<MeshFilter> (); transform.GetComponent<MeshFilter> ().sharedMesh = combineMesh; transform.GetComponent<MeshRenderer> ().sharedMaterial = combineMaterial; transform.gameObject.SetActive (true); }
public static Mesh Plane(Vector3 origin, Vector3 width, Vector3 length, int widthCount, int lengthCount) { var combine = new CombineInstance[widthCount * lengthCount]; var i = 0; for (var x = 0; x < widthCount; x++) { for (var y = 0; y < lengthCount; y++) { combine[i].mesh = Quad(origin + width * x + length * y, width, length); i++; } } var mesh = new Mesh(); mesh.CombineMeshes(combine, true, false); return mesh; }
static int CombineMeshes(IntPtr L) { try { int count = LuaDLL.lua_gettop(L); if (count == 2 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Mesh), typeof(UnityEngine.CombineInstance[]))) { UnityEngine.Mesh obj = (UnityEngine.Mesh)ToLua.ToObject(L, 1); UnityEngine.CombineInstance[] arg0 = ToLua.CheckObjectArray <UnityEngine.CombineInstance>(L, 2); obj.CombineMeshes(arg0); return(0); } else if (count == 3 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Mesh), typeof(UnityEngine.CombineInstance[]), typeof(bool))) { UnityEngine.Mesh obj = (UnityEngine.Mesh)ToLua.ToObject(L, 1); UnityEngine.CombineInstance[] arg0 = ToLua.CheckObjectArray <UnityEngine.CombineInstance>(L, 2); bool arg1 = LuaDLL.lua_toboolean(L, 3); obj.CombineMeshes(arg0, arg1); return(0); } else if (count == 4 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Mesh), typeof(UnityEngine.CombineInstance[]), typeof(bool), typeof(bool))) { UnityEngine.Mesh obj = (UnityEngine.Mesh)ToLua.ToObject(L, 1); UnityEngine.CombineInstance[] arg0 = ToLua.CheckObjectArray <UnityEngine.CombineInstance>(L, 2); bool arg1 = LuaDLL.lua_toboolean(L, 3); bool arg2 = LuaDLL.lua_toboolean(L, 4); obj.CombineMeshes(arg0, arg1, arg2); return(0); } else { return(LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Mesh.CombineMeshes")); } } catch (Exception e) { return(LuaDLL.toluaL_exception(L, e)); } }
public static Mesh CreateMesh(Vector2 []_points,float thin,Mesh OldMesh) { Object.Destroy(OldMesh); Mesh TargetMesh = new Mesh(); Vector3 [] points = new Vector3[_points.Length]; for(int i = 0;i < points.Length;i++) points[i] = new Vector3(_points[i].x,_points[i].y,0); CombineInstance[] combineInstances = new CombineInstance[points.Length-1]; for(int i = 0;i < points.Length-1;i++) { Vector3 w,h; w = points[i+1]-points[i]; w = w.normalized*(w.magnitude+thin); h = new Vector3(w.y*-1,w.x).normalized*thin; combineInstances[i].mesh = Quad(points[i],w,h); combineInstances[i].transform = Matrix4x4.identity; } TargetMesh.CombineMeshes(combineInstances); for (int i = 0;i < points.Length-1;i++) Object.Destroy(combineInstances[i].mesh); return TargetMesh; }
public Mesh GetCombineMesh() { MeshFilter[] meshFilters = GetComponentsInChildren<MeshFilter>(); CombineInstance[] combine = new CombineInstance[meshFilters.Length -1]; int i = 0; int idx = 0; Debug.Log(meshFilters.Length); while (i < meshFilters.Length) { if(meshFilters[i] != GetComponent<MeshFilter>()){ combine[idx].mesh = meshFilters[i].sharedMesh; Debug.Log(meshFilters[i].sharedMesh); combine[idx].transform = transform.worldToLocalMatrix * meshFilters[i].transform.localToWorldMatrix; idx ++; } //meshFilters[i].gameObject.active = false; i++; } Mesh mesh = new Mesh(); mesh.CombineMeshes(combine); return mesh; }
public Mesh FuseToChunkMesh(MeshFilter ChunkMesh, MeshFilter[] NewMeshes, bool Restart = true) { CombineInstance[] combine = new CombineInstance[NewMeshes.Length + 1]; List<MeshFilter> MeshList = new List<MeshFilter>(NewMeshes); for (int i = 0; i < combine.Length - 1; i++) { combine[i].mesh = MeshList[i].mesh; combine[i].transform = MeshList[i].transform.localToWorldMatrix; Destroy(MeshList[i].gameObject); } MeshList.Add(ChunkMesh); combine[NewMeshes.Length].mesh = MeshList[NewMeshes.Length].mesh; combine[NewMeshes.Length].transform = MeshList[NewMeshes.Length].transform.localToWorldMatrix; Mesh m = new Mesh(); m.CombineMeshes(combine); ChunkMesh.mesh = m; return ChunkMesh.mesh; }
public static Mesh CreateMeshFromCollider(BlobAssetReference <Collider> collider) { var mesh = new Mesh { hideFlags = HideFlags.DontSave }; var instances = new List <CombineInstance>(8); var numVertices = 0; foreach (var displayResult in (IEnumerable)k_DrawComponent_BuildDebugDisplayMesh.Invoke(null, new object[] { collider })) { var instance = new CombineInstance { mesh = k_DisplayResultsMesh.GetValue(displayResult) as Mesh, transform = (float4x4)k_DisplayResultsTransform.GetValue(displayResult) }; instances.Add(instance); numVertices += mesh.vertexCount; } mesh.indexFormat = numVertices > UInt16.MaxValue ? UnityEngine.Rendering.IndexFormat.UInt32 : UnityEngine.Rendering.IndexFormat.UInt16; mesh.CombineMeshes(instances.ToArray()); mesh.RecalculateBounds(); return(mesh); }
public void GenerateBeam() { MeshFilter meshFilter = this.GetComponent<MeshFilter>(); // generate two cylinders, one of them with reversed normals. Combine them. CombineInstance[] combineInstance = new CombineInstance[2]; combineInstance[0].mesh = GenerateMesh(false); combineInstance[0].transform = Matrix4x4.identity; combineInstance[1].mesh = GenerateMesh(true); combineInstance[1].transform = Matrix4x4.identity; Mesh combinedMesh = new Mesh(); combinedMesh.CombineMeshes(combineInstance); if (meshFilter.sharedMesh == null) meshFilter.sharedMesh = new Mesh(); meshFilter.sharedMesh.Clear(); meshFilter.sharedMesh.vertices = combinedMesh.vertices; meshFilter.sharedMesh.uv = combinedMesh.uv; meshFilter.sharedMesh.triangles = combinedMesh.triangles; meshFilter.sharedMesh.tangents = combinedMesh.tangents; meshFilter.sharedMesh.normals = combinedMesh.normals; }
protected virtual void PrepareForRendering (Mesh sharedMesh, bool force) { if(sharedMesh == null) return; SVGPath[] shape = svgShape.shape; if(shape != null && shape.Length > 0) { int[][] submeshes = new int[sharedMesh.subMeshCount][]; int subMeshCount = sharedMesh.subMeshCount; int i, j; for(i = 0; i < subMeshCount; i++) { submeshes[i] = sharedMesh.GetTriangles(i); } Mesh[] meshes = new Mesh[shape.Length + 1]; for(i = 0; i < shape.Length; i++) { int pointsLength = shape[i].points.Length - 1; StrokeSegment[] segments = new StrokeSegment[pointsLength]; for(j = 0; j < pointsLength; j++) { segments[j] = new StrokeSegment(shape[i].points[j], shape[i].points[j + 1]); } meshes[i] = SVGLineUtils.StrokeMesh(segments, width, color, lineJoin, lineCap, mitterLimit, dashArray, dashOffset, closeLine, roundQuality); } CombineInstance[] combineInstances = new CombineInstance[meshes.Length]; for(i = 0; i < meshes.Length; i++) { combineInstances[i].mesh = meshes[i]; } sharedMesh.CombineMeshes(combineInstances, false, false); } }
public Mesh InitializeStarfield() { float arg_49_0 = (!(Camera.main != null)) ? ((!(Camera.current != null)) ? 990f : Camera.current.farClipPlane) : (Camera.main.farClipPlane - 10f); float num = 5200f; float size = num / 100f * this.starSizeScale; TextAsset textAsset = Resources.Load<TextAsset>("StarsData"); if (textAsset == null) { Debug.Log("Can't find or read StarsData.bytes file."); return null; } StarField.Star[] array = new StarField.Star[9110]; using (BinaryReader binaryReader = new BinaryReader(new MemoryStream(textAsset.bytes))) { for (int i = 0; i < 9110; i++) { array[i].position.x = binaryReader.ReadSingle(); array[i].position.z = binaryReader.ReadSingle(); array[i].position.y = binaryReader.ReadSingle(); array[i].position = Vector3.Scale(array[i].position, new Vector3(-1f, 1f, -1f)); array[i].color.r = binaryReader.ReadSingle(); array[i].color.g = binaryReader.ReadSingle(); array[i].color.b = binaryReader.ReadSingle(); float a = Vector3.Dot(new Vector3(array[i].color.r, array[i].color.g, array[i].color.b), new Vector3(0.22f, 0.707f, 0.071f)); array[i].color.a = a; if (array[i].position.y >= 0.1f && array[i].color.a >= 0.017037f) { CombineInstance item = default(CombineInstance); item.mesh = this.createQuad(size); item.transform = this.BillboardMatrix(array[i].position * num); Color[] colors = new Color[] { array[i].color, array[i].color, array[i].color, array[i].color }; item.mesh.colors = colors; this.starQuad.Add(item); } } } Mesh mesh = new Mesh(); mesh.name = "StarFieldMesh"; mesh.CombineMeshes(this.starQuad.ToArray()); for (int j = 0; j < this.starQuad.Count; j++) { if (Application.isPlaying) { UnityEngine.Object.Destroy(this.starQuad[j].mesh); } else { UnityEngine.Object.DestroyImmediate(this.starQuad[j].mesh); } } this.starQuad.Clear(); mesh.Optimize(); mesh.bounds = new Bounds(Vector3.zero, Vector3.one * 2E+09f); return mesh; }
public void CombineMeshes() { LinkedList<MeshFilter> meshFilters = new LinkedList<MeshFilter>(); foreach (Chunk chunk in AllChunks) { meshFilters.AddLast(chunk.ChunkObj.GetComponent<MeshFilter>()); } CombineInstance[] combine = new CombineInstance[meshFilters.Count]; int i = 0; foreach (var filter in meshFilters) { combine[i].mesh = filter.mesh; combine[i].transform = filter.transform.localToWorldMatrix; filter.gameObject.SetActive(false); i += 1; } Mesh CombinedMesh = new Mesh(); MeshFilter ChunkTreeMeshFilter = Global.ChunkTreeObj.GetComponent<MeshFilter>(); if (ChunkTreeMeshFilter.mesh) { Object.Destroy(ChunkTreeMeshFilter.mesh); } CombinedMesh.CombineMeshes(combine); ChunkTreeMeshFilter.mesh = CombinedMesh; Global.ChunkTreeObj.GetComponent<MeshCollider>().sharedMesh = CombinedMesh; Global.ChunkTreeObj.SetActive(true); }
public static Entity CreateBodyWithMesh(EntityManager entityManager, UnityEngine.Material mat, UnityEngine.Mesh mesh, float3 position, quaternion orientation, BlobAssetReference <Unity.Physics.Collider> collider, float3 linearVelocity, float3 angularVelocity, float mass, bool isDynamic) { Entity entity = entityManager.CreateEntity(new ComponentType[] { }); entityManager.AddComponentData(entity, new LocalToWorld { }); entityManager.AddComponentData(entity, new Translation { Value = position }); entityManager.AddComponentData(entity, new Rotation { Value = orientation }); var colliderComponent = new PhysicsCollider { Value = collider }; entityManager.AddComponentData(entity, colliderComponent); #pragma warning disable 618 List <Unity.Physics.Authoring.DisplayBodyColliders.DrawComponent.DisplayResult> meshes; unsafe { meshes = Unity.Physics.Authoring.DisplayBodyColliders.DrawComponent.BuildDebugDisplayMesh(colliderComponent.ColliderPtr); } #pragma warning restore 618 CombineInstance[] instances = new CombineInstance[meshes.Count]; int numVertices = 0; for (int i = 0; i < meshes.Count; i++) { instances[i] = new CombineInstance { mesh = meshes[i].Mesh, transform = Matrix4x4.TRS(meshes[i].Position, meshes[i].Orientation, meshes[i].Scale) }; numVertices += meshes[i].Mesh.vertexCount; } mesh.indexFormat = numVertices > UInt16.MaxValue ? UnityEngine.Rendering.IndexFormat.UInt32 : UnityEngine.Rendering.IndexFormat.UInt16; mesh.CombineMeshes(instances); entityManager.AddSharedComponentData(entity, new RenderMesh { mesh = mesh, material = mat }); if (isDynamic) { entityManager.AddComponentData(entity, PhysicsMass.CreateDynamic(colliderComponent.MassProperties, mass)); float3 angularVelocityLocal = math.mul(math.inverse(colliderComponent.MassProperties.MassDistribution.Transform.rot), angularVelocity); entityManager.AddComponentData(entity, new PhysicsVelocity() { Linear = linearVelocity, Angular = angularVelocityLocal }); entityManager.AddComponentData(entity, new PhysicsDamping() { Linear = 0.01f, Angular = 0.05f }); } return(entity); }
Entity CreateBody(float3 position, quaternion orientation, BlobAssetReference <Collider> collider, float3 linearVelocity, float3 angularVelocity, float mass, bool isDynamic) { var entityManager = DefaultWorld.EntityManager; Entity entity = entityManager.CreateEntity(new ComponentType[] { }); entityManager.AddComponentData(entity, new LocalToWorld { }); entityManager.AddComponentData(entity, new Translation { Value = position }); entityManager.AddComponentData(entity, new Rotation { Value = orientation }); var colliderComponent = new PhysicsCollider { Value = collider }; entityManager.AddComponentData(entity, colliderComponent); var mesh = new Mesh(); var instances = new List <CombineInstance>(8); var numVertices = 0; foreach (var displayResult in (IEnumerable)k_DrawComponent_BuildDebugDisplayMesh.Invoke(null, new object[] { collider })) { var instance = new CombineInstance { mesh = k_DisplayResultsMesh.GetValue(displayResult) as Mesh, transform = (float4x4)k_DisplayResultsTransform.GetValue(displayResult) }; instances.Add(instance); numVertices += mesh.vertexCount; } mesh.indexFormat = numVertices > UInt16.MaxValue ? UnityEngine.Rendering.IndexFormat.UInt32 : UnityEngine.Rendering.IndexFormat.UInt16; mesh.CombineMeshes(instances.ToArray()); entityManager.AddSharedComponentData(entity, new RenderMesh { mesh = mesh, material = isDynamic ? dynamicMaterial : staticMaterial }); if (isDynamic) { entityManager.AddComponentData(entity, PhysicsMass.CreateDynamic(colliderComponent.MassProperties, mass)); float3 angularVelocityLocal = math.mul(math.inverse(colliderComponent.MassProperties.MassDistribution.Transform.rot), angularVelocity); entityManager.AddComponentData(entity, new PhysicsVelocity() { Linear = linearVelocity, Angular = angularVelocityLocal }); entityManager.AddComponentData(entity, new PhysicsDamping() { Linear = 0.01f, Angular = 0.05f }); } return(entity); }
// // Object creation // private Entity CreateBody(float3 position, quaternion orientation, BlobAssetReference <Collider> collider, float3 linearVelocity, float3 angularVelocity, float mass, bool isDynamic) { EntityManager entityManager = EntityManager; Entity entity = entityManager.CreateEntity(new ComponentType[] { }); entityManager.AddComponentData(entity, new LocalToWorld { }); entityManager.AddComponentData(entity, new Translation { Value = position }); entityManager.AddComponentData(entity, new Rotation { Value = orientation }); var colliderComponent = new PhysicsCollider { Value = collider }; entityManager.AddComponentData(entity, colliderComponent); Mesh mesh = new Mesh(); List <Unity.Physics.Authoring.DisplayBodyColliders.DrawComponent.DisplayResult> meshes; unsafe { meshes = Unity.Physics.Authoring.DisplayBodyColliders.DrawComponent.BuildDebugDisplayMesh(colliderComponent.ColliderPtr); } CombineInstance[] instances = new CombineInstance[meshes.Count]; for (int i = 0; i < meshes.Count; i++) { instances[i] = new CombineInstance { mesh = meshes[i].Mesh, transform = Matrix4x4.TRS(meshes[i].Position, meshes[i].Orientation, meshes[i].Scale) }; } mesh.CombineMeshes(instances); entityManager.AddSharedComponentData(entity, new RenderMesh { mesh = mesh, material = isDynamic ? dynamicMaterial : staticMaterial }); if (isDynamic) { entityManager.AddComponentData(entity, PhysicsMass.CreateDynamic(colliderComponent.MassProperties, mass)); float3 angularVelocityLocal = math.mul(math.inverse(colliderComponent.MassProperties.MassDistribution.Transform.rot), angularVelocity); entityManager.AddComponentData(entity, new PhysicsVelocity() { Linear = linearVelocity, Angular = angularVelocityLocal }); entityManager.AddComponentData(entity, new PhysicsDamping() { Linear = 0.01f, Angular = 0.05f }); } return(entity); }
void GenerateCombineSkin() { List <CombineInstance> combineInstances = new List <CombineInstance>(); List <Material> materials = new List <Material>(); List <Transform> bones = new List <Transform>(); for (int i = 0; i < parts.Count; i++) { var part = parts[i]; if (!part.combine) { continue; } GameObject go = GameObject.Instantiate(part.prefab); foreach (SkinnedMeshRenderer smr in go.GetComponentsInChildren <SkinnedMeshRenderer>()) { if (Application.isPlaying) { materials.AddRange(smr.materials); } else { materials.AddRange(smr.sharedMaterials); } for (int sub = 0; sub < smr.sharedMesh.subMeshCount; sub++) { CombineInstance ci = new CombineInstance(); ci.mesh = smr.sharedMesh; ci.subMeshIndex = sub; combineInstances.Add(ci); } foreach (Transform bone in smr.bones) { Transform t = FindSkeleton(bone.name); if (!t) { Debug.LogError("not found bones :" + bone.name + ", " + smr); } bones.Add(t); } } DestroyImmediate(go); } SkinnedMeshRenderer r; r = GetComponent <SkinnedMeshRenderer>(); if (!r) { r = gameObject.AddComponent <SkinnedMeshRenderer>(); } var newMesh = new Mesh(); newMesh.CombineMeshes(combineInstances.ToArray(), false, false); r.sharedMesh = newMesh; r.bones = bones.ToArray(); r.materials = materials.ToArray(); }
public static Mesh Copy(this Mesh source, bool recalculate = false, Matrix4x4?matrix = null, bool lightmaps = true, Mesh[] mergeMeshes = null) { Mesh copy = new Mesh(); copy.name = source.name; if (source.vertices != null) { copy.SetVertices(new List <Vector3>(source.vertices)); } if (source.uv != null) { copy.SetUVs(0, new List <Vector2>(source.uv)); } if (source.uv2 != null) { copy.SetUVs(1, new List <Vector2>(source.uv2)); } if (source.uv3 != null) { copy.SetUVs(2, new List <Vector2>(source.uv3)); } if (source.uv4 != null) { copy.SetUVs(3, new List <Vector2>(source.uv4)); } if (source.normals != null) { copy.SetNormals(new List <Vector3>(source.normals)); } if (source.tangents != null) { copy.SetTangents(new List <Vector4>(source.tangents)); } if (source.colors != null) { copy.SetColors(new List <Color>(source.colors)); } if (source.colors32 != null && source.colors32.Length > 0) { copy.colors32 = new List <Color32>(source.colors32).ToArray(); } if (source.bindposes != null && source.bindposes.Length > 0) { copy.bindposes = new List <Matrix4x4>(source.bindposes).ToArray(); } if (source.boneWeights != null && source.boneWeights.Length > 0) { copy.boneWeights = new List <BoneWeight>(source.boneWeights).ToArray(); } if (source.triangles != null && source.triangles.Length > 0) { copy.triangles = new List <int>(source.triangles).ToArray(); } copy.subMeshCount = source.subMeshCount; copy.bounds = source.bounds; if (recalculate) { copy.RecalculateBounds(); } if (matrix != null) { Mesh regen = new Mesh(); regen.name = copy.name; // Setup Source Combine CombineInstance combine = new CombineInstance(); combine.transform = matrix.Value; combine.mesh = copy; List <CombineInstance> combines = new List <CombineInstance>(); combines.Add(combine); // Merge Other Combines if (mergeMeshes != null && mergeMeshes.Length > 0) { foreach (var mergeMesh in mergeMeshes) { combines.Add(new CombineInstance() { transform = matrix.Value, mesh = mergeMesh }); } } regen.CombineMeshes(combines.ToArray(), true, true, lightmaps); return(regen); } else { return(copy); } }
// Build voxel object public override float Build(Storage voxels, Bounds bounds, Informer informer, object parameter) { // Check for given array if (voxels != null) { GameObject subContainer; int width = voxels.Width; int height = voxels.Height; int depth = voxels.Depth; int sides = voxels.FacesCount; int x, y, z; // Check for non-empty array if (width * height * depth * sides > 0) { if (mainContainer == null) { // Check if texture is required if (mainTextureTarget || emissiveTextureTarget) { // Create voxel texture, if required if (voxelTexture2D == null) { voxelTexture2D = new Texture2D.Process(); } // Build texture if (voxelTexture2D != null && voxelTexture2D.CurrentProgress < 1) { return(voxelTexture2D.Build(voxels, bounds) * 0.5f); } } else { voxelTexture2D = null; } // Get iterator iterator = voxels.GetIterator(); // Create empty game object mainContainer = new GameObject(targetName); if (mainContainer != null) { // Hide new container mainContainer.hideFlags |= HideFlags.HideAndDontSave; // Create empty list to store groups to groups = new Dictionary <Material, GameObject>(); // Create empty list to store mesh data interfaces to meshDataInterfaces = new List <IMeshData>(); currentMeshDataInterface = 0; // Copy position from source object mainContainer.transform.position = gameObject.transform.position; // Copy static flag mainContainer.isStatic = staticContainers; // Calculate total scaling for one block globalScaling = new Vector3(2.0f * bounds.extents.x / (float)width, 2.0f * bounds.extents.y / (float)height, 2.0f * bounds.extents.z / (float)depth); // Check for given mesh if (mesh != null) { // Calculate offset and scaling for one voxel mesh offset = -mesh.bounds.center; scaling.x = 0.5f / mesh.bounds.extents.x; scaling.y = 0.5f / mesh.bounds.extents.y; scaling.z = 0.5f / mesh.bounds.extents.z; offset.x *= scaling.x; offset.y *= scaling.y; offset.z *= scaling.z; scaling.x *= globalScaling.x; scaling.y *= globalScaling.y; scaling.z *= globalScaling.z; } else { // Unset translation und scaling offset = Vector3.zero; scaling = Vector3.one; } // Add offset for half voxel offset += new Vector3(0.5f * globalScaling.x, 0.5f * globalScaling.y, 0.5f * globalScaling.z); // Move to match position of the original object offset += bounds.center - gameObject.transform.position - bounds.extents; } } // Check for main container and voxel iterator if (mainContainer != null && iterator != null) { // Process voxels in steps for (int number = 0; number < 10; ++number) { // Retrieve material for current coordinate int iteratorIndex = iterator.Number; Color color; Material material = iterator.GetNextMaterial(out color, out x, out y, out z); // Check for valid voxel if (material != null) { //// Replace material, if texture template is set //if (textureMaterialTemplate != null && voxelTexture != null) //{ // material = textureMaterialTemplate; // material.SetTexture("_VoxelTex", voxelTexture.target); //} // Check for existing material groups if (groups != null) { // Check for new group if (!groups.TryGetValue(material, out subContainer) || (subContainer == null)) { // Create empty game object subContainer = new GameObject(material.name == null || material.name.Length == 0 ? (groups.Count + 1).ToString() : material.name); if (subContainer != null) { // Attach it to this main object subContainer.transform.parent = mainContainer.transform; // Unset local transformation subContainer.transform.localPosition = Vector3.zero; subContainer.transform.localScale = Vector3.one; subContainer.transform.localRotation = Quaternion.identity; // Copy static flag subContainer.isStatic = staticContainers; // Set layer number by transparency property if (material.HasProperty("_Color")) { if (material.color.a < 1) { subContainer.layer = 1; } else { subContainer.layer = 0; } } try { // Add group to list groups.Add(material, subContainer); } catch (System.Exception exception) { Debug.Log(exception.Message); } } } } else { // Unset container for first material subContainer = null; } // Calculate current voxel position Vector3 currentPosition = new Vector3((float)x * globalScaling.x + offset.x, (float)y * globalScaling.y + offset.y, (float)z * globalScaling.z + offset.z); // material container as parent for the current voxel GameObject parent = subContainer; // Create empty game object if (containerTemplate != null) { subContainer = Instantiate(containerTemplate); } else { subContainer = new GameObject(); } if (subContainer != null) { // Change name of the voxel container to current coordinate subContainer.name = x.ToString() + ", " + y.ToString() + ", " + z.ToString(); if (parent != null) { // Attach it to material container subContainer.transform.parent = parent.transform; } else { // Attach it to main object subContainer.transform.parent = mainContainer.transform; } // Set transformation to position and scale current cell subContainer.transform.localPosition = currentPosition; subContainer.transform.localScale = scaling * sizeFactor; subContainer.transform.localRotation = Quaternion.identity; // Copy static flag if (containerTemplate == null) { subContainer.isStatic = staticContainers; } // Set layer number by transparency property if (material.HasProperty("_Color")) { if (material.color.a < 1) { subContainer.layer = 1; } else { subContainer.layer = 0; } } // Check for valid mesh if (mesh != null) { // Add mesh filter MeshFilter meshFilter = subContainer.AddComponent <MeshFilter>(); if (meshFilter != null) { // Apply specified mesh as shared one for the sub container meshFilter.sharedMesh = mesh; // Check for vertex color utilization if (vertexColors) { // Create new array, if size does not match if (colors == null || colors.Length != mesh.vertexCount) { colors = new Color[mesh.vertexCount]; lastColor = colors[0]; } // Fill and apply new vertex colors array if (colors != null) { if (lastColor != color) { for (int index = 0; index < colors.Length; ++index) { colors[index] = color; } lastColor = color; } meshFilter.mesh.colors = colors; } } // Check for existing voxel map if (voxelTexture2D != null) { // Retrieve texture coordinate for current voxel Vector2 textureCoordinate = voxelTexture2D.GetTextureCoordinate(voxels, iteratorIndex); if (!float.IsNaN(textureCoordinate.x)) { //// Encode iterator index into texture coordinate //textureCoordinate.x += (float)iteratorIndex; // Create new array, if size does not match if (textureCoordinates == null || textureCoordinates.Length != mesh.vertexCount) { textureCoordinates = new Vector2[mesh.vertexCount]; } // Fill and apply new UV coordinates array if (textureCoordinates != null) { for (int index = 0; index < textureCoordinates.Length; ++index) { textureCoordinates[index] = textureCoordinate; } meshFilter.mesh.uv = textureCoordinates; } //Debug.Log(textureCoordinate); // Apply texture to material if (mainTextureTarget) { material.SetTexture("_MainTex", voxelTexture2D.Texture); } if (emissiveTextureTarget) { material.SetTexture("_EmissionMap", voxelTexture2D.Texture); } } } //// Check for active volume texture //if (voxelTexture != null && voxelTexture.target != null) //{ // // Instantiate mesh // Mesh newMesh = meshFilter.mesh; // // Compute texture coordinate center for current voxel // Vector3 textureCoordinate = new Vector3((x + 0.5f) / (float)voxelTexture.target.width, (y + 0.5f) / (float)voxelTexture.target.height, (z + 0.5f) / (float)voxelTexture.target.depth); // // Fill list of UVs for every vertex // List<Vector3> textureCoordinates = new List<Vector3>(newMesh.vertexCount); // for (int vertex = 0; vertex < mesh.vertexCount; ++vertex) // { // textureCoordinates.Add(textureCoordinate); // } // // Apply them to the mesh // newMesh.SetUVs(0, textureCoordinates); //} // Add mesh renderer MeshRenderer meshRenderer = subContainer.AddComponent <MeshRenderer>(); if (meshRenderer != null) { // Hide object meshRenderer.enabled = false; // Set material to renderer if (material != null) { meshRenderer.material = material; } } // Check for mesh data and add indices IMeshData[] meshDataComponents = subContainer.GetComponents <IMeshData>(); if (meshDataComponents != null) { foreach (IMeshData meshData in meshDataComponents) { meshData.SetVoxelIndices(new int[1] { iteratorIndex }); meshDataInterfaces.Add(meshData); } } } } } } else { iterator = null; break; } } // Return current progress when building has not been finished if (iterator != null) { return(((float)iterator.Number / (float)(voxels.Count + 1) * (mergeMeshes ? 0.5f : 1.0f)) * ((voxelTexture2D != null) ? 0.5f : 1.0f) + ((voxelTexture2D != null) ? 0.5f : 0.0f)); } } } } // Check for groups of materials if (groups != null && groups.Count > 0) { GameObject meshContainer; // Initialize group enumerator if (currentGroup == null) { currentGroup = groups.GetEnumerator(); if (currentGroup != null) { if (!currentGroup.MoveNext()) { currentGroup = null; } } } // Check for mesh baking if (mergeMeshes) { int count, index; int vertexCount, indexCount; int iteratorNumber; // Process collected material groups if (currentGroup != null) { // Check if semi-transparent meshes should be merged or if current group is opaque if (!opaqueOnly || (textureMaterialTemplate != null && voxelTexture != null) || (!currentGroup.Current.Key.HasProperty("_Color") || currentGroup.Current.Key.color.a <= 0 || currentGroup.Current.Key.color.a >= 1)) { if (materialContainer == null) { // Create empty game object for the material materialContainer = new GameObject(currentGroup.Current.Value.name); if (materialContainer != null) { // Attach it to this main object materialContainer.transform.parent = mainContainer.transform; // Unset relative transformation materialContainer.transform.localPosition = Vector3.zero; materialContainer.transform.localScale = Vector3.one; materialContainer.transform.localRotation = Quaternion.identity; // Copy static flag materialContainer.isStatic = staticContainers; // Get meshes of the current group and create array to store flags of processed meshes meshFilters = currentGroup.Current.Value.GetComponentsInChildren <MeshFilter>(); processedMeshes = new bool[meshFilters.Length]; // Initialize processing flags and count meshes to merge for (meshCount = 0, index = 0; index < meshFilters.Length; ++index) { if (meshFilters[index].gameObject != currentGroup.Current.Value) { processedMeshes[index] = false; ++meshCount; } else { processedMeshes[index] = true; } } if (meshCount == 0) { materialContainer = null; } currentMesh = 0; } } } else { materialContainer = null; } if (materialContainer != null) { // Count number of meshes and total vertices and indices count for current target for (iteratorNumber = 0, vertexCount = 0, indexCount = 0, count = 0, index = 0; index < meshFilters.Length; ++index) { // Check if mesh has not already been processed if (!processedMeshes[index]) { // Check for vertex, index and voxels count limit if (vertexCount + meshFilters[index].sharedMesh.vertexCount < 65536 && indexCount + meshFilters[index].sharedMesh.triangles.Length < 65536 && (objectVoxelLimit == 0 || count < objectVoxelLimit)) { // Increase number of vertices and indices vertexCount += meshFilters[index].sharedMesh.vertexCount; indexCount += meshFilters[index].sharedMesh.triangles.Length; // Increase voxels count ++count; // Get mesh data interface IMeshData meshData = meshFilters[index].gameObject.GetComponent <IMeshData>(); if (meshData != null) { // Get indices int[] indices = meshData.GetVoxelIndices(); // Increase number of voxel indices if (indices != null) { iteratorNumber += indices.Length; } } } else { break; } } } // Create array to store meshes to merge to CombineInstance[] subMeshes = new CombineInstance[count]; // Create array to store voxel indices for current mesh to int[] iteratorIndices = new int[iteratorNumber]; // Create empty list to store unused mesh data interface to List <IMeshData> unusedMeshDataInterfaces = new List <IMeshData>(); // Process meshes of the current group for (iteratorNumber = 0, vertexCount = 0, indexCount = 0, count = 0, index = 0; index < meshFilters.Length; ++index) { // Check if mesh is not already processed if (!processedMeshes[index]) { // Check for vertex and index limit if (vertexCount + meshFilters[index].sharedMesh.vertexCount < 65536 && indexCount + meshFilters[index].sharedMesh.triangles.Length < 65536 && (objectVoxelLimit == 0 || count < objectVoxelLimit)) { // Increase vertices and indices counts for current target mesh vertexCount += meshFilters[index].sharedMesh.vertexCount; indexCount += meshFilters[index].sharedMesh.triangles.Length; // Store mesh instance and calculate transformation relative to parent object subMeshes[count].mesh = meshFilters[index].sharedMesh; subMeshes[count].transform = currentGroup.Current.Value.transform.worldToLocalMatrix * meshFilters[index].transform.localToWorldMatrix; // Set flag to skip mesh at next iteration processedMeshes[index] = true; // Get mesh data interface IMeshData[] meshDataComponents = meshFilters[index].gameObject.GetComponents <IMeshData>(); if (meshDataComponents != null && meshDataComponents.Length >= 1) { // Get indices int[] indices = meshDataComponents[0].GetVoxelIndices(); // Check for valid voxel indices if (indices != null) { // Copy indices System.Array.Copy(indices, 0, iteratorIndices, iteratorNumber, indices.Length); iteratorNumber += indices.Length; } // Add interfaces for mesh data to list of unused ones unusedMeshDataInterfaces.AddRange(meshDataComponents); } // Increase sub meshes count for current merge target ++count; } } } // Create object for current mesh to merge if (containerTemplate != null) { meshContainer = Instantiate(containerTemplate); } else { meshContainer = new GameObject("Part"); } if (meshContainer != null) { // Attach it to this material object meshContainer.transform.parent = materialContainer.transform; // Unset relative transformation meshContainer.transform.localPosition = Vector3.zero; meshContainer.transform.localScale = Vector3.one; meshContainer.transform.localRotation = Quaternion.identity; // Copy static flag if (containerTemplate == null) { meshContainer.isStatic = staticContainers; } // Add mesh filter MeshFilter meshFilter = meshContainer.GetComponent <MeshFilter>(); if (meshFilter == null) { meshFilter = meshContainer.AddComponent <MeshFilter>(); } if (meshFilter != null) { // Create empty mesh object UnityEngine.Mesh mesh = new UnityEngine.Mesh(); if (mesh != null) { // Merge all collected meshes into new one mesh.CombineMeshes(subMeshes, true, true); // Set mesh to filter meshFilter.mesh = mesh; // Add mesh renderer MeshRenderer meshRenderer = meshContainer.GetComponent <MeshRenderer>(); if (meshRenderer == null) { meshRenderer = meshContainer.AddComponent <MeshRenderer>(); } // Set material if (meshRenderer != null) { meshRenderer.material = currentGroup.Current.Key; //meshRenderer.material = groups[group].material; meshRenderer.enabled = false; } // Get texture coordinates to manipulate them textureCoordinates = mesh.uv2; // Encode iterator indices into texture coordinates iteratorNumber = 0; vertexCount = 0; foreach (CombineInstance subMesh in subMeshes) { for (int vertexNumber = 0; vertexNumber < subMesh.mesh.vertexCount; ++vertexNumber, ++vertexCount) { textureCoordinates[vertexCount].x += (float)iteratorNumber; } ++iteratorNumber; } // Store manipulated UVs mesh.uv2 = textureCoordinates; // Remove mesh data interface of the merge meshes if (unusedMeshDataInterfaces != null) { foreach (IMeshData meshData in unusedMeshDataInterfaces) { meshDataInterfaces.Remove(meshData); } } // Check for mesh data and add indices IMeshData[] meshDataComponents = meshContainer.GetComponents <IMeshData>(); if (meshDataComponents != null) { foreach (IMeshData meshData in meshDataComponents) { meshData.SetVoxelIndices(iteratorIndices); meshDataInterfaces.Add(meshData); } } } } } // Decrease number of remaining objects currentMesh += count; if (currentMesh >= meshCount) { // Unset objects for current group materialContainer = null; // Remove original game object DestroyImmediate(currentGroup.Current.Value); //DestroyImmediate(groups[group].gameObject); } } } // Increase number of the current group, if it has been finished if (materialContainer == null) { if (currentGroup.MoveNext()) { ++groupNumber; } else { currentGroup = null; } } // Return current progress when building has not been finished if (currentGroup != null) { return((((float)groupNumber + ((float)currentMesh / (float)(meshCount + 1))) / (float)groups.Count * 0.5f + 0.5f) * ((voxelTexture2D != null) ? 0.5f : 1.0f) + ((voxelTexture2D != null) ? 0.5f : 0.0f)); } } // Clear groups list groups.Clear(); groups = null; } // Check for mesh data interfaces if (currentMeshDataInterface < meshDataInterfaces.Count) { // Transfer given voxels using the current interface float progress = meshDataInterfaces[currentMeshDataInterface].ProcessVoxels(voxels, bounds); if (progress >= 1) { ++currentMeshDataInterface; progress = 0; } if (currentMeshDataInterface < meshDataInterfaces.Count) { return(((float)currentMeshDataInterface + progress) / (float)meshDataInterfaces.Count); } } // Reset current processing data //currentDepth = 0; //currentHeight = 0; currentGroup = null; groupNumber = 0; meshFilters = null; processedMeshes = null; colors = null; voxelTexture2D = null; meshDataInterfaces = null; if (mainContainer != null) { // Show new main container and enable its renderers mainContainer.hideFlags &= ~HideFlags.HideAndDontSave; ShowRenderer(mainContainer); //Debug.Log("mainContainer = " + mainContainer.gameObject ); //GameObject prefab = PrefabUtility.CreatePrefab("Assets/Prefabs/test.prefab", mainContainer.gameObject, ReplacePrefabOptions.ReplaceNameBased); //StaticBatchingUtility.Combine(mainContainer); #if UNITY_EDITOR // Add object creation undo operation if (!Application.isPlaying) { UnityEditor.Undo.RegisterCreatedObjectUndo(mainContainer, "\"" + targetName + "\" Creation"); } #endif // Execute informer callback if (informer != null) { informer(new UnityEngine.Object[] { mainContainer }, parameter); } mainContainer = null; } return(1); }