Example #1
0
        public static GameObject CombineMeshes(string name,
                                          string materialName,
                                          CombinablesCollection objects,
                                          GameObject parent = null)
        {
            var gameObject = new GameObject(name);
            gameObject.SetActive(false);
            if (parent != null)
              gameObject.transform.parent = parent.transform;
            var meshFilter = gameObject.AddComponent<MeshFilter>();
            var meshRenderer = gameObject.AddComponent<MeshRenderer>();
            meshRenderer.sharedMaterial = Resources.Load("Materials/" + materialName,
                                                 typeof(Material)) as Material;

            MeshFilter[] meshFilters = new MeshFilter[objects.Count];
            for (var i = 0; i < objects.Count; ++i)
            {
              meshFilters[i] = objects[i].meshFilter;
              GameObject.Destroy(objects[i].gameObject);
            }

            CombineInstance[] combine = new CombineInstance[meshFilters.Length];
            for (var i = 0; i < meshFilters.Length; ++i)
            {
              combine[i].mesh = meshFilters[i].sharedMesh;
              combine[i].transform = meshFilters[i].transform.localToWorldMatrix;
            }

            meshFilter.mesh = new Mesh();
            meshFilter.mesh.CombineMeshes(combine);

            return gameObject;
        }
Example #2
0
	// Use this for initialization
	void Start () {
		GameObject face = Instantiate(Face) as GameObject;
		face.transform.parent = transform;
		FaceRenderer = face.GetComponentInChildren<SkinnedMeshRenderer>();

		GameObject body = Instantiate(Body) as GameObject;
		body.transform.parent = transform;
		BodyRenderer = body.GetComponentInChildren<SkinnedMeshRenderer>();
		
		CombinedRenderer = gameObject.GetComponent<SkinnedMeshRenderer>();
		// 重组Mesh后删除原始GO
		Mesh faceMesh = FaceRenderer.sharedMesh;
		Mesh bodyMesh = BodyRenderer.sharedMesh;

		CombineInstance[] combineInstances = new CombineInstance[2];
		combineInstances[0].mesh = faceMesh;
		combineInstances[0].transform = FaceRenderer.transform.localToWorldMatrix;
		combineInstances[1].mesh = bodyMesh;
		combineInstances[1].transform = BodyRenderer.transform.localToWorldMatrix;

		CombinedRenderer.sharedMesh = new Mesh();
		CombinedRenderer.sharedMesh.CombineMeshes(combineInstances);
		
		// 组合材质球引用
		Material[] sharedMats = new Material[2];
		sharedMats[0] = FaceRenderer.sharedMaterial;
		sharedMats[1] = BodyRenderer.sharedMaterial;
		CombinedRenderer.sharedMaterials = sharedMats;

		// Mesh和材质的关联是按照材质在数组中的顺序的,重组Mesh势必会产生一个新的材质球次序
	}
Example #3
0
    static void CombineSelected()
    {
        if (EditorUtility.DisplayDialog("Do you want to combine these objects?", "This can't be undone! Make sure you have a backup if you don't know what you're doing.", "Heck Yeah!", "No, I'm scared"))
        {
            int amountSelected = Selection.gameObjects.Length;

            MeshFilter[] meshFilters = new MeshFilter[amountSelected];
            CombineInstance[] combineInstances = new CombineInstance[amountSelected];

            for (var i = 0; i < amountSelected; i++)
            {
                meshFilters[i] = Selection.gameObjects[i].GetComponent<MeshFilter>();

                combineInstances[i].mesh = meshFilters[i].sharedMesh;
                combineInstances[i].transform = meshFilters[i].transform.localToWorldMatrix;
            }

            GameObject obj = new GameObject("CombinededMeshes", typeof(MeshFilter), typeof(MeshRenderer), typeof(MeshCollider));
            obj.GetComponent<MeshFilter>().mesh = new Mesh();
            obj.GetComponent<MeshFilter>().sharedMesh.CombineMeshes(combineInstances);
            obj.GetComponent<MeshRenderer>().sharedMaterial = new Material(meshFilters[0].gameObject.GetComponent<MeshRenderer>().sharedMaterial);
            obj.GetComponent<MeshCollider>().sharedMesh = obj.GetComponent<MeshFilter>().sharedMesh;

            foreach (MeshFilter m in meshFilters)
            {
                DestroyImmediate(m.gameObject);
            }
        }
    }
