Example #1
0
 private SpatialEnvelope calculateEnvelope(Geometry geom)
 {
     Envelope env = new Envelope();
     geom.GetEnvelope(env);
     SpatialEnvelope ogrenv = new SpatialEnvelope(env.MinX, env.MinY, env.MaxX, env.MaxY);
     return ogrenv;
 }
Example #2
0
        static void CreateIndexes(DataSource OGRDataSource, string MSSQLConnectionString)
        {
            // Create coordinate transformation
            SpatialReference sourceSRS = new SpatialReference("");
            sourceSRS.ImportFromEPSG(4326);
            SpatialReference targetSRS = new SpatialReference("");
            targetSRS.ImportFromEPSG(900913);
            CoordinateTransformation transform = new CoordinateTransformation(sourceSRS, targetSRS);

            for (int iLayer = 0; iLayer < OGRDataSource.GetLayerCount(); iLayer++)
            {
                Layer OGRLayer = OGRDataSource.GetLayerByIndex(iLayer);
                string layerName = OGRLayer.GetName();

                // Get extent in EPSG:900913
                Envelope extent = new Envelope();
                OGRLayer.GetExtent(extent,0);
                double[] ll = new double[] { extent.MinX, extent.MinY };
                double[] ur = new double[] { extent.MaxX, extent.MaxY };
                transform.TransformPoint(ll);
                transform.TransformPoint(ur);

                using (SqlConnection con = new SqlConnection(MSSQLConnectionString))
                {
                    con.Open();
                    try
                    {
                        // Create primary key/clustered index
                        string pkSQL = string.Format("ALTER TABLE [{0}] ADD CONSTRAINT [PK_{0}] PRIMARY KEY CLUSTERED([id] ASC)  WITH (SORT_IN_TEMPDB = ON);", layerName);
                        using (SqlCommand pkCmd = new SqlCommand(pkSQL, con))
                        {
                            log(TraceLevel.Info, string.Format("Creating clustured index pk_{0} on table {0}...", layerName));
                            pkCmd.CommandTimeout = 0;
                            pkCmd.ExecuteNonQuery();
                        }

                        // Create spatial index
                        OGRLayer.GetExtent(extent, 0);
                        string sidxSQL = string.Format("CREATE SPATIAL INDEX sidx_{0}_ogr_geometry ON [{0}](ogr_geometry) WITH (BOUNDING_BOX = ( {1}, {2}, {3}, {4} ), SORT_IN_TEMPDB = ON );", layerName, ll[0], ll[1], ur[0], ur[1]);
                        using (SqlCommand sidxCmd = new SqlCommand(sidxSQL, con))
                        {
                            log(TraceLevel.Info, string.Format("Creating spatial index sidx_{0}_ogr_geometry on table {0}...", layerName));
                            sidxCmd.CommandTimeout = 0;
                            sidxCmd.ExecuteNonQuery();
                        }
                    }
                    catch (Exception e)
                    {
                        log(TraceLevel.Error, e.Message);
                        Environment.Exit(1);
                    }
                }
            }
        }
Example #3
0
 public static HandleRef getCPtrAndSetReference(Envelope obj, object parent) {
   if (obj != null)
   {
     obj.swigParentRef = parent;
     return obj.swigCPtr;
   }
   else
   {
     return new HandleRef(null, IntPtr.Zero);
   }
 }
Example #4
0
 public static HandleRef getCPtrAndDisown(Envelope obj, object parent) {
   if (obj != null)
   {
     obj.swigCMemOwn = false;
     obj.swigParentRef = parent;
     return obj.swigCPtr;
   }
   else
   {
     return new HandleRef(null, IntPtr.Zero);
   }
 }
        /// <summary>
        /// Boundingbox of the dataset
        /// </summary>
        /// <returns>boundingbox</returns>
        public virtual Envelope GetExtents()
        {
            if (this.envelope == null)
            {
                using (var ogrEnvelope = new OgrEnvelope())
                {
                    int i = ogrLayer.GetExtent(ogrEnvelope, 1);

                    envelope = new Envelope(ogrEnvelope.MinX, ogrEnvelope.MaxX,
                                            ogrEnvelope.MinY, ogrEnvelope.MaxY);
                }
            }


            return(envelope);
        }
Example #6
0
    public bool Insert(Feature f)
    {
        bool     result = false;
        NoteData data   = new NoteData();

        data.fea = f;
        var geo = data.fea.GetGeometryRef();

        Assert.IsNotNull(geo);
        OSGeo.OGR.Envelope envogr = new OSGeo.OGR.Envelope();
        geo.GetEnvelope(envogr);
        Enyim.Collections.Envelope env = new Enyim.Collections.Envelope(envogr.MinX, envogr.MinY, envogr.MaxX, envogr.MaxY);
        envogr.Dispose();
        RTreeNode <NoteData> node = new RTreeNode <NoteData>(data, env);

        tree.Insert(node, env);
        result = true;
        return(result);
    }
Example #7
0
        public virtual IMetadata GetMetadata()
        {
            if (this._Layer == null)
            {
                return(null);
            }

            //计算图像大小-按数据边界
            OSGeo.OGR.Envelope envelope = new OSGeo.OGR.Envelope();
            this._Layer.GetExtent(envelope, 1);

            //提取图像参数值
            MetadataR pMeta = new MetadataR();

            pMeta.MinX       = Math.Round(envelope.MinX, 8);
            pMeta.MaxX       = Math.Round(envelope.MaxX, 8);
            pMeta.MinY       = Math.Round(envelope.MinY, 8);
            pMeta.MaxY       = Math.Round(envelope.MaxY, 8);
            pMeta.IsNorthern = (pMeta.MinY > 0);
            return(pMeta);
        }
Example #8
0
        /************************************* 判断两个Featuer是否重复 *************************************************/
        /// <summary>
        /// 判断两个Featuer是否重复,ori 当前Feat,next 目标Feat
        /// </summary>
        /// <param name="ori"></param>
        /// <param name="next"></param>
        /// <returns></returns>
        public static bool isSame(OSGeo.OGR.Feature ori, OSGeo.OGR.Feature next, double fanWei = 0.1)
        {
            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.OGR.Geometry oriGeom = ori.GetGeometryRef();
            OSGeo.OGR.Envelope oriEnve = new OSGeo.OGR.Envelope();
            oriGeom.GetEnvelope(oriEnve);
            OSGeo.OGR.Geometry nextGeom = next.GetGeometryRef();
            OSGeo.OGR.Envelope nextEnve = new OSGeo.OGR.Envelope();
            nextGeom.GetEnvelope(nextEnve);
            double oriArea  = oriGeom.GetArea();
            double nextArea = nextGeom.GetArea();
            bool   res      =
                Math.Abs(oriEnve.MaxX - nextEnve.MaxX) < fanWei && //外接矩形差
                Math.Abs(oriEnve.MaxY - nextEnve.MaxY) < fanWei &&
                Math.Abs(oriEnve.MinX - nextEnve.MinX) < fanWei &&
                Math.Abs(oriEnve.MinY - nextEnve.MinY) < fanWei;

            //面积?    && Math.Abs(oriArea - nextArea) < 0.1;
            oriGeom.Dispose();
            oriEnve.Dispose();
            nextGeom.Dispose();
            nextEnve.Dispose();
            return(res);
        }
Example #9
0
        /// <summary>
        /// Boundingbox of the dataset
        /// </summary>
        /// <returns>boundingbox</returns>
        public IEnvelope GetExtents()
        {
            if (this._bbox == null)
            {
                OSGeo.OGR.Envelope _OgrEnvelope = new Envelope();
                int i = _OgrLayer.GetExtent(_OgrEnvelope, 1);

                this._bbox = SharpMap.Converters.Geometries.GeometryFactory.CreateEnvelope(
                												 _OgrEnvelope.MinX,
                                                                 _OgrEnvelope.MinY,
                                                                 _OgrEnvelope.MaxX,
                                                                 _OgrEnvelope.MaxY);

            }

            return _bbox;
        }
