示例#1
0
        private void BuildRing(HalfEdge eStartRing)
        {
            CoordinateList line = new CoordinateList();
            HalfEdge       e    = eStartRing;

            Coordinate orig = e.Orig;

            line.Add(orig.Clone(), false);
            // scan along the path until a node is found (if one exists)
            while (e.Sym.Degree() == 2)
            {
                HalfEdge eNext = e.Next;
                // check if edges form a ring - if so, we're done
                if (eNext == eStartRing)
                {
                    break;
                }

                // add point to line, and move to next edge
                orig = eNext.Orig;
                line.Add(orig.Clone(), false);
                e = eNext;
            }
            // add final node
            Coordinate dest = e.Dest;

            line.Add(dest.Clone(), false);

            // store the scanned line
            AddLine(line);
        }
        private void AddEdgeCoordinates(SegmentNode ei0, SegmentNode ei1,
                                        CoordinateList coordList)
        {
            int npts = ei1.SegmentIndex - ei0.SegmentIndex + 2;

            var lastSegStartPt = _edge.GetCoordinate(ei1.SegmentIndex);
            // if the last intersection point is not equal to the its segment start pt,
            // add it to the points list as well.
            // (This check is needed because the distance metric is not totally reliable!)
            // The check for point equality is 2D only - Z values are ignored
            bool useIntPt1 = ei1.IsInterior || !ei1.Coord.Equals2D(lastSegStartPt);

            if (!useIntPt1)
            {
                npts--;
            }

            int ipt = 0;

            coordList.Add(ei0.Coord.Copy(), false);
            for (int i = ei0.SegmentIndex + 1; i <= ei1.SegmentIndex; i++)
            {
                coordList.Add(_edge.GetCoordinate(i));
            }
            if (useIntPt1)
            {
                coordList.Add(ei1.Coord.Copy());
            }
        }
示例#3
0
 /// <summary>
 /// Densifies a coordinate sequence.
 /// </summary>
 /// <param name="pts">The coordinate sequence to densify</param>
 /// <param name="distanceTolerance">The distance tolerance (<see cref="DistanceTolerance"/>)</param>
 /// <param name="precModel">The precision model to apply on the new coordinates</param>
 /// <returns>The densified coordinate sequence</returns>
 private static Coordinate[] DensifyPoints(Coordinate[] pts,
                                            double distanceTolerance, IPrecisionModel precModel)
 {
     var seg = new LineSegment();
     var coordList = new CoordinateList();
     for (int i = 0; i < pts.Length - 1; i++)
     {
         seg.P0 = pts[i];
         seg.P1 = pts[i + 1];
         coordList.Add(seg.P0, false);
         double len = seg.Length;
         int densifiedSegCount = (int) (len/distanceTolerance) + 1;
         if (densifiedSegCount > 1)
         {
             double densifiedSegLen = len/densifiedSegCount;
             for (int j = 1; j < densifiedSegCount; j++)
             {
                 double segFract = (j*densifiedSegLen)/len;
                 var p = seg.PointAlong(segFract);
                 precModel.MakePrecise(p);
                 coordList.Add(p, false);
             }
         }
     }
     coordList.Add(pts[pts.Length - 1], false);
     return coordList.ToCoordinateArray();
 }
示例#4
0
        CoordinateList ReadCoordination(Polyline polyline)
        {
            var coordinateList = new CoordinateList();
            int num            = polyline.NumberOfVertices - 1;

            for (int i = 0; i <= num; i++)
            {
                SegmentType segmentType = polyline.GetSegmentType(i);
                if (segmentType == SegmentType.Arc)
                {
                    try
                    {
                        coordinateList.Add(this.GetTessellatedCurveCoordinates(polyline.GetArcSegmentAt(i)), this.AllowRepeatedCoordinates);
                    }
                    catch (Exception ex)
                    {
                        coordinateList.Add(this.ReadCoordinate(polyline.GetPoint3dAt(i)), this.AllowRepeatedCoordinates);
                    }
                }
                else
                {
                    coordinateList.Add(this.ReadCoordinate(polyline.GetPoint3dAt(i)), this.AllowRepeatedCoordinates);
                }
            }
            if (polyline.Closed)
            {
                coordinateList.Add(coordinateList[0]);
            }

            return(coordinateList);
        }
示例#5
0
        public ILineString ReadLineString(Transaction tr, Polyline3d polyline3D)
        {
            var coordinateList = new CoordinateList();

            if (polyline3D.PolyType == Poly3dType.SimplePoly) // 0??
            {
                foreach (var v in polyline3D)
                {
                    PolylineVertex3d vertex = null;
                    if (v is ObjectId)
                    {
                        vertex = tr.GetObject((ObjectId)v, OpenMode.ForRead) as PolylineVertex3d;
                    }
                    else if (v is PolylineVertex3d)
                    {
                        vertex = (PolylineVertex3d)v;
                    }

                    if (vertex != null)
                    {
                        coordinateList.Add(this.ReadCoordinate(vertex.Position), this.AllowRepeatedCoordinates);
                    }
                }
            }
            else
            {
                var dBObjectCollection = new DBObjectCollection();
                polyline3D.Explode(dBObjectCollection);
                try
                {
                    foreach (var dBObject in dBObjectCollection)
                    {
                        var line = (Line)dBObject;
                        coordinateList.Add(this.ReadCoordinate(line.StartPoint), false);
                        coordinateList.Add(this.ReadCoordinate(line.EndPoint), false);
                    }
                }
                finally
                {
                    foreach (var dBObject in dBObjectCollection)
                    {
                        if (dBObject is IDisposable)
                        {
                            (dBObject as IDisposable).Dispose();
                        }
                    }
                }
                dBObjectCollection.Dispose();
            }

            if (polyline3D.Closed)
            {
                coordinateList.Add(coordinateList[0]);
            }
            if (coordinateList.Count > 1)
            {
                return(this.GeometryFactory.CreateLineString(coordinateList.ToCoordinateArray()));
            }
            return(LineString.Empty);
        }
示例#6
0
        /// <summary>
        /// Densifies a coordinate sequence.
        /// </summary>
        /// <param name="pts">The coordinate sequence to densify</param>
        /// <param name="distanceTolerance">The distance tolerance (<see cref="DistanceTolerance"/>)</param>
        /// <param name="precModel">The precision model to apply on the new coordinates</param>
        /// <returns>The densified coordinate sequence</returns>
        private static Coordinate[] DensifyPoints(Coordinate[] pts,
                                                  double distanceTolerance, IPrecisionModel precModel)
        {
            var seg       = new LineSegment();
            var coordList = new CoordinateList();

            for (int i = 0; i < pts.Length - 1; i++)
            {
                seg.P0 = pts[i];
                seg.P1 = pts[i + 1];
                coordList.Add(seg.P0, false);
                double len = seg.Length;
                int    densifiedSegCount = (int)(len / distanceTolerance) + 1;
                if (densifiedSegCount > 1)
                {
                    double densifiedSegLen = len / densifiedSegCount;
                    for (int j = 1; j < densifiedSegCount; j++)
                    {
                        double segFract = (j * densifiedSegLen) / len;
                        var    p        = seg.PointAlong(segFract);
                        precModel.MakePrecise(p);
                        coordList.Add(p, false);
                    }
                }
            }
            coordList.Add(pts[pts.Length - 1], false);
            return(coordList.ToCoordinateArray());
        }
        private static IGeometry CreateJ(IGeometry g)
        {
            var gf = FunctionsUtil.GetFactoryOrDefault(g);

            var jTop = new Coordinate[]
                           {
                               new Coordinate(0, HEIGHT),
                               new Coordinate(J_WIDTH, HEIGHT),
                               new Coordinate(J_WIDTH, J_RADIUS)
                           };
            var jBottom = new Coordinate[]
                              {
                                  new Coordinate(J_WIDTH - J_RADIUS, 0),
                                  new Coordinate(0, 0)
                              };

            var gsf = new GeometricShapeFactory(gf);
            gsf.Base = new Coordinate(J_WIDTH - 2 * J_RADIUS, 0);
            gsf.Size = 2 * J_RADIUS;
            gsf.NumPoints = 10;
            var jArc = gsf.CreateArc(1.5 * Math.PI, 0.5 * Math.PI);

            var coordList = new CoordinateList();
            coordList.Add(jTop, false);
            coordList.Add(((IGeometry)jArc).Reverse().Coordinates, false, 1, jArc.NumPoints - 1);
            coordList.Add(jBottom, false);

            return gf.CreateLineString(coordList.ToCoordinateArray());
        }
