Inkscape
Vector Graphics Editor
Loading...
Searching...
No Matches
curve.cpp
Go to the documentation of this file.
1/* Abstract curve type - implementation of default methods
2 *
3 * Authors:
4 * MenTaLguY <mental@rydia.net>
5 * Marco Cecchetti <mrcekets at gmail.com>
6 * Krzysztof Kosiński <tweenk.pl@gmail.com>
7 * Rafał Siejakowski <rs@rs-math.net>
8 *
9 * Copyright 2007-2009 Authors
10 *
11 * This library is free software; you can redistribute it and/or
12 * modify it either under the terms of the GNU Lesser General Public
13 * License version 2.1 as published by the Free Software Foundation
14 * (the "LGPL") or, at your option, under the terms of the Mozilla
15 * Public License Version 1.1 (the "MPL"). If you do not alter this
16 * notice, a recipient may use your version of this file under either
17 * the MPL or the LGPL.
18 *
19 * You should have received a copy of the LGPL along with this library
20 * in the file COPYING-LGPL-2.1; if not, write to the Free Software
21 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
22 * You should have received a copy of the MPL along with this library
23 * in the file COPYING-MPL-1.1
24 *
25 * The contents of this file are subject to the Mozilla Public License
26 * Version 1.1 (the "License"); you may not use this file except in
27 * compliance with the License. You may obtain a copy of the License at
28 * http://www.mozilla.org/MPL/
29 *
30 * This software is distributed on an "AS IS" basis, WITHOUT WARRANTY
31 * OF ANY KIND, either express or implied. See the LGPL or the MPL for
32 * the specific language governing rights and limitations.
33 */
34
35#include <2geom/curve.h>
36#include <2geom/exception.h>
37#include <2geom/nearest-time.h>
40#include <2geom/ord.h>
41#include <2geom/path-sink.h>
42
43namespace Geom
44{
45
47{
48 return nearest_time(p, toSBasis(), a, b);
49}
50
51std::vector<Coord> Curve::allNearestTimes(Point const& p, Coord from, Coord to) const
52{
53 return all_nearest_times(p, toSBasis(), from, to);
54}
55
56Coord Curve::length(Coord tolerance) const
57{
58 return ::Geom::length(toSBasis(), tolerance);
59}
60
61int Curve::winding(Point const &p) const
62{
63 try {
64 std::vector<Coord> ts = roots(p[Y], Y);
65 if(ts.empty()) return 0;
66 std::sort(ts.begin(), ts.end());
67
68 // skip endpoint roots when they are local maxima on the Y axis
69 // this follows the convention used in other winding routines,
70 // i.e. that the bottommost coordinate is not part of the shape
71 bool ignore_0 = unitTangentAt(0)[Y] <= 0;
72 bool ignore_1 = unitTangentAt(1)[Y] >= 0;
73
74 int wind = 0;
75 for (double t : ts) {
76 //std::cout << t << std::endl;
77 if ((t == 0 && ignore_0) || (t == 1 && ignore_1)) continue;
78 if (valueAt(t, X) > p[X]) { // root is ray intersection
79 Point tangent = unitTangentAt(t);
80 if (tangent[Y] > 0) {
81 // at the point of intersection, curve goes in +Y direction,
82 // so it winds in the direction of positive angles
83 ++wind;
84 } else if (tangent[Y] < 0) {
85 --wind;
86 }
87 }
88 }
89 return wind;
90 } catch (InfiniteSolutions const &e) {
91 // this means we encountered a line segment exactly coincident with the point
92 // skip, since this will be taken care of by endpoint roots in other segments
93 return 0;
94 }
95}
96
97std::vector<CurveIntersection> Curve::intersect(Curve const &/*other*/, Coord /*eps*/) const
98{
99 // TODO: approximate as Bezier
100 THROW_NOTIMPLEMENTED();
101}
102
103std::vector<CurveIntersection> Curve::intersectSelf(Coord eps) const
104{
106 struct Subcurve
107 {
108 std::unique_ptr<Curve> curve;
109 Interval parameter_range;
110
111 Subcurve(Curve *piece, Coord from, Coord to)
112 : curve{piece}
113 , parameter_range{from, to}
114 {}
115 };
116
118 auto const split_into_subcurves = [this] (std::vector<Coord> const &splits) {
119 std::vector<Subcurve> result;
120 result.reserve(splits.size() + 1);
121 Coord previous = 0;
122 for (Coord split : splits) {
123 // Use global EPSILON since we're operating on normalized curve times.
124 if (split < EPSILON || split > 1.0 - EPSILON) {
125 continue;
126 }
127 result.emplace_back(portion(previous, split), previous, split);
128 previous = split;
129 }
130 result.emplace_back(portion(previous, 1.0), previous, 1.0);
131 return result;
132 };
133
135 auto const pairwise_intersect = [=](std::vector<Subcurve> const &subcurves) {
136 std::vector<CurveIntersection> result;
137 for (unsigned i = 0; i < subcurves.size(); i++) {
138 for (unsigned j = i + 1; j < subcurves.size(); j++) {
139 auto const xings = subcurves[i].curve->intersect(*subcurves[j].curve, eps);
140 for (auto const &xing : xings) {
141 // To avoid duplicate intersections, skip values at exactly 1.
142 if (xing.first == 1. || xing.second == 1.) {
143 continue;
144 }
145 Coord const ti = subcurves[i].parameter_range.valueAt(xing.first);
146 Coord const tj = subcurves[j].parameter_range.valueAt(xing.second);
147 result.emplace_back(ti, tj, xing.point());
148 }
149 }
150 }
151 std::sort(result.begin(), result.end());
152 return result;
153 };
154
155 // Monotonic segments cannot have self-intersections. Thus, we can split
156 // the curve at critical points of the X or Y coordinate and intersect
157 // the portions. However, there's the risk that a juncture between two
158 // adjacent portions is mistaken for an intersection due to numerical errors.
159 // Hence, we run the algorithm for both the X and Y coordinates and only
160 // keep the intersections that show up in both intersection lists.
161
162 // Find the critical points of both coordinates.
163 std::unique_ptr<Curve> deriv{derivative()};
164 auto const crits_x = deriv->roots(0, X);
165 auto const crits_y = deriv->roots(0, Y);
166 if (crits_x.empty() || crits_y.empty()) {
167 return {};
168 }
169
170 // Split into pieces in two ways and find self-intersections.
171 auto const pieces_x = split_into_subcurves(crits_x);
172 auto const pieces_y = split_into_subcurves(crits_y);
173 auto const crossings_from_x = pairwise_intersect(pieces_x);
174 auto const crossings_from_y = pairwise_intersect(pieces_y);
175 if (crossings_from_x.empty() || crossings_from_y.empty()) {
176 return {};
177 }
178
179 // Filter the results, only keeping self-intersections found by both approaches.
180 std::vector<CurveIntersection> result;
181 unsigned index_y = 0;
182 for (auto &&candidate_x : crossings_from_x) {
183 // Find a crossing corresponding to this one in the y-method collection.
184 while (index_y != crossings_from_y.size()) {
185 auto const gap = crossings_from_y[index_y].first - candidate_x.first;
186 if (std::abs(gap) < EPSILON) {
187 // We found the matching intersection!
188 result.emplace_back(candidate_x);
189 index_y++;
190 break;
191 } else if (gap < 0.0) {
192 index_y++;
193 } else {
194 break;
195 }
196 }
197 }
198 return result;
199}
200
201Point Curve::unitTangentAt(Coord t, unsigned n) const
202{
203 std::vector<Point> derivs = pointAndDerivatives(t, n);
204 for (unsigned deriv_n = 1; deriv_n < derivs.size(); deriv_n++) {
205 Coord length = derivs[deriv_n].length();
206 if ( ! are_near(length, 0) ) {
207 // length of derivative is non-zero, so return unit vector
208 return derivs[deriv_n] / length;
209 }
210 }
211 return Point (0,0);
212};
213
214void Curve::feed(PathSink &sink, bool moveto_initial) const
215{
216 std::vector<Point> pts;
217 sbasis_to_bezier(pts, toSBasis(), 2); //TODO: use something better!
218 if (moveto_initial) {
219 sink.moveTo(initialPoint());
220 }
221 sink.curveTo(pts[0], pts[1], pts[2]);
222}
223
224} // namespace Geom
225
226/*
227 Local Variables:
228 mode:c++
229 c-file-style:"stroustrup"
230 c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +))
231 indent-tabs-mode:nil
232 fill-column:99
233 End:
234*/
235// vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4:fileencoding=utf-8:textwidth=99 :
Defines the different types of exceptions that 2geom can throw.
Abstract curve type.
Abstract continuous curve on a plane defined on [0,1].
Definition curve.h:78
virtual D2< SBasis > toSBasis() const =0
Convert the curve to a symmetric power basis polynomial.
virtual Point initialPoint() const =0
Retrieve the start of the curve.
virtual Point unitTangentAt(Coord t, unsigned n=3) const
Compute a vector tangent to the curve.
Definition curve.cpp:201
virtual std::vector< Coord > roots(Coord v, Dim2 d) const =0
Computes time values at which the curve intersects an axis-aligned line.
virtual void feed(PathSink &sink, bool moveto_initial) const
Feed the curve to a PathSink.
Definition curve.cpp:214
virtual std::vector< CurveIntersection > intersect(Curve const &other, Coord eps=EPSILON) const
Compute intersections with another curve.
Definition curve.cpp:97
virtual int winding(Point const &p) const
Compute the partial winding number of this curve.
Definition curve.cpp:61
virtual Coord valueAt(Coord t, Dim2 d) const
Evaluate one of the coordinates at the specified time value.
Definition curve.h:116
virtual std::vector< Coord > allNearestTimes(Point const &p, Coord from=0, Coord to=1) const
Compute time values at which the curve comes closest to a specified point.
Definition curve.cpp:51
virtual Coord nearestTime(Point const &p, Coord a=0, Coord b=1) const
Compute a time value at which the curve comes closest to a specified point.
Definition curve.cpp:46
virtual std::vector< CurveIntersection > intersectSelf(Coord eps=EPSILON) const
Compute intersections of this curve with itself.
Definition curve.cpp:103
virtual Coord length(Coord tolerance=0.01) const
Compute the arc length of this curve.
Definition curve.cpp:56
virtual Curve * derivative() const =0
Create a derivative of this curve.
virtual Curve * portion(Coord a, Coord b) const =0
Create a curve that corresponds to a part of this curve.
virtual std::vector< Point > pointAndDerivatives(Coord t, unsigned n) const =0
Evaluate the curve and its derivatives.
Range of real numbers that is never empty.
Definition interval.h:59
constexpr Coord valueAt(Coord t) const
Map the interval [0,1] onto this one.
Definition interval.h:99
Callback interface for processing path data.
Definition path-sink.h:56
virtual void curveTo(Point const &c0, Point const &c1, Point const &p)=0
Output a quadratic Bezier segment.
virtual void moveTo(Point const &p)=0
Move to a different point without creating a segment.
Two-dimensional point that doubles as a vector.
Definition point.h:66
Css & result
double Coord
Floating point type used to store coordinates.
Definition coord.h:76
constexpr Coord EPSILON
Default "acceptably small" value.
Definition coord.h:84
@ Y
Definition coord.h:48
@ X
Definition coord.h:48
Various utility functions.
Definition affine.h:22
Coord nearest_time(Point const &p, Curve const &c)
Definition curve.h:354
std::vector< double > all_nearest_times(Point const &p, D2< SBasis > const &c, D2< SBasis > const &dc, double from=0, double to=1)
void split(vector< Point > const &p, double t, vector< Point > &left, vector< Point > &right)
void sbasis_to_bezier(Bezier &bz, SBasis const &sb, size_t sz=0)
Changes the basis of p to be bernstein.
bool are_near(Affine const &a1, Affine const &a2, Coord eps=EPSILON)
Nearest time routines for D2<SBasis> and Piecewise<D2<SBasis>>
Comparator template.
callback interface for SVG path data
two-dimensional geometric operators.
Conversion between SBasis and Bezier basis polynomials.
Definition curve.h:24