Example #10
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Curve> boundary = new List <Curve>();

            DA.GetDataList <Curve>(0, boundary);

            string shpFileLoc = "";

            DA.GetData <string>("Shapefile Location", ref shpFileLoc);

            ////int SRef = 3857;
            GdalConfiguration.ConfigureOgr();
            GdalConfiguration.ConfigureGdal();

            OSGeo.OGR.Driver     drv = OSGeo.OGR.Ogr.GetDriverByName("ESRI Shapefile");
            OSGeo.OGR.DataSource ds  = OSGeo.OGR.Ogr.Open(shpFileLoc, 0);

            List <OSGeo.OGR.Layer> layerset = new List <OSGeo.OGR.Layer>();
            List <int>             fc       = new List <int>();

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

                if (layer == null)
                {
                    Console.WriteLine("FAILURE: Couldn't fetch advertised layer " + iLayer);
                    System.Environment.Exit(-1);
                }
                long count        = layer.GetFeatureCount(1);
                int  featureCount = System.Convert.ToInt32(count);
                fc.Add(featureCount);
                layerset.Add(layer);
            }

            //Get OGR envelope of Shapefile
            OSGeo.OGR.Envelope ext = new OSGeo.OGR.Envelope();
            layerset[0].GetExtent(ext, 1);
            Point3d extMin = new Point3d();
            Point3d extMax = new Point3d();

            extMin.X = ext.MinX;
            extMin.Y = ext.MinY;
            extMax.X = ext.MaxX;
            extMax.Y = ext.MaxY;

            OSGeo.OSR.SpatialReference sr = layerset[0].GetSpatialRef();

            OSGeo.OSR.SpatialReference dst = new OSGeo.OSR.SpatialReference("");
            dst.SetWellKnownGeogCS("WGS84");

            //Get the spatial refernce of the input Shapefile
            string sRef;

            sr.ExportToWkt(out sRef);

            OSGeo.OSR.CoordinateTransformation coordTransform = new OSGeo.OSR.CoordinateTransformation(sr, dst);
            OSGeo.OSR.CoordinateTransformation revTransform   = new OSGeo.OSR.CoordinateTransformation(dst, sr);

            //Get bounding box of data in Shapefile
            double[] extMinPT = new double[3] {
                extMin.X, extMin.Y, extMin.Z
            };
            double[] extMaxPT = new double[3] {
                extMax.X, extMax.Y, extMax.Z
            };
            coordTransform.TransformPoint(extMinPT);
            coordTransform.TransformPoint(extMaxPT);
            Point3d     extPTmin = new Point3d(extMinPT[0], extMinPT[1], extMinPT[2]);
            Point3d     extPTmax = new Point3d(extMaxPT[0], extMaxPT[1], extMaxPT[2]);
            Rectangle3d rec      = new Rectangle3d(Plane.WorldXY, Heron.Convert.ToXYZ(extPTmin), Heron.Convert.ToXYZ(extPTmax));

            //Declare trees
            GH_Structure <GH_String> fset    = new GH_Structure <GH_String>();
            GH_Structure <GH_Point>  gset    = new GH_Structure <GH_Point>();
            GH_Structure <GH_String> layname = new GH_Structure <GH_String>();

            OSGeo.OGR.FeatureDefn def = layerset[0].GetLayerDefn();

            //Loop through input boundaries
            for (int i = 0; i < boundary.Count; i++)
            {
                if (rec.BoundingBox.Contains(boundary[i].GetBoundingBox(true).Min) && (rec.BoundingBox.Contains(boundary[i].GetBoundingBox(true).Max)))
                {
                    //Create bounding box for clipping geometry
                    Point3d  min   = Heron.Convert.ToWGS(boundary[i].GetBoundingBox(true).Min);
                    Point3d  max   = Heron.Convert.ToWGS(boundary[i].GetBoundingBox(true).Max);
                    double[] minpT = new double[3];
                    double[] maxpT = new double[3];

                    minpT[0] = min.X;
                    minpT[1] = min.Y;
                    minpT[2] = min.Z;
                    maxpT[0] = max.X;
                    maxpT[1] = max.Y;
                    maxpT[2] = max.Z;
                    revTransform.TransformPoint(minpT);
                    revTransform.TransformPoint(maxpT);

                    OSGeo.OGR.Geometry bbox  = OSGeo.OGR.Geometry.CreateFromWkt("POLYGON((" + min.X + " " + min.Y + ", " + min.X + " " + max.Y + ", " + max.X + " " + max.Y + ", " + max.X + " " + min.Y + ", " + min.X + " " + min.Y + "))");
                    OSGeo.OGR.Geometry ebbox = OSGeo.OGR.Geometry.CreateFromWkt("POLYGON((" + minpT[0] + " " + minpT[1] + ", " + minpT[0] + " " + maxpT[1] + ", " + maxpT[0] + " " + maxpT[1] + ", " + maxpT[0] + " " + minpT[1] + ", " + minpT[0] + " " + minpT[1] + "))");

                    //Clip Shapefile
                    //http://pcjericks.github.io/py-gdalogr-cookbook/vector_layers.html
                    OSGeo.OGR.Layer clipped_layer = layerset[0];
                    clipped_layer.SetSpatialFilter(ebbox);

                    //Loop through geometry
                    OSGeo.OGR.Feature feat;
                    def = clipped_layer.GetLayerDefn();

                    int m = 0;
                    while ((feat = layerset[0].GetNextFeature()) != null)
                    {
                        if (feat.GetGeometryRef() != null)
                        {
                            //Get geometry points and field values
                            OSGeo.OGR.Geometry geom = feat.GetGeometryRef();
                            OSGeo.OGR.Geometry sub_geom;

                            //Start get points if open polylines and points
                            for (int gpc = 0; gpc < geom.GetPointCount(); gpc++)
                            { //Loop through geometry points
                                double[] pT = new double[3];
                                pT[0] = geom.GetX(gpc);
                                pT[1] = geom.GetY(gpc);
                                pT[2] = geom.GetZ(gpc);
                                if (Double.IsNaN(geom.GetZ(gpc)))
                                {
                                    pT[2] = 0;
                                }
                                coordTransform.TransformPoint(pT);

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

                                gset.Append(new GH_Point(Heron.Convert.ToXYZ(pt3D)), new GH_Path(i, m));
                                //End loop through geometry points

                                // Get Feature Values
                                if (fset.PathExists(new GH_Path(i, m)))
                                {
                                    fset.get_Branch(new GH_Path(i, m)).Clear();
                                }
                                for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                                {
                                    OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                    if (feat.IsFieldSet(iField))
                                    {
                                        fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, m));
                                    }
                                    else
                                    {
                                        fset.Append(new GH_String("null"), new GH_Path(i, m));
                                    }
                                }
                                //End Get Feature Values
                            }
                            //End getting points if open polylines or points

                            //Start getting points if closed polylines and multipolygons
                            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++)
                                {
                                    //Loop through geometry points
                                    double[] pT = new double[3];
                                    pT[0] = sub_geom.GetX(ptnum);
                                    pT[1] = sub_geom.GetY(ptnum);
                                    pT[2] = sub_geom.GetZ(ptnum);
                                    coordTransform.TransformPoint(pT);

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

                                    gset.Append(new GH_Point(Heron.Convert.ToXYZ(pt3D)), new GH_Path(i, m, gi));
                                    //End loop through geometry points

                                    // Get Feature Values
                                    if (fset.PathExists(new GH_Path(i, m)))
                                    {
                                        fset.get_Branch(new GH_Path(i, m)).Clear();
                                    }
                                    for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                                    {
                                        OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                        if (feat.IsFieldSet(iField))
                                        {
                                            fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, m));
                                        }
                                        else
                                        {
                                            fset.Append(new GH_String("null"), new GH_Path(i, m));
                                        }
                                    }
                                    //End Get Feature Values
                                }
                                //End getting points from closed polylines
                            }
                            m++;
                        }
                        feat.Dispose();
                    }
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "One or more boundaries may be outside the bounds of the Shapefile dataset.");
                    //return;
                }
            }

            //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);
                fieldnames.Add(fdef.GetNameRef());
            }

            DA.SetData(0, def.GetName());
            DA.SetDataList(1, fc);
            DA.SetData(2, rec);
            DA.SetData(3, sRef);
            DA.SetDataList(4, fieldnames);
            DA.SetDataTree(5, fset);
            DA.SetDataTree(6, gset);
        }
