예제 #1
0
        public static List <IGH_GeometricGoo> OgrGeomToGHGoo(OSGeo.OGR.Geometry geom, Transform transform)
        {
            List <IGH_GeometricGoo> gGoo = new List <IGH_GeometricGoo>();

            switch (geom.GetGeometryType())
            {
            case wkbGeometryType.wkbGeometryCollection:
            case wkbGeometryType.wkbGeometryCollection25D:
            case wkbGeometryType.wkbGeometryCollectionM:
            case wkbGeometryType.wkbGeometryCollectionZM:
                OSGeo.OGR.Geometry sub_geom;
                for (int gi = 0; gi < geom.GetGeometryCount(); gi++)
                {
                    sub_geom = geom.GetGeometryRef(gi);
                    gGoo.AddRange(GetGoo(sub_geom, transform));
                    sub_geom.Dispose();
                }
                break;

            default:
                gGoo = GetGoo(geom, transform);
                break;
            }

            return(gGoo);
        }
        public static bool NotStrictEqualityGeomType(this Geometry geom, Geometry other_geom)
        {
            string str_type1 = geom.GetGeometryType().ToString().ToUpper().Replace("WKB", "").Replace("MULTI", "");
            string str_type2 = other_geom.GetGeometryType().ToString().ToUpper().Replace("WKB", "").Replace("MULTI", "");

            if (str_type1.Equals(str_type2))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
예제 #3
0
        //read data really
        private static FeatureCollection GetFeatureCollection(OSGeo.OGR.Layer layer, GisSmartTools.Data.Schema schema)
        {
            FeatureCollection fc = new FeatureCollection();

            OSGeo.OGR.Feature     feature;
            OSGeo.OGR.FeatureDefn posDefn = layer.GetLayerDefn();
            int fieldCount = posDefn.GetFieldCount();
            int iField     = 0;

            //read all the features in layer
            while ((feature = layer.GetNextFeature()) != null)
            {
                OSGeo.OGR.Geometry         geometry = feature.GetGeometryRef();
                GisSmartTools.Data.Feature feat     = new Feature(feature.GetFID(), schema, null);
                //get and save feature's attributes
                for (iField = 0; iField < fieldCount; iField++)
                {
                    OSGeo.OGR.FieldDefn oField = posDefn.GetFieldDefn(iField);
                    Object    objAttr;
                    FieldType ft = oField.GetFieldType();
                    switch (ft)
                    {
                    case FieldType.OFTString:
                        objAttr = feature.GetFieldAsString(iField);
                        break;

                    case FieldType.OFTInteger:
                        objAttr = feature.GetFieldAsInteger(iField);
                        break;

                    case FieldType.OFTReal:
                        objAttr = feature.GetFieldAsDouble(iField);
                        break;

                    case FieldType.OFTWideString:
                        objAttr = feature.GetFieldAsString(iField);
                        break;

                    case FieldType.OFTStringList:
                        objAttr = feature.GetFieldAsStringList(iField);
                        break;

                    case FieldType.OFTIntegerList:
                        int outCount;
                        objAttr = feature.GetFieldAsIntegerList(iField, out outCount);
                        break;

                    case FieldType.OFTRealList:
                        int outCount2;
                        objAttr = feature.GetFieldAsDoubleList(iField, out outCount2);
                        break;

                    case FieldType.OFTWideStringList:
                        objAttr = feature.GetFieldAsStringList(iField);
                        break;

                    default:
                        objAttr = feature.GetFieldAsString(iField);
                        break;
                    }
                    feat.AddAttribute(oField.GetName(), objAttr);
                }

                //get geometry
                if (geometry != null)
                {
                    OSGeo.OGR.wkbGeometryType goetype = geometry.GetGeometryType();
                    switch (goetype)    //according to the type, we operate differently
                    {
                    case wkbGeometryType.wkbPoint:
                        if (geometry != null && goetype == wkbGeometryType.wkbPoint)
                        {
                            feat.geometry = new PointD(geometry.GetX(0), geometry.GetY(0));
                        }
                        //add feature to featureCollection
                        fc.InsertFeature(feat);
                        break;

                    case wkbGeometryType.wkbLineString:
                        List <PointD> pointlist  = new List <PointD>();
                        int           pointcount = geometry.GetPointCount();
                        for (int k = 0; k < pointcount; k++)
                        {
                            pointlist.Add(new PointD(geometry.GetX(k), geometry.GetY(k)));
                        }
                        feat.geometry = new SimplePolyline(pointlist);
                        //add feature to featureCollection
                        fc.InsertFeature(feat);
                        break;

                    case wkbGeometryType.wkbMultiLineString:
                        feat.geometry = GetPolyline(geometry);
                        fc.InsertFeature(feat);
                        break;

                    case wkbGeometryType.wkbPolygon:
                        feat.geometry = GetSimplePolygon(geometry);
                        //add feature to featureCollection
                        fc.InsertFeature(feat);
                        break;

                    case wkbGeometryType.wkbMultiPolygon:
                        feat.geometry = GetPolygon(geometry);
                        fc.InsertFeature(feat);
                        break;

                    default:
                        //we don't support another geometry types,
                        //so we don't load those records to avoid errors
                        break;
                    }
                }
                else
                {
                    Console.WriteLine("kkkkkkkkkkkkkkkkkkkkkkkkkkkkkk");
                }
            }

            return(fc);
        }
예제 #4
0
        public static bool CovertRegion2Line(string path, string savePath)
        {
            try
            {
                OSGeo.OGR.Ogr.RegisterAll();
                OSGeo.OGR.Driver dr = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
                if (dr == null)
                {
                    Console.WriteLine("启动驱动失败!\n");
                }

                OSGeo.OGR.DataSource ds    = dr.Open(path, 0);
                int             layerCount = ds.GetLayerCount();
                OSGeo.OGR.Layer layer      = ds.GetLayerByIndex(0);
                FeatureDefn     fdf        = layer.GetLayerDefn();
                int             fieldCount = fdf.GetFieldCount();

                // 创建数据源
                DataSource oDS = dr.CreateDataSource(savePath, null);
                if (oDS == null)
                {
                    Console.WriteLine("创建矢量文件【%s】失败!\n", savePath);
                    return(false);
                }
                OSGeo.OSR.SpatialReference srs = layer.GetSpatialRef();
                // 创建图层,创建一个多边形图层,这里没有指定空间参考,如果需要的话,需要在这里进行指定
                Layer oLayer = oDS.CreateLayer("line", srs, OSGeo.OGR.wkbGeometryType.wkbMultiLineString, null);

                if (oLayer == null)
                {
                    Console.WriteLine("图层创建失败!\n");
                    return(false);
                }
                for (int i = 0; i < fieldCount; i++)
                {
                    FieldDefn fieldDefn = fdf.GetFieldDefn(i);
                    oLayer.CreateField(fieldDefn, 1);
                }
                FeatureDefn       oDefn = oLayer.GetLayerDefn();
                OSGeo.OGR.Feature feat;
                while ((feat = layer.GetNextFeature()) != null)
                {
                    Feature            oFeatureMulty = new Feature(oDefn);
                    OSGeo.OGR.Geometry geometry      = feat.GetGeometryRef();
                    for (int i = 0; i < fieldCount; i++)
                    {
                        string value = feat.GetFieldAsString(i);
                        oFeatureMulty.SetField(i, value);
                    }
                    OSGeo.OGR.wkbGeometryType goetype = geometry.GetGeometryType();
                    if (goetype == OSGeo.OGR.wkbGeometryType.wkbPolygon)
                    {
                        Geometry tempGeo = new Geometry(wkbGeometryType.wkbMultiLineString);
                        int      count   = geometry.GetGeometryCount();
                        for (int j = 0; j < count; j++)
                        {
                            Geometry line = new Geometry(wkbGeometryType.wkbLinearRing);
                            Geometry geo  = geometry.GetGeometryRef(j);
                            for (int i = 0; i < geo.GetPointCount(); i++)
                            {
                                double x = geo.GetX(i);
                                double y = geo.GetY(i);
                                line.AddPoint(x, y, 0);
                            }
                            tempGeo.AddGeometryDirectly(line);
                        }
                        oFeatureMulty.SetGeometry(tempGeo);
                    }
                    oLayer.SetFeature(oFeatureMulty);
                }
                oLayer.Dispose();
                layer.Dispose();
                oDS.Dispose();
                ds.Dispose();
                dr.Dispose();
            }
            catch
            { }
            return(false);
        }
예제 #5
0
        /// <summary>
        /// 转换并纠偏,只使用与火星坐标纠偏
        /// </summary>
        /// <param name="dataTable">数据表,如果是点表中含X,Y字段,如果是线和面,表中含有PATH字段</param>
        /// <param name="filePath">存储路径</param>
        /// <param name="geoType">数据类型,暂时支持简单的点线面</param>
        //public static void saveShpFile(DataTable dataTable,string filePath,wkbGeometryType geoType)
        //{
        //    saveShpFile(dataTable, filePath, geoType, ProjectConvert.GCJ_WGS);
        //}
        /// <summary>
        /// 导出shp数据到表格
        /// </summary>
        /// <param name="path">文件路径</param>
        /// <returns>DataTable</returns>
        public static DataTable GetData(string path)
        {
            try
            {
                OSGeo.OGR.Ogr.RegisterAll();
                OSGeo.OGR.Driver dr = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");

                if (dr == null)
                {
                    Console.WriteLine("启动驱动失败!\n");
                }

                OSGeo.OGR.DataSource ds    = dr.Open(path, 0);
                int             layerCount = ds.GetLayerCount();
                OSGeo.OGR.Layer layer      = ds.GetLayerByIndex(0);
                DataTable       dataTable  = new DataTable();
                FeatureDefn     fdf        = layer.GetLayerDefn();
                int             fieldCount = fdf.GetFieldCount();
                for (int i = 0; i < fieldCount; i++)
                {
                    dataTable.Columns.Add(fdf.GetFieldDefn(i).GetName(), Type.GetType("System.String"));
                }
                if (fdf.GetGeomType() == OSGeo.OGR.wkbGeometryType.wkbPoint)
                {
                    if (!dataTable.Columns.Contains("X"))
                    {
                        dataTable.Columns.Add("X", Type.GetType("System.String"));
                    }
                    if (!dataTable.Columns.Contains("Y"))
                    {
                        dataTable.Columns.Add("Y", Type.GetType("System.String"));
                    }
                }
                else if (fdf.GetGeomType() == OSGeo.OGR.wkbGeometryType.wkbPolygon || fdf.GetGeomType() == OSGeo.OGR.wkbGeometryType.wkbLineString)
                {
                    if (!dataTable.Columns.Contains("PATH"))
                    {
                        dataTable.Columns.Add("PATH", Type.GetType("System.String"));
                    }
                }
                OSGeo.OGR.Feature feat;
                while ((feat = layer.GetNextFeature()) != null)
                {
                    DataRow            row      = dataTable.NewRow();
                    OSGeo.OGR.Geometry geometry = feat.GetGeometryRef();
                    for (int i = 0; i < fieldCount; i++)
                    {
                        string value = feat.GetFieldAsString(i);
                        row[i] = value.Replace(",", "");
                    }
                    OSGeo.OGR.wkbGeometryType goetype = geometry.GetGeometryType();
                    if (goetype == OSGeo.OGR.wkbGeometryType.wkbPoint)
                    {
                        double x = geometry.GetX(0);
                        double y = geometry.GetY(0);
                        row["X"] = x.ToString();
                        row["Y"] = y.ToString();
                    }
                    else if (goetype == OSGeo.OGR.wkbGeometryType.wkbLineString)
                    {
                        string points = "";
                        for (int i = 0; i < geometry.GetPointCount(); i++)
                        {
                            double x = geometry.GetX(i);
                            double y = geometry.GetY(i);
                            points += x.ToString() + "|" + y.ToString() + ";";
                        }
                        if (points != "")
                        {
                            points.Substring(0, points.Length - 1);
                        }
                        row["PATH"] = points;
                    }
                    else if (goetype == OSGeo.OGR.wkbGeometryType.wkbPolygon)
                    {
                        int    count  = geometry.GetGeometryCount();
                        string points = "";
                        for (int j = 0; j < count; j++)
                        {
                            Geometry geo = geometry.GetGeometryRef(j);
                            for (int i = 0; i < geo.GetPointCount(); i++)
                            {
                                double x = geo.GetX(i);
                                double y = geo.GetY(i);
                                points += x.ToString() + "|" + y.ToString() + ";";
                            }
                            if (points != "")
                            {
                                points.Substring(0, points.Length - 1);
                            }
                            points += "|";
                        }
                        if (points != "")
                        {
                            points.Substring(0, points.Length - 1);
                        }
                        row["PATH"] = points;
                    }
                }
                layer.Dispose();
                ds.Dispose();
                dr.Dispose();
                return(dataTable);
            }
            catch
            {
                return(null);
            }
        }
예제 #6
0
        /// <summary>
        /// This is the method that actually does the work.
        /// </summary>
        /// <param name="DA">The DA object is used to retrieve from inputs and store in outputs.</param>
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Curve boundary = null;

            DA.GetData <Curve>(0, ref boundary);

            int zoom = -1;

            DA.GetData <int>(1, ref zoom);

            string filePath = string.Empty;

            DA.GetData <string>(2, ref filePath);
            if (!filePath.EndsWith(@"\"))
            {
                filePath = filePath + @"\";
            }

            string prefix = string.Empty;

            DA.GetData <string>(3, ref prefix);
            if (prefix == "")
            {
                prefix = mbSource;
            }

            string URL = mbURL;

            string mbToken = string.Empty;

            DA.GetData <string>(4, ref mbToken);
            if (mbToken == "")
            {
                string hmbToken = System.Environment.GetEnvironmentVariable("HERONMAPBOXTOKEN");
                if (hmbToken != null)
                {
                    mbToken = hmbToken;
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Using Mapbox token stored in Environment Variable HERONMAPBOXTOKEN.");
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "No Mapbox token is specified.  Please get a valid token from mapbox.com");
                    return;
                }
            }

            bool run = false;

            DA.GetData <bool>("Run", ref run);


            ///GDAL setup
            RESTful.GdalConfiguration.ConfigureOgr();
            OSGeo.OGR.Ogr.RegisterAll();
            RESTful.GdalConfiguration.ConfigureGdal();


            GH_Curve  imgFrame;
            GH_String tCount;
            GH_Structure <GH_String>        fnames        = new GH_Structure <GH_String>();
            GH_Structure <GH_String>        fvalues       = new GH_Structure <GH_String>();
            GH_Structure <IGH_GeometricGoo> gGoo          = new GH_Structure <IGH_GeometricGoo>();
            GH_Structure <GH_String>        gtype         = new GH_Structure <GH_String>();
            GH_Structure <IGH_GeometricGoo> gGooBuildings = new GH_Structure <IGH_GeometricGoo>();



            int tileTotalCount      = 0;
            int tileDownloadedCount = 0;

            ///Get image frame for given boundary
            if (!boundary.GetBoundingBox(true).IsValid)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Boundary is not valid.");
                return;
            }
            BoundingBox boundaryBox = boundary.GetBoundingBox(true);

            //create cache folder for vector tiles
            string        cacheLoc       = filePath + @"HeronCache\";
            List <string> cachefilePaths = new List <string>();

            if (!Directory.Exists(cacheLoc))
            {
                Directory.CreateDirectory(cacheLoc);
            }

            //tile bounding box array
            List <Point3d> boxPtList = new List <Point3d>();


            //get the tile coordinates for all tiles within boundary
            var ranges  = Convert.GetTileRange(boundaryBox, zoom);
            var x_range = ranges.XRange;
            var y_range = ranges.YRange;

            if (x_range.Length > 100 || y_range.Length > 100)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "This tile range is too big (more than 100 tiles in the x or y direction). Check your units.");
                return;
            }

            ///cycle through tiles to get bounding box
            List <Polyline> tileExtents = new List <Polyline>();
            List <double>   tileHeight  = new List <double>();
            List <double>   tileWidth   = new List <double>();

            for (int y = (int)y_range.Min; y <= y_range.Max; y++)
            {
                for (int x = (int)x_range.Min; x <= x_range.Max; x++)
                {
                    //add bounding box of tile to list for translation
                    Polyline tileExtent = Heron.Convert.GetTileAsPolygon(zoom, y, x);
                    tileExtents.Add(tileExtent);
                    tileWidth.Add(tileExtent[0].DistanceTo(tileExtent[1]));
                    tileHeight.Add(tileExtent[1].DistanceTo(tileExtent[2]));

                    boxPtList.AddRange(tileExtent.ToList());
                    cachefilePaths.Add(cacheLoc + mbSource.Replace(" ", "") + zoom + "-" + x + "-" + y + ".mvt");
                    tileTotalCount = tileTotalCount + 1;
                }
            }

            tCount = new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)");

            ///bounding box of tile boundaries
            BoundingBox bboxPts = new BoundingBox(boxPtList);

            ///convert bounding box to polyline
            List <Point3d> imageCorners = bboxPts.GetCorners().ToList();

            imageCorners.Add(imageCorners[0]);
            imgFrame = new GH_Curve(new Rhino.Geometry.Polyline(imageCorners).ToNurbsCurve());

            ///tile range as string for (de)serialization of TileCacheMeta
            string tileRangeString = "Tile range for zoom " + zoom.ToString() + ": "
                                     + x_range[0].ToString() + "-"
                                     + y_range[0].ToString() + " to "
                                     + x_range[1].ToString() + "-"
                                     + y_range[1].ToString();

            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, tileRangeString);

            ///Query Mapbox URL
            ///download all tiles within boundary

            ///API to query
            string mbURLauth = mbURL + mbToken;

            if (run == true)
            {
                for (int y = (int)y_range.Min; y <= (int)y_range.Max; y++)
                {
                    for (int x = (int)x_range.Min; x <= (int)x_range.Max; x++)
                    {
                        //create tileCache name
                        string tileCache    = mbSource.Replace(" ", "") + zoom + "-" + x + "-" + y + ".mvt";
                        string tileCacheLoc = cacheLoc + tileCache;

                        //check cache folder to see if tile image exists locally
                        if (File.Exists(tileCacheLoc))
                        {
                        }

                        else
                        {
                            string urlAuth = Heron.Convert.GetZoomURL(x, y, zoom, mbURLauth);
                            System.Net.WebClient client = new System.Net.WebClient();
                            client.DownloadFile(urlAuth, tileCacheLoc);
                            client.Dispose();

                            ///https://gdal.org/development/rfc/rfc59.1_utilities_as_a_library.html
                            ///http://osgeo-org.1560.x6.nabble.com/gdal-dev-How-to-convert-shapefile-to-geojson-using-c-bindings-td5390953.html#a5391028
                            ///ogr2ogr is slow
                            //OSGeo.GDAL.Dataset httpDS = OSGeo.GDAL.Gdal.OpenEx("MVT:"+urlAuth,4,null,null,null);
                            //var transOptions = new OSGeo.GDAL.GDALVectorTranslateOptions(new[] { "-s_srs","EPSG:3857", "-t_srs", "EPSG:4326","-skipfailures" });
                            //var transDS = OSGeo.GDAL.Gdal.wrapper_GDALVectorTranslateDestName(mvtLoc + zoom + "-" + x + "-" + y , httpDS, transOptions, null, null);
                            //httpDS.Dispose();
                            //transDS.Dispose();

                            tileDownloadedCount = tileDownloadedCount + 1;
                        }
                    }
                }
            }

            //add to tile count total
            tCount = new GH_String(tileTotalCount + " tiles (" + tileDownloadedCount + " downloaded / " + (tileTotalCount - tileDownloadedCount) + " cached)");
            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, tCount.ToString());


            ///Build a VRT file
            ///https://stackoverflow.com/questions/55386597/gdal-c-sharp-wrapper-for-vrt-doesnt-write-a-vrt-file

            //string vrtFile = cacheLoc + "mapboxvector.vrt";
            //AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, vrtFile);
            //var vrtOptions = new OSGeo.GDAL.GDALBuildVRTOptions(new[] { "-overwrite" });
            //var vrtDataset = OSGeo.GDAL.Gdal.wrapper_GDALBuildVRT_names(vrtFile, cachefilePaths.ToArray(), vrtOptions, null, null);
            //vrtDataset.Dispose();


            ///Set transform from input spatial reference to Rhino spatial reference
            ///TODO: look into adding a step for transforming to CRS set in SetCRS
            OSGeo.OSR.SpatialReference rhinoSRS = new OSGeo.OSR.SpatialReference("");
            rhinoSRS.SetWellKnownGeogCS("WGS84");

            ///TODO: verify the userSRS is valid
            ///TODO: use this as override of global SetSRS
            OSGeo.OSR.SpatialReference userSRS = new OSGeo.OSR.SpatialReference("");
            //userSRS.SetFromUserInput(userSRStext);
            userSRS.SetFromUserInput("WGS84");


            OSGeo.OSR.SpatialReference sourceSRS = new SpatialReference("");
            sourceSRS.SetFromUserInput("EPSG:3857");

            ///These transforms move and scale in order to go from userSRS to XYZ and vice versa
            Transform userSRSToModelTransform   = Heron.Convert.GetUserSRSToModelTransform(userSRS);
            Transform modelToUserSRSTransform   = Heron.Convert.GetModelToUserSRSTransform(userSRS);
            Transform sourceToModelSRSTransform = Heron.Convert.GetUserSRSToModelTransform(sourceSRS);
            Transform modelToSourceSRSTransform = Heron.Convert.GetModelToUserSRSTransform(sourceSRS);

            //OSGeo.GDAL.Driver gdalOGR = OSGeo.GDAL.Gdal.GetDriverByName("VRT");
            //var ds = OSGeo.GDAL.Gdal.OpenEx(vrtFile, 4, ["VRT","MVT"], null, null);


            int t = 0;

            foreach (string mvtTile in cachefilePaths)// cachefilePaths)
            {
                OSGeo.OGR.Driver     drv        = OSGeo.OGR.Ogr.GetDriverByName("MVT");
                OSGeo.OGR.DataSource ds         = OSGeo.OGR.Ogr.Open("MVT:" + mvtTile, 0);
                string[]             mvtOptions = new[] { "CLIP", "NO" };
                //OSGeo.OGR.DataSource ds = drv.Open(mvtTile, 0);

                if (ds == null)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Error, "The vector datasource was unreadable by this component. It may not a valid file type for this component or otherwise null/empty.");
                    return;
                }

                ///Morph raw mapbox tile points to geolocated tile
                Vector3d  moveDir   = tileExtents[t].ElementAt(0) - new Point3d(0, 0, 0);
                Transform move      = Transform.Translation(moveDir);
                Transform scale     = Transform.Scale(Plane.WorldXY, tileWidth[t] / 4096, tileHeight[t] / 4096, 1);
                Transform scaleMove = Transform.Multiply(move, scale);

                for (int iLayer = 0; iLayer < ds.GetLayerCount(); iLayer++)
                {
                    OSGeo.OGR.Layer layer = ds.GetLayerByIndex(iLayer);

                    long count        = layer.GetFeatureCount(1);
                    int  featureCount = System.Convert.ToInt32(count);
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Layer #" + iLayer + " " + layer.GetName() + " has " + featureCount + " features");

                    //if (layer.GetName() == "admin" || layer.GetName() == "building")
                    //{

                    OSGeo.OGR.FeatureDefn def = layer.GetLayerDefn();

                    ///Get the field names
                    List <string> fieldnames = new List <string>();
                    for (int iAttr = 0; iAttr < def.GetFieldCount(); iAttr++)
                    {
                        OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iAttr);
                        fnames.Append(new GH_String(fdef.GetNameRef()), new GH_Path(iLayer, t));
                    }

                    ///Loop through geometry
                    OSGeo.OGR.Feature feat;

                    int m = 0;
                    ///error "Self-intersection at or near point..." when zoom gets below 12 for water
                    ///this is an issue with the way mvt simplifies geometries at lower zoom levels and is a known problem
                    ///TODO: look into how to fix invalid geom and return to the typical while loop iterating method
                    //while ((feat = layer.GetNextFeature()) != null)

                    while (true)
                    {
                        try
                        {
                            feat = layer.GetNextFeature();
                        }
                        catch
                        {
                            AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Some features had invalid geometry and were skipped.");
                            continue;
                        }

                        if (feat == null)
                        {
                            break;
                        }


                        OSGeo.OGR.Geometry geom = feat.GetGeometryRef();

                        ///reproject geometry to WGS84 and userSRS
                        ///TODO: look into using the SetCRS global variable here

                        gtype.Append(new GH_String(geom.GetGeometryName()), new GH_Path(iLayer, t, m));
                        Transform tr = scaleMove; // new Transform(1);

                        if (feat.GetGeometryRef() != null)
                        {
                            ///Convert GDAL geometries to IGH_GeometricGoo
                            foreach (IGH_GeometricGoo gMorphed in Heron.Convert.OgrGeomToGHGoo(geom, tr))
                            {
                                //gMorphed.Morph(morph);
                                gGoo.Append(gMorphed, new GH_Path(iLayer, t, m));
                            }

                            if (layer.GetName() == "building")
                            {
                                if (feat.GetFieldAsString(def.GetFieldIndex("extrude")) == "true")
                                {
                                    double unitsConversion = Rhino.RhinoMath.UnitScale(Rhino.RhinoDoc.ActiveDoc.ModelUnitSystem, Rhino.UnitSystem.Meters);
                                    double height          = System.Convert.ToDouble(feat.GetFieldAsString(def.GetFieldIndex("height"))) / unitsConversion;
                                    double min_height      = System.Convert.ToDouble(feat.GetFieldAsString(def.GetFieldIndex("min_height"))) / unitsConversion;
                                    bool   underground     = System.Convert.ToBoolean(feat.GetFieldAsString(def.GetFieldIndex("underground")));

                                    if (geom.GetGeometryType() == wkbGeometryType.wkbPolygon)
                                    {
                                        Extrusion        bldg    = Heron.Convert.OgrPolygonToExtrusion(geom, tr, height, min_height, underground);
                                        IGH_GeometricGoo bldgGoo = GH_Convert.ToGeometricGoo(bldg);
                                        gGooBuildings.Append(bldgGoo, new GH_Path(iLayer, t, m));
                                    }

                                    if (geom.GetGeometryType() == wkbGeometryType.wkbMultiPolygon)
                                    {
                                        List <Extrusion> bldgs = Heron.Convert.OgrMultiPolyToExtrusions(geom, tr, height, min_height, underground);
                                        foreach (Extrusion bldg in bldgs)
                                        {
                                            IGH_GeometricGoo bldgGoo = GH_Convert.ToGeometricGoo(bldg);
                                            gGooBuildings.Append(bldgGoo, new GH_Path(iLayer, t, m));
                                        }
                                    }
                                }
                            }

                            /// Get Feature Values
                            if (fvalues.PathExists(new GH_Path(iLayer, t, m)))
                            {
                                //fvalues.get_Branch(new GH_Path(iLayer, t, m)).Clear();
                            }

                            for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                            {
                                OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                if (feat.IsFieldSet(iField))
                                {
                                    fvalues.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(iLayer, t, m));
                                }
                                else
                                {
                                    fvalues.Append(new GH_String("null"), new GH_Path(iLayer, t, m));
                                }
                            }
                        }
                        m++;
                        geom.Dispose();
                        feat.Dispose();
                    }///end while loop through features

                    //}///end layer by name

                    layer.Dispose();
                }///end loop through layers

                ds.Dispose();
                t++;
            }///end loop through mvt tiles

            //write out new tile range metadata for serialization
            TileCacheMeta = tileRangeString;



            DA.SetData(0, imgFrame);
            DA.SetDataTree(1, fnames);
            DA.SetDataTree(2, fvalues);
            DA.SetDataTree(3, gGoo);
            DA.SetDataList(4, "copyright Mapbox");
            DA.SetDataTree(5, gtype);
            DA.SetDataTree(6, gGooBuildings);
            DA.SetDataList(7, tileExtents);
        }
