Exemplo n.º 1
0
        public static void _Polygong节点转为ShpPoint(Feature aPoly, string outFile)
        {
            OSGeo.OGR.Geometry geom    = aPoly.GetGeometryRef();
            OSGeo.OGR.Geometry subGeom = geom.GetGeometryRef(0);

            Driver     dr            = Ogr.GetDriverByName("ESRI shapefile");
            DataSource outDS         = dr.CreateDataSource(outFile, null);
            Layer      outLayer      = outDS.CreateLayer("toPoint", null, wkbGeometryType.wkbPoint25D, null);
            FieldDefn  pointID       = new FieldDefn("FeatID", FieldType.OFTReal);
            FieldDefn  cutField      = new FieldDefn("CUT", FieldType.OFTReal);
            FieldDefn  straightField = new FieldDefn("STRAIGHT", FieldType.OFTInteger);

            outLayer.CreateField(pointID, 1);
            outLayer.CreateField(cutField, 1);
            outLayer.CreateField(straightField, 1);

            int pointCount = subGeom.GetPointCount();

            for (int i = 0; i < pointCount; i++)
            {
                Feature  pFeat = new Feature(new FeatureDefn(""));
                Geometry pGeom = new Geometry(wkbGeometryType.wkbPoint);
                pGeom.AddPoint_2D(subGeom.GetX(i), subGeom.GetY(i));
                pFeat.SetGeometry(pGeom);
                outLayer.CreateFeature(pFeat);
                pGeom.Dispose();
                pFeat.Dispose();
            }
            outLayer.Dispose();
            outDS.Dispose();
        }
Exemplo n.º 2
0
        public static Mesh OgrPolygonToMesh(OSGeo.OGR.Geometry polygon)
        {
            double       tol   = Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance;
            List <Curve> pList = new List <Curve>();

            OSGeo.OGR.Geometry sub_geom;

            for (int i = 0; i < polygon.GetGeometryCount(); i++)
            {
                sub_geom = polygon.GetGeometryRef(i);
                Curve crv = Convert.OgrLinestringToCurve(sub_geom);
                //possible cause of viewport issue, try not forcing a close.  Other possibility would be trying to convert to (back to) polyline
                //crv.MakeClosed(tol);
                pList.Add(crv);
                sub_geom.Dispose();
            }

            //need to catch if not closed polylines
            Mesh mPatch = new Mesh();

            if (pList[0] != null)
            {
                Polyline pL = null;
                pList[0].TryGetPolyline(out pL);
                pList.RemoveAt(0);
                mPatch = Rhino.Geometry.Mesh.CreatePatch(pL, tol, null, pList, null, null, true, 1);
            }

            return(mPatch);
        }
Exemplo n.º 3
0
        public static List <IGH_GeometricGoo> OgrGeomToGHGoo(OSGeo.OGR.Geometry geom, Transform transform)
        {
            List <IGH_GeometricGoo> gGoo = new List <IGH_GeometricGoo>();

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

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

            return(gGoo);
        }
Exemplo n.º 4
0
        /*************************************  点角式  *****************************************/
        /// <summary>
        /// 清理等后生成新的文件
        ///
        /// </summary>
        public static void claenPoint(string filePath, string savefile, double jiaodu, int cishu)
        {
            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.OGR.Driver dr = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
            //进来的Layer
            OSGeo.OGR.DataSource oriDs    = dr.Open(filePath, 0);
            OSGeo.OGR.Layer      oriLayer = oriDs.GetLayerByIndex(0);
            //出去的Layer
            if (System.IO.File.Exists(savefile))
            {
                savefile.deleteFiles();
            }
            OSGeo.OGR.DataSource targDs    = dr.CreateDataSource(savefile, null);
            OSGeo.OGR.Layer      targLayer = targDs.CreateLayer("targ", null, OSGeo.OGR.wkbGeometryType.wkbPolygon, null);

            int featCount = oriLayer.GetFeatureCount(0);

            for (int i = 0; i < featCount; i++)
            {
                ///进来的Featuer
                OSGeo.OGR.Feature oriFeat = oriLayer.GetFeature(i);

                ///把一个Featuer转为点数组
                OSGeo.OGR.Geometry oriGeom = oriFeat.GetGeometryRef();
                OSGeo.OGR.Geometry subGeom = oriGeom.GetGeometryRef(0);
                int     pointCount         = subGeom.GetPointCount();
                Point[] aFeat = new Point[pointCount];
                for (int c = 0; c < pointCount; c++)
                {
                    aFeat[c].X = subGeom.GetX(c);
                    aFeat[c].Y = subGeom.GetY(c);
                    aFeat[c].Z = subGeom.GetZ(c);
                }

                ///调选点方法,得到一个新的Featuer
                Geometry newGeom = null;
                if (aFeat.Length > cishu * 3)
                {
                    newGeom = JID(aFeat, jiaodu, cishu);
                }
                else
                {
                    oriFeat.Dispose();
                    continue;
                }
                if (newGeom != null)
                {
                    Feature temp = new Feature(new FeatureDefn(""));
                    temp.SetGeometry(newGeom);
                    targLayer.CreateFeature(temp);
                    temp.Dispose();
                }
                oriFeat.Dispose();
                Console.WriteLine("已完成{0}/{1}", i, featCount);
            }
            oriDs.Dispose();
            targDs.Dispose();
        }