示例#8
0
        private static IGeometry CreateJ(IGeometry g)
        {
            var gf = FunctionsUtil.GetFactoryOrDefault(g);

            var jTop = new Coordinate[]
            {
                new Coordinate(0, HEIGHT),
                new Coordinate(J_WIDTH, HEIGHT),
                new Coordinate(J_WIDTH, J_RADIUS)
            };
            var jBottom = new Coordinate[]
            {
                new Coordinate(J_WIDTH - J_RADIUS, 0),
                new Coordinate(0, 0)
            };

            var gsf = new GeometricShapeFactory(gf);

            gsf.Base      = new Coordinate(J_WIDTH - 2 * J_RADIUS, 0);
            gsf.Size      = 2 * J_RADIUS;
            gsf.NumPoints = 10;
            var jArc = gsf.CreateArc(1.5 * Math.PI, 0.5 * Math.PI);

            var coordList = new CoordinateList();

            coordList.Add(jTop, false);
            coordList.Add(((IGeometry)jArc).Reverse().Coordinates, false, 1, jArc.NumPoints - 1);
            coordList.Add(jBottom, false);

            return(gf.CreateLineString(coordList.ToCoordinateArray()));
        }
        /// <summary>
        /// Assumes input is valid
        /// (e.g. <paramref name="start" /> minor or equals to <paramref name="end" />).
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        private ILineString ComputeLine(LinearLocation start, LinearLocation end)
        {
            ICoordinate[]  coordinates    = line.Coordinates;
            CoordinateList newCoordinates = new CoordinateList();

            int startSegmentIndex = start.SegmentIndex;

            if (start.SegmentFraction > 0.0)
            {
                startSegmentIndex += 1;
            }
            int lastSegmentIndex = end.SegmentIndex;

            if (end.SegmentFraction == 1.0)
            {
                lastSegmentIndex += 1;
            }
            if (lastSegmentIndex >= coordinates.Length)
            {
                lastSegmentIndex = coordinates.Length - 1;
            }
            // not needed - LinearLocation values should always be correct
            // Assert.IsTrue(end.SegmentFraction <= 1.0, "invalid segment fraction value");

            if (!start.IsVertex)
            {
                newCoordinates.Add(start.GetCoordinate(line));
            }
            for (int i = startSegmentIndex; i <= lastSegmentIndex; i++)
            {
                newCoordinates.Add(coordinates[i]);
            }
            if (!end.IsVertex)
            {
                newCoordinates.Add(end.GetCoordinate(line));
            }

            // ensure there is at least one coordinate in the result
            if (newCoordinates.Count <= 0)
            {
                newCoordinates.Add(start.GetCoordinate(line));
            }

            Coordinate[] newCoordinateArray = newCoordinates.ToCoordinateArray();

            /*
             * Ensure there is enough coordinates to build a valid line.
             * Make a 2-point line with duplicate coordinates, if necessary.
             * There will always be at least one coordinate in the coordList.
             */
            if (newCoordinateArray.Length <= 1)
            {
                newCoordinateArray = new Coordinate[] { newCoordinateArray[0], newCoordinateArray[0] }
            }
            ;

            return(line.Factory.CreateLineString(newCoordinateArray));
        }
 private void AddPoint(Coordinate p)
 {
     if (p == null)
     {
         return;
     }
     StartSection();
     _ptList.Add(p, false);
 }
示例#11
0
        /// <summary>
        /// Computes a variable buffer polygon for a single segment,
        /// with the given endpoints and buffer distances.
        /// The individual segment buffers are unioned
        /// to form the final buffer.
        /// </summary>
        /// <param name="p0">The segment start point</param>
        /// <param name="p1">The segment end point</param>
        /// <param name="dist0">The buffer distance at the start point</param>
        /// <param name="dist1">The buffer distance at the end point</param>
        /// <returns>The segment buffer</returns>
        private Polygon SegmentBuffer(Coordinate p0, Coordinate p1,
                                      double dist0, double dist1)
        {
            /*
             * Compute for increasing distance only, so flip if needed
             */
            if (dist0 > dist1)
            {
                return(SegmentBuffer(p1, p0, dist1, dist0));
            }

            // forward tangent line
            var tangent = OuterTangent(p0, dist0, p1, dist1);

            // if tangent is null then compute a buffer for largest circle
            if (tangent == null)
            {
                var    center = p0;
                double dist   = dist0;
                if (dist1 > dist0)
                {
                    center = p1;
                    dist   = dist1;
                }
                return(Circle(center, dist));
            }

            var t0 = tangent.GetCoordinate(0);
            var t1 = tangent.GetCoordinate(1);

            // reverse tangent line on other side of segment
            var seg = new LineSegment(p0, p1);
            var tr0 = seg.Reflect(t0);
            var tr1 = seg.Reflect(t1);

            var coords = new CoordinateList();

            coords.Add(t0);
            coords.Add(t1);

            // end cap
            AddCap(p1, dist1, t1, tr1, coords);

            coords.Add(tr1);
            coords.Add(tr0);

            // start cap
            AddCap(p0, dist0, tr0, t0, coords);

            // close
            coords.Add(t0);

            var pts     = coords.ToCoordinateArray();
            var polygon = _geomFactory.CreatePolygon(pts);

            return(polygon);
        }
示例#12
0
        public void Add()
        {
            var list = new CoordinateList<int>();
              var c = new Coordinate<int>(13, 14);
              list.Add(c);
              Assert.AreEqual(1, list.Count);

              list.Add(23, 24);
              Assert.AreEqual(2, list.Count);
        }
示例#13
0
        public CoordinateList <double> GetValues()
        {
            var list = new CoordinateList <double>();

            list.Add(_ul);
            list.Add(_ur);
            list.Add(_ll);
            list.Add(_lr);

            return(list);
        }
示例#14
0
        public CoordinateList<double> GetValues()
        {
            var list = new CoordinateList<double>();

              list.Add(_ul);
              list.Add(_ur);
              list.Add(_ll);
              list.Add(_lr);

              return list;
        }
示例#15
0
        Coordinate[] GetTessellatedCurveCoordinates(CircularArc3d curve)
        {
            var coordinateList = new CoordinateList();

            if (curve.StartPoint != curve.EndPoint)
            {
                switch (this.CurveTessellationMethod)
                {
                case CurveTessellation.None:
                    coordinateList.Add(this.ReadCoordinate(curve.StartPoint));
                    coordinateList.Add(this.ReadCoordinate(curve.EndPoint));
                    break;

                case CurveTessellation.Linear:
                {
                    var samplePoints = curve.GetSamplePoints((int)Math.Round(this.CurveTessellationValue));
                    for (int i = 0; i < samplePoints.Length; i++)
                    {
                        Point3d point3D = samplePoints[i].Point;
                        coordinateList.Add(this.ReadCoordinate(point3D));
                    }
                    break;
                }

                case CurveTessellation.Scaled:
                {
                    double num  = curve.GetArea(curve.GetParameterOf(curve.StartPoint), curve.GetParameterOf(curve.EndPoint)) * this.CurveTessellationValue;
                    double num2 = Math.Acos((curve.Radius - 1.0 / (num / 2.0)) / curve.Radius);
                    int    num3 = (int)Math.Round(6.2831853071795862 / num2);
                    if (num3 < 8)
                    {
                        num3 = 8;
                    }
                    if (num3 > 128)
                    {
                        num3 = 128;
                    }

                    var samplePoints2 = curve.GetSamplePoints(num3);
                    for (int j = 0; j < samplePoints2.Length; j++)
                    {
                        var point3d2 = samplePoints2[j].Point;
                        coordinateList.Add(this.ReadCoordinate(point3d2));
                    }
                    break;
                }
                }
            }
            return(coordinateList.ToCoordinateArray());
        }
示例#16
0
        CoordinateList <byte> GetControlPoints()
        {
            var objc = _adjustment[0] as ObjcParameter;

            var obj = objc.Parameters["Chnl"] as ReferenceParameter;

            var curve = objc.Parameters["Crv"] as ListParameter;

            var controlPoints = new CoordinateList <byte>();

            // Dirty hack. Fixme!
            if (curve == null)
            {
                return(controlPoints);
            }

            foreach (Parameter parameter in curve)
            {
                var    point = parameter as ObjcParameter;
                double x     =
                    (point.Parameters["Hrzn"] as DoubleParameter).Value;
                double y =
                    (point.Parameters["Vrtc"] as DoubleParameter).Value;

                controlPoints.Add(new Coordinate <byte>((byte)x, (byte)y));
            }

            return(controlPoints);
        }
        public static Geometry GridPoints(Geometry g, int nCells)
        {
            var env      = FunctionsUtil.GetEnvelopeOrDefault(g);
            var geomFact = FunctionsUtil.GetFactoryOrDefault(g);

            int nCellsOnSideY = (int)Math.Sqrt(nCells);
            int nCellsOnSideX = nCells / nCellsOnSideY;

            double cellSizeX = env.Width / (nCellsOnSideX - 1);
            double cellSizeY = env.Height / (nCellsOnSideY - 1);

            var pts = new CoordinateList();

            for (int i = 0; i < nCellsOnSideX; i++)
            {
                for (int j = 0; j < nCellsOnSideY; j++)
                {
                    double x = env.MinX + i * cellSizeX;
                    double y = env.MinY + j * cellSizeY;

                    pts.Add(new Coordinate(x, y));
                }
            }

            return(geomFact.CreateMultiPointFromCoords(pts.ToCoordinateArray()));
        }
示例#18
0
        /// <summary>
        /// Traverses edges from edgeStart which
        /// lie in a single line (have degree = 2).
        /// <para/>
        /// The direction of the linework is preserved as far as possible.
        /// Specifically, the direction of the line is determined
        /// by the start edge direction. This implies
        /// that if all edges are reversed, the created line
        /// will be reversed to match.
        /// (Other more complex strategies would be possible.
        /// E.g. using the direction of the majority of segments,
        /// or preferring the direction of the A edges.)
        /// </summary>
        private LineString BuildLine(OverlayEdge node)
        {
            var pts = new CoordinateList();

            pts.Add(node.Orig, false);

            bool isForward = node.IsForward;

            var e = node;

            do
            {
                e.MarkVisitedBoth();
                e.AddCoordinates(pts);

                // end line if next vertex is a node
                if (DegreeOfLines(e.SymOE) != 2)
                {
                    break;
                }
                e = NextLineEdgeUnvisited(e.SymOE);
                // e will be null if next edge has been visited, which indicates a ring
            }while (e != null);

            var ptsOut = pts.ToCoordinateArray(isForward);

            var line = _geometryFactory.CreateLineString(ptsOut);

            return(line);
        }
示例#19
0
        public Preview(Drawable drawable, CoordinateList<int> coordinates)
            : base(drawable)
        {
            _coordinates = coordinates;

              PreviewArea area = Area;
              area.Events = EventMask.ButtonPressMask | EventMask.ButtonReleaseMask |
            EventMask.PointerMotionHintMask | EventMask.PointerMotionMask |
            EventMask.LeaveNotifyMask;

              ButtonPressEvent += (sender, args) =>
            {
              // Fix me: calculate real-world coordinates
              _coordinates.Add(new Coordinate<int>((int) args.Event.X,
                           (int) args.Event.Y));
            };

              ExposeEvent += delegate
            {
              var layout = new Pango.Layout(area.PangoContext);
              layout.FontDescription = FontDescription.FromString("Tahoma 16");

              int i = 0;
              foreach (var coordinate in _coordinates)
              {
            layout.SetMarkup(String.Format("{0}", i));
              // Fix me: transfer from real-world coordinates
            area.GdkWindow.DrawLayout(Style.TextGC(StateType.Normal),
                      coordinate.X, coordinate.Y,
                      layout);
            i++;
              }
            };
        }
