public static void Main(string[] args)
 {
     try
     {
         /* -------------------------------------------------------------------- */
         /*      Initialize srs                                                  */
         /* -------------------------------------------------------------------- */
         SpatialReference src = new SpatialReference("");
         src.ImportFromProj4("+proj=latlong +datum=WGS84 +no_defs");
         Console.WriteLine( "SOURCE IsGeographic:" + src.IsGeographic() + " IsProjected:" + src.IsProjected() );
         SpatialReference dst = new SpatialReference("");
         dst.ImportFromProj4("+proj=somerc +lat_0=47.14439372222222 +lon_0=19.04857177777778 +x_0=650000 +y_0=200000 +ellps=GRS67 +units=m +no_defs");
         Console.WriteLine( "DEST IsGeographic:" + dst.IsGeographic() + " IsProjected:" + dst.IsProjected() );
         /* -------------------------------------------------------------------- */
         /*      making the transform                                            */
         /* -------------------------------------------------------------------- */
         CoordinateTransformation ct = new CoordinateTransformation(src, dst);
         double[] p = new double[3];
         p[0] = 19; p[1] = 47; p[2] = 0;
         ct.TransformPoint(p);
         Console.WriteLine("x:" + p[0] + " y:" + p[1] + " z:" + p[2]);
         ct.TransformPoint(p, 19.2, 47.5, 0);
         Console.WriteLine("x:" + p[0] + " y:" + p[1] + " z:" + p[2]);
     }
     catch (Exception e)
     {
         Console.WriteLine("Error occurred: " + e.Message);
         System.Environment.Exit(-1);
     }
 }
 public int SetCompoundCS(string name, SpatialReference horizcs, SpatialReference vertcs)
 {
     int ret = OsrPINVOKE.SpatialReference_SetCompoundCS(swigCPtr, name, SpatialReference.getCPtr(horizcs), SpatialReference.getCPtr(vertcs));
     if (OsrPINVOKE.SWIGPendingException.Pending) throw OsrPINVOKE.SWIGPendingException.Retrieve();
     return ret;
 }
        // private readonly TransformMethod _transform;

        /*!
         * 功能
         * 参数
         * 返回值
         * 版本号 1.0
         * 作者 樊晓剑
         * 创建时间  2016年4月21日
         * 修改时间
         */
        public Geometry projectionConvert(Geometry toConvert, OSGeo.OSR.SpatialReference projection)
        {
            double[] point   = new double[3];
            double[] topoint = new double[3];
            //获取投影,判断投影类型,如果符合要求则返回
            if (toConvert.GetSpatialReference().AutoIdentifyEPSG() != EPSG_ID)
            {
                OSGeo.OSR.CoordinateTransformation transformation = new OSGeo.OSR.CoordinateTransformation(toConvert.GetSpatialReference(), projection);


                for (int i = 0; i < toConvert.GetPointCount(); i++)
                {
                    toConvert.GetPoint(i, point);

                    transformation.TransformPoint(topoint, point[0], point[1], point[2]);

                    Geometry geometry = new Geometry(wkbGeometryType.wkbPolygon);
                    geometry.AddPoint(topoint[0], topoint[1], topoint[2]);
                    return(geometry);
                }


                //若不符合要求则进行转换


                //返回转换结果输出路径
            }

            return(toConvert);
        }
        /// <summary>
        /// Creates a points shapefile
        /// </summary>
        /// <param name="FileName"></param>
        private static void TestCreatePointsShapeFile(string FileName)
        {
            var points = new List <string>()
            {
                "P1", "P2", "P3", "P4"
            };

            OSGeo.OGR.Driver drv = Ogr.GetDriverByName("ESRI Shapefile");
            using (var ds = drv.CreateDataSource(FileName, new string[] {})) {
                var src = new OSGeo.OSR.SpatialReference("");
                src.ImportFromEPSG(23030);
                using (var layer = ds.CreateLayer("SENSORS", src, wkbGeometryType.wkbPoint, new string[] {})) {
                    FieldDefn fdefn = new FieldDefn("ID", FieldType.OFTString);
                    fdefn.SetWidth(32);
                    layer.CreateField(fdefn, 1);
                    fdefn = new FieldDefn("FIELD_2", FieldType.OFTReal);
                    layer.CreateField(fdefn, 1);

                    foreach (var s in points)
                    {
                        Feature feature = new Feature(layer.GetLayerDefn());
                        feature.SetField("ID", s);
                        feature.SetField("FIELD_2", 123.4d);
                        var    geom = new Geometry(wkbGeometryType.wkbPoint);
                        double X    = 123.4;
                        double Y    = 123.4;
                        geom.AddPointZM(X, Y, 123.4d, 0d);
                        feature.SetGeometry(geom);
                        layer.CreateFeature(feature);
                    }
                }
                ds.FlushCache();
            }
        }
Exemple #5
0
    public static string ReportLayer(Layer layer)
    {
        string      strInfomation = "";
        FeatureDefn def           = layer.GetLayerDefn();

        strInfomation += ("Layer name: " + def.GetName());
        strInfomation += ("Feature Count: " + layer.GetFeatureCount(1).ToString());
        Envelope ext = new Envelope();

        layer.GetExtent(ext, 1);
        strInfomation += ("Extent: " + ext.MinX.ToString() + "," + ext.MaxX.ToString() + "," +
                          ext.MinY.ToString() + "," + ext.MaxY.ToString());

        /* -------------------------------------------------------------------- */
        /*      Reading the spatial reference                                   */
        /* -------------------------------------------------------------------- */
        OSGeo.OSR.SpatialReference sr = layer.GetSpatialRef();
        string srs_wkt;

        if (sr != null)
        {
            sr.ExportToPrettyWkt(out srs_wkt, 1);
        }
        else
        {
            srs_wkt = "(unknown)";
        }


        strInfomation += ("Layer SRS WKT: " + srs_wkt);

        /* -------------------------------------------------------------------- */
        /*      Reading the fields                                              */
        /* -------------------------------------------------------------------- */
        strInfomation += ("Field definition:");
        for (int iAttr = 0; iAttr < def.GetFieldCount(); iAttr++)
        {
            FieldDefn fdef = def.GetFieldDefn(iAttr);

            strInfomation += (fdef.GetNameRef() + ": " +
                              fdef.GetFieldTypeName(fdef.GetFieldType()) + " (" +
                              fdef.GetWidth().ToString() + "." +
                              fdef.GetPrecision().ToString() + ")");
        }

        /* -------------------------------------------------------------------- */
        /*      Reading the shapes                                              */
        /* -------------------------------------------------------------------- */
        strInfomation += ("");
        Feature feat;

        while ((feat = layer.GetNextFeature()) != null)
        {
            strInfomation += ReportFeature(feat, def);
            feat.Dispose();
        }

        return(strInfomation);
    }
Exemple #6
0
        public static Transform GetUserSRSToModelTransform(OSGeo.OSR.SpatialReference userSRS)
        {
            ///TODO: Check what units the userSRS is in and coordinate with the scaling function.  Currently only accounts for a userSRS in meters.
            ///TODO: translate or scale GCS (decimal degrees) to something like a Projectected Coordinate System.  Need to go dd to xy

            ///transform rhino EAP from rhinoSRS to userSRS
            double eapLat   = EarthAnchorPoint.EarthBasepointLatitude;
            double eapLon   = EarthAnchorPoint.EarthBasepointLongitude;
            double eapElev  = EarthAnchorPoint.EarthBasepointElevation;
            Plane  eapPlane = EarthAnchorPoint.GetEarthAnchorPlane(out Vector3d eapNorth);

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

            OSGeo.OSR.CoordinateTransformation coordTransform = new OSGeo.OSR.CoordinateTransformation(rhinoSRS, userSRS);
            OSGeo.OGR.Geometry userAnchorPointDD = Heron.Convert.Point3dToOgrPoint(new Point3d(eapLon, eapLat, eapElev));
            Transform          t = new Transform(1.0);

            userAnchorPointDD.Transform(coordTransform);

            Point3d userAnchorPointPT = Heron.Convert.OgrPointToPoint3d(userAnchorPointDD, t);

            ///setup userAnchorPoint plane for move and rotation
            double eapLatNorth = EarthAnchorPoint.EarthBasepointLatitude + 0.5;
            double eapLonEast  = EarthAnchorPoint.EarthBasepointLongitude + 0.5;

            OSGeo.OGR.Geometry userAnchorPointDDNorth = Heron.Convert.Point3dToOgrPoint(new Point3d(eapLon, eapLatNorth, eapElev));
            OSGeo.OGR.Geometry userAnchorPointDDEast  = Heron.Convert.Point3dToOgrPoint(new Point3d(eapLonEast, eapLat, eapElev));
            userAnchorPointDDNorth.Transform(coordTransform);
            userAnchorPointDDEast.Transform(coordTransform);
            Point3d  userAnchorPointPTNorth = Heron.Convert.OgrPointToPoint3d(userAnchorPointDDNorth, t);
            Point3d  userAnchorPointPTEast  = Heron.Convert.OgrPointToPoint3d(userAnchorPointDDEast, t);
            Vector3d userAnchorNorthVec     = userAnchorPointPTNorth - userAnchorPointPT;
            Vector3d userAnchorEastVec      = userAnchorPointPTEast - userAnchorPointPT;

            Plane userEapPlane = new Plane(userAnchorPointPT, userAnchorEastVec, userAnchorNorthVec);

            ///shift (move and rotate) from userSRS EAP to 0,0 based on SRS north direction
            Transform scale = Transform.Scale(new Point3d(0.0, 0.0, 0.0), (1 / Rhino.RhinoMath.UnitScale(Rhino.RhinoDoc.ActiveDoc.ModelUnitSystem, Rhino.UnitSystem.Meters)));

            if (userSRS.GetLinearUnitsName().ToUpper().Contains("FEET") || userSRS.GetLinearUnitsName().ToUpper().Contains("FOOT"))
            {
                scale = Transform.Scale(new Point3d(0.0, 0.0, 0.0), (1 / Rhino.RhinoMath.UnitScale(Rhino.RhinoDoc.ActiveDoc.ModelUnitSystem, Rhino.UnitSystem.Feet)));
            }

            ///if SRS is geographic (ie WGS84) use Rhino's internal projection
            ///this is still buggy as it doesn't work with other geographic systems like NAD27
            if ((userSRS.IsProjected() == 0) && (userSRS.IsLocal() == 0))
            {
                userEapPlane.Transform(WGSToXYZTransform());
                scale = WGSToXYZTransform();
            }

            Transform shift = Transform.ChangeBasis(eapPlane, userEapPlane);

            Transform shiftScale = Transform.Multiply(scale, shift);

            return(shiftScale);
        }
        /// <summary>
        /// Gest the Src WKT given the EPSG code
        /// </summary>
        /// <param name="EPSG"></param>
        public static string EPSG2WKT(int EPSG)
        {
            var src = new OSGeo.OSR.SpatialReference("");

            src.ImportFromEPSG(EPSG);
            src.ExportToWkt(out var proj_wkt, null);
            return(proj_wkt);
        }