Exemplo n.º 5
0
        public static Extrusion OgrPolygonToExtrusion(OSGeo.OGR.Geometry polygon, Transform transform, double height, double min_height, bool underground)
        {
            List <Curve> pList = new List <Curve>();

            OSGeo.OGR.Geometry sub_geom;
            int direction = 1;

            if (underground)
            {
                direction = -1;
            }

            //pList = OgrMultiLinestringToCurves(polygon, transform);

            for (int i = 0; i < polygon.GetGeometryCount(); i++)
            {
                sub_geom = polygon.GetGeometryRef(i);
                Curve crv = Heron.Convert.OgrRingToCurve(sub_geom, transform);
                if (crv.ClosedCurveOrientation(Plane.WorldXY.ZAxis) == CurveOrientation.Clockwise)
                {
                    crv.Reverse();
                }
                pList.Add(crv);
                sub_geom.Dispose();
            }

            pList[0].TryGetPlane(out var profilePlane);
            Transform profileTransform = Transform.PlaneToPlane(profilePlane, Plane.WorldXY);

            Extrusion extrusion = Extrusion.Create(pList[0], (height - min_height) * direction, true);

            if (extrusion == null)
            {
                return(null);
            }

            if (pList.Count > 1)
            {
                pList.RemoveAt(0);
                foreach (Curve innerCurve in pList)
                {
                    Curve crv = innerCurve.DuplicateCurve();
                    crv.Transform(profileTransform);
                    extrusion.AddInnerProfile(crv);
                }
            }

            Vector3d moveDir = new Vector3d(0, 0, min_height);

            extrusion.Translate(moveDir);

            return(extrusion);
        }
Exemplo n.º 6
0
        public static Mesh OgrMultiPolyToMesh(OSGeo.OGR.Geometry multipoly, Transform transform)
        {
            double tol = Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance;

            OSGeo.OGR.Geometry sub_geom;
            List <Mesh>        mList = new List <Mesh>();

            for (int i = 0; i < multipoly.GetGeometryCount(); i++)
            {
                sub_geom = multipoly.GetGeometryRef(i);
                Mesh mP = Heron.Convert.OgrPolygonToMesh(sub_geom, transform);
                mP.UnifyNormals();
                mList.Add(mP);
                sub_geom.Dispose();
            }
            Mesh m = new Mesh();

            m.Append(mList);

            //m.Ngons.AddPlanarNgons(tol);
            m.FaceNormals.ComputeFaceNormals();
            m.Normals.ComputeNormals();
            //m.RebuildNormals();
            m.Compact();
            m.UnifyNormals();


            if (m.DisjointMeshCount > 0)
            {
                Mesh[] mDis = m.SplitDisjointPieces();
                Mesh   mm   = new Mesh();
                foreach (Mesh mPiece in mDis)
                {
                    if (mPiece.SolidOrientation() < 0)
                    {
                        mPiece.Flip(false, false, true);
                    }
                    mm.Append(mPiece);
                }
                //mm.Ngons.AddPlanarNgons(tol);
                mm.FaceNormals.ComputeFaceNormals();
                mm.Normals.ComputeNormals();
                //mm.RebuildNormals();
                mm.Compact();
                mm.UnifyNormals();

                return(mm);
            }
            else
            {
                return(m);
            }
        }
