Inheritance: MonoBehaviour
        /// <summary>
        /// Decompose the polygon into several smaller non-concave polygons.
        /// </summary>
        /// <param name="vertices">The polygon to decompose.</param>
        /// <param name="sheer">The sheer to use if you get bad results, try using a higher value.</param>
        /// <returns>A list of triangles</returns>
        public static List<Vertices> ConvexPartition(Vertices vertices, float sheer = 0.001f)
        {
            Debug.Assert(vertices.Count > 3);

            List<Point> compatList = new List<Point>(vertices.Count);

            foreach (Vector2 vertex in vertices)
            {
                compatList.Add(new Point(vertex.X, vertex.Y));
            }

            Triangulator t = new Triangulator(compatList, sheer);

            List<Vertices> list = new List<Vertices>();

            foreach (List<Point> triangle in t.Triangles)
            {
                Vertices outTriangles = new Vertices(triangle.Count);

                foreach (Point outTriangle in triangle)
                {
                    outTriangles.Add(new Vector2(outTriangle.X, outTriangle.Y));
                }

                list.Add(outTriangles);
            }

            return list;
        }
Exemple #2
0
    public void FillShape()
    {
        meshRenderer.enabled = true;

        Mesh mesh = new Mesh();

        Vector2[] points = polygonCollider2D.points;
        Vector3[] vertices = new Vector3[ polygonCollider2D.GetTotalPointCount() ];

        for( int j=0; j < polygonCollider2D.GetTotalPointCount(); j++ )
        {
            Vector2 actual = points[ j ];
            vertices[ j ] = new Vector3( actual.x, actual.y, 1 );
        }

        Triangulator tr = new Triangulator( points );
        int [] triangles = tr.Triangulate();

        mesh.vertices = vertices;
        mesh.triangles = triangles;

        MeshFilter mf = GetComponent<MeshFilter>();
        if( !mf )
        {
            mf = gameObject.AddComponent<MeshFilter>();
        }
        mf.mesh = mesh;
    }
Exemple #3
0
        private void Awake()
        {
            mf = GetComponent<MeshFilter>();
            if (mf != null)
            {
                //modify collider points to snipping tringle
                //poll.points

                Vector2[] vert2d = new Vector2[mf.mesh.vertexCount];

                for (int v = 0; v < mf.mesh.vertexCount; v++)
                {
                    vert2d[v] = new Vector2(mf.mesh.vertices[v].x, mf.mesh.vertices[v].y);
                }

                Triangulator tr = new Triangulator(vert2d);
                int[] indices = tr.Triangulate();
                Vector3[] vertices = new Vector3[indices.Length];
                for (int i = 0; i < vertices.Length; i++)
                {
                    vertices[i] = new Vector3(vertices[i].x, vertices[i].y, 0);
                }

                // Create the mesh
                Mesh msh = mf.mesh;
                msh.vertices = vertices;
                msh.triangles = indices;
                msh.RecalculateNormals();
                msh.RecalculateBounds();
                mf.mesh = msh;
                // mesh.mesh.triangles = newTriangles;
            }
        }
	void Start () {
		int pointCount = 0;
		
		PolygonCollider2D pc2 = gameObject.GetComponent<PolygonCollider2D>();
		pointCount = pc2.GetTotalPointCount();
		
		MeshFilter mf = GetComponent<MeshFilter>();
		Mesh mesh = new Mesh();
		
		
		Vector2[] points = pc2.points;
		Vector3[] vertices = new Vector3[pointCount];
		
		for(int j=0; j<pointCount; j++){
			Vector2 actual = points[j];
			vertices[j] = new Vector3(actual.x, actual.y, 0);
		}
		
		Triangulator tr = new Triangulator(points);
		int [] triangles = tr.Triangulate();
		
		
		mesh.vertices = vertices;
		mesh.triangles = triangles;
		
		mf.mesh = mesh;
	}
Exemple #5
0
    // Update is called once per frame
    void Update()
    {
        if (!Application.isPlaying) {
            triangulator = new Triangulator ();
            Vector2[] vertex = polyCollider.points;
            triangulator.UpdatePoints (vertex);
            int[] index = triangulator.Triangulate ();

            Vector3[] vertex3D = new Vector3[vertex.Length];
            for (int i = 0; i < vertex.Length; i++) {
                vertex3D [i] = vertex [i];
            }
            Vector2[] uvs = new Vector2[vertex.Length];

            for (int i=0; i < uvs.Length; i++) {
                uvs [i] = new Vector2 (vertex [i].x, vertex [i].y);
            }

            Mesh msh = new Mesh ();
            msh.vertices = vertex3D;
            msh.triangles = index;
            msh.uv = uvs;
            msh.RecalculateBounds ();
            msh.RecalculateNormals ();

            mshFilter.mesh = msh;
        }
    }
Exemple #6
0
        /// <summary>
        /// Decompose the polygon into several smaller non-concave polygons.
        /// </summary>
        /// <param name="vertices">The polygon to decompose.</param>
        /// <param name="sheer">The sheer to use if you get bad results, try using a higher value.</param>
        /// <returns>A list of trapezoids</returns>
        public static List<Vertices> ConvexPartitionTrapezoid(Vertices vertices, float sheer = 0.001f)
        {
            List<Point> compatList = new List<Point>(vertices.Count);

            foreach (Vector2 vertex in vertices)
            {
                compatList.Add(new Point(vertex.X, vertex.Y));
            }

            Triangulator t = new Triangulator(compatList, sheer);

            List<Vertices> list = new List<Vertices>();

            foreach (Trapezoid trapezoid in t.Trapezoids)
            {
                Vertices verts = new Vertices();

                List<Point> points = trapezoid.GetVertices();
                foreach (Point point in points)
                {
                    verts.Add(new Vector2(point.X, point.Y));
                }

                list.Add(verts);
            }

            return list;
        }
Exemple #7
0
	public void meshInit() {
		Vector2[] vertices = new Vector2[points.Count + 4];
		int j = 0;
		for (; j < points.Count; j++) {
			Point p = points[j];
			double x = centre - Math.Cos (p.getTheta()) * p.getRad();
			double y = -Camera.main.orthographicSize - Camera.main.orthographicSize * 0.05d + (Math.Sin (p.getTheta()) * p.getRad());
			vertices[j] = new Vector2((float)x,(float) y);
		}
		vertices [j++] = new Vector2 ((float)+ size,(float) -size);
		vertices [j++] = new Vector2 ((float)size, (float)size);
		vertices [j++] = new Vector2 ((float)- size, (float)size);
		vertices [j++] = new Vector2 ((float)- size, (float)- size);

		Triangulator t = new Triangulator (vertices);
		int[] indices = t.Triangulate ();
		Vector3[] v3 = new Vector3[vertices.Length];
		for (int i = 0; i < v3.Length; i++) {
			v3[i] = new Vector3(vertices[i].x, vertices[i].y, 0);
		}


		Mesh m = new Mesh ();
		m.vertices = v3;
		m.triangles = indices;
		m.RecalculateNormals ();
		m.RecalculateBounds ();

		
		//Add to stuff
		this.GetComponent<MeshFilter> ().mesh = m;
	}
Exemple #8
0
    // Use this for initialization
    void Start()
    {
        mshRenderer = GetComponent<MeshRenderer>();
        mshFilter = GetComponent<MeshFilter>();
        polyCollider = GetComponent<PolygonCollider2D>();

        triangulator = new Triangulator ();
        if(polyCollider.points.Length == 0) CreateDefaultPlatform ();
    }
Exemple #9
0
    public void updateMesh()
    {
        mesh = GetComponent<MeshFilter> ().mesh;
        edgeCollider = GetComponent<EdgeCollider2D> ();

        meshBkgFilter = gameObject.transform.Find ("Background").GetComponent<MeshFilter> ();
        meshBkg = meshBkgFilter.mesh;

        float x = 0;
        float y = 0;
        float z = (float) gameObject.transform.position.z;

        if (relativePosition) {
            x = (float) gameObject.transform.position.x;
            y = (float) gameObject.transform.position.y;
        }

        // Use the triangulator to get indices for creating triangles
        Triangulator tr = new Triangulator(vertices);
        int[] indices = tr.Triangulate();

        // Create the Vector3 and collider vertices
        Vector3[] vertices3 = new Vector3[vertices.Length];
        Vector2[] points = new Vector2[vertices.Length];
        for (int i=0; i<vertices.Length; i++) {
            vertices3[i] = new Vector3(x + vertices[i].x, y + vertices[i].y, z);
            points[i] = new Vector2(x + vertices[i].x, y + vertices[i].y);
        }

        Vector2[] uvs = new Vector2[vertices3.Length];
        int i2 = 0;
        while (i2 < uvs.Length) {
            uvs[i2] = new Vector2(vertices3[i2].x, vertices3[i2].z);
            i2++;
        }

        edgeCollider.points = points;

        mesh.vertices = vertices3;
        mesh.triangles = indices;
        mesh.uv = uvs;
        mesh.RecalculateNormals();
        mesh.RecalculateBounds();

        //Background (reverse terrain)
        meshBkg.vertices = vertices3;
        meshBkg.triangles = indices;
        meshBkg.uv = uvs;
        meshBkg.RecalculateNormals();
        meshBkg.RecalculateBounds();
        ReverseNormals (meshBkgFilter);
    }
Exemple #10
0
    void MESH_init()
    {
        // Create Vector2 vertices
        vertices2D = new List<Vector2> ();
        vertices2D.Add (new Vector2 (0, 0));
        vertices2D.Add (new Vector2 (-FOV_length * .5f, FOV_width));
        vertices2D.Add (new Vector2 (0, FOV_width));
        vertices2D.Add (new Vector2 (FOV_length * .5f, FOV_width));

        // Use the triangulator to get indices for creating triangles
        Triangulator tr = new Triangulator (vertices2D);
        trias = tr.Triangulate ();

        // Create the Vector3 vertices
        verts = new Vector3[vertices2D.Count];
        for (int i=0; i<verts.Length; i++) {
            verts [i] = new Vector3 (vertices2D [i].x, 0, vertices2D [i].y);
        }

        // Create the mesh
        mesh = new Mesh ();
        mesh.vertices = verts;
        mesh.triangles = trias;
        mesh.uv = vertices2D.ToArray ();

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

        if (mat == null) {
            mat = new Material (Shader.Find ("Transparent/Diffuse"));
            //mat.mainTexture = texture;
            Color c = Color.green; c = new Color(c.r,c.g,c.b,.2f);
            mat.color = c; //new Color(1,.5f,0,.5f);
        }

        meshRenderer = (MeshRenderer)gameObject.GetComponent (typeof(MeshRenderer));
        if (meshRenderer == null)
            meshRenderer = (MeshRenderer)gameObject.AddComponent (typeof(MeshRenderer));

        meshFilter = (MeshFilter)gameObject.GetComponent (typeof(MeshFilter));
        if (meshFilter == null)
            meshFilter = (MeshFilter)gameObject.AddComponent (typeof(MeshFilter));
        meshFilter.mesh = mesh;
        meshRenderer.material = mat;

        meshCollider = (MeshCollider)gameObject.GetComponent (typeof(MeshCollider));
        if (meshCollider == null) {
            meshCollider = (MeshCollider)gameObject.AddComponent (typeof(MeshCollider));
        }
        meshCollider.sharedMesh = mesh;
        meshCollider.isTrigger = true;
    }
Exemple #11
0
    void Start()
    {
        switch (gameObject.GetComponent<PlayerController> ().playerType) {

        case 0:
            pc2 = squareCollider;
            break;

        case 1:
            //pc2 = circleCollider;
            gameObject.GetComponent<MeshRenderer>().enabled = false;
            break;

        case 2:
            pc2 = triangleCollider;
            break;

        case 3:
            pc2 = trapezoidCollider;
            break;

        case 4:
            pc2 = rectangleCollider;
            break;

        case 5:
            pc2 = starCollider;
            break;
        }

        // don't act if type is circle
        if (gameObject.GetComponent<PlayerController> ().playerType != 1){
        //Render thing
        int pointCount = 0;
        pointCount = pc2.GetTotalPointCount();
        MeshFilter mf = GetComponent<MeshFilter>();
        Mesh mesh = new Mesh();
        Vector2[] points = pc2.points;
        Vector3[] vertices = new Vector3[pointCount];
        for(int j=0; j<pointCount; j++){
            Vector2 actual = points[j];
            vertices[j] = new Vector3(actual.x, actual.y, 0);
        }
        Triangulator tr = new Triangulator(points);
        int [] triangles = tr.Triangulate();
        mesh.vertices = vertices;
        mesh.triangles = triangles;
        mf.mesh = mesh;
        //Render thing
        }
    }