Exemple #8
0
        /// <summary>
        /// 线声源离散
        /// </summary>
        /// <param name="sourcePath">声源路径</param>
        /// <param name="resultPath">离散后路径</param>
        /// <param name="splitLength">分割长度</param>
        /// <param name="timeType">时段</param>
        /// <param name="frequency">频率</param>
        /// <returns></returns>
        private Layer getSource()
        {
            String sourceResultPath = m_resultPath + "\\SourceTemp.shp";//输出路径

            // 写入文件
            OSGeo.OGR.Driver resultDriver = Ogr.GetDriverByName("ESRI Shapefile");

            // 创建数据源

            DataSource resultDataSource;

            if (Ogr.Open(sourceResultPath, 0) != null)
            {
                resultDataSource = Ogr.Open(sourceResultPath, 1);
                resultDataSource.DeleteLayer(0);
            }
            else
            {
                resultDataSource = resultDriver.CreateDataSource(sourceResultPath, null);
            }

            //投影信息
            OSGeo.OSR.SpatialReference projection = new OSGeo.OSR.SpatialReference("");
            projection.ImportFromEPSG(3395);

            //构建声源点图层
            Layer resultLayer = resultDataSource.CreateLayer("POINT", projection, wkbGeometryType.wkbPoint, null);

            //构建属性
            resultLayer.CreateField(new FieldDefn("HEIGHT_G", FieldType.OFTReal), 1);  //高度
            resultLayer.CreateField(new FieldDefn("PWLs", FieldType.OFTReal), 1);      //单一频率声功率级
            resultLayer.CreateField(new FieldDefn("FREQUENCY", FieldType.OFTReal), 1); //频率

            ISource    sourceBean = null;
            DataSource sourceDataSource;

            foreach (KeyValuePair <String, String> item in m_sourcePath)
            {
                switch (item.Key)
                {
                case "road":
                    sourceBean = new RoadSourrce();
                    break;

                case "rainway":
                    sourceBean = new RainwaySource();
                    break;

                case "subway":
                    sourceBean = new RoadSourrce();
                    break;
                }
                //源文件
                sourceDataSource = Ogr.Open(item.Value, 0);
                resultLayer      = sourceBean.getSource(sourceDataSource.GetLayerByIndex(0), resultLayer, m_splitLength, m_timeType, m_frequency);
            }
            return(resultLayer);
        }
Exemple #9
0
        public static Transform GetModelToUserSRSTransform(OSGeo.OSR.SpatialReference userSRS)
        {
            var xyzToUserSRS = GetUserSRSToModelTransform(userSRS);

            if (xyzToUserSRS.TryGetInverse(out Transform transform))
            {
                return(transform);
            }
            return(Transform.Unset);
        }
Exemple #10
0
        /// <summary>
        /// Gets the projection info.
        /// </summary>
        /// <returns>The projection info.</returns>
        public ProjectionInfo GetProj4ProjectionInfo()
        {
            string sProj4String;

            //SpatialReference osrSpatialref = _ogrLayer.GetSpatialRef();
            // CGX
            OSGeo.OSR.SpatialReference osrSpatialref = _ogrLayer.GetSpatialRef();
            osrSpatialref.ExportToProj4(out sProj4String);
            return(ProjectionInfo.FromProj4String(sProj4String));
        }
 public static HandleRef getCPtrAndSetReference(SpatialReference obj, object parent) {
   if (obj != null)
   {
     obj.swigParentRef = parent;
     return obj.swigCPtr;
   }
   else
   {
     return new HandleRef(null, IntPtr.Zero);
   }
 }
        public void GetProjString(string file)
        {
            using var dataset = Gdal.Open(file, Access.GA_ReadOnly);

            string wkt = dataset.GetProjection();

            using var spatialReference = new OSGeo.OSR.SpatialReference(wkt);

            spatialReference.ExportToProj4(out string projString);

            Assert.False(string.IsNullOrWhiteSpace(projString));
        }
Exemple #13
0
        ///// <summary>
        ///// Loads a Ogr datasource with the specified layer
        ///// </summary>
        ///// <param name="filename">datasource</param>
        ///// <param name="layerName">name of layer</param>
        /////If you want this functionality use
        /////<example>
        /////SharpMap.Data.Providers.Ogr prov = new SharpMap.Data.Providers.Ogr(datasource);
        /////prov.LayerName = layerName;
        /////</example>
        //[Obsolete("This constructor does not work well with VB.NET. Use LayerName property instead")]
        //public Ogr(string filename, string layerName)
        //{
        //    Filename = filename;

        //    _ogrDataSource = OgrOgr.Open(filename, 1);
        //    _ogrLayer = _ogrDataSource.GetLayerByName(layerName);
        //    OsrSpatialReference spatialReference = _ogrLayer.GetSpatialRef();
        //    if (spatialReference != null)
        //        SRID = spatialReference.AutoIdentifyEPSG();
        //}

        /// <summary>
        /// Loads a Ogr datasource with the specified layer
        /// </summary>
        /// <param name="filename">datasource</param>
        /// <param name="layerNum">number of layer</param>
        public Ogr(string filename, int layerNum)
        {
            Filename = filename;

            _ogrDataSource = OgrOgr.Open(filename, 0);
            _ogrLayer      = _ogrDataSource.GetLayerByIndex(layerNum);
            OsrSpatialReference spatialReference = _ogrLayer.GetSpatialRef();

            if (spatialReference != null)
            {
                SRID = spatialReference.AutoIdentifyEPSG();
            }
        }
    public static string ToProj4(string wkt)
    {
      if (string.IsNullOrEmpty(wkt))
        return wkt;

      using (SpatialReference sr = new SpatialReference(wkt))
      {
        string res = null;
        sr.ExportToProj4(out res);

        return res;
      }
    }
Exemple #15
0
        //将内存中一个图层的数据保存在文件中
        public override Boolean SaveToFile(String tablename)
        {
            if (!this.featureSources.ContainsKey(tablename))
            {
                return(false);
            }
            int           srid          = 3857;
            FeatureSource featuresource = this.featureSources[tablename];

            OSGeo.OSR.SpatialReference sr = featuresource.schema.rs.spetialReference;
            if (sr != null)
            {
                srid = 3857;
            }
            return(this.pgio.Save2Table(this.featureSources[tablename], srid));
        }
        /// <summary>
        /// Simple coordinate reprojection
        /// </summary>
        /// <param name="EpsgIn"></param>
        /// <param name="EpsgOut"></param>
        /// <returns></returns>
        public static double[] ReprojectCoordinates(int EpsgIn, int EpsgOut, double x, double y, double z)
        {
            var src = new OSGeo.OSR.SpatialReference(EPSG2WKT(EpsgIn));

            logger.Trace($"SOURCE IsGeographic:" + src.IsGeographic() + " IsProjected:" + src.IsProjected());
            var dst = new OSGeo.OSR.SpatialReference(EPSG2WKT(EpsgOut));

            logger.Trace("DEST IsGeographic:" + dst.IsGeographic() + " IsProjected:" + dst.IsProjected());
            var ct = new OSGeo.OSR.CoordinateTransformation(src, dst);

            double[] p = new double[] { x, y, z };
            logger.Trace("From: x:" + p[0] + " y:" + p[1] + " z:" + p[2]);
            ct.TransformPoint(p);
            logger.Trace("To: x:" + p[0] + " y:" + p[1] + " z:" + p[2]);
            return(p);
        }
        /// <summary>
        /// Build a contour vector layer
        /// </summary>
        /// <param name="InputRaster"></param>
        /// <param name="OutputShp">output shapefile</param>
        /// <param name="ContoutInterval">increment balue (from CotourBase) to create contour</param>
        /// <param name="ContourBase">initial value to compute contour</param>
        public static void Contour(string InputRaster, string OutputShp, double ContourInterval, double ContourBase)
        {
            // https://gis.stackexchange.com/questions/210500/calling-gdal-contour-from-python-ipython

            using (var dsc = Gdal.Open(InputRaster, Access.GA_ReadOnly)) {
                var band = dsc.GetRasterBand(1);

                // Generate layer to save Contourlines in
                using (var ogr_ds = Ogr.GetDriverByName("ESRI Shapefile").CreateDataSource(OutputShp, new string[] { "srs", dsc.GetProjection() })) {
                    var srs         = new OSGeo.OSR.SpatialReference(dsc.GetProjection());
                    var contour_shp = ogr_ds.CreateLayer("contour", srs, wkbGeometryType.wkbLineString, null);
                    contour_shp.CreateField(new FieldDefn("ID", FieldType.OFTInteger), 1);
                    contour_shp.CreateField(new FieldDefn("ELEVATION", FieldType.OFTReal), 2);

                    //Generate Contour lines
                    Gdal.ContourGenerate(band, ContourInterval, ContourBase, 0, null, 0, -9999.9, contour_shp, contour_shp.FindFieldIndex("ID", 0), contour_shp.FindFieldIndex("ELEVATION", 0), GDalProgress, string.Empty);
                }
            }
        }
    public static string ToCoordinateSystem(string srs, bool isName)
    {
      if (string.IsNullOrEmpty(srs))
        return srs;

      string result = null;
      if (_srCache.TryGetValue(srs, out result))
        return result;

      using (SpatialReference sr = new SpatialReference(null))
      {
        if (isName)
        {
          int srsId;
          if (int.TryParse(srs, out srsId))
            sr.ImportFromEPSG(srsId);
          else
          {
            // TODO
          }
        }
        else
        {
          if (srs.StartsWith("+proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0"))
          {   //      +proj=merc +a=6378137 +b=6378137 +lat_ts=0.0 +lon_0=0.0 +x_0=0.0 +y_0=0.0 +k=1.0 +units=m +nadgrids=@null +wktext +no_defs
              //sr.ImportFromProj4(srs);
            sr.ImportFromEPSG(900913);
          }
          else
          {
            sr.ImportFromProj4(srs);
          }
        }

        sr.ExportToWkt(out result);

        if (result != null)
          _srCache.TryAdd(srs, result);

        return result;
      }
    }
        /// <summary>
        /// Reproject a raster.
        /// Working with errors
        /// </summary>
        /// <param name="InputFilePath"></param>
        /// <param name="OutputFilePath"></param>
        /// <param name="EPSG">output EPSG</param>
        public static void RasterReprojection(string InputFilePath, string OutputFilePath, int EPSG)
        {
            // TODO: Check for errors!
            var sr = new OSGeo.OSR.SpatialReference(null);

            sr.ImportFromEPSG(EPSG);
            sr.ExportToWkt(out var srs_wkt, null);

            // reproject raster and save to EHdr
            using (var srcDs = Gdal.Open(InputFilePath, Access.GA_ReadOnly))
                using (var vrt = Gdal.AutoCreateWarpedVRT(srcDs, srcDs.GetProjectionRef(), srs_wkt, ResampleAlg.GRA_Average, 0)) {
                    var OutDirver = srcDs.GetDriver();
                    OutDirver.CreateCopy(OutputFilePath, vrt, 1, null, GDalProgress, "Raster Reprojection");
                }
            //using( var MemDirver = Gdal.GetDriverByName("MEM"))

            //using( var bilDirver = srcDs.GetDriver() Gdal.GetDriverByName("EHdr"))
            //using( var bilfile = bilDirver.CreateCopy("lo que sea/asd/", vrt, 1, null,null, null))

            return;
        }
        private static NetTopologySuite.Geometries.Point Wgs84ToWgs84UpsNorth(Point location)
        {
            if (location.SRID != 4326)
            {
                throw new Exception("Unsupported coordinate system: " + location.SRID);
            }

            OSGeo.OSR.SpatialReference wgs84Src = new OSGeo.OSR.SpatialReference("");
            wgs84Src.ImportFromProj4("+proj=longlat +datum=WGS84 +no_defs");

            OSGeo.OSR.SpatialReference stereoNorthPoleDest = new OSGeo.OSR.SpatialReference("");
            stereoNorthPoleDest.ImportFromProj4("+proj=stere +lat_0=90 +lat_ts=90 +lon_0=0 +k=0.994 +x_0=2000000 +y_0=2000000 +datum=WGS84 +units=m +no_defs");

            OSGeo.OSR.CoordinateTransformation ct = new OSGeo.OSR.CoordinateTransformation(wgs84Src, stereoNorthPoleDest);

            double[] point = new double[3];
            point[0] = location.X;
            point[1] = location.Y;
            point[2] = location.Z;

            ct.TransformPoint(point);

            return(new Point(point[0], point[1]));
        }