Example #11
0
 public int GetExtent(Envelope extent, int force)
 {
     int ret = OgrPINVOKE.Layer_GetExtent(swigCPtr, Envelope.getCPtr(extent), force);
     if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve();
     return ret;
 }
        public static void ConvertFeatureToRaster(Layer layer, out Dataset outputDataset, double rasterCellSize, string fieldName)
        {
            DriverUtils.RegisterGdalOgrDrivers();

            Envelope envelope = new Envelope();
            layer.GetExtent(envelope, 0);

            //Compute the out raster cell resolutions
            int x_res = Convert.ToInt32((envelope.MaxX - envelope.MinX) / rasterCellSize);
            int y_res = Convert.ToInt32((envelope.MaxY - envelope.MinY) / rasterCellSize);

            //Console.WriteLine("Extent: " + envelope.MaxX + " " + envelope.MinX + " " + envelope.MaxY + " " + envelope.MinY);
            //Console.WriteLine("X resolution: " + x_res);
            //Console.WriteLine("X resolution: " + y_res);

            //Create new tiff in disk
            string tempRaster = "tempZoneRaster.tif";
            if (File.Exists(tempRaster))
            {
                File.Delete(tempRaster);
            }
            OSGeo.GDAL.Driver outputDriver = Gdal.GetDriverByName("GTiff");
            outputDataset = outputDriver.Create(tempRaster, x_res, y_res, 1, DataType.GDT_Int32, null);

            //Extrac srs from input feature
            string inputShapeSrs;
            SpatialReference spatialRefrence = layer.GetSpatialRef();
            spatialRefrence.ExportToWkt(out inputShapeSrs);

            //Assign input feature srs to outpur raster
            outputDataset.SetProjection(inputShapeSrs);

            //Geotransform
            double[] argin = new double[] { envelope.MinX, rasterCellSize, 0, envelope.MaxY, 0, -rasterCellSize };
            outputDataset.SetGeoTransform(argin);

            //Set no data
            Band band = outputDataset.GetRasterBand(1);
            //band.SetNoDataValue(GdalUtilConstants.NoDataValue);
            band.Fill(GdalUtilConstants.NoDataValue, 0.0);

            //Feature to raster rasterize layer options

            //No of bands (1)
            int[] bandlist = new int[] { 1 };

            //Values to be burn on raster (10.0)
            double[] burnValues = new double[] { 10.0 };
            //Dataset myDataset = Gdal.Open(outputRasterFile, Access.GA_Update);

            //additional options

            string[] rasterizeOptions;
            //rasterizeOptions = new string[] { "ALL_TOUCHED=TRUE", "ATTRIBUTE=" + fieldName }; //To set all touched pixels into raster pixel

            rasterizeOptions = new string[] { "ATTRIBUTE=" + fieldName };

            //Rasterize layer
            //Gdal.RasterizeLayer(myDataset, 1, bandlist, layer, IntPtr.Zero, IntPtr.Zero, 1, burnValues, null, null, null); // To burn the given burn values instead of feature attributes
            //Gdal.RasterizeLayer(outputDataset, 1, bandlist, layer, IntPtr.Zero, IntPtr.Zero, 1, burnValues, rasterizeOptions, new Gdal.GDALProgressFuncDelegate(ProgressFunc), "Raster conversion");

            Gdal.RasterizeLayer(outputDataset, 1, bandlist, layer, IntPtr.Zero, IntPtr.Zero, 1, burnValues, rasterizeOptions, null, null);
        }
Example #13
0
 public static HandleRef getCPtr(Envelope obj)
 {
     return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
 }
Example #14
0
        /// <summary>
        /// Boundingbox of the dataset
        /// </summary>
        /// <returns>boundingbox</returns>
        public virtual IEnvelope GetExtents()
        {
            if (this.envelope == null)
            {
                using (var ogrEnvelope = new Envelope())
                {
                    int i = ogrLayer.GetExtent(ogrEnvelope, 1);

                    envelope = GeometryFactory.CreateEnvelope(ogrEnvelope.MinX,
                                                              ogrEnvelope.MaxX,
                                                              ogrEnvelope.MinY,
                                                              ogrEnvelope.MaxY);
                }
            }


            return envelope;
        }
