Пример #1
0
 public void Apply(bool isCalculatingBounds = false)
 {
     mesh.Clear();
     mesh.SetVertices(vertices);
     mesh.SetTriangles(triangles, 0);
     mesh.SetUVs(0, uv);
     mesh.RecalculateNormals();
     if (isCalculatingBounds)
     {
         mesh.RecalculateBounds();
     }
 }
Пример #2
0
        public void MakeMesh(UnityEngine.Mesh mesh, Vector3[] verts,
                             int[] triangles, Vector2[] uvs = null, Color[] colors = null)
        {
            if (mesh == null)
            {
                return;
            }

            if (verts.Length < 3)
            {
                return;
            }

            if (triangles.Length < 1)
            {
                return;
            }

            mesh.Clear();

            mesh.vertices  = verts;
            mesh.triangles = triangles;
            mesh.uv        = uvs;
            mesh.colors    = colors;

            mesh.RecalculateBounds();       // 重算bounds,bounds的size、extent、center常用
            mesh.RecalculateNormals();      // 重算法线
            mesh.RecalculateTangents();     // 重算切线
        }
Пример #3
0
    /// <summary>
    /// Clears out the mesh, fills in the data, and recalculates normals and bounds.
    /// </summary>
    /// <param name="aMesh">An already existing mesh to fill out.</param>
    public void  Build                 (ref Mesh aMesh, bool aCalculateTangents)
    {
    	// round off a few decimal points to try and get better pixel-perfect results
    	/*for(int i=0;i<mVerts.Count;i+=1) mVerts[i] = new Vector3(
    		(float)System.Math.Round(mVerts[i].x, 3),
    		(float)System.Math.Round(mVerts[i].y, 3),
    		(float)System.Math.Round(mVerts[i].z, 3));*/

        
    	
        aMesh.Clear();
        aMesh.vertices  = mVerts  .ToArray();
        aMesh.uv        = mUVs    .ToArray();
        aMesh.triangles = mIndices.ToArray();
        aMesh.colors    = mColors .ToArray();
        aMesh.normals   = mNorms  .ToArray();
        aMesh.tangents  = mTans   .ToArray();
        if (mUV2s != null) {
			#if UNITY_5
			aMesh.uv2 = mUV2s.ToArray();
			#else
            aMesh.uv1 = mUV2s.ToArray();
			#endif
        }
        if (mNorms.Count == 0) aMesh.RecalculateNormals();
        if (aCalculateTangents && mTans.Count == 0) {
            RecalculateTangents(aMesh);
        } else {
            aMesh.tangents = null;
        }
        aMesh.RecalculateBounds ();
    }
Пример #4
0
    static void CreateQuad(Mesh mesh, float W, float H)
    {
        Vector3[] verts = new Vector3[4];
        Vector2[] uvs = new Vector2[4];

        verts[0] = new Vector3(-W/2, H/2, 0);
        verts[1] = new Vector3(W/2, H/2, 0);
        verts[2] = new Vector3(W/2, -H/2, 0);
        verts[3] = new Vector3(-W/2, -H/2, 0);

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

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

        mesh.Clear();
        mesh.vertices = verts;
        mesh.uv = uvs;
        mesh.triangles = triangles;
    }
Пример #5
0
    public void Begin()
    {
        gameObject.transform.position = Vector3.zero;
        Min = Vector3.one * 1000;
        Max = Vector3.one * -1000;
        if (gameObject.GetComponent<MeshFilter>() == null)
            gameObject.AddComponent<MeshFilter>();
        if (gameObject.GetComponent<MeshRenderer>() == null)
            gameObject.AddComponent<MeshRenderer>();

            mesh = GetComponent<MeshFilter>().mesh;
        mesh.Clear();

        var rnd = GetComponent<MeshRenderer>();
        rnd.material = material;
        rnd.receiveShadows = true;
        rnd.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On;

        //back = GameObject.Find("BACK");
        //if (back.GetComponent<MeshFilter>() == null)
        //    back.AddComponent<MeshFilter>();
        //if (back.GetComponent<MeshRenderer>() == null)
        //    back.AddComponent<MeshRenderer>();

        //mesh_b = back.GetComponent<MeshFilter>().mesh;
        //mesh_b.Clear();

        //var rnd_b = back.GetComponent<MeshRenderer>();
        //rnd_b.material = material;
        //rnd_b.receiveShadows = true;
        //rnd_b.shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.On;
        GO = true;
    }
Пример #6
0
    float gr = (1.0f + Mathf.Sqrt(5.0f)) / 2.0f; //golen ratio (a+b is to a as a is to b)

    #endregion Fields

    #region Methods

    void Start()
    {
        Nose = GameObject.Find("Nose");
        Nose.AddComponent<MeshFilter>();
        Nose.AddComponent<MeshRenderer>();
        noseMesh = GetComponent<MeshFilter>().mesh;//attach mesh to nose
        noseMesh.Clear();

        noseMesh.vertices = new Vector3[] {//construct pyramid for nose
            new Vector3( gr,   		     1,		  	0),
            new Vector3( gr-1,    -gr*0.6f, -gr*0.75f),
            new Vector3( gr-1, 	  -gr*0.6f,  gr*0.75f),
            new Vector3( gr*1.5f, -gr*0.6f,   		0)};

        List<int> noseTrianglesIndices = new List<int>() {//arrange triangles
            0,  1,  2,
            0,  3,  1,
            0,  2,  3,
            1,  3,  2};
        noseMesh.triangles = noseTrianglesIndices.ToArray();

        //Set Colour
        Material material = new Material(Shader.Find("Standard"));
        Color fleshtone = new Color(10, 205, 180);
        material.SetColor("fleshtone", fleshtone);

        Nose.GetComponent<Renderer>().material = material;

        noseMesh.RecalculateBounds();
        noseMesh.RecalculateNormals();
        noseMesh.Optimize();
    }
    public override Mesh ComputeMesh()
    {
        Vector3 p0 = new Vector3(0, 0, 0);
        Vector3 p1 = new Vector3(0, 0.66f, 0);
        Vector3 p2 = new Vector3(0.33f, 1, 0);
        Vector3 p3 = new Vector3(1, 1, 0);
        Vector3 p4 = new Vector3(0.4f, 0.6f, 0);

        Vector3 anchor = new Vector3(0.25f, 0.75f, 0);

        var vertices = new Vector3[] { p0, p1, p2, p3, p4 };
        for(int i = 0; i < vertices.Length; i++)
        {
            vertices[i].Set(vertices[i].x - anchor.x, vertices[i].y - anchor.y, vertices[i].z - anchor.z);
        }

        var mesh = new Mesh();

        mesh.Clear();
        mesh.vertices = vertices;

        mesh.triangles = new int[]{
            0,1,4,
            1,2,4,
            2,3,4
        };

        mesh.colors = new Color[] { new Color(0, 0, 0, 0), new Color(255, 255, 255, 0), new Color(0, 0, 0, 0), new Color(0, 0, 0, 0), new Color(0, 0, 0, 0) };

        mesh.RecalculateNormals();
        mesh.RecalculateBounds();
        mesh.Optimize();

        return mesh;
    }
Пример #8
0
 private void UpdateMesh()
 {
     unityMesh.Clear();
     unityMesh.vertices  = vectors;
     unityMesh.triangles = triangles;
     unityMesh.RecalculateNormals();
 }
Пример #9
0
    public bool AddTypeElement(System.Xml.Linq.XElement elemtype)
    {
        XAttribute fileAtt = elemtype.Attribute("file");
        if (fileAtt == null)
        {
            //Add error message here
            return false;
        }
        string filePath = Path.Combine(Path.GetDirectoryName(new Uri(elemtype.BaseUri).LocalPath), fileAtt.Value);
        filePath = Path.GetFullPath(filePath);

        //	Load the OBJ in
        var lStream = new FileStream(filePath, FileMode.Open);
        var lOBJData = OBJLoader.LoadOBJ(lStream);
        lStream.Close();
        meshData = new MeshData[(int)MeshLayer.Count];
        Mesh tempMesh = new Mesh();
        for (int i = 0; i < meshData.Length; i++)
        {
            tempMesh.LoadOBJ(lOBJData, ((MeshLayer)i).ToString());
            meshData[i] = new MeshData(tempMesh);
            tempMesh.Clear();
        }
        lStream = null;
        lOBJData = null;
        return true;
    }