示例#20
0
        private IGeometry ConstructMeridianGraticule(double thisX, double minorInt, Envelope constrExtents, Polygon mapExtents)
        {
            var coords = new CoordinateList();

            var thisY = constrExtents.MinY;

            while (thisY <= constrExtents.MaxY)
            {
                coords.Add(new Coordinate(CalcScaleCorrectedX(thisX, thisY), thisY));
                thisY += minorInt;
            }

            var graticule = (IGeometry) new LineString(coords.ToArray());

            if (!_webMercatorEnv.Contains(graticule.EnvelopeInternal))
            {
                graticule = _webMercatorPoly.Intersection(graticule);
            }

            if (!mapExtents.EnvelopeInternal.Contains(graticule.EnvelopeInternal))
            {
                graticule = mapExtents.Intersection(graticule);
            }

            return(graticule);
        }
        /// <summary>
        /// Snap segments of the source to nearby snap vertices.
        /// Source segments are "cracked" at a snap vertex, and further
        /// snapping takes place on the modified list of segments.
        /// For each distinct snap vertex, at most one source segment
        /// is snapped to.  This prevents "cracking" multiple segments
        /// at the same point, which would almost certainly cause the result to be invalid.
        /// </summary>
        /// <param name="srcCoords"></param>
        /// <param name="snapPts"></param>
        private void SnapSegments(CoordinateList srcCoords, ICoordinate[] snapPts)
        {
            int distinctPtCount = snapPts.Length;

            // check for duplicate snap pts.
            // Need to do this better - need to check all points for dups (using a Set?)
            if (snapPts[0].Equals2D(snapPts[snapPts.Length - 1]))
            {
                distinctPtCount = snapPts.Length - 1;
            }

            for (int i = 0; i < distinctPtCount; i++)
            {
                ICoordinate snapPt = snapPts[i];
                int         index  = FindSegmentIndexToSnap(snapPt, srcCoords);

                /**
                 * If a segment to snap to was found, "crack" it at the snap pt.
                 * The new pt is inserted immediately into the src segment list,
                 * so that subsequent snapping will take place on the latest segments.
                 * Duplicate points are not added.
                 */
                if (index >= 0)
                {
                    srcCoords.Add(index + 1, new Coordinate(snapPt), false);
                }
            }
        }
        /// <summary>
        /// Snap segments of the source to nearby snap vertices.<para/>
        /// Source segments are "cracked" at a snap vertex.
        /// A single input segment may be snapped several times
        /// to different snap vertices.<para/>
        /// For each distinct snap vertex, at most one source segment
        /// is snapped to.  This prevents "cracking" multiple segments
        /// at the same point, which would likely cause
        /// topology collapse when being used on polygonal linework.
        /// </summary>
        /// <param name="srcCoords">The coordinates of the source linestring to snap</param>
        /// <param name="snapPts">The target snap vertices</param>
        private void SnapSegments(CoordinateList srcCoords, Coordinate[] snapPts)
        {
            // guard against empty input
            if (snapPts.Length == 0)
            {
                return;
            }

            var distinctPtCount = snapPts.Length;

            // check for duplicate snap pts when they are sourced from a linear ring.
            // TODO: Need to do this better - need to check *all* points for dups (using a Set?)
            if (snapPts[0].Equals2D(snapPts[snapPts.Length - 1]))
            {
                distinctPtCount = snapPts.Length - 1;
            }

            for (var i = 0; i < distinctPtCount; i++)
            {
                var snapPt = snapPts[i];
                var index  = FindSegmentIndexToSnap(snapPt, srcCoords);

                /*
                 * If a segment to snap to was found, "crack" it at the snap pt.
                 * The new pt is inserted immediately into the src segment list,
                 * so that subsequent snapping will take place on the modified segments.
                 * Duplicate points are not added.
                 */
                if (index >= 0)
                {
                    srcCoords.Add(index + 1, new Coordinate(snapPt), false);
                }
            }
        }
示例#23
0
    // Use this for initialization
    void Start()
    {
        instance  = this;
        _grid     = GameObject.Find("Grid").GetComponent <RectGrid>();
        _renderer = _grid.gameObject.GetComponent <Parallelepiped>();
        xMin      = 0;  //(int)_renderer.From[0];
        xMax      = 20; //(int)_renderer.To[0];
        zMin      = 0;  //(int)_renderer.From[2];
        zMax      = 20; //(int)_renderer.To[2];

        for (int x = xMin; x < xMax; x++)
        {
            for (int z = zMin; z < zMax; z++)
            {
                int        elevationMax = mapTopography[x][z];
                Coordinate coordinate   = new Coordinate();
                coordinate.x             = x;
                coordinate.z             = z;
                coordinate.y             = elevationMax - 1;
                coordinate.respawnMarker = respawnMarkerList.Exists(r => r[0] == x && r[1] == z);
                syncCoordinates.Add(coordinate);
            }
        }

        CacheMatrix();

        RenderVoxels();

        CursorController.instance.Load();
    }
示例#24
0
        public Preview(Drawable drawable, CoordinateList <int> coordinates) :
            base(drawable)
        {
            _coordinates = coordinates;

            PreviewArea area = Area;

            area.Events = EventMask.ButtonPressMask | EventMask.ButtonReleaseMask |
                          EventMask.PointerMotionHintMask | EventMask.PointerMotionMask |
                          EventMask.LeaveNotifyMask;

            ButtonPressEvent += (sender, args) =>
            {
                // Fix me: calculate real-world coordinates
                _coordinates.Add(new Coordinate <int>((int)args.Event.X,
                                                      (int)args.Event.Y));
            };

            ExposeEvent += delegate
            {
                var layout = new Pango.Layout(area.PangoContext);
                layout.FontDescription = FontDescription.FromString("Tahoma 16");

                int i = 0;
                foreach (var coordinate in _coordinates)
                {
                    layout.SetMarkup(String.Format("{0}", i));
                    // Fix me: transfer from real-world coordinates
                    area.GdkWindow.DrawLayout(Style.TextGC(StateType.Normal),
                                              coordinate.X, coordinate.Y,
                                              layout);
                    i++;
                }
            };
        }
示例#25
0
        /// <summary>
        /// Gets the Voronoi cell around a site specified
        /// by the origin of a QuadEdge.
        /// </summary>
        /// <remarks>
        /// The userData of the polygon is set to be the <see cref="Coordinate" />
        /// of the site.  This allows attaching external
        /// data associated with the site to this cell polygon.
        /// </remarks>
        /// <param name="qe">a quadedge originating at the cell site</param>
        /// <param name="geomFact">a factory for building the polygon</param>
        /// <returns>a polygon indicating the cell extent</returns>
        public Polygon GetVoronoiCellPolygon(QuadEdge qe, GeometryFactory geomFact)
        {
            var cellPts = new List <Coordinate>();
            var startQE = qe;

            do
            {
                // Coordinate cc = circumcentre(qe);
                // use previously computed circumcentre
                var cc = qe.Rot.Orig.Coordinate;
                cellPts.Add(cc);

                // move to next triangle CW around vertex
                qe = qe.OPrev;
            } while (qe != startQE);

            var coordList = new CoordinateList();

            coordList.AddAll(cellPts, false);
            coordList.CloseRing();

            if (coordList.Count < 4)
            {
                Debug.WriteLine(coordList);
                coordList.Add(coordList[coordList.Count - 1], true);
            }

            var pts      = coordList.ToCoordinateArray();
            var cellPoly = geomFact.CreatePolygon(geomFact.CreateLinearRing(pts));

            var v = startQE.Orig;

            cellPoly.UserData = v.Coordinate;
            return(cellPoly);
        }
示例#26
0
        public static CoordinateList get_all_coordinates_for_row(int x, int y)
        {
            CoordinateList coords = get_other_coordinates_for_row(x, y);

            coords.Add(x, y);
            return(coords);
        }
示例#27
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="coords"></param>
 /// <param name="isForward"></param>
 /// <param name="coordList"></param>
 private static void AddEdge(Coordinate[] coords, bool isForward, CoordinateList coordList)
 {
     if (isForward)
     {
         for (int i = 0; i < coords.Length; i++)
         {
             coordList.Add(coords[i], false);
         }
     }
     else
     {
         for (int i = coords.Length - 1; i >= 0; i--)
         {
             coordList.Add(coords[i], false);
         }
     }
 }
示例#28
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="coords"></param>
 /// <param name="isForward"></param>
 /// <param name="coordList"></param>
 private static void AddEdge(IList <Coordinate> coords, bool isForward, CoordinateList coordList)
 {
     if (isForward)
     {
         for (int i = 0; i < coords.Count; i++)
         {
             coordList.Add(coords[i], false);
         }
     }
     else
     {
         for (int i = coords.Count - 1; i >= 0; i--)
         {
             coordList.Add(coords[i], false);
         }
     }
 }
示例#29
0
        public void Add_AppendsCoordinateToTheEndOfList()
        {
            CoordinateList target = new CoordinateList(_coordinates);

            target.Add(_coordinate);

            Assert.Equal(_coordinate, target.Last());
        }
示例#30
0
        public void Add_IncresesCount()
        {
            CoordinateList target = new CoordinateList(_coordinates);

            target.Add(_coordinate);

            Assert.Equal(_coordinates.Length + 1, target.Count);
        }
示例#31
0
        public static CoordinateList get_all_coordinates_for_block(int x, int y)
        {
            //Console.WriteLine($"{x}, {y}");
            CoordinateList coords = get_other_coordinates_for_block(x, y);

            coords.Add(x, y);
            return(coords);
        }