Example #15
0
 //http://www.gisremotesensing.com/2015/09/vector-to-raster-conversion-using-gdal-c.html
 public static void Rasterize(string inputFeature, string outRaster, string fieldName, int cellSize)
 {
     // Define pixel_size and NoData value of new raster  
     int rasterCellSize = cellSize;
     const double noDataValue = -9999;
     string outputRasterFile = outRaster;
     //Register the vector drivers  
     Ogr.RegisterAll();
     //Reading the vector data  
     DataSource dataSource = Ogr.Open(inputFeature, 0);
     var count = dataSource.GetLayerCount();
     Layer layer = dataSource.GetLayerByIndex(0);
     var litems = layer.GetFeatureCount(0);
     var lname= layer.GetName();
     Envelope envelope = new Envelope();
     layer.GetExtent(envelope, 0);
     //Compute the out raster cell resolutions  
     int x_res = Convert.ToInt32((envelope.MaxX - envelope.MinX) / rasterCellSize);
     int y_res = Convert.ToInt32((envelope.MaxY - envelope.MinY) / rasterCellSize);
     Console.WriteLine("Extent: " + envelope.MaxX + " " + envelope.MinX + " " + envelope.MaxY + " " + envelope.MinY);
     Console.WriteLine("X resolution: " + x_res);
     Console.WriteLine("X resolution: " + y_res);
     //Register the raster drivers  
     Gdal.AllRegister();
     //Check if output raster exists & delete (optional)  
     if (File.Exists(outputRasterFile))
     {
         File.Delete(outputRasterFile);
     }
     //Create new tiff   
     OSGeo.GDAL.Driver outputDriver = Gdal.GetDriverByName("GTiff");
     Dataset outputDataset = outputDriver.Create(outputRasterFile, x_res, y_res, 1, DataType.GDT_Float64, null);
     //Extrac srs from input feature   
     string inputShapeSrs;
     SpatialReference spatialRefrence = layer.GetSpatialRef();
     spatialRefrence.ExportToWkt(out inputShapeSrs);
     //Assign input feature srs to outpur raster  
     outputDataset.SetProjection(inputShapeSrs);
     //Geotransform  
     double[] argin = new double[] { envelope.MinX, rasterCellSize, 0, envelope.MaxY, 0, -rasterCellSize };
     outputDataset.SetGeoTransform(argin);
     //Set no data  
     Band band = outputDataset.GetRasterBand(1);
     band.SetNoDataValue(noDataValue);
     //close tiff  
     outputDataset.FlushCache();
     outputDataset.Dispose();
     //Feature to raster rasterize layer options  
     //No of bands (1)  
     int[] bandlist = new int[] { 1 };
     //Values to be burn on raster (10.0)  
     double[] burnValues = new double[] { 10.0 };
     Dataset myDataset = Gdal.Open(outputRasterFile, Access.GA_Update);
     //additional options  
     string[] rasterizeOptions;
     //rasterizeOptions = new string[] { "ALL_TOUCHED=TRUE", "ATTRIBUTE=" + fieldName }; //To set all touched pixels into raster pixel  
     rasterizeOptions = new string[] { "ATTRIBUTE=" + fieldName };
     //Rasterize layer  
     //Gdal.RasterizeLayer(myDataset, 1, bandlist, layer, IntPtr.Zero, IntPtr.Zero, 1, burnValues, null, null, null); // To burn the given burn values instead of feature attributes  
     Gdal.RasterizeLayer(myDataset, 1, bandlist, layer, IntPtr.Zero, IntPtr.Zero, 1, burnValues, rasterizeOptions, new Gdal.GDALProgressFuncDelegate(ProgressFunc), "Raster conversion");
 }
        public static void AnalyzeRoadBoundingBoxes(string pMdbFile, string pLogFile, Action <Object, bool> aLog, int pOnlyApproved = 0)
        {
            var roadSuspects = new List <RoadSuspect>();
            // Setup SQL string to select all or only some streets
            string sql;

            if (pOnlyApproved == 1)
            {
                sql = "SELECT ADRROADID, NAMEENGLISH, NAMEARABIC, NAMEPOPULARENGLISH, NAMEPOPULARARABIC, ROADTYPE, ADRDISTRICTID, APPROVED FROM ADM_ADRROAD WHERE APPROVED = 1 ORDER BY ADRROADID";
            }
            else
            {
                sql = "SELECT ADRROADID, NAMEENGLISH, NAMEARABIC, NAMEPOPULARENGLISH, NAMEPOPULARARABIC, ROADTYPE, ADRDISTRICTID, APPROVED FROM ADM_ADRROAD ORDER BY ADRROADID";
            }

            // Setup fieldAttributes dictionary to hold road names
            var mRoads = new Dictionary <int, DataRow>();

            // Connect to database and load names
            var mOdbcConn    = new OdbcConnection("Driver={Microsoft Access Driver (*.mdb, *.accdb)};Dbq=" + pMdbFile + ";Uid=Admin;Pwd=;");
            var mDataAdapter = new OdbcDataAdapter(sql, mOdbcConn);
            var mDataTable   = new DataTable();

            mDataAdapter.Fill(mDataTable);
            int ctr1   = 0;
            int total1 = mDataTable.Rows.Count;

            foreach (DataRow mRow in mDataTable.Rows)
            {
                int mRoadId;
                if (int.TryParse(mRow["ADRROADID"].ToString(), out mRoadId))
                {
                    mRoads.Add(mRoadId, mRow);
                }
                ctr1++;
                if (ctr1 % 100 == 0)
                {
                    double mFraction1 = (((double)ctr1 / (double)total1) * 100);
                    Application.DoEvents();
                }
            }
            Debug.WriteLine("Done loading road names");
            mOdbcConn.Close();
            mDataAdapter = null;
            mOdbcConn    = null;

            // Connect to database using OGR to load geometries
            var mDriver = Ogr.GetDriverByName("PGeo");

            if (mDriver == null)
            {
                return;
            }

            Debug.WriteLine("Loaded driver");
            var mSource = mDriver.Open(pMdbFile, 0);

            if (mSource == null)
            {
                return;
            }

            Debug.WriteLine("Loaded datasource");
            var mLayer = mSource.GetLayerByName("ADRROADSEGMENT");

            if (mLayer == null)
            {
                return;
            }
            Debug.WriteLine("Loaded layer");

            // Create simplified roads
            var mSimplifiedRoadsFeatureSet = new SimplifiedRoads();

            int mTotal2 = mLayer.GetFeatureCount(0);

            foreach (var mRoadID in mRoads)
            {
                mLayer.SetAttributeFilter("ADRROADID = " + mRoadID.Key);

                OSGeo.OGR.Feature mFeature;
                int           mNumShapes  = 0;
                double        mLength     = 0;
                double        mLeft       = 0;
                double        mBottom     = 0;
                double        mTop        = 0;
                double        mRight      = 0;
                int           mDuplicates = 0;
                List <string> mGeoms      = new List <string>();
                while (null != (mFeature = mLayer.GetNextFeature()))
                {
                    OSGeo.OGR.Geometry mGeom = mFeature.GetGeometryRef();

                    if (mGeom != null)
                    {
                        string wkt;
                        mGeom.ExportToWkt(out wkt);
                        OSGeo.OGR.Envelope mExtent = new OSGeo.OGR.Envelope();
                        mGeom.GetEnvelope(mExtent);
                        if (mTop == 0 || mExtent.MaxY > mTop)
                        {
                            mTop = mExtent.MaxY;
                        }
                        if (mBottom == 0 || mExtent.MinY < mBottom)
                        {
                            mBottom = mExtent.MinY;
                        }
                        if (mLeft == 0 || mExtent.MinX < mLeft)
                        {
                            mLeft = mExtent.MinX;
                        }
                        if (mRight == 0 || mExtent.MaxX > mRight)
                        {
                            mRight = mExtent.MaxX;
                        }

                        if (!mGeoms.Contains(wkt))
                        {
                            mLength = mLength + mGeom.Length();
                            mGeoms.Add(wkt);
                        }
                        else
                        {
                            mDuplicates++;
                        }
                    }

                    mNumShapes++;
                }

                var mBoxWidth    = mRight - mLeft;
                var mBoxHeight   = mTop - mBottom;
                var mBoxDiagonal = Math.Sqrt(mBoxWidth * mBoxWidth + mBoxHeight * mBoxHeight);

                roadSuspects.Add(new RoadSuspect(mRoadID.Key,
                                                 mNumShapes,
                                                 mDuplicates,
                                                 Math.Round(mBoxDiagonal, 1),
                                                 Math.Round(mLength, 1)));


                if (mLength > (2.2 * mBoxDiagonal) || mDuplicates > 0)
                {
                    aLog(String.Format("r: {0}, s: {1}, l: {2}, d: {3}, bb: {4}",
                                       mRoadID.Key,
                                       mNumShapes,
                                       Math.Round(mLength, 1),
                                       mDuplicates,
                                       Math.Round(mBoxDiagonal, 1)),
                         true);
                }
            }

            using (var mCsvWriter = new CsvHelper.CsvWriter(new ExcelSerializer(pLogFile)))
            {
                mCsvWriter.WriteRecords(roadSuspects);
                aLog("Wrote output to " + pLogFile, true);
                aLog("Operation completed...", true);
            }
        }