Exemplo n.º 7
0
        /// <summary>
        /// 获取复杂多边形
        /// </summary>
        /// <param name="geometry"></param>
        /// <returns></returns>
        private static Polygon GetPolygon(OSGeo.OGR.Geometry geometry)
        {
            List <SimplePolygon> spolygons = new List <SimplePolygon>();
            int gonCount = geometry.GetGeometryCount();

            for (int i = 0; i < gonCount; ++i)
            {
                //获取第i个子对象
                OSGeo.OGR.Geometry gon = geometry.GetGeometryRef(i);
                spolygons.Add(GetSimplePolygon(gon));
            }
            return(new Polygon(spolygons));
        }
Exemplo n.º 8
0
        public static List <Curve> OgrMultiLinestring(OSGeo.OGR.Geometry multilinestring)
        {
            List <Curve> cList = new List <Curve>();

            OSGeo.OGR.Geometry sub_geom;

            for (int i = 0; i < multilinestring.GetGeometryCount(); i++)
            {
                sub_geom = multilinestring.GetGeometryRef(i);
                cList.Add(Convert.OgrLinestringToCurve(sub_geom));
                sub_geom.Dispose();
            }
            return(cList);
        }
Exemplo n.º 9
0
        public static List <Point3d> OgrMultiPointToPoint3d(OSGeo.OGR.Geometry ogrMultiPoint)
        {
            List <Point3d> ptList = new List <Point3d>();

            OSGeo.OGR.Geometry sub_geom;
            for (int i = 0; i < ogrMultiPoint.GetGeometryCount(); i++)
            {
                sub_geom = ogrMultiPoint.GetGeometryRef(i);
                for (int ptnum = 0; ptnum < sub_geom.GetPointCount(); ptnum++)
                {
                    ptList.Add(Convert.ToXYZ(new Point3d(sub_geom.GetX(0), sub_geom.GetY(0), sub_geom.GetZ(0))));
                }
            }
            return(ptList);
        }
Exemplo n.º 10
0
        public static List <Point3d> OgrMultiPointToPoint3d(OSGeo.OGR.Geometry ogrMultiPoint, Transform transform)
        {
            List <Point3d> ptList = new List <Point3d>();

            OSGeo.OGR.Geometry sub_geom;
            for (int i = 0; i < ogrMultiPoint.GetGeometryCount(); i++)
            {
                sub_geom = ogrMultiPoint.GetGeometryRef(i);
                for (int ptnum = 0; ptnum < sub_geom.GetPointCount(); ptnum++)
                {
                    ptList.Add(Heron.Convert.OgrPointToPoint3d(sub_geom, transform));
                }
            }
            return(ptList);
        }
Exemplo n.º 11
0
        public static List <Extrusion> OgrMultiPolyToExtrusions(OSGeo.OGR.Geometry multipoly, Transform transform, double height, double min_height, bool underground)
        {
            OSGeo.OGR.Geometry sub_geom;
            List <Extrusion>   eList = new List <Extrusion>();

            for (int i = 0; i < multipoly.GetGeometryCount(); i++)
            {
                sub_geom = multipoly.GetGeometryRef(i);
                Extrusion mP = Heron.Convert.OgrPolygonToExtrusion(sub_geom, transform, height, min_height, underground);
                eList.Add(mP);
                sub_geom.Dispose();
            }

            return(eList);
        }