Exemple #21
0
        public static void Test2()
        {
            try
            {
                Ogr.RegisterAll();
                string     shapefile = @"C:\data\Links\Links.shp";
                DataSource ds        = Ogr.Open(shapefile, 0);
                Driver     driver    = ds.GetDriver();

                int nLayerCount = ds.GetLayerCount();//1
                for (int iLayer = 0; iLayer < nLayerCount; iLayer++)
                {
                    Layer  layer     = ds.GetLayerByIndex(iLayer);
                    string layerName = layer.GetName();
                    int    fc        = layer.GetFeatureCount(1);

                    Envelope env = new Envelope();
                    layer.GetExtent(env, 1);

                    //MessageBox.Show("test sr");
                    OSGeo.OSR.SpatialReference sr = layer.GetSpatialRef();
                    string sr_wkt;
                    sr.ExportToPrettyWkt(out sr_wkt, 1);

                    layer.GetName();
                    FeatureDefn def = layer.GetLayerDefn();
                    def.GetName();
                    for (int iField = 0; iField < def.GetFieldCount(); iField++)
                    {
                        FieldDefn fdef          = def.GetFieldDefn(iField);
                        string    fieldName     = fdef.GetName();                             //Id Name URL
                        FieldType fieldType     = fdef.GetFieldType();                        //OFTInteger OFTString OFTString
                        string    fieldTypeName = fdef.GetFieldTypeName(fdef.GetFieldType()); //Integer String String
                        int       width         = fdef.GetWidth();                            //6 50 254
                        int       precision     = fdef.GetPrecision();                        //0 0 0
                    }

                    for (int fid = 0; fid < layer.GetFeatureCount(1); fid++)
                    {
                        Feature  f           = layer.GetFeature(fid);
                        int      id          = f.GetFID();
                        int      nFiledCount = f.GetFieldCount();
                        Geometry geom        = f.GetGeometryRef();

                        // retrive geometry data
                        //this.Geometrys.Add(geom);

                        string geomName = geom.GetGeometryName();            //POINT
                        string geomType = geom.GetGeometryType().ToString(); //wkbPoint

                        Envelope geom_env = new Envelope();
                        geom.GetEnvelope(geom_env);

                        // wkt
                        string geom_wkt;
                        geom.ExportToWkt(out geom_wkt);//"POINT (-63.490966216299803 46.66247022944782)"

                        int wkbSize = geom.WkbSize();
                        if (wkbSize > 0)
                        {
                            // wkb
                            byte[] geom_wkb = new byte[wkbSize];
                            geom.ExportToWkb(geom_wkb);
                            string str_wkb = BitConverter.ToString(geom_wkb);

                            // wkb--->wkt
                            Geometry geom2 = Geometry.CreateFromWkb(geom_wkb);
                            string   geom2_wkt;
                            geom2.ExportToWkt(out geom2_wkt);
                        }

                        f.Dispose();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.ToString());
                return;
            }
        }
Exemple #22
0
        public void readLayerTest(string strVectorFile)
        {
            Gdal.AllRegister();
            //为了支持中文路径,请添加下面这句代码
            Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");
            //为了使属性表字段支持中文,请添加下面这句
            Gdal.SetConfigOption("SHAPE_ENCODING", "");


            // 注册所有的驱动
            Ogr.RegisterAll();
            Gdal.SetConfigOption("GDAL_DATA", "E://lib//gdal//gdal1.9//data");

            //打开数据
            DataSource ds = Ogr.Open(strVectorFile, 0);



            if (ds == null)
            {
                Console.WriteLine("打开文件【{0}】失败!", strVectorFile);
                return;
            }
            Console.WriteLine("打开文件【{0}】成功!", strVectorFile);


            // 获取该数据源中的图层个数,一般shp数据图层只有一个,如果是mdb、dxf等图层就会有多个
            int iLayerCount = ds.GetLayerCount();

            // 获取第一个图层
            Layer oLayer = ds.GetLayerByIndex(0);


            String c = "";

            oLayer.GetSpatialRef().AutoIdentifyEPSG();

            Console.WriteLine(oLayer.GetSpatialRef().AutoIdentifyEPSG());


            OSGeo.OSR.SpatialReference spa = oLayer.GetSpatialRef();
            // if (spa==null)
            // {
            spa = new OSGeo.OSR.SpatialReference(null);
            spa.ImportFromEPSG(3395);


            spa.ExportToWkt(out c);
            Console.WriteLine(c);

            return;


            // }
            //  String a = "";
            // spa.EPSGTreatsAsLatLong();
            // Console.WriteLine(spa.ExportToWkt(out a));

            // oLayer.GetSpatialRef().ExportToWkt(out a);

            // Console.WriteLine(spa.GetProjParm(out a));

            // Console.WriteLine(oLayer.GetSpatialRef().GetLinearUnitsName());
            if (oLayer == null)
            {
                Console.WriteLine("获取第{0}个图层失败!\n", 0);
                return;
            }

            // 对图层进行初始化,如果对图层进行了过滤操作,执行这句后,之前的过滤全部清空
            oLayer.ResetReading();

            // 通过属性表的SQL语句对图层中的要素进行筛选,这部分详细参考SQL查询章节内容
            //  oLayer.SetAttributeFilter("\"NAME99\"LIKE \"北京市市辖区\"");

            // 通过指定的几何对象对图层中的要素进行筛选
            //oLayer.SetSpatialFilter();

            // 通过指定的四至范围对图层中的要素进行筛选
            //oLayer.SetSpatialFilterRect();

            // 获取图层中的属性表表头并输出
            // Console.WriteLine("属性表结构信息:");
            FeatureDefn oDefn       = oLayer.GetLayerDefn();
            int         iFieldCount = oDefn.GetFieldCount();

            for (int iAttr = 0; iAttr < iFieldCount; iAttr++)
            {
                FieldDefn oField = oDefn.GetFieldDefn(iAttr);

                Console.WriteLine("{0}:{1} ({2}.{3})", oField.GetNameRef(),
                                  oField.GetFieldTypeName(oField.GetFieldType()),
                                  oField.GetWidth(), oField.GetPrecision());
            }

            // 输出图层中的要素个数
            Console.WriteLine("要素个数 = {0}", oLayer.GetFeatureCount(0));

            Feature oFeature = null;

            // 下面开始遍历图层中的要素
            while ((oFeature = oLayer.GetNextFeature()) != null)
            {
                Console.WriteLine("当前处理第{0}个: \n属性值:", oFeature.GetFID());
                // 获取要素中的属性表内容

                for (int iField = 0; iField < iFieldCount; iField++)
                {
                    FieldDefn oFieldDefn = oDefn.GetFieldDefn(iField);
                    FieldType type       = oFieldDefn.GetFieldType();

                    switch (type)
                    {
                    case FieldType.OFTString:
                        Console.WriteLine("{0}\t", oFeature.GetFieldAsString(iField));
                        break;

                    case FieldType.OFTReal:
                        Console.WriteLine("{0}\t", oFeature.GetFieldAsDouble(iField));
                        break;

                    case FieldType.OFTInteger:
                        Console.WriteLine("{0}\t", oFeature.GetFieldAsInteger(iField));
                        break;

                    default:
                        Console.WriteLine("{0}\t", oFeature.GetFieldAsString(iField));
                        break;
                    }
                }

                // 获取要素中的几何体
                Geometry oGeometry = oFeature.GetGeometryRef();

                //  String a=oGeometry.GetGeometryName();
                //  String b = "";
                //  oGeometry.ExportToWkt(out b);
                Console.WriteLine(oGeometry.GetGeometryName());
                // 为了演示,只输出一个要素信息
                break;
            }

            Console.WriteLine("数据集关闭!");
            Console.ReadLine();
        }
Exemple #23
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);
        }
Exemple #24
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);
        }
Exemple #25
0
        public static List <string> OGRInfo(string datasourceFileLocation)
        {
            List <string> info = new List <string>();

            Ogr.RegisterAll();
            DataSource ds = Ogr.Open(datasourceFileLocation, 0);

            if (ds == null)
            {
                info.Add("Couldn not open vector data source.");
                return(info);
            }

            OSGeo.OGR.Driver drv = ds.GetDriver();
            if (drv == null)
            {
                info.Add("Could not find driver to open vector data source.");
                return(info);
            }

            info.Add("Using driver: " + drv.GetName());

            ///Iterating through layers
            for (int iLayer = 0; iLayer < ds.GetLayerCount(); iLayer++)
            {
                Layer layer = ds.GetLayerByIndex(iLayer);
                if (layer == null)
                {
                    info.Add("Could not find layers in the vector data source.");
                    return(info);
                }
                FeatureDefn def = layer.GetLayerDefn();
                info.Add("Layer name: " + def.GetName());
                info.Add("Feature count: " + layer.GetFeatureCount(1));
                Envelope ext = new Envelope();
                layer.GetExtent(ext, 1);
                info.Add("Extent: " + ext.MinX + ", " + ext.MinY + ", " + ext.MaxX + ", " + ext.MaxY);

                ///Reading the spatial reference
                OSGeo.OSR.SpatialReference sr = layer.GetSpatialRef();
                string srs_wkt = string.Empty;
                if (sr != null)
                {
                    sr.ExportToPrettyWkt(out srs_wkt, 1);
                }
                else
                {
                    srs_wkt = "(unknow)";
                }
                info.Add("Layer SRS WKT: " + srs_wkt);

                ///Reading the fields
                info.Add("Field Names (type): ");
                for (int iAttr = 0; iAttr < def.GetFieldCount(); iAttr++)
                {
                    FieldDefn fdef = def.GetFieldDefn(iAttr);
                    info.Add(fdef.GetName() + " (" +
                             fdef.GetFieldTypeName(fdef.GetFieldType()) + ")");
                }
            }
            ds.Dispose();

            return(info);
        }
        public override void DoWork(Action <string, double> ReportProgress, Action Done)
        {
            // Checking for cancellation
            if (CancellationToken.IsCancellationRequested)
            {
                return;
            }

            ///Make sure there's an API key
            string mbToken = ApiKey;

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

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

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

            ///Mapbox uses EPSG:3857
            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);

            double lat = Heron.Convert.XYZToWGS(Location).Y;
            double lon = Heron.Convert.XYZToWGS(Location).X;

            ///Setup contour style and unit type
            string contourType = String.Empty;
            double?contourNum  = Contour;

            if (contourNum < 0.0)
            {
                contourNum = 0.0;
            }
            double unitConversion = Rhino.RhinoMath.UnitScale(Rhino.RhinoDoc.ActiveDoc.ModelUnitSystem, Rhino.UnitSystem.Meters);

            if (MapboxIsochroneSpeckle.MinutesOrMeters == "Distance")
            {
                contourType = "contours_meters=";
                contourNum  = contourNum * unitConversion;
            }
            else
            {
                contourType = "contours_minutes=";
                if (contourNum > 60)
                {
                    contourNum = 60;
                    RuntimeMessages.Add((GH_RuntimeMessageLevel.Warning, "Maximum minute contour is 60.  Contour value reduced to 60."));
                }
            }

            ///Make sure Denoise is between 0..1
            double?denoiseNum = Denoise;

            if (denoiseNum < 0.0)
            {
                denoiseNum = 0.0;
            }
            if (denoiseNum > 1.0)
            {
                denoiseNum = 1.0;
            }

            ///Make sure Generalize is > 0
            double?generalizeNum = Generalize * unitConversion;

            if (generalizeNum < 0.0)
            {
                generalizeNum = 0.0;
            }

            ///Construct URL query string
            string url = @"https://api.mapbox.com/isochrone/v1/mapbox/";

            if (!String.IsNullOrEmpty(MapboxIsochroneSpeckle.Profile))
            {
                url = url + MapboxIsochroneSpeckle.Profile.ToLower() + "/";
            }
            if (lon > -180.0 && lon <= 180.0)
            {
                url = url + lon + "%2C";
            }
            if (lat > -90.0 && lat <= 90.0)
            {
                url = url + lat + "?";
            }
            if (!String.IsNullOrEmpty(contourType))
            {
                url = url + contourType.ToLower();
            }
            if (contourNum != null)
            {
                url = url + contourNum;
            }
            url = url + "&polygons=true";
            if (denoiseNum != null)
            {
                url = url + "&denoise=" + denoiseNum;
            }
            if (generalizeNum != null)
            {
                url = url + "&generalize=" + generalizeNum;
            }
            if (mbToken != "")
            {
                url = url + "&access_token=" + mbToken;
            }

            Url = url;


            if (CancellationToken.IsCancellationRequested)
            {
                return;
            }
            if (Run)
            {
                List <IGH_GeometricGoo> gGoo       = new List <IGH_GeometricGoo>();
                OSGeo.OGR.DataSource    dataSource = OSGeo.OGR.Ogr.Open(url, 0);

                if (dataSource == null)
                {
                    RuntimeMessages.Add((GH_RuntimeMessageLevel.Error, "Mapbox returned an invalid response."));
                    return;
                }

                ///Only interested in geometry, not fields or values
                OSGeo.OGR.Layer   ogrLayer = dataSource.GetLayerByIndex(0);
                OSGeo.OGR.Feature feat;

                while ((feat = ogrLayer.GetNextFeature()) != null)
                {
                    OSGeo.OGR.Geometry geomUser = feat.GetGeometryRef().Clone();
                    ///reproject geometry to WGS84 and userSRS
                    ///TODO: look into using the SetCRS global variable here
                    if (geomUser.GetSpatialReference() == null)
                    {
                        geomUser.AssignSpatialReference(userSRS);
                    }

                    geomUser.TransformTo(userSRS);
                    if (feat.GetGeometryRef() != null)
                    {
                        gGoo.AddRange(Heron.Convert.OgrGeomToGHGoo(geomUser, userSRSToModelTransform));
                    }
                }

                Isochrones = gGoo;
            }

            Done();
        }
 public int CopyGeogCSFrom(SpatialReference rhs)
 {
     int ret = OsrPINVOKE.SpatialReference_CopyGeogCSFrom(swigCPtr, SpatialReference.getCPtr(rhs));
     if (OsrPINVOKE.SWIGPendingException.Pending) throw OsrPINVOKE.SWIGPendingException.Retrieve();
     return ret;
 }