Example #17
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            ///Gather GHA inputs
            List <Curve> boundary = new List <Curve>();

            DA.GetDataList <Curve>("Boundary", boundary);

            string shpFilePath = string.Empty;

            DA.GetData <string>("Vector Data Location", ref shpFilePath);

            bool cropIt = true;

            DA.GetData <Boolean>("Crop file", ref cropIt);

            string userSRStext = "WGS84";

            DA.GetData <string>(2, ref userSRStext);


            ///GDAL setup
            ///Some preliminary testing has been done to read SHP, GeoJSON, OSM, KML, MVT, GML and GDB
            ///It can be spotty with KML, MVT and GML and doesn't throw informative errors.  Likely has to do with getting a valid CRS and
            ///TODO: resolve errors with reading KML, MVT, GML.

            DataSource   dataSource = CreateDataSource(shpFilePath);
            List <Layer> layerSet   = GetLayers(dataSource);

            ///Declare trees
            GH_Structure <GH_Rectangle> recs = new GH_Structure <GH_Rectangle>();
            GH_Structure <GH_String>    spatialReferences = new GH_Structure <GH_String>();
            GH_Structure <GH_String>    fnames            = new GH_Structure <GH_String>();
            GH_Structure <GH_String>    fset = new GH_Structure <GH_String>();
            GH_Structure <GH_Point>     gset = new GH_Structure <GH_Point>();

            GH_Structure <GH_Point>     gsetUser = new GH_Structure <GH_Point>();
            GH_Structure <GH_Rectangle> recsUser = new GH_Structure <GH_Rectangle>();

            GH_Structure <GH_String>        gtype = new GH_Structure <GH_String>();
            GH_Structure <IGH_GeometricGoo> gGoo  = new GH_Structure <IGH_GeometricGoo>();


            ///Loop through each layer. Layers usually occur in Geodatabase GDB format. SHP usually has only one layer.
            for (int iLayer = 0; iLayer < dataSource.GetLayerCount(); iLayer++)
            {
                OSGeo.OGR.Layer layer = dataSource.GetLayerByIndex(iLayer);

                if (layer == null)
                {
                    Console.WriteLine($"Couldn't fetch advertised layer {iLayer}");
                    System.Environment.Exit(-1);
                }

                long count        = layer.GetFeatureCount(1);
                int  featureCount = System.Convert.ToInt32(count);



                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, $"Layer #{iLayer} {layer.GetName()} has {featureCount} features");

                ///Get the spatial reference of the input vector file and set to WGS84 if not known
                ///
                OSGeo.OSR.SpatialReference sourceSRS = new SpatialReference(Osr.SRS_WKT_WGS84);
                string spatialReference = GetSpatialReference(layer, iLayer, dataSource, sourceSRS);
                spatialReferences.Append(new GH_String(spatialReference), new GH_Path(iLayer));


                ///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);

                ///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);

                ///Get OGR envelope of the data in the layer in the sourceSRS
                OSGeo.OGR.Envelope ext = new OSGeo.OGR.Envelope();
                layer.GetExtent(ext, 1);

                OSGeo.OGR.Geometry extMinSourceOgr = new OSGeo.OGR.Geometry(wkbGeometryType.wkbPoint);
                extMinSourceOgr.AddPoint(ext.MinX, ext.MinY, 0.0);
                extMinSourceOgr.AssignSpatialReference(sourceSRS);

                OSGeo.OGR.Geometry extMaxSourceOgr = new OSGeo.OGR.Geometry(wkbGeometryType.wkbPoint);
                extMaxSourceOgr.AddPoint(ext.MaxX, ext.MaxY, 0.0);
                extMaxSourceOgr.AssignSpatialReference(sourceSRS);

                ///Get extents in Rhino SRS
                Point3d extPTmin = Heron.Convert.OgrPointToPoint3d(extMinSourceOgr, sourceToModelSRSTransform);
                Point3d extPTmax = Heron.Convert.OgrPointToPoint3d(extMaxSourceOgr, sourceToModelSRSTransform);

                Rectangle3d rec = new Rectangle3d(Plane.WorldXY, extPTmin, extPTmax);
                recs.Append(new GH_Rectangle(rec), new GH_Path(iLayer));

                ///Get extents in userSRS
                ///Can give odd results if crosses 180 longitude
                extMinSourceOgr.TransformTo(userSRS);
                extMaxSourceOgr.TransformTo(userSRS);

                Point3d extPTminUser = Heron.Convert.OgrPointToPoint3d(extMinSourceOgr, userSRSToModelTransform);
                Point3d extPTmaxUser = Heron.Convert.OgrPointToPoint3d(extMaxSourceOgr, userSRSToModelTransform);

                Rectangle3d recUser = new Rectangle3d(Plane.WorldXY, extPTminUser, extPTmaxUser);
                recsUser.Append(new GH_Rectangle(recUser), new GH_Path(iLayer));


                if (boundary.Count == 0 && cropIt == true)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Define a boundary or set cropIt to False");
                }

                else if (boundary.Count == 0 && cropIt == false)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Clipping boundary has not been defined. File extents will be used instead");
                    boundary.Add(rec.ToNurbsCurve());
                }



                ///Loop through input boundaries
                for (int i = 0; i < boundary.Count; i++)
                {
                    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(i, iLayer));
                    }

                    ///Check if boundary is contained in extent
                    if (!rec.IsValid || ((rec.Height == 0) && (rec.Width == 0)))
                    {
                        ///Get field data if even if no geometry is present in the layer
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "One or more vector datasource bounds are not valid.");
                        OSGeo.OGR.Feature feat;
                        int m = 0;

                        while ((feat = layer.GetNextFeature()) != null)
                        {
                            ///Loop through field values
                            for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                            {
                                OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, iLayer, m));
                                fdef.Dispose();
                            }
                            m++;
                            feat.Dispose();
                        }
                    }

                    else if (boundary[i] == null)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Clipping boundary " + i + " not set.");
                    }

                    else if (!boundary[i].IsValid)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Clipping boundary " + i + "  is not valid.");
                    }

                    else if (rec.IsValid && Curve.PlanarClosedCurveRelationship(rec.ToNurbsCurve(), boundary[i], Plane.WorldXY, Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance) == RegionContainment.Disjoint)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "One or more clipping boundaries may be outside the bounds of the vector datasource.");
                    }

                    else
                    {
                        ///Create bounding box for clipping geometry
                        Point3d min = boundary[i].GetBoundingBox(true).Min;
                        Point3d max = boundary[i].GetBoundingBox(true).Max;
                        min.Transform(modelToSourceSRSTransform);
                        max.Transform(modelToSourceSRSTransform);
                        double[] minpT = new double[3];
                        double[] maxpT = new double[3];

                        minpT[0] = min.X;
                        minpT[1] = min.Y;
                        minpT[2] = min.Z;
                        maxpT[0] = max.X;
                        maxpT[1] = max.Y;
                        maxpT[2] = max.Z;


                        OSGeo.OGR.Geometry ebbox = OSGeo.OGR.Geometry.CreateFromWkt("POLYGON((" + minpT[0] + " " + minpT[1] + ", " + minpT[0] + " " + maxpT[1] + ", " + maxpT[0] + " " + maxpT[1] + ", " + maxpT[0] + " " + minpT[1] + ", " + minpT[0] + " " + minpT[1] + "))");

                        ///Create bounding box for clipping geometry
                        ///Not working on MVT type files
                        //boundary[i].Transform(modelToSourceSRSTransform);
                        //OSGeo.OGR.Geometry ebbox = Heron.Convert.CurveToOgrPolygon(boundary[i]);


                        ///Clip Shapefile
                        ///http://pcjericks.github.io/py-gdalogr-cookbook/vector_layers.html
                        OSGeo.OGR.Layer clipped_layer = layer;

                        if (cropIt)
                        {
                            clipped_layer.SetSpatialFilter(ebbox);
                        }

                        ///Loop through geometry
                        OSGeo.OGR.Feature feat;
                        def = clipped_layer.GetLayerDefn();

                        int m = 0;
                        while ((feat = clipped_layer.GetNextFeature()) != null)
                        {
                            OSGeo.OGR.Geometry geom = feat.GetGeometryRef();
                            OSGeo.OGR.Geometry sub_geom;

                            OSGeo.OGR.Geometry geomUser = feat.GetGeometryRef().Clone();
                            OSGeo.OGR.Geometry sub_geomUser;

                            ///reproject geometry to WGS84 and userSRS
                            ///TODO: look into using the SetCRS global variable here
                            if (geom.GetSpatialReference() == null)
                            {
                                geom.AssignSpatialReference(sourceSRS);
                            }
                            if (geomUser.GetSpatialReference() == null)
                            {
                                geomUser.AssignSpatialReference(sourceSRS);
                            }

                            geom.TransformTo(rhinoSRS);
                            geomUser.TransformTo(userSRS);
                            gtype.Append(new GH_String(geom.GetGeometryName()), new GH_Path(i, iLayer, m));

                            if (feat.GetGeometryRef() != null)
                            {
                                ///Convert GDAL geometries to IGH_GeometricGoo
                                gGoo.AppendRange(Heron.Convert.OgrGeomToGHGoo(geomUser, userSRSToModelTransform), new GH_Path(i, iLayer, m));

                                /// Get Feature Values
                                if (fset.PathExists(new GH_Path(i, iLayer, m)))
                                {
                                    fset.get_Branch(new GH_Path(i, iLayer, m)).Clear();
                                }
                                for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                                {
                                    OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                    if (feat.IsFieldSet(iField))
                                    {
                                        fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, iLayer, m));
                                    }
                                    else
                                    {
                                        fset.Append(new GH_String("null"), new GH_Path(i, iLayer, m));
                                    }
                                }
                                ///End get Feature Values


                                ///Start get points if open polylines and points
                                for (int gpc = 0; gpc < geom.GetPointCount(); gpc++)
                                {
                                    ///Loop through geometry points for Rhino SRS
                                    double[] ogrPt = new double[3];
                                    geom.GetPoint(gpc, ogrPt);
                                    Point3d pt3D = new Point3d(ogrPt[0], ogrPt[1], ogrPt[2]);
                                    pt3D.Transform(Heron.Convert.WGSToXYZTransform());

                                    gset.Append(new GH_Point(pt3D), new GH_Path(i, iLayer, m));

                                    ///Loop through geometry points for User SRS
                                    double[] ogrPtUser = new double[3];
                                    geomUser.GetPoint(gpc, ogrPtUser);
                                    Point3d pt3DUser = new Point3d(ogrPtUser[0], ogrPtUser[1], ogrPtUser[2]);
                                    pt3DUser.Transform(userSRSToModelTransform);

                                    gsetUser.Append(new GH_Point(pt3DUser), new GH_Path(i, iLayer, m));

                                    ///End loop through geometry points


                                    /// Get Feature Values
                                    if (fset.PathExists(new GH_Path(i, iLayer, m)))
                                    {
                                        fset.get_Branch(new GH_Path(i, iLayer, m)).Clear();
                                    }
                                    for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                                    {
                                        OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                        if (feat.IsFieldSet(iField))
                                        {
                                            fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, iLayer, m));
                                        }
                                        else
                                        {
                                            fset.Append(new GH_String("null"), new GH_Path(i, iLayer, m));
                                        }
                                    }
                                    ///End Get Feature Values
                                }
                                ///End getting points if open polylines or points


                                ///Start getting points if closed polylines and multipolygons
                                for (int gi = 0; gi < geom.GetGeometryCount(); gi++)
                                {
                                    sub_geom = geom.GetGeometryRef(gi);
                                    OSGeo.OGR.Geometry subsub_geom;

                                    sub_geomUser = geomUser.GetGeometryRef(gi);
                                    OSGeo.OGR.Geometry subsub_geomUser;

                                    if (sub_geom.GetGeometryCount() > 0)
                                    {
                                        for (int n = 0; n < sub_geom.GetGeometryCount(); n++)
                                        {
                                            subsub_geom     = sub_geom.GetGeometryRef(n);
                                            subsub_geomUser = sub_geomUser.GetGeometryRef(n);

                                            for (int ptnum = 0; ptnum < subsub_geom.GetPointCount(); ptnum++)
                                            {
                                                ///Loop through geometry points
                                                double[] ogrPt = new double[3];
                                                subsub_geom.GetPoint(ptnum, ogrPt);
                                                Point3d pt3D = new Point3d(ogrPt[0], ogrPt[1], ogrPt[2]);
                                                pt3D.Transform(Heron.Convert.WGSToXYZTransform());

                                                gset.Append(new GH_Point(pt3D), new GH_Path(i, iLayer, m, gi, n));

                                                ///Loop through geometry points for User SRS
                                                double[] ogrPtUser = new double[3];
                                                subsub_geomUser.GetPoint(ptnum, ogrPtUser);
                                                Point3d pt3DUser = new Point3d(ogrPtUser[0], ogrPtUser[1], ogrPtUser[2]);
                                                pt3DUser.Transform(userSRSToModelTransform);

                                                gsetUser.Append(new GH_Point(pt3DUser), new GH_Path(i, iLayer, m, gi, n));

                                                ///End loop through geometry points
                                            }
                                            subsub_geom.Dispose();
                                            subsub_geomUser.Dispose();
                                        }
                                    }

                                    else
                                    {
                                        for (int ptnum = 0; ptnum < sub_geom.GetPointCount(); ptnum++)
                                        {
                                            ///Loop through geometry points
                                            double[] ogrPt = new double[3];
                                            sub_geom.GetPoint(ptnum, ogrPt);
                                            Point3d pt3D = new Point3d(ogrPt[0], ogrPt[1], ogrPt[2]);
                                            pt3D.Transform(Heron.Convert.WGSToXYZTransform());

                                            gset.Append(new GH_Point(pt3D), new GH_Path(i, iLayer, m, gi));

                                            ///Loop through geometry points for User SRS
                                            double[] ogrPtUser = new double[3];
                                            sub_geomUser.GetPoint(ptnum, ogrPtUser);
                                            Point3d pt3DUser = new Point3d(ogrPtUser[0], ogrPtUser[1], ogrPtUser[2]);
                                            pt3DUser.Transform(userSRSToModelTransform);

                                            gsetUser.Append(new GH_Point(pt3DUser), new GH_Path(i, iLayer, m, gi));

                                            ///End loop through geometry points
                                        }
                                    }

                                    sub_geom.Dispose();
                                    sub_geomUser.Dispose();


                                    /// Get Feature Values
                                    if (fset.PathExists(new GH_Path(i, iLayer, m)))
                                    {
                                        fset.get_Branch(new GH_Path(i, iLayer, m)).Clear();
                                    }
                                    for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                                    {
                                        OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                        if (feat.IsFieldSet(iField))
                                        {
                                            fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, iLayer, m));
                                        }
                                        else
                                        {
                                            fset.Append(new GH_String("null"), new GH_Path(i, iLayer, m));
                                        }
                                    }
                                    ///End Get Feature Values
                                }


                                //m++;
                            }
                            m++;
                            geom.Dispose();
                            geomUser.Dispose();
                            feat.Dispose();
                        } ///end while loop through features
                    }     ///end clipped layer else statement
                }         ///end loop through boundaries

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

            dataSource.Dispose();

            DA.SetDataTree(0, recs);
            DA.SetDataTree(1, spatialReferences);
            DA.SetDataTree(2, fnames);
            DA.SetDataTree(3, fset);
            DA.SetDataTree(4, gset);

            DA.SetDataTree(5, gsetUser);
            DA.SetDataTree(6, recsUser);

            DA.SetDataTree(7, gGoo);
            DA.SetDataTree(8, gtype);
        }