Exemplo n.º 12
0
        public static Mesh OgrPolygonToMesh(OSGeo.OGR.Geometry polygon, Transform transform)
        {
            double       tol   = Rhino.RhinoDoc.ActiveDoc.ModelAbsoluteTolerance;
            List <Curve> pList = new List <Curve>();

            OSGeo.OGR.Geometry sub_geom;

            for (int i = 0; i < polygon.GetGeometryCount(); i++)
            {
                sub_geom = polygon.GetGeometryRef(i);
                Curve crv = Heron.Convert.OgrRingToCurve(sub_geom, transform);
                //possible cause of viewport issue, try not forcing a close.  Other possibility would be trying to convert to (back to) polyline
                //crv.MakeClosed(tol);

                if (!crv.IsClosed && sub_geom.GetPointCount() > 2)
                {
                    Curve   closingLine = new Line(crv.PointAtEnd, crv.PointAtStart).ToNurbsCurve();
                    Curve[] result      = Curve.JoinCurves(new Curve[] { crv, closingLine });
                    crv = result[0];
                }

                pList.Add(crv);
                sub_geom.Dispose();
            }

            //need to catch if not closed polylines
            Mesh mPatch = new Mesh();

            if (pList[0] != null && pList[0].IsClosed)
            {
                Polyline pL = null;
                pList[0].TryGetPolyline(out pL);
                pList.RemoveAt(0);
                mPatch = Rhino.Geometry.Mesh.CreatePatch(pL, tol, null, pList, null, null, true, 1);

                ///Adds ngon capability
                ///https://discourse.mcneel.com/t/create-ngon-mesh-rhinocommon-c/51796/12
                mPatch.Ngons.AddPlanarNgons(tol);
                mPatch.FaceNormals.ComputeFaceNormals();
                mPatch.Normals.ComputeNormals();
                mPatch.Compact();
                mPatch.UnifyNormals();
            }

            return(mPatch);
        }
Exemplo n.º 13
0
        /// <summary>
        /// 清理原文件
        /// </summary>
        /// <param name="filePath"></param>
        public static void claenPoint(string filePath, double jiaodu, int cishu)
        {
            OSGeo.OGR.Ogr.RegisterAll();
            OSGeo.OGR.Driver     dr       = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
            OSGeo.OGR.DataSource oriDs    = dr.Open(filePath, 1);
            OSGeo.OGR.Layer      oriLayer = oriDs.GetLayerByIndex(0);

            int featCount = oriLayer.GetFeatureCount(0);

            for (int i = 0; i < featCount; i++)
            {
                OSGeo.OGR.Feature  oriFeat = oriLayer.GetFeature(i);
                OSGeo.OGR.Geometry oriGeom = oriFeat.GetGeometryRef();
                OSGeo.OGR.Geometry subGeom = oriGeom.GetGeometryRef(0);

                int pointCount = subGeom.GetPointCount();

                Point[] aFeat = new Point[pointCount];

                for (int c = 0; c < pointCount; c++)
                {
                    aFeat[c].X = subGeom.GetX(c);
                    aFeat[c].Y = subGeom.GetY(c);
                    aFeat[c].Z = subGeom.GetZ(c);
                }

                OSGeo.OGR.Geometry newGeom = null;
                if (aFeat.Length > cishu * 3)
                {
                    newGeom = JID(aFeat, jiaodu, cishu);
                }
                else
                {
                    oriFeat.Dispose();
                    continue;
                }
                if (newGeom != null)
                {
                    oriFeat.SetGeometry(newGeom);
                    oriLayer.SetFeature(oriFeat);
                }
                Console.WriteLine("cleanPoint已完成{0}/{1}", i, featCount);
                oriFeat.Dispose();
            }
            oriDs.Dispose();
        }
Exemplo n.º 14
0
        /// <summary>
        /// 获取复杂线
        /// </summary>
        /// <param name="geometry"></param>
        /// <returns></returns>
        private static Polyline GetPolyline(OSGeo.OGR.Geometry geometry)
        {
            List <SimplePolyline> lines = new List <SimplePolyline>();
            int lineCount = geometry.GetGeometryCount();    //子图形对象数目

            for (int i = 0; i < lineCount; ++i)
            {
                List <PointD> line = new List <PointD>();
                //获取第i个子对象
                OSGeo.OGR.Geometry sline = geometry.GetGeometryRef(i);
                int pointcount2          = sline.GetPointCount();
                for (int j = 0; j < pointcount2; ++j)
                {
                    line.Add(new PointD(sline.GetX(j), sline.GetY(j)));
                }
                lines.Add(new SimplePolyline(line));
            }
            return(new Polyline(lines));
        }