Example #4
0
    public void Combine()
    {
        List<MeshFilter> mfs = new List<MeshFilter>();
        FindMeshFilters(transform, mfs);

        MeshFilter[] meshFilters = mfs.ToArray();
        CombineInstance[] combine = new CombineInstance[meshFilters.Length];
        int i = 0;
        while (i < meshFilters.Length)
        {
            combine[i].mesh = meshFilters[i].sharedMesh;
            combine[i].transform = meshFilters[i].transform.localToWorldMatrix;
            meshFilters[i].gameObject.SetActive(false);
            i++;
        }

        MeshFilter thisMf = this.GetComponent<MeshFilter>();
        if (thisMf == null)
        {
            thisMf = gameObject.AddComponent<MeshFilter>();
        }

        MeshRenderer thisMr = this.GetComponent<MeshRenderer>();
        if (thisMr == null)
        {
            thisMr = gameObject.AddComponent<MeshRenderer>();
        }

        thisMr.material = this.UseMaterial;

        thisMf.sharedMesh = new Mesh();
        thisMf.sharedMesh.CombineMeshes(combine);

        transform.gameObject.SetActive(true);
    }
    /// <summary>
    /// Static method for batching a list of meshes. Note that the selector information goes to tangent vertex
    /// information, so any data in the mesh tangents will be lost.
    /// </summary>
    /// <param name="meshList">The list of meshes to batch</param>
    public static Mesh BatchList(List<Mesh> meshList)
    {
        // We will use this to combine the meshes
        CombineInstance[] combineInstances = new CombineInstance[meshList.Count];
        List<Vector4> tangentSelectors = new List<Vector4>();

        for (int i = 0; i < combineInstances.Length; i++)
        {
            Mesh mesh = meshList[i];

            for (int j = 0; j < mesh.vertexCount; j++)
            {
                tangentSelectors.Add(new Vector4(i, 0, 0, 0));
            }

            combineInstances[i].mesh = mesh;

            // We don't want to transform the meshes, it will be done in the shader.
            combineInstances[i].transform = Matrix4x4.identity;
        }

        // Make our new mesh out of the combined instance
        Mesh resultMesh = new Mesh();
        resultMesh.CombineMeshes(combineInstances);
        // And set the selectors of the meshes
        resultMesh.tangents = tangentSelectors.ToArray();

        return resultMesh;
    }
Example #6
0
    /*
     * The method that merges the meshes.
     * This code is based off of code from unity's script reference for
     * Mesh.CombineMeshes.
     */
    void MergeBorder()
    {
        //first, create an array of all meshes
        MeshFilter[] meshFilters = transform.GetComponentsInChildren<MeshFilter>();
        CombineInstance[] combine = new CombineInstance[meshFilters.Length];
        int i = 0;
        //use Unity's CombineInstance so Mesh.CombineMeshes may be called appropriately
        while (i < meshFilters.Length) {
            combine[i].mesh = meshFilters[i].sharedMesh;
            combine[i].transform = (meshFilters[i].transform.localToWorldMatrix);
            meshFilters[i].gameObject.SetActive(false); //turn off old meshes
            i++;
        }
        //create new, combined mesh and attach to a child since the parent is not a transform
        Transform mainWall = transform.GetChild (0);
        Mesh OneTrueMesh = new Mesh ();
        mainWall.GetComponent<MeshFilter>().mesh = OneTrueMesh;
        mainWall.GetComponent<MeshFilter>().mesh.CombineMeshes(combine);
        mainWall.gameObject.SetActive(true);

        //make sure the new mesh is the correct size and position
        mainWall.position = new Vector3 (0, 0, 0);
        mainWall.localScale = new Vector3 (1, 1, 1);
        mainWall.gameObject.AddComponent (typeof(MeshCollider));
        this.mainWall = mainWall; //store the child so VictoryScript may reference it
    }
    // 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;
    }