Пример #10
0
    private void initialize()
    {
        if (_sharedMesh == null) {
            _sharedMesh	= new Mesh ();
        }
        p_Mesh		= _sharedMesh;
        p_Vertices	= new Vector3[4];
        p_Triangles	= new int[6];
        p_UVs		= new Vector2[4];
        p_Renderer	= GetComponent<MeshRenderer> ();

        if (p_Renderer.sharedMaterial == null) {
            p_Renderer.sharedMaterial	= Resources.GetBuiltinResource <Material> ("Sprites-Default.mat");
        }

        p_Mesh.Clear ();
        p_Filter	= GetComponent<MeshFilter>();

        p_Triangles[0]	= 0;
        p_Triangles[1]	= 1;
        p_Triangles[2]	= 2;
        p_Triangles[3]	= 2;
        p_Triangles[4]	= 3;
        p_Triangles[5]	= 0;
    }
    /// <summary>
    /// Use this for initialization.
    /// </summary>
    public void Start() 
    {
        m_tangoApplication = FindObjectOfType<TangoApplication>();
        m_tangoApplication.Register(this);

        m_uwTss.SetColumn (0, new Vector4 (1.0f, 0.0f, 0.0f, 0.0f));
        m_uwTss.SetColumn (1, new Vector4 (0.0f, 0.0f, 1.0f, 0.0f));
        m_uwTss.SetColumn (2, new Vector4 (0.0f, 1.0f, 0.0f, 0.0f));
        m_uwTss.SetColumn (3, new Vector4 (0.0f, 0.0f, 0.0f, 1.0f));

        m_cTuc.SetColumn (0, new Vector4 (1.0f, 0.0f, 0.0f, 0.0f));
        m_cTuc.SetColumn (1, new Vector4 (0.0f, -1.0f, 0.0f, 0.0f));
        m_cTuc.SetColumn (2, new Vector4 (0.0f, 0.0f, 1.0f, 0.0f));
        m_cTuc.SetColumn (3, new Vector4 (0.0f, 0.0f, 0.0f, 1.0f));

        m_triangles = new int[VERT_COUNT];
        // Assign triangles, note: this is just for visualizing point in the mesh data.
        for (int i = 0; i < VERT_COUNT; i++)
        {
            m_triangles[i] = i;
        }

        m_mesh = GetComponent<MeshFilter>().mesh;
        m_mesh.Clear();
        m_mesh.triangles = m_triangles;
        m_mesh.RecalculateBounds();
        m_mesh.RecalculateNormals();
       
    }
Пример #12
0
            public static void Create(GameObject go, IEnumerable <Vector3> vertices)
            {
                if (vertices == null || vertices.Count <Vector3>() < 3)
                {
                    return;
                }
                MeshFilter meshFilter = (MeshFilter)go.GetComponent <MeshFilter>();

                if (Object.op_Equality((Object)meshFilter, (Object)null))
                {
                    meshFilter = (MeshFilter)go.AddComponent <MeshFilter>();
                }
                UnityEngine.Mesh mesh = meshFilter.get_mesh();
                mesh.Clear();
                mesh.set_vertices(vertices.ToArray <Vector3>());
                int[] numArray = new int[(mesh.get_vertices().Length - 2) * 3];
                int   index    = 0;
                int   num      = 0;

                while (index < numArray.Length)
                {
                    numArray[index]     = 0;
                    numArray[index + 1] = num + 1;
                    numArray[index + 2] = num + 2;
                    index += 3;
                    ++num;
                }
                mesh.set_triangles(numArray);
                mesh.RecalculateNormals();
                mesh.RecalculateBounds();
                meshFilter.set_sharedMesh(mesh);
            }
 static public int Clear(IntPtr l)
 {
     try {
         int argc = LuaDLL.lua_gettop(l);
         if (argc == 1)
         {
             UnityEngine.Mesh self = (UnityEngine.Mesh)checkSelf(l);
             self.Clear();
             pushValue(l, true);
             return(1);
         }
         else if (argc == 2)
         {
             UnityEngine.Mesh self = (UnityEngine.Mesh)checkSelf(l);
             System.Boolean   a1;
             checkType(l, 2, out a1);
             self.Clear(a1);
             pushValue(l, true);
             return(1);
         }
         pushValue(l, false);
         LuaDLL.lua_pushstring(l, "No matched override function Clear to call");
         return(2);
     }
     catch (Exception e) {
         return(error(l, e));
     }
 }
Пример #14
0
    public static void addMesh(List<MeshAttributes> meshAttributesList, Mesh shipMesh)
    {
        List<Vector3> shipVertices = new List<Vector3>();

        List<int> shipTris = new List<int>();

        if (shipMesh.vertices.Count() > 0)
            shipVertices = shipMesh.vertices.ToList();
        if (shipMesh.triangles.Count() > 0)
            shipTris = shipMesh.triangles.ToList();

        int lastVertices = shipVertices.Count;

        foreach (MeshAttributes meshAttributes in meshAttributesList) {

            for (int i = 0; i < meshAttributes.triangles.Length; i++) {
                meshAttributes.triangles[i] = meshAttributes.triangles[i] + shipVertices.Count;
            }

            shipVertices.AddRange(meshAttributes.vertices);

            lastVertices = meshAttributes.vertices.Count();

            shipTris.AddRange(meshAttributes.triangles);
        }

        shipMesh.Clear();

        shipMesh.vertices = shipVertices.ToArray();

        shipMesh.triangles = shipTris.ToArray();

        shipMesh.RecalculateNormals();
    }
Пример #15
0
    static int Clear(IntPtr L)
    {
        try
        {
            int count = LuaDLL.lua_gettop(L);

            if (count == 1 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Mesh)))
            {
                UnityEngine.Mesh obj = (UnityEngine.Mesh)ToLua.ToObject(L, 1);
                obj.Clear();
                return(0);
            }
            else if (count == 2 && TypeChecker.CheckTypes(L, 1, typeof(UnityEngine.Mesh), typeof(bool)))
            {
                UnityEngine.Mesh obj  = (UnityEngine.Mesh)ToLua.ToObject(L, 1);
                bool             arg0 = LuaDLL.lua_toboolean(L, 2);
                obj.Clear(arg0);
                return(0);
            }
            else
            {
                return(LuaDLL.luaL_throw(L, "invalid arguments to method: UnityEngine.Mesh.Clear"));
            }
        }
        catch (Exception e)
        {
            return(LuaDLL.toluaL_exception(L, e));
        }
    }
Пример #16
0
    void ClearScene()
    {
        //clear objects
        foreach (var item in objects)
        {
            Destroy(item.Value);
        }
        objects.Clear();
        newPrims.Clear();

        //clear avatars
        foreach (var item in avatars)
        {
            Destroy(item.Value);
        }
        avatars.Clear();
        renderAvatars.Clear();
        avHasTex.Clear();
        newAvatars.Clear();
        newTerseAvatarUpdates.Clear();

        //clear terrain
        mesh1.Clear();
        mesh2.Clear();
    }
Пример #17
0
    // Mesh Generation
    /////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
    /// <summary>
    /// Generate the playground
    /// </summary>
    public void GenerateArena()
    {
        //Set the camera
        Camera.main.transform.position = transform.position + new Vector3(SizeX / 2.0f, 0, SizeY / 2.0f) + Camera.main.transform.forward * -(Mathf.Max(SizeX, SizeY) + 10);
        Camera.main.orthographicSize = Mathf.Max(SizeX, SizeY) * 0.75f;
        Camera.main.transform.GetChild(0).localScale = new Vector3(3.6f * Camera.main.orthographicSize, 2.025f * Camera.main.orthographicSize, 1);

        //Clean old and set new mesh
        mesh = new Mesh();
        mesh.name = "Arena";
        mesh.Clear();

        //Set up the arrays
        vertices = new Vector3[(SizeX + 1) * (SizeY + 1)];
        triangles = new int[SizeX * SizeY * 6];
        uvs1 = new Vector2[vertices.Length];
        uvs2 = new Vector2[vertices.Length];
        colors = new Color[vertices.Length];

        //Set the vertices and vertex colors and uvs
        for(int i = 0; i < vertices.Length; i++){
            int x = i % (SizeX + 1);
            int y = Mathf.FloorToInt(i / (SizeX + 1));

            vertices[i] = new Vector3(x, 0, y);
            colors[i] = new Color(0.05f, 0.05f, 0.05f, 1);

            uvs1[i] = new Vector2((float) x / SizeX, (float) y / SizeY); //Main UV over the full mesh
            uvs2[i] = new Vector2(x, y); //Sub uv over only one tile
        }

        //Set the triangles
        for(int i = 0; i < triangles.Length / 6; i++){
            int firstTri = i + Mathf.FloorToInt(i / SizeX); //Position of the first tri of the quad
            triangles[i * 6] = firstTri;
            triangles[i * 6 + 1] = firstTri + (SizeX + 1);
            triangles[i * 6 + 2] = firstTri + 1;
            triangles[i * 6 + 3] = firstTri + 1;
            triangles[i * 6 + 4] = firstTri + (SizeX + 1);
            triangles[i * 6 + 5] = firstTri + (SizeX + 2);
        }

        //Set mesh parts
        mesh.vertices = vertices;
        mesh.triangles = triangles;
        mesh.uv = uvs1;
        mesh.uv2 = uvs2;
        mesh.colors = colors;

        mesh.RecalculateBounds ();
        mesh.RecalculateNormals ();

        //Assign to components
        GetComponent<MeshFilter>().mesh = mesh;
        GetComponent<MeshRenderer>().material = FloorMaterial;

        generateEdge();

        Debug.Log("Arena generated");
    }
    public void Start()
    {
        _mushroom = new GameObject("Mushroom");
        _mushroom.AddComponent<MeshFilter>();
        _mushroom.AddComponent<MeshRenderer>();

        _mesh = new Mesh();

        _vertices = new List<Vector3>();
        _indices = new List<int>();
        _uvs = new List<Vector2>();
        _mesh.Clear();

        GenerateVertices();
        GenerateIndices();
        GenerateUvs();
        //DrawVertices();

        _mesh.vertices = _vertices.ToArray();
        _mesh.triangles = _indices.ToArray();
        _mesh.uv = _uvs.ToArray();

        _mesh.RecalculateBounds();
        _mesh.RecalculateNormals();

        _mushroom.GetComponent<MeshFilter>().mesh = _mesh;
        _mushroom.renderer.material.color = Color.grey;
    }