Exemplo n.º 15
0
        /// <summary>
        /// 获取简单多边形
        /// </summary>
        /// <param name="geo"></param>
        /// <returns></returns>
        private static SimplePolygon GetSimplePolygon(OSGeo.OGR.Geometry geometry)
        {
            List <SimplePolyline> rings = new List <SimplePolyline>();
            int ringCount = geometry.GetGeometryCount();//子图形对象数目

            for (int i = 0; i < ringCount; ++i)
            {
                List <PointD> pointlist = new List <PointD>();
                //获取第i个子对象
                OSGeo.OGR.Geometry ring = geometry.GetGeometryRef(i);
                int pointcount2         = ring.GetPointCount();
                for (int k = 0; k < pointcount2; k++)
                {
                    pointlist.Add(new PointD(ring.GetX(k), ring.GetY(k)));
                }
                rings.Add(new SimplePolyline(pointlist));
            }
            return(new SimplePolygon(rings));
        }
Exemplo n.º 16
0
 public static void GetPointCount(this OSGeo.OGR.Geometry geometry, ref int count)
 {
     if (geometry != null)
     {
         int geoCount = geometry.GetGeometryCount();
         if (geoCount > 0)
         {
             for (int i = 0; i < geoCount; i++)
             {
                 using (var childGeo = geometry.GetGeometryRef(i))
                 {
                     childGeo.GetPointCount(ref count);
                 }
             }
         }
         else
         {
             count += geometry.GetPointCount();
         }
     }
 }
Exemplo n.º 17
0
        public static Mesh OgrMultiPolyToMesh(OSGeo.OGR.Geometry multipoly, Transform transform)
        {
            OSGeo.OGR.Geometry sub_geom;
            List <Mesh>        mList = new List <Mesh>();

            for (int i = 0; i < multipoly.GetGeometryCount(); i++)
            {
                sub_geom = multipoly.GetGeometryRef(i);
                Mesh mP = Heron.Convert.OgrPolygonToMesh(sub_geom, transform);
                mP.UnifyNormals();
                mList.Add(mP);
                sub_geom.Dispose();
            }
            Mesh m = new Mesh();

            m.Append(mList);
            m.RebuildNormals();
            m.UnifyNormals();

            if (m.DisjointMeshCount > 0)
            {
                Mesh[] mDis = m.SplitDisjointPieces();
                Mesh   mm   = new Mesh();
                foreach (Mesh mPiece in mDis)
                {
                    if (mPiece.SolidOrientation() < 0)
                    {
                        mPiece.Flip(false, false, true);
                    }
                    mm.Append(mPiece);
                }
                mm.RebuildNormals();
                mm.UnifyNormals();
                return(mm);
            }
            else
            {
                return(m);
            }
        }
Exemplo n.º 18
0
        public static List <int> _平角点ID集(Feature aFeatuer, double userSet, int seleTime)
        {
            OSGeo.OGR.Geometry oriGeom = aFeatuer.GetGeometryRef();
            OSGeo.OGR.Geometry subGeom = oriGeom.GetGeometryRef(0);
            int pointCount             = subGeom.GetPointCount();

            Point[] pointList = new Point[pointCount];
            for (int c = 0; c < pointCount; c++)
            {
                pointList[c].X = subGeom.GetX(c);
                pointList[c].Y = subGeom.GetY(c);
                pointList[c].Z = subGeom.GetZ(c);
            }
            if (pointList.Length < seleTime * 3)
            {
                MessageBox.Show("这个图形点数小于重复次数~试试降低重复次数~或删除");
                return(null);
            }
            List <int> ids = new List <int>();

            for (int i = 0; i < pointList.Length; i++)
            {
                int    frontId, thisId, backId;
                bool[] yon = new bool[seleTime];
                for (int t = 1; t <= seleTime; t++)
                {
                    frontId = i < t ? pointList.Length - 1 + i - t : i - t;
                    thisId  = i;
                    backId  = i > pointList.Length - 1 - t ? i - (pointList.Length - 1) + t : i + t;
                    double jiaodu = cosCalculator(pointList[frontId], pointList[thisId], pointList[backId]);
                    yon[t - 1] = jiaodu > userSet;
                }
                if (yon.Contains(true))
                {
                    ids.Add(i);
                }
            }
            return(ids);
        }