示例#32
0
        override public bool Execute()
        {
            if (_adjustment != null)
            {
                ObjcParameter objc = _adjustment[0] as ObjcParameter;

                ReferenceParameter obj = objc.Parameters["Chnl"] as
                                         ReferenceParameter;
                string origChannel = (obj.Set[0] as EnmrType).Value;

                ListParameter curve = objc.Parameters["Crv"] as ListParameter;

                CoordinateList <byte> controlPoints = new CoordinateList <byte>();

                foreach (Parameter parameter in curve)
                {
                    ObjcParameter point = parameter as ObjcParameter;
                    double        x     =
                        (point.Parameters["Hrzn"] as DoubleParameter).Value;
                    double y =
                        (point.Parameters["Vrtc"] as DoubleParameter).Value;

                    controlPoints.Add(new Coordinate <byte>((byte)x, (byte)y));
                }

                HistogramChannel channel;

                switch (origChannel)
                {
                case "Cmps":
                    channel = HistogramChannel.Value;
                    break;

                case "Rd":
                    channel = HistogramChannel.Red;
                    break;

                case "Grn":
                    channel = HistogramChannel.Green;
                    break;

                case "Bl":
                    channel = HistogramChannel.Blue;
                    break;

                default:
                    Console.WriteLine("CurvesEvent: " + origChannel);
                    return(false);
                }

                ActiveDrawable.CurvesSpline(channel, controlPoints);
            }
            else
            {
                Console.WriteLine("CurvesEvent: adjustment == null?");
            }
            return(true);
        }
示例#33
0
        public void AddXYCoordinates(string x, string y, string coordinateName)
        {
            if (CoordinateList == null)
            {
                CoordinateList = new List <Coordinate>();
            }

            CoordinateList.Add(new Coordinate(x, y, coordinateName));
        }
 /// <summary>
 /// Adds a point to the current line.
 /// </summary>
 /// <param name="pt">The <see cref="Coordinate" /> to add.</param>
 /// <param name="allowRepeatedPoints">If <c>true</c>, allows the insertions of repeated points.</param>
 public void Add(Coordinate pt, bool allowRepeatedPoints)
 {
     if (_coordList == null)
     {
         _coordList = new CoordinateList();
     }
     _coordList.Add(pt, allowRepeatedPoints);
     _lastPt = pt;
 }
示例#35
0
        /// <summary>
        /// Reads a stream and converts the shapefile record to an equilivent geometry object.
        /// </summary>
        /// <param name="file">The stream to read.</param>
        /// <param name="geometryFactory">The geometry factory to use when making the object.</param>
        /// <returns>The Geometry object that represents the shape file record.</returns>
        public override IGeometry Read(BigEndianBinaryReader file, IGeometryFactory geometryFactory)
        {
            int shapeTypeNum             = file.ReadInt32();
            ShapeGeometryTypes shapeType = (ShapeGeometryTypes)Enum.Parse(typeof(ShapeGeometryTypes), shapeTypeNum.ToString());

            if (!(shapeType == ShapeGeometryTypes.LineString || shapeType == ShapeGeometryTypes.LineStringM ||
                  shapeType == ShapeGeometryTypes.LineStringZ || shapeType == ShapeGeometryTypes.LineStringZM))
            {
                throw new ShapefileException("Attempting to load a non-arc as arc.");
            }

            //read and for now ignore bounds.
            double[] box = new double[4];
            for (int i = 0; i < 4; i++)
            {
                double d = file.ReadDouble();
                box[i] = d;
            }

            int numParts  = file.ReadInt32();
            int numPoints = file.ReadInt32();

            int[] partOffsets = new int[numParts];
            for (int i = 0; i < numParts; i++)
            {
                partOffsets[i] = file.ReadInt32();
            }

            ILineString[] lines = new LineString[numParts];
            int           start, finish, length;

            for (int part = 0; part < numParts; part++)
            {
                start = partOffsets[part];
                if (part == numParts - 1)
                {
                    finish = numPoints;
                }
                else
                {
                    finish = partOffsets[part + 1];
                }
                length = finish - start;
                CoordinateList points = new CoordinateList();
                points.Capacity = length;
                Coordinate external;
                for (int i = 0; i < length; i++)
                {
                    external = new Coordinate(file.ReadDouble(), file.ReadDouble());
                    // points.Add(geometryFactory.PrecisionModel.ToInternal(external));
                    new PrecisionModel(geometryFactory.PrecisionModel).MakePrecise(external);
                    points.Add(external);
                }
                lines[part] = geometryFactory.CreateLineString((ICoordinate[])points.ToArray(typeof(ICoordinate)));
            }
            return(geometryFactory.CreateMultiLineString(lines));
        }
示例#36
0
        public override bool Execute()
        {
            if (_adjustment != null)
            {
              ObjcParameter objc = _adjustment[0] as ObjcParameter;

              ReferenceParameter obj = objc.Parameters["Chnl"] as
            ReferenceParameter;
              string origChannel = (obj.Set[0] as EnmrType).Value;

              ListParameter curve = objc.Parameters["Crv"] as ListParameter;

              CoordinateList<byte> controlPoints = new CoordinateList<byte>();

              foreach (Parameter parameter in curve)
            {
              ObjcParameter point = parameter as ObjcParameter;
              double x =
            (point.Parameters["Hrzn"] as DoubleParameter).Value;
              double y =
            (point.Parameters["Vrtc"] as DoubleParameter).Value;

              controlPoints.Add(new Coordinate<byte>((byte) x, (byte) y));
            }

              HistogramChannel channel;

              switch (origChannel)
            {
            case "Cmps":
              channel = HistogramChannel.Value;
              break;
            case "Rd":
              channel = HistogramChannel.Red;
              break;
            case "Grn":
              channel = HistogramChannel.Green;
              break;
            case "Bl":
              channel = HistogramChannel.Blue;
              break;
            default:
              Console.WriteLine("CurvesEvent: " + origChannel);
              return false;
            }

              ActiveDrawable.CurvesSpline(channel, controlPoints);
            }
              else
            {
              Console.WriteLine("CurvesEvent: adjustment == null?");
            }
              return true;
        }
示例#37
0
        public void Equals()
        {
            var list1 = new CoordinateList<int>();
              var list2 = new CoordinateList<int>();
              var c = new Coordinate<int>(13, 14);

              list1.Add(c);
              Assert.IsFalse(list1.Equals(list2));

              list2.Add(c);
              Assert.IsTrue(list1.Equals(list2));
        }