Пример #19
0
	private void BuildMesh (MeshFilter mf, MeshRenderer mr, MeshCollider mc, int i, int j) {
		Mesh mesh = new Mesh();
		mesh.Clear();
		
		// the vertices of our new mesh, separated into two groups
		Vector3[] inner = new Vector3[grid.smoothness + 1]; // the inner vertices (closer to the centre)
		Vector3[] outer = new Vector3[grid.smoothness + 1]; // the outer vertices

		// vertices must be given in local space
		Transform trnsfrm = mf.gameObject.transform;
		
		// the amount of vertices depends on how much the grid is smoothed
		for (int k = 0; k < grid.smoothness + 1; k++) {
			// rad is the current distance from the centre, sctr is the current sector and i * (1.0f / grid.smoothness) is the fraction inside the current sector
			inner[k] = trnsfrm.InverseTransformPoint(grid.GridToWorld(new Vector3(i, j + k * (1.0f / grid.smoothness), 0)));
			outer[k] = trnsfrm.InverseTransformPoint(grid.GridToWorld(new Vector3(i + 1, j + k * (1.0f / grid.smoothness), 0)));
		}
		
		//this is wher the actual vertices go
		Vector3[] vertices = new Vector3[2 * (grid.smoothness + 1)];
		// copy the sorted vertices into the new array
		inner.CopyTo(vertices, 0);
		// for each inner vertex its outer counterpart has the same index plus grid.smoothness + 1, this will be relevant later
		outer.CopyTo(vertices, grid.smoothness + 1);
		// assign them as the vertices of the mesh
		mesh.vertices = vertices;
		
		// now we have to assign the triangles
		int[] triangles = new int[6 * grid.smoothness]; // for each smoothing step we need two triangles and each triangle is three indices
		int counter = 0; // keeps track of the current index
		for (int k = 0; k < grid.smoothness; k++) {
			// triangles are assigned in a clockwise fashion
			triangles[counter] = k;
			triangles[counter+1] = k + (grid.smoothness + 1) + 1;
			triangles[counter+2] = k + (grid.smoothness + 1);
			
			triangles[counter+3] = k + 1;
			triangles[counter+4] = k + (grid.smoothness + 1) + 1;
			triangles[counter+5] = k;

			counter += 6; // increment the counter for the nex six indices
		}
		mesh.triangles = triangles;
		
		// add some dummy UVs to keep the shader happy or else it complains, but they are not used in this example
		Vector2[] uvs = new Vector2[vertices.Length];
        for (int k = 0; k < uvs.Length; k++) {
            uvs[k] = new Vector2(vertices[k].x, vertices[k].y);
        }
        mesh.uv = uvs;
		
		// the usual cleanup
		mesh.RecalculateNormals();
		mesh.RecalculateBounds();
		mesh.Optimize();
		
		// assign the mesh  to the mesh filter and mesh collider
		mf.mesh = mesh;
		mc.sharedMesh = mesh;
	}
Пример #20
0
 static public int Clear(IntPtr l)
 {
     try{
         if (matchType(l, 2, typeof(System.Boolean)))
         {
             UnityEngine.Mesh self = (UnityEngine.Mesh)checkSelf(l);
             System.Boolean   a1;
             checkType(l, 2, out a1);
             self.Clear(a1);
             return(0);
         }
         else if (matchType(l, 2))
         {
             UnityEngine.Mesh self = (UnityEngine.Mesh)checkSelf(l);
             self.Clear();
             return(0);
         }
         LuaDLL.luaL_error(l, "No matched override function to call");
         return(0);
     }
     catch (Exception e) {
         LuaDLL.luaL_error(l, e.ToString());
         return(0);
     }
 }
Пример #21
0
    void Start()
    {
        m_meshFilter = gameObject.GetComponent<MeshFilter>();
        m_meshRenderer = gameObject.GetComponent<MeshRenderer>();
        Mesh mesh = new Mesh();
        mesh.name = "testMesh";
        mesh.Clear();

        Vector3[] vertices = new Vector3[m_triangleCount * 3];
        Vector2[] uv = new Vector2[m_triangleCount * 3];
        int[] triangles = new int[m_triangleCount * 3];
        for (int i = 0; i < m_triangleCount * 3; i++) {
            vertices[i] = Random.insideUnitSphere * m_size;
            uv[i] = new Vector2(Random.Range(0.0f, 1.0f), Random.Range(0.0f, 1.0f));
            triangles[i] = i;
        }

        mesh.vertices = vertices;
        mesh.uv = uv;
        mesh.triangles = triangles;
        mesh.RecalculateNormals();

        m_meshFilter.mesh = mesh;
        m_meshRenderer.renderer.material.color = Color.black;
    }
    public void ShowMarquee(RaycastHit hit)
    {
        verts.Clear ();
        uvs.Clear ();
        tris.Clear ();

        WorldPos pos = RaycastUtility.GetBlockPos (hit);
        Block.Direction direction = Block.Direction.up;
        float norX = hit.normal.x;
        float norY = hit.normal.y;
        float norZ = hit.normal.z;
        if (norX > 0)
            direction = Block.Direction.east;
        if (norX < 0)
            direction = Block.Direction.west;
        if (norY > 0)
            direction = Block.Direction.up;
        if (norY < 0)
            direction = Block.Direction.down;
        if (norZ > 0)
            direction = Block.Direction.north;
        if (norZ < 0)
            direction = Block.Direction.south;

        BuildFace (pos, direction);

        mesh = GetComponent<MeshFilter> ().mesh;
        mesh.Clear ();
        mesh.vertices = verts.ToArray ();
        mesh.triangles = tris.ToArray ();
        mesh.uv = uvs.ToArray ();
        mesh.RecalculateNormals ();
    }
Пример #23
0
    // Use this for initialization
    void Start()
    {
        mesh = GetComponent<MeshFilter> ().mesh;

        float x = transform.position.x;
        float y = transform.position.y;
        float z = transform.position.z;

        newVertices.Add( new Vector3 (x  , y  , z ));
        newVertices.Add( new Vector3 (x + 1 , y  , z ));
        newVertices.Add( new Vector3 (x + 1 , y-1  , z ));
        newVertices.Add( new Vector3 (x  , y-1  , z ));

        newTriangles.Add(0);
        newTriangles.Add(1);
        newTriangles.Add(3);
        newTriangles.Add(1);
        newTriangles.Add(2);
        newTriangles.Add(3);

        mesh.Clear ();
        mesh.vertices = newVertices.ToArray();
        mesh.triangles = newTriangles.ToArray();
        mesh.Optimize ();
        mesh.RecalculateNormals ();
    }