Example #8
0
	// Use this for initialization
	void Start()
	{
		MeshFilter meshFilter = GetComponent<MeshFilter>();
		meshFilter.mesh.Clear();
		
		MeshFilter[] meshFilters = GetComponentsInChildren<MeshFilter>( true);
		MeshRenderer meshRenderer = transform.GetComponent<MeshRenderer>();
		meshRenderer.materials = meshFilters[0].renderer.sharedMaterials;
		
		CombineInstance[] combine = new CombineInstance[ meshFilters.Length - 1];
		
		int i = 0;
		int ci = 0;
		while( i < meshFilters.Length)
		{
			if( meshFilter != meshFilters[i])
			{
				combine[ci].mesh = meshFilters[i].sharedMesh;
				combine[ci].transform = meshFilters[i].transform.localToWorldMatrix;
				++ci;
			}
			
			meshFilters[i].gameObject.active = false;
			i++;
		}
		
		meshFilter.mesh.CombineMeshes( combine);
		transform.gameObject.active = true;
		
		MeshCollider meshCollider = transform.gameObject.GetComponent<MeshCollider>();
		if( null != meshCollider)
			meshCollider.sharedMesh = transform.gameObject.GetComponent<MeshFilter>().mesh;
	}
    void MakeCubeFromQuads()
    {
        mesh.Clear();

        Vector3[] verts = new Vector3[8];
        verts[0] = new Vector3(-.5f, -.5f, -.5f);
        verts[1] = new Vector3(-.5f, .5f, -.5f);
        verts[2] = new Vector3(.5f, .5f, -.5f);
        verts[3] = new Vector3(.5f, -.5f, -.5f);
        verts[4] = new Vector3(-.5f, -.5f, .5f);
        verts[5] = new Vector3(-.5f, .5f, .5f);
        verts[6] = new Vector3(.5f, .5f, .5f);
        verts[7] = new Vector3(.5f, -.5f, .5f);

        CombineInstance[] combine = new CombineInstance[6];
        combine[0] = BuildAndReturnQuad(verts[0], verts[1], verts[2], verts[3]);
        combine[1] = BuildAndReturnQuad(verts[3], verts[2], verts[6], verts[7]);
        combine[2] = BuildAndReturnQuad(verts[7], verts[6], verts[5], verts[4]);
        combine[3] = BuildAndReturnQuad(verts[4], verts[5], verts[1], verts[0]);
        combine[4] = BuildAndReturnQuad(verts[1], verts[5], verts[6], verts[2]);
        combine[5] = BuildAndReturnQuad(verts[4], verts[0], verts[3], verts[7]);

        mesh.CombineMeshes(combine, true, false);
        mesh.RecalculateNormals();
        mesh.RecalculateBounds();
    }
    CombineInstance BuildAndReturnQuad(Vector3 p1, Vector3 p2, Vector3 p3, Vector3 p4)
    {
        Mesh tempMesh = new Mesh();
        CombineInstance combine = new CombineInstance();

        Vector3[] verts = new Vector3[4];
        verts[0] = p1;
        verts[1] = p2;
        verts[2] = p3;
        verts[3] = p4;

        int[] tris = new int[6];
        tris[0] = 0;
        tris[1] = 1;
        tris[2] = 2;
        tris[3] = 0;
        tris[4] = 2;
        tris[5] = 3;

        Vector2[] uvs = new Vector2[4];
        uvs[0] = new Vector2(0, 0);
        uvs[1] = new Vector2(0, 1);
        uvs[2] = new Vector2(1, 1);
        uvs[3] = new Vector2(1, 0);

        tempMesh.vertices = verts;
        tempMesh.triangles = tris;
        tempMesh.uv = uvs;

        combine.mesh = tempMesh;
        combine.transform = filter.transform.localToWorldMatrix;

        return combine;
    }
    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();
    }
Example #12
0
    // Use this for initialization
    void Combine()
    {
        ////---------------- 先获取材质 -------------------------
        ////获取自身和所有子物体中所有MeshRenderer组件
        MeshRenderer[] meshRenderers = GetComponentsInChildren<MeshRenderer>();
        //新建材质球数组
        Material[] mats = new Material[meshRenderers.Length];
        for (int i = 0; i < meshRenderers.Length; i++)
        {
            //生成材质球数组
            mats[i] = meshRenderers[i].sharedMaterial;
        }
        //---------------- 合并 Mesh -------------------------
        //获取自身和所有子物体中所有MeshFilter组件
        MeshFilter[] meshFilters = GetComponentsInChildren<MeshFilter>();
        CombineInstance[] combine = new CombineInstance[meshFilters.Length];
        for (int i = 0; i < meshFilters.Length; i++)
        {
            combine[i].mesh = meshFilters[i].sharedMesh;
            //矩阵(Matrix)自身空间坐标的点转换成世界空间坐标的点
            combine[i].transform = meshFilters[i].transform.localToWorldMatrix;
            meshFilters[i].gameObject.SetActive(false);
        }
        //为新的整体新建一个mesh
        GetComponent<MeshFilter>().mesh = new Mesh();
        //合并Mesh. 第二个false参数, 表示并不合并为一个网格, 而是一个子网格列表
        //Debug.Log(combine.ToString() + combine.Length);
        GetComponent<MeshFilter>().mesh.CombineMeshes(combine);
        GetComponent<MeshCollider>().sharedMesh = GetComponent<MeshFilter>().mesh;
        gameObject.SetActive(true);

        //为合并后的新Mesh指定材质 ------------------------------
        transform.GetComponent<MeshRenderer>().sharedMaterials = mats;
    }
	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 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;
        }