示例#38
0
        /// <summary>
        /// Reads a stream and converts the shapefile record to an equilivent geometry object.
        /// </summary>
        /// <param name="file">The stream to read.</param>
        /// <param name="geometryFactory">The geometry factory to use when making the object.</param>
        /// <returns>The Geometry object that represents the shape file record.</returns>
        public override IGeometry Read(BigEndianBinaryReader file, IGeometryFactory geometryFactory)
        {
            int shapeTypeNum = file.ReadInt32();
            type = (ShapeGeometryType) Enum.Parse(typeof(ShapeGeometryType), shapeTypeNum.ToString());
            if (type == ShapeGeometryType.NullShape)
                return geometryFactory.CreateMultiLineString(null);

            if (!(type == ShapeGeometryType.LineString  || type == ShapeGeometryType.LineStringM ||
                  type == ShapeGeometryType.LineStringZ || type == ShapeGeometryType.LineStringZM))
                throw new ShapefileException("Attempting to load a non-arc as arc.");

            // Read and for now ignore bounds.            
            int bblength = GetBoundingBoxLength();
            bbox = new double[bblength];
            for (; bbindex < 4; bbindex++)
            {
                double d = file.ReadDouble();
                bbox[bbindex] = d;
            }
        
            int numParts = file.ReadInt32();
            int numPoints = file.ReadInt32();
            int[] partOffsets = new int[numParts];
            for (int i = 0; i < numParts; i++)
                partOffsets[i] = file.ReadInt32();
			
            ILineString[] lines = new ILineString[numParts];			
            for (int part = 0; part < numParts; part++)
            {
                int start, finish, length;
                start = partOffsets[part];
                if (part == numParts - 1)
                     finish = numPoints;
                else finish = partOffsets[part + 1];
                length = finish - start;
                CoordinateList points = new CoordinateList();                
                points.Capacity = length;
                for (int i = 0; i < length; i++)
                {
                    double x = file.ReadDouble();
                    double y = file.ReadDouble();
                    ICoordinate external = new Coordinate(x, y);
                    geometryFactory.PrecisionModel.MakePrecise(external);
                    points.Add(external);				    
                }
                ILineString line = geometryFactory.CreateLineString(points.ToArray());
                lines[part] = line;
            }
            geom = geometryFactory.CreateMultiLineString(lines);
            GrabZMValues(file);
            return geom;
        }
        /// <summary>
        ///
        /// </summary>
        /// <returns></returns>
        private Coordinate[] Simplify()
        {
            _usePt = new bool[_pts.Count];
            for (int i = 0; i < _pts.Count; i++)
                _usePt[i] = true;

            SimplifySection(0, _pts.Count - 1);
            CoordinateList coordList = new CoordinateList();
            for (int i = 0; i < _pts.Count; i++)
                if (_usePt[i])
                    coordList.Add(new Coordinate(_pts[i]));
            return coordList.ToCoordinateArray();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        public ICoordinate[] Simplify()
        {
            usePt = new bool[pts.Length];
            for (int i = 0; i < pts.Length; i++)
                usePt[i] = true;

            SimplifySection(0, pts.Length - 1);
            CoordinateList coordList = new CoordinateList();
            for (int i = 0; i < pts.Length; i++)
                if (usePt[i])
                    coordList.Add(new Coordinate(pts[i]));
            return coordList.ToCoordinateArray();
        }
示例#41
0
        public void Enumerator()
        {
            var list = new CoordinateList<int>();
              for (int i = 0; i < 10; i++)
            {
              list.Add(new Coordinate<int>(i, 2 * i));
            }

              int count = 0;
              foreach (var c in list)
            {
              Assert.IsTrue(c == new Coordinate<int>(count, 2 * count));
              count++;
            }
              Assert.AreEqual(list.Count, count);
        }
示例#42
0
		/// <summary>
		/// Reads a stream and converts the shapefile record to an equilivent geometry object.
		/// </summary>
		/// <param name="file">The stream to read.</param>
		/// <param name="geometryFactory">The geometry factory to use when making the object.</param>
		/// <returns>The Geometry object that represents the shape file record.</returns>
		public override IGeometry Read(BigEndianBinaryReader file, IGeometryFactory geometryFactory)
		{
			int shapeTypeNum = file.ReadInt32();
            ShapeGeometryTypes shapeType = (ShapeGeometryTypes)Enum.Parse(typeof(ShapeGeometryTypes), shapeTypeNum.ToString());
            if( ! ( shapeType == ShapeGeometryTypes.LineString  || shapeType == ShapeGeometryTypes.LineStringM   ||
                    shapeType == ShapeGeometryTypes.LineStringZ || shapeType == ShapeGeometryTypes.LineStringZM  ))
				throw new ShapefileException("Attempting to load a non-arc as arc.");

			//read and for now ignore bounds.
			double[] box = new double[4];
			for (int i = 0; i < 4; i++) 
			{
				double d= file.ReadDouble();
				box[i] =d;
			}
        
			int numParts = file.ReadInt32();
			int numPoints = file.ReadInt32();
			int[] partOffsets = new int[numParts];
			for (int i = 0; i < numParts; i++)
				partOffsets[i] = file.ReadInt32();
			
			ILineString[] lines = new ILineString[numParts];
			int start, finish, length;
			for (int part = 0; part < numParts; part++)
			{
				start = partOffsets[part];
				if (part == numParts - 1)
					 finish = numPoints;
				else finish = partOffsets[part + 1];
				length = finish - start;
                CoordinateList points = new CoordinateList();
				points.Capacity=length;
				ICoordinate external;
				for (int i = 0; i < length; i++)
				{
					external = new Coordinate(file.ReadDouble(),file.ReadDouble());
					geometryFactory.PrecisionModel.MakePrecise( external);
                    points.Add(external);
				}
                lines[part] = geometryFactory.CreateLineString(points.ToArray());
			}
			return geometryFactory.CreateMultiLineString(lines);
		}
        public IGeometry Densify(double segLength)
        {
            newCoords = new CoordinateList();

            ICoordinateSequence seq = inputLine.CoordinateSequence;

            Coordinate p0 = new Coordinate();
            Coordinate p1 = new Coordinate();
            seq.GetCoordinate(0, p0);
            newCoords.Add(new Coordinate(p0));

            for (int i = 0; i < seq.Count - 1; i++)
            {
                seq.GetCoordinate(i, p0);
                seq.GetCoordinate(i + 1, p1);
                Densify(p0, p1, segLength);
            }
            Coordinate[] newPts = newCoords.ToCoordinateArray();
            return inputLine.Factory.CreateLineString(newPts);
        }
示例#44
0
        private void BuildRing(HalfEdge eStartRing)
        {
            CoordinateList line = new CoordinateList();
            HalfEdge e = eStartRing;

            Coordinate orig = e.Orig;
            line.Add(orig.Clone(), false);
            // scan along the path until a node is found (if one exists)
            while (e.Sym.Degree() == 2)
            {
                HalfEdge eNext = e.Next;
                // check if edges form a ring - if so, we're done
                if (eNext == eStartRing)
                    break;

                // add point to line, and move to next edge
                orig = eNext.Orig;
                line.Add(orig.Clone(), false);
                e = eNext;
            }
            // add final node
            Coordinate dest = e.Dest;
            line.Add(dest.Clone(), false);

            // store the scanned line
            AddLine(line);
        }
示例#45
0
        public void ToArray()
        {
            var list = new CoordinateList<int>();
              var c = new Coordinate<int>(13, 14);

              int[] array = list.ToArray();
              Assert.IsNull(array);

              list.Add(c);
              array = list.ToArray();
              Assert.AreEqual(2, array.Length);
        }
 public Coordinate[] GetCoordinates()
 {
     CoordinateList coords = new CoordinateList();
     VWVertex curr = this;
     do
     {
         coords.Add(curr._pt, false);
         curr = curr.Next;
     }
     while (curr != null);
     return coords.ToCoordinateArray();
 }
示例#47
0
        /// <summary>
        /// Builds a line starting from the given edge.
        /// The start edge origin is a node (valence = 1 or >= 3), 
        /// unless it is part of a pure ring.
        /// </summary>
        /// <remarks>
        /// A pure ring has no other incident lines.
        /// In this case the start edge may occur anywhere on the ring.
        /// </remarks>
        /// <remarks>
        /// The line is built up to the next node encountered,
        /// or until the start edge is re-encountered
        /// (which happens if the edges form a ring).
        /// </remarks>
        /// <param name="eStart"></param>
        private void BuildLine(HalfEdge eStart)
        {
            CoordinateList line = new CoordinateList();
            DissolveHalfEdge e = (DissolveHalfEdge)eStart;
            _ringStartEdge = null;

            MarkHalfEdge.MarkBoth(e);
            Coordinate orig = e.Orig;
            line.Add(orig.Clone(), false);
            // scan along the path until a node is found (if one exists)
            while (e.Sym.Degree() == 2)
            {
                UpdateRingStartEdge(e);
                DissolveHalfEdge eNext = (DissolveHalfEdge)e.Next;
                // check if edges form a ring - if so, we're done
                if (eNext == eStart)
                {
                    BuildRing(_ringStartEdge);
                    return;
                }
                // add point to line, and move to next edge
                orig = eNext.Orig;
                line.Add(orig.Clone(), false);
                e = eNext;
                MarkHalfEdge.MarkBoth(e);
            }
            // add final node
            Coordinate dest = e.Dest;
            line.Add(dest.Clone(), false);

            // queue up the final node edges
            StackEdges(e.Sym);
            // store the scanned line
            AddLine(line);
        }
        /// <summary>
        /// Snap segments of the source to nearby snap vertices.<para/>
        /// Source segments are "cracked" at a snap vertex.
        /// A single input segment may be snapped several times
        /// to different snap vertices.<para/>
        /// For each distinct snap vertex, at most one source segment
        /// is snapped to.  This prevents "cracking" multiple segments
        /// at the same point, which would likely cause
        /// topology collapse when being used on polygonal linework.
        /// </summary>
        /// <param name="srcCoords">The coordinates of the source linestring to snap</param>
        /// <param name="snapPts">The target snap vertices</param>
        private void SnapSegments(CoordinateList srcCoords, Coordinate[] snapPts)
        {
            // guard against empty input
            if (snapPts.Length == 0) return;

            var distinctPtCount = snapPts.Length;

            // check for duplicate snap pts when they are sourced from a linear ring.
            // TODO: Need to do this better - need to check *all* points for dups (using a Set?)
            if (snapPts[0].Equals2D(snapPts[snapPts.Length - 1]))
                distinctPtCount = snapPts.Length - 1;

            for (var i = 0; i < distinctPtCount; i++)
            {
                var snapPt = snapPts[i];
                var index = FindSegmentIndexToSnap(snapPt, srcCoords);
                /*
                 * If a segment to snap to was found, "crack" it at the snap pt.
                 * The new pt is inserted immediately into the src segment list,
                 * so that subsequent snapping will take place on the modified segments.
                 * Duplicate points are not added.
                 */
                if (index >= 0)
                    srcCoords.Add(index + 1, new Coordinate(snapPt), false);
            }
        }
示例#49
0
        public void ForEach()
        {
            var list = new CoordinateList<int>();
              for (int i = 0; i < 10; i++)
            {
              list.Add(new Coordinate<int>(i, 2 * i));
            }

              int count = 0;
              list.ForEach(c =>
            {
              Assert.IsTrue(c == new Coordinate<int>(count, 2 * count));
              count++;
            });
              Assert.AreEqual(list.Count, count);
        }
        public IGeometry ToGeometry(IGeometryFactory geomFactory)
        {
            if (IsNull)
            {
                return geomFactory.CreatePoint((ICoordinateSequence)null);
            }

            Coordinate px00 = new Coordinate(_minX, _minA - _minX);
            Coordinate px01 = new Coordinate(_minX, _minX - _minB);

            Coordinate px10 = new Coordinate(_maxX, _maxX - _maxB);
            Coordinate px11 = new Coordinate(_maxX, _maxA - _maxX);

            Coordinate py00 = new Coordinate(_minA - _minY, _minY);
            Coordinate py01 = new Coordinate(_minY + _maxB, _minY);

            Coordinate py10 = new Coordinate(_maxY + _minB, _maxY);
            Coordinate py11 = new Coordinate(_maxA - _maxY, _maxY);

            IPrecisionModel pm = geomFactory.PrecisionModel;
            pm.MakePrecise(px00);
            pm.MakePrecise(px01);
            pm.MakePrecise(px10);
            pm.MakePrecise(px11);
            pm.MakePrecise(py00);
            pm.MakePrecise(py01);
            pm.MakePrecise(py10);
            pm.MakePrecise(py11);

            CoordinateList coordList = new CoordinateList();
            coordList.Add(px00, false);
            coordList.Add(px01, false);
            coordList.Add(py10, false);
            coordList.Add(py11, false);
            coordList.Add(px11, false);
            coordList.Add(px10, false);
            coordList.Add(py01, false);
            coordList.Add(py00, false);

            if (coordList.Count == 1)
            {
                return geomFactory.CreatePoint(px00);
            }
            Coordinate[] pts;
            if (coordList.Count == 2)
            {
                pts = coordList.ToCoordinateArray();
                return geomFactory.CreateLineString(pts);
            }
            // must be a polygon, so add closing point
            coordList.Add(px00, false);
            pts = coordList.ToCoordinateArray();
            return geomFactory.CreatePolygon(geomFactory.CreateLinearRing(pts), null);
        }
示例#51
0
        /// <summary>
        /// Reads a stream and converts the shapefile record to an equilivent geometry object.
        /// </summary>
        /// <param name="file">The stream to read.</param>
        /// <param name="geometryFactory">The geometry factory to use when making the object.</param>
        /// <returns>The Geometry object that represents the shape file record.</returns>
        public override IGeometry Read(BigEndianBinaryReader file, IGeometryFactory geometryFactory)
        {
            int shapeTypeNum = file.ReadInt32();
            type = (ShapeGeometryType) Enum.Parse(typeof(ShapeGeometryType), shapeTypeNum.ToString());
            if (type == ShapeGeometryType.NullShape)
                return geometryFactory.CreatePolygon(null, null);

            if (!(type == ShapeGeometryType.Polygon  || type == ShapeGeometryType.PolygonM ||
                  type == ShapeGeometryType.PolygonZ || type == ShapeGeometryType.PolygonZM))	
                throw new ShapefileException("Attempting to load a non-polygon as polygon.");

            // Read and for now ignore bounds.
            int bblength = GetBoundingBoxLength();
            bbox = new double[bblength];
            for (; bbindex < 4; bbindex++)
            {
                double d = file.ReadDouble();
                bbox[bbindex] = d;
            }
            
            int[] partOffsets;        
            int numParts = file.ReadInt32();
            int numPoints = file.ReadInt32();
            partOffsets = new int[numParts];
            for (int i = 0; i < numParts; i++)
                partOffsets[i] = file.ReadInt32();

            ArrayList shells = new ArrayList();
            ArrayList holes = new ArrayList();

            int start, finish, length;
            for (int part = 0; part < numParts; part++)
            {
                start = partOffsets[part];
                if (part == numParts - 1)
                    finish = numPoints;
                else finish = partOffsets[part + 1];
                length = finish - start;
                CoordinateList points = new CoordinateList();
                points.Capacity = length;
                for (int i = 0; i < length; i++)
                {
                    ICoordinate external = new Coordinate(file.ReadDouble(), file.ReadDouble() );					
                    geometryFactory.PrecisionModel.MakePrecise( external);
                    ICoordinate internalCoord = external;

                    // Thanks to Abhay Menon!
                    if (!Double.IsNaN(internalCoord.Y) && !Double.IsNaN(internalCoord.X))
                        points.Add(internalCoord, false);
                }

                if (points.Count > 2) // Thanks to Abhay Menon!
                {
                    if (points[0].Distance(points[points.Count - 1]) > .00001)
                        points.Add(new Coordinate(points[0]));
                    else if (points[0].Distance(points[points.Count - 1]) > 0.0)
                        points[points.Count - 1].CoordinateValue = points[0];

                    ILinearRing ring = geometryFactory.CreateLinearRing(points.ToArray());

                    // If shape have only a part, jump orientation check and add to shells
                    if (numParts == 1)
                        shells.Add(ring);
                    else
                    {
                        // Orientation check
                        if (CGAlgorithms.IsCCW(points.ToArray()))
                             holes.Add(ring);
                        else shells.Add(ring);
                    }                    
                }
            }

            // Now we have a list of all shells and all holes
            ArrayList holesForShells = new ArrayList(shells.Count);
            for (int i = 0; i < shells.Count; i++)
                holesForShells.Add(new ArrayList());

            // Find holes
            for (int i = 0; i < holes.Count; i++)
            {
                ILinearRing testRing = (ILinearRing) holes[i];
                ILinearRing minShell = null;
                IEnvelope minEnv = null;
                IEnvelope testEnv = testRing.EnvelopeInternal;
                ICoordinate testPt = testRing.GetCoordinateN(0);
                ILinearRing tryRing;
                for (int j = 0; j < shells.Count; j++)
                {
                    tryRing = (ILinearRing) shells[j];
                    IEnvelope tryEnv = tryRing.EnvelopeInternal;
                    if (minShell != null)
                        minEnv = minShell.EnvelopeInternal;
                    bool isContained = false;
                    CoordinateList coordList = new CoordinateList(tryRing.Coordinates);
                    if (tryEnv.Contains(testEnv) && 
                       (CGAlgorithms.IsPointInRing(testPt, coordList.ToArray()) || (PointInList(testPt, coordList)))) 				
                        isContained = true;

                    // Check if this new containing ring is smaller than the current minimum ring
                    if (isContained)
                    {
                        if (minShell == null || minEnv.Contains(tryEnv))
                            minShell = tryRing;             

                        // Suggested by Brian Macomber and added 3/28/2006:
                        // holes were being found but never added to the holesForShells array
                        // so when converted to geometry by the factory, the inner rings were never created.
                        ArrayList holesForThisShell = (ArrayList) holesForShells[j];
                        holesForThisShell.Add(testRing);
                    }
                }
            }

            IPolygon[] polygons = new IPolygon[shells.Count];
            for (int i = 0; i < shells.Count; i++)
                polygons[i] = (geometryFactory.CreatePolygon((ILinearRing) shells[i], 
                    (ILinearRing[]) ((ArrayList) holesForShells[i]).ToArray(typeof(ILinearRing))));

            if (polygons.Length == 1)
                 geom = polygons[0];
            else geom = geometryFactory.CreateMultiPolygon(polygons);
            GrabZMValues(file);
            return geom;
        }
示例#52
0
        public void WriteShapeFiles(DataAccessLayer DAL)
        {
            #if !(PocketPC || WindowsCE || Mobile)
            List<TtPolygon> polys = DAL.GetPolygons();
            Dictionary<string, TtMetaData> metas = DAL.GetMetaData().ToDictionary(m => m.CN, m => m);

            string folder = SelectedPath + "\\GIS";
            Directory.CreateDirectory(folder);

            foreach (TtPolygon poly in polys)
            {
                string _CurrDir = String.Format("{0}\\{1}\\", folder, poly.Name.ScrubFileName());
                string _File = String.Format("{0}\\{1}\\{1}", folder, poly.Name.ScrubFileName());
                Directory.CreateDirectory(_CurrDir);

                string CurrFileName = System.IO.Path.Combine(folder, poly.Name);

                List<TtPoint> points = DAL.GetPointsInPolygon(poly.CN).ToList();

                List<WayPoint> wayPoints = points.FilterOnly(OpType.WayPoint).Cast<WayPoint>().ToList();
                points = points.FilterOut(OpType.WayPoint).ToList();

                TtMetaData md;

                if (points.Count > 0 || wayPoints.Count > 0)
                {
                    if (points.Count > 0)
                        md = DAL.GetMetaDataByCN(points[0].MetaDefCN);
                    else
                        md = DAL.GetMetaDataByCN(wayPoints[0].MetaDefCN);
                    if (md == null)
                        continue;
                }
                else
                    continue;

                if (wayPoints.Count > 0)
                    WriteWayPoints(_File, wayPoints, md);

                if (points.Count < 1)
                    continue;

                CoordinateList BAdjCoords = new CoordinateList();
                CoordinateList BUnAdjCoords = new CoordinateList();

                CoordinateList NavAdjCoords = new CoordinateList();
                CoordinateList NavUnAdjCoords = new CoordinateList();

                bool hasWayPoints = false;

                TtPoint firstBndPoint = null, lastBntPoint = null;

                foreach (TtPoint point in points)
                {
                    if (point.IsNavPoint())
                    {
                        NavAdjCoords.Add(new Coordinate(point.AdjX, point.AdjY, point.AdjZ));
                        NavUnAdjCoords.Add(new Coordinate(point.UnAdjX, point.UnAdjY, point.UnAdjZ));
                    }

                    if (point.IsBndPoint())
                    {
                        BAdjCoords.Add(new Coordinate(point.AdjX, point.AdjY, point.AdjZ));
                        BUnAdjCoords.Add(new Coordinate(point.UnAdjX, point.UnAdjY, point.UnAdjZ));

                        if (firstBndPoint == null)
                            firstBndPoint = point;

                        lastBntPoint = point;
                    }

                    if (point.op == OpType.WayPoint)
                    {
                        hasWayPoints = true;
                    }
                }

                double polyLinePerim = -1;
                if (firstBndPoint != null)
                    polyLinePerim = poly.Perimeter - TtUtils.Distance(firstBndPoint, lastBntPoint, true);

                #region Navigation

                #region Adj
                string FileName = _File + "_NavAdj";
                GeometryFactory geoFac = new GeometryFactory();
                ShapefileDataWriter sdw;
                Polygonizer polyizer = new Polygonizer();

                ArrayList features = new ArrayList();
                AttributesTable attTable = new AttributesTable();

                attTable.AddAttribute("Poly_Name", poly.Name);
                attTable.AddAttribute("Desc", poly.Description);
                attTable.AddAttribute("Poly", "Navigation Adjusted");
                attTable.AddAttribute("CN", poly.CN);
                attTable.AddAttribute("Perim_M", poly.Perimeter);
                attTable.AddAttribute("PerimLine_M", polyLinePerim);

                Feature feat = new Feature();
                DbaseFileHeader dbh;

                if (NavAdjCoords.Count > 1)
                {
                    sdw = new ShapefileDataWriter(FileName, geoFac);

                    feat.Geometry = new NetTopologySuite.Geometries.LineString(NavAdjCoords.ToArray());

                    feat.Attributes = attTable;

                    features.Add(feat);

                    dbh = ShapefileDataWriter.GetHeader((Feature)features[0], features.Count);

                    sdw.Header = dbh;
                    sdw.Write(features);
                    WriteProjection(FileName, md.Zone);

                    //points
                    FileName = _File + "_NavAdj_Points";
                    geoFac = new GeometryFactory();
                    sdw = new ShapefileDataWriter(FileName, geoFac);
                    features = new ArrayList();
                    attTable["Poly"] = "Navigation Adjusted Points";

                    features = GetPointFeatures(points.Where(p => p.IsNavPoint()), true, DAL, metas);

                    if (features.Count > 0)
                    {
                        dbh = ShapefileDataWriter.GetHeader((Feature)features[0], features.Count);
                        sdw.Header = dbh;
                        sdw.Write(features);
                        WriteProjection(FileName, md.Zone);
                    }
                }
                #endregion

                #region UnAdj
                if (NavUnAdjCoords.Count > 1)
                {
                    FileName = _File + "_NavUnAdj";
                    geoFac = new GeometryFactory();
                    sdw = new ShapefileDataWriter(FileName, geoFac);
                    features = new ArrayList();
                    attTable["Poly"] = "Navigation UnAdjusted";
                    feat = new Feature();
                    feat.Geometry = new NetTopologySuite.Geometries.LineString(NavUnAdjCoords.ToArray());
                    //feat.Geometry = new NetTopologySuite.Geometries.LinearRing(NavUnAdjCoords.ToArray());
                    feat.Attributes = attTable;

                    features.Add(feat);

                    dbh = ShapefileDataWriter.GetHeader((Feature)features[0], features.Count);
                    sdw.Header = dbh;
                    sdw.Write(features);
                    WriteProjection(FileName, md.Zone);

                    //points
                    FileName = _File + "_NavUnAdj_Points";
                    geoFac = new GeometryFactory();
                    sdw = new ShapefileDataWriter(FileName, geoFac);
                    features = new ArrayList();
                    attTable["Poly"] = "Navigation UnAdjusted Points";

                    features = GetPointFeatures(points.Where(p => p.IsNavPoint()), false, DAL, metas);

                    if (features.Count > 0)
                    {
                        dbh = ShapefileDataWriter.GetHeader((Feature)features[0], features.Count);
                        sdw.Header = dbh;
                        sdw.Write(features);
                        WriteProjection(FileName, md.Zone);
                    }
                }
                #endregion

                #endregion

                #region Boundary

                #region Adj Line
                if (BAdjCoords.Count > 1)
                {
                    FileName = _File + "_BndAdjLine";
                    geoFac = new GeometryFactory();
                    sdw = new ShapefileDataWriter(FileName, geoFac);
                    features = new ArrayList();
                    attTable["Poly"] = "Boundary Adjusted Line";
                    feat = new Feature();
                    feat.Geometry = new NetTopologySuite.Geometries.LineString(BAdjCoords.ToArray());
                    feat.Attributes = attTable;

                    features.Add(feat);

                    dbh = ShapefileDataWriter.GetHeader((Feature)features[0], features.Count);
                    sdw.Header = dbh;
                    sdw.Write(features);
                    WriteProjection(FileName, md.Zone);
                }
                #endregion

                #region UnAdj Line
                if (BUnAdjCoords.Count > 1)
                {
                    FileName = _File + "_BndUnAdjLine";
                    geoFac = new GeometryFactory();
                    sdw = new ShapefileDataWriter(FileName, geoFac);
                    features = new ArrayList();
                    attTable["Poly"] = "Boundary UnAdjusted Line";
                    feat = new Feature();
                    feat.Geometry = new NetTopologySuite.Geometries.LineString(BUnAdjCoords.ToArray());
                    feat.Attributes = attTable;

                    features.Add(feat);

                    dbh = ShapefileDataWriter.GetHeader((Feature)features[0], features.Count);
                    sdw.Header = dbh;
                    sdw.Write(features);
                    WriteProjection(FileName, md.Zone);
                }
                #endregion

                #region Adj
                if (BAdjCoords.Count > 3)
                {
                    FileName = _File + "_BndAdj";
                    geoFac = new GeometryFactory();
                    sdw = new ShapefileDataWriter(FileName, geoFac);
                    features = new ArrayList();
                    attTable.AddAttribute("Area_MtSq", poly.Area);
                    attTable["Poly"] = "Boundary Adjusted";
                    feat = new Feature();

                    if (BAdjCoords[0] != BAdjCoords[BAdjCoords.Count - 1])
                        BAdjCoords.Add(BAdjCoords[0]);

                    feat.Geometry = new NetTopologySuite.Geometries.Polygon(new NetTopologySuite.Geometries.LinearRing(BAdjCoords.ToArray()));
                    feat.Attributes = attTable;

                    features.Add(feat);

                    dbh = ShapefileDataWriter.GetHeader((Feature)features[0], features.Count);
                    sdw.Header = dbh;
                    sdw.Write(features);
                    WriteProjection(FileName, md.Zone);

                    //points
                    FileName = _File + "_BndAdj_Points";
                    geoFac = new GeometryFactory();
                    sdw = new ShapefileDataWriter(FileName, geoFac);
                    features = new ArrayList();
                    attTable["Poly"] = "Boundary Adjusted Points";

                    features = GetPointFeatures(points.Where(p => p.IsBndPoint()), true, DAL, metas);

                    if (features.Count > 0)
                    {
                        dbh = ShapefileDataWriter.GetHeader((Feature)features[0], features.Count);
                        sdw.Header = dbh;
                        sdw.Write(features);
                        WriteProjection(FileName, md.Zone);
                    }
                }
                #endregion

                #region UnAdj
                if (BUnAdjCoords.Count > 3)
                {
                    FileName = _File + "_BndUnAdj";
                    geoFac = new GeometryFactory();
                    sdw = new ShapefileDataWriter(FileName, geoFac);
                    features = new ArrayList();
                    attTable["Poly"] = "Boundary UnAdjusted";
                    feat = new Feature();

                    if (BUnAdjCoords[0] != BUnAdjCoords[BUnAdjCoords.Count - 1])
                        BUnAdjCoords.Add(BUnAdjCoords[0]);

                    feat.Geometry = new NetTopologySuite.Geometries.Polygon(new LinearRing(BUnAdjCoords.ToArray()));
                    feat.Attributes = attTable;

                    features.Add(feat);

                    dbh = ShapefileDataWriter.GetHeader((Feature)features[0], features.Count);
                    sdw.Header = dbh;
                    sdw.Write(features);
                    WriteProjection(FileName, md.Zone);

                    //points
                    FileName = _File + "_BndUnAdj_Points";
                    geoFac = new GeometryFactory();
                    sdw = new ShapefileDataWriter(FileName, geoFac);
                    features = new ArrayList();
                    attTable["Poly"] = "Boundary UnAdjusted Points";

                    features = GetPointFeatures(points.Where(p => p.IsBndPoint()), false, DAL, metas);

                    if (features.Count > 0)
                    {
                        dbh = ShapefileDataWriter.GetHeader((Feature)features[0], features.Count);
                        sdw.Header = dbh;
                        sdw.Write(features);
                        WriteProjection(FileName, md.Zone);
                    }
                }
                #endregion

                #region WayPoints
                if (hasWayPoints)
                {
                    //points
                    FileName = _File + "_WayPoints";
                    geoFac = new GeometryFactory();
                    sdw = new ShapefileDataWriter(FileName, geoFac);
                    features = new ArrayList();
                    attTable["Poly"] = "WayPoints";

                    features = GetPointFeatures(points.Where(p => p.op == OpType.WayPoint), false, DAL, metas);

                    if (features.Count > 0)
                    {
                        dbh = ShapefileDataWriter.GetHeader((Feature)features[0], features.Count);
                        sdw.Header = dbh;
                        sdw.Write(features);
                        WriteProjection(FileName, md.Zone);
                    }
                }
                #endregion
                #endregion
            }
            #endif
        }
 private Coordinate[] CollapseLine()
 {
     var coordList = new CoordinateList();
     for (int i = 0; i < _inputLine.Length; i++)
     {
         if (_isDeleted[i] != Delete)
             coordList.Add(_inputLine[i]);
     }
     //    if (coordList.size() < inputLine.length)      System.out.println("Simplified " + (inputLine.length - coordList.size()) + " pts");
     return coordList.ToCoordinateArray();
 }
示例#54
0
        static void Main()
        {
            // Create a new coordinate with some values
            Coordinate c = new Coordinate();
            c.SetDMS(00, 10, 20.8f, true, 30, 40, 50.9f, false);

            // Create a new coordinate list with
            CoordinateList cl = new CoordinateList();
            cl.Add(new Coordinate( 1.0f, 1.0f));
            cl.Add(new Coordinate(-2.4f, 1.5f));
            cl.Add(new Coordinate(-3.7f, 2.2f));
            cl.Add(new Coordinate(-2.0f, -.5f));

            // Show formatting capabilities
            MessageBox.Show(
                string.Format("String Formatting:\r\nD: {0:D}\r\nDM: {0:DM}\r\nDMS: {0:DMS}\r\nISO: {0:ISO}", c),
                "Formatting example");

            // Serialize coordinates to a string object
            System.Text.StringBuilder sb = new System.Text.StringBuilder();
            System.IO.StringWriter sw = new System.IO.StringWriter(sb);
            string part1, part2;

            // Single coordinate
            System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(Coordinate));
            xs.Serialize(sw, c);
            sw.Flush();
            part1 = sb.ToString();

            // Coordinate list
            sb.Length = 0;
            System.Xml.Serialization.XmlSerializer xsl = new System.Xml.Serialization.XmlSerializer(typeof(CoordinateList));
            xsl.Serialize(sw, cl);
            sw.Flush();
            part2 = sb.ToString();

            sw.Close();

            // Show serialized data
            MessageBox.Show(string.Format("Single coordinate:\r\n{0}\r\n\r\nCoordinate list:\r\n{1}", part1, part2),
                "Serialization example");

            // Deserialize single coordinate from a string object
            System.IO.StringReader sr = new System.IO.StringReader(part1);
            Coordinate c1 = (Coordinate)xs.Deserialize(sr);
            sr.Close();

            // Deserialize coordinate list from a string object
            sr = new System.IO.StringReader(part2);
            CoordinateList cl1 = (CoordinateList)xsl.Deserialize(sr);
            sr.Close();

            // Show properties of deserialized data
            string message = string.Format(
                "Single coordinate:\r\n{0}\r\nLatitude: {1}°\r\nLongitude: {2}°\r\n\r\nCoordinate list:\r\n",
                c1, c1.Latitude, c1.Longitude);
            foreach (Coordinate coord in cl1)
                message += coord.ToString() + "\r\n";

            MessageBox.Show(message, "Deserialization example");
        }