Exemplo n.º 19
0
        static void WriteComponentGeometryFragment(JsonTextWriter writer, Geometry geom, string name, DatedElectionResult[] results, DatedTPPResult[] tppResults, int? no = null)
        {
            if (results.Length == 0)
                return;

            int number = no.HasValue ? no.Value : 0;
            double area = geom.Area();

            //To keep the CZML payload to only the main areas (and not islands), don't write CZML packets for
            //island parts
            if (area < MIN_AREA)
                return;

            //Debug.WriteLine($"{name}: {number} - {area}");

            //if (!_areas.ContainsKey(name))
            //    _areas[name] = area;
            //else
            //    _areas[name] = Math.Max(_areas[name], area);

            // {
            writer.WriteStartObject();
            {
                var ring = geom.GetGeometryRef(0);
                var ptCount = ring.GetPointCount();

                // "id": "Electorate/<electorate>/<number>"
                writer.WritePropertyName("id");
                writer.WriteValue($"Electorate/{name}/{number}");
                // "name": "<electorate>"
                writer.WritePropertyName("name");
                writer.WriteValue("Federal Electorate");
                // "description": "<electorate>"
                writer.WritePropertyName("description");
                writer.WriteValue(name);
                // "parent": "Electorate/<electorate>"
                writer.WritePropertyName("parent");
                writer.WriteValue($"Electorate/{name}");
                
                // "polygon": {
                writer.WritePropertyName("polygon");
                writer.WriteStartObject();
                {
                    // "outline" {
                    writer.WritePropertyName("outline");
                    writer.WriteStartObject();
                    {
                        writer.WritePropertyName("boolean");
                        writer.WriteValue(true);
                    }
                    writer.WriteEndObject(); // }

                    // "outlineColor" {
                    writer.WritePropertyName("outlineColor");
                    writer.WriteStartObject();
                    {
                        // "rgba": [
                        writer.WritePropertyName("rgba");
                        writer.WriteStartArray();
                        {
                            //Black
                            writer.WriteValue(0);
                            writer.WriteValue(0);
                            writer.WriteValue(0);
                            writer.WriteValue(255);
                        }
                        writer.WriteEndArray(); // ]
                    }
                    writer.WriteEndObject(); // }

                    // "material": {
                    writer.WritePropertyName("material");
                    writer.WriteStartObject();
                    {
                        // "solidColor": {
                        writer.WritePropertyName("solidColor");
                        writer.WriteStartObject();
                        {
                            // "color": {
                            writer.WritePropertyName("color");
                            writer.WriteStartObject();
                            {
                                // "epoch": <start>
                                writer.WritePropertyName("epoch");
                                writer.WriteValue(_sceneStart);

                                // "rgba": [
                                writer.WritePropertyName("rgba");
                                writer.WriteStartArray();
                                {
                                    //HACK: This example doesn't take into account that electorate redistribution occurs
                                    //Meaning that our 2015 snapshot of Australian Federal Electorates may contain electorates
                                    //that either have changed or did not exist in earlier Federal Elections. Since the AEC does
                                    //not publicly provide such data, we'll denote such electorates as unknown (White)
                                    //
                                    //So peek at the first result, if it's dated on our first Federal Election we know the
                                    //electorate existed back then
                                    bool bDidNotExistIn2004 = !(results[0].ElectionDate.Year == _dtStart.Year &&
                                        results[0].ElectionDate.Month == _dtStart.Month &&
                                        results[0].ElectionDate.Day == _dtStart.Day);

                                    if (bDidNotExistIn2004)
                                    {
                                        //0 seconds since epoch
                                        writer.WriteValue(0);
                                        //White
                                        writer.WriteValue(255);
                                        writer.WriteValue(255);
                                        writer.WriteValue(255);
                                        writer.WriteValue(COLOR_ALPHA);
                                    }
                                    else
                                    {
                                        //0 seconds since epoch
                                        writer.WriteValue(0);

                                        int[] color = GetPartyColor(results[0].PartyNm);
                                        foreach (var c in color)
                                        {
                                            writer.WriteValue(c);
                                        }
                                    }

                                    foreach (var result in results.Skip(1))
                                    {
                                        int dt = (int)result.ElectionDate.Subtract(_dtStart).TotalSeconds;
                                        writer.WriteValue(dt);
                                        int[] color = GetPartyColor(result.PartyNm);
                                        foreach (var c in color)
                                        {
                                            writer.WriteValue(c);
                                        }
                                    }
                                }
                                writer.WriteEndArray(); // ]
                            }
                            writer.WriteEndObject(); // }
                        }
                        writer.WriteEndObject(); // }
                    }
                    writer.WriteEndObject(); // }

                    // "extrudedHeight": {
                    /*
                    writer.WritePropertyName("extrudedHeight");
                    writer.WriteStartObject();
                    {
                        // "epoch": <start>
                        writer.WritePropertyName("epoch");
                        writer.WriteValue(_sceneStart);

                        // "number": [
                        writer.WritePropertyName("number");
                        writer.WriteStartArray();
                        {
                            //HACK: This example doesn't take into account that electorate redistribution occurs
                            //Meaning that our 2015 snapshot of Australian Federal Electorates may contain electorates
                            //that either have changed or did not exist in earlier Federal Elections. Since the AEC does
                            //not publicly provide such data, we'll denote such electorates as unknown (White)
                            //
                            //So peek at the first result, if it's dated on our first Federal Election we know the
                            //electorate existed back then
                            bool bDidNotExistIn2004 = !(tppResults[0].ElectionDate.Year == _dtStart.Year &&
                                tppResults[0].ElectionDate.Month == _dtStart.Month &&
                                tppResults[0].ElectionDate.Day == _dtStart.Day);

                            if (bDidNotExistIn2004)
                            {
                                //0 seconds since epoch
                                writer.WriteValue(0);
                                //0 height
                                writer.WriteValue(0);
                            }
                            else
                            {
                                //0 seconds since epoch
                                writer.WriteValue(0);
                                //The winning party's percentage
                                writer.WriteValue(Math.Max(tppResults[0].LaborPc, tppResults[0].CoalitionPc) * EXTRUSION_MULTIPLIER);
                            }

                            foreach (var tppResult in tppResults.Skip(1))
                            {
                                int dt = (int)tppResult.ElectionDate.Subtract(_dtStart).TotalSeconds;
                                writer.WriteValue(dt);
                                //The winning party's percentage
                                writer.WriteValue(Math.Max(tppResults[0].LaborPc, tppResults[0].CoalitionPc) * EXTRUSION_MULTIPLIER);
                            }
                        }
                        writer.WriteEndArray(); // ]
                    }
                    writer.WriteEndObject(); // }
                    */
                    // "positions": {
                    writer.WritePropertyName("positions");
                    writer.WriteStartObject();
                    {
                        // "cartographicDegrees": [
                        writer.WritePropertyName("cartographicDegrees");
                        writer.WriteStartArray();
                        {
                            double[] coords = new double[3];
                            foreach (int idx in Enumerable.Range(0, ptCount - 1))
                            {
                                ring.GetPoint(idx, coords);
                                foreach (double coord in coords)
                                {
                                    writer.WriteValue(coord);
                                }
                            }
                        }
                        writer.WriteEndArray(); // ]
                    }
                    writer.WriteEndObject(); // }
                }
                writer.WriteEndObject(); // }
            }
            writer.WriteEndObject(); // }
        }