Example #15
0
        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;
        }
Example #16
0
        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;
        }
Example #17
0
        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;
        }
Example #18
0
        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!!");
            }
        }
	// 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;		
	}
 static public int constructor(IntPtr l)
 {
     try {
                     #if DEBUG
         var    method     = System.Reflection.MethodBase.GetCurrentMethod();
         string methodName = GetMethodName(method);
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.BeginSample(methodName);
                     #else
         Profiler.BeginSample(methodName);
                     #endif
                     #endif
         UnityEngine.CombineInstance o;
         o = new UnityEngine.CombineInstance();
         pushValue(l, true);
         pushValue(l, o);
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
             #if DEBUG
     finally {
                     #if UNITY_5_5_OR_NEWER
         UnityEngine.Profiling.Profiler.EndSample();
                     #else
         Profiler.EndSample();
                     #endif
     }
             #endif
 }
Example #21
0
    // Use this for initialization
    void Start()
    {
        // http://forum.unity3d.com/threads/combinemeshes-example-flawed.33209/
        foreach (Transform child in transform)
            child.position += transform.position;

        transform.position = Vector3.zero;
        transform.rotation = Quaternion.identity;

        // Find all children meshes
        MeshFilter[] meshFilters = GetComponentsInChildren<MeshFilter>();
        CombineInstance[] combine = new CombineInstance[meshFilters.Length];

        int i = 0;
        while(i < meshFilters.Length)
        {
            combine[i].mesh = meshFilters[i].sharedMesh;
            combine[i].transform = meshFilters[i].transform.localToWorldMatrix;
            meshFilters[i].gameObject.active = false;
            i++;
        }

        transform.GetComponent<MeshFilter>().mesh = new Mesh();
        transform.GetComponent<MeshFilter>().mesh.CombineMeshes(combine, commonMaterial);
        transform.gameObject.active = true;

        // Set bound of mesh collider attached to game object
        MeshCollider collider = GetComponent<MeshCollider>();
        if (collider)
        {
            // set mesh for collider
            collider.sharedMesh = transform.GetComponent<MeshFilter>().mesh;
        }
    }
Example #22
0
	public void AttachNewCollider(string _ColliderPrefab, Vector3 _RelativePos, Quaternion _RelativeRot)
	{
		GameObject newCollider = (GameObject)GameObject.Instantiate(Resources.Load(_ColliderPrefab, typeof(GameObject)));
		if(newCollider == null)
		{
			Debug.LogError("Collider prefab didn't exist! " + _ColliderPrefab);
		}
		
		newCollider.transform.parent = m_CompoundCollider.transform;
		newCollider.transform.localPosition = _RelativePos;
		newCollider.transform.localRotation = _RelativeRot;
		
		// Move the collider to identity transform
		Vector3 oldPos = m_CompoundCollider.transform.position;
		Quaternion oldRot = m_CompoundCollider.transform.rotation;
		m_CompoundCollider.transform.position = Vector3.zero;
		m_CompoundCollider.transform.rotation = Quaternion.identity;
		
		// Create a cube
		GameObject newSphere = GameObject.CreatePrimitive(PrimitiveType.Cylinder);
		MeshFilter mf = newSphere.GetComponent<MeshFilter>();
		
		// Get the mesh filters of the colliders
		MeshFilter[] meshFilters = m_CompoundCollider.GetComponentsInChildren<MeshFilter>();
		List<CombineInstance> combines = new List<CombineInstance>();
        for(int i = 0; i < meshFilters.Length; ++i) 
		{
			if(meshFilters[i].collider == null)
				continue;

			Vector3 scale = meshFilters[i].collider.bounds.size + new Vector3(1.0f, 0.0f, 1.0f);
			scale.x = scale.x / Mathf.Sqrt(2.0f) * 2.0f;
			scale.z = scale.z / Mathf.Sqrt(2.0f) * 2.0f;
			scale.y = scale.y;
			
			newSphere.transform.localScale = scale;
			newSphere.transform.localPosition = meshFilters[i].collider.bounds.center;

			CombineInstance combine = new CombineInstance();
			combine.mesh = mf.sharedMesh;
			combine.transform = mf.transform.localToWorldMatrix;
			combines.Add(combine);
        }
		
		// Destroy the cube
		Destroy(newSphere);
		
		// Create a new mesh for the shield to use
        Mesh mesh = new Mesh();
		mesh.name = "Shield";
		mesh.CombineMeshes(combines.ToArray(), true, true);
		mesh.Optimize();
	
		// Update the shield bounds
		gameObject.GetComponent<CGalaxyShipShield>().UpdateShieldBounds(mesh);
		
		// Move back to old transform
		m_CompoundCollider.transform.position = oldPos;
		m_CompoundCollider.transform.rotation = oldRot;
	}
        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();
            }
        }
