Exemplo n.º 1
0
        /// <summary>
        /// Finds a src segment which snaps to (is close to) the given snap point
        /// Only one segment is determined - this is to prevent
        /// snapping to multiple segments, which would almost certainly cause invalid geometry
        /// to be created.
        /// (The heuristic approach of snapping is really only appropriate when
        /// snap pts snap to a unique spot on the src geometry)
        /// </summary>
        /// <param name="snapPt"></param>
        /// <param name="srcCoords"></param>
        /// <returns>-1 if no segment snaps.</returns>
        private int FindSegmentIndexToSnap(ICoordinate snapPt, CoordinateList srcCoords)
        {
            double minDist   = Double.MaxValue;
            int    snapIndex = -1;

            for (int i = 0; i < srcCoords.Count - 1; i++)
            {
                seg.P0 = srcCoords[i];
                seg.P1 = srcCoords[i + 1];

                /**
                 * If the snap pt is already in the src list, don't snap
                 */
                if (seg.P0.Equals2D(snapPt) || seg.P1.Equals2D(snapPt))
                {
                    return(-1);
                }

                double dist = seg.Distance(snapPt);
                if (dist < snapTolerance && dist < minDist)
                {
                    minDist   = dist;
                    snapIndex = i;
                }
            }
            return(snapIndex);
        }
        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());
            }
        }
Exemplo n.º 3
0
        public void equals_false(int[] coords1, int[] coords2)
        {
            CoordinateList cg1 = new CoordinateList(coords1);
            CoordinateList cg2 = new CoordinateList(coords2);

            Assert.False(cg1.Equals(cg2));
        }
 public static CoordinateList Unique(Coordinate[] coords)
 {
     var coordsCopy = CoordinateArrays.CopyDeep(coords);
     Array.Sort(coordsCopy);
     var coordList = new CoordinateList(coordsCopy, false);
     return coordList;
 }
Exemplo n.º 5
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);
        }
Exemplo n.º 6
0
        public bool isAchsenSegmentModelValid(AchsenSegmentModel achsenSegmentModel, string geoJsonString)
        {
            AchsenSegmentModel model = GenerateAchsenSegmentModelFromGeoJsonString(achsenSegmentModel);
            var      isValid         = true;
            Envelope maxExtent       = GisConstants.MaxExtent;

            foreach (Coordinate coord in model.Shape.Coordinates)
            {
                if (!(coord.X >= maxExtent.MinX && coord.X <= maxExtent.MaxX && coord.Y >= maxExtent.MinY && coord.Y <= maxExtent.MaxY))
                {
                    isValid = false;
                }
            }
            if (!model.Shape.IsSimple)
            {
                isValid = false;
            }
            CoordinateList list = new CoordinateList(model.Shape.Coordinates, false);

            if (list.Count <= 1)
            {
                isValid = false;
            }

            return(isValid);
        }
Exemplo n.º 7
0
        public void get_intersecting_blocks_true(CoordinateList reference_cells, List <CoordinateList> expected_coords, string message)
        {
            List <CoordinateList> block_coords = SudokuGrid.get_intersecting_blocks(reference_cells);

            bool match_found         = false;
            bool match_found_for_all = true;

            foreach (CoordinateList expected_block in expected_coords)
            {
                match_found = false;
                foreach (CoordinateList found_block in block_coords)
                {
                    if (expected_block.Equals(found_block))
                    {
                        match_found = true;
                    }
                }

                if (!match_found)
                {
                    match_found_for_all = false;
                }
            }

            Assert.True(match_found_for_all && (expected_coords.Count() == block_coords.Count()), $"{message}; matches found={match_found_for_all}; expected count={expected_coords.Count()}; found count={block_coords.Count()}");
        }
Exemplo n.º 8
0
        public async Task <IActionResult> PutAsync(int id, [FromBody] CoordinateList value)
        {
            if (!ModelState.IsValid || value == null)
            {
                return(new BadRequestObjectResult(ModelState));
            }

            var existingList = await _service.GetList(id).ConfigureAwait(false);

            if (existingList == null)
            {
                return(new NotFoundResult());
            }

            var validator        = new CoordinateListValidator();
            var validationResult = validator.Validate(value);

            if (!validationResult.IsValid)
            {
                return(new BadRequestObjectResult(MapValidationResultToModelState(validationResult)));
            }

            var result = await _service.SaveList(value.ToCoordinateListEntity(id)).ConfigureAwait(false);

            return(new ObjectResult(result.ToCoordinateListDto()));
        }
        /// <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);
                }
            }
        }