Exemple #12
0
        private int[] GetMeshTriangles()
        {
            List<Vector2> vertices = new List<Vector2>();
            foreach (Vector3 v in _PlanetVertices) {
                vertices.Add((Vector2) v);
            }
            Triangulator triangulator = new Triangulator(vertices.ToArray());

            //TODO: hack, trying to reuse me cast
            PolygonCollider2D col = gameObject.AddComponent<PolygonCollider2D>();
            col.SetPath(0, vertices.ToArray());

            return triangulator.Triangulate();
        }
 public static Mesh CreateMesh(Vector2[] poly)
 {
     Triangulator triangulator = new Triangulator(poly);
     int[] tris = triangulator.Triangulate();
     Mesh m = new Mesh();
     Vector3[] vertices = new Vector3[poly.Length * 2];
     for (int i = 0; i < poly.Length; i++)
     {
         vertices[i].x = poly[i].x;
         vertices[i].y = poly[i].y;
         vertices[i].z = -10;
         vertices[i + poly.Length].x = poly[i].x;
         vertices[i + poly.Length].y = poly[i].y;
         vertices[i + poly.Length].z = 10;
     }
     int[] triangles = new int[tris.Length * 2 + poly.Length * 6];
     int count_tris = 0;
     for (int i = 0; i < tris.Length; i += 3)
     {
         triangles[i] = tris[i];
         triangles[i + 1] = tris[i + 1];
         triangles[i + 2] = tris[i + 2];
     }
     count_tris += tris.Length;
     for (int i = 0; i < tris.Length; i += 3)
     {
         triangles[count_tris + i] = tris[i + 2] + poly.Length;
         triangles[count_tris + i + 1] = tris[i + 1] + poly.Length;
         triangles[count_tris + i + 2] = tris[i] + poly.Length;
     }
     count_tris += tris.Length;
     for (int i = 0; i < poly.Length; i++)
     {
         int n = (i + 1) % poly.Length;
         triangles[count_tris] = i;
         triangles[count_tris + 1] = i + poly.Length;
         triangles[count_tris + 2] = n;
         triangles[count_tris + 3] = n;
         triangles[count_tris + 4] = n + poly.Length;
         triangles[count_tris + 5] = i + poly.Length;
         count_tris += 6;
     }
     m.vertices = vertices;
     m.triangles = triangles;
     m.RecalculateNormals();
     m.RecalculateBounds();
     m.Optimize();
     return m;
 }
Exemple #14
0
    // Use this for initialization
    void Start() {

        // Create the vertices of the plant
        List<Vector2> vertices2D = new List<Vector2>();
        int halfPoints = NUMBER_OF_VERTICES / 2; // Number of points for one side of the plant
        for (int i = 0; i < NUMBER_OF_VERTICES; i++) {
            int sideFactor = i < halfPoints ? 1 : -1; // This factor helps to draw the plant with one single stroke
            float percentOfCompletion = ((float)(i % halfPoints)) / ((float)halfPoints - 1f); // Percentage of completion of a single side

            if(sideFactor > 0) // Right side of the plant
                vertices2D.Add(new Vector2(shaftCurve.Evaluate(percentOfCompletion) * width * sideFactor, heigth * percentOfCompletion));
            else // Left side of the plant
                vertices2D.Add(new Vector2(shaftCurve.Evaluate(1 - percentOfCompletion) * width * sideFactor, heigth * (1 - percentOfCompletion)));
        }

        // Use the triangulator to get indices for creating triangles
        Triangulator tr = new Triangulator(vertices2D.ToArray());
        int[] indices = tr.Triangulate();

        // Create the Vector3 vertices
        Vector3[] vertices = new Vector3[vertices2D.Count];
        for (int i = 0; i < vertices.Length; i++) {
            vertices[i] = new Vector3(vertices2D[i].x, vertices2D[i].y, 0);
        }

        // Create the mesh
        Mesh msh = new Mesh();
        msh.vertices = vertices;
        msh.triangles = indices;

        Vector2[] uvs = new Vector2[vertices.Length];

        for (int i = 0; i < uvs.Length; i++)
        {
            uvs[i] = new Vector2(vertices[i].x, vertices[i].z);
        }
        msh.uv = uvs;

        msh.RecalculateNormals();
        msh.RecalculateBounds();
        msh.Optimize();

        // Set up game object with mesh;
        MeshFilter filter = GetComponent<MeshFilter>();
        filter.mesh = msh;


    }
    public static void create(string name, List<Vector2> verticesList)
    {
        GameObject obstacle = new GameObject (name, typeof(MeshFilter), typeof(MeshRenderer));
        MeshFilter mesh_filter = obstacle.GetComponent<MeshFilter> ();

        obstacle.transform.position = new Vector3 (0, 0.01f, 0);

        var renderer = obstacle.GetComponent<Renderer>();
        renderer.sharedMaterial = new Material (Shader.Find ("Transparent/Diffuse"));
        renderer.sharedMaterial.color = new Color (1, 0, 0, .3f);

        Vector2[] vertices2D = verticesList.ToArray();

        // Use the triangulator to get indices for creating triangles
        Triangulator tr = new Triangulator(vertices2D);
        int[] indicesArray = tr.Triangulate();
        List<int> indices = new List<int>();
        for (int i = 0;i<indicesArray.Length;i++) {
            indices.Add (indicesArray[i]);
        }

        // Create the Vector3 vertices
        List<Vector3> vertices = new List<Vector3>();

        for (int i=0; i<vertices2D.Length; i++) {
            vertices.Add (new Vector3(vertices2D[i].x, 0, vertices2D[i].y));
        }

        // Create the mesh
        Mesh mesh = new Mesh();

        mesh.vertices = vertices.ToArray();
        mesh.uv = verticesList.ToArray();
        mesh.triangles = indices.ToArray();
        mesh.RecalculateNormals();
        mesh.RecalculateBounds();

        //flip if needed
        if (mesh.normals [0].y == -1) {
            indices.Reverse ();
            mesh.triangles = indices.ToArray ();
            mesh.RecalculateNormals();
        }

        mesh_filter.mesh = mesh;
        GeometryLoader gl = GameObject.Find ("GeometryLoader").GetComponent<GeometryLoader> ();
        gl.setWorldAsParent (obstacle);
    }
    public void Generate()
    {
        // Create Vector2 vertices
        Vector2[] vertices2D = new Vector2[] { };
        foreach (Vector3 point in points)
        {
            point_pos.Add(new Vector2(point.x,point.z));
        }
        vertices2D = point_pos.ToArray();
        // Use the triangulator to get indices for creating triangles
        Triangulator tr = new Triangulator(vertices2D);
        int[] indices = tr.Triangulate();

        // Create the Vector3 vertices
        Vector3[] vertices = new Vector3[vertices2D.Length];
        for (int i = 0; i < vertices.Length; i++)
        {
            vertices[i] = new Vector3(vertices2D[i].x, 0, vertices2D[i].y);
        }

        // Create the mesh
        Mesh msh = new Mesh();
        msh.vertices = vertices;
        msh.triangles = indices;
        msh.RecalculateNormals();
        msh.RecalculateBounds();

        // Set up game object with mesh;
        if(gameObject.GetComponent<MeshRenderer>() == null) {
            gameObject.AddComponent<MeshRenderer>();
            gameObject.AddComponent<MeshFilter>();
        }
        MeshFilter filter = gameObject.GetComponent<MeshFilter> ();
        filter.mesh = msh;

        Mesh mesh = GetComponent<MeshFilter>().mesh;
        Vector3[] UVvertices = mesh.vertices;
        Vector2[] uvs = new Vector2[vertices.Length];

        for (int i = 0; i < uvs.Length; i++)
        {
            uvs[i] = new Vector2(UVvertices[i].x / 10, UVvertices[i].z / 10);
        }
        mesh.uv = uvs;
    }
Exemple #17
0
    public void UpdateMesh()
    {
        var poly = GetComponent<PolygonCollider2D>();
        var tris = new Triangulator(poly.points);
        var indices = tris.Triangulate();

        Mesh mesh = new Mesh();
        Vector3[] points3 = new Vector3[poly.points.Length];
        for (int i = 0; i < poly.points.Length; i++)
            points3[i] = poly.points[i];

        Vector2[] uv = new Vector2[poly.points.Length];
        for (int i = 0; i < poly.points.Length; i++)
            uv[i] = transform.TransformPoint(poly.points[i]);
        mesh.vertices = points3;
        mesh.uv = uv;
        mesh.triangles = indices;

        GetComponent<MeshFilter>().mesh = mesh;
    }
    void Start()
    {
        // Create Vector2 vertices
        Vector2[] vertices2D = new Vector2[] {
            new Vector2(0,0),
            new Vector2(0,50),
            new Vector2(50,50),
            new Vector2(50,100),
            new Vector2(0,100),
            new Vector2(0,150),
            new Vector2(150,150),
            new Vector2(150,100),
            new Vector2(100,100),
            new Vector2(100,50),
            new Vector2(150,50),
            new Vector2(150,0),
        };

        // Use the triangulator to get indices for creating triangles
        Triangulator tr = new Triangulator(vertices2D);
        int[] indices = tr.Triangulate();

        // Create the Vector3 vertices
        Vector3[] vertices = new Vector3[vertices2D.Length];
        for (int i = 0; i < vertices.Length; i++)
        {
            vertices[i] = new Vector3(vertices2D[i].x, vertices2D[i].y, 0);
        }

        // Create the mesh
        Mesh msh = new Mesh();
        msh.vertices = vertices;
        msh.triangles = indices;
        msh.RecalculateNormals();
        msh.RecalculateBounds();

        // Set up game object with mesh;
        gameObject.AddComponent(typeof(MeshRenderer));
        MeshFilter filter = gameObject.AddComponent(typeof(MeshFilter)) as MeshFilter;
        filter.mesh = msh;
    }
    public void CreateMesh(Vector2[] newPoints, Material material)
    {
        // Use the triangulator to get indices for creating triangles
        Triangulator tr = new Triangulator(newPoints);
        int[] indices = tr.Triangulate();

        // Create the Vector3 vertices
        Vector3[] vertices = new Vector3[newPoints.Length];
        for (int i=0; i<vertices.Length; i++) {
            vertices[i] = new Vector3(newPoints[i].x, newPoints[i].y, 0);
        }

        // Create the New Mesh
        this.mesh = new Mesh();
        mesh.vertices = vertices;
        mesh.triangles = indices;
        mesh.RecalculateNormals();
        mesh.RecalculateBounds();

        //Set up texture coordinate for New Mesh
        Vector2[] uvs = new Vector2[vertices.Length];
        for(int i = 0; i<uvs.Length; i++){
            uvs[i] = new Vector2(vertices[i].x, vertices[i].y);
        }
        mesh.uv = uvs;

        // Set up game object with mesh;
        if(GetComponent<MeshRenderer>()==null)
        gameObject.AddComponent(typeof(MeshRenderer));

        if(GetComponent<MeshFilter>()==null)
        gameObject.AddComponent(typeof(MeshFilter));

        MeshFilter filter = GetComponent<MeshFilter>() as MeshFilter;
        filter.mesh = this.mesh;
        MeshRenderer mRenderer = GetComponent<MeshRenderer>() as MeshRenderer;
        mRenderer.material = material;

        //NOTE HARD CODING !!!
        mRenderer.sortingLayerName = "Foreground";
    }
	/// <summary>
	/// Sets the collider2D according to an array of vector3s
	/// </summary>
	/// <param name="vertices">The vector3 vertex locations of the district shape</param>
	public void SetCollider(Vector3[] vertices)
	{
		Vector2[] temp = new Vector2[vertices.Length];
		Vector3 tempTemp; 
		for (int i = 0; i < vertices.Length; i++) {
			//take just the relevant x and z coordinates...
			temp[i] = new Vector2(vertices[i].x, vertices[i].z); 
			//And now we have to transform them into local coordinates, for use in the collider
			tempTemp = new Vector3(temp[i].x, 0, temp[i].y); 
			tempTemp = this.transform.InverseTransformPoint(tempTemp); 
			temp[i] = new Vector2(tempTemp.x, tempTemp.z); 
		}
		//area.points = temp; 
		Triangulator triangluator = new Triangulator (temp); 
		mesh.triangles = triangluator.Triangulate (); 
		mesh.RecalculateNormals (); 
		//this.gameObject.AddComponent<MeshCollider>(mesh);
		MeshCollider mCol = this.gameObject.AddComponent<MeshCollider> (); 
		mCol.sharedMesh = mesh; 
		//mCol.isTrigger = true; 
	}