Пример #24
0
    // Use this for initialization
    void Start()
    {
        mesh = new Mesh();
        mesh.name = "testMesh";
        mesh.Clear();

        Vector3[] vertices = new Vector3[4];
        vertices[0] = new Vector3(0.0f, 0.0f, 0.0f);
        vertices[1] = new Vector3(1.0f, 0.0f, 0.0f);
        vertices[2] = new Vector3(1.0f, 1.0f, 0.0f);
        vertices[3] = new Vector3(0.0f, 1.0f, 0.0f);
        mesh.vertices = vertices;

        //TraceMesh(mesh);

        int[] triangles = new int[6] { 3, 2, 0, 2, 1, 0};
        mesh.triangles = triangles;

        mesh.uv = new Vector2[] {
            new Vector2 (0, 0),
            new Vector2 (0, 1),
            new Vector2 (1, 1),
            new Vector2 (1, 0)
        };

        //Vector3[] normals = new Vector3[4] { Vector3.forward, Vector3.forward, Vector3.forward, Vector3.forward };
        //mesh.normals = normals;

        mesh.RecalculateNormals();

        MeshFilter mf = (MeshFilter)gameObject.GetComponent(typeof(MeshFilter));
        MeshRenderer mr = (MeshRenderer)gameObject.GetComponent(typeof(MeshRenderer));
        mf.mesh = mesh;
        mr.material.color = Color.white;
    }
        private static void SetDataToMesh(UnityEngine.Mesh mesh, MyMeshData meshData, NativeArray <TurtleMeshAllocationCounter> submeshSizes)
        {
            UnityEngine.Profiling.Profiler.BeginSample("applying mesh data");
            int vertexCount = meshData.vertexData.Length;
            int indexCount  = meshData.indices.Length;

            mesh.Clear();

            mesh.SetVertexBufferParams(vertexCount, GetVertexLayout());
            mesh.SetVertexBufferData(meshData.vertexData, 0, 0, vertexCount, 0, MeshUpdateFlags.DontRecalculateBounds | MeshUpdateFlags.DontResetBoneBounds | MeshUpdateFlags.DontValidateIndices);

            mesh.SetIndexBufferParams(indexCount, IndexFormat.UInt32);
            mesh.SetIndexBufferData(meshData.indices, 0, 0, indexCount, MeshUpdateFlags.DontRecalculateBounds | MeshUpdateFlags.DontResetBoneBounds | MeshUpdateFlags.DontValidateIndices);

            mesh.subMeshCount = submeshSizes.Length;
            for (int i = 0; i < submeshSizes.Length; i++)
            {
                var submeshSize = submeshSizes[i];
                var descriptor  = new SubMeshDescriptor()
                {
                    baseVertex = 0,
                    topology   = MeshTopology.Triangles,
                    indexCount = submeshSize.totalTriangleIndexes,
                    indexStart = submeshSize.indexInTriangles,
                };
                mesh.SetSubMesh(i, descriptor, MeshUpdateFlags.DontRecalculateBounds | MeshUpdateFlags.DontResetBoneBounds | MeshUpdateFlags.DontValidateIndices);
            }

            mesh.bounds = meshData.meshBounds[0];
            UnityEngine.Profiling.Profiler.EndSample();
        }
Пример #26
0
	public void ApplyChunkSettings(Chunk chunk, CubedObjectBehaviour parent) {
		this.chunk = chunk;
		renderer.materials = new Material[] { chunk.blockMaterial };
		
		var mesh = new Mesh();
		mesh.Clear();
	    mesh.vertices = chunk.meshData.RenderableVertices.ToArray();
	    mesh.triangles = chunk.meshData.RenderableTriangles.ToArray();
	    mesh.uv = chunk.meshData.RenderableUvs.ToArray();
	    mesh.RecalculateNormals();
		
		var meshFilter = GetComponent<MeshFilter>();
	    // sharedMesh is null during generation
	    // TODO: Fix this as the generator shows errors in the console when using mesh vs. sharedMesh
	    //mesh = (meshFilter.mesh if EditorApplication.isPlayingOrWillChangePlaymode else meshFilter.sharedMesh)
		if(Application.isPlaying) meshFilter.mesh = mesh;
		else meshFilter.sharedMesh = mesh;
		
		if(parent.colliderType == ColliderType.MeshColliderPerChunk) {
			var colliderMesh = new Mesh();
			colliderMesh.vertices = chunk.meshData.CollidableVertices.ToArray();
			colliderMesh.triangles = chunk.meshData.CollidableTriangles.ToArray();
			var meshCollider = GetComponent<MeshCollider>();
			if(colliderMesh != null) {
				if(meshCollider == null) meshCollider = gameObject.AddComponent<MeshCollider>();
			   	meshCollider.sharedMesh = colliderMesh;
			   	meshCollider.convex = false;
				meshCollider.enabled = true;
			}
			else {
				if(meshCollider != null) meshCollider.enabled = false;
			}
		}
		transform.localPosition = (chunk.gridPosition * parent.chunkDimensions).ToVector3() * parent.cubeSize;
	}
    // Initializes a mesh with a plane with nVerticesX * nVerticesY vertices.
    public void InitPlane(Mesh mesh, int nVerticesX, int nVerticesY, Vector3[] vertices=null)
    {
        mesh.Clear ();

        int nVertices = nVerticesX * nVerticesY;
        int nTriangles = (nVerticesX - 1) * (nVerticesY - 1) * 6;

        bool initVertices = (vertices == null);

        if (initVertices) {
            vertices = new Vector3[nVertices];
        }

        Vector2[] uvs = new Vector2[nVertices];
        int[] triangles = new int[nTriangles];

        int i = 0;
        int iTriangles = 0;
        float incX = 1.0f / (nVerticesX - 1);
        float incY = 1.0f / (nVerticesY - 1);
        float xCoord = -0.5f;
        float yCoord = -0.5f;

        for(int y = 0; y < nVerticesY; y++) {

            for (int x = 0; x < nVerticesX; x++) {

                if (initVertices) {
                    vertices[i] = new Vector3(xCoord, yCoord, 0);
                }
                uvs[i] = new Vector2(xCoord + 0.5f, yCoord + 0.5f);

                if (x < nVerticesX - 1 && y < nVerticesY - 1)
                {
                    int v0 = i;
                    int v1 = i + 1;
                    int v2 = i + nVerticesX;
                    int v3 = i + nVerticesX + 1;
                    triangles[iTriangles++] = v0;
                    triangles[iTriangles++] = v2;
                    triangles[iTriangles++] = v3;
                    triangles[iTriangles++] = v0;
                    triangles[iTriangles++] = v3;
                    triangles[iTriangles++] = v1;
                }

                xCoord += incX;
                i++;
            }

            yCoord += incY;
            xCoord = -0.5f;
        }

        mesh.vertices = vertices;
        mesh.triangles = triangles;
        mesh.uv = uvs;
        mesh.RecalculateNormals ();
    }
Пример #28
0
 private static void UpdateMesh(UnityEngine.Mesh mesh, Vector3[] vertices, int[] triangles)
 {
     mesh.Clear();
     mesh.vertices  = vertices;
     mesh.triangles = triangles;
     mesh.RecalculateNormals();
     mesh.RecalculateBounds();
 }
        /// <summary>
        /// Fill label mesh.
        /// </summary>
        /// <param name="mesh">Mesh.</param>
        /// <param name="width">Label width.</param>
        /// <param name="height">Label height.</param>
        /// <param name="text">Label text.</param>
        /// <param name="color">Color.</param>
        /// <param name="align">Text align.</param>
        /// <param name="font">Font.</param>
        /// <param name="fontSize">Font size.</param>
        /// <param name="lineHgt">Line height multiplier.</param>
        /// <param name="effect">Effect.</param>
        /// <param name="effectValue">Effect value.</param>
        /// <param name="effectColor">Effect color.</param>
        public static void FillText(
            Mesh mesh, int width, int height, string text, Color color, TextAnchor align, Font font, int fontSize,
            float lineHgt, GuiFontEffect effect = GuiFontEffect.None, Vector2? effectValue = null, Color? effectColor = null)
        {
            if (mesh == null) {
                return;
            }
            mesh.Clear ();
            if (font == null || string.IsNullOrEmpty (text)) {
                return;
            }

            _settings.fontSize = (int) (fontSize * GuiSystem.Instance.VirtualToRealScaleFactor);
            _settings.resizeTextMaxSize = _settings.fontSize;

            var scale = fontSize / (float) _settings.fontSize;

            _settings.font = font;
            _settings.textAnchor = align;
            _settings.generationExtents = new Vector2 (width, height) / scale;
            _settings.lineSpacing = lineHgt;
            _settings.color = color;
            _generator.Invalidate ();
            if (!_generator.Populate (text, _settings)) {
                return;
            }

            _generator.GetVertices (_verts);

            GuiMeshTools.PrepareBuffer (effect, effectValue, effectColor);

            for (int i = 0, iMax = _verts.Count - 4, charID = 0; i < iMax; charID++) {
                if (text[charID] == ' ') {
                    i += 4;
                    continue;
                }
                _uiV = _verts[i++];
                _c = _uiV.color;
                _v0 = _uiV.position * scale;
                _uv0 = _uiV.uv0;

                _uiV = _verts[i++];
                _v1 = _uiV.position * scale;
                _uv1 = _uiV.uv0;

                _uiV = _verts[i++];
                _v2 = _uiV.position * scale;
                _uv2 = _uiV.uv0;

                _uiV = _verts[i++];
                _v3 = _uiV.position * scale;
                _uv3 = _uiV.uv0;
                GuiMeshTools.FillBuffer (ref _v0, ref _v1, ref _v2, ref _v3, ref _uv0, ref _uv1, ref _uv2, ref _uv3, ref _c);
            }

            GuiMeshTools.GetBuffers (mesh, false);
            mesh.bounds = new Bounds (Vector3.zero, new Vector3 (width, height, 0f));
        }