Exemplo n.º 10
0
        public void TestLoadCoordinates_CRLF()
        {
            string xml = @"<?xml version=""1.0"" encoding=""UTF-8""?>
                <kml xmlns=""http://www.opengis.net/kml/2.2"" xmlns:gx=""http://www.google.com/kml/ext/2.2"">
                <Placemark>
                    <LineString>
                        <coordinates>
                        134.1754575,34.48808388888889,2
                        134.182555,34.484685,4
                        </coordinates>
                    </LineString>
                </Placemark>
                </kml>";

            CoordinateList list = sut.load(xml);

            System.Collections.IEnumerator enumerator = list.Iter().GetEnumerator();
            enumerator.MoveNext();
            Coordinate coordinate1 = (Coordinate)enumerator.Current;

            enumerator.MoveNext();
            Coordinate coordinate2 = (Coordinate)enumerator.Current;

            Assert.AreEqual(134.1754575, coordinate1.Longitude);
            Assert.AreEqual(34.48808388888889, coordinate1.Latitude);
            Assert.AreEqual(2, coordinate1.Altitude);

            Assert.AreEqual(134.182555, coordinate2.Longitude);
            Assert.AreEqual(34.484685, coordinate2.Latitude);
            Assert.AreEqual(4, coordinate2.Altitude);
        }
Exemplo n.º 11
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);
        }
Exemplo n.º 12
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++;
              }
            };
        }
        /// <summary>
        /// Terminate the current <see cref="LineString" />.
        /// </summary>
        public void EndLine()
        {
            if (_coordList == null)
                return;
            
            if (IgnoreInvalidLines && _coordList.Count < 2)
            {
                _coordList = null;
                return;
            }

            Coordinate[] rawPts = _coordList.ToCoordinateArray();
            Coordinate[] pts = rawPts;
            if (FixInvalidLines)
                pts = ValidCoordinateSequence(rawPts);

            _coordList = null;
            ILineString line = null;
            try
            {
                line = _geomFact.CreateLineString(pts);
            }
            catch (ArgumentException ex)
            {
                // exception is due to too few points in line.
                // only propagate if not ignoring short lines
                if (!IgnoreInvalidLines)
                    throw ex;
            }

            if (line != null) 
                _lines.Add(line);
        }
Exemplo n.º 14
0
 static public CoordinateListDto Map(CoordinateList coordinateList)
 {
     return(new CoordinateListDto
     {
         Id = coordinateList.Id
     });
 }
Exemplo n.º 15
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);
        }
Exemplo n.º 16
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());
        }
Exemplo n.º 17
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);
        }
Exemplo n.º 18
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);
        }
Exemplo n.º 19
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);
                }
            }
        }
Exemplo n.º 20
0
 public static Entities.CoordinateList ToCoordinateListEntity(this CoordinateList list, int id)
 {
     return(new Entities.CoordinateList(
                id,
                list.Name,
                list.Coordinates != null ? list.Coordinates.ToCoordinateEntitySet() : new HashSet <Entities.Coordinate>()));
 }
        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()));
        }
Exemplo n.º 22
0
        ///** Convience method for STRUCT construction. */
        //private STRUCT toSTRUCT( Datum attributes[], String dataType )
        //        throws SQLException
        //{
        //    if( dataType.startsWith("*.")){
        //        dataType = "DRA."+dataType.substring(2);//TODO here
        //    }
        //    StructDescriptor descriptor =
        //        StructDescriptor.createDescriptor( dataType, connection );

        //     return new STRUCT( descriptor, connection, attributes );
        //}

        ///**
        // * Convience method for ARRAY construction.
        // * <p>
        // * Compare and contrast with toORDINATE - which treats <code>Double.NaN</code>
        // * as<code>NULL</code></p>
        // */
        //private ARRAY toARRAY( double doubles[], String dataType )
        //        throws SQLException
        //{
        //    ArrayDescriptor descriptor =
        //        ArrayDescriptor.createDescriptor( dataType, connection );

        //     return new ARRAY( descriptor, connection, doubles );
        //}

        ///**
        // * Convience method for ARRAY construction.
        // */
        //private ARRAY toARRAY( int ints[], String dataType )
        //    throws SQLException
        //{
        //    ArrayDescriptor descriptor =
        //        ArrayDescriptor.createDescriptor( dataType, connection );

        //     return new ARRAY( descriptor, connection, ints );
        //}

        ///**
        // * Convience method for NUMBER construction.
        // * <p>
        // * Double.NaN is represented as <code>NULL</code> to agree
        // * with JTS use.</p>
        // */
        //private NUMBER toNUMBER( double number ) throws SQLException{
        //    if( Double.isNaN( number )){
        //        return null;
        //    }
        //    return new NUMBER( number );
        //}

        /**
         * reverses the coordinate order
         *
         * @param factory
         * @param sequence
         *
         * @return CoordinateSequence reversed sequence
         */
        private ICoordinateSequence reverse(ICoordinateSequenceFactory factory, ICoordinateSequence sequence)
        {
            var list = new CoordinateList(sequence.ToCoordinateArray());

            list.Reverse();
            return(factory.Create(list.ToCoordinateArray()));
        }