Exemple #21
0
    private static Mesh GetTriangleMeshBasic(Vector2[] vxs)
    {
        // convert to 3D space
        var vxs3d = System.Array.ConvertAll <Vector2, Vector3>(vxs, v => v);

        // triangulate polygon
        var triangulator = new Triangulator(vxs);
        var indices      = triangulator.Triangulate();

        // create mesh
        var m = new Mesh();

        // assign to mesh
        m.vertices  = vxs3d;
        m.triangles = indices;

        // recompute geometry
        // QUESTION why do we need bounds?
        m.RecalculateNormals();
        m.RecalculateBounds();

        return(m);
    }
    void CreatePolygon()
    {
        // Use the triangulator to get indices for creating triangles
        Triangulator tr = new Triangulator(vertices2D);
        int[] indices = tr.Triangulate();

        // Create the Vector3 vertices
        Vector3[] vertices = new Vector3[vertices2D.Length];
        for (int i=0; i<vertices.Length; i++) {
            vertices[i] = new Vector3(vertices2D[i].x, 0.0f, vertices2D[i].y);
        }

        // Create the mesh
        Mesh msh = new Mesh();
        msh.vertices = vertices;
        msh.triangles = indices;
        msh.RecalculateNormals();
        msh.RecalculateBounds();

        // Set up game object with mesh;
        MeshFilter filter = gameObject.GetComponent(typeof(MeshFilter)) as MeshFilter;
        filter.mesh = msh;
    }
	Mesh buildMesh(params Vector2[] points) {
		// Use the triangulator to get indices for creating triangles
		Triangulator tr = new Triangulator(points);
		int[] indices = tr.Triangulate();
		
		// Create the Vector3 vertices
		Vector3[] vertices = new Vector3[points.Length];
		for (int i = 0; i < vertices.Length; i++) {
			vertices[i] = new Vector3(points[i].x, points[i].y, 0);
		}
		
		// Create the mesh
		Mesh msh = new Mesh();
		msh.vertices = vertices;
		msh.triangles = indices;
		msh.RecalculateNormals();
		msh.RecalculateBounds();
		
		
		MeshFilter mf = GetComponent<MeshFilter>();
		mf.mesh = msh;
		return msh;
	}
    public void MakeShape(Vector2[] vertices2D, Color color)
    {
        var vertices3D   = System.Array.ConvertAll <Vector2, Vector3>(vertices2D, v => v);
        var triangulator = new Triangulator(vertices2D);
        var indices      = triangulator.Triangulate();
        var colors       =
            Enumerable.Range(0, vertices3D.Length)
            .Select(i => color)
            .ToArray();
        var mesh = new Mesh {
            vertices  = vertices3D,
            triangles = indices,
            colors    = colors
        };
        GameObject gameObject = new GameObject();

        mesh.RecalculateNormals();
        mesh.RecalculateBounds();
        if (gameObject.GetComponent <MeshRenderer>() == null)
        {
            gameObject.AddComponent <MeshRenderer>().material = new Material(Shader.Find("Sprites/Default"));
        }
        if (gameObject.GetComponent <MeshFilter>() == null)
        {
            gameObject.AddComponent <MeshFilter>().mesh = mesh;
        }
        if (gameObject.GetComponent <Rigidbody2D>() == null)
        {
            gameObject.AddComponent <Rigidbody2D>().mass = 700f;
        }
        if (gameObject.GetComponent <PolygonCollider2D>() == null)
        {
            gameObject.AddComponent <PolygonCollider2D>().points = positions.ToArray();
        }
        GetComponent <LineRenderer>().SetVertexCount(0);
        positions = new List <Vector2>();
    }
    public static void create(string name, List <Vector2> verticesList, float zOffset)
    {
        Material sideMaterial;

        GeometryLoader gl = GameObject.Find("GeometryLoader").GetComponent <GeometryLoader>();

        sideMaterial = gl.theme.getWallsMaterialST();

        GameObject floor       = new GameObject(name, typeof(MeshFilter), typeof(MeshRenderer));
        MeshFilter mesh_filter = floor.GetComponent <MeshFilter>();
        Mesh       mesh        = mesh_filter.mesh;

        floor.GetComponent <Renderer>().material = sideMaterial;
        mesh.Clear();

        floor.GetComponent <Renderer>().shadowCastingMode = UnityEngine.Rendering.ShadowCastingMode.Off;
        floor.GetComponent <Renderer>().material          = sideMaterial;

        Vector2[] vertices2D = verticesList.ToArray();

        Triangulator tr = new Triangulator(vertices2D);

        int[] indices = tr.Triangulate();

        // Create the Vector3 vertices
        Vector3[] vertices = new Vector3[vertices2D.Length];
        for (int i = 0; i < vertices.Length; i++)
        {
            vertices[i] = new Vector3(vertices2D[i].x, zOffset + 0.05f, vertices2D[i].y);
        }

        // Create the mesh
        mesh           = TangentHelper.TangentSolver(mesh);
        mesh.vertices  = vertices;
        mesh.triangles = indices;
        mesh.RecalculateBounds();
    }
    /// <summary>
    /// Generate surface using LineRenderer and edgeCollider2D
    /// </summary>
    private void GenerateSurface()
    {
        List <Vector2> points = new List <Vector2>();

        lineRenderer.positionCount   = _generatedPoints.Count;
        lineRenderer.widthMultiplier = lineWidth;

        for (int i = 0; i < _generatedPoints.Count; ++i)
        {
            Vector2 point = _generatedPoints[i];
            points.Add(point);
            lineRenderer.SetPosition(i, point);
        }
        edgeCollider2D.points = points.ToArray();

        _generatedPoints[0] = (new Vector2(_generatedPoints[0].x, _generatedPoints[0].y - 100));
        _generatedPoints.Add(new Vector2(_generatedPoints[_generatedPoints.Count - 1].x, _generatedPoints[_generatedPoints.Count - 1].y - 100));

        //// Triangulation of the surface below lineRenderer
        Triangulator tr = new Triangulator(_generatedPoints.ToArray());

        int[]     indices  = tr.Triangulate();
        Vector3[] vertices = new Vector3[_generatedPoints.Count];
        for (int i = 0; i < vertices.Length; i++)
        {
            vertices[i] = new Vector3(_generatedPoints[i].x, _generatedPoints[i].y, 0);
        }

        Mesh mesh = new Mesh();

        mesh.vertices  = vertices;
        mesh.triangles = indices;
        mesh.RecalculateNormals();
        mesh.RecalculateBounds();

        meshFilter.mesh = mesh;
    }
    // Start is called before the first frame update
    void Start()
    {
        raycastAngle = 360 / (photonRaycastTrajectorySpokes + 1);
        hitList      = new Vector2[photonRaycastTrajectorySpokes + 1];

        //Creating triangles for mesh using Triangulator
        //Created by runevision
        //Available at http://wiki.unity3d.com/index.php?title=Triangulator
        //Usage based on example on wiki.
        Triangulator tr = new Triangulator(hitList);

        int[]     indices  = tr.Triangulate();
        Vector3[] vertices = new Vector3[hitList.Length];
        for (int i = 0; i < vertices.Length; i++)
        {
            vertices[i] = new Vector3(hitList[i].x, hitList[i].y, 0);
        }

        //Create the new mesh
        Mesh msh = new Mesh();

        msh.vertices  = vertices;
        msh.triangles = indices;
        msh.RecalculateNormals();
        msh.RecalculateBounds();
        //Set the new mesh to be the gameobject mesh.
        GetComponent <MeshFilter>().mesh = msh;

        //Create layermasks
        wallMask = LayerMask.GetMask("Walls");

        //Set photon distance
        photonDistance = initialPhotonDistance;
        //Start the subroutines
        StartCoroutine("photonRandomizer");
        StartCoroutine("expandPhotonDistance");
    }
Exemple #28
0
    GameObject CreateMesh(string meshPartName, Vector3[] newVerts)
    {
        // Convert from 3d to 2d
        Vector2[] newVerts2D = new Vector2[newVerts.Length];

        for (int i = 0; i < newVerts2D.Length; i++)
        {
            newVerts2D[i] = new Vector2(newVerts[i].x, newVerts[i].y);
        }

        Triangulator tr = new Triangulator(newVerts2D);

        int[] indices = tr.Triangulate();

        // Create vector 3 vertices
        Vector3[] vertices = new Vector3[newVerts2D.Length];
        for (int i = 0; i < vertices.Length; i++)
        {
            vertices[i] = new Vector3(newVerts2D[i].x, newVerts2D[i].y, 0f);
        }

        // Create the mesh
        Mesh newMesh = new Mesh();

        newMesh.vertices  = vertices;
        newMesh.triangles = indices;
        newMesh.RecalculateNormals();
        newMesh.RecalculateBounds();

        // Setup gameobject with mesh
        GameObject MeshObject = new GameObject(meshPartName, typeof(MeshFilter), typeof(MeshRenderer));

        MeshObject.GetComponent <MeshFilter>().mesh       = newMesh;
        MeshObject.GetComponent <MeshRenderer>().material = MatToApply;

        return(MeshObject);
    }
Exemple #29
0
    /// <summary>
    /// Creates and returns a circle mesh given two vertices on its center 
    /// and any outer edge point.
    /// </summary>
    private static Mesh CircleMesh(Vector2 v0, Vector2 v1, Color fillColor)
    {
        var radius = Vector2.Distance(v0, v1);

        // We want to make sure that the circle appears to be curved.
        // This can be approximated by drawing a regular polygon with lots of segments.
        // The number of segments can be increased based on the radius so that large circles also appear curved.
        // We use an offset and multiplier to create a tunable linear function.
        const float segmentOffset = 40f;
        const float segmentMultiplier = 5f;
        var numSegments = (int) (radius * segmentMultiplier + segmentOffset);

        // Create an array of points arround a cricle
        var circleVertices = Enumerable.Range(0, numSegments).Select(i => {
            var theta = 2 * Mathf.PI * i / numSegments;
            return new Vector2(Mathf.Cos(theta), Mathf.Sin(theta)) * radius;
            }).ToArray();

        // Find all the triangles in the shape
        var triangles = new Triangulator(circleVertices).Triangulate();

        // Assign each vertex the fill color
        var colors = Enumerable.Repeat(fillColor, circleVertices.Length).ToArray();

        var mesh = new Mesh {
            name = "Circle",
            vertices = circleVertices.ToVector3(),
            triangles = triangles,
            colors = colors
        };

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

        return mesh;
    }
Exemple #30
0
    private void CreateBuilding(WayStruct str)
    {
        GameObject go = new GameObject($"building_{str.id.ToString()}");

        go.AddComponent <MeshFilter>();
        go.AddComponent <MeshRenderer>();

        var  mf   = go.GetComponent <MeshFilter>();
        Mesh mesh = new Mesh();

        mf.mesh = mesh;


        Vector2[] points = str.nodes.Select(x => x.position).ToArray();
        points = points.Take(points.Length - 1).ToArray();
        Vector2 scaleVec = new Vector2(10000, 10000);

        for (int n = 0; n < points.Length; n++)
        {
            points[n] = new Vector2((points[n].x - minlat) * -1f, points[n].y - minlon);
            points[n].Scale(scaleVec);
        }
        Triangulator tr = new Triangulator(points);

        int[]     indices = tr.Triangulate();
        Vector3[] vec3d   = new Vector3[points.Length];
        for (int i = 0; i < vec3d.Length; i++)
        {
            vec3d[i] = new Vector3(points[i].x, 0, points[i].y);
        }

        mesh.vertices  = vec3d;
        mesh.triangles = indices;
        mesh.RecalculateNormals();
        mesh.RecalculateBounds();
        go.GetComponent <MeshRenderer>().material = buildingMaterial;
    }
Exemple #31
0
    public static Mesh polygon(float size, int corners)
    {
        if (corners == 4)
        {
            Debug.LogWarning("SimplePolygon: This will just create a simple square, are you sure you dont want to use rectangle()?");
        }
        if (corners < 3)
        {
            Debug.LogError("SimplePolygon: The number of corners is lower than 3, which will not create a real Polygon");
        }
        float angle = 360 / corners;

        Vector2[] vertices2D = new Vector2[corners];
        vertices2D[0] = new Vector2(size, 0);
        for (int i = 1; i < vertices2D.Length; i++)
        {
            vertices2D[i] = Quaternion.Euler(0, 0, -angle) * vertices2D[i - 1];
        }

        Triangulator tr = new Triangulator(vertices2D);

        int[] triangles = tr.Triangulate();

        Vector3[] vertices = new Vector3[corners];
        for (int i = 0; i < vertices.Length; i++)
        {
            vertices[i] = new Vector3(vertices2D[i].x, 0, vertices2D[i].y);
        }

        Mesh mesh = new Mesh();

        mesh.vertices  = vertices;
        mesh.triangles = triangles;
        mesh.RecalculateNormals();
        mesh.RecalculateBounds();
        return(mesh);
    }
Exemple #32
0
        // [Test]
        // disabled this test because there are issues with OSGeo.OGR dependency on buildserver
        public void FirstTestCityGml()
        {
            Ogr.RegisterAll();
            // source: Sample input files: https://www.opengeodata.nrw.de/produkte/geobasis/3dg/lod2_gml/
            var file           = @"./testdata/LoD2_280_5657_1_NW.gml";
            var gmlDriver      = Ogr.GetDriverByName("GML");
            var dsGml          = gmlDriver.Open(file, 0);
            var numberOfLayers = dsGml.GetLayerCount();

            Assert.IsTrue(numberOfLayers == 1);
            var buildingLayer = dsGml.GetLayerByName("building");
            var featuresGml   = buildingLayer.GetFeatureCount(0);

            Assert.IsTrue(featuresGml == 82);

            // take first geometry
            var featureGml = buildingLayer.GetNextFeature();

            var geometry = featureGml.GetGeometryRef();
            var wkt      = string.Empty;

            geometry.ExportToWkt(out wkt);
            Assert.IsTrue(wkt.Contains("MULTILINESTRING"));
            var multilinestring = (MultiLineString)Wkx.Geometry.Deserialize <WktSerializer>(wkt);

            Assert.IsTrue(multilinestring.Geometries.Count == 5);

            var polyhedral = multilinestring.ToPolyhedralSurface();

            var triangulatedPolyhedral = Triangulator.Triangulate(polyhedral);

            // todo: improve results...
            // turns out the mulitlinestrings are not the solids...
            // so the following gltf is a mess
            // needs something different for parsing gml
            GltfCreator.CreateGltf(triangulatedPolyhedral, @"gml.gltf");
        }