Пример #30
0
        /// Collect and bind geometry from stream
        public void Bind(UnityEngine.Mesh mesh)
        {
            var vertices  = new List <Vector3>();
            var triangles = new List <int>();
            var uv        = useUV ? new List <Vector2>() : null;
            var color     = useColor ? new List <Color32>() : null;
            var normals   = useUV ? new List <Vector3>() : null;

            // Collect
            foreach (var gp in geometry.Geometry)
            {
                gp.VertexOffset = vertices.Count;
                vertices.AddRange(gp.Vertices);
                triangles.AddRange(gp.Triangles);
                if (uv != null)
                {
                    uv.AddRange(gp.UV);
                }
                if (color != null)
                {
                    color.AddRange(gp.Color);
                }
                if (normals != null)
                {
                    normals.AddRange(gp.Normals);
                }
            }

            // Attach
            mesh.Clear();
            mesh.vertices  = vertices.ToArray();
            mesh.triangles = triangles.ToArray();
            if (useUV)
            {
                mesh.uv = uv.ToArray();
            }
            if (useColor)
            {
                mesh.colors32 = color.ToArray();
            }
            if (useNormals)
            {
                mesh.normals = normals.ToArray();
            }

            // Bind
            if (!useNormals)
            {
                mesh.RecalculateNormals();
            }
            mesh.RecalculateBounds();
            mesh.Optimize();

            // Summary
            vertexGen   = vertices.Count;
            triangleGen = triangles.Count;
        }
Пример #31
0
 public static void ApplyToMesh(Mesh mesh, MeshDesc desc)
 {
     mesh.Clear();
     mesh.vertices = desc.positions.ToArray();
     mesh.normals = desc.normals.ToArray();
     mesh.triangles = desc.indices.ToArray();
     mesh.Optimize();
     mesh.RecalculateBounds();
 }
Пример #32
0
        private void MeshUpdated(Mesh m)
        {
            MeshFilter filter = GetComponent<MeshFilter>();
            mesh = filter.mesh;
            mesh.Clear();

            mesh.vertices = m.vertices;
            mesh.triangles = m.triangles;
        }
Пример #33
0
 private void UpdateMesh()
 {
     meshVertices[0] = a.position - center;
     meshVertices[1] = b.position - center;
     meshVertices[2] = c.position - center;
     uMesh.Clear();
     uMesh.vertices  = meshVertices;
     uMesh.triangles = meshTriangles;
 }
Пример #34
0
 public void GenerateMesh()
 {
     mesh = new Mesh ();
     mesh.Clear ();
     mesh.vertices = vertices.ToArray();
     mesh.triangles = triangles.ToArray();
     mesh.uv = uv.ToArray();
     mesh.normals = normals.ToArray();
     mesh.Optimize ();
 }
Пример #35
0
        /// <summary>
        /// Function to pre-allocate vertex attributes for a mesh of size X.
        /// </summary>
        /// <param name="mesh"></param>
        /// <param name="size"></param>
        public TMP_MeshInfo (Mesh mesh, int size)
        {
            // Clear existing mesh data
            mesh.Clear();

            this.mesh = mesh;

            int sizeX4 = size * 4;
            int sizeX6 = size * 6;

            this.vertexCount = 0;

            this.vertices = new Vector3[sizeX4];
            this.uvs0 = new Vector2[sizeX4];
            this.uvs2 = new Vector2[sizeX4];
            this.uvs4 = new Vector2[sizeX4]; // SDF scale data
            this.colors32 = new Color32[sizeX4];

            this.normals = new Vector3[sizeX4];
            this.tangents = new Vector4[sizeX4];

            this.triangles = new int[sizeX6];

            int index_X6 = 0;
            int index_X4 = 0;
            while (index_X4 / 4 < size)
            {
                for (int i = 0; i < 4; i++)
                {
                    this.vertices[index_X4 + i] = Vector3.zero;
                    this.uvs0[index_X4 + i] = Vector2.zero;
                    this.uvs2[index_X4 + i] = Vector2.zero;
                    this.uvs4[index_X4 + i] = Vector2.zero;
                    this.colors32[index_X4 + i] = s_DefaultColor;
                    this.normals[index_X4 + i] = s_DefaultNormal;
                    this.tangents[index_X4 + i] = s_DefaultTangent;
                }

                this.triangles[index_X6 + 0] = index_X4 + 0;
                this.triangles[index_X6 + 1] = index_X4 + 1;
                this.triangles[index_X6 + 2] = index_X4 + 2;
                this.triangles[index_X6 + 3] = index_X4 + 2;
                this.triangles[index_X6 + 4] = index_X4 + 3;
                this.triangles[index_X6 + 5] = index_X4 + 0;

                index_X4 += 4;
                index_X6 += 6;
            }

            // Pre-assign base vertex attributes.
            this.mesh.vertices = this.vertices;
            this.mesh.normals = this.normals;
            this.mesh.tangents = this.tangents;
            this.mesh.triangles = this.triangles;
        } 
Пример #36
0
	static void CreateMesh()
	{		
		GameObject newSpriteObject = new GameObject();		
		newSpriteObject.name = "Sprite";

		newSpriteObject.AddComponent("MeshFilter");
		MeshFilter meshFilter = newSpriteObject.GetComponent("MeshFilter") as MeshFilter;
		if (meshFilter==null)
		{
			Debug.LogError("MeshFilter not found!");
			return;
		}
		
		Vector3 p0 = new Vector3(-5, -5, 0);
		Vector3 p1 = new Vector3(5, -5, 0);
		Vector3 p2 = new Vector3(-5, 5, 0);
		Vector3 p3 = new Vector3(5, 5, 0);
		
		Mesh mesh = new Mesh();
		meshFilter.mesh = mesh;
		
		mesh.Clear();
		
		mesh.vertices = new Vector3[]
		{
			p1, p0, p2,
			p1, p2, p3
		};
		
		mesh.triangles = new int[]
		{
			0, 1, 2,
			3, 4, 5
		};
		
		Vector2 uv0 = new Vector2(0f,0f);
		Vector2 uv1 = new Vector2(1f,0f);
		Vector2 uv2 = new Vector2(0f,1f);
		Vector2 uv3 = new Vector2(1f,1f);
		
		mesh.uv = new Vector2[]
		{
			uv1, uv0, uv2,
			uv1, uv2, uv3
		};
		
		mesh.RecalculateNormals();
		mesh.RecalculateBounds();
		mesh.Optimize();
		
		newSpriteObject.AddComponent("MeshRenderer");
		newSpriteObject.AddComponent(typeof(Sprite));
		mesh.name = "SpriteMesh";	
	}
Пример #37
0
    void Start()
    {
        world=GameObject.Find("World").GetComponent("World") as World;

        mesh = GetComponent<MeshFilter> ().mesh;

        for(int i = -25; i < 25; i+=1){
            for(int z = -25; z < 25; z+=1){
                //if((i > 1 || i  < -1) || (z > 1 || z < -1)){

                    Debug.Log("Special kinda stupid");

                    unModVerts.Add(new Vector3 (((i*400))/50, 		(world.terrainHeight((i*400), 		(z*400)+400))/50, 	((z*400)+400)/50));
                    unModVerts.Add(new Vector3 (((i*400)+400)/50, 	(world.terrainHeight((i*400)+400, 	(z*400)+400))/50,	((z*400)+400)/50));
                    unModVerts.Add(new Vector3 (((i*400)+400)/50, 	(world.terrainHeight((i*400)+400, 	(z*400)))/50,  		(z*400)/50));
                    unModVerts.Add(new Vector3 (((i*400))/50,		(world.terrainHeight((i*400), 		(z*400)))/50, 		(z*400)/50));

                    if(world.terrainHeight((i*200), 		(z*200)) > 180){
                        unModUV.Add(new Vector2 (.25f, 0));
                        unModUV.Add(new Vector2 (.5f, .25f));
                        unModUV.Add(new Vector2 (.5f, 	0));
                        unModUV.Add(new Vector2 (.25f, .25f));

                    }else if (world.terrainHeight((i*200), 		(z*200)) > 30){
                        unModUV.Add(new Vector2 (0, 0));
                        unModUV.Add(new Vector2 (.25f, .25f));
                        unModUV.Add(new Vector2 (.25f, 	0));
                        unModUV.Add(new Vector2 (0, .25f));

                    }else{
                        unModUV.Add(new Vector2 (.5f, 0));
                        unModUV.Add(new Vector2 (.75f, .25f));
                        unModUV.Add(new Vector2 (.75f, 	0));
                        unModUV.Add(new Vector2 (.5f, .25f));

                    }

                    unModTris.Add(faceCount * 4  ); //1
                    unModTris.Add(faceCount * 4 + 1 ); //2
                    unModTris.Add(faceCount * 4 + 2 ); //3
                    unModTris.Add(faceCount * 4  ); //1
                    unModTris.Add(faceCount * 4 + 2 ); //3
                    unModTris.Add(faceCount * 4 + 3 ); //4
                    faceCount++;
                //}
            }
        }
        mesh.Clear ();
        mesh.vertices = unModVerts.ToArray();
        mesh.uv = unModUV.ToArray();
        mesh.triangles = unModTris.ToArray();
        mesh.Optimize ();
        mesh.RecalculateNormals ();
    }