Example #18
0
 public void GetEnvelope(Envelope env)
 {
     OgrPINVOKE.Geometry_GetEnvelope(swigCPtr, Envelope.getCPtr(env));
     if (OgrPINVOKE.SWIGPendingException.Pending) throw OgrPINVOKE.SWIGPendingException.Retrieve();
 }
Example #19
0
        private List <Geometry> getWidth(Layer buildingLayer, Geometry sourcePoint, Geometry receivePoint, Geometry line)
        {
            topBuilding st = new topBuilding();

            st.width    = 0;
            st.high     = 0;
            st.tophigh  = null;
            st.topwidth = null;
            // buildingLayer.ResetReading();
            Feature bFeature = null;

            OSGeo.OGR.Envelope env = new OSGeo.OGR.Envelope();
            while ((bFeature = buildingLayer.GetNextFeature()) != null)
            {
                bFeature.GetGeometryRef().GetEnvelope(env);

                double width = Math.Sqrt((env.MaxX - env.MinX) * (env.MaxX - env.MinX) + (env.MaxY - env.MinY) * (env.MaxY - env.MinY));


                if (st.width < width)
                {
                    st.width    = width;
                    st.topwidth = bFeature.GetGeometryRef();
                }


                if (st.high < bFeature.GetFieldAsDouble("HEIGHT_G"))
                {
                    st.high    = bFeature.GetFieldAsDouble("HEIGHT_G");
                    st.tophigh = bFeature.GetGeometryRef();
                }
            }


            List <Geometry> list = null;

            //list.Add(line);



            if (st.topwidth != null)
            {
                list = new List <Geometry>();
                SortedDictionary <double, Geometry> upLinePoint    = new SortedDictionary <double, Geometry>();
                SortedDictionary <double, Geometry> belowLinePoint = new SortedDictionary <double, Geometry>();
                double k = (sourcePoint.GetY(0) - receivePoint.GetY(0)) / (sourcePoint.GetX(0) - receivePoint.GetX(0));
                double b = sourcePoint.GetY(0) - k * sourcePoint.GetX(0);

                Geometry buildingring = new Geometry(wkbGeometryType.wkbLinearRing);
                st.topwidth.GetEnvelope(env);
                buildingring.AddPoint(env.MinX, env.MinY, 0);
                buildingring.AddPoint(env.MaxX, env.MinY, 0);

                buildingring.AddPoint(env.MaxX, env.MaxY, 0);
                buildingring.AddPoint(env.MinX, env.MaxY, 0);


                for (int i = 0; i < buildingring.GetPointCount(); i++)
                {
                    Geometry point = GeometryCreate.createPoint3D(buildingring.GetX(i), buildingring.GetY(i), buildingring.GetZ(i));
                    if (point.GetY(0) < k * point.GetX(0) + b)
                    {
                        belowLinePoint.Add(sourcePoint.Distance(point), point);
                    }
                    else if (buildingring.GetY(i) > k * buildingring.GetX(i) + b)
                    {
                        upLinePoint.Add(sourcePoint.Distance(point), point);
                    }
                }

                Geometry uoLine    = new Geometry(wkbGeometryType.wkbLineString);
                Geometry belowLine = new Geometry(wkbGeometryType.wkbLineString);

                if (upLinePoint.Count > 0)
                {
                    uoLine.AddPoint(sourcePoint.GetX(0), sourcePoint.GetY(0), sourcePoint.GetZ(0));
                    foreach (KeyValuePair <double, Geometry> item in upLinePoint)
                    {
                        uoLine.AddPoint(item.Value.GetX(0), item.Value.GetY(0), item.Value.GetZ(0));
                    }
                    uoLine.AddPoint(receivePoint.GetX(0), receivePoint.GetY(0), receivePoint.GetZ(0));
                }

                if (belowLinePoint.Count > 0)
                {
                    belowLine.AddPoint(sourcePoint.GetX(0), sourcePoint.GetY(0), sourcePoint.GetZ(0));
                    foreach (KeyValuePair <double, Geometry> item in belowLinePoint)
                    {
                        belowLine.AddPoint(item.Value.GetX(0), item.Value.GetY(0), item.Value.GetZ(0));
                    }
                    belowLine.AddPoint(receivePoint.GetX(0), receivePoint.GetY(0), receivePoint.GetZ(0));
                }

                list.Add(uoLine);
                list.Add(belowLine);
            }



            return(list);
        }