Exemple #28
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            Curve boundary = null;

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

            string sourceFileLocation = string.Empty;

            DA.GetData <string>(1, ref sourceFileLocation);

            string clippedLocation = string.Empty;

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

            RESTful.GdalConfiguration.ConfigureGdal();
            OSGeo.GDAL.Gdal.AllRegister();
            ///Specific settings for getting WMS images
            OSGeo.GDAL.Gdal.SetConfigOption("GDAL_HTTP_UNSAFESSL", "YES");
            OSGeo.GDAL.Gdal.SetConfigOption("GDAL_SKIP", "WMS");

            ///Read in the raster data
            Dataset datasource = Gdal.Open(sourceFileLocation, Access.GA_ReadOnly);

            OSGeo.GDAL.Driver drv = datasource.GetDriver();

            string srcInfo = string.Empty;

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


            ///Get the spatial reference of the input raster file and set to WGS84 if not known
            ///Set up transform from source to WGS84
            OSGeo.OSR.SpatialReference sr = new SpatialReference(Osr.SRS_WKT_WGS84);

            if (datasource.GetProjection() == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) is missing.  SRS set automatically set to WGS84.");
            }

            else
            {
                sr = new SpatialReference(datasource.GetProjection());

                if (sr.Validate() != 0)
                {
                    ///Check if SRS needs to be converted from ESRI format to WKT to avoid error:
                    ///"No translation for Lambert_Conformal_Conic to PROJ.4 format is known."
                    ///https://gis.stackexchange.com/questions/128266/qgis-error-6-no-translation-for-lambert-conformal-conic-to-proj-4-format-is-kn
                    SpatialReference srEsri = sr;
                    srEsri.MorphFromESRI();
                    string projEsri = string.Empty;
                    srEsri.ExportToWkt(out projEsri);

                    ///If no SRS exists, check Ground Control Points SRS
                    SpatialReference srGCP   = new SpatialReference(datasource.GetGCPProjection());
                    string           projGCP = string.Empty;
                    srGCP.ExportToWkt(out projGCP);

                    if (!string.IsNullOrEmpty(projEsri))
                    {
                        datasource.SetProjection(projEsri);
                        sr = srEsri;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) morphed form ESRI format.");
                    }
                    else if (!string.IsNullOrEmpty(projGCP))
                    {
                        datasource.SetProjection(projGCP);
                        sr = srGCP;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) set from Ground Control Points (GCPs).");
                    }
                    else
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) is unknown or unsupported.  SRS assumed to be WGS84." +
                                          "Try setting the SRS with the GdalWarp component using -t_srs EPSG:4326 for the option input.");
                        sr.SetWellKnownGeogCS("WGS84");
                    }
                }
                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Data source SRS: EPSG:" + sr.GetAttrValue("AUTHORITY", 1));
                }
            }

            ///Get info about image
            List <string> infoOptions = new List <string> {
                "-stats"
            };

            srcInfo = Gdal.GDALInfo(datasource, new GDALInfoOptions(infoOptions.ToArray()));

            //OSGeo.OSR.SpatialReference sr = new SpatialReference(ds.GetProjection());
            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);

            double[] adfGeoTransform = new double[6];
            double[] invTransform    = new double[6];
            datasource.GetGeoTransform(adfGeoTransform);
            Gdal.InvGeoTransform(adfGeoTransform, invTransform);
            Band band = datasource.GetRasterBand(1);

            int width  = datasource.RasterXSize;
            int height = datasource.RasterYSize;

            ///Dataset bounding box
            double oX = adfGeoTransform[0] + adfGeoTransform[1] * 0 + adfGeoTransform[2] * 0;
            double oY = adfGeoTransform[3] + adfGeoTransform[4] * 0 + adfGeoTransform[5] * 0;
            double eX = adfGeoTransform[0] + adfGeoTransform[1] * width + adfGeoTransform[2] * height;
            double eY = adfGeoTransform[3] + adfGeoTransform[4] * width + adfGeoTransform[5] * height;

            ///Transform to WGS84.
            ///TODO: Allow for UserSRS
            double[] extMinPT = new double[3] {
                oX, eY, 0
            };
            double[] extMaxPT = new double[3] {
                eX, oY, 0
            };
            coordTransform.TransformPoint(extMinPT);
            coordTransform.TransformPoint(extMaxPT);
            Point3d dsMin = new Point3d(extMinPT[0], extMinPT[1], extMinPT[2]);
            Point3d dsMax = new Point3d(extMaxPT[0], extMaxPT[1], extMaxPT[2]);

            ///Get bounding box for entire raster data
            Rectangle3d datasourceBBox = new Rectangle3d(Plane.WorldXY, Heron.Convert.WGSToXYZ(dsMin), Heron.Convert.WGSToXYZ(dsMax));


            ///https://gis.stackexchange.com/questions/312440/gdal-translate-bilinear-interpolation
            ///set output to georeferenced tiff as a catch-all
            string clippedRasterFile = clippedLocation + Path.GetFileNameWithoutExtension(sourceFileLocation) + "_clipped.tif";
            string previewPNG        = clippedLocation + Path.GetFileNameWithoutExtension(sourceFileLocation) + "_preview.png";

            AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Original Resolution: " + datasource.RasterXSize.ToString() + "x" + datasource.RasterYSize.ToString());

            if (boundary != null)
            {
                Point3d clipperMin = Heron.Convert.XYZToWGS(boundary.GetBoundingBox(true).Corner(true, false, true));
                Point3d clipperMax = Heron.Convert.XYZToWGS(boundary.GetBoundingBox(true).Corner(false, true, true));

                double lonWest  = clipperMin.X;
                double lonEast  = clipperMax.X;
                double latNorth = clipperMin.Y;
                double latSouth = clipperMax.Y;

                ///GDALTranslate should also be its own component with full control over options
                var translateOptions = new[]
                {
                    "-of", "GTiff",
                    //"-a_nodata", "0",
                    "-projwin_srs", "WGS84",
                    "-projwin", $"{lonWest}", $"{latNorth}", $"{lonEast}", $"{latSouth}"
                };

                using (Dataset clippedDataset = Gdal.wrapper_GDALTranslate(clippedRasterFile, datasource, new GDALTranslateOptions(translateOptions), null, null))
                {
                    Dataset previewDataset = Gdal.wrapper_GDALTranslate(previewPNG, clippedDataset, null, null, null);

                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Clipped Resolution: " + clippedDataset.RasterXSize.ToString() + "x" + datasource.RasterYSize.ToString());

                    ///clean up
                    clippedDataset.FlushCache();
                    clippedDataset.Dispose();
                    previewDataset.FlushCache();
                    previewDataset.Dispose();

                    AddPreviewItem(previewPNG, BBoxToRect(boundary.GetBoundingBox(true)));
                }
            }

            else
            {
                Dataset previewDataset = Gdal.wrapper_GDALTranslate(previewPNG, datasource, null, null, null);

                ///clean up
                previewDataset.FlushCache();
                previewDataset.Dispose();

                AddPreviewItem(previewPNG, datasourceBBox);
            }

            ///clean up
            datasource.FlushCache();
            datasource.Dispose();

            DA.SetData(0, srcInfo);
            DA.SetData(1, datasourceBBox);
            DA.SetData(2, clippedRasterFile);
        }