示例#55
0
        /// <summary>
        /// Reads a stream and converts the shapefile record to an equilivent geometry object.
        /// </summary>
        /// <param name="file">The stream to read.</param>
        /// <param name="geometryFactory">The geometry factory to use when making the object.</param>
        /// <returns>The Geometry object that represents the shape file record.</returns>
        public override IGeometry Read(BigEndianBinaryReader file, IGeometryFactory geometryFactory)
        {
            int shapeTypeNum = file.ReadInt32();
            ShapeGeometryTypes shapeType = (ShapeGeometryTypes)Enum.Parse(typeof(ShapeGeometryTypes), shapeTypeNum.ToString());

            if (shapeType == ShapeGeometryTypes.NullShape)
                return null;

            if( ! ( shapeType == ShapeGeometryTypes.LineString  || shapeType == ShapeGeometryTypes.LineStringM   ||
                    shapeType == ShapeGeometryTypes.LineStringZ || shapeType == ShapeGeometryTypes.LineStringZM  ))
                throw new ShapefileException("Attempting to load a non-arc as arc.");

            //read and for now ignore bounds.
            double[] box = new double[4];
            for (int i = 0; i < 4; i++)
            {
                double d= file.ReadDouble();
                box[i] =d;
            }

            int numParts = file.ReadInt32();
            int numPoints = file.ReadInt32();
            int[] partOffsets = new int[numParts];
            for (int i = 0; i < numParts; i++)
                partOffsets[i] = file.ReadInt32();

            ILineString[] lines = new ILineString[numParts];
            int start, finish, length;
            for (int part = 0; part < numParts; part++)
            {
                start = partOffsets[part];
                if (part == numParts - 1)
                     finish = numPoints;
                else finish = partOffsets[part + 1];
                length = finish - start;
                CoordinateList points = new CoordinateList();
                points.Capacity=length;
                ICoordinate external;
                for (int i = 0; i < length; i++)
                {
                    external = new Coordinate(file.ReadDouble(),file.ReadDouble());
                    geometryFactory.PrecisionModel.MakePrecise( external);
                    points.Add(external);
                }
                if (numPoints < 2)
                    lines[part] = geometryFactory.CreateLineString(null as Topology.Geometries.ICoordinate[]);
                else
                    lines[part] = geometryFactory.CreateLineString(points.ToArray());
            }

            //If we have Z-coordinates, read them..
            if (shapeType == ShapeGeometryTypes.LineStringZ || shapeType == ShapeGeometryTypes.LineStringZM)
            {
                //z-Bounds
                double zMin = file.ReadDouble();
                double zMax = file.ReadDouble();
                for (int part = 0; part < numParts; part++)
                {
                    start = partOffsets[part];
                    if (part == numParts - 1)
                        finish = numPoints;
                    else finish = partOffsets[part + 1];
                    length = finish - start;
                    for (int i = 0; i < length; i++)
                    {
                        double val = file.ReadDouble();
                        if (numPoints > 1)
                        {

                            lines[part].Coordinates[i].Z = val;
                        }
                    }

                }
            }

            //If we have M-coordinates, read them..
            if (shapeType == ShapeGeometryTypes.LineStringM || shapeType == ShapeGeometryTypes.LineStringZM)
            {
                //m-Bounds
                double mMin = file.ReadDouble();
                double mMax = file.ReadDouble();
                for (int part = 0; part < numParts; part++)
                {
                    start = partOffsets[part];
                    if (part == numParts - 1)
                        finish = numPoints;
                    else finish = partOffsets[part + 1];
                    length = finish - start;
                    for (int i = 0; i < length; i++)
                    {
                        double val = file.ReadDouble();
                        //dont store..
                    }

                }
            }

            return geometryFactory.CreateMultiLineString(lines);
        }