Пример #38
0
 public void GenerateLines()
 {
     mesh = linesObject.GetComponent<MeshFilter>().sharedMesh;
     mesh.Clear();
     foreach(Edge e in edges)
     {
         AddLine(mesh, MakeQuad(e, lineWidth), false);
     }
     mesh.RecalculateNormals();
     mesh.RecalculateBounds();
 }
    // Use this for initialization
    void Init()
    {
        m_Filter = gameObject.GetComponent< MeshFilter >();
        m_Mesh = m_Filter.mesh;
        m_Mesh.Clear();

        IsDirty = true;
        m_Initialized = true;

        print (name + " initialized");
    }
Пример #40
0
            public static void BuildMeshFromNodeHandleForColoredCubesVolume(Mesh mesh, uint nodeHandle, bool onlyPositions)
            {
                // Get the data from Cubiquity.
                ColoredCubesVertex[] vertices;
                ushort[] indices;
                CubiquityDLL.GetMesh<ColoredCubesVertex>(nodeHandle, out vertices, out indices);
                int noOfVertices = vertices.Length;
                int noOfIndices = indices.Length;
#endif

                // Cubiquity uses 16-bit index arrays to save space, and it appears Unity does the same (at least, there is
                // a limit of 65535 vertices per mesh). However, the Mesh.triangles property is of the signed 32-bit int[]
                // type rather than the unsigned 16-bit ushort[] type. Perhaps this is so they can switch to 32-bit index
                // buffers in the future? At any rate, it means we have to perform a conversion.
                int[] indicesAsInt = new int[noOfIndices];
                for (int ct = 0; ct < noOfIndices; ct++)
                {
                    indicesAsInt[ct] = indices[ct];
                }

                // Clear any previous mesh data.
                mesh.Clear(true);

                // Required for the CubicVertex decoding process.
                Vector3 offset = new Vector3(0.5f, 0.5f, 0.5f);

                // Copy the vertex positions from Cubiquity into the Unity mesh.
                Vector3[] positions = new Vector3[noOfVertices];
                for (int ct = 0; ct < noOfVertices; ct++)
                {
                    // Get and decode the position
                    positions[ct].Set(vertices[ct].x, vertices[ct].y, vertices[ct].z);
                    positions[ct] -= offset;
                }
                // Assign vertex data to the mesh.
                mesh.vertices = positions;

                // For collision meshes the vertex positions are enough, but
                // for meshes which are rendered we want all vertex attributes.
                if(!onlyPositions)
                {
                    Color32[] colors32 = new Color32[noOfVertices];
                    for (int ct = 0; ct < noOfVertices; ct++)
                    {
                        // Get and decode the color
                        colors32[ct] = (Color32)vertices[ct].color;
                    }
                    // Assign vertex data to the mesh.
                    mesh.colors32 = colors32;
                }

                // Assign index data to the mesh.
                mesh.triangles = indicesAsInt;
            }
Пример #41
0
    Mesh CreateMesh()
    {
        mesh = new Mesh();
        mesh.Clear();

        float length = zSize;
        float width = xSize;
        int resX = resolution;
        int resZ = resolution;

        Vector3[] vertices = new Vector3[resX * resZ];
        for (int z = 0; z < resZ; z++) {
            float zPos = ((float)z / (resZ - 1) - .5f) * length;

            for (int x = 0; x < resX; x++) {
                float xPos = ((float)x / (resX - 1) - .5f) * width;
                vertices[x + z * resX] = new Vector3(xPos, 0f, zPos);
            }
        }

        Vector3[] normales = new Vector3[vertices.Length];
        for (int n = 0; n < normales.Length; n++)
            normales[n] = Vector3.up;

        Vector2[] uvs = new Vector2[vertices.Length];
        for (int v = 0; v < resZ; v++) {
            for (int u = 0; u < resX; u++) {
                uvs[u + v * resX] = new Vector2((float)u / (resX - 1), (float)v / (resZ - 1));
            }
        }

        int nbFaces = (resX - 1) * (resZ - 1);
        int[] triangles = new int[nbFaces * 6];
        int t = 0;
        for (int face = 0; face < nbFaces; face++) {
            int i = face % (resX - 1) + (face / (resZ - 1) * resX);

            triangles[t++] = i + resX;
            triangles[t++] = i + 1;
            triangles[t++] = i;

            triangles[t++] = i + resX;
            triangles[t++] = i + resX + 1;
            triangles[t++] = i + 1;
        }

        mesh.vertices = vertices;
        mesh.normals = normales;
        mesh.uv = uvs;
        mesh.triangles = triangles;

        return mesh;
    }
Пример #42
0
        public void BuildMesh()
        {
            if (gameObject.GetComponent("MeshFilter") == null)
            {
                gameObject.AddComponent("MeshFilter");
            }
            if (gameObject.GetComponent("MeshRenderer") == null)
            {
                gameObject.AddComponent("MeshRenderer");
            }
            UnityEngine.Mesh mesh = GetComponent <MeshFilter>().mesh;
            mesh.Clear();
            mesh.subMeshCount = 3;

            verticeslist     = new List <Vector3>();
            UVlist           = new List <Vector2>();
            trianglelist     = new List <int>();
            wallTrianglelist = new List <int>();
            solidRoof        = new List <int>();



            Generate(size, Level);

            MeshRenderer mr = gameObject.GetComponent <MeshRenderer>();


            mesh.vertices = verticeslist.ToArray();
            mesh.uv       = UVlist.ToArray();
            mesh.SetTriangles(trianglelist.ToArray(), 0);         //make floor
            mesh.SetTriangles(wallTrianglelist.ToArray(), 1);     //make walls
            mesh.SetTriangles(solidRoof.ToArray(), 2);            //make walls
            mesh.Optimize();
            mesh.RecalculateBounds();
            mesh.RecalculateNormals();
            mesh.calculateMeshTangents();

            Material[] tempm = new Material[3];
            tempm[0]     = floorMaterial;
            tempm[1]     = wallMaterial;
            tempm[2]     = solidRoofMaterial;
            mr.materials = tempm;
            MeshFilter mf = GetComponent <MeshFilter>();

            if (mf == null)
            {
                Debug.Log("MeshFilter is null.");
            }
            else
            {
                mf.mesh = mesh;
            }
        }
        /// <summary>
        /// deactivate and free up this object for use again by the level controller
        /// </summary>
        public void deactivateAndClear()
        {
            gameObject.SetActive(false);
            currentChunkMesh = new UnityEngine.Mesh();
            currentChunkMesh.Clear();

            currentChunk         = null;
            chunkLocation        = default;
            colliderBakerHandler = default;
            isMeshed             = false;
            isActive             = false;
        }
Пример #44
0
        public void UpdateMeshCollider()
        {
            collisionMeshVertices[0] = a.position - center;
            collisionMeshVertices[1] = b.position - center;
            collisionMeshVertices[2] = c.position - center;
            collisionMeshVertices[3] = -Vector3.Cross(b.position - a.position, c.position - a.position).normalized * 0.025f;
            collisionMesh.Clear();
            collisionMesh.vertices  = collisionMeshVertices;
            collisionMesh.triangles = collisionMeshTriangles;

            if (!(a.position == b.position || b.position == c.position))
            {
                meshCollider.sharedMesh = collisionMesh;
            }
        }
Пример #45
0
    public void UpdateMesh()
    {
        mMesh.Clear();
        var spriteName = mIsAnimated ? FindNextFrameName() : mSpriteName;

        if (mSpriteSheet.Sprites.ContainsKey(spriteName))
        {
            var descr = mSpriteSheet.Sprites[spriteName];
            UpdateComponents(descr);
            mMesh.vertices  = mVertex.Select(v => v.position).ToArray();
            mMesh.uv        = mVertex.Select(v => v.uv).ToArray();
            mMesh.triangles = mIndices;
            SpriteSize      = descr.mSpriteSize;
        }
    }