Example #24
0
    void Start()
    {
        Quaternion startRotation=transform.localRotation;

        foreach(Transform child in transform)
            child.position += transform.position;
        transform.position = Vector3.zero;
        transform.rotation = Quaternion.identity;

        MeshFilter[] meshFilters = (MeshFilter[]) GetComponentsInChildren<MeshFilter>();
        CombineInstance[] combine = new CombineInstance[meshFilters.Length-1];
        int index = 0;
        for (int i = 0; i < meshFilters.Length; i++)
        {
            if (meshFilters[i].sharedMesh == null) continue;
            combine[index].mesh = meshFilters[i].sharedMesh;
            combine[index++].transform = meshFilters[i].transform.localToWorldMatrix;
            meshFilters[i].renderer.enabled = false;
        }
        GetComponent<MeshFilter>().mesh = new Mesh();
        GetComponent<MeshFilter>().mesh.CombineMeshes (combine);
        renderer.material = meshFilters[1].renderer.sharedMaterial;

        transform.localRotation=startRotation;
    }
Example #25
0
	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");
		}
	}
Example #26
0
    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;
    }
Example #27
0
        protected override void GenerateMesh()
        {
            foreach(Transform child in transform)
                DestroyImmediate(child.gameObject);

            var rand = new MersenneTwister(randomSeed);

            var totalHeight = 0.0f;
            var scaleDown = 1.0f;
            var combineMeshInstances = new List<CombineInstance>();
            for(int i = 0; i < layerCount; ++i)
            {
                var baseRadius = Mathf.Lerp(baseRadiusMin, baseRadiusMax, rand.NextSinglePositive()) * scaleDown;
                var baseBezier = GenerateBaseBezier(baseRadius * scaleDown, rand);

                var previousTotalHeight = totalHeight;
                totalHeight += Mathf.Lerp(layerHeightMin, layerHeightMax, rand.NextSinglePositive()) * scaleDown;
                var heightBezier = Bezier.ConstructSmoothSpline(
                    new Vector3[]{
                        Vector3.up * previousTotalHeight,
                        Vector3.up * totalHeight
                    }
                );

                var heightSegs = (uint)heightSegments;
                var pathSegs = (uint)(radiusSegments * scaleDown);

                if( heightSegs > 0 && pathSegs > 2 )
                {
                    var combineMeshInstance = new CombineInstance();
                    combineMeshInstance.mesh = Loft.GenerateMesh(
                        heightBezier,
                        baseBezier,
                        heightSegs,
                        pathSegs
                    );
                    combineMeshInstances.Add(combineMeshInstance);

                    var topCap = new CombineInstance();
                    topCap.mesh = baseBezier.Triangulate(pathSegs, Vector3.up * totalHeight);
                    combineMeshInstances.Add(topCap);
                }

                scaleDown *= Mathf.Lerp(scaleDownMin, scaleDownMax, rand.NextSinglePositive());
            }

            var meshFilter = GetComponent<MeshFilter>();
            if( meshFilter.sharedMesh )
                DestroyImmediate(meshFilter.sharedMesh);

            meshFilter.sharedMesh = new Mesh();
            meshFilter.sharedMesh.CombineMeshes(combineMeshInstances.ToArray(), true, false);

            foreach(var combineInstance in combineMeshInstances)
                DestroyImmediate(combineInstance.mesh);
        }