Exemple #29
0
    public static void Main(string[] args)
    {
        if (args.Length != 1) usage();

        Console.WriteLine("");

        try
        {
            /* -------------------------------------------------------------------- */
            /*      Register driver(s).                                             */
            /* -------------------------------------------------------------------- */
            Gdal.AllRegister();

            /* -------------------------------------------------------------------- */
            /*      Open dataset.                                                   */
            /* -------------------------------------------------------------------- */
            Dataset ds = Gdal.Open( args[0], Access.GA_ReadOnly );

            if (ds == null)
            {
                Console.WriteLine("Can't open " + args[0]);
                System.Environment.Exit(-1);
            }

            Console.WriteLine("Raster dataset parameters:");
            Console.WriteLine("  Projection: " + ds.GetProjectionRef());
            Console.WriteLine("  RasterCount: " + ds.RasterCount);
            Console.WriteLine("  RasterSize (" + ds.RasterXSize + "," + ds.RasterYSize + ")");

            /* -------------------------------------------------------------------- */
            /*      Get driver                                                      */
            /* -------------------------------------------------------------------- */
            Driver drv = ds.GetDriver();

            if (drv == null)
            {
                Console.WriteLine("Can't get driver.");
                System.Environment.Exit(-1);
            }

            Console.WriteLine("Using driver " + drv.LongName);

            /* -------------------------------------------------------------------- */
            /*      Get metadata                                                    */
            /* -------------------------------------------------------------------- */
            string[] metadata = ds.GetMetadata("");
            if (metadata.Length > 0)
            {
                Console.WriteLine("  Metadata:");
                for (int iMeta = 0; iMeta < metadata.Length; iMeta++)
                {
                    Console.WriteLine("    " + iMeta + ":  " + metadata[iMeta]);
                }
                Console.WriteLine("");
            }

            /* -------------------------------------------------------------------- */
            /*      Report "IMAGE_STRUCTURE" metadata.                              */
            /* -------------------------------------------------------------------- */
            metadata = ds.GetMetadata("IMAGE_STRUCTURE");
            if (metadata.Length > 0)
            {
                Console.WriteLine("  Image Structure Metadata:");
                for (int iMeta = 0; iMeta < metadata.Length; iMeta++)
                {
                    Console.WriteLine("    " + iMeta + ":  " + metadata[iMeta]);
                }
                Console.WriteLine("");
            }

            /* -------------------------------------------------------------------- */
            /*      Report subdatasets.                                             */
            /* -------------------------------------------------------------------- */
            metadata = ds.GetMetadata("SUBDATASETS");
            if (metadata.Length > 0)
            {
                Console.WriteLine("  Subdatasets:");
                for (int iMeta = 0; iMeta < metadata.Length; iMeta++)
                {
                    Console.WriteLine("    " + iMeta + ":  " + metadata[iMeta]);
                }
                Console.WriteLine("");
            }

            /* -------------------------------------------------------------------- */
            /*      Report geolocation.                                             */
            /* -------------------------------------------------------------------- */
            metadata = ds.GetMetadata("GEOLOCATION");
            if (metadata.Length > 0)
            {
                Console.WriteLine("  Geolocation:");
                for (int iMeta = 0; iMeta < metadata.Length; iMeta++)
                {
                    Console.WriteLine("    " + iMeta + ":  " + metadata[iMeta]);
                }
                Console.WriteLine("");
            }

            /* -------------------------------------------------------------------- */
            /*      Report corners.                                                 */
            /* -------------------------------------------------------------------- */
            Console.WriteLine( "Corner Coordinates:" );
            Console.WriteLine("  Upper Left (" + GDALInfoGetPosition( ds, 0.0, 0.0) + ")");
            Console.WriteLine("  Lower Left (" + GDALInfoGetPosition( ds, 0.0, ds.RasterYSize) + ")");
            Console.WriteLine("  Upper Right (" + GDALInfoGetPosition( ds, ds.RasterXSize, 0.0) + ")");
            Console.WriteLine("  Lower Right (" + GDALInfoGetPosition( ds, ds.RasterXSize, ds.RasterYSize) + ")");
            Console.WriteLine("  Center (" + GDALInfoGetPosition( ds, ds.RasterXSize / 2, ds.RasterYSize / 2) + ")");
            Console.WriteLine("");

            /* -------------------------------------------------------------------- */
            /*      Report projection.                                              */
            /* -------------------------------------------------------------------- */
            string projection = ds.GetProjectionRef();
            if (projection != null)
            {
                SpatialReference srs = new SpatialReference(null);
                if (srs.ImportFromWkt(ref projection) == 0)
                {
                    string wkt;
                    srs.ExportToPrettyWkt(out wkt, 0);
                    Console.WriteLine("Coordinate System is:");
                    Console.WriteLine(wkt);
                }
                else
                {
                    Console.WriteLine("Coordinate System is:");
                    Console.WriteLine(projection);
                }
            }

            /* -------------------------------------------------------------------- */
            /*      Report GCPs.                                                    */
            /* -------------------------------------------------------------------- */
            if( ds.GetGCPCount( ) > 0 )
            {
                Console.WriteLine( "GCP Projection: ", ds.GetGCPProjection());
                GCP[] GCPs = ds.GetGCPs();
                for( int i = 0; i < ds.GetGCPCount(); i++ )
                {
                    Console.WriteLine("GCP[" + i + "]: Id=" + GCPs[i].Id + ", Info=" + GCPs[i].Info);
                    Console.WriteLine("          (" + GCPs[i].GCPPixel + "," + GCPs[i].GCPLine + ") -> ("
                                + GCPs[i].GCPX + "," + GCPs[i].GCPY + "," + GCPs[i].GCPZ + ")");
                    Console.WriteLine("");
                }
                Console.WriteLine("");

                double[] transform = new double[6];
                Gdal.GCPsToGeoTransform(GCPs, transform, 0);
                Console.WriteLine("GCP Equivalent geotransformation parameters: ", ds.GetGCPProjection());
                for (int i = 0; i < 6; i++)
                    Console.WriteLine("t[" + i + "] = " + transform[i].ToString());
                Console.WriteLine("");
            }

            /* -------------------------------------------------------------------- */
            /*      Get raster band                                                 */
            /* -------------------------------------------------------------------- */
            for (int iBand = 1; iBand <= ds.RasterCount; iBand++)
            {
                Band band = ds.GetRasterBand(iBand);
                Console.WriteLine("Band " + iBand + " :");
                Console.WriteLine("   DataType: " + Gdal.GetDataTypeName(band.DataType));
                Console.WriteLine("   ColorInterpretation: " + Gdal.GetColorInterpretationName(band.GetRasterColorInterpretation()));
                ColorTable ct = band.GetRasterColorTable();
                if (ct != null)
                    Console.WriteLine("   Band has a color table with " + ct.GetCount() + " entries.");

                Console.WriteLine("   Description: " + band.GetDescription());
                Console.WriteLine("   Size (" + band.XSize + "," + band.YSize + ")");
                int BlockXSize, BlockYSize;
                band.GetBlockSize(out BlockXSize, out BlockYSize);
                Console.WriteLine("   BlockSize (" + BlockXSize + "," + BlockYSize + ")");
                double val;
                int hasval;
                band.GetMinimum(out val, out hasval);
                if (hasval != 0) Console.WriteLine("   Minimum: " + val.ToString());
                band.GetMaximum(out val, out hasval);
                if (hasval != 0) Console.WriteLine("   Maximum: " + val.ToString());
                band.GetNoDataValue(out val, out hasval);
                if (hasval != 0) Console.WriteLine("   NoDataValue: " + val.ToString());
                band.GetOffset(out val, out hasval);
                if (hasval != 0) Console.WriteLine("   Offset: " + val.ToString());
                band.GetScale(out val, out hasval);
                if (hasval != 0) Console.WriteLine("   Scale: " + val.ToString());

                for (int iOver = 0; iOver < band.GetOverviewCount(); iOver++)
                {
                    Band over = band.GetOverview(iOver);
                    Console.WriteLine("      OverView " + iOver + " :");
                    Console.WriteLine("         DataType: " + over.DataType);
                    Console.WriteLine("         Size (" + over.XSize + "," + over.YSize + ")");
                    Console.WriteLine("         PaletteInterp: " + over.GetRasterColorInterpretation().ToString());
                }
            }
        }
        catch (Exception e)
        {
            Console.WriteLine("Application error: " + e.Message);
        }
    }
Exemple #30
0
        /// <summary>
        /// Creates an OGR data source from a FeatureDataTable
        /// </summary>
        /// <param name="table">The name of the table</param>
        /// <param name="geometryType">The geometry type</param>
        /// <param name="driver">The driver</param>
        /// <param name="connection">The connection string</param>
        /// <param name="driverOptions">The options for the driver</param>
        /// <param name="layerOptions">The options for the layer</param>
        public static void CreateFromFeatureDataTable(FeatureDataTable table, 
            OgcGeometryType geometryType, int srid, string driver, string connection, string[] driverOptions = null, string[] layerOptions = null)
        {
            if (table == null)
                throw new ArgumentNullException("table");

            if (table.Rows.Count == 0)
                throw new ArgumentException("The table contains no rows", "table");

            if (geometryType < OgcGeometryType.Point || geometryType > OgcGeometryType.MultiPolygon)
                throw new ArgumentException("Invalid geometry type", "geometryType");

            if (string.IsNullOrWhiteSpace(driver))
                throw new ArgumentException("No driver specified", "driver");

            var dr = OSGeo.OGR.Ogr.GetDriverByName(driver);
            if (dr == null)
                throw new Exception(string.Format("Cannot load driver '{0}'!", driver));

            //if (!dr.TestCapability("ODrCCreateDataSource"))
            //    throw new Exception(string.Format("Driver '{0}' cannot create a data source!", driver));

            // Create the data source
            var ds = dr.CreateDataSource(connection, driverOptions);
            //if (!ds.TestCapability("ODsCCreateLayer"))
            //    throw new Exception(string.Format("Driver '{0}' cannot create a layer!", driver));

            // Create the spatial reference
            var sr = new OSGeo.OSR.SpatialReference(string.Empty);
            sr.ImportFromEPSG(srid);

            // Create the layer
            var lyr = ds.CreateLayer(table.TableName, sr, (OgrGeometryType)geometryType, layerOptions);
            sr.Dispose();

            //lyr.GetSpatialRef();
            foreach (System.Data.DataColumn dc in table.Columns)
            {
                using (var fldDef = GetFieldDefinition(dc))
                    lyr.CreateField(fldDef, 0);
            }

            using (var ld = lyr.GetLayerDefn())
            {
                foreach (FeatureDataRow fdr in table.Rows)
                {
                    if ((int)fdr.Geometry.OgcGeometryType != (int)geometryType)
                        continue;

                    using (var feature = new OgrFeature(ld))
                    {
                        feature.SetGeometry(OgrGeometry.CreateFromWkb(fdr.Geometry.AsBinary()));
                        var idx = -1;
                        foreach (System.Data.DataColumn dc in table.Columns)
                        {
                            idx++;
                            var fd = ld.GetFieldDefn(idx);
                            DateTime dt;
                            switch (fd.GetFieldType())
                            {
                                case OgrFieldType.OFTBinary:
                                    //Nothing
                                    break;
                                case OgrFieldType.OFTDate:
                                    dt = ((DateTime)fdr[dc]).Date;
                                    feature.SetField(idx, dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, 0);
                                    break;
                                case OgrFieldType.OFTDateTime:
                                    dt = (DateTime)fdr[dc];
                                    feature.SetField(idx, dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, 0);
                                    break;
                                case OgrFieldType.OFTTime:
                                    var tod = ((DateTime)fdr[dc]).TimeOfDay;
                                    feature.SetField(idx, 0, 0, 0, tod.Hours, tod.Minutes, tod.Seconds, 0);
                                    break;
                                case OgrFieldType.OFTInteger:
                                    feature.SetField(idx, Convert.ToInt32(fdr[dc]));
                                    break;
                                case OgrFieldType.OFTIntegerList:
                                    var il = GetIntegerList(fdr[dc], dc.DataType);
                                    feature.SetFieldIntegerList(idx, il.Length, il);
                                    break;
                                case OgrFieldType.OFTReal:
                                    feature.SetField(idx, Convert.ToDouble(fdr[dc]));
                                    break;
                                case OgrFieldType.OFTRealList:
                                    var dl = GetDoubleList(fdr[dc], dc.DataType);
                                    feature.SetFieldDoubleList(idx, dl.Length, dl);
                                    break;
                                case OgrFieldType.OFTString:
                                    feature.SetField(idx, Convert.ToString(fdr[dc]));
                                    break;
                                case OgrFieldType.OFTStringList:
                                    var sl = (string[])fdr[dc];
                                    feature.SetFieldStringList(idx, sl);
                                    break;

                            }
                            fd.Dispose();
                        }
                        lyr.CreateFeature(feature);
                        feature.Dispose();
                    }
                    //ld.Dispose();
                }
            }

            lyr.Dispose();
            ds.Dispose();
            dr.Dispose();
        }
 public static CoordinateTransformation CreateCoordinateTransformation(SpatialReference src, SpatialReference dst)
 {
     IntPtr cPtr = OsrPINVOKE.CreateCoordinateTransformation(SpatialReference.getCPtr(src), SpatialReference.getCPtr(dst));
     CoordinateTransformation ret = (cPtr == IntPtr.Zero) ? null : new CoordinateTransformation(cPtr, true, ThisOwn_true());
     if (OsrPINVOKE.SWIGPendingException.Pending) throw OsrPINVOKE.SWIGPendingException.Retrieve();
     return ret;
 }
 public CoordinateTransformation(SpatialReference src, SpatialReference dst) : this(OsrPINVOKE.new_CoordinateTransformation(SpatialReference.getCPtr(src), SpatialReference.getCPtr(dst)), true, null) {
   if (OsrPINVOKE.SWIGPendingException.Pending) throw OsrPINVOKE.SWIGPendingException.Retrieve();
 }