Example #20
0
        /// <summary>
        /// Boundingbox of the dataset
        /// </summary>
        /// <returns>boundingbox</returns>
        public SharpMap.Geometries.BoundingBox GetExtents()
        {
            if (this._bbox == null)
            {
                OSGeo.OGR.Envelope _OgrEnvelope = new Envelope();
                int i = _OgrLayer.GetExtent(_OgrEnvelope, 1);

                this._bbox = new SharpMap.Geometries.BoundingBox(_OgrEnvelope.MinX,
                                                                 _OgrEnvelope.MinY,
                                                                 _OgrEnvelope.MaxX,
                                                                 _OgrEnvelope.MaxY);

            }

            return _bbox;
        }
Example #21
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Curve> boundary = new List <Curve>();

            DA.GetDataList <Curve>(0, boundary);

            string shpFileLoc = "";

            DA.GetData <string>("Vector Data Location", ref shpFileLoc);

            ///GDAL setup
            ///Some preliminary testing has been done to read SHP, GeoJSON, OSM, KML, MVT, GML and GDB
            ///It can be spotty with KML, MVT and GML and doesn't throw informative errors.  Likely has to do with getting a valid CRS and
            ///TODO: resolve errors with reading KML, MVT, GML.

            RESTful.GdalConfiguration.ConfigureOgr();
            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.OGR.Driver     drv = OSGeo.OGR.Ogr.GetDriverByName("ESRI Shapefile");
            OSGeo.OGR.DataSource ds  = OSGeo.OGR.Ogr.Open(shpFileLoc, 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;
            }

            List <OSGeo.OGR.Layer> layerset = new List <OSGeo.OGR.Layer>();
            List <int>             fc       = new List <int>();

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

                if (layer == null)
                {
                    Console.WriteLine("Couldn't fetch advertised layer " + iLayer);
                    System.Environment.Exit(-1);
                }
                else
                {
                    layerset.Add(layer);
                }
            }

            ///Declare trees
            GH_Structure <GH_String>    layname = new GH_Structure <GH_String>();
            GH_Structure <GH_Integer>   fcs     = new GH_Structure <GH_Integer>();
            GH_Structure <GH_Rectangle> recs    = new GH_Structure <GH_Rectangle>();
            GH_Structure <GH_String>    sRefs   = new GH_Structure <GH_String>();
            GH_Structure <GH_String>    fnames  = new GH_Structure <GH_String>();
            GH_Structure <GH_String>    fset    = new GH_Structure <GH_String>();
            GH_Structure <GH_Point>     gset    = new GH_Structure <GH_Point>();


            ///Loop through each layer. Layers usually occur in Geodatabase GDB format. SHP usually has only one layer.
            for (int iLayer = 0; iLayer < ds.GetLayerCount(); iLayer++)
            {
                OSGeo.OGR.Layer layer = ds.GetLayerByIndex(iLayer);

                if (layer == null)
                {
                    Console.WriteLine("Couldn't fetch advertised layer " + iLayer);
                    System.Environment.Exit(-1);
                }

                long count        = layer.GetFeatureCount(1);
                int  featureCount = System.Convert.ToInt32(count);
                fcs.Append(new GH_Integer(featureCount), new GH_Path(iLayer));

                layname.Append(new GH_String(layer.GetName()), new GH_Path(iLayer));


                ///Get OGR envelope of the data in the layer
                OSGeo.OGR.Envelope ext = new OSGeo.OGR.Envelope();
                layer.GetExtent(ext, 1);
                Point3d extMin = new Point3d();
                Point3d extMax = new Point3d();
                extMin.X = ext.MinX;
                extMin.Y = ext.MinY;
                extMax.X = ext.MaxX;
                extMax.Y = ext.MaxY;


                ///Get the spatial reference of the input vector file and set to WGS84 if not known
                OSGeo.OSR.SpatialReference sr = new SpatialReference(Osr.SRS_WKT_WGS84);
                string sRef = "";

                if (layer.GetSpatialRef() == null)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Coordinate Reference System (CRS) is missing.  CRS set automatically set to WGS84.");
                    sr.ImportFromXML(shpFileLoc);
                    string pretty = "";
                    sr.ExportToPrettyWkt(out pretty, 0);
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, pretty);
                    sr.SetWellKnownGeogCS("WGS84");
                    sRef = "Coordinate Reference System (CRS) is missing.  CRS set automatically set to WGS84.";
                    //sr.ImportFromEPSG(2263);
                }
                else
                {
                    if (layer.GetSpatialRef().Validate() != 0)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Coordinate Reference System (CRS) is unknown or unsupported.  CRS set automatically set to WGS84.");
                        sr.SetWellKnownGeogCS("WGS84");
                        sRef = "Coordinate Reference System (CRS) is unknown or unsupported.  SRS set automatically set to WGS84.";
                    }
                    else
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Coordinate Reference System (CRS) set from layer" + iLayer + ".");
                        sr = layer.GetSpatialRef();
                        sr.ExportToWkt(out sRef);
                    }
                }

                sRefs.Append(new GH_String(sRef), new GH_Path(iLayer));


                ///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 dst = new OSGeo.OSR.SpatialReference("");
                dst.SetWellKnownGeogCS("WGS84");
                OSGeo.OSR.CoordinateTransformation coordTransform = new OSGeo.OSR.CoordinateTransformation(sr, dst);
                OSGeo.OSR.CoordinateTransformation revTransform   = new OSGeo.OSR.CoordinateTransformation(dst, sr);


                ///Get bounding box of data in layer
                double[] extMinPT = new double[3] {
                    extMin.X, extMin.Y, extMin.Z
                };
                double[] extMaxPT = new double[3] {
                    extMax.X, extMax.Y, extMax.Z
                };
                coordTransform.TransformPoint(extMinPT);
                coordTransform.TransformPoint(extMaxPT);
                Point3d     extPTmin = new Point3d(extMinPT[0], extMinPT[1], extMinPT[2]);
                Point3d     extPTmax = new Point3d(extMaxPT[0], extMaxPT[1], extMaxPT[2]);
                Rectangle3d rec      = new Rectangle3d(Plane.WorldXY, Heron.Convert.ToXYZ(extPTmin), Heron.Convert.ToXYZ(extPTmax));
                recs.Append(new GH_Rectangle(rec), new GH_Path(iLayer));


                ///Loop through input boundaries
                for (int i = 0; i < boundary.Count; i++)
                {
                    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(i, iLayer));
                    }

                    ///Check if boundary is contained in extent
                    if (!rec.IsValid || ((rec.Height == 0) && (rec.Width == 0)))
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "One or more vector datasource bounds are not valid.");
                        OSGeo.OGR.Feature feat;
                        int m = 0;

                        while ((feat = layer.GetNextFeature()) != null)
                        {
                            ///Loop through field values
                            for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                            {
                                OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, iLayer, m));
                                fdef.Dispose();
                            }
                            m++;
                            feat.Dispose();
                        }
                    }

                    else if (boundary[i] == null)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Clipping boundary " + i + " not set.");
                    }

                    else if (!boundary[i].IsValid)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "Clipping boundary " + i + "  is not valid.");
                    }

                    else if (rec.IsValid && Curve.PlanarClosedCurveRelationship(rec.ToNurbsCurve(), boundary[i], Plane.WorldXY, Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance) == RegionContainment.Disjoint)
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "One or more boundaries may be outside the bounds of the vector datasource.");
                    }

                    else
                    {
                        ///Create bounding box for clipping geometry
                        Point3d  min   = Heron.Convert.ToWGS(boundary[i].GetBoundingBox(true).Min);
                        Point3d  max   = Heron.Convert.ToWGS(boundary[i].GetBoundingBox(true).Max);
                        double[] minpT = new double[3];
                        double[] maxpT = new double[3];

                        minpT[0] = min.X;
                        minpT[1] = min.Y;
                        minpT[2] = min.Z;
                        maxpT[0] = max.X;
                        maxpT[1] = max.Y;
                        maxpT[2] = max.Z;
                        revTransform.TransformPoint(minpT);
                        revTransform.TransformPoint(maxpT);

                        ///Convert to OGR geometry
                        ///TODO: add conversion from GH geometry to OGR to Convert class
                        OSGeo.OGR.Geometry ebbox = OSGeo.OGR.Geometry.CreateFromWkt("POLYGON((" + minpT[0] + " " + minpT[1] + ", " + minpT[0] + " " + maxpT[1] + ", " + maxpT[0] + " " + maxpT[1] + ", " + maxpT[0] + " " + minpT[1] + ", " + minpT[0] + " " + minpT[1] + "))");

                        ///Clip Shapefile
                        ///http://pcjericks.github.io/py-gdalogr-cookbook/vector_layers.html
                        ///TODO: allow for polyline/curve as clipper, not just bounding box
                        OSGeo.OGR.Layer clipped_layer = layer;
                        clipped_layer.SetSpatialFilter(ebbox);

                        ///Loop through geometry
                        OSGeo.OGR.Feature feat;
                        def = clipped_layer.GetLayerDefn();

                        int m = 0;
                        while ((feat = clipped_layer.GetNextFeature()) != null)
                        {
                            OSGeo.OGR.Geometry geom = feat.GetGeometryRef();
                            OSGeo.OGR.Geometry sub_geom;

                            ///reproject geometry to WGS84
                            ///TODO: look into using the SetCRS global variable here
                            geom.Transform(coordTransform);

                            if (feat.GetGeometryRef() != null)
                            {
                                ///Start get points if open polylines and points
                                for (int gpc = 0; gpc < geom.GetPointCount(); gpc++)
                                {
                                    ///Loop through geometry points
                                    double[] pT = new double[3];
                                    pT[0] = geom.GetX(gpc);
                                    pT[1] = geom.GetY(gpc);
                                    pT[2] = geom.GetZ(gpc);
                                    if (Double.IsNaN(geom.GetZ(gpc)))
                                    {
                                        pT[2] = 0;
                                    }
                                    //coordTransform.TransformPoint(pT);

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

                                    gset.Append(new GH_Point(Heron.Convert.ToXYZ(pt3D)), new GH_Path(i, iLayer, m));
                                    ///End loop through geometry points

                                    /// Get Feature Values
                                    if (fset.PathExists(new GH_Path(i, iLayer, m)))
                                    {
                                        fset.get_Branch(new GH_Path(i, iLayer, m)).Clear();
                                    }
                                    for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                                    {
                                        OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                        if (feat.IsFieldSet(iField))
                                        {
                                            fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, iLayer, m));
                                        }
                                        else
                                        {
                                            fset.Append(new GH_String("null"), new GH_Path(i, iLayer, m));
                                        }
                                    }
                                    ///End Get Feature Values
                                }
                                ///End getting points if open polylines or points



                                ///Start getting points if closed polylines and multipolygons
                                for (int gi = 0; gi < geom.GetGeometryCount(); gi++)
                                {
                                    sub_geom = geom.GetGeometryRef(gi);
                                    OSGeo.OGR.Geometry subsub_geom;
                                    List <Point3d>     geom_list = new List <Point3d>();

                                    ///trouble getting all points.  this is a troubleshoot
                                    ///gset.Append(new GH_Point(new Point3d(0, 0, sub_geom.GetGeometryCount())), new GH_Path(i, iLayer, m, gi));

                                    if (sub_geom.GetGeometryCount() > 0)
                                    {
                                        for (int n = 0; n < sub_geom.GetGeometryCount(); n++)
                                        {
                                            subsub_geom = sub_geom.GetGeometryRef(n);
                                            for (int ptnum = 0; ptnum < subsub_geom.GetPointCount(); ptnum++)
                                            {
                                                ///Loop through geometry points
                                                double[] pT = new double[3];
                                                pT[0] = subsub_geom.GetX(ptnum);
                                                pT[1] = subsub_geom.GetY(ptnum);
                                                pT[2] = subsub_geom.GetZ(ptnum);

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

                                                gset.Append(new GH_Point(Heron.Convert.ToXYZ(pt3D)), new GH_Path(i, iLayer, m, gi, n));
                                                ///End loop through geometry points
                                            }
                                            subsub_geom.Dispose();
                                        }
                                    }

                                    else
                                    {
                                        for (int ptnum = 0; ptnum < sub_geom.GetPointCount(); ptnum++)
                                        {
                                            ///Loop through geometry points
                                            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];

                                            gset.Append(new GH_Point(Heron.Convert.ToXYZ(pt3D)), new GH_Path(i, iLayer, m, gi));
                                            ///End loop through geometry points
                                        }
                                    }

                                    sub_geom.Dispose();

                                    /// Get Feature Values
                                    if (fset.PathExists(new GH_Path(i, iLayer, m)))
                                    {
                                        fset.get_Branch(new GH_Path(i, iLayer, m)).Clear();
                                    }
                                    for (int iField = 0; iField < feat.GetFieldCount(); iField++)
                                    {
                                        OSGeo.OGR.FieldDefn fdef = def.GetFieldDefn(iField);
                                        if (feat.IsFieldSet(iField))
                                        {
                                            fset.Append(new GH_String(feat.GetFieldAsString(iField)), new GH_Path(i, iLayer, m));
                                        }
                                        else
                                        {
                                            fset.Append(new GH_String("null"), new GH_Path(i, iLayer, m));
                                        }
                                    }
                                    ///End Get Feature Values
                                }
                                //m++;
                            }
                            m++;
                            feat.Dispose();
                        } ///end while loop through features
                    }
                }         //end loop through boundaries

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

            ds.Dispose();

            DA.SetDataTree(0, layname);
            DA.SetDataTree(1, fcs);
            DA.SetDataTree(2, recs);
            DA.SetDataTree(3, sRefs);
            DA.SetDataTree(4, fnames);
            DA.SetDataTree(5, fset);
            DA.SetDataTree(6, gset);
        }