Exemple #33
0
    /*
     * Create a polygonal mesh, used for structures such as water
     */
    public static Mesh CreatePolygonMesh(JSONNode coords, CoordBoundingBox bounds)
    {
        // Keep normals and vertices in positions in 3d space
        List <Vector3> normals  = new List <Vector3> ();
        List <Vector3> vertices = new List <Vector3> ();

        // The triangulator can only handle 2d shapes so simulate one
        List <Vector2> triangulation = new List <Vector2> ();

        for (int i = 0; i < coords.Count - 1; i++)
        {
            // Store the vertex for the triangulator
            Vector2 vertex = bounds.Interpolate(float.Parse(coords [i] [1].Value), float.Parse(coords [i] [0].Value));
            triangulation.Add(vertex);

            // Add the vertex plus a y position to allow for 3d space
            vertices.Add(new Vector3(vertex.x, 0, vertex.y));

            // Normals should always point up on this flat surface
            normals.Add(Vector3.up);
        }

        // Iject triangulation points and create a new base mesh
        Triangulator t = new Triangulator(triangulation.ToArray());
        Mesh         m = new Mesh();

        // Store vertices and get triangles from the triangulator
        m.vertices  = vertices.ToArray();
        m.triangles = t.Triangulate();
        m.normals   = normals.ToArray();

        // Recalculate mesh properties
        m.RecalculateBounds();
        m.RecalculateNormals();

        return(m);
    }
    public void Visualize(List <Line> edges)
    {
        List <Vector2> vertices2d = new List <Vector2>();

        foreach (Line edge in edges)
        {
            if (!vertices2d.Contains(edge.StartingPoint.Position))
            {
                vertices2d.Add(edge.StartingPoint.Position);
            }
        }


        Triangulator triangulator = new Triangulator(vertices2d.ToArray());

        int[] indices = triangulator.Triangulate();

        Vector3[] vertices = new Vector3[vertices2d.Count];
        for (int i = 0; i < vertices.Length; i++)
        {
            vertices[i] = new Vector3(vertices2d[i].x, vertices2d[i].y, 0);
        }

        Mesh msh = new Mesh();

        msh.vertices  = vertices;
        msh.triangles = indices;
        msh.RecalculateNormals();
        msh.RecalculateBounds();

        gameObject.AddComponent(typeof(MeshRenderer));
        MeshFilter filter = gameObject.AddComponent(typeof(MeshFilter)) as MeshFilter;

        filter.mesh = msh;

        gameObject.GetComponent <MeshRenderer>().material = _material;
    }
Exemple #35
0
    private void OnDrawGizmosSelected()
    {
        // Create Vector2 vertices
        Vector2[] vertices2D = GetComponent <PolygonCollider2D>().points;

        // Use the triangulator to get indices for creating triangles
        Triangulator tr = new Triangulator(vertices2D);

        int[] indices = tr.Triangulate();

        // Create the Vector3 vertices
        Vector3[] vertices = new Vector3[vertices2D.Length];
        for (int i = 0; i < vertices.Length; i++)
        {
            vertices[i] = new Vector3(vertices2D[i].x, vertices2D[i].y, 0);
        }



        var meshFilter = GetComponent <MeshFilter>();

        if (meshFilter.sharedMesh == null)
        {
            meshFilter.sharedMesh = new Mesh();
        }
        else
        {
            meshFilter.sharedMesh.Clear();
        }

        var mesh = meshFilter.sharedMesh;

        mesh.vertices  = vertices;
        mesh.triangles = indices;
        mesh.RecalculateNormals();
        mesh.RecalculateBounds();
    }
Exemple #36
0
    void SetMesh(List <Vector3> _verts, Vector2[] v2d)
    {
        Triangulator tr = new Triangulator(v2d);

        int[] indices = tr.Triangulate();
        //mesh.SetVertices(_verts);

        Mesh mesh = new Mesh();

        mesh.vertices  = _verts.ToArray();
        mesh.triangles = indices;
        //mesh.RecalculateNormals();
        mesh.RecalculateBounds();

        MeshVerts = mesh.vertices;
        triangles = indices;

        gameObject.AddComponent(typeof(MeshRenderer));

        MeshFilter filter = gameObject.AddComponent(typeof(MeshFilter)) as MeshFilter;

        GetComponent <MeshRenderer>().material = (Material)Resources.Load("materials/lot");
        filter.mesh = mesh;

        LineRenderer lr = gameObject.AddComponent <LineRenderer>();

        lr.numPositions = AdjVerts.Count + 1;
        Vector3        offset  = new Vector3(0, .01f, 0);
        List <Vector3> lrVerts = new List <Vector3>();

        AdjVerts.ForEach(i => lrVerts.Add(i + offset));
        lrVerts.Add(lrVerts[0]);
        lr.SetPositions(lrVerts.ToArray());
        lr.SetWidth(.1f, .1f);
        lr.material = (Material)Resources.Load("materials/darkgrey");
        //lr.SetColors(Color.grey, Color.grey);
    }
Exemple #37
0
    void OnDrawGizmos()
    {
        if (points == null || points.Length < 3)
        {
            return;
        }

        List <Vector3> pt = new List <Vector3>();

        for (int i = 0; i < points.Length; i++)
        {
            if (points[i] == null)
            {
                continue;
            }

            pt.Add(points[i].transform.position);

            Gizmos.DrawSphere(points[i].transform.position, 0.1f);
        }

        if (pt.Count < 3)
        {
            return;
        }

        List <Triangle> tri;

        // perform triangulation
        if (Triangulator.MonotoneChain(pt, Vector3.up, out tri))
        {
            for (int i = 0; i < tri.Count; i++)
            {
                tri[i].OnDebugDraw(Color.yellow);
            }
        }
    }
Exemple #38
0
    void Start()
    {
        // Create Vector2 vertices
        Vector2[] vertices2D = new Vector2[] {
            new Vector2(0, 0),
            new Vector2(25, 25),
            new Vector2(0, 50),
            new Vector2(50, 50),
            new Vector2(50, 0)
        };

        // Use the triangulator to get indices for creating triangles
        Triangulator tr = new Triangulator(vertices2D);

        int[] indices = tr.Triangulate();

        // Create the Vector3 vertices
        Vector3[] vertices = new Vector3[vertices2D.Length];
        for (int i = 0; i < vertices.Length; i++)
        {
            vertices[i] = new Vector3(vertices2D[i].x, vertices2D[i].y, 0);
        }

        // Create the mesh
        Mesh msh = new Mesh();

        msh.vertices  = vertices;
        msh.triangles = indices;
        msh.RecalculateNormals();
        msh.RecalculateBounds();

        // Set up game object with mesh;
        gameObject.AddComponent(typeof(MeshRenderer));
        MeshFilter filter = gameObject.AddComponent(typeof(MeshFilter)) as MeshFilter;

        filter.mesh = msh;
    }
Exemple #39
0
        public void CreateGlbWithMultipleColors()
        {
            // arrange
            var buildingWkb       = File.OpenRead(@"testfixtures/ams_building.wkb");
            var g                 = Geometry.Deserialize <WkbSerializer>(buildingWkb);
            var polyhedralsurface = ((PolyhedralSurface)g);

            var colors = (from geo in polyhedralsurface.Geometries
                          let random = new Random()
                                       let color = String.Format("#{0:X6}", random.Next(0x1000000))
                                                   select color).ToList();

            // act
            var triangles = Triangulator.GetTriangles(polyhedralsurface, colors.ToArray(), 100);
            var bytes     = GlbCreator.GetGlb(triangles);
            var fileName  = Path.Combine(TestContext.CurrentContext.WorkDirectory, "ams_building_multiple_colors.glb");

            File.WriteAllBytes(fileName, bytes);

            // assert (each triangle becomes a primitive because colors
            var model = ModelRoot.Load(fileName);

            Assert.AreEqual(triangles.Count, model.LogicalMeshes[0].Primitives.Count);
        }
Exemple #40
0
        public static void CreateGlbForSimpleBuilding()
        {
            // arrange
            var buildingDelawareWkt = "POLYHEDRALSURFACE Z (((1237196.52254261 -4794569.11324542 4006730.36853675,1237205.09930114 -4794565.00723136 4006732.61840877,1237198.22281801 -4794557.02527831 4006744.21497578,1237196.52254261 -4794569.11324542 4006730.36853675)),((1237198.22281801 -4794557.02527831 4006744.21497578,1237189.64607418 -4794561.13128501 4006741.96510802,1237196.52254261 -4794569.11324542 4006730.36853675,1237198.22281801 -4794557.02527831 4006744.21497578)),((1237199.14544946 -4794579.27792655 4006738.92021596,1237207.72222617 -4794575.17190377 4006741.17009276,1237200.84572844 -4794567.18993371 4006752.76668446,1237199.14544946 -4794579.27792655 4006738.92021596)),((1237200.84572844 -4794567.18993371 4006752.76668446,1237192.26896643 -4794571.29594914 4006750.51681191,1237199.14544946 -4794579.27792655 4006738.92021596,1237200.84572844 -4794567.18993371 4006752.76668446)),((1237205.09930114 -4794565.00723136 4006732.61840877,1237196.52254261 -4794569.11324542 4006730.36853675,1237207.72222617 -4794575.17190377 4006741.17009276,1237205.09930114 -4794565.00723136 4006732.61840877)),((1237207.72222617 -4794575.17190377 4006741.17009276,1237199.14544946 -4794579.27792655 4006738.92021596,1237196.52254261 -4794569.11324542 4006730.36853675,1237207.72222617 -4794575.17190377 4006741.17009276)),((1237196.52254261 -4794569.11324542 4006730.36853675,1237189.64607418 -4794561.13128501 4006741.96510802,1237199.14544946 -4794579.27792655 4006738.92021596,1237196.52254261 -4794569.11324542 4006730.36853675)),((1237199.14544946 -4794579.27792655 4006738.92021596,1237192.26896643 -4794571.29594914 4006750.51681191,1237189.64607418 -4794561.13128501 4006741.96510802,1237199.14544946 -4794579.27792655 4006738.92021596)),((1237189.64607418 -4794561.13128501 4006741.96510802,1237198.22281801 -4794557.02527831 4006744.21497578,1237192.26896643 -4794571.29594914 4006750.51681191,1237189.64607418 -4794561.13128501 4006741.96510802)),((1237192.26896643 -4794571.29594914 4006750.51681191,1237200.84572844 -4794567.18993371 4006752.76668446,1237198.22281801 -4794557.02527831 4006744.21497578,1237192.26896643 -4794571.29594914 4006750.51681191)),((1237198.22281801 -4794557.02527831 4006744.21497578,1237205.09930114 -4794565.00723136 4006732.61840877,1237200.84572844 -4794567.18993371 4006752.76668446,1237198.22281801 -4794557.02527831 4006744.21497578)),((1237200.84572844 -4794567.18993371 4006752.76668446,1237207.72222617 -4794575.17190377 4006741.17009276,1237205.09930114 -4794565.00723136 4006732.61840877,1237200.84572844 -4794567.18993371 4006752.76668446)))";
            var colors = new List <string>()
            {
                "#385E0F", "#385E0F", "#FF0000", "#FF0000", "#EEC900", "#EEC900", "#EEC900", "#EEC900", "#EEC900", "#EEC900", "#EEC900", "#EEC900"
            };
            var g = Geometry.Deserialize <WktSerializer>(buildingDelawareWkt);
            var polyhedralsurface = ((PolyhedralSurface)g);
            var center            = polyhedralsurface.GetCenter();
            var triangles         = Triangulator.GetTriangles(polyhedralsurface, colors.ToArray(), 100);

            CheckNormal(triangles[2], center);
            Assert.IsTrue(triangles.Count == 12);

            // act
            var bytes    = GlbCreator.GetGlb(triangles);
            var fileName = Path.Combine(TestContext.CurrentContext.WorkDirectory, "simle_building.glb");

            File.WriteAllBytes(fileName, bytes);

            // assert
        }
    void Start()
    {
        PolygonCollider2D polygonCollider = GetComponent <PolygonCollider2D>();
        MeshFilter        filter          = GetComponent <MeshFilter>();

        renderer = GetComponent <MeshRenderer>();
        main     = GameObject.FindWithTag("Main").GetComponent <Main>();

        Mesh mesh = new Mesh();

        Vector2[] points   = polygonCollider.points;
        Vector3[] vertices = new Vector3[points.Length];
        //int[] triangles = new int[points.Length * 3];

        for (int i = 0; i < points.Length; i++)
        {
            points[i].Scale(new Vector2(1.1f, 1.1f));
        }

        for (int i = 0; i < points.Length; i++)
        {
            vertices[i] = new Vector3(points[i].x, points[i].y, 0);
        }



        mesh.vertices = vertices;
        Triangulator t = new Triangulator(points);

        int[] triangles = t.Triangulate();
        renderer.material = matOff;
        mesh.triangles    = triangles;
        //mesh.uv = uv;
        mesh.name   = "Test";
        filter.mesh = mesh;
    }