Exemplo n.º 23
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>
        /// Finds a src segment which snaps to (is close to) the given snap point<para/>
        /// Only a single segment is selected for snapping.
        /// This prevents multiple segments snapping to the same snap vertex,
        /// which would almost certainly cause invalid geometry
        /// to be created.
        /// (The heuristic approach of snapping used here
        /// is really only appropriate when
        /// snap pts snap to a unique spot on the src geometry)<para/>
        /// Also, if the snap vertex occurs as a vertex in the src coordinate list,
        /// no snapping is performed.
        /// </summary>
        /// <param name="snapPt">The point to snap to</param>
        /// <param name="srcCoords">The source segment coordinates</param>
        /// <returns>The index of the snapped segment <br/>
        /// or -1 if no segment snaps to the snap point.</returns>
        private int FindSegmentIndexToSnap(Coordinate snapPt, CoordinateList srcCoords)
        {
            var minDist   = Double.MaxValue;
            var snapIndex = -1;

            for (var i = 0; i < srcCoords.Count - 1; i++)
            {
                _seg.P0 = srcCoords[i];
                _seg.P1 = srcCoords[i + 1];

                /*
                 * Check if the snap pt is equal to one of the segment endpoints.
                 *
                 * If the snap pt is already in the src list, don't snap at all.
                 */
                if (_seg.P0.Equals2D(snapPt) || _seg.P1.Equals2D(snapPt))
                {
                    if (_allowSnappingToSourceVertices)
                    {
                        continue;
                    }
                    return(-1);
                }

                var dist = _seg.Distance(snapPt);
                if (dist < _snapTolerance && dist < minDist)
                {
                    minDist   = dist;
                    snapIndex = i;
                }
            }
            return(snapIndex);
        }
Exemplo n.º 25
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();
 }
Exemplo n.º 26
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);
        }
Exemplo n.º 27
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);
        }
Exemplo n.º 28
0
        private void AddLine(CoordinateList line)
        {
            Coordinate[] array = line.ToCoordinateArray();
            ILineString  ls    = _factory.CreateLineString(array);

            _lines.Add(ls);
        }
Exemplo n.º 29
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());
        }
Exemplo n.º 30
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);
        }
Exemplo n.º 31
0
        /// <summary>
        /// Limits a list of segments.
        /// </summary>
        /// <param name="pts">The segment sequence to limit</param>
        /// <returns>The sections which intersect the limit envelope</returns>
        public List <Coordinate[]> Limit(IEnumerable <Coordinate> pts)
        {
            if (pts == null)
            {
                throw new ArgumentNullException(nameof(pts));
            }

            _lastOutside = null;
            _ptList      = null;
            _sections    = new List <Coordinate[]>();

            foreach (var p in pts)
            {
                if (_limitEnv.Intersects(p))
                {
                    AddPoint(p);
                }
                else
                {
                    AddOutside(p);
                }
            }
            // finish last section, if any
            FinishSection();
            return(_sections);
        }
 /// <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;
 }