示例#56
0
 /// <summary>
 /// 
 /// </summary>
 /// <param name="coords"></param>
 /// <param name="isForward"></param>
 /// <param name="coordList"></param>
 private static void AddEdge(Coordinate[] coords, bool isForward, CoordinateList coordList)
 {
     if (isForward)
     {
         for (int i = 0; i < coords.Length; i++)
             coordList.Add(coords[i], false);                
     }
     else
     {
         for (int i = coords.Length - 1; i >= 0; i--)                
             coordList.Add(coords[i], false);                
     }
 }
示例#57
0
        CoordinateList<byte> GetControlPoints()
        {
            ObjcParameter objc = _adjustment[0] as ObjcParameter;

              ReferenceParameter obj = objc.Parameters["Chnl"] as
            ReferenceParameter;

              ListParameter curve = objc.Parameters["Crv"] as ListParameter;

              CoordinateList<byte> controlPoints = new CoordinateList<byte>();

              // Dirty hack. Fixme!
              if (curve == null)
            return controlPoints;

              foreach (Parameter parameter in curve)
            {
              ObjcParameter point = parameter as ObjcParameter;
              double x =
            (point.Parameters["Hrzn"] as DoubleParameter).Value;
              double y =
            (point.Parameters["Vrtc"] as DoubleParameter).Value;

              controlPoints.Add(new Coordinate<byte>((byte) x, (byte) y));
            }

              return controlPoints;
        }
