public static bool CircleIntersectSegment(LineSegment<Vector2> segment, Circle circle, out Vector2 intersection) { intersection = ClosestPointOnSegment(segment, circle.Position); var distance2 = DistanceSquared(intersection, circle.Position); if (distance2 <= circle.Radius * circle.Radius) return true; else return false; }
public static Point ProjectOnto(this Point p, LineSegment seg, LineType type, out int? end) { end = 0; Vector v = seg.Vector(); Vector w = p.Sub(seg.A); T c1 = w.Dot(v); // c1 == |w|*|v|*cos(angle between them) if (c1 <= 0) { // angle between line segment and (p-seg.A) is negative (-180..0)? if (v.X == 0 && v.Y == 0) { // seg.A == seg.B end = null; return seg.A; } else if (c1 < 0) end = -1; if (type != LineType.Infinite) return seg.A; } T c2 = v.Quadrance(); // == |v|*|v| if (c1 >= c2) { // quadrance from seg.A to projected point >= quadrance of seg if (c1 > c2) end = 1; if (type == LineType.Segment) return seg.B; } if (c2 == 0) { // seg.A and seg.B are infitessimally close together; c2 was truncated to zero end = null; return seg.A; } T frac = c1 / c2; // == |w|/|v|*cos(angle) Point projected = seg.A.Add(v.Mul(frac)); // == p0 + v/|v|*|w|*cos(angle) return projected; }
public LLMarkerRotated LLShape(DrawStyle style, ref LineSegment<Coord> toArrow) { Coord frac = Width * Scale / toArrow.Length(); var markerPoint = toArrow.PointAlong(1 - frac * 0.5f); toArrow = toArrow.A.To(toArrow.PointAlong(1 - Math.Min(frac, 1))); return new LLMarkerRotated(style, markerPoint, Scale, Geometry, (Coord)toArrow.Vector().AngleDeg()); }
public void CheckPaths(LineSegment line, Vector3 slot) { var p1 = line.p1 * divisions; var p2 = line.p2 * divisions; var th = 0.01f; th += 0.5f; if (p1.x == p2.x && p1.z != p2.z && p1.y == p2.y) // travels along z, stationary in x and y { var line2d = new Vector2(p1.x, p1.y); var slot2d = new Vector2(slot.x, slot.y); if (Vector2.Distance(line2d, slot2d) <= th) { if (p1.z < p2.z && p1.z <= slot.z - th && p2.z >= slot.z + th) MakeNew(slot, line); } } else if (p1.z == p2.z && p1.x != p2.x && p1.y == p2.y) // travels along x, stationary in z and y { var line2d = new Vector2(p1.y, p1.z); var slot2d = new Vector2(slot.y, slot.z); if (Vector2.Distance(line2d, slot2d) <= th) if (p1.x < p2.x && p1.x <= slot.x - th && p2.x >= slot.x + th) MakeNew(slot, line); } }
public bool CollidesWith(LineSegment lineSegment) { var axisA = new Line(Point1, Point2.Substract(Point1)); if (axisA.OnOneSide(lineSegment)) { return false; } var axisB = new Line(lineSegment.Point1, lineSegment.Point2.Substract(lineSegment.Point1)); if (axisB.OnOneSide(this)) { return false; } if (axisA.Direction.IsParallel(axisB.Direction)) { Range rangeA = ProjectOnto(axisA.Direction); Range rangeB = lineSegment.ProjectOnto(axisA.Direction); return rangeA.Overlaps(rangeB); } return true; }
public void ScanVoxels(LineSegment line, bool movesInX) { var divisions = cSectionGCD.sloxelResolution.x; var half = 0.5f / divisions; foreach (var v in cSectionGCD.voxels) { if (movesInX) { var x = v.Key.x; var v2d = new Vector2(v.Key.y, v.Key.z); var l2d = new Vector2(line.p1.y, line.p1.z); if (Mathf.Abs(v.Key.y - line.p1.y) <= half && Mathf.Abs(v.Key.z - line.p1.z) <= half) { if (line.p2.x > line.p1.x && line.p1.x < x + half && line.p2.x > x - half) // p2 greater than p1, p1 < x + half, p2 > x - half MakeNew(v.Value, line); else if (line.p2.x < line.p1.x && line.p1.x > x - half && line.p2.x < x + half) MakeNew(v.Value, line); } } else // Moves In Z { var z = v.Key.z; var v2 = new Vector2(v.Key.x, v.Key.y); var l2 = new Vector2(line.p1.x, line.p1.y); if (Mathf.Abs(v.Key.x - line.p1.x) <= half && Mathf.Abs(v.Key.y - line.p1.y) <= half) { if (line.p2.z > line.p1.z && line.p1.z < z + half && line.p2.z > z - half) // p2 greater than p1, p1 < x + half, p2 > x - half MakeNew(v.Value, line); else if (line.p2.z < line.p1.z && line.p1.z > z - half && line.p2.z < z + half) MakeNew(v.Value, line); } } } }
public void Test_SetLineWidth() { var line = new LineSegment (); line.Width = 2.0f; Assert.AreEqual (2.0f, line.Width); }
// Creates a polyline with two paths in the shape of an 'X' centered at the given point private Polyline CreatePolylineX(MapPoint center, double length) { var halfLen = length / 2.0; LineSegment segment = new LineSegment( new MapPoint(center.X - halfLen, center.Y + halfLen, MyMapView.SpatialReference), new MapPoint(center.X + halfLen, center.Y - halfLen, MyMapView.SpatialReference)); LineSegment segment2 = new LineSegment( new MapPoint(center.X + halfLen, center.Y + halfLen, MyMapView.SpatialReference), new MapPoint(center.X - halfLen, center.Y - halfLen, MyMapView.SpatialReference)); var segmentCollection = new SegmentCollection(MyMapView.SpatialReference) { segment }; var segmentCollection2 = new SegmentCollection(MyMapView.SpatialReference) { segment2 }; return new Polyline(new [] { segmentCollection, segmentCollection2}, MyMapView.SpatialReference); }
public PathStatistics(PathData data) { _data = data; int i = 1; _totalLength = 0; ISegment newSegment; while (i < _data.Points.Length) { switch (_data.Types[i]) { case 1: newSegment = new LineSegment(_data.Points[i - 1], _data.Points[i]); i++; break; case 3: newSegment = new CubicBezierSegment(_data.Points[i - 1], _data.Points[i], _data.Points[i + 1], _data.Points[i + 2]); i+= 3; break; default: throw new NotSupportedException(); } newSegment.StartOffset = _totalLength; _segments.Add(newSegment); _totalLength += newSegment.Length; } }
public void Test_SetLineLength() { var line = new LineSegment (); line.Length = 2; Assert.AreEqual (2.0f, line.Length); }
private void SetPlayShape() { play.Children.Clear (); Path p = new Path(); PathGeometry geometry = new PathGeometry (); PathFigure f = new PathFigure (); f.Segments = new PathSegmentCollection (); p.Data = geometry; p.Fill = new SolidColorBrush(Colors.Red); p.Stroke = new SolidColorBrush(Colors.Black); geometry.Figures = new PathFigureCollection (); geometry.Figures.Add(f); LineSegment m = new LineSegment(); m.Point = new Point(3, 2); f.Segments.Add(m); m = new LineSegment(); m.Point = new Point(14, 8.5); f.Segments.Add(m); m = new LineSegment(); m.Point = new Point(3, 15); f.Segments.Add(m); m = new LineSegment(); m.Point = new Point(3, 2); f.Segments.Add(m); play.Children.Add(p); }
/// <summary> /// Projects the specified line segment on the specified plane. /// </summary> /// <param name="lineSegment">A line segment.</param> /// <param name="plane">A plane.</param> /// <returns>The <paramref name="lineSegment"/> projected on the <paramref name="plane"/>.</returns> public static LineSegment LineSegmentOnPlane(LineSegment lineSegment, Plane plane) { return new LineSegment { End1 = Project.PointOnPlane(lineSegment.End1, plane), End2 = Project.PointOnPlane(lineSegment.End2, plane), }; }
/// <summary> /// Projects the specified line segment on the specified line segment. /// </summary> /// <param name="lineSegment1">A line segment.</param> /// <param name="lineSegment2">A line segment.</param> /// <returns>The <paramref name="lineSegment1"/> projected on the <paramref name="lineSegment2"/>.</returns> public static LineSegment LineSegmentOnLineSegment(LineSegment lineSegment1, LineSegment lineSegment2) { return new LineSegment { End1 = Project.PointOnLineSegment(lineSegment1.End1, lineSegment2), End2 = Project.PointOnLineSegment(lineSegment1.End2, lineSegment2), }; }
/// <summary> /// Projects the specified line segment on the specified line. /// </summary> /// <param name="lineSegment">A line segment.</param> /// <param name="line">A line.</param> /// <returns>The <paramref name="lineSegment"/> projected on the <paramref name="line"/>.</returns> public static LineSegment LineSegmentOnLine(LineSegment lineSegment, Line line) { return new LineSegment { End1 = Project.PointOnLine(lineSegment.End1, line), End2 = Project.PointOnLine(lineSegment.End2, line), }; }
public void Test_SetTexture() { var line = new LineSegment (); var tex = new Texture("abstract7.png"); line.Texture = tex; Assert.AreEqual (tex, line.Texture); }
public void LineSegmentProperties() { var line = new LineSegment(new Point(0, 1), new Point(1, 1)); line.AssertEquals(new LineSegment(new Point(0, 1), new Point(1, 1))); line.Start.AssertEquals(new Point(0, 1)); line.End.AssertEquals(new Point(1, 1)); line.Delta.AssertEquals(new Vector(1, 0)); }
public static Vector2 ClosestPointOnLine(LineSegment<Vector2> line, Vector2 point) { var ap = point - line.A; var ab = line.B - line.A; var ab2 = Vector2.Dot(ab, ab); var apab = Vector2.Dot(ap, ab); var t = apab / ab2; return line.A + ab * t; }
public void DistanceToPointTest( float x, float y, float x1, float y1, float x2, float y2, float expectedDistance ) { Point pt = new Point( x, y ); Point pt1 = new Point( x1, y1 ); Point pt2 = new Point( x2, y2 ); LineSegment segment = new LineSegment( pt1, pt2 ); Assert.AreEqual( expectedDistance, segment.DistanceToPoint( pt ) ); }
private void TestItsc(LineSegment<float> p, LineSegment<float> q, Point<float>? expected, float expect_pFrac, LineType pt = LineType.Segment, LineType qt = LineType.Segment) { float pFrac, qFrac; bool intersected = p.ComputeIntersection(pt, out pFrac, q, qt, out qFrac); Assert.AreEqual(expected.HasValue, intersected); Point<float>? result = p.ComputeIntersection(pt, q, qt); Assert.AreEqual(expected, result); Assert.AreEqual(expect_pFrac, pFrac); }
public void Test_New() { var line = new LineSegment (); Assert.AreEqual (1.0f, line.Width); Assert.AreEqual (10, line.Length); Assert.AreEqual (Color.White, line.Color); Assert.AreEqual (null, line.Texture); }
public void IntersectsWith() { var line1 = new LineSegment(new Point(0, 0), new Point(1, 0)); var line2 = new LineSegment(new Point(1, 1), new Point(2, 1)); Assert.IsFalse(line1.IntersectsWith(line2), "collinear"); var line3 = new LineSegment(new Point(1, 1), new Point(0, 0)); Assert.IsTrue(line1.IntersectsWith(line3), "intersecting"); var line4 = new LineSegment(new Point(1, 1), new Point(-1, 0)); Assert.IsFalse(line1.IntersectsWith(line4), "intersection is outside segment"); }
/// <summary> /// Method to rotate line segments in the XY-Cartesian plane counter-clockwise through a given angle. /// </summary> /// <param name="lineSegment">Line Segment object.</param> /// <param name="transformeAngle">Transformation angle in degrees.</param> /// <returns>Returns new LineSegment object which is the original point rotated around the Z-axis.</returns> public static LineSegment GetTransformedRectangle(LineSegment lineSegment, double rotationAngle) { double angleInRadians = rotationAngle * Math.PI / 180; double rotatedProjX = Math.Abs(Math.Cos(angleInRadians)) * lineSegment.ProjectionX + Math.Abs(Math.Sin(angleInRadians)) * lineSegment.ProjectionY; double rotatedProjY = Math.Abs(Math.Sin(angleInRadians)) * lineSegment.ProjectionX + Math.Abs(Math.Cos(angleInRadians)) * lineSegment.ProjectionY; LineSegment result = new LineSegment(rotatedProjX, rotatedProjY); return result; }
public bool CollidesWith(LineSegment lineSegment) { IVector2D d = lineSegment.Point2.Substract(lineSegment.Point1); IVector2D lp = Position.Substract(lineSegment.Point1); IVector2D pr = lp.ProjectOnto(d); return lp.Equals(pr) && pr.Length() <= d.Length() && pr.DotProduct(d) >= 0; }
/// <summary> /// /// </summary> /// <param name="querySeg"></param> /// <returns></returns> public virtual IList Query(LineSegment querySeg) { Envelope env = new Envelope(querySeg.P0, querySeg.P1); LineSegmentVisitor visitor = new LineSegmentVisitor(querySeg); _index.Query(env, visitor); IList itemsFound = visitor.Items; return itemsFound; }
public void Test_SetColor() { var line = new LineSegment (); line.Color = Color.Blue; Assert.AreEqual (Color.Blue, line.Color); line.SetColor (255, 0, 0, 255); Assert.AreEqual (Color.Red, line.Color); }
public static Vector2 ClosestPointOnSegment(LineSegment<Vector2> segment, Vector2 point) { var ap = point - segment.A; var ab = segment.B - segment.A; var ab2 = Vector2.Dot(ab, ab); var apab = Vector2.Dot(ap, ab); var t = apab / ab2; if (t < 0f) t = 0f; else if (t > 1f) t = 1f; return segment.A + ab * t; }
public GraphicLine(string name, int x1, int y1, int x2, int y2, uint color, int width) :base(name, x1,y1, x2-x1, y2-y1) { fLine = new LineG(new Point(x1, y1), new Point(x2, y2)); fWidth = width; fColor = color; // The weight is in points, so we need to convert to local units. // In this case, we'll go with inches. fPen = new GDIPen(PenType.Geometric, PenStyle.Solid, PenJoinStyle.Round, PenEndCap.Round, color, Frame.Width, Guid.NewGuid()); }
public Angle AngleBetweenPoints(Vector CenterPoint) { Vector endPointToCenter = new LineSegment(EndingPos, CenterPoint).TranlsateToVector(); Vector incomingVector = new LineSegment(EndingPos, StartingPos).TranlsateToVector(); if ((endPointToCenter.Magnitude() * incomingVector.Magnitude() == 0)) throw new DivideByZeroException(); double cosineOfTheAngle = (incomingVector * endPointToCenter) / (endPointToCenter.Magnitude() * incomingVector.Magnitude()); if (cosineOfTheAngle > 1 || cosineOfTheAngle < -1) throw new Exception("Out of range of acos"); Angle angleToReturn = new Angle(Math.Acos(cosineOfTheAngle)); return angleToReturn; }
public static int CompareLengths_MAX (LineSegment segment0, LineSegment segment1) { float length0 = Vector2.Distance ((Vector2)segment0.p0, (Vector2)segment0.p1); float length1 = Vector2.Distance ((Vector2)segment1.p0, (Vector2)segment1.p1); if (length0 < length1) { return 1; } if (length0 > length1) { return -1; } return 0; }
public static int CompareLengthsMax(LineSegment a, LineSegment b) { var l0 = Point.Distance(a.P0, a.P1); var l1 = Point.Distance(b.P0, b.P1); if (l0 < l1) { return 1; } if (l0 > l1) { return -1; } return 0; }
/// <summary> /// Generates a WPF geometry for a single graphic path geometry /// </summary> public static Geometry GenerateGeometry(GraphicPathGeometry graphicPathGeometry) { if (graphicPathGeometry == null) { return(null); } PathGeometry pathGeometry = new PathGeometry(); pathGeometry.FillRule = ConvertFillRule(graphicPathGeometry.FillRule); PathFigureCollection pathFigureCollection = new PathFigureCollection(); pathGeometry.Figures = pathFigureCollection; PathSegmentCollection pathSegmentCollection = null; foreach (var segment in graphicPathGeometry.Segments) { switch (segment) { case GraphicMoveSegment graphicMove: { var pathFigure = new PathFigure(); pathFigureCollection.Add(pathFigure); pathFigure.StartPoint = graphicMove.StartPoint; pathFigure.IsClosed = graphicMove.IsClosed; pathSegmentCollection = new PathSegmentCollection(); pathFigure.Segments = pathSegmentCollection; break; } case GraphicLineSegment graphicLineTo: { LineSegment lineSegment = new LineSegment(); pathSegmentCollection.Add(lineSegment); lineSegment.Point = graphicLineTo.To; break; } case GraphicCubicBezierSegment graphicCubicBezier: { BezierSegment bezierSegment = new BezierSegment(); pathSegmentCollection.Add(bezierSegment); bezierSegment.Point1 = graphicCubicBezier.ControlPoint1; bezierSegment.Point2 = graphicCubicBezier.ControlPoint2; bezierSegment.Point3 = graphicCubicBezier.EndPoint; break; } case GraphicQuadraticBezierSegment graphicQuadraticBezier: { QuadraticBezierSegment quadraticBezierSegment = new QuadraticBezierSegment(); pathSegmentCollection.Add(quadraticBezierSegment); quadraticBezierSegment.Point1 = graphicQuadraticBezier.ControlPoint; quadraticBezierSegment.Point2 = graphicQuadraticBezier.EndPoint; break; } } } pathGeometry.Freeze(); return(pathGeometry); }
/// <summary> /// Create polygons from raster. /// </summary> /// <param name="input">The Polygon Raster(Grid file).</param> /// <param name="connectionGrid">Connection Grid.</param> /// <param name="output">The Polygon shapefile path.</param> /// <param name="cancelProgressHandler">The progress handler.</param> /// <returns>True, if executed successfully.</returns> public bool Execute(IRaster input, IRaster connectionGrid, IFeatureSet output, ICancelProgressHandler cancelProgressHandler) { if (input == null || output == null) { return(false); } output.DataTable.Columns.Add("Value", typeof(double)); var featureHash = new Dictionary <double, LineSegmentList>(); var previous = 0.0; var height = input.CellHeight; var width = input.CellWidth; var xMin = input.Xllcenter - (width / 2.0); var yMin = input.Yllcenter - (height / 2.0); var xMax = xMin + (width * input.NumColumns); var yMax = yMin + (height * input.NumRows); var numRows = input.NumRows; var numColumns = input.NumColumns; Func <int, int, double, bool> same = (y, x, value) => y >= 0 && y < numRows && x >= 0 && x < numColumns && input.Value[y, x] == value; Func <int, int, double> get = (y, x) => y >= 0 && y < numRows && x >= 0 && x < numColumns ? input.Value[y, x] : input.NoDataValue; Func <int, int, int, int, bool> eqValues = (y1, x1, y2, x2) => get(y1, x1) == get(y2, x2); var enableCon = connectionGrid != null; Func <int, int, int> connection = (y, x) => connectionGrid != null ? (int)connectionGrid.Value[y, x] : 0; for (int y = 0; y < numRows; y++) { int current = Convert.ToInt32((y * 100.0) / input.NumRows); if (current > previous) { cancelProgressHandler.Progress(string.Empty, current, current + TextStrings.progresscompleted); previous = current; } Debug.WriteLine("Row : " + y + " done."); for (int x = 0; x < numColumns; x++) { var value = input.Value[y, x]; if (value == input.NoDataValue) { continue; } LineSegmentList lineList; if (!featureHash.TryGetValue(value, out lineList)) { lineList = new LineSegmentList(); featureHash.Add(value, lineList); } var curCon = connection(y, x); /* * 6 7 8 * 5 0 1 * 4 3 2 * current cell (x,y)=0 */ var con7 = same(y + 1, x, value); var con5 = same(y, x - 1, value); var con3 = same(y - 1, x, value); var con1 = same(y, x + 1, value); var con8L = enableCon && same(y + 1, x + 1, value) && !con7 && (curCon == 8 || connection(y + 1, x + 1) == 4); var con8R = enableCon && same(y + 1, x + 1, value) && !con1 && (curCon == 8 || connection(y + 1, x + 1) == 4); var con6L = enableCon && same(y + 1, x - 1, value) && !con5 && (curCon == 6 || connection(y + 1, x - 1) == 2); var con6R = enableCon && same(y + 1, x - 1, value) && !con7 && (curCon == 6 || connection(y + 1, x - 1) == 2); var con4L = enableCon && same(y - 1, x - 1, value) && !con5 && (curCon == 4 || connection(y - 1, x - 1) == 8); var con4R = enableCon && same(y - 1, x - 1, value) && !con3 && (curCon == 4 || connection(y - 1, x - 1) == 8); var con2L = enableCon && same(y - 1, x + 1, value) && !con3 && (curCon == 2 || connection(y - 1, x + 1) == 6); var con2R = enableCon && same(y - 1, x + 1, value) && !con1 && (curCon == 2 || connection(y - 1, x + 1) == 6); /* Cell points: * tl tc tr * cl cr * bl bc br */ var tl = new Coordinate(xMin + (x * width), yMax - ((y + 1) * height)); var tc = new Coordinate(xMin + ((x + 0.5) * width), yMax - ((y + 1) * height)); var tr = new Coordinate(xMin + ((x + 1) * width), yMax - ((y + 1) * height)); var cl = new Coordinate(xMin + (x * width), yMax - ((y + 0.5) * height)); var cr = new Coordinate(xMin + ((x + 1) * width), yMax - ((y + 0.5) * height)); var bl = new Coordinate(xMin + (x * width), yMax - (y * height)); var bc = new Coordinate(xMin + ((x + 0.5) * width), yMax - (y * height)); var br = new Coordinate(xMin + ((x + 1) * width), yMax - (y * height)); /* * Cell edges: * e_tl e_tr * ----|---- * e_lt | | e_rt * - - * e_lb | | e_rb * ----|---- * e_bl e_br */ bool eTr = false, eTl = false, eLt = false, eLb = false, eRt = false, eRb = false, eBr = false, eBl = false; if (!con7) { // top: right half if (!con8L) { var a1 = con6R && con1; var a2 = !con8R && !con6L && con4L && !con2R; eTr = a1 || a2; } // top: left half if (!con6R) { var a1 = con8L && con5; var a2 = !con8R && !con6L && !con4L && con2R; eTl = a1 || a2; } // top: full if (!con8L && !con6R && !con4L && !con2R) { eTr = eTl = true; } } if (!con3) { // bottom: left half if (!con4R) { var a1 = con2L && con5; var a2 = !con2R && !con4L && !con6L && con8R; eBl = a1 || a2; } // bottom: right half if (!con2L) { var a1 = con4R && con1; var a2 = !con2R && !con4L && !con8R && con6L; eBr = a1 || a2; } // bottom: full if (!con4R && !con2L && !con8R && !con6L) { eBl = eBr = true; } } if (!con1) { // right: bottom half if (!con2R) { var a1 = con8R && con3; var a2 = !con2L && !con8L && !con4R && con6R; eRb = a1 || a2; } // right: top half if (!con8R) { var a1 = con2R && con7; var a2 = !con2L && !con8L && !con6R && con4R; eRt = a1 || a2; } // right: full if (!con2R && !con8R && !con4R && !con6R) { eRb = eRt = true; } } if (!con5) { // left: bottom half if (!con4L) { var a1 = con3 && con6L; var a2 = !con6R && !con4R && con8L && !con2L; eLb = a1 || a2; } // left: top half if (!con6L) { var a1 = con4L && con7; var a2 = !con6R && !con4R && !con8L && con2L; eLt = a1 || a2; } // left: full if (!con4L && !con6L && !con8L && !con2L) { eLb = eLt = true; } } // Smooth boundaries regarding to outer cells // Right top corner if (eTr && eRt) { if (eqValues(y + 1, x, y, x + 1)) { var a1 = connection(y + 1, x); var a2 = connection(y, x + 1); if ((a1 == 6 || a1 == 2 || a2 == 6 || a2 == 2) && !(a1 == 6 && a2 == 2)) { lineList.AddSegment(tc, cr); eTr = eRt = false; } } } // Left top corner if (eTl && eLt) { if (eqValues(y, x - 1, y + 1, x)) { var a1 = connection(y, x - 1); var a2 = connection(y + 1, x); if ((a1 == 8 || a1 == 4 || a2 == 8 || a2 == 4) && !(a1 == 8 && a2 == 4)) { lineList.AddSegment(tc, cl); eTl = eLt = false; } } } // Left bottom corner if (eBl && eLb) { if (eqValues(y - 1, x, y, x - 1)) { var a1 = connection(y - 1, x); var a2 = connection(y, x - 1); if ((a1 == 6 || a1 == 2 || a2 == 6 || a2 == 2) && !(a1 == 6 && a2 == 2)) { lineList.AddSegment(cl, bc); eBl = eLb = false; } } } // Right bottom corner if (eBr && eRb) { if (eqValues(y, x + 1, y - 1, x)) { var a1 = connection(y, x + 1); var a2 = connection(y - 1, x); if ((a1 == 8 || a1 == 4 || a2 == 8 || a2 == 4) && !(a1 == 8 && a2 == 4)) { lineList.AddSegment(bc, cr); eBr = eRb = false; } } } // Smooth boundaries regarding direction of current cell switch (curCon) { case 2: case 6: if (eTr && eRt) { lineList.AddSegment(tc, cr); eTr = eRt = false; } if (eBl && eLb) { lineList.AddSegment(bc, cl); eBl = eLb = false; } break; case 4: case 8: if (eTl && eLt) { lineList.AddSegment(cl, tc); eTl = eLt = false; } if (eBr && eRb) { lineList.AddSegment(cr, bc); eBr = eRb = false; } break; } // Add remaining edges // Top if (eTl && eTr) { lineList.AddSegment(tl, tr); } else if (eTl) { lineList.AddSegment(tl, tc); } else if (eTr) { lineList.AddSegment(tc, tr); } // Left if (eLt && eLb) { lineList.AddSegment(tl, bl); } else if (eLt) { lineList.AddSegment(tl, cl); } else if (eLb) { lineList.AddSegment(cl, bl); } // Bottom if (eBl && eBr) { lineList.AddSegment(bl, br); } else if (eBl) { lineList.AddSegment(bl, bc); } else if (eBr) { lineList.AddSegment(bc, br); } // Right if (eRt && eRb) { lineList.AddSegment(tr, br); } else if (eRt) { lineList.AddSegment(tr, cr); } else if (eRb) { lineList.AddSegment(cr, br); } // Right top out diagonals if (con8L) { lineList.AddSegment(tc, new Coordinate(xMin + ((x + 1) * width), yMax - ((y + 1 + 0.5) * height))); } if (con8R) { lineList.AddSegment(cr, new Coordinate(xMin + ((x + 1 + 0.5) * width), yMax - ((y + 1) * height))); } // Right in diagonals if (con4L || con8L) { if (!con6R && !con6L && !con7 && !con5) { lineList.AddSegment(tc, cl); } } if (con4R || con8R) { if (!con2R && !con2L && !con1 && !con3) { lineList.AddSegment(cr, bc); } } // Left Top out diagonals if (con6R) { lineList.AddSegment(tc, new Coordinate(xMin + (x * width), yMax - ((y + 1 + 0.5) * height))); } if (con6L) { lineList.AddSegment(cl, new Coordinate(xMin + ((x - 0.5) * width), yMax - ((y + 1) * height))); } // Left In diagonals if (con6R || con2R) { if (!con8R && !con8L && !con7 && !con1) { lineList.AddSegment(tc, cr); } } if (con6L || con2L) { if (!con4R && !con4L && !con5 && !con3) { lineList.AddSegment(cl, bc); } } if (cancelProgressHandler.Cancel) { return(false); } } } foreach (var pair in featureHash) { #if DEBUG var sw = new Stopwatch(); sw.Start(); #endif var key = pair.Key; var lineSegList = pair.Value.List; var polyList = new List <IPolygon>(); var ind = 0; while (ind != lineSegList.Count) { var polyShell = new List <Coordinate>(); var start = lineSegList[ind++]; polyShell.Add(start.P0); polyShell.Add(start.P1); while (!polyShell[0].Equals2D(polyShell[polyShell.Count - 1])) { var last = polyShell[polyShell.Count - 1]; LineSegment segment = null; for (int i = ind; i < lineSegList.Count; i++) { var cur = lineSegList[i]; if (cur.P0.Equals2D(last) || cur.P1.Equals2D(last)) { segment = cur; if (ind != i) { var swap = lineSegList[ind]; lineSegList[ind] = cur; lineSegList[i] = swap; } ind++; break; } } Debug.Assert(segment != null, "Segment may not be null"); polyShell.Add(segment.P0.Equals2D(last) ? segment.P1 : segment.P0); } polyList.Add(new Polygon(new LinearRing(polyShell.ToArray()))); } IGeometry geometry = polyList.Count == 1 ? (IGeometry)polyList[0] : new MultiPolygon(polyList.ToArray()); var f = output.AddFeature(geometry); f.DataRow["Value"] = key; #if DEBUG sw.Stop(); Debug.WriteLine(sw.ElapsedMilliseconds); #endif } output.AttributesPopulated = true; output.Save(); return(true); }
public static bool CollapseSingleSegmentsToPolySegments(PathFigure original) { bool flag = false; PathSegmentCollection segmentCollection = new PathSegmentCollection(); for (int index = 0; index < original.Segments.Count; ++index) { LineSegment lineSegment = original.Segments[index] as LineSegment; QuadraticBezierSegment quadraticBezierSegment1 = original.Segments[index] as QuadraticBezierSegment; BezierSegment bezierSegment1 = original.Segments[index] as BezierSegment; int num = index; if (lineSegment != null) { PointCollection pointCollection = (PointCollection)null; for (; index + 1 < original.Segments.Count && original.Segments[index + 1] is LineSegment && !PathFigureUtilities.IsSignificantChangeBetweenSegments((PathSegment)lineSegment, original.Segments[index + 1]); ++index) { if (pointCollection == null) { pointCollection = new PointCollection(); pointCollection.Add(lineSegment.Point); } pointCollection.Add(((LineSegment)original.Segments[index + 1]).Point); } if (index != num) { PolyLineSegment polyLineSegment = new PolyLineSegment(); polyLineSegment.Points = pointCollection; PathSegmentUtilities.SetStrokeAndJoinOnSegment((PathSegment)polyLineSegment, lineSegment.IsStroked, new bool?(lineSegment.IsSmoothJoin)); segmentCollection.Add((PathSegment)polyLineSegment); flag = true; } else { segmentCollection.Add((PathSegment)lineSegment); } } else if (quadraticBezierSegment1 != null) { PointCollection pointCollection = (PointCollection)null; QuadraticBezierSegment quadraticBezierSegment2; for (; index + 1 < original.Segments.Count && (quadraticBezierSegment2 = original.Segments[index + 1] as QuadraticBezierSegment) != null && !PathFigureUtilities.IsSignificantChangeBetweenSegments((PathSegment)quadraticBezierSegment1, (PathSegment)quadraticBezierSegment2); ++index) { if (pointCollection == null) { pointCollection = new PointCollection(); pointCollection.Add(quadraticBezierSegment1.Point1); pointCollection.Add(quadraticBezierSegment1.Point2); } pointCollection.Add(quadraticBezierSegment2.Point1); pointCollection.Add(quadraticBezierSegment2.Point2); } if (index != num) { PolyQuadraticBezierSegment quadraticBezierSegment3 = new PolyQuadraticBezierSegment(); quadraticBezierSegment3.Points = pointCollection; PathSegmentUtilities.SetStrokeAndJoinOnSegment((PathSegment)quadraticBezierSegment3, quadraticBezierSegment1.IsStroked, new bool?(quadraticBezierSegment1.IsSmoothJoin)); segmentCollection.Add((PathSegment)quadraticBezierSegment3); flag = true; } else { segmentCollection.Add((PathSegment)quadraticBezierSegment1); } } else if (bezierSegment1 != null) { PointCollection pointCollection = (PointCollection)null; BezierSegment bezierSegment2; for (; index + 1 < original.Segments.Count && (bezierSegment2 = original.Segments[index + 1] as BezierSegment) != null && !PathFigureUtilities.IsSignificantChangeBetweenSegments((PathSegment)bezierSegment1, (PathSegment)bezierSegment2); ++index) { if (pointCollection == null) { pointCollection = new PointCollection(); pointCollection.Add(bezierSegment1.Point1); pointCollection.Add(bezierSegment1.Point2); pointCollection.Add(bezierSegment1.Point3); } pointCollection.Add(bezierSegment2.Point1); pointCollection.Add(bezierSegment2.Point2); pointCollection.Add(bezierSegment2.Point3); } if (index != num) { PolyBezierSegment polyBezierSegment = new PolyBezierSegment(); polyBezierSegment.Points = pointCollection; PathSegmentUtilities.SetStrokeAndJoinOnSegment((PathSegment)polyBezierSegment, bezierSegment1.IsStroked, new bool?(bezierSegment1.IsSmoothJoin)); segmentCollection.Add((PathSegment)polyBezierSegment); flag = true; } else { segmentCollection.Add((PathSegment)bezierSegment1); } } else { segmentCollection.Add(original.Segments[index]); } } if (flag) { original.Segments = segmentCollection; } return(flag); }
FoldMarker GetFoldMarkerFromColumn(int firstLogicalLine, int xPos) { float spaceWidth = GetWidth(' '); LineSegment line = firstLogicalLine < Document.TotalNumberOfLines ? Document.GetLineSegment(firstLogicalLine) : null; if (line == null) { return(null); } int lineNumber = firstLogicalLine; int tabIndent = Document.TextEditorProperties.TabIndent; int column = 0; int logicalColumn = 0; float paintPos = 0; ArrayList starts = textArea.Document.FoldingManager.GetFoldedFoldingsWithStart(lineNumber); while (true) { // save current paint position float oldPaintPos = paintPos; // search for folding if (starts.Count > 0) { foreach (FoldMarker folding in starts) { if (folding.IsFolded && logicalColumn >= folding.StartColumn && (logicalColumn < folding.EndColumn || lineNumber != folding.EndLine)) { column += folding.FoldText.Length; paintPos += folding.FoldText.Length * spaceWidth; // special case when xPos is inside the fold marker if (xPos <= paintPos) { return(folding); } logicalColumn = folding.EndColumn; if (lineNumber != folding.EndLine) { lineNumber = folding.EndLine; line = Document.GetLineSegment(lineNumber); starts = textArea.Document.FoldingManager.GetFoldedFoldingsWithStart(lineNumber); } break; } } } // --> no folding, going on with the count char ch = logicalColumn >= line.Length ? ' ' : Document.GetCharAt(line.Offset + logicalColumn); switch (ch) { case '\t': int oldColumn = column; column += tabIndent; column = (column / tabIndent) * tabIndent; paintPos += (column - oldColumn) * spaceWidth; break; default: paintPos += GetWidth(ch); ++column; break; } // when the paint position is reached, give it back otherwise advance to the next char if (xPos <= paintPos - (paintPos - oldPaintPos) / 2) { return(null); } ++logicalColumn; } }
/// <summary> /// /// </summary> /// <param name="seg"></param> public virtual void Remove(LineSegment seg) { index.Remove(new Envelope(seg.P0, seg.P1), seg); }
private static void AddVisibleSegments(List <LineSegment> segments, List <Rectangle> overlappingRectangles, bool isVertical, int cutoff) { // Loop over rectangles, to cut away hidden sections of segments. for (int rectangleIndex = overlappingRectangles.Count - 1; rectangleIndex >= 0; --rectangleIndex) { Rectangle rectangle = overlappingRectangles[rectangleIndex]; // Calculate segments for this rectangle, and start with initial full segments. List <LineSegment> rectangleSegments = isVertical ? GetVerticalEdges(ref rectangle, cutoff) : GetHorizontalEdges(ref rectangle, cutoff); // Loop over rectangles that are higher in the z-order (so lower index), since they can overlap. for (int overlappingRectangleIndex = rectangleIndex - 1; overlappingRectangleIndex >= 0; --overlappingRectangleIndex) { // Cut away whatever is hidden by the rectangle higher in the z-order. Rectangle overlappingRectangle = overlappingRectangles[overlappingRectangleIndex]; // Calculate inflated rectangle coordinates. int overlappingRectanglePositionMin, overlappingRectanglePositionMax, minInflated, maxInflated; if (isVertical) { overlappingRectanglePositionMin = overlappingRectangle.Left; overlappingRectanglePositionMax = overlappingRectangle.Right; minInflated = overlappingRectangle.Top - cutoff; maxInflated = overlappingRectangle.Bottom + cutoff; } else { overlappingRectanglePositionMin = overlappingRectangle.Top; overlappingRectanglePositionMax = overlappingRectangle.Bottom; minInflated = overlappingRectangle.Left - cutoff; maxInflated = overlappingRectangle.Right + cutoff; } // Start with the end of the list and work back to the beginning, so segments that are split in two by this overlapping rectangle will not be checked again. for (int index = rectangleSegments.Count - 1; index >= 0; --index) { LineSegment segment = rectangleSegments[index]; // Is the segment somewhere between the left and right edges of the inflated overlapping rectangle? if (segment.Near < segment.Far && overlappingRectanglePositionMin < segment.Position && segment.Position < overlappingRectanglePositionMax) { if (minInflated <= segment.Near) { // Cut off the top of the segment. if (segment.Near < maxInflated) { segment.Near = maxInflated; } } else if (segment.Far <= maxInflated) { // Cut off the bottom of the segment. if (minInflated < segment.Far) { segment.Far = minInflated; } } else { // Split the segment in two. rectangleSegments.Add(new LineSegment(segment.Position, segment.Near, minInflated)); segment.Near = maxInflated; } } } } // Only keep those segments that are non-empty. foreach (LineSegment segment in rectangleSegments) { if (segment.Near < segment.Far) { segments.Add(segment); } } } }
protected override int TryHighlightAddedAndDeletedLines(IDocument document, int line, LineSegment lineSegment) { ProcessLineSegment(document, ref line, lineSegment, "++", AppSettings.DiffAddedColor); ProcessLineSegment(document, ref line, lineSegment, "+ ", AppSettings.DiffAddedColor); ProcessLineSegment(document, ref line, lineSegment, " +", AppSettings.DiffAddedColor); ProcessLineSegment(document, ref line, lineSegment, "--", AppSettings.DiffRemovedColor); ProcessLineSegment(document, ref line, lineSegment, "- ", AppSettings.DiffRemovedColor); ProcessLineSegment(document, ref line, lineSegment, " -", AppSettings.DiffRemovedColor); return(line); }
private void UpdatePath() { var innerRadius = this.InnerRadius + this.StrokeThickness / 2; var outerRadius = this.Radius - this.StrokeThickness / 2; if (_isUpdating || this.ActualWidth == 0 || innerRadius <= 0 || outerRadius < innerRadius) { return; } var pathGeometry = new PathGeometry(); var pathFigure = new PathFigure(); pathFigure.IsClosed = true; var center = this.Center ?? new Point( outerRadius + this.StrokeThickness / 2, outerRadius + this.StrokeThickness / 2); // Starting Point pathFigure.StartPoint = new Point( center.X + Math.Sin(StartAngle * Math.PI / 180) * innerRadius, center.Y - Math.Cos(StartAngle * Math.PI / 180) * innerRadius); // Inner Arc var innerArcSegment = new ArcSegment(); innerArcSegment.IsLargeArc = (EndAngle - StartAngle) >= 180.0; innerArcSegment.Point = new Point( center.X + Math.Sin(EndAngle * Math.PI / 180) * innerRadius, center.Y - Math.Cos(EndAngle * Math.PI / 180) * innerRadius); innerArcSegment.Size = new Size(innerRadius, innerRadius); innerArcSegment.SweepDirection = SweepDirection.Clockwise; var lineSegment = new LineSegment { Point = new Point( center.X + Math.Sin(EndAngle * Math.PI / 180) * outerRadius, center.Y - Math.Cos(EndAngle * Math.PI / 180) * outerRadius) }; // Outer Arc var outerArcSegment = new ArcSegment(); outerArcSegment.IsLargeArc = (EndAngle - StartAngle) >= 180.0; outerArcSegment.Point = new Point( center.X + Math.Sin(StartAngle * Math.PI / 180) * outerRadius, center.Y - Math.Cos(StartAngle * Math.PI / 180) * outerRadius); outerArcSegment.Size = new Size(outerRadius, outerRadius); outerArcSegment.SweepDirection = SweepDirection.Counterclockwise; pathFigure.Segments.Add(innerArcSegment); pathFigure.Segments.Add(lineSegment); pathFigure.Segments.Add(outerArcSegment); pathGeometry.Figures.Add(pathFigure); this.InvalidateArrange(); this.Data = pathGeometry; }
private void TryIndent(TextArea textArea, int begin, int end) { string str1 = ""; Stack stack = new Stack(); IDocument document = textArea.Document; string indentationString = Tab.GetIndentationString(document); int lineNumber1 = begin; int x = 0; bool flag = false; XmlNodeType xmlNodeType = XmlNodeType.XmlDeclaration; XmlTextReader xmlTextReader = (XmlTextReader)null; using (StringReader stringReader = new StringReader(document.TextContent)) { try { xmlTextReader = new XmlTextReader((TextReader)stringReader); label_25: while (xmlTextReader.Read()) { if (flag) { str1 = stack.Count != 0 ? (string)stack.Pop() : ""; } if (xmlTextReader.NodeType == XmlNodeType.EndElement) { str1 = stack.Count != 0 ? (string)stack.Pop() : ""; } while (xmlTextReader.LineNumber > lineNumber1 && lineNumber1 <= end) { if (xmlNodeType == XmlNodeType.CDATA || xmlNodeType == XmlNodeType.Comment) { ++lineNumber1; } else { LineSegment lineSegment = document.GetLineSegment(lineNumber1); string text1 = document.GetText((ISegment)lineSegment); string text2 = !(text1.Trim() == ">") ? str1 + text1.Trim() : (string)stack.Peek() + text1.Trim(); if (text2 != text1) { document.Replace(lineSegment.Offset, lineSegment.Length, text2); ++x; } ++lineNumber1; } } if (xmlTextReader.LineNumber <= end) { flag = xmlTextReader.NodeType == XmlNodeType.Element && xmlTextReader.IsEmptyElement; string str2 = (string)null; if (xmlTextReader.NodeType == XmlNodeType.Element) { stack.Push((object)str1); if (xmlTextReader.LineNumber < begin) { str1 = this.GetIndentation(textArea, xmlTextReader.LineNumber - 1); } str2 = xmlTextReader.Name.Length >= 16 ? str1 + indentationString : str1 + new string(' ', 2 + xmlTextReader.Name.Length); str1 = str1 + indentationString; } xmlNodeType = xmlTextReader.NodeType; if (xmlTextReader.NodeType == XmlNodeType.Element && xmlTextReader.HasAttributes) { int lineNumber2 = xmlTextReader.LineNumber; xmlTextReader.MoveToAttribute(0); if (xmlTextReader.LineNumber != lineNumber2) { str2 = str1; } xmlTextReader.MoveToAttribute(xmlTextReader.AttributeCount - 1); while (true) { if (xmlTextReader.LineNumber > lineNumber1 && lineNumber1 <= end) { LineSegment lineSegment = document.GetLineSegment(lineNumber1); string text1 = document.GetText((ISegment)lineSegment); string text2 = str2 + text1.Trim(); if (text2 != text1) { document.Replace(lineSegment.Offset, lineSegment.Length, text2); ++x; } ++lineNumber1; } else { goto label_25; } } } } else { break; } } xmlTextReader.Close(); } catch (XmlException ex) { } finally { if (xmlTextReader != null) { xmlTextReader.Close(); } } } if (x <= 1) { return; } document.UndoStack.Undo(); }
// animation: private Storyboard IntilaizeStory(Point start, Point end, PacketType packetType) { // Create a NameScope for the page so that // we can use Storyboards. NameScope.SetNameScope(PublicParamerters.MainWindow.Canvas_SensingFeild, new NameScope()); // Create a rectangle. Border aRectangle = new Border(); aRectangle.CornerRadius = new CornerRadius(5); aRectangle.Width = 5; aRectangle.Height = 5; switch (packetType) { case PacketType.Data: aRectangle.Background = Brushes.Black; Stroke = Brushes.Black; break; case PacketType.ShareSinkPosition: aRectangle.Background = Brushes.Blue; Stroke = Brushes.Blue; break; case PacketType.ReportSinkPosition: aRectangle.Background = Brushes.Green; Stroke = Brushes.Green; break; case PacketType.ResponseSinkPosition: aRectangle.Background = Brushes.Red; Stroke = Brushes.Red; break; case PacketType.ObtainSinkPosition: aRectangle.Background = Brushes.Yellow; Stroke = Brushes.Yellow; break; default: aRectangle.Background = Brushes.SkyBlue; Stroke = Brushes.SkyBlue; break; } MovedObjectStack.Push(aRectangle); // Create a transform. This transform // will be used to move the rectangle. TranslateTransform animatedTranslateTransform = new TranslateTransform(); // Register the transform's name with the page // so that they it be targeted by a Storyboard. PublicParamerters.MainWindow.Canvas_SensingFeild.RegisterName("AnimatedTranslateTransform", animatedTranslateTransform); aRectangle.RenderTransform = animatedTranslateTransform; PublicParamerters.MainWindow.Canvas_SensingFeild.Children.Add(aRectangle); // Create the animation path. PathGeometry animationPath = new PathGeometry(); PathFigure pFigure = new PathFigure(); // add the figure. pFigure.StartPoint = start; // define the start point of the Figure. LineSegment lineSegment = new LineSegment(); // move according to line. lineSegment.Point = end; // set the end point. pFigure.Segments.Add(lineSegment); // add the line to the figure. animationPath.Figures.Add(pFigure); // add the figure to the path. // Freeze the PathGeometry for performance benefits. animationPath.Freeze(); // Create a DoubleAnimationUsingPath to move the // rectangle horizontally along the path by animating // its TranslateTransform. DoubleAnimationUsingPath translateXAnimation = new DoubleAnimationUsingPath(); translateXAnimation.PathGeometry = animationPath; translateXAnimation.Duration = TimeSpan.FromSeconds(Settings.Default.AnimationSpeed); // Set the Source property to X. This makes // the animation generate horizontal offset values from // the path information. translateXAnimation.Source = PathAnimationSource.X; // Set the animation to target the X property // of the TranslateTransform named "AnimatedTranslateTransform". Storyboard.SetTargetName(translateXAnimation, "AnimatedTranslateTransform"); Storyboard.SetTargetProperty(translateXAnimation, new PropertyPath(TranslateTransform.XProperty)); // Create a DoubleAnimationUsingPath to move the // rectangle vertically along the path by animating // its TranslateTransform. DoubleAnimationUsingPath translateYAnimation = new DoubleAnimationUsingPath(); translateYAnimation.PathGeometry = animationPath; //translateYAnimation.Duration = TimeSpan.FromSeconds(Properties.Settings.Default.AnimationSpeed); translateYAnimation.Duration = TimeSpan.FromSeconds(Settings.Default.AnimationSpeed); // Set the Source property to Y. This makes // the animation generate vertical offset values from // the path information. translateYAnimation.Source = PathAnimationSource.Y; // Set the animation to target the Y property // of the TranslateTransform named "AnimatedTranslateTransform". Storyboard.SetTargetName(translateYAnimation, "AnimatedTranslateTransform"); Storyboard.SetTargetProperty(translateYAnimation, new PropertyPath(TranslateTransform.YProperty)); // Create a Storyboard to contain and apply the animations. Storyboard pathAnimationStoryboard = new Storyboard(); //pathAnimationStoryboard.RepeatBehavior = RepeatBehavior.Forever; pathAnimationStoryboard.Children.Add(translateXAnimation); pathAnimationStoryboard.Children.Add(translateYAnimation); return(pathAnimationStoryboard); }
void PaintDocumentLine(Graphics g, int lineNumber, Rectangle lineRectangle) { Brush bgColorBrush = GetBgColorBrush(lineNumber); Brush backgroundBrush = textArea.Enabled ? bgColorBrush : SystemBrushes.InactiveBorder; if (lineNumber >= textArea.Document.TotalNumberOfLines) { g.FillRectangle(backgroundBrush, lineRectangle); if (TextEditorProperties.ShowInvalidLines) //判断是否要画无效的行。 { DrawInvalidLineMarker(g, lineRectangle.Left, lineRectangle.Top); } if (TextEditorProperties.ShowVerticalRuler) //判断是否要画垂直标尺。 { DrawVerticalRuler(g, lineRectangle); } return; } float physicalXPos = lineRectangle.X; int column = 0; physicalColumn = 0; if (TextEditorProperties.EnableFolding) { while (true) { ArrayList starts = textArea.Document.FoldingManager.GetFoldedFoldingsWithStartAfterColumn(lineNumber, column - 1); if (starts == null || starts.Count <= 0) { if (lineNumber < textArea.Document.TotalNumberOfLines) { physicalXPos = PaintLinePart(g, lineNumber, column, textArea.Document.GetLineSegment(lineNumber).Length, lineRectangle, physicalXPos); } break; } // search the first starting folding FoldMarker firstFolding = (FoldMarker)starts[0]; foreach (FoldMarker fm in starts) { if (fm.StartColumn < firstFolding.StartColumn) { firstFolding = fm; } } starts.Clear(); physicalXPos = PaintLinePart(g, lineNumber, column, firstFolding.StartColumn, lineRectangle, physicalXPos); column = firstFolding.EndColumn; lineNumber = firstFolding.EndLine; ColumnRange selectionRange2 = textArea.SelectionManager.GetSelectionAtLine(lineNumber); bool drawSelected = ColumnRange.WholeColumn.Equals(selectionRange2) || firstFolding.StartColumn >= selectionRange2.StartColumn && firstFolding.EndColumn <= selectionRange2.EndColumn; physicalXPos = PaintFoldingText(g, lineNumber, physicalXPos, lineRectangle, firstFolding.FoldText, drawSelected); } } else { physicalXPos = PaintLinePart(g, lineNumber, 0, textArea.Document.GetLineSegment(lineNumber).Length, lineRectangle, physicalXPos); } if (lineNumber < textArea.Document.TotalNumberOfLines) { // Paint things after end of line ColumnRange selectionRange = textArea.SelectionManager.GetSelectionAtLine(lineNumber); LineSegment currentLine = textArea.Document.GetLineSegment(lineNumber); HighlightColor selectionColor = textArea.Document.HighlightingStrategy.GetEnvironmentColorForName("Selection"); float spaceWidth = GetWidth(g, ' '); bool selectionBeyondEOL = selectionRange.EndColumn > currentLine.Length || ColumnRange.WholeColumn.Equals(selectionRange); if (TextEditorProperties.ShowEOLMarker) { HighlightColor eolMarkerColor = textArea.Document.HighlightingStrategy.GetEnvironmentColorForName("EOLMarkers"); physicalXPos += DrawEOLMarker(g, eolMarkerColor.Color, selectionBeyondEOL ? bgColorBrush : backgroundBrush, physicalXPos, lineRectangle.Y); } else { if (selectionBeyondEOL) { g.FillRectangle(BrushRegistry.GetBrush(selectionColor.BackgroundColor), new RectangleF(physicalXPos, lineRectangle.Y, spaceWidth, lineRectangle.Height)); physicalXPos += spaceWidth; } } Brush fillBrush = selectionBeyondEOL && TextEditorProperties.AllowCaretBeyondEOL ? bgColorBrush : backgroundBrush; g.FillRectangle(fillBrush, new RectangleF(physicalXPos, lineRectangle.Y, lineRectangle.Width - physicalXPos + lineRectangle.X, lineRectangle.Height)); } if (TextEditorProperties.ShowVerticalRuler) { DrawVerticalRuler(g, lineRectangle); } }
private FoldMarker GetFoldMarkerFromColumn(int firstLogicalLine, int xPos) { float width = this.GetWidth(' '); LineSegment lineSegment = (firstLogicalLine < base.Document.TotalNumberOfLines) ? base.Document.GetLineSegment(firstLogicalLine) : null; if (lineSegment == null) { return(null); } int num = firstLogicalLine; int tabIndent = base.Document.TextEditorProperties.TabIndent; int num2 = 0; int num3 = 0; float num4 = 0f; ArrayList foldedFoldingsWithStart = this.textArea.Document.FoldingManager.GetFoldedFoldingsWithStart(num); while (true) { float num5 = num4; if (foldedFoldingsWithStart.Count > 0) { foreach (FoldMarker foldMarker in foldedFoldingsWithStart) { if (foldMarker.IsFolded && num3 >= foldMarker.StartColumn && (num3 < foldMarker.EndColumn || num != foldMarker.EndLine)) { num2 += foldMarker.FoldText.Length; num4 += (float)foldMarker.FoldText.Length * width; if ((float)xPos <= num4) { return(foldMarker); } num3 = foldMarker.EndColumn; if (num != foldMarker.EndLine) { num = foldMarker.EndLine; lineSegment = base.Document.GetLineSegment(num); foldedFoldingsWithStart = this.textArea.Document.FoldingManager.GetFoldedFoldingsWithStart(num); break; } break; } } } char c = (num3 >= lineSegment.Length) ? ' ' : base.Document.GetCharAt(lineSegment.Offset + num3); char c2 = c; if (c2 == '\t') { int num6 = num2; num2 += tabIndent; num2 = num2 / tabIndent * tabIndent; num4 += (float)(num2 - num6) * width; } else { num4 += this.GetWidth(c); num2++; } if ((float)xPos <= num4 - (num4 - num5) / 2f) { break; } num3++; } return(null); }
/// <summary> /// Draws line segment. /// </summary> /// <param name="image">Input image.</param> /// <param name="line">Line</param> /// <param name="color">Line color.</param> /// <param name="thickness">Line thickness.</param> public static void Draw <TColor>(this Image <TColor, byte> image, LineSegment line, TColor color, float thickness) where TColor : IColor3 { Draw(image, new LineSegment[] { line }, color, thickness); }
/// <summary> /// /// </summary> /// <param name="ls"></param> public override void Select(LineSegment ls) { container.TestLineSegment(p, ls); }
public override bool HandleKeyPress(SharpDevelopTextAreaControl editor, char ch) { CSharpExpressionFinder ef = new CSharpExpressionFinder(editor.FileName); int cursor = editor.ActiveTextAreaControl.Caret.Offset; ExpressionContext context = null; if (ch == '(') { if (CodeCompletionOptions.KeywordCompletionEnabled) { switch (editor.GetWordBeforeCaret().Trim()) { case "for": case "lock": context = ExpressionContext.Default; break; case "using": context = ExpressionContext.TypeDerivingFrom(ParserService.CurrentProjectContent.GetClass("System.IDisposable"), false); break; case "catch": context = ExpressionContext.TypeDerivingFrom(ParserService.CurrentProjectContent.GetClass("System.Exception"), false); break; case "foreach": case "typeof": case "sizeof": case "default": context = ExpressionContext.Type; break; } } if (context != null) { if (IsInComment(editor)) { return(false); } editor.ShowCompletionWindow(new CtrlSpaceCompletionDataProvider(context), ch); return(true); } else if (EnableMethodInsight && CodeCompletionOptions.InsightEnabled) { editor.ShowInsightWindow(new MethodInsightDataProvider()); return(true); } return(false); } else if (ch == '[') { LineSegment line = editor.Document.GetLineSegmentForOffset(cursor); if (TextUtilities.FindPrevWordStart(editor.Document, cursor) <= line.Offset) { // [ is first character on the line // -> Attribute completion editor.ShowCompletionWindow(new AttributesDataProvider(ParserService.CurrentProjectContent), ch); return(true); } } else if (ch == ',' && CodeCompletionOptions.InsightRefreshOnComma && CodeCompletionOptions.InsightEnabled) { if (InsightRefreshOnComma(editor, ch)) { return(true); } } else if (ch == '=') { LineSegment curLine = editor.Document.GetLineSegmentForOffset(cursor); string documentText = editor.Text; int position = editor.ActiveTextAreaControl.Caret.Offset - 2; if (position > 0 && (documentText[position + 1] == '+')) { ExpressionResult result = ef.FindFullExpression(documentText, position); if (result.Expression != null) { ResolveResult resolveResult = ParserService.Resolve(result, editor.ActiveTextAreaControl.Caret.Line + 1, editor.ActiveTextAreaControl.Caret.Column + 1, editor.FileName, documentText); if (resolveResult != null && resolveResult.ResolvedType != null) { IClass underlyingClass = resolveResult.ResolvedType.GetUnderlyingClass(); if (underlyingClass != null && underlyingClass.IsTypeInInheritanceTree(ParserService.CurrentProjectContent.GetClass("System.MulticastDelegate"))) { EventHandlerCompletitionDataProvider eventHandlerProvider = new EventHandlerCompletitionDataProvider(result.Expression, resolveResult); eventHandlerProvider.InsertSpace = true; editor.ShowCompletionWindow(eventHandlerProvider, ch); } } } } else if (position > 0) { ExpressionResult result = ef.FindFullExpression(documentText, position); if (result.Expression != null) { ResolveResult resolveResult = ParserService.Resolve(result, editor.ActiveTextAreaControl.Caret.Line + 1, editor.ActiveTextAreaControl.Caret.Column + 1, editor.FileName, documentText); if (resolveResult != null && resolveResult.ResolvedType != null) { if (ProvideContextCompletion(editor, resolveResult.ResolvedType, ch)) { return(true); } } } } } else if (ch == ';') { LineSegment curLine = editor.Document.GetLineSegmentForOffset(cursor); // don't return true when inference succeeds, otherwise the ';' won't be added to the document. TryDeclarationTypeInference(editor, curLine); } return(base.HandleKeyPress(editor, ch)); }
/// <summary> /// /// </summary> /// <param name="querySeg"></param> public LineSegmentVisitor(LineSegment querySeg) { this.querySeg = querySeg; }
private float PaintLinePart(Graphics g, int lineNumber, int startColumn, int endColumn, Rectangle lineRectangle, float physicalXPos) { bool flag = this.DrawLineMarkerAtLine(lineNumber); Brush bgColorBrush = this.GetBgColorBrush(lineNumber); Brush brush = this.textArea.Enabled ? bgColorBrush : SystemBrushes.InactiveBorder; HighlightColor colorFor = this.textArea.Document.HighlightingStrategy.GetColorFor("Selection"); ColumnRange selectionAtLine = this.textArea.SelectionManager.GetSelectionAtLine(lineNumber); HighlightColor colorFor2 = this.textArea.Document.HighlightingStrategy.GetColorFor("TabMarkers"); HighlightColor colorFor3 = this.textArea.Document.HighlightingStrategy.GetColorFor("SpaceMarkers"); float width = this.GetWidth(g, ' '); LineSegment lineSegment = this.textArea.Document.GetLineSegment(lineNumber); int num = startColumn; Brush brush2 = BrushRegistry.GetBrush(colorFor.BackgroundColor); Brush brush3 = brush; if (lineSegment.Words != null) { int num2 = 0; int num3 = 0; while (num2 < lineSegment.Words.Count && num3 < startColumn) { TextWord textWord = (TextWord)lineSegment.Words[num2]; if (textWord.Type == TextWordType.Tab) { num3++; } else { if (textWord.Type == TextWordType.Space) { num3++; } else { num3 += textWord.Length; } } num2++; } int num4 = num2; while (num4 < lineSegment.Words.Count && num < endColumn) { ArrayList markers = base.Document.MarkerStrategy.GetMarkers(lineSegment.Offset + num3); foreach (TextMarker textMarker in markers) { if (textMarker.TextMarkerType == TextMarkerType.SolidBlock) { brush3 = BrushRegistry.GetBrush(textMarker.Color); break; } } TextWord textWord2 = (TextWord)lineSegment.Words[num4]; switch (textWord2.Type) { case TextWordType.Word: { string word = textWord2.Word; float num5 = physicalXPos; Brush markerBrushAt = this.GetMarkerBrushAt(lineSegment.Offset + num, word.Length, out markers); Brush backBrush; if (!flag && markerBrushAt != null) { backBrush = markerBrushAt; } else { if (!flag && textWord2.SyntaxColor.HasBackground) { backBrush = BrushRegistry.GetBrush(textWord2.SyntaxColor.BackgroundColor); } else { backBrush = brush3; } } if (ColumnRange.WholeColumn.Equals(selectionAtLine) || (selectionAtLine.EndColumn - 1 >= word.Length + num && selectionAtLine.StartColumn <= num)) { physicalXPos += this.DrawDocumentWord(g, word, new PointF(physicalXPos, (float)lineRectangle.Y), textWord2.Font, colorFor.HasForgeground ? colorFor.Color : textWord2.Color, brush2); } else { if (ColumnRange.NoColumn.Equals(selectionAtLine)) { physicalXPos += this.DrawDocumentWord(g, word, new PointF(physicalXPos, (float)lineRectangle.Y), textWord2.Font, textWord2.Color, backBrush); } else { int num6 = Math.Min(word.Length, Math.Max(0, selectionAtLine.StartColumn - num)); int num7 = Math.Max(num6, Math.Min(word.Length, selectionAtLine.EndColumn - num)); physicalXPos += this.DrawDocumentWord(g, word.Substring(0, num6), new PointF(physicalXPos, (float)lineRectangle.Y), textWord2.Font, textWord2.Color, backBrush); physicalXPos += this.DrawDocumentWord(g, word.Substring(num6, num7 - num6), new PointF(physicalXPos, (float)lineRectangle.Y), textWord2.Font, colorFor.HasForgeground ? colorFor.Color : textWord2.Color, brush2); physicalXPos += this.DrawDocumentWord(g, word.Substring(num7), new PointF(physicalXPos, (float)lineRectangle.Y), textWord2.Font, textWord2.Color, backBrush); } } foreach (TextMarker textMarker2 in markers) { if (textMarker2.TextMarkerType != TextMarkerType.SolidBlock) { this.DrawMarker(g, textMarker2, new RectangleF(num5, (float)lineRectangle.Y, physicalXPos - num5, (float)lineRectangle.Height)); } } if (this.highlight != null && ((this.highlight.OpenBrace.Y == lineNumber && this.highlight.OpenBrace.X == num) || (this.highlight.CloseBrace.Y == lineNumber && this.highlight.CloseBrace.X == num))) { this.DrawBracketHighlight(g, new Rectangle((int)num5, lineRectangle.Y, (int)(physicalXPos - num5) - 1, lineRectangle.Height - 1)); } this.physicalColumn += word.Length; num += word.Length; break; } case TextWordType.Space: { RectangleF rectangleF = new RectangleF(physicalXPos, (float)lineRectangle.Y, (float)Math.Ceiling((double)width), (float)lineRectangle.Height); Brush brush4; if (ColumnRange.WholeColumn.Equals(selectionAtLine) || (num >= selectionAtLine.StartColumn && num < selectionAtLine.EndColumn)) { brush4 = brush2; } else { Brush markerBrushAt2 = this.GetMarkerBrushAt(lineSegment.Offset + num, 1, out markers); if (!flag && markerBrushAt2 != null) { brush4 = markerBrushAt2; } else { if (!flag && textWord2.SyntaxColor != null && textWord2.SyntaxColor.HasBackground) { brush4 = BrushRegistry.GetBrush(textWord2.SyntaxColor.BackgroundColor); } else { brush4 = brush3; } } } g.FillRectangle(brush4, rectangleF); if (base.TextEditorProperties.ShowSpaces) { this.DrawSpaceMarker(g, colorFor3.Color, physicalXPos, (float)lineRectangle.Y); } foreach (TextMarker marker in markers) { this.DrawMarker(g, marker, rectangleF); } physicalXPos += width; num++; this.physicalColumn++; break; } case TextWordType.Tab: { int num8 = this.physicalColumn; this.physicalColumn += base.TextEditorProperties.TabIndent; this.physicalColumn = this.physicalColumn / base.TextEditorProperties.TabIndent * base.TextEditorProperties.TabIndent; float num9 = (float)(this.physicalColumn - num8) * width; RectangleF rectangleF2 = new RectangleF(physicalXPos, (float)lineRectangle.Y, (float)Math.Ceiling((double)num9), (float)lineRectangle.Height); Brush brush4; if (ColumnRange.WholeColumn.Equals(selectionAtLine) || (num >= selectionAtLine.StartColumn && num <= selectionAtLine.EndColumn - 1)) { brush4 = brush2; } else { Brush markerBrushAt3 = this.GetMarkerBrushAt(lineSegment.Offset + num, 1, out markers); if (!flag && markerBrushAt3 != null) { brush4 = markerBrushAt3; } else { if (!flag && textWord2.SyntaxColor != null && textWord2.SyntaxColor.HasBackground) { brush4 = BrushRegistry.GetBrush(textWord2.SyntaxColor.BackgroundColor); } else { brush4 = brush3; } } } g.FillRectangle(brush4, rectangleF2); if (base.TextEditorProperties.ShowTabs) { this.DrawTabMarker(g, colorFor2.Color, physicalXPos, (float)lineRectangle.Y); } foreach (TextMarker marker2 in markers) { this.DrawMarker(g, marker2, rectangleF2); } physicalXPos += num9; num++; break; } } num4++; } } return(physicalXPos); }
/// <summary> /// /// </summary> /// <param name="seg"></param> public virtual void Add(LineSegment seg) { index.Insert(new Envelope(seg.P0, seg.P1), seg); }
private ITrackingCommand BuildBackwardPass() { BehaviorManager.TraceSource.TraceEvent(TraceEventType.Information, 0, "UTurn Behavior: Initialize Backward Pass"); // rotate the polygon into the current relative frame CarTimestamp curTimestamp = Services.RelativePose.CurrentTimestamp; RelativeTransform relTransform = Services.RelativePose.GetTransform(polygonTimestamp, curTimestamp); relTransform.TransformPointsInPlace(polygon); finalOrientation = finalOrientation.Transform(relTransform); polygonTimestamp = curTimestamp; // retrieve the vehicle state Coordinates headingVec = new Coordinates(1, 0); Coordinates headingVec180 = headingVec.Rotate180(); Coordinates headingVec90 = headingVec.Rotate90(); // figure out center point of turn Circle rearAxleCircle = Circle.FromPointSlopeRadius(new Coordinates(0, 0), headingVec180, minRadius); Coordinates center = rearAxleCircle.center; // calculate the points of the wheels Coordinates rearLeftPoint = headingVec90 * TahoeParams.T / 2; Coordinates rearRightPoint = -headingVec90 * TahoeParams.T / 2; Coordinates frontLeftPoint = headingVec * TahoeParams.L + headingVec90 * TahoeParams.T / 2; Coordinates frontRightPoint = headingVec * TahoeParams.L - headingVec90 * TahoeParams.T / 2; double minHit = Math.PI / 2.1; GetMinHitAngle(rearLeftPoint, center, ref minHit); GetMinHitAngle(rearRightPoint, center, ref minHit); //GetMinHitAngle(frontLeftPoint, center, false, ref minHit); //GetMinHitAngle(frontRightPoint, center, false, ref minHit); frontLeftPoint = headingVec * TahoeParams.FL + headingVec90 * TahoeParams.T / 2; frontRightPoint = headingVec * TahoeParams.FL - headingVec90 * TahoeParams.T / 2.0; rearRightPoint = -headingVec * TahoeParams.RL - headingVec90 * TahoeParams.T / 2.0; rearLeftPoint = -headingVec * TahoeParams.RL + headingVec90 * TahoeParams.T / 2.0; List <Polygon> obstacles = GetObstacles(curTimestamp); GetObstacleHitAngle(frontLeftPoint, center, obstacles, ref minHit); GetObstacleHitAngle(rearLeftPoint, center, obstacles, ref minHit); GetObstacleHitAngle(rearRightPoint, center, obstacles, ref minHit); // trim some off the hit for safety' minHit -= (0.3 / minRadius); // move at least 0.6 meters minHit = Math.Max(minHit, 0.6 / minRadius); // calculate the exit stopping point // shift the line by the minimum turning radius Coordinates u = finalOrientation.P1 - finalOrientation.P0; u = u.Normalize().Rotate90(); Line offsetLine = new Line(); offsetLine.P0 = finalOrientation.P0 + u * (minRadius + 2); offsetLine.P1 = finalOrientation.P1 + u * (minRadius + 2); // final the intersection of the current turn circle with a radius of twice the min turn radius and the offset line Circle twoTurn = new Circle(2 * minRadius + 2, center); Coordinates[] intersections; double startAngle = (-center).ArcTan; if (twoTurn.Intersect(offsetLine, out intersections)) { // figure out where there were hits for (int i = 0; i < intersections.Length; i++) { // get the angle of the hit double angle = (intersections[i] - center).ArcTan; if (angle < startAngle) { angle += 2 * Math.PI; } angle -= startAngle; if (angle < minHit) { minHit = angle; } } } minHit = Math.Max(minHit, 0.6 / minRadius); // set the stopping point at the min hit point Coordinates stopPoint = rearAxleCircle.GetPoint(startAngle + minHit); // calculate the stop distance stopDistance = rearAxleCircle.r * minHit; stopTimestamp = curTimestamp; curvature = 1 / minRadius; // calculate the required steering angle double steeringCommand = SteeringUtilities.CurvatureToSteeringWheelAngle(-1 / minRadius, uturnSpeed); ISpeedCommandGenerator shiftSpeedCommand = new ShiftSpeedCommand(TransmissionGear.Reverse); ISteeringCommandGenerator initialSteeringCommand = new ConstantSteeringCommandGenerator(steeringCommand, steeringRate, true); ISpeedCommandGenerator passSpeedCommand = new FeedbackSpeedCommandGenerator(new StopSpeedGenerator(new TravelledDistanceProvider(curTimestamp, stopDistance), uturnSpeed)); ISteeringCommandGenerator passSteeringCommand = new ConstantSteeringCommandGenerator(steeringCommand, null, false); ChainedTrackingCommand cmd = new ChainedTrackingCommand( new TrackingCommand(shiftSpeedCommand, initialSteeringCommand, true), new TrackingCommand(passSpeedCommand, passSteeringCommand, false)); cmd.Label = backwardLabel; Services.UIService.PushCircle(new Circle(minRadius, center), curTimestamp, "uturn circle", true); Services.UIService.PushPoint(stopPoint, curTimestamp, "uturn stop point", true); Services.UIService.PushPolygon(polygon, curTimestamp, "uturn polygon", true); return(cmd); }
static string BuildFileContent(TextArea textArea) { StringBuilder rtf = new StringBuilder(); bool firstLine = true; Color curColor = Color.Black; bool oldItalic = false; bool oldBold = false; bool escapeSequence = false; foreach (ISelection selection in textArea.SelectionManager.SelectionCollection) { int selectionOffset = textArea.Document.PositionToOffset(selection.StartPosition); int selectionEndOffset = textArea.Document.PositionToOffset(selection.EndPosition); for (int i = selection.StartPosition.Y; i <= selection.EndPosition.Y; ++i) { LineSegment line = textArea.Document.GetLineSegment(i); int offset = line.Offset; if (line.Words == null) { continue; } foreach (TextWord word in line.Words) { switch (word.Type) { case TextWordType.Space: if (selection.ContainsOffset(offset)) { rtf.Append(' '); } ++offset; break; case TextWordType.Tab: if (selection.ContainsOffset(offset)) { rtf.Append(@"\tab"); } ++offset; escapeSequence = true; break; case TextWordType.Word: Color c = word.Color; if (offset + word.Word.Length > selectionOffset && offset < selectionEndOffset) { string colorstr = c.R + ", " + c.G + ", " + c.B; if (!colors.ContainsKey(colorstr)) { colors[colorstr] = ++colorNum; colorString.Append(@"\red" + c.R + @"\green" + c.G + @"\blue" + c.B + ";"); } if (c != curColor || firstLine) { rtf.Append(@"\cf" + colors[colorstr].ToString()); curColor = c; escapeSequence = true; } if (oldItalic != word.Italic) { if (word.Italic) { rtf.Append(@"\i"); } else { rtf.Append(@"\i0"); } oldItalic = word.Italic; escapeSequence = true; } if (oldBold != word.Bold) { if (word.Bold) { rtf.Append(@"\b"); } else { rtf.Append(@"\b0"); } oldBold = word.Bold; escapeSequence = true; } if (firstLine) { rtf.Append(@"\f0\fs" + (textArea.TextEditorProperties.Font.Size * 2)); firstLine = false; } if (escapeSequence) { rtf.Append(' '); escapeSequence = false; } string printWord; if (offset < selectionOffset) { printWord = word.Word.Substring(selectionOffset - offset); } else if (offset + word.Word.Length > selectionEndOffset) { printWord = word.Word.Substring(0, (offset + word.Word.Length) - selectionEndOffset); } else { printWord = word.Word; } rtf.Append(printWord.Replace(@"\", @"\\").Replace("{", "\\{").Replace("}", "\\}")); } offset += word.Length; break; } } if (offset < selectionEndOffset) { rtf.Append(@"\par"); } rtf.Append('\n'); } } return(rtf.ToString()); }
private void PaintDocumentLine(Graphics g, int lineNumber, Rectangle lineRectangle) { Brush bgColorBrush = this.GetBgColorBrush(lineNumber); Brush brush = this.textArea.Enabled ? bgColorBrush : SystemBrushes.InactiveBorder; if (lineNumber >= this.textArea.Document.TotalNumberOfLines) { g.FillRectangle(brush, lineRectangle); if (base.TextEditorProperties.ShowInvalidLines) { this.DrawInvalidLineMarker(g, (float)lineRectangle.Left, (float)lineRectangle.Top); } if (base.TextEditorProperties.ShowVerticalRuler) { this.DrawVerticalRuler(g, lineRectangle); } return; } float num = (float)lineRectangle.X; int num2 = 0; this.physicalColumn = 0; if (base.TextEditorProperties.EnableFolding) { while (true) { ArrayList foldedFoldingsWithStartAfterColumn = this.textArea.Document.FoldingManager.GetFoldedFoldingsWithStartAfterColumn(lineNumber, num2 - 1); if (foldedFoldingsWithStartAfterColumn == null || foldedFoldingsWithStartAfterColumn.Count <= 0) { break; } FoldMarker foldMarker = (FoldMarker)foldedFoldingsWithStartAfterColumn[0]; foreach (FoldMarker foldMarker2 in foldedFoldingsWithStartAfterColumn) { if (foldMarker2.StartColumn < foldMarker.StartColumn) { foldMarker = foldMarker2; } } foldedFoldingsWithStartAfterColumn.Clear(); num = this.PaintLinePart(g, lineNumber, num2, foldMarker.StartColumn, lineRectangle, num); num2 = foldMarker.EndColumn; lineNumber = foldMarker.EndLine; ColumnRange selectionAtLine = this.textArea.SelectionManager.GetSelectionAtLine(lineNumber); bool drawSelected = ColumnRange.WholeColumn.Equals(selectionAtLine) || (foldMarker.StartColumn >= selectionAtLine.StartColumn && foldMarker.EndColumn <= selectionAtLine.EndColumn); num = this.PaintFoldingText(g, lineNumber, num, lineRectangle, foldMarker.FoldText, drawSelected); } if (lineNumber < this.textArea.Document.TotalNumberOfLines) { num = this.PaintLinePart(g, lineNumber, num2, this.textArea.Document.GetLineSegment(lineNumber).Length, lineRectangle, num); } } else { num = this.PaintLinePart(g, lineNumber, 0, this.textArea.Document.GetLineSegment(lineNumber).Length, lineRectangle, num); } if (lineNumber < this.textArea.Document.TotalNumberOfLines) { ColumnRange selectionAtLine2 = this.textArea.SelectionManager.GetSelectionAtLine(lineNumber); LineSegment lineSegment = this.textArea.Document.GetLineSegment(lineNumber); HighlightColor colorFor = this.textArea.Document.HighlightingStrategy.GetColorFor("Selection"); float width = this.GetWidth(g, ' '); bool flag = selectionAtLine2.EndColumn > lineSegment.Length || ColumnRange.WholeColumn.Equals(selectionAtLine2); if (base.TextEditorProperties.ShowEOLMarker) { HighlightColor colorFor2 = this.textArea.Document.HighlightingStrategy.GetColorFor("EOLMarkers"); num += this.DrawEOLMarker(g, colorFor2.Color, flag ? bgColorBrush : brush, num, (float)lineRectangle.Y); } else { if (flag) { g.FillRectangle(BrushRegistry.GetBrush(colorFor.BackgroundColor), new RectangleF(num, (float)lineRectangle.Y, width, (float)lineRectangle.Height)); num += width; } } Brush brush2 = (flag && base.TextEditorProperties.AllowCaretBeyondEOL) ? bgColorBrush : brush; g.FillRectangle(brush2, new RectangleF(num, (float)lineRectangle.Y, (float)lineRectangle.Width - num + (float)lineRectangle.X, (float)lineRectangle.Height)); } if (base.TextEditorProperties.ShowVerticalRuler) { this.DrawVerticalRuler(g, lineRectangle); } }
float PaintLinePart(Graphics g, int lineNumber, int startColumn, int endColumn, Rectangle lineRectangle, float physicalXPos) { bool drawLineMarker = DrawLineMarkerAtLine(lineNumber); Brush bgColorBrush = GetBgColorBrush(lineNumber); Brush backgroundBrush = textArea.Enabled ? bgColorBrush : SystemBrushes.InactiveBorder; HighlightColor selectionColor = textArea.Document.HighlightingStrategy.GetEnvironmentColorForName("Selection"); ColumnRange selectionRange = textArea.SelectionManager.GetSelectionAtLine(lineNumber); HighlightColor tabMarkerColor = textArea.Document.HighlightingStrategy.GetEnvironmentColorForName("TabMarkers"); HighlightColor spaceMarkerColor = textArea.Document.HighlightingStrategy.GetEnvironmentColorForName("SpaceMarkers"); float spaceWidth = GetWidth(g, ' '); LineSegment currentLine = textArea.Document.GetLineSegment(lineNumber); int logicalColumn = startColumn; Brush selectionBackgroundBrush = BrushRegistry.GetBrush(selectionColor.BackgroundColor); Brush unselectedBackgroundBrush = backgroundBrush; if (currentLine.Words != null) { int startword = 0; int wordOffset = 0; //首先查找第一个不是空格或Tab的单词. for (; startword < currentLine.Words.Count; ++startword) { if (wordOffset >= startColumn) { break; } TextWord currentWord = ((TextWord)currentLine.Words[startword]); if (currentWord.Type == TextWordType.Tab) { ++wordOffset; } else if (currentWord.Type == TextWordType.Space) { ++wordOffset; } else { wordOffset += currentWord.Length; } } for (int i = startword; i < currentLine.Words.Count; ++i) { // 到行的末尾(即全部的单词都画完了),则退出for语句. if (logicalColumn >= endColumn) { break; } ArrayList markers = Document.TextMarkerStrategy.GetMarkers(currentLine.Offset + wordOffset); foreach (TextMarker marker in markers) { if (marker.TextMarkerType == TextMarkerType.SolidBlock) { unselectedBackgroundBrush = BrushRegistry.GetBrush(marker.Color); break; } } // Clear old marker arrary // TODO: cut the word if startColumn or endColimn is in the word; // needed for foldings wich can start or end in the middle of a word TextWord currentWord = ((TextWord)currentLine.Words[i]); switch (currentWord.Type) { case TextWordType.Space: RectangleF spaceRectangle = new RectangleF(physicalXPos, lineRectangle.Y, (float)Math.Ceiling(spaceWidth), lineRectangle.Height); Brush spaceBackgroundBrush; if (ColumnRange.WholeColumn.Equals(selectionRange) || logicalColumn >= selectionRange.StartColumn && logicalColumn < selectionRange.EndColumn) { spaceBackgroundBrush = selectionBackgroundBrush; } else { Brush markerBrush = GetMarkerBrushAt(currentLine.Offset + logicalColumn, 1); if (!drawLineMarker && markerBrush != null) { spaceBackgroundBrush = markerBrush; } else if (!drawLineMarker && currentWord.HighlightColor != null && currentWord.HighlightColor.HasBackground) { spaceBackgroundBrush = BrushRegistry.GetBrush(currentWord.HighlightColor.BackgroundColor); } else { spaceBackgroundBrush = unselectedBackgroundBrush; } } g.FillRectangle(spaceBackgroundBrush, spaceRectangle); if (TextEditorProperties.ShowSpaces) { DrawSpaceMarker(g, spaceMarkerColor.Color, physicalXPos, lineRectangle.Y); } foreach (TextMarker marker in markers) { DrawMarker(g, marker, spaceRectangle); } physicalXPos += spaceWidth; ++logicalColumn; ++physicalColumn; break; case TextWordType.Tab: int oldPhysicalColumn = physicalColumn; physicalColumn += TextEditorProperties.TabIndent; physicalColumn = (physicalColumn / TextEditorProperties.TabIndent) * TextEditorProperties.TabIndent; float tabWidth = (physicalColumn - oldPhysicalColumn) * spaceWidth; RectangleF tabRectangle = new RectangleF(physicalXPos, lineRectangle.Y, (float)Math.Ceiling(tabWidth), lineRectangle.Height); if (ColumnRange.WholeColumn.Equals(selectionRange) || logicalColumn >= selectionRange.StartColumn && logicalColumn <= selectionRange.EndColumn - 1) { spaceBackgroundBrush = selectionBackgroundBrush; } else { Brush markerBrush = GetMarkerBrushAt(currentLine.Offset + logicalColumn, 1); if (!drawLineMarker && markerBrush != null) { spaceBackgroundBrush = markerBrush; } else if (!drawLineMarker && currentWord.HighlightColor != null && currentWord.HighlightColor.HasBackground) { spaceBackgroundBrush = BrushRegistry.GetBrush(currentWord.HighlightColor.BackgroundColor); } else { spaceBackgroundBrush = unselectedBackgroundBrush; } } g.FillRectangle(spaceBackgroundBrush, tabRectangle); if (TextEditorProperties.ShowTabs) { DrawTabMarker(g, tabMarkerColor.Color, physicalXPos, lineRectangle.Y); } foreach (TextMarker marker in markers) { DrawMarker(g, marker, tabRectangle); } physicalXPos += tabWidth; ++logicalColumn; break; case TextWordType.Word: string word = currentWord.Word; float lastPos = physicalXPos; Brush bgMarkerBrush = GetMarkerBrushAt(currentLine.Offset + logicalColumn, word.Length); Brush wordBackgroundBrush; if (!drawLineMarker && bgMarkerBrush != null) { wordBackgroundBrush = bgMarkerBrush; } else if (!drawLineMarker && currentWord.HighlightColor.HasBackground) { wordBackgroundBrush = BrushRegistry.GetBrush(currentWord.HighlightColor.BackgroundColor); } else { wordBackgroundBrush = unselectedBackgroundBrush; } if (ColumnRange.WholeColumn.Equals(selectionRange) || selectionRange.EndColumn - 1 >= word.Length + logicalColumn && selectionRange.StartColumn <= logicalColumn) { physicalXPos += DrawDocumentWord(g, word, new PointF(physicalXPos, lineRectangle.Y), currentWord.Font, selectionColor.HasForgeground ? selectionColor.Color : currentWord.Color, selectionBackgroundBrush); } else { if (ColumnRange.NoColumn.Equals(selectionRange) /* || selectionRange.StartColumn > logicalColumn + word.Length || selectionRange.EndColumn - 1 <= logicalColumn */) { physicalXPos += DrawDocumentWord(g, word, new PointF(physicalXPos, lineRectangle.Y), currentWord.Font, currentWord.Color, wordBackgroundBrush); } else { int offset1 = Math.Min(word.Length, Math.Max(0, selectionRange.StartColumn - logicalColumn)); int offset2 = Math.Max(offset1, Math.Min(word.Length, selectionRange.EndColumn - logicalColumn)); physicalXPos += DrawDocumentWord(g, word.Substring(0, offset1), new PointF(physicalXPos, lineRectangle.Y), currentWord.Font, currentWord.Color, wordBackgroundBrush); physicalXPos += DrawDocumentWord(g, word.Substring(offset1, offset2 - offset1), new PointF(physicalXPos, lineRectangle.Y), currentWord.Font, selectionColor.HasForgeground ? selectionColor.Color : currentWord.Color, selectionBackgroundBrush); physicalXPos += DrawDocumentWord(g, word.Substring(offset2), new PointF(physicalXPos, lineRectangle.Y), currentWord.Font, currentWord.Color, wordBackgroundBrush); } } // if (markerBrush != null) { // markerBrush.Dispose(); // } foreach (TextMarker marker in markers) { if (marker.TextMarkerType != TextMarkerType.SolidBlock) { DrawMarker(g, marker, new RectangleF(lastPos, lineRectangle.Y, (physicalXPos - lastPos), lineRectangle.Height)); } } // draw bracket highlight if (highlight != null) { if (highlight.OpenBrace.Y == lineNumber && highlight.OpenBrace.X == logicalColumn || highlight.CloseBrace.Y == lineNumber && highlight.CloseBrace.X == logicalColumn) { DrawBracketHighlight(g, new Rectangle((int)lastPos, lineRectangle.Y, (int)(physicalXPos - lastPos) - 1, lineRectangle.Height - 1)); } } physicalColumn += word.Length; logicalColumn += word.Length; break; } markers.Clear(); } //for } //if return(physicalXPos); }
void HandleInput() { float moveSpeed = MovementSpeed * Time.deltaTime; float rotSpeed = TurnSpeed * Time.deltaTime; float vert = Input.GetAxisRaw("Player" + PlayerNumber + "_Vertical"); float hori = Input.GetAxisRaw("Player" + PlayerNumber + "_Horizontal"); if (vert > 0) //up { if (World.worldMap[(int)(Y), (int)(X + dirX * moveSpeed)] <= 0) { X += dirX * moveSpeed; } if (World.worldMap[(int)(Y + dirY * moveSpeed), (int)(X)] <= 0) { Y += dirY * moveSpeed; } } //move backwards if no wall behind you if (vert < 0) //down { if (World.worldMap[(int)(Y), (int)(X - dirX * moveSpeed)] <= 0) { X -= dirX * moveSpeed; } if (World.worldMap[(int)(Y - dirY * moveSpeed), (int)(X)] <= 0) { Y -= dirY * moveSpeed; } } //rotate to the right if (hori > 0) //right { //both camera direction and camera plane must be rotated float oldDirX = dirX; dirX = dirX * Mathf.Cos(-rotSpeed) - dirY * Mathf.Sin(-rotSpeed); dirY = oldDirX * Mathf.Sin(-rotSpeed) + dirY * Mathf.Cos(-rotSpeed); float oldPlaneX = planeX; planeX = planeX * Mathf.Cos(-rotSpeed) - planeY * Mathf.Sin(-rotSpeed); planeY = oldPlaneX * Mathf.Sin(-rotSpeed) + planeY * Mathf.Cos(-rotSpeed); } //rotate to the left if (hori < 0) //left { //both camera direction and camera plane must be rotated float oldDirX = dirX; dirX = dirX * Mathf.Cos(rotSpeed) - dirY * Mathf.Sin(rotSpeed); dirY = oldDirX * Mathf.Sin(rotSpeed) + dirY * Mathf.Cos(rotSpeed); float oldPlaneX = planeX; planeX = planeX * Mathf.Cos(rotSpeed) - planeY * Mathf.Sin(rotSpeed); planeY = oldPlaneX * Mathf.Sin(rotSpeed) + planeY * Mathf.Cos(rotSpeed); } bool canshoot = FpsGameModeInstance.IsOpened; if (canshoot && Input.GetButtonDown("Player" + PlayerNumber + "_Fire")) { lastFireTime = Time.time; int clipnum = UnityEngine.Random.Range(0, ShotSounds.Length - 1); audioSource.PlayOneShot(ShotSounds[clipnum]); Vector2 start = new Vector2(X, Y); LineSegment line = new LineSegment(start, start + new Vector2(dirX, dirY) * ShotRange); Vector2 dir = new Vector2(dirX, dirY) * ShotRange; ContactFilter2D filter = new ContactFilter2D(); RaycastHit2D[] hits = new RaycastHit2D[20]; Vector2 hitVector = new Vector2(); if (GridSystem.IntersectsElement(start, dir, World, Renderer.Rect.rect.width, out hitVector) == true) { int amount = Physics2D.Raycast(line.Start, dir, filter, hits, (hitVector - line.Start).magnitude); if (amount > 0) { for (var i = 0; i < amount; i++) { var hit = hits[i]; if (hit.collider == collider2D) { continue; } m_pointsystem.ShotPlayer(); //-----------------------------------------Add Points shooting------------------------------// Debug.Log("Shot someone!!!"); var player = hit.collider.GetComponent <FPSPlayer>(); if (player) { //player.Health -= DamagePerShot; player.Hit(DamagePerShot, this); player.Pointsystem.GotShot(); } } } else { return; } } } }
void Update() { // for intersection checking sample points if (_segments.Count > 2) { //Debug.Log("Segment intersection test begin!"); Vector3 pos3 = transform.transform.position; Vector2 pos = new Vector2(pos3.x, pos3.y); Vector2 end = ((LineSegment)_segments[_segments.Count - 1]).pos; Vector2 aabb_min, aabb_max; if (end.x < pos.x) { aabb_min.x = end.x; aabb_max.x = pos.x; } else { aabb_min.x = pos.x; aabb_max.x = end.x; } if (end.y < pos.y) { aabb_min.y = end.y; aabb_max.y = pos.y; } else { aabb_min.y = pos.y; aabb_max.y = end.y; } for (int i = 0; i < _segments.Count - 2; ++i) { LineSegment seg = (LineSegment)_segments[i]; if (seg.IntersectP(aabb_min, aabb_max)) { CreatePolygon(pos, i + 1); break; } } } if (emit && emitTime != 0) { emitTime -= Time.deltaTime; if (emitTime == 0) { emitTime = -1; } if (emitTime < 0) { emit = false; } } if (!emit && points.Count == 0 && autoDestruct) { Destroy(o); Destroy(gameObject); } // early out if there is no camera if (!Camera.main) { return; } bool re = false; // if we have moved enough, create a new vertex and make sure we rebuild the mesh float theDistance = (lastPosition - transform.position).magnitude; if (emit) { if (theDistance > minVertexDistance) { bool make = false; if (points.Count < 3) { make = true; } else { Vector3 l1 = ((Point)points[points.Count - 2]).position - ((Point)points[points.Count - 3]).position; Vector3 l2 = ((Point)points[points.Count - 1]).position - ((Point)points[points.Count - 2]).position; if (Vector3.Angle(l1, l2) > maxAngle || theDistance > maxVertexDistance) { make = true; } } if (make) { Point p = new Point(); p.position = transform.position; p.timeCreated = Time.time; points.Add(p); lastPosition = transform.position; AddSegmentsPoints(transform.position); } else { ((Point)points[points.Count - 1]).position = transform.position; ((Point)points[points.Count - 1]).timeCreated = Time.time; } } else if (points.Count > 0) { ((Point)points[points.Count - 1]).position = transform.position; ((Point)points[points.Count - 1]).timeCreated = Time.time; } } if (!emit && lastFrameEmit && points.Count > 0) { ((Point)points[points.Count - 1]).lineBreak = true; } lastFrameEmit = emit; // approximate if we should rebuild the mesh or not if (points.Count > 1) { Vector3 cur1 = Camera.main.WorldToScreenPoint(((Point)points[0]).position); lastCameraPosition1.z = 0; Vector3 cur2 = Camera.main.WorldToScreenPoint(((Point)points[points.Count - 1]).position); lastCameraPosition2.z = 0; float distance = (lastCameraPosition1 - cur1).magnitude; distance += (lastCameraPosition2 - cur2).magnitude; if (distance > movePixelsForRebuild || Time.time - lastRebuildTime > maxRebuildTime) { re = true; lastCameraPosition1 = cur1; lastCameraPosition2 = cur2; } } else { re = true; } if (re) { lastRebuildTime = Time.time; ArrayList remove = new ArrayList(); //ArrayList remove_seg = new ArrayList(); int i = 0; foreach (Point p in points) { bool add = false; // cull old points first if (p.dead && Time.time - p.transTime > deadTime) { add = true; } else if (p.highlight && Time.time - p.transTime > highlightTime) { add = true; } else if (Time.time - p.timeCreated > lifeTime) { add = true; } if (add) { remove.Add(p); //remove_seg.Add(_segments[i]); } i++; } foreach (Point p in remove) { points.Remove(p); } remove.Clear(); //foreach (LineSegment s in remove_seg) _segments.Remove(s); //remove_seg.Clear(); if (points.Count > 1) { Vector3[] newVertices = new Vector3[points.Count * 2]; Vector2[] newUV = new Vector2[points.Count * 2]; int[] newTriangles = new int[(points.Count - 1) * 6]; Color[] newColors = new Color[points.Count * 2]; i = 0; float curDistance = 0.00f; foreach (Point p in points) { float time = (Time.time - p.timeCreated) / lifeTime; time = time * 0.5f + 0.5f; if (p.dead && p.transTime + deadTime < p.timeCreated + lifeTime) { time = (p.transTime - p.timeCreated) / lifeTime + (Time.time - p.transTime) / deadTime; time = time * 0.5f + 0.5f; } else if (p.highlight) { time = (Time.time - p.transTime) / highlightTime; if (time > 1) { time = 1f; } } Color color = Color.Lerp(Color.white, Color.clear, time); if (colors != null && colors.Length > 0) { float colorTime = time * (colors.Length - 1); float min = Mathf.Floor(colorTime); float max = Mathf.Clamp(Mathf.Ceil(colorTime), 1, colors.Length - 1); float lerp = Mathf.InverseLerp(min, max, colorTime); if (min >= colors.Length) { min = colors.Length - 1; } if (min < 0) { min = 0; } if (max >= colors.Length) { max = colors.Length - 1; } if (max < 0) { max = 0; } color = Color.Lerp(colors[(int)min], colors[(int)max], lerp); } float size = 1f; if (sizes != null && sizes.Length > 0) { float sizeTime = time * (sizes.Length - 1); float min = Mathf.Floor(sizeTime); float max = Mathf.Clamp(Mathf.Ceil(sizeTime), 1, sizes.Length - 1); float lerp = Mathf.InverseLerp(min, max, sizeTime); if (min >= sizes.Length) { min = sizes.Length - 1; } if (min < 0) { min = 0; } if (max >= sizes.Length) { max = sizes.Length - 1; } if (max < 0) { max = 0; } size = Mathf.Lerp(sizes[(int)min], sizes[(int)max], lerp); } Vector3 lineDirection = Vector3.zero; if (i == 0) { lineDirection = p.position - ((Point)points[i + 1]).position; } else { lineDirection = ((Point)points[i - 1]).position - p.position; } Vector3 vectorToCamera = Camera.main.transform.position - p.position; Vector3 perpendicular = Vector3.Cross(lineDirection, vectorToCamera).normalized; newVertices[i * 2] = p.position + (perpendicular * (size * 0.5f)); newVertices[(i * 2) + 1] = p.position + (-perpendicular * (size * 0.5f)); newColors[i * 2] = newColors[(i * 2) + 1] = color; newUV[i * 2] = new Vector2(curDistance * uvLengthScale, 0); newUV[(i * 2) + 1] = new Vector2(curDistance * uvLengthScale, 1); if (i > 0 && !((Point)points[i - 1]).lineBreak) { if (higherQualityUVs) { curDistance += (p.position - ((Point)points[i - 1]).position).magnitude; } else { curDistance += (p.position - ((Point)points[i - 1]).position).sqrMagnitude; } newTriangles[(i - 1) * 6] = (i * 2) - 2; newTriangles[((i - 1) * 6) + 1] = (i * 2) - 1; newTriangles[((i - 1) * 6) + 2] = i * 2; newTriangles[((i - 1) * 6) + 3] = (i * 2) + 1; newTriangles[((i - 1) * 6) + 4] = i * 2; newTriangles[((i - 1) * 6) + 5] = (i * 2) - 1; } i++; } Mesh mesh = (o.GetComponent(typeof(MeshFilter)) as MeshFilter).mesh; mesh.Clear(); mesh.vertices = newVertices; mesh.colors = newColors; mesh.uv = newUV; mesh.triangles = newTriangles; } } }
public HingeJoint(LineSegment centerLine, RaytraceableFunction1D radius) { articularSurface = new SymmetricCylinder(centerLine, radius); }
public void UpdatePlot() { int numPoints = (int)PlotCanvas.ActualWidth; double xScale = (plot.EndX - plot.StartX) / (double)numPoints; double minY = double.MaxValue; double maxY = double.MinValue; foreach (PlotFunction plotFunction in plot.PlotFunctions) { for (int pos = 0; pos < numPoints; pos++) { plot.SetX((double)pos * xScale); double value = plot.GetY(plotFunction.Name); if (value < minY) { minY = value; } if (value > maxY) { maxY = value; } } } PlotCanvas.Children.Clear(); int colorPos = 0; foreach (PlotFunction plotFunction in plot.PlotFunctions) { Path plotPath = new Path(); plotPath.StrokeThickness = 2; plotPath.Stroke = new SolidColorBrush(colors[colorPos]); colorPos++; if (colorPos > colors.Length) { colorPos = 0; } PathGeometry pathGeometry = new PathGeometry(); pathGeometry.Figures = new PathFigureCollection(); plotPath.Data = pathGeometry; PlotCanvas.Children.Add(plotPath); PathFigure pathFigure = new PathFigure(); pathFigure.StartPoint = new Point(0, 0); pathFigure.IsClosed = false; pathFigure.Segments = new PathSegmentCollection(); pathGeometry.Figures.Add(pathFigure); for (int pos = 0; pos < numPoints; pos++) { double x = (double)pos * xScale; plot.SetX(x); double y = plot.GetY(plotFunction.Name); double yScale = (y - minY) / (maxY - minY); double plotY = PlotCanvas.ActualHeight - (PlotCanvas.ActualHeight * yScale); LineSegment lineSegment = new LineSegment(); lineSegment.IsStroked = (pos != 0); lineSegment.Point = new Point((double)pos, plotY); pathFigure.Segments.Add(lineSegment); } } }
public HingeJoint(LineSegment centerLine, RaytraceableFunction1D radius, ContinuousMap <double, double> startAngle, ContinuousMap <double, double> endAngle) { articularSurface = new SymmetricCylinder(centerLine, radius, startAngle, endAngle); }
private void SetPathData() { if (Points == null) { return; } var points = new List <Point>(); foreach (var point in Points) { var pointProperties = point.GetType().GetProperties(); if (pointProperties.All(p => p.Name != "X") || pointProperties.All(p => p.Name != "Y")) { continue; } var x = (double)point.GetType().GetProperty("X").GetValue(point, new object[] { }); var y = (double)point.GetType().GetProperty("Y").GetValue(point, new object[] { }); points.Add(new Point(x, y)); } if (points.Count <= 1) { return; } var Teeth_PathFigure = new PathFigure { StartPoint = points.FirstOrDefault() }; var Teeth_SegmentCollection = new PathSegmentCollection(); var bezierSegments = InterpolationUtils.InterpolatePointWithBezierCurves(points, true); if (bezierSegments == null || bezierSegments.Count < 1) { foreach (var point in points.GetRange(1, points.Count - 1)) { var lineSegment = new LineSegment { Point = point }; Teeth_SegmentCollection.Add(lineSegment); } } else { foreach (var curveSeg in bezierSegments) { var segment = new BezierSegment { Point1 = curveSeg.FirstControlPoint, Point2 = curveSeg.SecondControlPoint, Point3 = curveSeg.EndPoint }; Teeth_SegmentCollection.Add(segment); } } Teeth_PathFigure.Segments = Teeth_SegmentCollection; var Teeth_PathFigureCollection = new PathFigureCollection { Teeth_PathFigure }; var Teeth_PathGeometry = new PathGeometry { Figures = Teeth_PathFigureCollection }; path.Data = Teeth_PathGeometry; }
private void AddGeometry(StringBuilder svgString, PathGeometry path) { svgString.Append("<path d=\""); foreach (PathFigure pf in path.Figures) { svgString.Append("M "); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", pf.StartPoint.X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", pf.StartPoint.Y); foreach (PathSegment ps in pf.Segments) { if (ps is PolyLineSegment) { PolyLineSegment seg = ps as PolyLineSegment; for (int i = 0; i < seg.Points.Count; ++i) { svgString.Append("L "); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", seg.Points[i].X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", seg.Points[i].Y); } } else if (ps is PolyBezierSegment) { PolyBezierSegment seg = ps as PolyBezierSegment; for (int i = 0; i < seg.Points.Count; i += 3) { svgString.Append("C "); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", seg.Points[i].X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", seg.Points[i].Y); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", seg.Points[i + 1].X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", seg.Points[i + 1].Y); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", seg.Points[i + 2].X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", seg.Points[i + 2].Y); } } else if (ps is LineSegment) { LineSegment seg = ps as LineSegment; svgString.Append("L "); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", seg.Point.X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", seg.Point.Y); } else if (ps is BezierSegment) { BezierSegment seg = ps as BezierSegment; svgString.Append("C "); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", seg.Point1.X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", seg.Point1.Y); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", seg.Point2.X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", seg.Point2.Y); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", seg.Point3.X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", seg.Point3.Y); } else if (ps is QuadraticBezierSegment) { //Untested: BuildGeometry converts quadratic bezier to cubic QuadraticBezierSegment seg = ps as QuadraticBezierSegment; svgString.Append("Q "); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", seg.Point1.X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", seg.Point1.Y); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", seg.Point2.X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", seg.Point2.Y); } else if (ps is PolyQuadraticBezierSegment) { //Untested: BuildGeometry converts quadratic bezier to cubic PolyQuadraticBezierSegment seg = ps as PolyQuadraticBezierSegment; for (int i = 0; i < seg.Points.Count; i += 2) { svgString.Append("Q "); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", seg.Points[i].X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", seg.Points[i].Y); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", seg.Points[i + 1].X); svgString.AppendFormat(CultureInfo.InvariantCulture, "{0} ", seg.Points[i + 1].Y); } } else { Debug.Assert(false); //If asserted, implement segment type } } if (pf.IsClosed) { svgString.Append("Z "); } } svgString.Append("\" fill = \"black\" />"); svgString.Append(Environment.NewLine); }
/// <summary> /// Gets the line segment starting at <paramref name="index"/> /// </summary> /// <param name="index">The index of the segment</param> /// <param name="ls">The line segment to extract to</param> public void GetLineSegment(int index, ref LineSegment ls) { ls.P0 = _pts[index]; ls.P1 = _pts[index + 1]; }