Exemple #42
0
        private static Mesh meshFromBorders(Vector2[] borders)
        {
            borders = avoidMeridian(borders);
            Triangulator tri = new Triangulator(borders);

            int[] tris = tri.Triangulate();

            Vector3[] verts = coordsToThreeSpace(borders);
            Vector3[] norms = new Vector3[borders.Length];

            for (int i = 0; i < borders.Length; i++)
            {
                norms[i] = Vector3.forward;
            }

            Mesh mesh = new Mesh();

            mesh.vertices  = verts;
            mesh.triangles = tris;
            mesh.normals   = norms;
            mesh.RecalculateBounds();
            //mesh.RecalculateNormals();
            return(mesh);
        }
Exemple #43
0
    public override void OnMove()
    {
        if (step != 0)
        {
            line.points2[line.points2.Count - 1] = Input.mousePosition;
            line.Draw();
        }

        if (step >= 2)
        {
            vertices2D[vertices2D.Count - 1] = Input.mousePosition;
            Triangulator tr       = new Triangulator(vertices2D.ToArray());
            int[]        indices  = tr.Triangulate();
            Vector3[]    vertices = new Vector3[vertices2D.Count];
            for (int i = 0; i < vertices.Length; i++)
            {
                vertices[i] = new Vector3(vertices2D[i].x, vertices2D[i].y, 50);
            }
            msh.vertices  = vertices;
            msh.triangles = indices;
            msh.RecalculateNormals();
            msh.RecalculateBounds();
        }
    }
Exemple #44
0
        /**
         * Create new GameObject, part of a building
         *                  triangleType = 0 => generate triangles via Triangulator for roofs
         *                               = 1 => generate optimized triangles for walls = only two triangles is enough for 4 wall points
         *                               = 2 => generate triangles for 4 point roofs
         */
        private void CreateGameObject(string buildingName, Vector3[] edges, int triangleType)
        {
            var gameObjectArea = new GameObject(buildingName);

#if UNITY_EDITOR
            const StaticEditorFlags flags = StaticEditorFlags.BatchingStatic | StaticEditorFlags.LightmapStatic;
            GameObjectUtility.SetStaticEditorFlags(gameObjectArea, flags);
#endif
            var meshFilter = (MeshFilter)gameObjectArea.AddComponent(typeof(MeshFilter));
            var mesh       = meshFilter.mesh;
            mesh.Clear();
            mesh.vertices = edges;
            //fill area with triangles
            int[] triangles = triangleType != 0 ? GenerateTrianglesFor4Points() : Triangulator.GenerateTriangleNewVersion(edges.ToList());

            mesh.triangles = triangles;
            mesh.RecalculateNormals();
            mesh.RecalculateBounds();
#if UNITY_EDITOR
            MeshUtility.Optimize(mesh);
#endif
            ChangeBuildingSurfaceColor(gameObjectArea, ColorUtils.DefaultBuilding);
            BatchedBuildings.Add(gameObjectArea);
        }
Exemple #45
0
    public void init(PolygonCollider2D collider, GameObject objectToAddMesh, Vector2 orgin)
    {
        int pointCount        = 0;
        PolygonCollider2D pc2 = collider;

        pointCount = pc2.GetTotalPointCount();

        MeshFilter mf   = objectToAddMesh.GetComponent <MeshFilter>();
        Mesh       mesh = new Mesh();

        Vector2[] points   = pc2.points;
        Vector3[] vertices = new Vector3[pointCount];
        for (int j = 0; j < pointCount; j++)
        {
            Vector2 actual = points[j] - orgin;
            vertices[j] = new Vector3(actual.x, actual.y, 0);
        }
        Triangulator tr = new Triangulator(points);

        int [] triangles = tr.Triangulate();
        mesh.vertices  = vertices;
        mesh.triangles = triangles;
        mf.mesh        = mesh;
    }
Exemple #46
0
    public void UpdateMesh()
    {
        var poly    = GetComponent <PolygonCollider2D>();
        var tris    = new Triangulator(poly.points);
        var indices = tris.Triangulate();

        Mesh mesh;

        if (export)
        {
            mesh = GetComponent <MeshFilter>().mesh;
        }
        else
        {
            mesh = new Mesh();
        }
        Vector3[] points3 = new Vector3[poly.points.Length];
        Vector3[] norms   = new Vector3[poly.points.Length];
        for (int i = 0; i < poly.points.Length; i++)
        {
            points3[i] = poly.points[i];
            norms[i]   = Vector3.back;
        }

        Vector2[] uv = new Vector2[poly.points.Length];
        for (int i = 0; i < poly.points.Length; i++)
        {
            uv[i] = transform.TransformPoint(poly.points[i]);
        }
        mesh.vertices  = points3;
        mesh.uv        = uv;
        mesh.normals   = norms;
        mesh.triangles = indices;

        GetComponent <MeshFilter>().mesh = mesh;
    }
    void CreatePolygon()
    {
        string objectName = "Polygon";
        Mesh mesh = new Mesh ();

        Vector3[] vertices = new Vector3[cubeIndex];
        for (int i=0; i<cubeIndex; i++) {
            vertices [i] = cubeList [i].transform.position;
        }
        mesh.vertices = vertices;

        Vector2[] verticesXY = new Vector2[cubeIndex];
        for (int i=0; i<cubeIndex; i++) {
            Vector3 pos = cubeList [i].transform.position;
            verticesXY [i] = new Vector2 (pos.x, pos.y);
        }
        Triangulator tr = new Triangulator (verticesXY, Camera.mainCamera.transform.position);
        int[] indices = tr.Triangulate ();
        mesh.triangles = indices;

        //  UVデータの設定は今回は省略
        mesh.uv = new Vector2[cubeIndex];

        mesh.RecalculateNormals ();	// 法線の再計算
        mesh.RecalculateBounds ();	// バウンディングボリュームの再計算
        mesh.Optimize ();

        GameObject newGameobject = new GameObject (objectName);

        MeshRenderer meshRenderer = newGameobject.AddComponent<MeshRenderer> ();
        meshRenderer.material = polygonMaterial;
        //meshRenderer.material.mainTexture = (Texture)Instantiate (Resources.Load ("Image2"));

        MeshFilter meshFilter = newGameobject.AddComponent<MeshFilter> ();
        meshFilter.mesh = mesh;
    }
Exemple #48
0
    public void CalculateVerts()
    {
        mesh.Clear();

        // Use the triangulator to get indices for creating triangles
        ConstrainVertsToLimter();
        Triangulator tr = new Triangulator(verts.ToVector2Array());
        int[] indices = tr.Triangulate();

        Vector2[] uvs = new Vector2[verts.Length];

        for (int i=0; i < uvs.Length; i++) {
            uvs[i] = new Vector2(verts[i].x, verts[i].z);
        }

        mesh.vertices = verts;
        mesh.uv = uvs;
        mesh.triangles = indices;
        mesh.RecalculateNormals();
        mesh.RecalculateBounds();
        mesh.Optimize();

        polyColl.points = verts.ToVector2Array();
    }
        public void CreateGlbWithWrongNumberOfColorsGivesArgumentOfRangeException()
        {
            // arrange
            var buildingWkb       = File.OpenRead(@"testfixtures/ams_building.wkb");
            var g                 = Geometry.Deserialize <WkbSerializer>(buildingWkb);
            var polyhedralsurface = ((PolyhedralSurface)g);

            var shaderColors      = new ShaderColors();
            var metallicRoughness = new PbrMetallicRoughnessColors();

            metallicRoughness.BaseColors = (from geo in polyhedralsurface.Geometries
                                            let random = new Random()
                                                         let color = String.Format("#{0:X6}", random.Next(0x1000000))
                                                                     select color).ToList();

            // accidentally remove 1:
            metallicRoughness.BaseColors.RemoveAt(metallicRoughness.BaseColors.Count - 1);

            var specularGlosiness = new PbrSpecularGlossinessColors();

            specularGlosiness.DiffuseColors = metallicRoughness.BaseColors;

            shaderColors.PbrMetallicRoughnessColors  = metallicRoughness;
            shaderColors.PbrSpecularGlossinessColors = specularGlosiness;

            // act
            try {
                var triangles = Triangulator.GetTriangles(polyhedralsurface, 100, shaderColors);
            }
            catch (Exception ex) {
                // assert
                Assert.IsTrue(ex != null);
                Assert.IsTrue(ex is ArgumentOutOfRangeException);
                Assert.IsTrue(ex.Message.Contains("Diffuse, BaseColor"));
            }
        }
Exemple #50
0
    public void UpdateMesh()
    {
        Mesh mesh = new Mesh();

        Vector2[] points   = coll.points;
        Vector3[] vertices = new Vector3[points.Length];
        Vector2[] uv       = new Vector2[points.Length];

        for (int i = 0; i < points.Length; i++)
        {
            vertices[i] = points[i];
            uv[i]       = points[i];
        }

        Triangulator tr = new Triangulator(points);

        int[] triangles = tr.Triangulate();

        mesh.vertices  = vertices;
        mesh.triangles = triangles;
        mesh.uv        = uv;

        meshFilter.mesh = mesh;
    }
    public void SetMesh()
    {
        meshFilter   = GetComponent <MeshFilter>();
        polyCollider = GetComponent <PolygonCollider2D>();


        Triangulator triangulator = new Triangulator(meshPoints);

        int[] triangles = triangulator.Triangulate();
        mesh = new Mesh();

        List <Vector3> meshPoint3s = new List <Vector3>();

        foreach (Vector2 v in meshPoints)
        {
            meshPoint3s.Add(v);
        }
        mesh.vertices  = meshPoint3s.ToArray();
        mesh.triangles = triangles;
        mesh.RecalculateNormals();

        meshFilter.mesh     = mesh;
        polyCollider.points = meshPoints;
    }
Exemple #52
0
        void GenerateFillMesh()
        {
            var meshFilter   = gameObject.AddComponent <MeshFilter>();
            var mesh         = new Mesh();
            var meshRenderer = gameObject.AddComponent <MeshRenderer>();

            Vector2[] points = new Vector2[nodes.Length];
            for (int i = 0; i < points.Length; i++)
            {
                points[i] = nodes[i].point;
            }

            List <Vector3> points3d = new List <Vector3>();

            for (int i = 0; i < nodes.Length; i++)
            {
                points3d.Add(new Vector3(nodes[i].point.x, nodes[i].point.y, fillMeshZ));
            }

            mesh.SetVertices(points3d);

            var t = new Triangulator(points);

            mesh.SetIndices(t.Triangulate(), MeshTopology.Triangles, 0);
            meshFilter.mesh = mesh;

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

            for (int i = 0; i < nodes.Length; i++)
            {
                uvs.Add(new Vector2(nodes[i].point.x, nodes[i].point.y));
            }
            mesh.SetUVs(0, uvs);

            meshRenderer.material = fillMaterial;
        }
Exemple #53
0
    public void FillShape()
    {
        PolygonCollider2D pc2 = gameObject.GetComponent <PolygonCollider2D>();
        int pointCount        = pc2.GetTotalPointCount();

        MeshFilter mf   = GetComponent <MeshFilter>();
        Mesh       mesh = new Mesh();

        Vector2[] points   = pc2.points;
        Vector3[] vertices = new Vector3[pointCount];
        for (int j = 0; j < pointCount; j++)
        {
            Vector2 actual = points[j];
            vertices[j] = new Vector3(actual.x, actual.y, 0);
        }
        Triangulator tr = new Triangulator(points);

        int[] triangles = tr.Triangulate();
        mesh.vertices  = vertices;
        mesh.triangles = triangles;
        mf.mesh        = mesh;

        mf.sharedMesh.RecalculateBounds();
    }
