Skip to content
Snippets Groups Projects
VectorTile.cs 8.86 KiB
Newer Older
using Mapbox.Vector.Tile;
using System.Collections.Generic;
using System.IO;
using System.Threading.Tasks;
Knuiman, Bart's avatar
Knuiman, Bart committed
using UnityEngine.Networking;

namespace Wander
{
    // Always multiple of 3. Each 3 form a triangle.
    public struct TriangulatedPolygon
Knuiman, Bart's avatar
Knuiman, Bart committed
    public class VectorTile
    {
Knuiman, Bart's avatar
Knuiman, Bart committed
        public bool DownloadStarted => started;
        public bool Valid => valid;
        public bool Finished => finished;
        public bool Triangulated => triangulated;
Knuiman, Bart's avatar
Knuiman, Bart committed
        private bool started;
        private bool valid;
        private bool finished;
        private bool triangulated;
        private Task parseTileTask;
        private List<VectorTileLayer> layers;
        private List<List<TriangulatedPolygon>> polygonLayers;
Knuiman, Bart's avatar
Knuiman, Bart committed
        internal UnityWebRequest request;

        public void StartDownload()
        {
            Debug.Assert(!started);
            request.SendWebRequest();
            started = true;
        }
        {
            if (finished)
                return true;

            if (!request.isDone)
                return false;

Knuiman, Bart's avatar
Knuiman, Bart committed
            if (request.result == UnityWebRequest.Result.Success)
            {
                if (parseTileTask == null)
                {
Knuiman, Bart's avatar
Knuiman, Bart committed
                    var data = request.downloadHandler.data; // call on mainthread.
                    parseTileTask = Task.Run( () =>
                    {
Knuiman, Bart's avatar
Knuiman, Bart committed
                        var stream = new MemoryStream( data );
                        layers = VectorTileParser.Parse( stream );
                    } );
                }
                else if (parseTileTask.IsCompleted)
                {
                    valid = parseTileTask.IsCompletedSuccessfully;
                    finished = true;
                    parseTileTask = null;
                }
            }

            return finished;
        }