Exemplo n.º 33
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++;
                }
            };
        }
        public void IsInRing_ThrowsArgumentExceptionIfCoordinateListDoesNotRepresentRing()
        {
            Coordinate         c      = new Coordinate(0, 0);
            CoordinateList     ring   = new CoordinateList(new Coordinate[] { new Coordinate(0, 1), new Coordinate(1, 0), new Coordinate(1, 2) });
            Euclidean2DLocator target = new Euclidean2DLocator();

            Assert.Throws <ArgumentException>(() => target.IsInRing(c, ring));
        }
 /// <summary>
 /// Snaps the vertices and segments of the source LineString
 /// to the given set of snap points.
 /// </summary>
 /// <param name="snapPts">the vertices to snap to</param>
 /// <returns>list of the snapped points</returns>
 public Coordinate[] SnapTo(Coordinate[] snapPts)
 {
     CoordinateList coordList = new CoordinateList(_srcPts);
     SnapVertices(coordList, snapPts);
     SnapSegments(coordList, snapPts);
     Coordinate[] newPts = coordList.ToCoordinateArray();
     return newPts;
 }
        public void IsInRing_ThrowsArgumentExceptionIfRingHasLessThen3Points()
        {
            Coordinate         c      = new Coordinate(0, 0);
            CoordinateList     ring   = new CoordinateList(new Coordinate[] { new Coordinate(0, 1), new Coordinate(1, 0) });
            Euclidean2DLocator target = new Euclidean2DLocator();

            Assert.Throws <ArgumentException>(() => target.IsInRing(c, ring));
        }
        public async Task <IActionResult> GetCoordinateList(int coordinateListId)
        {
            Squares.Models.Coordinates.CoordinateList createdCoordinateList = await _coordinateService.GetCoordinateList(coordinateListId).ConfigureAwait(false);

            CoordinateList apiCoordinateList = Mapper.Map(createdCoordinateList);

            return(Ok(apiCoordinateList));
        }
Exemplo n.º 38
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);
        }
Exemplo n.º 39
0
        public override bool Execute()
        {
            CoordinateList<byte> controlPoints = new CoordinateList<byte>() {
            new Coordinate<byte>(0, 0),
            new Coordinate<byte>(127, 127),
            new Coordinate<byte>(255, 0)};

              ActiveDrawable.CurvesSpline(HistogramChannel.Value, controlPoints);
              return true;
        }
Exemplo n.º 40
0
 public void Select(CoordinateList<double> segs, ChannelOps operation, 
     bool antialias, bool feather, double featherRadius)
 {
     var array = segs.ToArray();
       if (!gimp_free_select(_imageID, array.Length, array, operation,
         antialias, feather, featherRadius))
     {
       throw new GimpSharpException();
     }
 }
Exemplo n.º 41
0
        public CoordinateList<double> GetValues()
        {
            var list = new CoordinateList<double>();

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

              return list;
        }
Exemplo n.º 42
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;
        }
Exemplo n.º 43
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));
        }
Exemplo n.º 44
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>
        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();
        }
        /// <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();
        }
Exemplo n.º 47
0
 // [Test]
 public void Close()
 {
     var vectors = new Vectors(_image, "firstVector");
       var controlpoints = new CoordinateList<double>() {
     new Coordinate<double>(50, 50),
     new Coordinate<double>(100, 100),
     new Coordinate<double>(150, 150)
       };
       var stroke = vectors.NewFromPoints(VectorsStrokeType.Bezier,
              controlpoints, false);
       stroke.Close();
       bool closed;
       stroke.GetPoints(out closed);
       Assert.IsTrue(closed);
 }
Exemplo n.º 48
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);
        }
        public override Coordinate[] Edit(Coordinate[] coordinates, IGeometry geom)
        {
            if (coordinates.Length == 0)
                return null;

            var reducedCoords = new Coordinate[coordinates.Length];
            // copy coordinates and reduce
            for (int i = 0; i < coordinates.Length; i++)
            {
                var coord = new Coordinate(coordinates[i]);
                _targetPrecModel.MakePrecise(coord);
                reducedCoords[i] = coord;
            }
            // remove repeated points, to simplify returned geometry as much as possible
            var noRepeatedCoordList = new CoordinateList(reducedCoords,
                    false);
            var noRepeatedCoords = noRepeatedCoordList.ToCoordinateArray();

            /**
             * Check to see if the removal of repeated points collapsed the coordinate
             * List to an invalid length for the type of the parent geometry. It is not
             * necessary to check for Point collapses, since the coordinate list can
             * never collapse to less than one point. If the length is invalid, return
             * the full-length coordinate array first computed, or null if collapses are
             * being removed. (This may create an invalid geometry - the client must
             * handle this.)
             */
            int minLength = 0;
            if (geom is ILineString)
                minLength = 2;
            if (geom is ILinearRing)
                minLength = LinearRing.MinimumValidSize;

            Coordinate[] collapsedCoords = reducedCoords;
            if (_removeCollapsed)
                collapsedCoords = null;

            // return null or orginal length coordinate array
            if (noRepeatedCoords.Length < minLength)
            {
                return collapsedCoords;
            }

            // ok to return shorter coordinate array
            return noRepeatedCoords;
        }