Exemple #33
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);
        }
Exemple #34
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Curve> boundary = new List <Curve>();

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

            string IMG_file = string.Empty;

            DA.GetData <string>(1, ref IMG_file);

            RESTful.GdalConfiguration.ConfigureGdal();
            OSGeo.GDAL.Gdal.AllRegister();

            Dataset datasource = Gdal.Open(IMG_file, Access.GA_ReadOnly);

            OSGeo.GDAL.Driver drv = datasource.GetDriver();


            if (datasource == 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;
            }

            ///Get info about image
            string        srcInfo     = string.Empty;
            List <string> infoOptions = new List <string> {
                "-stats"
            };

            srcInfo = Gdal.GDALInfo(datasource, new GDALInfoOptions(infoOptions.ToArray()));


            ///Get the spatial reference of the input raster file and set to WGS84 if not known
            ///Set up transform from source to WGS84
            OSGeo.OSR.SpatialReference sr = new SpatialReference(Osr.SRS_WKT_WGS84);
            if (datasource.GetProjection() == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Coordinate Reference System (CRS) is missing.  CRS set automatically set to WGS84.");
            }

            else
            {
                sr = new SpatialReference(datasource.GetProjection());

                if (sr.Validate() != 0)
                {
                    ///Check if SRS needs to be converted from ESRI format to WKT to avoid error:
                    ///"No translation for Lambert_Conformal_Conic to PROJ.4 format is known."
                    ///https://gis.stackexchange.com/questions/128266/qgis-error-6-no-translation-for-lambert-conformal-conic-to-proj-4-format-is-kn
                    SpatialReference srEsri = sr;
                    srEsri.MorphFromESRI();
                    string projEsri = string.Empty;
                    srEsri.ExportToWkt(out projEsri);

                    ///If no SRS exists, check Ground Control Points SRS
                    SpatialReference srGCP   = new SpatialReference(datasource.GetGCPProjection());
                    string           projGCP = string.Empty;
                    srGCP.ExportToWkt(out projGCP);

                    if (!string.IsNullOrEmpty(projEsri))
                    {
                        datasource.SetProjection(projEsri);
                        sr = srEsri;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) morphed form ESRI format.");
                    }
                    else if (!string.IsNullOrEmpty(projGCP))
                    {
                        datasource.SetProjection(projGCP);
                        sr = srGCP;
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) set from Ground Control Points (GCPs).");
                    }
                    else
                    {
                        AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Spatial Reference System (SRS) is unknown or unsupported.  SRS assumed to be WGS84." +
                                          "Try setting the SRS with the GdalWarp component using -t_srs EPSG:4326 for the option input.");
                        sr.SetWellKnownGeogCS("WGS84");
                    }
                }

                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Data source SRS: EPSG:" + sr.GetAttrValue("AUTHORITY", 1));
                }
            }

            //OSGeo.OSR.SpatialReference sr = new SpatialReference(ds.GetProjection());
            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);

            double[] adfGeoTransform = new double[6];
            double[] invTransform    = new double[6];
            datasource.GetGeoTransform(adfGeoTransform);
            Gdal.InvGeoTransform(adfGeoTransform, invTransform);

            int width  = datasource.RasterXSize;
            int height = datasource.RasterYSize;

            ///Dataset bounding box
            double oX = adfGeoTransform[0] + adfGeoTransform[1] * 0 + adfGeoTransform[2] * 0;
            double oY = adfGeoTransform[3] + adfGeoTransform[4] * 0 + adfGeoTransform[5] * 0;
            double eX = adfGeoTransform[0] + adfGeoTransform[1] * width + adfGeoTransform[2] * height;
            double eY = adfGeoTransform[3] + adfGeoTransform[4] * width + adfGeoTransform[5] * height;

            ///Transform to WGS84
            double[] extMinPT = new double[3] {
                oX, eY, 0
            };
            double[] extMaxPT = new double[3] {
                eX, oY, 0
            };
            coordTransform.TransformPoint(extMinPT);
            coordTransform.TransformPoint(extMaxPT);
            Point3d dsMin = new Point3d(extMinPT[0], extMinPT[1], extMinPT[2]);
            Point3d dsMax = new Point3d(extMaxPT[0], extMaxPT[1], extMaxPT[2]);

            Rectangle3d dsbox = new Rectangle3d(Plane.WorldXY, Heron.Convert.WGSToXYZ(dsMin), Heron.Convert.WGSToXYZ(dsMax));

            double pixelWidth  = dsbox.Width / width;
            double pixelHeight = dsbox.Height / height;

            ///Declare trees
            GH_Structure <GH_Point>   pointcloud = new GH_Structure <GH_Point>();
            GH_Structure <GH_Integer> rCount     = new GH_Structure <GH_Integer>();
            GH_Structure <GH_Integer> cCount     = new GH_Structure <GH_Integer>();
            GH_Structure <GH_Mesh>    tMesh      = new GH_Structure <GH_Mesh>();

            for (int i = 0; i < boundary.Count; i++)
            {
                GH_Path path = new GH_Path(i);

                Curve clippingBoundary = boundary[i];

                if (!clip)
                {
                    clippingBoundary = dsbox.ToNurbsCurve();
                }

                string clippedTopoFile = "/vsimem/topoclipped.tif";

                if (!(dsbox.BoundingBox.Contains(clippingBoundary.GetBoundingBox(true).Min) && (dsbox.BoundingBox.Contains(clippingBoundary.GetBoundingBox(true).Max))) && clip)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "One or more boundaries may be outside the bounds of the topo dataset.");
                }

                ///Offsets to mesh/boundary based on pixel size
                Point3d clipperMinPreAdd  = clippingBoundary.GetBoundingBox(true).Corner(true, false, true);
                Point3d clipperMinPostAdd = new Point3d(clipperMinPreAdd.X, clipperMinPreAdd.Y, clipperMinPreAdd.Z);
                Point3d clipperMin        = Heron.Convert.XYZToWGS(clipperMinPostAdd);

                Point3d clipperMaxPreAdd = clippingBoundary.GetBoundingBox(true).Corner(false, true, true);
                ///add/subtract pixel width if desired to get closer to boundary
                Point3d clipperMaxPostAdd = new Point3d();
                Point3d clipperMax        = new Point3d();
                if (clip)
                {
                    clipperMaxPostAdd = new Point3d(clipperMaxPreAdd.X + pixelWidth, clipperMaxPreAdd.Y - pixelHeight, clipperMaxPreAdd.Z);
                    clipperMax        = Heron.Convert.XYZToWGS(clipperMaxPostAdd);
                }
                else
                {
                    clipperMaxPostAdd = new Point3d(clipperMaxPreAdd.X, clipperMaxPreAdd.Y, clipperMaxPreAdd.Z);
                    clipperMax        = Heron.Convert.XYZToWGS(clipperMaxPostAdd);
                }


                double lonWest  = clipperMin.X;
                double lonEast  = clipperMax.X;
                double latNorth = clipperMin.Y;
                double latSouth = clipperMax.Y;

                var translateOptions = new[]
                {
                    "-of", "GTiff",
                    "-a_nodata", "0",
                    "-projwin_srs", "WGS84",
                    "-projwin", $"{lonWest}", $"{latNorth}", $"{lonEast}", $"{latSouth}"
                };

                using (Dataset clippedDataset = Gdal.wrapper_GDALTranslate(clippedTopoFile, datasource, new GDALTranslateOptions(translateOptions), null, null))
                {
                    Band band = clippedDataset.GetRasterBand(1);
                    width  = clippedDataset.RasterXSize;
                    height = clippedDataset.RasterYSize;
                    clippedDataset.GetGeoTransform(adfGeoTransform);
                    Gdal.InvGeoTransform(adfGeoTransform, invTransform);

                    rCount.Append(new GH_Integer(height), path);
                    cCount.Append(new GH_Integer(width), path);
                    Mesh           mesh  = new Mesh();
                    List <Point3d> verts = new List <Point3d>();
                    //var vertsParallel = new System.Collections.Concurrent.ConcurrentDictionary<double[][], Point3d>(Environment.ProcessorCount, ((Urow - 1) * (Lrow - 1)));

                    double[] bits = new double[width * height];
                    band.ReadRaster(0, 0, width, height, bits, width, height, 0, 0);

                    for (int col = 0; col < width; col++)
                    {
                        for (int row = 0; row < height; row++)
                        {
                            // equivalent to bits[col][row] if bits is 2-dimension array
                            double pixel = bits[col + row * width];
                            if (pixel < -10000)
                            {
                                pixel = 0;
                            }

                            double gcol = adfGeoTransform[0] + adfGeoTransform[1] * col + adfGeoTransform[2] * row;
                            double grow = adfGeoTransform[3] + adfGeoTransform[4] * col + adfGeoTransform[5] * row;

                            ///convert to WGS84
                            double[] wgsPT = new double[3] {
                                gcol, grow, pixel
                            };
                            coordTransform.TransformPoint(wgsPT);
                            Point3d pt = new Point3d(wgsPT[0], wgsPT[1], wgsPT[2]);

                            verts.Add(Heron.Convert.WGSToXYZ(pt));
                        }

                        /*Parallel.For(Urow, Lrow - 1, rowP =>
                         *  {
                         *      // equivalent to bits[col][row] if bits is 2-dimension array
                         *      double pixel = bits[col + rowP * width];
                         *      if (pixel < -10000)
                         *      {
                         *          pixel = 0;
                         *      }
                         *
                         *      double gcol = adfGeoTransform[0] + adfGeoTransform[1] * col + adfGeoTransform[2] * rowP;
                         *      double grow = adfGeoTransform[3] + adfGeoTransform[4] * col + adfGeoTransform[5] * rowP;
                         *
                         *      Point3d pt = new Point3d(gcol, grow, pixel);
                         *      vertsParallel[] = Heron.Convert.ToXYZ(pt);
                         *  });
                         * */
                    }

                    //Create meshes
                    //non Parallel
                    mesh.Vertices.AddVertices(verts);
                    //Parallel
                    //mesh.Vertices.AddVertices(vertsParallel.Values);

                    for (int u = 1; u < cCount[path][0].Value; u++)
                    {
                        for (int v = 1; v < rCount[path][0].Value; v++)
                        {
                            mesh.Faces.AddFace(v - 1 + (u - 1) * (height), v - 1 + u * (height), v - 1 + u * (height) + 1, v - 1 + (u - 1) * (height) + 1);
                            //(k - 1 + (j - 1) * num2, k - 1 + j * num2, k - 1 + j * num2 + 1, k - 1 + (j - 1) * num2 + 1)
                        }
                    }

                    //mesh.Flip(true, true, true);
                    tMesh.Append(new GH_Mesh(mesh), path);

                    band.Dispose();
                }
                Gdal.Unlink("/vsimem/topoclipped.tif");
            }

            datasource.Dispose();

            DA.SetDataTree(0, tMesh);
            DA.SetData(1, dsbox);
            DA.SetData(2, srcInfo);
        }