        // Number of failed polys to triangulate are returned.
        public int Triangulate()
            if (triangulated )
                return 0;
            int numFailedPolys = 0;
            polygonLayers = new List<List<TriangulatedPolygon>>();
            List<double> vertices = new List<double>();
            List<int> holeIndices = new List<int>();
            for ( int i =0; i < layers.Count; i++ )
            {
                var features = layers[i].VectorTileFeatures;
                var polygons = new List<TriangulatedPolygon>();
                for (int j = 0; j< features.Count; j++)
                {
                    if (features[j].GeometryType != Tile.GeomType.Polygon)
                        continue;
                    vertices.Clear();
                    holeIndices.Clear();
                    var rings = features[j].Geometry;
                    for (int k = 0;k < rings.Count;k++)
                    {
                        if (k != 0) // if is not first ring, this is a hole
                        {
                            holeIndices.Add( vertices.Count / 2 );
                        }
                        var ring = rings[k];
                        for (int q = 0;q < ring.Count;q++)
                        {
                            vertices.Add( ring[q].X );
                            vertices.Add( ring[q].Y );
                        }
                    }
                    try
                    {
                        var indices = EarcutNet.Earcut.Tessellate( vertices, holeIndices );
                        TriangulatedPolygon poly = new TriangulatedPolygon();
                        poly.vertices = new List<Vector2>( indices.Count );
Knuiman, Bart's avatar
Knuiman, Bart committed
                        for (int k = 0;k < indices.Count; k++)
                        {
                            double x = vertices[indices[k]*2];
                            double y = vertices[indices[k]*2+1];
                            poly.vertices.Add( new Vector2( (float)x, (float)y ) );
                        }
                        polygons.Add( poly );
                        Debug.Assert( poly.vertices.Count % 3 == 0 );
                    }
                    catch (Exception)
                    {
                        numFailedPolys++;
                    }
                }
                polygonLayers.Add( polygons );
            }
            triangulated = true;
            return numFailedPolys;
        }

Knuiman, Bart's avatar
Knuiman, Bart committed
        // Calls callback(x, y, channel) for each raster position (256 channels) where each value represents a single channel.
        // If no polygon was hit, 255 is called.
        // If polygon was hit, but no feature was matched, 254 is called.
        public void RenderToTextureSingle( int width, int height, string attributeKeyMatch, List<List<string>> layerNamesList, Func<int, int, byte, bool> callback )
        {
            Debug.Assert( triangulated, "First call Triangulate." );
Knuiman, Bart's avatar
Knuiman, Bart committed
            Debug.Assert( layerNamesList.Count < 254, "254 and 255 are reserved for no hit or no match." );
            bool cancel = false;

            // First match layers to layer names.
            for (int l = 0;l < layers.Count && !cancel;l++)
Knuiman, Bart's avatar
Knuiman, Bart committed
                var layer = layers[l];

                for (int f = 0;f < layer.VectorTileFeatures.Count && !cancel;f++)
Knuiman, Bart's avatar
Knuiman, Bart committed
                    var feature = layer.VectorTileFeatures[f];
                    feature.SelectedLayerIdx = 254;

                    if (feature.GeometryType != Tile.GeomType.Polygon)
                        continue;

                    if (feature.Attributes == null)
                        continue;

                    // Find matching layer.
                    bool matchingLayerFound = false;
                    for (int a = 0;a < feature.Attributes.Count && !matchingLayerFound;a++)
                    {
                        if (feature.Attributes[a].Key != attributeKeyMatch)
                            continue;
                        
                        string function = feature.Attributes[a].Value as string;
                        for (int layerIdx = 0;layerIdx < layerNamesList.Count && !matchingLayerFound;layerIdx++)
                        {
                            for (int layerNameIdx = 0;layerNameIdx < layerNamesList[layerIdx].Count;layerNameIdx++)
                            {
                                if (function.Contains( layerNamesList[layerIdx][layerNameIdx] ))
                                {
                                    feature.SelectedLayerIdx = layerIdx;
                                    matchingLayerFound = true;
                                    break;
                                }
                            }
                        }
                    }
                }
            }

            // For each layer, for each pixel, now check triangle intersections.
            for (int l = 0;l < layers.Count && !cancel;l++)
            {
                var layer = layers[l];
Knuiman, Bart's avatar
Knuiman, Bart committed
                for (int y = 0;y < height && !cancel;y++)
                {
                    for (int x = 0;x < width && !cancel;x++)
Knuiman, Bart's avatar
Knuiman, Bart committed
                        Vector2 p  = new Vector2(x, y);

                        for (int f = 0;f < layer.VectorTileFeatures.Count && !cancel;f++)
                        {
                            var feature = layer.VectorTileFeatures[f];

Knuiman, Bart's avatar
Knuiman, Bart committed
                            if (feature.GeometryType != Tile.GeomType.Polygon)
                                continue;

                            var triangles = polygonLayers[l][f].vertices;
                            bool hit   = false;
Knuiman, Bart's avatar
Knuiman, Bart committed
                            for (int i = 0;i < triangles.Count && !cancel;i += 3)
                            {
                                hit = GeomUtil.PointIsInsideTriangle( p, triangles[i], triangles[i+1], triangles[i+2] );
Knuiman, Bart's avatar
Knuiman, Bart committed
                                if (hit)
Knuiman, Bart's avatar
Knuiman, Bart committed
                                    cancel = callback(x, y, (byte)feature.SelectedLayerIdx); // If SelectedLayerIdx did not match, it was set to 254.
Knuiman, Bart's avatar
Knuiman, Bart committed
                            if (!hit)
Knuiman, Bart's avatar
Knuiman, Bart committed
                                callback( x, y, 255 ); // no hit
Knuiman, Bart's avatar
Knuiman, Bart committed
    }

    public static class VectorTileLoader
    {
Knuiman, Bart's avatar
Knuiman, Bart committed
        public static VectorTile LoadFromUrl( string url, bool autoStart=true )
Knuiman, Bart's avatar
Knuiman, Bart committed
        {
            VectorTile tile = new VectorTile();
Knuiman, Bart's avatar
Knuiman, Bart committed
            tile.request = UnityWebRequest.Get( url );
            if (autoStart)
            {
                tile.StartDownload();
            }
Knuiman, Bart's avatar
Knuiman, Bart committed
            return tile;
        }
    }
}