Exemplo n.º 20
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);
        }
Exemplo n.º 21
0
        public static bool CovertRegion2Line(string path, string savePath)
        {
            try
            {
                OSGeo.OGR.Ogr.RegisterAll();
                OSGeo.OGR.Driver dr = OSGeo.OGR.Ogr.GetDriverByName("ESRI shapefile");
                if (dr == null)
                {
                    Console.WriteLine("启动驱动失败!\n");
                }

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

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

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

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

                OSGeo.OGR.DataSource ds    = dr.Open(path, 0);
                int             layerCount = ds.GetLayerCount();
                OSGeo.OGR.Layer layer      = ds.GetLayerByIndex(0);
                DataTable       dataTable  = new DataTable();
                FeatureDefn     fdf        = layer.GetLayerDefn();
                int             fieldCount = fdf.GetFieldCount();
                for (int i = 0; i < fieldCount; i++)
                {
                    dataTable.Columns.Add(fdf.GetFieldDefn(i).GetName(), Type.GetType("System.String"));
                }
                if (fdf.GetGeomType() == OSGeo.OGR.wkbGeometryType.wkbPoint)
                {
                    if (!dataTable.Columns.Contains("X"))
                    {
                        dataTable.Columns.Add("X", Type.GetType("System.String"));
                    }
                    if (!dataTable.Columns.Contains("Y"))
                    {
                        dataTable.Columns.Add("Y", Type.GetType("System.String"));
                    }
                }
                else if (fdf.GetGeomType() == OSGeo.OGR.wkbGeometryType.wkbPolygon || fdf.GetGeomType() == OSGeo.OGR.wkbGeometryType.wkbLineString)
                {
                    if (!dataTable.Columns.Contains("PATH"))
                    {
                        dataTable.Columns.Add("PATH", Type.GetType("System.String"));
                    }
                }
                OSGeo.OGR.Feature feat;
                while ((feat = layer.GetNextFeature()) != null)
                {
                    DataRow            row      = dataTable.NewRow();
                    OSGeo.OGR.Geometry geometry = feat.GetGeometryRef();
                    for (int i = 0; i < fieldCount; i++)
                    {
                        string value = feat.GetFieldAsString(i);
                        row[i] = value.Replace(",", "");
                    }
                    OSGeo.OGR.wkbGeometryType goetype = geometry.GetGeometryType();
                    if (goetype == OSGeo.OGR.wkbGeometryType.wkbPoint)
                    {
                        double x = geometry.GetX(0);
                        double y = geometry.GetY(0);
                        row["X"] = x.ToString();
                        row["Y"] = y.ToString();
                    }
                    else if (goetype == OSGeo.OGR.wkbGeometryType.wkbLineString)
                    {
                        string points = "";
                        for (int i = 0; i < geometry.GetPointCount(); i++)
                        {
                            double x = geometry.GetX(i);
                            double y = geometry.GetY(i);
                            points += x.ToString() + "|" + y.ToString() + ";";
                        }
                        if (points != "")
                        {
                            points.Substring(0, points.Length - 1);
                        }
                        row["PATH"] = points;
                    }
                    else if (goetype == OSGeo.OGR.wkbGeometryType.wkbPolygon)
                    {
                        int    count  = geometry.GetGeometryCount();
                        string points = "";
                        for (int j = 0; j < count; j++)
                        {
                            Geometry geo = geometry.GetGeometryRef(j);
                            for (int i = 0; i < geo.GetPointCount(); i++)
                            {
                                double x = geo.GetX(i);
                                double y = geo.GetY(i);
                                points += x.ToString() + "|" + y.ToString() + ";";
                            }
                            if (points != "")
                            {
                                points.Substring(0, points.Length - 1);
                            }
                            points += "|";
                        }
                        if (points != "")
                        {
                            points.Substring(0, points.Length - 1);
                        }
                        row["PATH"] = points;
                    }
                }
                layer.Dispose();
                ds.Dispose();
                dr.Dispose();
                return(dataTable);
            }
            catch
            {
                return(null);
            }
        }
Exemplo n.º 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>("Vector Data Location", ref shpFileLoc);

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

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

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

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

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

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

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


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

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

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

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


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


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

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

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


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


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


                ///Loop through input boundaries
                for (int i = 0; i < boundary.Count; i++)
                {
                    OSGeo.OGR.FeatureDefn def = layer.GetLayerDefn();

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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



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

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

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

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

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

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

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

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

                                    sub_geom.Dispose();

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

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

            ds.Dispose();

            DA.SetDataTree(0, layname);
            DA.SetDataTree(1, fcs);
            DA.SetDataTree(2, recs);
            DA.SetDataTree(3, sRefs);
            DA.SetDataTree(4, fnames);
            DA.SetDataTree(5, fset);
            DA.SetDataTree(6, gset);
        }
Exemplo n.º 24
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);
        }
Exemplo n.º 25
0
        public static List <IGH_GeometricGoo> OgrGeomToGHGoo(OSGeo.OGR.Geometry geom, Transform transform)
        {
            List <IGH_GeometricGoo> gGoo = new List <IGH_GeometricGoo>();

            OSGeo.OGR.Geometry sub_geom;

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

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

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

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

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

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

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

            default:

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

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


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

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

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

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

            return(gGoo);
        }