示例#58
0
        /// <summary>
        /// Snap segments of the source to nearby snap vertices.
        /// Source segments are "cracked" at a snap vertex, and further
        /// snapping takes place on the modified list of segments.
        /// For each distinct snap vertex, at most one source segment
        /// is snapped to.  This prevents "cracking" multiple segments 
        /// at the same point, which would almost certainly cause the result to be invalid.
        /// </summary>
        /// <param name="srcCoords"></param>
        /// <param name="snapPts"></param>
        private void SnapSegments(CoordinateList srcCoords, ICoordinate[] snapPts)
        {
            int distinctPtCount = snapPts.Length;

            // check for duplicate snap pts.  
            // Need to do this better - need to check all points for dups (using a Set?)
            if (snapPts[0].Equals2D(snapPts[snapPts.Length - 1]))
                distinctPtCount = snapPts.Length - 1;

            for (int i = 0; i < distinctPtCount; i++)
            {
                ICoordinate snapPt = snapPts[i];
                int index = FindSegmentIndexToSnap(snapPt, srcCoords);
                /**
                 * If a segment to snap to was found, "crack" it at the snap pt.
                 * The new pt is inserted immediately into the src segment list,
                 * so that subsequent snapping will take place on the latest segments.
                 * Duplicate points are not added.
                 */
                if (index >= 0)
                    srcCoords.Add(index + 1, new Coordinate(snapPt), false);
            }
        }
示例#59
0
        private static IGeometry CreateS(IGeometry g)
        {
            var gf = FunctionsUtil.GetFactoryOrDefault(g);

            double centreX = WIDTH - S_RADIUS;

            var top = new[]
                          {
                              new Coordinate(WIDTH, HEIGHT),
                              new Coordinate(centreX, HEIGHT)
                          };
            var bottom = new[]
                             {
                                 new Coordinate(centreX, 0),
                                 new Coordinate(WIDTH - 2*S_RADIUS, 0)
                             };

            var gsf = new GeometricShapeFactory(gf);
            gsf.Centre = new Coordinate(centreX, HEIGHT - S_RADIUS);
            gsf.Size = 2 * S_RADIUS;
            gsf.NumPoints = 10;
            var arcTop = gsf.CreateArc(0.5 * Math.PI, Math.PI);

            var gsf2 = new GeometricShapeFactory(gf);
            gsf2.Centre = new Coordinate(centreX, S_RADIUS);
            gsf2.Size = 2 * S_RADIUS;
            gsf2.NumPoints = 10;
            var arcBottom = (ILineString)((IGeometry)gsf2.CreateArc(1.5 * Math.PI, Math.PI)).Reverse();

            var coordList = new CoordinateList();
            coordList.Add(top, false);
            coordList.Add(arcTop.Coordinates, false, 1, arcTop.NumPoints - 1);
            coordList.Add(new Coordinate(centreX, HEIGHT / 2));
            coordList.Add(arcBottom.Coordinates, false, 1, arcBottom.NumPoints - 1);
            coordList.Add(bottom, false);

            return gf.CreateLineString(coordList.ToCoordinateArray());
        }
        /// <summary>
        /// Assumes input is valid 
        /// (e.g. <paramref name="start" /> minor or equals to <paramref name="end" />).
        /// </summary>
        /// <param name="start"></param>
        /// <param name="end"></param>
        /// <returns></returns>
        private ILineString ComputeLine(LinearLocation start, LinearLocation end)
        {
            ICoordinate[] coordinates = line.Coordinates;
            CoordinateList newCoordinates = new CoordinateList();

            int startSegmentIndex = start.SegmentIndex;
            if (start.SegmentFraction > 0.0)
                startSegmentIndex += 1;
            int lastSegmentIndex = end.SegmentIndex;
            if (end.SegmentFraction == 1.0)
                lastSegmentIndex += 1;
            if (lastSegmentIndex >= coordinates.Length)
                lastSegmentIndex = coordinates.Length - 1;
            // not needed - LinearLocation values should always be correct
            // Assert.IsTrue(end.SegmentFraction <= 1.0, "invalid segment fraction value");

            if (!start.IsVertex)
                newCoordinates.Add(start.GetCoordinate(line));
            for (int i = startSegmentIndex; i <= lastSegmentIndex; i++)
                newCoordinates.Add(coordinates[i]);            
            if (!end.IsVertex)
                newCoordinates.Add(end.GetCoordinate(line));

            // ensure there is at least one coordinate in the result
            if (newCoordinates.Count <= 0)
                newCoordinates.Add(start.GetCoordinate(line));

            ICoordinate[] newCoordinateArray = newCoordinates.ToCoordinateArray();

            /*
             * Ensure there is enough coordinates to build a valid line.
             * Make a 2-point line with duplicate coordinates, if necessary.
             * There will always be at least one coordinate in the coordList.
             */
            if (newCoordinateArray.Length <= 1)
                newCoordinateArray = new ICoordinate[] { newCoordinateArray[0], newCoordinateArray[0] };
            
            return line.Factory.CreateLineString(newCoordinateArray);
        }