Exemple #35
0
        public static void Rasterize(string inputFeature, string referRaster, string outRaster, string fieldName = "")
        {
            //Register the raster drivers
            Gdal.AllRegister();
            //Register the vector drivers
            Ogr.RegisterAll();
            //Open referRaster
            Dataset _referRaster = Gdal.Open(referRaster, Access.GA_ReadOnly);

            //Get geoTransform Args
            double[] _geoTransform = new double[6];
            _referRaster.GetGeoTransform(_geoTransform);
            // Define pixel_size and NoData value of new raster
            //int rasterCellSize = cellSize;
            double _xCellSize = _geoTransform[1];
            double _yCellSize = -_geoTransform[5];

            const double noDataValue      = -10000;
            string       outputRasterFile = outRaster;

            //Reading the vector data
            DataSource dataSource = Ogr.Open(inputFeature, 0);
            Layer      layer      = dataSource.GetLayerByIndex(0);
            Envelope   envelope   = new Envelope();

            layer.GetExtent(envelope, 0);
            //Compute the out raster cell resolutions
            int x_res = _referRaster.RasterXSize;
            int y_res = _referRaster.RasterYSize;

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

            //Check if output raster exists & delete (optional)
            if (File.Exists(outputRasterFile))
            {
                File.Delete(outputRasterFile);
            }
            //Create new tiff
            DataType dType = _referRaster.GetRasterBand(1).DataType;

            //OSGeo.GDAL.Driver outputDriver = Gdal.GetDriverByName("GTiff");
            OSGeo.GDAL.Driver outputDriver = Gdal.GetDriverByName("HFA");

            Dataset outputDataset = outputDriver.Create(outputRasterFile, x_res, y_res, 1, dType, null);
            //Extrac srs from input feature
            string inputShapeSrs;

            OSGeo.OSR.SpatialReference spatialRefrence = layer.GetSpatialRef();
            if (spatialRefrence != null)
            {
                spatialRefrence.ExportToWkt(out inputShapeSrs);
                //Assign input feature srs to outpur raster
                outputDataset.SetProjection(inputShapeSrs);
            }
            //Geotransform
            outputDataset.SetGeoTransform(_geoTransform);
            //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 };
            rasterizeOptions = new string[] { };
            //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");
            Gdal.RasterizeLayer(
                myDataset, //NEW inDS
                1,         //BAND
                bandlist,  //int[] bandlist = new int[] { 1 };Band数量
                layer,     // 待转
                IntPtr.Zero,
                IntPtr.Zero,
                1,
                burnValues, //Values to be burn on raster (10.0)
                rasterizeOptions,
                new Gdal.GDALProgressFuncDelegate(ProgressFunc),
                "Raster conversion"
                );
            myDataset.FlushCache();
            myDataset.Dispose();
        }
        public void testProjectionConvert()
        {
            Gdal.AllRegister();
            Gdal.SetConfigOption("GDAL_FILENAME_IS_UTF8", "YES");
            Gdal.SetConfigOption("SHAPE_ENCODING", "");
            Ogr.RegisterAll();
            Gdal.SetConfigOption("GDAL_DATA", Environment.CurrentDirectory + "//data");
            //读取文件
            DataSource ds     = Ogr.Open(fromPath, 0);
            Layer      oLayer = ds.GetLayerByIndex(0);

            // 写入文件

            OSGeo.OGR.Driver oDriver = Ogr.GetDriverByName("ESRI Shapefile");



            OSGeo.OSR.SpatialReference projection = new OSGeo.OSR.SpatialReference("");
            projection.ImportFromEPSG(3395);

            DataSource oDS;

            if (Ogr.Open(toPath, 0) != null)
            {
                oDS = Ogr.Open(toPath, 1);
                oDS.DeleteLayer(0);
            }
            else
            {
                oDS = oDriver.CreateDataSource(toPath, null);
            }



            Layer toLayer = oDS.CreateLayer("POINT", projection, oLayer.GetGeomType(), null);

            Random      ran      = new Random();
            Feature     oFeature = null;
            Geometry    lines    = null;
            FeatureDefn oDefn    = oLayer.GetLayerDefn();

            FieldDefn oFieldID = new FieldDefn("HEIGHT_G", FieldType.OFTReal);

            toLayer.CreateField(oFieldID, 1);

            FieldDefn oFieldName = new FieldDefn("PWLs", FieldType.OFTReal);

            toLayer.CreateField(oFieldName, 1);

            OSGeo.OSR.CoordinateTransformation coordTrans = new OSGeo.OSR.CoordinateTransformation(oLayer.GetSpatialRef(), projection);



            while ((oFeature = oLayer.GetNextFeature()) != null)
            {
                lines = oFeature.GetGeometryRef();
                lines.Transform(coordTrans);

                Feature feature = new Feature(oDefn);
                feature.SetGeometry(lines);
                feature.SetField(0, 4.0);
                feature.SetField(1, ran.Next(40, 120));
                toLayer.CreateFeature(feature);
            }

            oDS.SyncToDisk();
        }
Exemple #37
0
        private static void ReportLayer(Layer layer)
        {
            //layer info
            string   layerName  = layer.GetName();                //Links
            string   layerName2 = layer.GetLayerDefn().GetName(); //Links
            int      fc         = layer.GetFeatureCount(1);       //16
            Envelope ext        = new Envelope();

            layer.GetExtent(ext, 1);
            /* -------------------------------------------------------------------- */
            /*      Reading the spatial reference                                   */
            /* -------------------------------------------------------------------- */
            OSGeo.OSR.SpatialReference sr = layer.GetSpatialRef();
            string srs_wkt;

            if (sr != null)
            {
                sr.ExportToPrettyWkt(out srs_wkt, 1);
            }
            else
            {
                srs_wkt = "(unknown)";
            }

            // feature definition
            FeatureDefn def = layer.GetLayerDefn();
            //string layerName2 = def.GetName();//Links

            /* -------------------------------------------------------------------- */
            /*      Reading the fields                                              */
            /* -------------------------------------------------------------------- */
            int nFieldCount = def.GetFieldCount();//3

            for (int iField = 0; iField < nFieldCount; iField++)
            {
                // field definition
                FieldDefn fdef = def.GetFieldDefn(iField);
                // field info
                string    fieldName     = fdef.GetName();                             //Id Name URL
                string    fieldNameRef  = fdef.GetNameRef();                          // Id Name URL
                FieldType fieldType     = fdef.GetFieldType();                        //OFTInteger OFTString OFTString
                string    fieldTypeName = fdef.GetFieldTypeName(fdef.GetFieldType()); //Integer String String
                int       width         = fdef.GetWidth();                            //6 50 254
                int       precision     = fdef.GetPrecision();                        //0 0 0
            }

            /* -------------------------------------------------------------------- */
            /*      Reading the shapes                                              */
            /* -------------------------------------------------------------------- */
            for (int fid = 0; fid < layer.GetFeatureCount(1); fid++)
            {
                Feature f = layer.GetFeature(fid);
                ReportFeature(f, def);
                f.Dispose();
            }
            //Feature f;
            //while ((f = layer.GetNextFeature()) != null)
            //{
            //   ReportFeature(f, def);
            //   f.Dispose();
            //}
        }