예제 #7
0
        public static List <IGH_GeometricGoo> OgrGeomToGHGoo(OSGeo.OGR.Geometry geom, Transform transform)
        {
            List <IGH_GeometricGoo> gGoo = new List <IGH_GeometricGoo>();

            OSGeo.OGR.Geometry sub_geom;

            //find appropriate geometry type in feature and convert to Rhino geometry
            switch (geom.GetGeometryType())
            {
            case wkbGeometryType.wkbPoint25D:
            case wkbGeometryType.wkbPointM:
            case wkbGeometryType.wkbPointZM:
            case wkbGeometryType.wkbPoint:
                gGoo.Add(new GH_Point(Heron.Convert.OgrPointToPoint3d(geom, transform)));
                break;

            case wkbGeometryType.wkbMultiPoint25D:
            case wkbGeometryType.wkbMultiPointZM:
            case wkbGeometryType.wkbMultiPointM:
            case wkbGeometryType.wkbMultiPoint:
                List <GH_Point> gH_Points = new List <GH_Point>();
                foreach (Point3d p in Heron.Convert.OgrMultiPointToPoint3d(geom, transform))
                {
                    gH_Points.Add(new GH_Point(p));
                }
                gGoo.AddRange(gH_Points);
                break;

            case wkbGeometryType.wkbLinearRing:
                gGoo.Add(new GH_Curve(Heron.Convert.OgrLinestringToCurve(geom, transform)));
                break;

            case wkbGeometryType.wkbLineString25D:
            case wkbGeometryType.wkbLineStringM:
            case wkbGeometryType.wkbLineStringZM:
            case wkbGeometryType.wkbLineString:
                gGoo.Add(new GH_Curve(Heron.Convert.OgrLinestringToCurve(geom, transform)));
                break;

            case wkbGeometryType.wkbMultiLineString25D:
            case wkbGeometryType.wkbMultiLineStringZM:
            case wkbGeometryType.wkbMultiLineStringM:
            case wkbGeometryType.wkbMultiLineString:
                List <GH_Curve> gH_Curves = new List <GH_Curve>();
                foreach (Curve crv in Heron.Convert.OgrMultiLinestringToCurves(geom, transform))
                {
                    gH_Curves.Add(new GH_Curve(crv));
                }
                gGoo.AddRange(gH_Curves);
                break;

            case wkbGeometryType.wkbPolygonZM:
            case wkbGeometryType.wkbPolygonM:
            case wkbGeometryType.wkbPolygon25D:
            case wkbGeometryType.wkbPolygon:
                gGoo.Add(new GH_Mesh(Heron.Convert.OgrPolygonToMesh(geom, transform)));
                break;

            case wkbGeometryType.wkbMultiPolygonZM:
            case wkbGeometryType.wkbMultiPolygon25D:
            case wkbGeometryType.wkbMultiPolygonM:
            case wkbGeometryType.wkbMultiPolygon:
                gGoo.Add(new GH_Mesh(Heron.Convert.OgrMultiPolyToMesh(geom, transform)));
                break;

            default:

                ///Feature is of an unrecognized geometry type
                ///Loop through geometry points

                for (int gpc = 0; gpc < geom.GetPointCount(); gpc++)
                {
                    double[] ogrPt = new double[3];
                    geom.GetPoint(gpc, ogrPt);
                    Point3d pt3D = new Point3d(ogrPt[0], ogrPt[1], ogrPt[2]);
                    pt3D.Transform(transform);
                    gGoo.Add(new GH_Point(pt3D));
                }


                for (int gi = 0; gi < geom.GetGeometryCount(); gi++)
                {
                    sub_geom = geom.GetGeometryRef(gi);
                    List <Point3d> geom_list = new List <Point3d>();

                    for (int ptnum = 0; ptnum < sub_geom.GetPointCount(); ptnum++)
                    {
                        double[] pT = new double[3];
                        pT[0] = sub_geom.GetX(ptnum);
                        pT[1] = sub_geom.GetY(ptnum);
                        pT[2] = sub_geom.GetZ(ptnum);

                        Point3d pt3D = new Point3d();
                        pt3D.X = pT[0];
                        pt3D.Y = pT[1];
                        pt3D.Z = pT[2];

                        pt3D.Transform(transform);
                        gGoo.Add(new GH_Point(pt3D));
                    }
                    sub_geom.Dispose();
                }
                break;
            }

            return(gGoo);
        }