Example #28
0
        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;
        }
    static public int set_subMeshIndex(IntPtr l)
    {
        UnityEngine.CombineInstance o = (UnityEngine.CombineInstance)checkSelf(l);
        int v;

        checkType(l, 2, out v);
        o.subMeshIndex = v;
        setBack(l, o);
        return(0);
    }
	void construct(){
		CombineInstance[] combine = new CombineInstance[filters.Count];
        for (int i  = 0; i < filters.Count; i++){
		    combine[i].mesh = filters[i].sharedMesh;
            combine[i].transform = filters[i].transform.localToWorldMatrix;
			filters[i].gameObject.SetActive(filters[i].gameObject == gameObject);
		}
        filter.mesh = new Mesh();
        filter.mesh.CombineMeshes(combine, merge);
	}
 private void CombineMeshesIntoTargetObject(MeshFilter[] meshFilters, GameObject target)
 {
     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;
     }
     target.transform.GetComponent<MeshFilter>().mesh.CombineMeshes(combine);
 }
Example #32
0
    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);
    }
 static public int constructor(IntPtr l)
 {
     try {
         UnityEngine.CombineInstance o;
         o = new UnityEngine.CombineInstance();
         pushValue(l, o);
         return(1);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
 static public int constructor(IntPtr l)
 {
     try {
         UnityEngine.CombineInstance o;
         o = new UnityEngine.CombineInstance();
         pushValue(l, o);
         return(1);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
Example #35
0
 static void CombineInstance_transform(JSVCall vc)
 {
     if (vc.bGet)
     {
         UnityEngine.CombineInstance _this = (UnityEngine.CombineInstance)vc.csObj;
         var result = _this.transform;
         JSMgr.datax.setObject((int)JSApi.SetType.Rval, result);
     }
     else
     {
         UnityEngine.Matrix4x4       arg0  = (UnityEngine.Matrix4x4)JSMgr.datax.getObject((int)JSApi.GetType.Arg);
         UnityEngine.CombineInstance _this = (UnityEngine.CombineInstance)vc.csObj;
         _this.transform = arg0;
         JSMgr.changeJSObj(vc.jsObjID, _this);
     }
 }
Example #36
0
 static void CombineInstance_subMeshIndex(JSVCall vc)
 {
     if (vc.bGet)
     {
         UnityEngine.CombineInstance _this = (UnityEngine.CombineInstance)vc.csObj;
         var result = _this.subMeshIndex;
         JSApi.setInt32((int)JSApi.SetType.Rval, (System.Int32)(result));
     }
     else
     {
         System.Int32 arg0 = (System.Int32)JSApi.getInt32((int)JSApi.GetType.Arg);
         UnityEngine.CombineInstance _this = (UnityEngine.CombineInstance)vc.csObj;
         _this.subMeshIndex = arg0;
         JSMgr.changeJSObj(vc.jsObjID, _this);
     }
 }
Example #37
0
    static bool Mesh_CombineMeshes__CombineInstance_Array(JSVCall vc, int argc)
    {
        int len = argc;

        if (len == 1)
        {
            UnityEngine.CombineInstance[] arg0 = JSDataExchangeMgr.GetJSArg <UnityEngine.CombineInstance[]>(() =>
            {
                int jsObjID = JSApi.getObject((int)JSApi.GetType.Arg);
                int length  = JSApi.getArrayLength(jsObjID);
                var ret     = new UnityEngine.CombineInstance[length];
                for (var i = 0; i < length; i++)
                {
                    JSApi.getElement(jsObjID, i);
                    ret[i] = (UnityEngine.CombineInstance)JSMgr.datax.getObject((int)JSApi.GetType.SaveAndRemove);
                }
                return(ret);
            });
            ((UnityEngine.Mesh)vc.csObj).CombineMeshes(arg0);
        }

        return(true);
    }
 static public int get_transform(IntPtr l)
 {
     UnityEngine.CombineInstance o = (UnityEngine.CombineInstance)checkSelf(l);
     pushValue(l, o.transform);
     return(1);
 }
 static public int get_subMeshIndex(IntPtr l)
 {
     UnityEngine.CombineInstance o = (UnityEngine.CombineInstance)checkSelf(l);
     pushValue(l, o.subMeshIndex);
     return(1);
 }
 static public int get_mesh(IntPtr l)
 {
     UnityEngine.CombineInstance o = (UnityEngine.CombineInstance)checkSelf(l);
     pushValue(l, o.mesh);
     return(1);
 }
        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);
            }
        }
        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();
        }