Exemple #54
0
        private static void WriteTiles(NpgsqlConnection conn, string geometryTable, string geometryColumn, double[] translation, Node node, string outputPath, string colorColumn = "")
        {
            if (node.Features.Count > 0)
            {
                counter++;
                var subset     = (from f in node.Features select(f.Id)).ToArray();
                var geometries = BoundingBoxRepository.GetGeometrySubset(conn, geometryTable, geometryColumn, translation, subset, colorColumn);

                var triangleCollection = Triangulator.GetTriangles(geometries);

                var bytes        = GlbCreator.GetGlb(triangleCollection);
                var b3dm         = new B3dm.Tile.B3dm(bytes);
                var featureTable = new FeatureTable();
                featureTable.BATCH_LENGTH = geometries.Count;
                b3dm.FeatureTableJson     = JsonConvert.SerializeObject(featureTable);

                var batchTable = new BatchTable();

                var r       = new Random();
                var heights = new List <float>();
                for (var i = 0; i < geometries.Count; i++)
                {
                    heights.Add(r.Next(100));
                }
                batchTable.Height   = heights.ToArray();
                b3dm.BatchTableJson = JsonConvert.SerializeObject(batchTable);
                B3dmWriter.WriteB3dm($"{outputPath}/tiles/{node.Id}.b3dm", b3dm);
            }
            // and write children too
            foreach (var subnode in node.Children)
            {
                var perc = Math.Round(((double)counter / Counter.Instance.Count) * 100, 2);
                Console.Write($"\rProgress: tile {counter} - {perc.ToString("F")}%");
                WriteTiles(conn, geometryTable, geometryColumn, translation, subnode, outputPath, colorColumn);
            }
        }
    bool ConvertCountries()
    {
        List<CNode> foundNodes = new List<CNode> ();

        ConnectedNodes (nodes [0], foundNodes);
        if (foundNodes.Count == nodes.Count && nodes.FindAll (x => x.links.Count < 2).Count == 0) {
            //Debug.Log ("All nodes are connected by two links");
            List<List<CNode>> nodeShapes = new List<List<CNode>> ();

            List<CNode> multiNodes = nodes.FindAll (x => x.links.Count > 2);
            /*if(multiNodes.Count == 0) {
                        nodeShapes.Add(nodes);
                    }*/

            List<CNode[]> doneNodes = new List<CNode[]> ();

            foreach (CNode junction in multiNodes) { //we loop through each junction to catch all the shapes
                List<CNode> cwNodes = junction.CClockwiseConnected ();

                foreach (CNode node in cwNodes) { //we go around each node, looking for its clockwise next point
                    if (doneNodes.Find (x => x [0] == node && x [1] == junction) != null) {
                        continue;
                    }

                    float angleSum = 0f;

                    doneNodes.Add (new CNode[2]{node, junction}); //we start by adding the node so we don't go around it clockwise again

                    CNode currentNode = junction;
                    CNode lastNode = node;

                    //Debug.Log ("Started from " + lastNode.gameObject.name + " and " + currentNode.gameObject.name);

                    List<CNode> currentShape = new List<CNode> ();
                    currentShape.Add (node);

                    do {
                        CNode temp = currentNode;

                        currentShape.Add (currentNode);

                        currentNode = currentNode.CClockwiseFrom (lastNode);

                        float addAngle =  MeshMaker.GetCWAngle(temp.gameObject.transform.position,
                                                         lastNode.gameObject.transform.position,
                                                         currentNode.gameObject.transform.position) - Mathf.PI; //we look at the exterior angle, which is why we subtract Pi

                        //Debug.Log ("Angle between " + lastNode.gameObject.name + " and " + currentNode.gameObject.name + " is " + addAngle.ToString());

                        angleSum += addAngle;

                        lastNode = temp;

                        //Debug.Log ("Added " + currentNode.gameObject.name);

                        if (currentNode.links.Count > 2) { //if it's a node before a junction, we might loop through it in the future and want to avoid it now
                            doneNodes.Add (new CNode[2]{lastNode, currentNode});
                        }
                    } while(currentNode != node);

                    //Debug.Log (angleSum.ToString());

                    if(angleSum < 0) { //This is true for shapes we've gone around the inside of - otherwise, we can include a negative shape
                        nodeShapes.Add (currentShape);
                    }
                }

            }

            for (int nodeIndex = 0; nodeIndex < nodeShapes.Count; nodeIndex++) { //we generate the shapes out of the list of CNodes

                List<CNode> nodeList = nodeShapes [nodeIndex];

                Vector3[] vertices = new Vector3[nodeList.Count];

                Vector3 averageVert = new Vector3();

                for (int i = 0; i < nodeList.Count; i++) {
                    averageVert += nodeList [i].gameObject.transform.position;
                }

                averageVert /= nodeList.Count;

                for (int i = 0; i < nodeList.Count; i++) {
                    vertices[i] = nodeList [i].gameObject.transform.position - averageVert;
                }

                Triangulator triangulator = new Triangulator (vertices);

                triangulator.Triangulate ();

                GameObject newObject = new GameObject ();

                MeshFilter newFilter = newObject.AddComponent<MeshFilter> ();
                newFilter.mesh.vertices = vertices;
                newFilter.mesh.triangles = triangulator.Triangulate ();
                newFilter.mesh.RecalculateBounds ();
                newFilter.mesh.RecalculateNormals ();

                MeshRenderer newRenderer = newObject.AddComponent<MeshRenderer> ();
                newRenderer.material.shader = Shader.Find ("UI/Default");
                float colorFraction = nodeIndex / (nodeShapes.Count * 1.0f);
                //Debug.Log ("Coloring at " + colorFraction.ToString ());
                newRenderer.material.color = new Color (colorFraction, colorFraction, colorFraction, 1f);

                newObject.AddComponent<MeshCollider>();

                newObject.AddComponent<CountryObject>();

                newObject.transform.Translate(averageVert + new Vector3(0f, 0f, 1f));

                MeshMaker.GenerateOutline(newObject);
            }

            return true;
        }

        return false;
    }
