Code

fix pasting style after copying a text span
[inkscape.git] / src / libavoid / geometry.cpp
1 /*
2  * vim: ts=4 sw=4 et tw=0 wm=0
3  *
4  * libavoid - Fast, Incremental, Object-avoiding Line Router
5  * Copyright (C) 2004-2006  Michael Wybrow <mjwybrow@users.sourceforge.net>
6  *
7  * --------------------------------------------------------------------
8  * Much of the code in this module is based on code published with
9  * and/or described in "Computational Geometry in C" (Second Edition),
10  * Copyright (C) 1998  Joseph O'Rourke <orourke@cs.smith.edu>
11  * --------------------------------------------------------------------
12  * The segmentIntersectPoint function is based on code published and
13  * described in Franklin Antonio, Faster Line Segment Intersection,
14  * Graphics Gems III, p. 199-202, code: p. 500-501.
15  * --------------------------------------------------------------------
16  *
17  * This library is free software; you can redistribute it and/or
18  * modify it under the terms of the GNU Lesser General Public
19  * License as published by the Free Software Foundation; either
20  * version 2.1 of the License, or (at your option) any later version.
21  *
22  * This library is distributed in the hope that it will be useful,
23  * but WITHOUT ANY WARRANTY; without even the implied warranty of
24  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
25  * Lesser General Public License for more details.
26  *
27  * You should have received a copy of the GNU Lesser General Public
28  * License along with this library; if not, write to the Free Software
29  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
30  *
31 */
33 #include "libavoid/graph.h"
34 #include "libavoid/geometry.h"
35 #include "libavoid/polyutil.h"
37 #include <math.h>
39 namespace Avoid {
42 Point::Point()
43 {
44 }
47 Point::Point(const double xv, const double yv)
48     : x(xv)
49     , y(yv)
50 {
51 }
54 bool Point::operator==(const Point& rhs) const
55 {
56     if ((x == rhs.x) && (y == rhs.y))
57     {
58         return true;
59     }
60     return false;
61 }
64 bool Point::operator!=(const Point& rhs) const
65 {
66     if ((x != rhs.x) || (y != rhs.y))
67     {
68         return true;
69     }
70     return false;
71 }
74 // Returns true iff the point c lies on the closed segment ab.
75 //
76 // Based on the code of 'Between'.
77 //
78 static const bool inBetween(const Point& a, const Point& b, const Point& c)
79 {
80     // We only call this when we know the points are collinear,
81     // otherwise we should be checking this here.
82     assert(vecDir(a, b, c) == 0);
84     if (a.x != b.x)
85     {
86         // not vertical
87         return (((a.x < c.x) && (c.x < b.x)) ||
88                 ((b.x < c.x) && (c.x < a.x)));
89     }
90     else
91     {
92         return (((a.y < c.y) && (c.y < b.y)) ||
93                 ((b.y < c.y) && (c.y < a.y)));
94     }
95 }
98 // Returns true if the segment cd intersects the segment ab, blocking
99 // visibility.
100 //
101 // Based on the code of 'IntersectProp' and 'Intersect'.
102 //
103 bool segmentIntersect(const Point& a, const Point& b, const Point& c,
104         const Point& d)
106     int ab_c = vecDir(a, b, c);
107     if ((ab_c == 0) && inBetween(a, b, c))
108     {
109         return true;
110     }
112     int ab_d = vecDir(a, b, d);
113     if ((ab_d == 0) && inBetween(a, b, d))
114     {
115         return true;
116     }
118     // It's ok for either of the points a or b to be on the line cd,
119     // so we don't have to check the other two cases.
121     int cd_a = vecDir(c, d, a);
122     int cd_b = vecDir(c, d, b);
124     // Is an intersection if a and b are on opposite sides of cd,
125     // and c and d are on opposite sides of the line ab.
126     //
127     // Note: this is safe even though the textbook warns about it
128     // since, unlike them, our vecDir is equivilent to 'AreaSign'
129     // rather than 'Area2'.
130     return (((ab_c * ab_d) < 0) && ((cd_a * cd_b) < 0));
134 // Returns true iff the point p in a valid region that can contain
135 // shortest paths.  a0, a1, a2 are ordered vertices of a shape.
136 //
137 // Based on the code of 'InCone'.
138 //
139 bool inValidRegion(bool IgnoreRegions, const Point& a0, const Point& a1,
140         const Point& a2, const Point& b)
142     // r is a0--a1
143     // s is a1--a2
145     int rSide = vecDir(b, a0, a1);
146     int sSide = vecDir(b, a1, a2);
148     bool rOutOn = (rSide <= 0);
149     bool sOutOn = (sSide <= 0);
151     bool rOut = (rSide < 0);
152     bool sOut = (sSide < 0);
154     if (vecDir(a0, a1, a2) > 0)
155     {
156         // Convex at a1:
157         //
158         //   !rO      rO
159         //    sO      sO
160         //
161         // ---s---+
162         //        |
163         //   !rO  r   rO
164         //   !sO  |  !sO
165         //
166         //
167         if (IgnoreRegions)
168         {
169             return (rOutOn && !sOut) || (!rOut && sOutOn);
170         }
171         return (rOutOn || sOutOn);
172     }
173     else
174     {
175         // Concave at a1:
176         //
177         //   !rO      rO
178         //   !sO     !sO
179         //
180         //        +---s---
181         //        |
182         //   !rO  r   rO
183         //    sO  |   sO
184         //
185         //
186         return (IgnoreRegions ? false : (rOutOn && sOutOn));
187     }
191 // Gives the side of a corner that a point lies on:
192 //      1   anticlockwise
193 //     -1   clockwise
194 // e.g.                     /|s2
195 //       /s3          -1   / |
196 //      /                 /  |
197 //  1  |s2  -1           / 1 |  -1
198 //     |                /    |
199 //     |s1           s3/     |s1
200 //     
201 int cornerSide(const Point &c1, const Point &c2, const Point &c3,
202         const Point& p)
204     int s123 = vecDir(c1, c2, c3);
205     int s12p = vecDir(c1, c2, p);
206     int s23p = vecDir(c2, c3, p);
208     if (s12p == 0)
209     {
210         // Case of p being somewhere on c1-c2.
211         return s23p;
212     }
213     if (s23p == 0)
214     {
215         // Case of p being somewhere on c2-c3.
216         return s12p;
217     }
219     if (s123 == 1)
220     {
221         if ((s12p == 1) && (s23p == 1))
222         {
223             return 1;
224         }
225         return -1;
226     }
227     else if (s123 == -1)
228     {
229         if ((s12p == -1) && (s23p == -1))
230         {
231             return -1;
232         }
233         return 1;
234     }
235     // Case of c3 being somewhere on c1-c2.
236     return s12p;
240 // Returns the distance between points a and b.
241 //
242 double dist(const Point& a, const Point& b)
244     double xdiff = a.x - b.x;
245     double ydiff = a.y - b.y;
247     return sqrt((xdiff * xdiff) + (ydiff * ydiff));
250 // Returns the total length of all line segments in the polygon
251 double totalLength(const Polygn& poly)
253     double l = 0;
254     for (int i = 0; i < poly.pn-1; ++i) {
255         l += dist(poly.ps[i], poly.ps[i+1]);
256     }
257     return l;
260 // Uses the dot-product rule to find the angle (radians) between ab and bc
261 double angle(const Point& a, const Point& b, const Point& c)
263     double ux = b.x - a.x,
264            uy = b.y - a.y,
265            vx = c.x - b.x,
266            vy = c.y - b.y,
267            lu = sqrt(ux*ux+uy*uy),
268            lv = sqrt(vx*vx+vy*vy),
269            udotv = ux * vx + uy * vy,
270            costheta = udotv / (lu * lv);
271     return acos(costheta);
274 // Returns true iff the point q is inside (or on the edge of) the
275 // polygon argpoly.
276 //
277 // This is a fast version that only works for convex shapes.  The
278 // other version (inPolyGen) is more general.
279 //
280 bool inPoly(const Polygn& poly, const Point& q)
282     int n = poly.pn;
283     Point *P = poly.ps;
284     for (int i = 0; i < n; i++)
285     {
286         // point index; i1 = i-1 mod n
287         int prev = (i + n - 1) % n;
288         if (vecDir(P[prev], P[i], q) == -1)
289         {
290             return false;
291         }
292     }
293     return true;
297 // Returns true iff the point q is inside (or on the edge of) the
298 // polygon argpoly.
299 //
300 // Based on the code of 'InPoly'.
301 //
302 bool inPolyGen(const Polygn& argpoly, const Point& q)
304     // Numbers of right and left edge/ray crossings.
305     int Rcross = 0;
306     int Lcross = 0;
308     // Copy the argument polygon
309     Polygn poly = copyPoly(argpoly);
310     Point *P = poly.ps;
311     int    n = poly.pn;
313     // Shift so that q is the origin. This is done for pedogical clarity.
314     for (int i = 0; i < n; ++i)
315     {
316         P[i].x = P[i].x - q.x;
317         P[i].y = P[i].y - q.y;
318     }
320     // For each edge e=(i-1,i), see if crosses ray.
321     for (int i = 0; i < n; ++i)
322     {
323         // First see if q=(0,0) is a vertex.
324         if ((P[i].x == 0) && (P[i].y == 0))
325         {
326             // We count a vertex as inside.
327             freePoly(poly);
328             return true;
329         }
331         // point index; i1 = i-1 mod n
332         int i1 = ( i + n - 1 ) % n;
334         // if e "straddles" the x-axis...
335         // The commented-out statement is logically equivalent to the one
336         // following.
337         // if( ((P[i].y > 0) && (P[i1].y <= 0)) ||
338         //         ((P[i1].y > 0) && (P[i].y <= 0)) )
340         if ((P[i].y > 0) != (P[i1].y > 0))
341         {
342             // e straddles ray, so compute intersection with ray.
343             double x = (P[i].x * P[i1].y - P[i1].x * P[i].y)
344                     / (P[i1].y - P[i].y);
346             // crosses ray if strictly positive intersection.
347             if (x > 0)
348             {
349                 Rcross++;
350             }
351         }
353         // if e straddles the x-axis when reversed...
354         // if( ((P[i].y < 0) && (P[i1].y >= 0)) ||
355         //         ((P[i1].y < 0) && (P[i].y >= 0)) )
357         if ((P[i].y < 0) != (P[i1].y < 0))
358         {
359             // e straddles ray, so compute intersection with ray.
360             double x = (P[i].x * P[i1].y - P[i1].x * P[i].y)
361                     / (P[i1].y - P[i].y);
363             // crosses ray if strictly positive intersection.
364             if (x < 0)
365             {
366                 Lcross++;
367             }
368         }
369     }
370     freePoly(poly);
372     // q on the edge if left and right cross are not the same parity.
373     if ( (Rcross % 2) != (Lcross % 2) )
374     {
375         // We count the edge as inside.
376         return true;
377     }
379     // Inside iff an odd number of crossings.
380     if ((Rcross % 2) == 1)
381     {
382         return true;
383     }
385     // Outside.
386     return false;
391 // Line Segment Intersection
392 // Original code by Franklin Antonio 
393 // 
394 // The SAME_SIGNS macro assumes arithmetic where the exclusive-or
395 // operation will work on sign bits.  This works for twos-complement,
396 // and most other machine arithmetic.
397 #define SAME_SIGNS( a, b ) \
398         (((long) ((unsigned long) a ^ (unsigned long) b)) >= 0 )
399 // 
400 int segmentIntersectPoint(const Point& a1, const Point& a2,
401         const Point& b1, const Point& b2, double *x, double *y) 
404     double Ax,Bx,Cx,Ay,By,Cy,d,e,f,num,offset;
405     double x1lo,x1hi,y1lo,y1hi;
407     Ax = a2.x - a1.x;
408     Bx = b1.x - b2.x;
410     // X bound box test:
411     if (Ax < 0)
412     {
413         x1lo = a2.x;
414         x1hi = a1.x;
415     }
416     else
417     {
418         x1hi = a2.x;
419         x1lo = a1.x;
420     }
421     if (Bx > 0)
422     {
423         if (x1hi < b2.x || b1.x < x1lo) return DONT_INTERSECT;
424     }
425     else
426     {
427         if (x1hi < b1.x || b2.x < x1lo) return DONT_INTERSECT;
428     }
430     Ay = a2.y - a1.y;
431     By = b1.y - b2.y;
433     // Y bound box test:
434     if (Ay < 0)
435     {
436         y1lo = a2.y;
437         y1hi = a1.y;
438     }
439     else
440     {
441         y1hi = a2.y;
442         y1lo = a1.y;
443     }
444     if (By > 0)
445     {
446         if (y1hi < b2.y || b1.y < y1lo) return DONT_INTERSECT;
447     }
448     else
449     {
450         if (y1hi < b1.y || b2.y < y1lo) return DONT_INTERSECT;
451     }
454     Cx = a1.x - b1.x;
455     Cy = a1.y - b1.y;
456     // alpha numerator:
457     d = By*Cx - Bx*Cy;
458     // Both denominator:
459     f = Ay*Bx - Ax*By;
460     // aplha tests:
461     if (f > 0)
462     {
463         if (d < 0 || d > f) return DONT_INTERSECT;
464     }
465     else
466     {
467         if (d > 0 || d < f) return DONT_INTERSECT;
468     }
470     // beta numerator:
471     e = Ax*Cy - Ay*Cx;       
472     // beta tests:
473     if (f > 0)
474     {
475         if (e < 0 || e > f) return DONT_INTERSECT;
476     }
477     else
478     {
479         if (e > 0 || e < f) return DONT_INTERSECT;
480     }
482     // compute intersection coordinates:
484     if (f == 0) return PARALLEL;
485     
486     // Numerator:
487     num = d*Ax;
488     // Round direction:
489     offset = SAME_SIGNS(num,f) ? f/2 : -f/2;
490     // Intersection X:
491     *x = a1.x + (num+offset) / f;
493     num = d*Ay;
494     offset = SAME_SIGNS(num,f) ? f/2 : -f/2;
495     // Intersection Y:
496     *y = a1.y + (num+offset) / f;
498     return DO_INTERSECT;