Пример #46
0
        /// <summary>
        /// Update the mesh for it's assigned chunk
        /// </summary>
        public void updateMeshWithChunkData()
        {
            currentChunkMesh = new UnityEngine.Mesh();
            currentChunkMesh.Clear();

            currentChunkMesh.vertices = currentChunk.mesh.getVertices();
            currentChunkMesh.colors   = currentChunk.mesh.getColors();
            currentChunkMesh.SetTriangles(currentChunk.mesh.triangles, 0);
            currentChunkMesh.RecalculateNormals();

            transform.position      = chunkLocation * Chunk.Diameter;
            meshFilter.mesh         = currentChunkMesh;
            meshCollider.sharedMesh = currentChunkMesh;
            isMeshed = true;
        }
Пример #47
0
    void MakeMesh(UnityEngine.Mesh mesh, Face face, int vertices_begin, int vertices_end, int indices_begin, int indices_end, int indices_offset)
    {
        //we have to clear the mesh first, otherwise there will be exceptions.
        mesh.Clear();

        int vertices_count = vertices_end - vertices_begin + 1;

        UnityEngine.Vector3[] vertices = new UnityEngine.Vector3[vertices_count];
        UnityEngine.Vector3[] normals  = new UnityEngine.Vector3[vertices_count];
        UnityEngine.Vector2[] uv       = new UnityEngine.Vector2[vertices_count];
        for (int k = vertices_begin, i = 0; k <= vertices_end; ++k, ++i)
        {
            vertices[i].x = face.Vertices[k].Position.X;
            vertices[i].y = face.Vertices[k].Position.Y;
            //HACK: unity3d uses left-hand coordinate, so we have to mirror z corrd
            vertices[i].z = -face.Vertices[k].Position.Z;

            normals[i].x = face.Vertices[k].Normal.X;
            normals[i].y = face.Vertices[k].Normal.Y;
            //HACK: unity3d uses left-hand coordinate, so we have to mirror z corrd
            normals[i].z = -face.Vertices[k].Normal.Z;

            uv[i].x = face.Vertices[k].TexCoord.X;
            //HACK: unity3d uses left-bottom corner as the origin of the texture
            uv[i].y = 1 - face.Vertices[k].TexCoord.Y;

            if (face.Vertices[k].TexCoord.X < 0 || face.Vertices[k].TexCoord.X > 1)
            {
                Debug.Log("Texture Repeat!" + face.Vertices[k].TexCoord.X.ToString());
            }
        }
        //indices for this face
        int[] triangles = new int[indices_end - indices_begin + 1];
        for (int k = indices_begin, i = 0; k <= indices_end; k += 3, i += 3)
        {
            //HACK: OpenGL's default front face is counter-clock-wise
            triangles[i]     = face.Indices[k + 2] - indices_offset;
            triangles[i + 1] = face.Indices[k + 1] - indices_offset;
            triangles[i + 2] = face.Indices[k + 0] - indices_offset;
        }

        mesh.vertices  = vertices;
        mesh.normals   = normals;
        mesh.uv        = uv;
        mesh.triangles = triangles;
    }
        /// <summary>
        /// Update the mesh for it's assigned chunk
        /// </summary>
        public void updateMeshWithChunkData()
        {
            currentChunkMesh = new UnityEngine.Mesh();
            currentChunkMesh.Clear();

            currentChunkMesh.vertices = currentChunk.mesh.getVertices();
            currentChunkMesh.colors   = currentChunk.mesh.getColors();
            currentChunkMesh.SetTriangles(currentChunk.mesh.triangles, 0);
            currentChunkMesh.RecalculateNormals();

            transform.position      = chunkLocation * Chunk.Diameter;
            meshFilter.mesh         = currentChunkMesh;
            meshCollider.sharedMesh = currentChunkMesh;
            isMeshed = true;

            /// schedule a job to bake the mesh collider asyncly so it doesn't lag.
            colliderBakerHandler = (new ColliderMeshBakingJob(currentChunkMesh.GetInstanceID())).Schedule();
        }
Пример #49
0
        /// <summary>
        /// Update the mesh for it's assigned chunk
        /// </summary>
        public void updateMeshWithChunkData()
        {
            currentChunkMesh = new UnityEngine.Mesh();
            currentChunkMesh.Clear();

            currentChunkMesh.vertices = currentChunkMeshData.vertices;
            currentChunkMesh.colors   = currentChunkMeshData.colors;
            currentChunkMesh.SetTriangles(currentChunkMeshData.triangles, 0);
            currentChunkMesh.RecalculateNormals();

            transform.position      = (chunkLocation * Chunk.Diameter).vec3;
            meshFilter.mesh         = currentChunkMesh;
            meshCollider.sharedMesh = currentChunkMesh;
            isMeshed = true;

            /// schedule a job to bake the mesh collider asyncly so it doesn't lag.
            /// //@todo: use threadpool here to go over unity's priority?
            colliderBakerHandler = (new ColliderMeshBakingJob(currentChunkMesh.GetInstanceID())).Schedule();
        }
Пример #50
0
        public static void CopyFromPositionOnly(this UnityEngine.Mesh mesh, GeneratedMeshContents contents)
        {
            if (object.ReferenceEquals(contents, null))
            {
                throw new ArgumentNullException("contents");
            }

            if (contents.description.vertexCount < 3 ||
                contents.description.indexCount < 3)
            {
                mesh.Clear();
                return;
            }

            mesh.SetVertices(contents.positions);

            mesh.SetTriangles(contents.indices.ToArray(), 0, false);
            mesh.bounds = contents.bounds;
        }
Пример #51
0
        void InitializeVerts()
        {
            int    w     = Size.x;
            int    h     = Size.y;
            float3 start = -new float3(w, h, 0) / 2f;

            for (int x = 0; x < w; ++x)
            {
                for (int y = 0; y < h; ++y)
                {
                    int i = y * w + x;

                    float3 p = start + new float3(x, y, 0);
                    // 0---1
                    // | / |
                    // 2---3
                    int vi = i * 4;
                    _verts[vi + 0] = p + new float3(0, 1, 0);
                    _verts[vi + 1] = p + new float3(1, 1, 0);
                    _verts[vi + 2] = p + new float3(0, 0, 0);
                    _verts[vi + 3] = p + new float3(1, 0, 0);

                    int ii = i * 6;
                    _indices[ii + 0] = vi + 0;
                    _indices[ii + 1] = vi + 1;
                    _indices[ii + 2] = vi + 2;
                    _indices[ii + 3] = vi + 3;
                    _indices[ii + 4] = vi + 2;
                    _indices[ii + 5] = vi + 1;
                }
            }

            _mesh.Clear();

            _mesh.SetVertices(_verts);
            _mesh.SetIndices(_indices, MeshTopology.Triangles, 0);

            _mesh.RecalculateBounds();
            _mesh.RecalculateNormals();
            _mesh.RecalculateTangents();
        }
Пример #52
0
 public void updateMesh()
 {
     mesh.Clear();
     if (vertices == null)
     {
         vertices = new List <Vector3> ();
     }
     else if (vertices.Count > 0)
     {
         vertices.Clear();
     }
     for (int i = 0; i < levels.Count; i++)
     {
         for (int j = 0; j < levels [i].vertices.Count; j++)
         {
             vertices.Add(levels [i].vertices [j]);
         }
     }
     mesh.vertices  = vertices.ToArray();
     mesh.triangles = DelanunayTriangulation.Calculate(mesh.vertices);
 }
Пример #53
0
 public UnityEngine.Mesh CreateNewUnityMesh(GeneratedMeshKey meshKey)
 {
     UnityEngine.Mesh sharedMesh = null;
     if (garbageMeshes.Count > 0)
     {
         var lastIndex = garbageMeshes.Count - 1;
         sharedMesh = garbageMeshes[lastIndex];
         garbageMeshes.RemoveAt(lastIndex);
         if (sharedMesh)
         {
             sharedMesh.Clear();
         }
     }
     if (!sharedMesh)
     {
         sharedMesh = new UnityEngine.Mesh()
         {
             name = meshKey.GetHashCode().ToString()
         }
     }
     ;
     return(ReturnOrRegisterUnityMeshAndIncreaseRefCount(meshKey, sharedMesh));
 }