Exemple #56
0
    public void RefreshPhysics()
    {
        //Debug.Log("RefreshPhysics");
        if (boxColliders == null && GetPhysics() == Physics.Boxed)
        {
            boxColliders = new BoxCollider[1];
        }

        if (!Application.isPlaying && !GetCreatePhysicsInEditor())
        {
            DestroyPhysicsChildren();
        }

        if (Application.isPlaying || GetCreatePhysicsInEditor())
        {

            switch (GetPhysics())
            {
                case Physics.None:
                    DestroyPhysicsChildren();
                    break;

                case Physics.Boxed:

                    DestroyMeshCollider();

                    if (lastPhysicsVertsCount != GetSplits(physicsColliderCount, 0f, 1f).Length || boxColliders[0] == null)
                    {
                        if (!Application.isPlaying)
                        {
                            DestroyPhysicsChildren();
                        }

                        lastPhysicsVertsCount = GetSplits(physicsColliderCount, 0f, 1f).Length;

                        RageVertex[] splits = new RageVertex[0];

                        splits = GetSplits(physicsColliderCount, 0f, 1f);

                        boxColliders = new BoxCollider[splits.Length - 1];

                        int t = 0;
                        t = splits.Length - 1;

                        for (int i = 0; i < t; i++)
                        {
                            GameObject newObj = new GameObject();
                            newObj.name = "ZZZ_" + gameObject.name + "_BoxCollider";
                            newObj.transform.parent = transform;
                            BoxCollider box = newObj.AddComponent(typeof(BoxCollider)) as BoxCollider;
                            box.material = GetPhysicsMaterial();

                            int i2 = i + 1;

                            Vector3 pos;
                            Vector3 pos2;
                            Vector3 norm = GetNormal(splits[i].splinePosition);
                            Vector3 norm2 = GetNormal(splits[i2].splinePosition);

                            pos = splits[i].position - norm * (GetBoxColliderDepth() * 0.5f - GetPhysicsNormalOffset());
                            pos2 = splits[i2].position - norm2 * (GetBoxColliderDepth() * 0.5f - GetPhysicsNormalOffset());

                            newObj.layer = transform.gameObject.layer;
                            newObj.tag = transform.gameObject.tag;
                            newObj.gameObject.transform.localPosition = (pos + pos2) * 0.5f;
                            newObj.gameObject.transform.LookAt(transform.TransformPoint(newObj.gameObject.transform.localPosition + Vector3.Cross((pos - pos2).normalized, new Vector3(0f, 0f, -1f))), new Vector3(1f, 0f, 0f));
                            newObj.gameObject.transform.localScale = new Vector3(GetPhysicsZDepth(), ((pos + norm * GetBoxColliderDepth() * 0.5f) - (pos2 + norm2 * GetBoxColliderDepth() * 0.5f)).magnitude, 1f * GetBoxColliderDepth());
                            boxColliders[i] = box;
                        }
                    }
                    else
                    {
                        int i = 0;
                        RageVertex[] splits = new RageVertex[0];
                        splits = GetSplits(GetPhysicsColliderCount(), 0f, 1f);

                        foreach (BoxCollider obj in boxColliders)
                        {
                            obj.material = GetPhysicsMaterial();
                            int i2 = i + 1;

                            Vector3 norm = GetNormal(splits[i].splinePosition);
                            Vector3 norm2 = GetNormal(splits[i2].splinePosition);
                            Vector3 pos;
                            Vector3 pos2;

                            pos = splits[i].position - norm * (GetBoxColliderDepth() * 0.5f - GetPhysicsNormalOffset());
                            pos2 = splits[i2].position - norm2 * (GetBoxColliderDepth() * 0.5f - GetPhysicsNormalOffset());

                            obj.gameObject.transform.localPosition = (pos + pos2) * 0.5f;
                            obj.gameObject.transform.LookAt(transform.TransformPoint(obj.gameObject.transform.localPosition + Vector3.Cross((pos - pos2).normalized, new Vector3(0f, 0f, -1f))), new Vector3(1f, 0f, 0f));
                            obj.gameObject.transform.localScale = new Vector3(GetPhysicsZDepth(), ((pos + norm * GetBoxColliderDepth() * 0.5f) - (pos2 + norm2 * GetBoxColliderDepth() * 0.5f)).magnitude, 1f * GetBoxColliderDepth());
                            i++;
                        }

                        lastPhysicsVertsCount = physicsColliderCount;
                    }

                    break;

                case Physics.MeshCollider:

                    DestroyBoxColliders();

                    if (GetPhysicsColliderCount() > 2 && (GetCreatePhysicsInEditor() || Application.isPlaying))
                    {

                        Vector3[] verts = null;
                        RageVertex[] splits2 = null;
                        int[] tris = null;

                        int tt = 0;

                        if (GetFill() != Fill.Landscape)
                        {

                            splits2 = GetSplits(GetPhysicsColliderCount(), 0f, 1f);
                            verts = new Vector3[splits2.Length * 2];
                            //verts = new Vector3[GetPhysicsColliderCount() * 2];
                            tris = new int[verts.Length * 3 + (verts.Length - 2) * 6];
                            //splits2 = GetSplits(GetPhysicsColliderCount(), 0f, 1f);

                            for (int v = 0; v < verts.Length; v += 2)
                            {
                                verts[v] = splits2[v / 2].position + new Vector3(0f, 0f, GetPhysicsZDepth() * 0.5f) + GetNormal(splits2[v / 2].splinePosition) * GetPhysicsNormalOffset();
                                verts[v + 1] = splits2[v / 2].position + new Vector3(0f, 0f, GetPhysicsZDepth() * -0.5f) + GetNormal(splits2[v / 2].splinePosition) * GetPhysicsNormalOffset();

                                if (v < verts.Length - 2)
                                {
                                    tris[tt + 0] = v + 0;
                                    tris[tt + 1] = v + 2;
                                    tris[tt + 2] = v + 1;
                                    tris[tt + 3] = v + 1;
                                    tris[tt + 4] = v + 2;
                                    tris[tt + 5] = v + 3;
                                }
                                else
                                {
                                    tris[tt + 0] = v + 0;
                                    tris[tt + 1] = 0;
                                    tris[tt + 2] = v + 1;
                                    tris[tt + 3] = v + 1;
                                    tris[tt + 4] = 0;
                                    tris[tt + 5] = 1;
                                }

                                tt += 6;
                            }

                        }
                        else
                        {
                            splits2 = GetSplits(GetPhysicsColliderCount(), 0f, 1f);
                            verts = new Vector3[splits2.Length * 2 + 4];
                            tris = new int[verts.Length * 3 + (verts.Length - 2) * 6];

                            //verts = new Vector3[GetPhysicsColliderCount() * 2 + 4];
                            //tris = new int[verts.Length * 3 + (verts.Length - 2) * 6];
                            //splits2 = GetSplits(GetPhysicsColliderCount() - 1, 0f, 1f);
                            float bottomY = GetBounds().yMin - Mathf.Clamp(GetLandscapeBottomDepth(), 1f, 100000000f);

                            verts[0] = new Vector3(splits2[0].position.x, bottomY, GetPhysicsZDepth() * 0.5f);
                            verts[1] = new Vector3(splits2[0].position.x, bottomY, GetPhysicsZDepth() * -0.5f);

                            for (int v = 2; v < verts.Length - 2; v += 2)
                            {
                                verts[v] = splits2[(v - 2) / 2].position + new Vector3(0f, 0f, GetPhysicsZDepth() * 0.5f) + GetNormal(splits2[(v - 2) / 2].splinePosition) * GetPhysicsNormalOffset();
                                verts[v + 1] = splits2[(v - 2) / 2].position + new Vector3(0f, 0f, GetPhysicsZDepth() * -0.5f) + GetNormal(splits2[(v - 2) / 2].splinePosition) * GetPhysicsNormalOffset();
                            }

                            for (int v = 0; v < verts.Length; v += 2)
                            {
                                if (v < verts.Length - 2)
                                {
                                    tris[tt + 0] = v + 0;
                                    tris[tt + 1] = v + 2;
                                    tris[tt + 2] = v + 1;
                                    tris[tt + 3] = v + 1;
                                    tris[tt + 4] = v + 2;
                                    tris[tt + 5] = v + 3;
                                }
                                else
                                {
                                    tris[tt + 0] = v + 0;
                                    tris[tt + 1] = 0;
                                    tris[tt + 2] = v + 1;
                                    tris[tt + 3] = v + 1;
                                    tris[tt + 4] = 0;
                                    tris[tt + 5] = 1;
                                }

                                tt += 6;
                            }

                            verts[verts.Length - 2] = new Vector3(splits2[splits2.Length - 1].position.x, bottomY, GetPhysicsZDepth() * 0.5f);
                            verts[verts.Length - 1] = new Vector3(splits2[splits2.Length - 1].position.x, bottomY, GetPhysicsZDepth() * -0.5f);

                        }

                        Vector2[] pverts = new Vector2[verts.Length / 2];
                        for (int i = 0; i < pverts.Length; i++)
                        {
                            pverts[i] = new Vector2(verts[i * 2].x, verts[i * 2].y);
                        }

                        Vector2[] pverts2 = new Vector2[verts.Length / 2];
                        for (int i = 0; i < pverts2.Length; i++)
                        {
                            pverts2[i] = new Vector2(verts[i * 2 + 1].x, verts[i * 2 + 1].y);
                        }

                        Triangulator triangulator = new Triangulator(pverts);
                        int[] fillTris = triangulator.Triangulate();
                        //for (int i = fillTris.Length - 1; i >= 0; i--)
                        for (int i = 0; i < fillTris.Length; i++)
                        {
                            tris[tt++] = fillTris[i] * 2;
                        }

                        Triangulator triangulator2 = new Triangulator(pverts2);
                        int[] fillTris2 = triangulator2.Triangulate();
                        //for (int i = 0; i < fillTris2.Length; i++)
                        for (int i = fillTris2.Length-1; i >= 0; i--)
                        {
                            tris[tt++] = fillTris2[i] * 2 + 1;
                        }

                        MeshCollider meshCollider = gameObject.GetComponent(typeof(MeshCollider)) as MeshCollider;
                        bool wasNull = false;
                        if (meshCollider == null)
                        {
                            wasNull = true;
                        }

                        Mesh colMesh = null;
                        if (wasNull)
                        {
                            colMesh = new Mesh();
                        }
                        else
                        {
                            if (meshCollider.sharedMesh != null)
                            {
                                colMesh = meshCollider.sharedMesh;
                            }
                            else
                            {
                                colMesh = new Mesh();
                            }
                        }

                        colMesh.Clear();
                        colMesh.vertices = verts;
                        colMesh.triangles = tris;
                        colMesh.RecalculateBounds();
                        colMesh.RecalculateNormals();
                        colMesh.Optimize();

                        if (wasNull)
                        {
                            //MeshFilter filter = gameObject.GetComponent(typeof(MeshFilter)) as MeshFilter;
                            meshCollider = gameObject.AddComponent(typeof(MeshCollider)) as MeshCollider;
                        }
                        meshCollider.sharedMesh = null;
                        meshCollider.sharedMesh = colMesh;

                        meshCollider.sharedMaterial = physicsMaterial;
                        meshCollider.convex = GetCreateConvexMeshCollider();

                    }

                    break;
                case Physics.OutlineMeshCollider:

                    DestroyBoxColliders();

                    if (GetPhysicsColliderCount() > 2 && (GetCreatePhysicsInEditor() || Application.isPlaying))
                    {

                        int splitCount = GetPhysicsColliderCount();

                        Vector3[] verts = new Vector3[(splitCount + 1) * 4];
                        int[] tris = new int[splitCount * 24];

                        int v = 0;
                        for (int i = 0; i <= splitCount; i++)
                        {
                            float splinePos = (float)i / (float)splitCount;
                            Vector3 normal = GetNormal(splinePos);
                            verts[v++] = GetPosition(splinePos) + normal * GetOutlineWidth() * 0.5f + normal * GetOutlineNormalOffset() + new Vector3(0f, 0f, GetPhysicsZDepth() * 0.5f);
                            verts[v++] = GetPosition(splinePos) + normal * GetOutlineWidth() * -0.5f + normal * GetOutlineNormalOffset() + new Vector3(0f, 0f, GetPhysicsZDepth() * 0.5f);
                            verts[v++] = GetPosition(splinePos) + normal * GetOutlineWidth() * -0.5f + normal * GetOutlineNormalOffset() - new Vector3(0f, 0f, GetPhysicsZDepth() * 0.5f);
                            verts[v++] = GetPosition(splinePos) + normal * GetOutlineWidth() * 0.5f + normal * GetOutlineNormalOffset() - new Vector3(0f, 0f, GetPhysicsZDepth() * 0.5f);
                        }

                        int t = 0;
                        for (int i = 0; i < splitCount; i++)
                        {

                            tris[t++] = i * 4 + 0;
                            tris[t++] = i * 4 + 0 + 4 + 1;
                            tris[t++] = i * 4 + 0 + 4;
                            tris[t++] = i * 4 + 0;
                            tris[t++] = i * 4 + 0 + 1;
                            tris[t++] = i * 4 + 0 + 4 + 1;

                            tris[t++] = i * 4 + 1;
                            tris[t++] = i * 4 + 1 + 4 + 1;
                            tris[t++] = i * 4 + 1 + 4;
                            tris[t++] = i * 4 + 1;
                            tris[t++] = i * 4 + 1 + 1;
                            tris[t++] = i * 4 + 1 + 4 + 1;

                            tris[t++] = i * 4 + 2;
                            tris[t++] = i * 4 + 2 + 4 + 1;
                            tris[t++] = i * 4 + 2 + 4;
                            tris[t++] = i * 4 + 2;
                            tris[t++] = i * 4 + 2 + 1;
                            tris[t++] = i * 4 + 2 + 4 + 1;

                            tris[t++] = i * 4 + 3;
                            tris[t++] = i * 4 + 3 + 1;
                            tris[t++] = i * 4 + 3 + 4;
                            tris[t++] = i * 4 + 3;
                            tris[t++] = i * 4;
                            tris[t++] = i * 4 + 3 + 1;

                            /*
                            tris[t++] = i * 4 + 0;
                            tris[t++] = i * 4 + 0 + 4;
                            tris[t++] = i * 4 + 0 + 4 + 1;
                            tris[t++] = i * 4 + 0;
                            tris[t++] = i * 4 + 0 + 4 + 1;
                            tris[t++] = i * 4 + 0 + 1;

                            tris[t++] = i * 4 + 1;
                            tris[t++] = i * 4 + 1 + 4;
                            tris[t++] = i * 4 + 1 + 4 + 1;
                            tris[t++] = i * 4 + 1;
                            tris[t++] = i * 4 + 1 + 4 + 1;
                            tris[t++] = i * 4 + 1 + 1;

                            tris[t++] = i * 4 + 2;
                            tris[t++] = i * 4 + 2 + 4;
                            tris[t++] = i * 4 + 2 + 4 + 1;
                            tris[t++] = i * 4 + 2;
                            tris[t++] = i * 4 + 2 + 4 + 1;
                            tris[t++] = i * 4 + 2 + 1;

                            tris[t++] = i * 4 + 3;
                            tris[t++] = i * 4 + 3 + 4;
                            tris[t++] = i * 4 + 3 + 1;
                            tris[t++] = i * 4 + 3;
                            tris[t++] = i * 4 + 3 + 1;
                            tris[t++] = i * 4;
                            */
                        }

                        MeshCollider meshCollider = gameObject.GetComponent(typeof(MeshCollider)) as MeshCollider;
                        bool wasNull = false;
                        if (meshCollider == null)
                        {
                            wasNull = true;
                        }

                        Mesh colMesh = null;
                        if (wasNull)
                        {
                            colMesh = new Mesh();
                        }
                        else
                        {
                            if (meshCollider.sharedMesh != null)
                            {
                                colMesh = meshCollider.sharedMesh;
                            }
                            else
                            {
                                colMesh = new Mesh();
                            }
                        }

                        colMesh.Clear();
                        colMesh.vertices = verts;
                        colMesh.triangles = tris;
                        colMesh.RecalculateBounds();
                        colMesh.RecalculateNormals();
                        colMesh.Optimize();

                        if (wasNull)
                        {
                            //MeshFilter filter = gameObject.GetComponent(typeof(MeshFilter)) as MeshFilter;
                            meshCollider = gameObject.AddComponent(typeof(MeshCollider)) as MeshCollider;
                        }
                        meshCollider.sharedMesh = null;
                        meshCollider.sharedMesh = colMesh;

                        meshCollider.sharedMaterial = physicsMaterial;
                        meshCollider.convex = GetCreateConvexMeshCollider();

                    }

                    break;
            }
        }
    }