Exemple #38
0
        protected override void SolveInstance(IGH_DataAccess DA)
        {
            List <Curve> boundary = new List <Curve>();

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

            string IMG_file = "";

            DA.GetData <string>("IMG Location", ref IMG_file);

            /*
             * //Does not work with HGT files
             *
             * byte[] imageBuffer;
             *
             * using (FileStream fs = new FileStream(IMG_file, FileMode.Open, FileAccess.Read))
             * {
             *    using (BinaryReader br = new BinaryReader(fs))
             *    {
             *        long numBytes = new FileInfo(IMG_file).Length;
             *        imageBuffer = br.ReadBytes((int)numBytes);
             *        br.Close();
             *        fs.Close();
             *    }
             * }
             */

            RESTful.GdalConfiguration.ConfigureGdal();
            OSGeo.GDAL.Gdal.AllRegister();

            //string memFilename = "/vsimem/inmemfile";
            //Gdal.FileFromMemBuffer(memFilename, imageBuffer);

            Dataset ds = Gdal.Open(IMG_file, Access.GA_ReadOnly);

            OSGeo.GDAL.Driver drv = ds.GetDriver();


            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;
            }


            ///Get the spatial reference of the input raster file and set to WGS84 if not known
            ///Set up transform from source to WGS84
            OSGeo.OSR.SpatialReference sr = new SpatialReference(Osr.SRS_WKT_WGS84);
            if (ds.GetProjection() == null)
            {
                AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Coordinate Reference System (CRS) is missing.  CRS set automatically set to WGS84.");
            }

            else
            {
                sr = new SpatialReference(ds.GetProjection());
                if (sr.Validate() != 0)
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Coordinate Reference System (CRS) is unknown or unsupported.  CRS set automatically set to WGS84.");
                    sr.SetWellKnownGeogCS("WGS84");
                }

                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Remark, "Data source SRS: EPSG:" + sr.GetAttrValue("AUTHORITY", 1));
                }
            }

            //OSGeo.OSR.SpatialReference sr = new SpatialReference(ds.GetProjection());
            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);

            double[] adfGeoTransform = new double[6];
            double[] invTransform    = new double[6];
            ds.GetGeoTransform(adfGeoTransform);
            Gdal.InvGeoTransform(adfGeoTransform, invTransform);
            Band band = ds.GetRasterBand(1);

            int width  = ds.RasterXSize;
            int height = ds.RasterYSize;

            //Dataset bounding box
            double oX = adfGeoTransform[0] + adfGeoTransform[1] * 0 + adfGeoTransform[2] * 0;
            double oY = adfGeoTransform[3] + adfGeoTransform[4] * 0 + adfGeoTransform[5] * 0;
            double eX = adfGeoTransform[0] + adfGeoTransform[1] * width + adfGeoTransform[2] * height;
            double eY = adfGeoTransform[3] + adfGeoTransform[4] * width + adfGeoTransform[5] * height;

            ///Transform to WGS84
            double[] extMinPT = new double[3] {
                oX, eY, 0
            };
            double[] extMaxPT = new double[3] {
                eX, oY, 0
            };
            coordTransform.TransformPoint(extMinPT);
            coordTransform.TransformPoint(extMaxPT);
            Point3d dsMin = new Point3d(extMinPT[0], extMinPT[1], extMinPT[2]);
            Point3d dsMax = new Point3d(extMaxPT[0], extMaxPT[1], extMaxPT[2]);

            //Point3d dsMin = new Point3d(oX, eY, 0);
            //Point3d dsMax = new Point3d(eX, oY, 0);
            Rectangle3d dsbox = new Rectangle3d(Plane.WorldXY, Heron.Convert.WGSToXYZ(dsMin), Heron.Convert.WGSToXYZ(dsMax));

            //Declare trees
            GH_Structure <GH_Point>   pointcloud = new GH_Structure <GH_Point>();
            GH_Structure <GH_Integer> rCount     = new GH_Structure <GH_Integer>();
            GH_Structure <GH_Integer> cCount     = new GH_Structure <GH_Integer>();
            GH_Structure <GH_Mesh>    tMesh      = new GH_Structure <GH_Mesh>();

            for (int i = 0; i < boundary.Count; i++)
            {
                if (dsbox.BoundingBox.Contains(boundary[i].GetBoundingBox(true).Min) && (dsbox.BoundingBox.Contains(boundary[i].GetBoundingBox(true).Max)))
                {
                    Point3d min = Heron.Convert.XYZToWGS(boundary[i].GetBoundingBox(true).Corner(true, false, true));
                    Point3d max = Heron.Convert.XYZToWGS(boundary[i].GetBoundingBox(true).Corner(false, true, true));

                    ///Transform to source SRS
                    double[] minR = new double[3] {
                        min.X, min.Y, min.Z
                    };
                    double[] maxR = new double[3] {
                        max.X, max.Y, max.Z
                    };
                    revTransform.TransformPoint(minR);
                    revTransform.TransformPoint(maxR);

                    GH_Path path = new GH_Path(i);

                    // http://gis.stackexchange.com/questions/46893/how-do-i-get-the-pixel-value-of-a-gdal-raster-under-an-ogr-point-without-numpy

                    double ur, uc, lr, lc;

                    Gdal.ApplyGeoTransform(invTransform, minR[0], minR[1], out uc, out ur);
                    Gdal.ApplyGeoTransform(invTransform, maxR[0], maxR[1], out lc, out lr);
                    //Gdal.ApplyGeoTransform(invTransform, min.X, min.Y, out uc, out ur);
                    //Gdal.ApplyGeoTransform(invTransform, max.X, max.Y, out lc, out lr);

                    int Urow = System.Convert.ToInt32(ur);
                    int Ucol = System.Convert.ToInt32(uc);
                    int Lrow = System.Convert.ToInt32(lr) + 1;
                    int Lcol = System.Convert.ToInt32(lc) + 1;
                    rCount.Append(new GH_Integer(Lrow - Urow), path);
                    cCount.Append(new GH_Integer(Lcol - Ucol), path);
                    Mesh           mesh  = new Mesh();
                    List <Point3d> verts = new List <Point3d>();
                    //var vertsParallel = new System.Collections.Concurrent.ConcurrentDictionary<double[][], Point3d>(Environment.ProcessorCount, ((Urow - 1) * (Lrow - 1)));

                    double[] bits = new double[width * height];
                    band.ReadRaster(0, 0, width, height, bits, width, height, 0, 0);

                    for (int col = Ucol; col < Lcol; col++)
                    {
                        for (int row = Urow; row < Lrow; row++)
                        {
                            // equivalent to bits[col][row] if bits is 2-dimension array
                            double pixel = bits[col + row * width];
                            if (pixel < -10000)
                            {
                                pixel = 0;
                            }

                            double gcol = adfGeoTransform[0] + adfGeoTransform[1] * col + adfGeoTransform[2] * row;
                            double grow = adfGeoTransform[3] + adfGeoTransform[4] * col + adfGeoTransform[5] * row;

                            ///convert to WGS84
                            double[] wgsPT = new double[3] {
                                gcol, grow, pixel
                            };
                            coordTransform.TransformPoint(wgsPT);
                            Point3d pt = new Point3d(wgsPT[0], wgsPT[1], wgsPT[2]);

                            //Point3d pt = new Point3d(gcol, grow, pixel);
                            verts.Add(Heron.Convert.WGSToXYZ(pt));
                        }

                        /*Parallel.For(Urow, Lrow - 1, rowP =>
                         *  {
                         *      // equivalent to bits[col][row] if bits is 2-dimension array
                         *      double pixel = bits[col + rowP * width];
                         *      if (pixel < -10000)
                         *      {
                         *          pixel = 0;
                         *      }
                         *
                         *      double gcol = adfGeoTransform[0] + adfGeoTransform[1] * col + adfGeoTransform[2] * rowP;
                         *      double grow = adfGeoTransform[3] + adfGeoTransform[4] * col + adfGeoTransform[5] * rowP;
                         *
                         *      Point3d pt = new Point3d(gcol, grow, pixel);
                         *      vertsParallel[] = Heron.Convert.ToXYZ(pt);
                         *  });
                         * */
                    }

                    //Create meshes
                    //non Parallel
                    mesh.Vertices.AddVertices(verts);
                    //Parallel
                    //mesh.Vertices.AddVertices(vertsParallel.Values);

                    for (int u = 1; u < cCount[path][0].Value; u++)
                    {
                        for (int v = 1; v < rCount[path][0].Value; v++)
                        {
                            mesh.Faces.AddFace(v - 1 + (u - 1) * (Lrow - Urow), v - 1 + u * (Lrow - Urow), v - 1 + u * (Lrow - Urow) + 1, v - 1 + (u - 1) * (Lrow - Urow) + 1);
                            //(k - 1 + (j - 1) * num2, k - 1 + j * num2, k - 1 + j * num2 + 1, k - 1 + (j - 1) * num2 + 1)
                        }
                    }
                    //mesh.Flip(true, true, true);
                    tMesh.Append(new GH_Mesh(mesh), path);
                }

                else
                {
                    AddRuntimeMessage(GH_RuntimeMessageLevel.Warning, "One or more boundaries may be outside the bounds of the topo dataset.");
                    //return;
                }
            }
            DA.SetDataTree(0, tMesh);
            DA.SetData(1, dsbox);
        }
 public int IsSameVertCS(SpatialReference rhs)
 {
     int ret = OsrPINVOKE.SpatialReference_IsSameVertCS(swigCPtr, SpatialReference.getCPtr(rhs));
     if (OsrPINVOKE.SWIGPendingException.Pending) throw OsrPINVOKE.SWIGPendingException.Retrieve();
     return ret;
 }
Exemple #40
0
        public static void Rasterize(string inputFeature, string outRaster, string fieldName, int cellSize)
        {
            int rasterCellSize = cellSize;

            const double noDataValue = -9999;

            string outputRasterFile = outRaster;

            Ogr.RegisterAll();

            DataSource dataSource = Ogr.Open(inputFeature, 0);
            Layer      layer      = dataSource.GetLayerByIndex(0);
            Envelope   envelope   = new Envelope();

            layer.GetExtent(envelope, 0);

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



            Gdal.AllRegister();

            if (File.Exists(outputRasterFile))
            {
                File.Delete(outputRasterFile);
            }
            //Create new tiff
            OSGeo.GDAL.Driver outputDriver = Gdal.GetDriverByName("GTiff");
            //OSGeo.GDAL.Driver outputDriver = Gdal.GetDriverByName("HFA");
            Dataset outputDataset = outputDriver.Create(outputRasterFile, x_res, y_res, 1, DataType.GDT_Float64, null);
            //Extrac srs from input feature
            string inputShapeSrs;

            OSGeo.OSR.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 };
            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");
            Gdal.RasterizeLayer(myDataset, 1, bandlist, layer, IntPtr.Zero, IntPtr.Zero, 1, burnValues, rasterizeOptions, new Gdal.GDALProgressFuncDelegate(ProgressFunc), "Raster conversion");
        }
 public static HandleRef getCPtr(SpatialReference obj)
 {
     return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr;
 }
Exemple #42
0
        /// <summary>
        /// Creates an OGR data source from a FeatureDataTable
        /// </summary>
        /// <param name="table">The name of the table</param>
        /// <param name="geometryType">The geometry type</param>
        /// <param name="driver">The driver</param>
        /// <param name="connection">The connection string</param>
        /// <param name="driverOptions">The options for the driver</param>
        /// <param name="layerOptions">The options for the layer</param>
        public static void CreateFromFeatureDataTable(FeatureDataTable table,
                                                      OgcGeometryType geometryType, int srid, string driver, string connection, string[] driverOptions = null, string[] layerOptions = null)
        {
            if (table == null)
            {
                throw new ArgumentNullException("table");
            }

            if (table.Rows.Count == 0)
            {
                throw new ArgumentException("The table contains no rows", "table");
            }

            if (geometryType < OgcGeometryType.Point || geometryType > OgcGeometryType.MultiPolygon)
            {
                throw new ArgumentException("Invalid geometry type", "geometryType");
            }

            if (string.IsNullOrWhiteSpace(driver))
            {
                throw new ArgumentException("No driver specified", "driver");
            }

            var dr = OSGeo.OGR.Ogr.GetDriverByName(driver);

            if (dr == null)
            {
                throw new Exception(string.Format("Cannot load driver '{0}'!", driver));
            }

            //if (!dr.TestCapability("ODrCCreateDataSource"))
            //    throw new Exception(string.Format("Driver '{0}' cannot create a data source!", driver));

            // Create the data source
            var ds = dr.CreateDataSource(connection, driverOptions);
            //if (!ds.TestCapability("ODsCCreateLayer"))
            //    throw new Exception(string.Format("Driver '{0}' cannot create a layer!", driver));

            // Create the spatial reference
            var sr = new OSGeo.OSR.SpatialReference(string.Empty);

            sr.ImportFromEPSG(srid);

            // Create the layer
            var lyr = ds.CreateLayer(table.TableName, sr, (OgrGeometryType)geometryType, layerOptions);

            sr.Dispose();

            //lyr.GetSpatialRef();
            foreach (System.Data.DataColumn dc in table.Columns)
            {
                using (var fldDef = GetFieldDefinition(dc))
                    lyr.CreateField(fldDef, 0);
            }

            using (var ld = lyr.GetLayerDefn())
            {
                foreach (FeatureDataRow fdr in table.Rows)
                {
                    if ((int)fdr.Geometry.OgcGeometryType != (int)geometryType)
                    {
                        continue;
                    }

                    using (var feature = new OgrFeature(ld))
                    {
                        feature.SetGeometry(OgrGeometry.CreateFromWkb(fdr.Geometry.AsBinary()));
                        var idx = -1;
                        foreach (System.Data.DataColumn dc in table.Columns)
                        {
                            idx++;
                            var      fd = ld.GetFieldDefn(idx);
                            DateTime dt;
                            switch (fd.GetFieldType())
                            {
                            case OgrFieldType.OFTBinary:
                                //Nothing
                                break;

                            case OgrFieldType.OFTDate:
                                dt = ((DateTime)fdr[dc]).Date;
                                feature.SetField(idx, dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, 0);
                                break;

                            case OgrFieldType.OFTDateTime:
                                dt = (DateTime)fdr[dc];
                                feature.SetField(idx, dt.Year, dt.Month, dt.Day, dt.Hour, dt.Minute, dt.Second, 0);
                                break;

                            case OgrFieldType.OFTTime:
                                var tod = ((DateTime)fdr[dc]).TimeOfDay;
                                feature.SetField(idx, 0, 0, 0, tod.Hours, tod.Minutes, tod.Seconds, 0);
                                break;

                            case OgrFieldType.OFTInteger:
                                feature.SetField(idx, Convert.ToInt32(fdr[dc]));
                                break;

                            case OgrFieldType.OFTIntegerList:
                                var il = GetIntegerList(fdr[dc], dc.DataType);
                                feature.SetFieldIntegerList(idx, il.Length, il);
                                break;

                            case OgrFieldType.OFTReal:
                                feature.SetField(idx, Convert.ToDouble(fdr[dc]));
                                break;

                            case OgrFieldType.OFTRealList:
                                var dl = GetDoubleList(fdr[dc], dc.DataType);
                                feature.SetFieldDoubleList(idx, dl.Length, dl);
                                break;

                            case OgrFieldType.OFTString:
                                feature.SetField(idx, Convert.ToString(fdr[dc]));
                                break;

                            case OgrFieldType.OFTStringList:
                                var sl = (string[])fdr[dc];
                                feature.SetFieldStringList(idx, sl);
                                break;
                            }
                            fd.Dispose();
                        }
                        lyr.CreateFeature(feature);
                        feature.Dispose();
                    }
                    //ld.Dispose();
                }
            }

            lyr.Dispose();
            ds.Dispose();
            dr.Dispose();
        }