Exemplo n.º 50
0
 /// <summary>
 /// Snap source vertices to vertices in the target.
 /// </summary>
 /// <param name="srcCoords"></param>
 /// <param name="snapPts"></param>
 private void SnapVertices(CoordinateList srcCoords, ICoordinate[] snapPts)
 {
     // try snapping vertices
     // assume src list has a closing point (is a ring)
     for (int i = 0; i < srcCoords.Count - 1; i++)
     {
         ICoordinate srcPt = srcCoords[i];
         ICoordinate snapVert = FindSnapForVertex(srcPt, snapPts);
         if (snapVert != null)
         {
             // update src with snap pt
             srcCoords[i] = new Coordinate(snapVert);
             // keep final closing point in synch (rings only)
             if (i == 0 && isClosed)
                 srcCoords[srcCoords.Count - 1] = new Coordinate(snapVert);
         }
     }
 }
Exemplo n.º 51
0
        public void GetPoints()
        {
            var vectors = new Vectors(_image, "firstVector");
              var controlpoints = new CoordinateList<double>() {
            new Coordinate<double>(50, 50),
            new Coordinate<double>(100, 100),
            new Coordinate<double>(150, 150)
              };
              var stroke = vectors.NewFromPoints(VectorsStrokeType.Bezier,
                     controlpoints, false);
              bool closed;

              // Fix me: this one segfaults
              // var points = stroke.GetPoints(out closed);
              // Assert.AreEqual(controlpoints.Count, points.Count);
              // Assert.AreEqual(controlpoints, points);
              // Assert.IsFalse(closed);
        }
Exemplo n.º 52
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);
		}
 /// <summary>
 /// Snap source vertices to vertices in the target.
 /// </summary>
 /// <param name="srcCoords">the points to snap</param>
 /// <param name="snapPts">the points to snap to</param>
 private void SnapVertices(CoordinateList srcCoords, Coordinate[] snapPts)
 {
     // try snapping vertices
     // if src is a ring then don't snap final vertex
     var end = _isClosed ? srcCoords.Count - 1 : srcCoords.Count;
     for (var i = 0; i < end; i++)
     {
         var srcPt = srcCoords[i];
         var snapVert = FindSnapForVertex(srcPt, snapPts);
         if (snapVert != null)
         {
             // update src with snap pt
             srcCoords[i] = new Coordinate(snapVert);
             // keep final closing point in synch (rings only)
             if (i == 0 && _isClosed)
                 srcCoords[srcCoords.Count - 1] = new Coordinate(snapVert);
         }
     }
 }
Exemplo n.º 54
0
        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);
        }
Exemplo n.º 55
0
        /// <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);
        }
Exemplo n.º 56
0
 private void AddLine(CoordinateList line)
 {
     Coordinate[] array = line.ToCoordinateArray();
     ILineString ls = _factory.CreateLineString(array);
     _lines.Add(ls);
 }
Exemplo n.º 57
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);
        }
Exemplo n.º 58
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);
        }
Exemplo n.º 59
0
 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();
 }
        /// <summary>
        /// Finds a src segment which snaps to (is close to) the given snap point<para/>
        /// Only a single segment is selected for snapping.
        /// This prevents multiple segments snapping to the same snap vertex,
        /// which would almost certainly cause invalid geometry
        /// to be created.
        /// (The heuristic approach of snapping used here
        /// is really only appropriate when
        /// snap pts snap to a unique spot on the src geometry)<para/>
        /// Also, if the snap vertex occurs as a vertex in the src coordinate list,
        /// no snapping is performed.
        /// </summary>
        /// <param name="snapPt">The point to snap to</param>
        /// <param name="srcCoords">The source segment coordinates</param>
        /// <returns>The index of the snapped segment <br/>
        /// or -1 if no segment snaps to the snap point.</returns>
        private int FindSegmentIndexToSnap(Coordinate snapPt, CoordinateList srcCoords)
        {
            var minDist = Double.MaxValue;
            var snapIndex = -1;
            for (var i = 0; i < srcCoords.Count - 1; i++)
            {
                _seg.P0 = srcCoords[i];
                _seg.P1 = srcCoords[i + 1];

                /*
                 * Check if the snap pt is equal to one of the segment endpoints.
                 *
                 * If the snap pt is already in the src list, don't snap at all.
                 */
                if (_seg.P0.Equals2D(snapPt) || _seg.P1.Equals2D(snapPt))
                {
                    if (_allowSnappingToSourceVertices)
                        continue;
                    return -1;
                }

                var dist = _seg.Distance(snapPt);
                if (dist < _snapTolerance && dist < minDist)
                {
                    minDist = dist;
                    snapIndex = i;
                }
            }
            return snapIndex;
        }