Пример #54
0
        public void HandleOnUpdateMesh( )
        {
            if (Vertices.Length < 3)
            {
                throw new System.Exception("A Mesh must needs more than 3 points, no less!");
            }

            //var _mesh = GetComponent<MeshFilter>().mesh;
            //if ( !_mesh )
            //{
            //    _mesh = new UnityEngine.Mesh ( );
            //    GetComponent<MeshFilter> ( ).mesh = _mesh;
            //}
            var _mesh = new UnityEngine.Mesh();

            _mesh.Clear( );
            _mesh.vertices  = Vertices;
            _mesh.uv        = UV;
            _mesh.triangles = Triangles;
            _mesh.normals   = Normals;
            GetComponent <MeshFilter> ( ).mesh         = _mesh;
            GetComponent <MeshCollider> ( ).sharedMesh = _mesh;
        }
Пример #55
0
 public void Apply(UnityEngine.Mesh mesh)
 {
     mesh.Clear();
     if (vertices != null)
     {
         mesh.SetVertices(vertices);
     }
     if (triangles != null)
     {
         mesh.SetTriangles(triangles, 0);
     }
     if (normals != null)
     {
         if (normals.Count == vertices.Count)
         {
             mesh.SetNormals(normals);
         }
         else if (normals.Count > 0 && Batching.verbose > 0)
         {
             Debug.LogWarning("Skipping collider normals because some meshes were missing them.");
         }
     }
 }
Пример #56
0
 public void Apply(UnityEngine.Mesh mesh)
 {
     mesh.Clear();
     if (this.vertices != null)
     {
         mesh.SetVertices(this.vertices);
     }
     if (this.triangles != null)
     {
         mesh.SetTriangles(this.triangles, 0);
     }
     if (this.normals != null)
     {
         if (this.normals.Count == this.vertices.Count)
         {
             mesh.SetNormals(this.normals);
         }
         else if (this.normals.Count > 0 && Batching.verbose > 0)
         {
             Debug.LogWarning("Skipping mesh normals because some meshes were missing them.");
         }
     }
     if (this.tangents != null)
     {
         if (this.tangents.Count == this.vertices.Count)
         {
             mesh.SetTangents(this.tangents);
         }
         else if (this.tangents.Count > 0 && Batching.verbose > 0)
         {
             Debug.LogWarning("Skipping mesh tangents because some meshes were missing them.");
         }
     }
     if (this.colors32 != null)
     {
         if (this.colors32.Count == this.vertices.Count)
         {
             mesh.SetColors(this.colors32);
         }
         else if (this.colors32.Count > 0 && Batching.verbose > 0)
         {
             Debug.LogWarning("Skipping mesh colors because some meshes were missing them.");
         }
     }
     if (this.uv != null)
     {
         if (this.uv.Count == this.vertices.Count)
         {
             mesh.SetUVs(0, this.uv);
         }
         else if (this.uv.Count > 0 && Batching.verbose > 0)
         {
             Debug.LogWarning("Skipping mesh uvs because some meshes were missing them.");
         }
     }
     if (this.uv2 != null)
     {
         if (this.uv2.Count == this.vertices.Count)
         {
             mesh.SetUVs(1, this.uv2);
         }
         else if (this.uv2.Count > 0 && Batching.verbose > 0)
         {
             Debug.LogWarning("Skipping mesh uv2s because some meshes were missing them.");
         }
     }
     if (this.positions != null)
     {
         mesh.SetUVs(2, this.positions);
     }
 }
Пример #57
0
 public void Clear()
 {
     mesh1.Clear();
     mesh2.Clear();
 }
Пример #58
0
        public static void CopyFrom(this UnityEngine.Mesh mesh, List <GeneratedMeshContents> contents, List <int> triangleBrushes)
        {
            if (object.ReferenceEquals(contents, null))
            {
                throw new ArgumentNullException("contents");
            }

            if (contents.Count == 0)
            {
                mesh.Clear();
                return;
            }

            var bounds = new Bounds();

            sPositionsList.Clear();
            sNormalsList.Clear();
            sTangentsList.Clear();
            sUV0List.Clear();
            sBaseVertices.Clear();
            for (int i = 0; i < contents.Count; i++)
            {
                if (contents[i] == null ||
                    contents[i].positions.Length == 0 ||
                    contents[i].indices.Length == 0)
                {
                    continue;
                }

                sBaseVertices.Add(sPositionsList.Count);
                sPositionsList.AddRange(contents[i].positions);
                if (contents[i].normals.IsCreated)
                {
                    sNormalsList.AddRange(contents[i].normals);
                }
                if (contents[i].tangents.IsCreated)
                {
                    sTangentsList.AddRange(contents[i].tangents);
                }
                if (contents[i].uv0.IsCreated)
                {
                    sUV0List.AddRange(contents[i].uv0);
                }

                if (i == 0)
                {
                    bounds = contents[i].bounds;
                }
                else
                {
                    bounds.Encapsulate(contents[i].bounds);
                }
            }

            mesh.Clear(keepVertexLayout: true);
            mesh.SetVertices(sPositionsList);
            if (sNormalsList.Count == sPositionsList.Count)
            {
                mesh.SetNormals(sNormalsList);
            }
            if (sTangentsList.Count == sPositionsList.Count)
            {
                mesh.SetTangents(sTangentsList);
            }
            if (sUV0List.Count == sPositionsList.Count)
            {
                mesh.SetUVs(0, sUV0List);
            }

            mesh.subMeshCount = sBaseVertices.Count;
            for (int i = 0, n = 0; i < contents.Count; i++)
            {
                if (contents[i] == null ||
                    contents[i].indices.Length == 0)
                {
                    continue;
                }
                triangleBrushes.AddRange(contents[i].brushIndices);
                var triangles       = contents[i].indices.ToArray();
                var submesh         = n;
                var calculateBounds = false;
                int baseVertex      = sBaseVertices[n];
                //mesh.SetSubMesh()
                mesh.SetTriangles(triangles: triangles, submesh: submesh, calculateBounds: calculateBounds, baseVertex: baseVertex);
                n++;
            }
            mesh.bounds = bounds;
        }
Пример #59
0
 public void Apply(UnityEngine.Mesh mesh)
 {
     mesh.Clear();
     if (vertices != null)
     {
         mesh.SetVertices(vertices);
     }
     if (triangles != null)
     {
         mesh.SetTriangles(triangles, 0);
     }
     if (normals != null)
     {
         if (normals.Count == vertices.Count)
         {
             mesh.SetNormals(normals);
         }
         else if (normals.Count > 0 && Batching.verbose > 0)
         {
             Debug.LogWarning("Skipping renderer normals because some meshes were missing them.");
         }
     }
     if (tangents != null)
     {
         if (tangents.Count == vertices.Count)
         {
             mesh.SetTangents(tangents);
         }
         else if (tangents.Count > 0 && Batching.verbose > 0)
         {
             Debug.LogWarning("Skipping renderer tangents because some meshes were missing them.");
         }
     }
     if (colors32 != null)
     {
         if (colors32.Count == vertices.Count)
         {
             mesh.SetColors(colors32);
         }
         else if (colors32.Count > 0 && Batching.verbose > 0)
         {
             Debug.LogWarning("Skipping renderer colors because some meshes were missing them.");
         }
     }
     if (uv != null)
     {
         if (uv.Count == vertices.Count)
         {
             mesh.SetUVs(0, uv);
         }
         else if (uv.Count > 0 && Batching.verbose > 0)
         {
             Debug.LogWarning("Skipping renderer uvs because some meshes were missing them.");
         }
     }
     if (uv2 != null)
     {
         if (uv2.Count == vertices.Count)
         {
             mesh.SetUVs(1, uv2);
         }
         else if (uv2.Count > 0 && Batching.verbose > 0)
         {
             Debug.LogWarning("Skipping renderer uv2s because some meshes were missing them.");
         }
     }
     if (positions != null)
     {
         mesh.SetUVs(2, positions);
     }
 }
Пример #60
-5
		/**
		 *	Copy @src mesh values to @dest
		 */
		public static void Copy(Mesh dest, Mesh src)
		{
			dest.Clear();
			dest.vertices = src.vertices;

			List<Vector4> uvs = new List<Vector4>();

			src.GetUVs(0, uvs); dest.SetUVs(0, uvs);
			src.GetUVs(1, uvs); dest.SetUVs(1, uvs);
			src.GetUVs(2, uvs); dest.SetUVs(2, uvs);
			src.GetUVs(3, uvs); dest.SetUVs(3, uvs);

			dest.normals = src.normals;
			dest.tangents = src.tangents;
			dest.boneWeights = src.boneWeights;
			dest.colors = src.colors;
			dest.colors32 = src.colors32;
			dest.bindposes = src.bindposes;

			dest.subMeshCount = src.subMeshCount;

			for(int i = 0; i < src.subMeshCount; i++)
				dest.SetIndices(src.GetIndices(i), src.GetTopology(i), i);

			dest.name = z_Util.IncrementPrefix("z", src.name);
		}