Exemple #57
0
    public void GenerateTriangles(Mesh mesh, RageVertex[] fillVerts, RageVertex[] embossVerts, RageVertex[] outlineVerts, bool AAfill, bool AAemboss, bool AAoutline, bool multipleMaterials)
    {
        int[] tris = null;

        Vector2[] verts = new Vector2[0];

        if (GetFill() != Fill.Landscape)
        {
            if (AAfill)
            {
                verts = new Vector2[fillVerts.Length / 2];
            }
            else
            {
                verts = new Vector2[fillVerts.Length];
            }

            for (int i = 0; i < verts.Length; i++)
            {
                verts[i] = new Vector2(fillVerts[i].position.x, fillVerts[i].position.y);
            }
        }

        tris = new int[GetOutlineTriangleCount(outlineVerts, AAoutline) * 3 + GetFillTriangleCount(fillVerts, AAfill) * 3 + GetEmbossTriangleCount(embossVerts, AAemboss) * 3];

        int tIndex = 0;
        int vertsPerBand = 0;
        int bandCount = 0;

        switch (GetFill())
        {
            case Fill.None:

                break;
            case Fill.Solid:
            case Fill.Gradient:
                Triangulator triangulator = new Triangulator(verts);

                int[] fillTris = triangulator.Triangulate();

                for (int i = 0; i < fillTris.Length; i++)
                {
                    tris[tIndex++] = fillTris[i];
                }
                break;
            case Fill.Landscape:

                if (AAfill)
                {
                    bandCount = 2;
                    vertsPerBand = fillVerts.Length / 3;
                }
                else
                {
                    bandCount = 1;
                    vertsPerBand = fillVerts.Length / 2;
                }

                for (int v = 0; v < vertsPerBand-1; v++)
                {
                    for (int b = 0; b < bandCount; b++)
                    {
                        tris[tIndex++] = v + b * vertsPerBand;
                        tris[tIndex++] = v + (b + 1) * vertsPerBand;
                        tris[tIndex++] = v + (b + 1) * vertsPerBand + 1;
                        tris[tIndex++] = v + b * vertsPerBand;
                        tris[tIndex++] = v + (b + 1) * vertsPerBand + 1;
                        tris[tIndex++] = v + b * vertsPerBand + 1;
                    }
                }

            break;
        }

        vertsPerBand = 0;
        bandCount = 0;

        // fill antialiasing triangles
        if (AAfill)
        {
            vertsPerBand = verts.Length-1;

            for (int v = 0; v <= vertsPerBand; v++)
            {
                for (int b = 0; b < 1; b++)
                {
                    tris[tIndex++] = v + b * vertsPerBand;
                    tris[tIndex++] = v + (b + 1) * vertsPerBand;
                    tris[tIndex++] = v + (b + 1) * vertsPerBand + 1;
                    tris[tIndex++] = v + b * vertsPerBand;
                    tris[tIndex++] = v + (b + 1) * vertsPerBand + 1;
                    tris[tIndex++] = v + b * vertsPerBand + 1;
                }
            }

        }

        if (AAemboss)
        {
            vertsPerBand = embossVerts.Length / 4;
            bandCount = 3;
        }
        else
        {
            vertsPerBand = embossVerts.Length / 2;
            bandCount = 1;
        }

        for (int v = 0; v < vertsPerBand-1; v++)
        {
            for (int b = 0; b < bandCount; b++)
            {
                if (v < vertsPerBand - 1)
                {
                    tris[tIndex++] = v + b * vertsPerBand + fillVerts.Length;
                    tris[tIndex++] = v + (b + 1) * vertsPerBand + 1 + fillVerts.Length;
                    tris[tIndex++] = v + (b + 1) * vertsPerBand + fillVerts.Length;
                    tris[tIndex++] = v + b * vertsPerBand + fillVerts.Length;
                    tris[tIndex++] = v + b * vertsPerBand + 1 + fillVerts.Length;
                    tris[tIndex++] = v + (b + 1) * vertsPerBand + 1 + fillVerts.Length;
                }
            }
        }

        if (AAoutline)
        {
            vertsPerBand = outlineVerts.Length / 4;
            bandCount = 3;
        }
        else
        {
            vertsPerBand = outlineVerts.Length / 2;
            bandCount = 1;
        }

        for (int v = 0; v < vertsPerBand-1; v++)
        {
            for (int b = 0; b < bandCount; b++)
            {
                tris[tIndex++] = v + b * vertsPerBand + embossVerts.Length + fillVerts.Length;
                tris[tIndex++] = v + (b + 1) * vertsPerBand + 1 + embossVerts.Length + fillVerts.Length;
                tris[tIndex++] = v + (b + 1) * vertsPerBand + embossVerts.Length + fillVerts.Length;
                tris[tIndex++] = v + b * vertsPerBand + embossVerts.Length + fillVerts.Length;
                tris[tIndex++] = v + b * vertsPerBand + 1 + embossVerts.Length + fillVerts.Length;
                tris[tIndex++] = v + (b + 1) * vertsPerBand + 1 + embossVerts.Length + fillVerts.Length;
            }
        }

        // Free outline AA caps
        if (GetOutline() == Outline.Free && AAoutline)
        {
            int vertsInBand = outlineVerts.Length / 4;
            tris[tIndex++] = 0 + embossVerts.Length + fillVerts.Length;
            tris[tIndex++] = vertsInBand * 2 + embossVerts.Length + fillVerts.Length;
            tris[tIndex++] = vertsInBand + embossVerts.Length + fillVerts.Length;
            tris[tIndex++] = 0 + embossVerts.Length + fillVerts.Length;
            tris[tIndex++] = vertsInBand * 3 + embossVerts.Length + fillVerts.Length;
            tris[tIndex++] = vertsInBand * 2 + embossVerts.Length + fillVerts.Length;

            tris[tIndex++] = vertsInBand * 1 - 1 + embossVerts.Length + fillVerts.Length;
            tris[tIndex++] = vertsInBand * 3 - 1 + embossVerts.Length + fillVerts.Length;
            tris[tIndex++] = vertsInBand * 2 - 1 + embossVerts.Length + fillVerts.Length;
            tris[tIndex++] = vertsInBand * 1 - 1 + embossVerts.Length + fillVerts.Length;
            tris[tIndex++] = vertsInBand * 4 - 1 + embossVerts.Length + fillVerts.Length;
            tris[tIndex++] = vertsInBand * 3 - 1 + embossVerts.Length + fillVerts.Length;
        }

        if (multipleMaterials)
        {
            int ii = 0;
            int[] outlineTriangles = new int[GetOutlineTriangleCount(outlineVerts, AAoutline) * 3];
            int[] restOfTriangles = new int[tris.Length - GetOutlineTriangleCount(outlineVerts, AAoutline) * 3];
            mesh.subMeshCount = 2;

            for (; ii < restOfTriangles.Length; ii++)
            {
                restOfTriangles[ii] = tris[ii];
            }
            if (GetTexturing1() == UVMapping.Fill)
            {
                mesh.SetTriangles(restOfTriangles, 0);
            }
            if (GetTexturing2() == UVMapping.Fill)
            {
                mesh.SetTriangles(restOfTriangles, 1);
            }
            for (; ii < tris.Length; ii++)
            {
                outlineTriangles[ii - restOfTriangles.Length] = tris[ii];
            }

            if (GetTexturing1() == UVMapping.Outline)
            {
                mesh.SetTriangles(outlineTriangles, 0);
            }
            if (GetTexturing2() == UVMapping.Outline)
            {
                mesh.SetTriangles(outlineTriangles, 1);
            }
        }
        else
        {

            if (inverseTriangleDrawOrder)
            {
                int len = tris.Length;
                int[] triangles2 = new int[tris.Length];
                for (int i = 0; i < len; i+=3)
                {
                    triangles2[len - i - 3] = tris[i];
                    triangles2[len - i - 3 + 1] = tris[i + 1];
                    triangles2[len - i - 3 + 2] = tris[i + 2];
                }
                tris = triangles2;
            }

            mesh.triangles = tris;
        }
    }
    private void CreateBuilding(Way w)
    {
        Mesh roofm = new Mesh();
        Mesh wallsm = new Mesh();
        Loom.RunAsync(() =>
        {
            Vector3[] nodes = new Vector3[w.nodes.Count];
            Vector2[] xz = new Vector2[w.nodes.Count];

            float height = (float)w.nodes[0].northing % 10 + 2.0f;

            if (w.height != 0)
                height = w.height;

            Vector3 centroid = new Vector3();
            Loom.QueueOnMainThread(()=>{
                Vector3 position;
                RaycastHit hit;
                for (int a = 0; a < w.nodes.Count; a++)
                {
                    Node n = w.nodes[a];
                    position = new Vector3((float)((n.easthing - offsetPositionX) / precision), 5000, (float)((n.northing - offsetPositionZ) / precision));
                    float castH = 0;

                    if (Physics.Raycast(position, -Vector3.up, out hit, Mathf.Infinity, layerMask))
                    {
                        castH = hit.point.y;
                    }
                    nodes[a] = new Vector3(position.x, castH + height, position.z);
                    xz[a] = new Vector2(position.x, position.z);
                    centroid += nodes[a];
                }
                centroid /= w.nodes.Count;
                centroid.y += 1;

            Vector2[] xzRoof = new Vector2[w.nodes.Count - 1];

            for (int a = 0; a < xzRoof.Length; a++)
            {
                xzRoof[a] = xz[a];
            }

            Triangulator tr = new Triangulator(xzRoof);

            int[] indices = tr.Triangulate();

            // Create the mesh

            Vector2[] uvs = new Vector2[nodes.Length];
            for (int a = 0; a < nodes.Length; a++)
            {
                if (a < nodes.Length - 1)
                {
                    uvs[a] = new Vector2(Mathf.Abs(nodes[a].x - nodes[a + 1].x), Mathf.Abs(nodes[a].z - nodes[a + 1].z));
                }
                else
                {
                    uvs[a] = new Vector2(1, 1);
                }
            }

            // Set up game object with mesh;

                centroid = new Vector3(centroid.x, centroid.y, centroid.z);
                BuildingCountourMesh(nodes, wallsm);
                roofm.vertices = nodes;
                roofm.triangles = indices;
                roofm.uv = uvs;
                roofm.RecalculateNormals();
                roofm.RecalculateBounds();

                GameObject build = new GameObject();
                build.name = w.id.ToString();

                build.transform.parent = this.transform;
                GameObject roof = new GameObject();
                //roof.transform.position = new Vector3(0,baseHeight,0);
                roof.name = (2 * w.id).ToString();
                mapManager.mapHash.Add(2 * w.id);
                wayList.Add(2 * w.id);

                GameObject walls = new GameObject();
                walls.name = (3 * w.id).ToString();
                //walls.transform.position = new Vector3(0,baseHeight,0);
                mapManager.mapHash.Add(3 * w.id);
                wayList.Add(3 * w.id);

                if (w.name != null)
                {
                    GameObject label = new GameObject();
                    FloatingLabel lb = label.AddComponent<FloatingLabel>();
                    lb.transform.parent = roof.transform;
                    lb.text = w.name;
                    lb.target = GameObject.FindGameObjectWithTag("Player").transform;
                    lb.transform.position = centroid;
                }
                walls.transform.parent = build.transform;
                roof.transform.parent = build.transform;
                MeshCollider wallmc = walls.AddComponent<MeshCollider>();
                MeshCollider roofmc = roof.AddComponent<MeshCollider>();

                walls.AddComponent(typeof(MeshRenderer));
                MeshFilter filter = walls.AddComponent(typeof(MeshFilter)) as MeshFilter;
                filter.mesh = wallsm;
                walls.GetComponent<MeshRenderer>().material = buildingMaterial;
                if (w.height != 0)
                    walls.GetComponent<MeshRenderer>().material = Resources.Load("Materials/Real Height Material") as Material;

                //walls.transform.parent = transform;

                wallmc.sharedMesh = wallsm;

                roof.AddComponent(typeof(MeshRenderer));
                roof.AddComponent(typeof(MeshCollider));
                MeshFilter filter2 = roof.AddComponent(typeof(MeshFilter)) as MeshFilter;
                filter2.mesh = roofm;

                roofmc.sharedMesh = roofm;
                roof.GetComponent<MeshRenderer>().material = buildingMaterial;
                if (w.height != 0)
                    roof.GetComponent<MeshRenderer>().material = Resources.Load("Materials/Real Height Material") as Material;
                roof.transform.parent = transform;
            });
        });
    }
    private void CreateGroundArea(Way w)
    {
        Vector3[] nodes = new Vector3[w.nodes.Count];
        Vector2[] xz = new Vector2[w.nodes.Count];

        float height = 0;

        if (w.height != 0)
            height = w.height;

        Vector3 centroid = new Vector3();
        for (int a = 0; a < w.nodes.Count; a++)
        {
            RaycastHit hit;
            Node n = w.nodes[a];
            nodes[a] = new Vector3((float)((n.easthing - offsetPositionX) / precision), 5000, (float)((n.northing - offsetPositionZ) / precision));
            if (Physics.Raycast(nodes[a], -Vector3.up, out hit, Mathf.Infinity, layerMask))
            {
                nodes[a].y = hit.point.y + height + 0.5f;
            }
            else
            {
                nodes[a].y = 1;
            }
            xz[a] = new Vector2((float)((n.easthing - offsetPositionX) / precision), (float)((n.northing - offsetPositionZ) / precision));
            centroid += nodes[a];
        }
        centroid /= w.nodes.Count;
        centroid.y += 1;

          //  Vector3 position = new Vector3(centroid.x, 5000, centroid.z);
        float baseHeight = 0;

        /*RaycastHit hit;
        if (Physics.Raycast(position, -Vector3.up, out hit, Mathf.Infinity, layerMask))
        {
            baseHeight = hit.point.y;
        }*/
        //centroid = new Vector3(centroid.x, centroid.y + baseHeight, centroid.z);
        GameObject build = new GameObject();
        //build.transform.position = new Vector3(0, centroid.y, 0);
        build.name = w.id.ToString();
        mapManager.mapHash.Add(w.id);
        wayList.Add(w.id);
        build.isStatic = true;
        build.transform.parent = this.transform;
        GameObject roof = new GameObject();
           // roof.transform.position = new Vector3(0, centroid.y, 0);
        roof.name = (2 * w.id).ToString();
        mapManager.mapHash.Add(2 * w.id);
        wayList.Add(2 * w.id);
        roof.isStatic = true;
        if (w.name != null)
        {
            GameObject label = new GameObject();
            FloatingLabel lb = label.AddComponent<FloatingLabel>();
            lb.text = w.name;
            lb.transform.position = centroid;
            lb.target = GameObject.FindGameObjectWithTag("Player").transform;
            label.transform.parent = build.transform;
        }
        roof.transform.parent = build.transform;

        Vector2[] xzRoof = new Vector2[w.nodes.Count - 1];

        for (int a = 0; a < xzRoof.Length; a++)
        {
            xzRoof[a] = xz[a];
        }

        Triangulator tr = new Triangulator(xzRoof);

        int[] indices = tr.Triangulate();
        // Create the mesh
        Mesh roofm = new Mesh();
        roofm.vertices = nodes;
        roofm.triangles = indices;

        Vector2[] uvs = new Vector2[nodes.Length];
        for (int a = 0; a < nodes.Length; a++)
        {
            if (a < nodes.Length - 1)
            {
                uvs[a] = new Vector2(Mathf.Abs(nodes[a].x) / nodes[nodes.Length - 1].x, Mathf.Abs(nodes[a].z) / nodes[nodes.Length - 1].x);
            }
            else
            {
                uvs[a] = new Vector2(1, 1);
            }
        }

        roofm.uv = uvs;
        roofm.RecalculateNormals();
        roofm.RecalculateBounds();

        roof.AddComponent(typeof(MeshRenderer));
        MeshFilter filter2 = roof.AddComponent(typeof(MeshFilter)) as MeshFilter;
        roof.AddComponent<MeshCollider>();
        filter2.mesh = roofm;
        if (w.type == WayType.Parking)
            roof.GetComponent<MeshRenderer>().material = Resources.Load("Materials/Parking Material") as Material;
        if (w.type == WayType.Park)
            roof.GetComponent<MeshRenderer>().material = Resources.Load("Materials/Park Material") as Material;
        if (w.type == WayType.RiverBank)
            roof.GetComponent<MeshRenderer>().material = Resources.Load("Materials/River Material") as Material;

        roof.transform.parent = transform;
    }
        /// <summary>
        /// Processes the indices to triangle.
        /// </summary>
        /// <param name="indices">The indices.</param>
        private IEnumerable<Triangle> TessellatePolygon(IEnumerable<int> indices)
        {
            var triangulator = new Triangulator(_currentMeshGeometry.Vertices.Select(vertex => vertex.Position).ToList(), indices);

            return triangulator.GetTriangles().Select(triangle => new Triangle(triangle.Item1, triangle.Item2, triangle.Item3));
        }