1 /* === S Y N F I G ========================================================= */
2 /*! \file curve_helper.cpp
3 ** \brief Curve Helper File
5 ** $Id: curve_helper.cpp,v 1.1.1.1 2005/01/04 01:23:14 darco Exp $
8 ** Copyright (c) 2002 Robert B. Quattlebaum Jr.
10 ** This software and associated documentation
11 ** are CONFIDENTIAL and PROPRIETARY property of
12 ** the above-mentioned copyright holder.
14 ** You may not copy, print, publish, or in any
15 ** other way distribute this software without
16 ** a prior written agreement with
17 ** the copyright holder.
20 /* ========================================================================= */
22 /* === H E A D E R S ======================================================= */
31 #include "curve_helper.h"
38 /* === U S I N G =========================================================== */
42 using namespace synfig;
44 /* === M A C R O S ========================================================= */
46 const Real ERROR = 1e-11;
48 /* === G L O B A L S ======================================================= */
50 /* === P R O C E D U R E S ================================================= */
52 /* === M E T H O D S ======================================================= */
54 /* === E N T R Y P O I N T ================================================= */
56 Real synfig::find_closest(const etl::bezier<Point> &curve, const Point &point,
57 float step, Real *dout, float *tout)
60 float time(curve.find_closest(point,4));
61 Real dist((curve(time)-point).mag());
66 Real d,closest = 1.0e50;
67 float t,time,closestt = -1;
76 for(t = step; t < 1; t+=step, p0=p1)
79 d = line_point_distsq(p0,p1,point,time);
84 closestt = t-step + time*step;//t+(time-1)*step; //time between [t-step,t]
88 d = line_point_distsq(p0,end,point,time);
92 closestt= t-step + time*(1-t+step); //time between [t-step,1.0]
95 //set the time value if we found a closer point
98 if(tout) *tout = closestt;
105 // Line and BezHull Definitions
106 void BezHull::Bound(const etl::bezier<Point> &b)
110 //with a starting vertex, find the only vertex that has all other vertices on it's right
117 Vector::value_type deqn;
119 //get left most vertex
122 for(i = 1; i < 4; ++i)
133 //find the farthest point with all points on right
135 do //should reassign cur so it won't break on first step
137 for(i = 0; i < 4; ++i)
139 if(i == cur || i == last) continue;
141 //rotate vector to right to make normal
142 vi = -(b[i] - b[cur]).perp();
143 d = vi.mag_squared();
145 //we want only the farthest (solves the case with many points on a line)
150 for(j = 0; j < 4; ++j)
153 if(d < 0) break; //we're on left, nope!
156 //everyone is on right... yay! :)
159 //advance point and add last one into hull
166 }while(cur != first);
170 //will work but does not keep winding order
173 //build set of line segs which have no points on other side...
174 //start with initial normal segments
176 //start with single triangle
182 //initial reject (if point is inside triangle don't care)
191 float s = (vp*v1) / (v1*v1),
192 t = (vp*v2) / (v2*v2);
194 //if we're inside the triangle we don't this sissy point
195 if( s >= 0 && s <= 1 && t >= 0 && t <= 1 )
202 //expand triangle based on info...
207 //distance from point to vertices
210 ds = (p[0]-b[3]).mag_squared();
211 for(i = 1; i < 3; ++i)
213 d = (p[3]-p[i]).mag_squared();
224 for(i = 0; i < 3; j = i++)
226 d = line_point_distsq(p[j],p[i],b[4],t);
235 //We don't need no stinkin extra vertex, just replace
242 //must expand volume to work with point...
243 // after the index then
250 for(i = 3; i > index+1; --i)
255 p[index] = b[3]; //recopy b3
264 synfig::intersect(const Point &p1, const Vector &v1, float &t1,
265 const Point &p2, const Vector &v2, float &t2)
267 /* Parametric intersection:
268 l1 = p1 + tv1, l2 = p2 + sv2
271 group parameters: sv2 - tv1 = p1-p2
274 invert matrix (on condition det != 0):
279 det = v1y.v2x - v1x.v2y
281 if non 0 then A^-1 = invdet * | v2y -v2x |
284 [t s]^ = A^-1 [p1-p2]^
287 Vector::value_type det = v1[1]*v2[0] - v1[0]*v2[1];
289 //is determinant valid?
290 if(det > ERR || det < -ERR)
296 t1 = det*(v2[1]*p_p[0] - v2[0]*p_p[1]);
297 t2 = det*(v1[1]*p_p[0] - v1[0]*p_p[1]);
305 //Returns the true or false intersection of a rectangle and a line
306 int intersect(const Rect &r, const Point &p, const Vector &v)
310 /*get horizontal intersections and then vertical intersections
313 Vertical planes - n = (1,0)
314 Horizontal planes - n = (0,1)
316 so if we are solving for ray with implicit line
320 if(v[0] > ERR || v[0] < -ERR)
323 t[0] = (r.minx - p[0])/v[0];
324 t[1] = (r.maxx - p[0])/v[0];
327 return (int)(p[1] >= r.miny && p[1] <= r.maxy);
331 if(v[1] > ERR || v[1] < -ERR)
334 t[2] = (r.miny - p[1])/v[1];
335 t[3] = (r.maxy - p[1])/v[1];
338 return (int)(p[0] >= r.minx && p[0] <= r.maxx);
341 return (int)(t[0] <= t[3] && t[1] >= t[2]);
344 int synfig::intersect(const Rect &r, const Point &p)
346 return (p[1] < r.maxy && p[1] > r.miny) && p[0] > r.minx;
349 //returns 0 or 1 for true or false number of intersections of a ray with a bezier convex hull
350 int intersect(const BezHull &bh, const Point &p, const Vector &v)
352 float mint = 0, maxt = 1e20;
356 Vector::value_type nv;
358 Point last = bh.p[3];
359 for(int i = 0; i < bh.size; ++i)
361 n = (bh.p[i] - last).perp(); //rotate 90 deg.
365 if n.v < 0 - going in
374 maxt = min(maxt,(float)((n*(p-last))/nv));
376 if( nv < -ERR) //going IN
378 mint = max(mint,(float)((n*(p-last))/nv));
381 if( n*(p-last) > 0 ) //outside entirely
393 int Clip(const Rect &r, const Point &p1, const Point &p2, Point *op1, Point *op2)
398 /*get horizontal intersections and then vertical intersections
401 Vertical planes - n = (1,0)
402 Horizontal planes - n = (0,1)
404 so if we are solving for ray with implicit line
408 if(v[0] > ERR || v[0] < -ERR)
411 float tt1 = (r.minx - p1[0])/v[0],
412 tt2 = (r.maxx - p1[0])/v[0];
414 //line in positive direction (normal comparisons
426 if(p1[1] < r.miny || p1[1] > r.maxy)
431 if(v[1] > ERR || v[1] < -ERR)
434 float tt1 = (r.miny - p1[1])/v[1],
435 tt2 = (r.maxy - p1[1])/v[1];
437 //line in positive direction (normal comparisons
449 if(p1[0] < r.minx || p1[0] > r.maxx)
453 if(op1) *op1 = p1 + v*t1;
454 if(op2) *op2 = p1 + v*t2;
459 static void clean_bez(const bezier<Point> &b, bezier<Point> &out)
468 temp.subdivide(0,&temp,b.get_r());
471 temp.subdivide(&temp,0,b.get_s());
476 // CIntersect Definitions
478 CIntersect::CIntersect()
479 : max_depth(10) //depth of 10 means timevalue parameters will have an approx. error bound of 2^-10
483 struct CIntersect::SCurve
485 bezier<Point> b; //the current subdivided curve
487 //float mid, //the midpoint time value on this section of the subdivided curve
488 // scale; //the current delta in time values this curve would be on original curve
490 float mag; //approximate sum of magnitudes of each edge of control polygon
491 Rect aabb; //Axis Aligned Bounding Box for quick (albeit less accurate) collision
495 SCurve(const bezier<Point> &c,float rin, float sin)
496 :b(c),rt(rin),st(sin),mag(1)
501 void Split(SCurve &l, SCurve &r) const
503 b.subdivide(&l.b,&r.b);
507 l.st = r.rt = (rt+st)/2;
514 //Curve to the left of point test
515 static int recurse_intersect(const CIntersect::SCurve &b, const Point &p1, int depthleft = 10)
517 //reject when the line does not intersect the bounding box
518 if(!intersect(b.aabb,p1)) return 0;
520 //accept curves (and perform super detailed check for intersections)
521 //if the values are below tolerance
523 //NOTE FOR BETTERING OF ALGORITHM: SHOULD ALSO/IN-PLACE-OF CHECK MAGNITUDE OF EDGES (or approximate)
526 //NOTE FOR IMPROVEMENT: Polish roots based on original curve
527 // (may be too expensive to be effective)
530 for(int i = 0; i < 3; ++i)
532 //intersect line segmentsssss
534 //solve for the y_value
535 Vector v = b.b[i+1] - b.b[i];
537 if(v[1] > ERROR && v[1] < ERROR)
539 Real xi = (p1[1] - b.b[i][1])/v[1];
541 //and add in the turn (up or down) if it's valid
542 if(xi < p1[0]) turn += (v[1] > 0) ? 1 : -1;
549 //subdivide the curve and continue
550 CIntersect::SCurve l1,r1;
551 b.Split(l1,r1); //subdivide left
553 //test each subdivision against the point
554 return recurse_intersect(l1,p1) + recurse_intersect(r1,p1);
557 int intersect(const bezier<Point> &b, const Point &p)
559 CIntersect::SCurve sb;
562 sb.rt = 0; sb.st = 1;
563 sb.mag = 1; Bound(sb.aabb,sb.b);
565 return recurse_intersect(sb,p);
568 //Curve curve intersection
569 void CIntersect::recurse_intersect(const SCurve &left, const SCurve &right, int depth)
571 //reject curves that do not overlap with bouding boxes
572 if(!intersect(left.aabb,right.aabb)) return;
574 //accept curves (and perform super detailed check for intersections)
575 //if the values are below tolerance
577 //NOTE FOR BETTERING OF ALGORITHM: SHOULD ALSO/IN-PLACE-OF CHECK MAGNITUDE OF EDGES (or approximate)
578 if(depth >= max_depth)
580 //NOTE FOR IMPROVEMENT: Polish roots based on original curve with the Jacobian
581 // (may be too expensive to be effective)
583 //perform root approximation
584 //collide line segments
588 for(int i = 0; i < 3; ++i)
590 for(int j = 0; j < 3; ++j)
592 //intersect line segmentsssss
593 if(intersect_line_segments(left.b[i],left.b[i+1],t,right.b[j],right.b[j+1],s))
596 times.push_back(intersect_set::value_type(t,s));
604 //NOTE FOR IMPROVEMENT: only subdivide one curve and choose the one that has
605 // the highest approximated length
606 //fast approximation to curve length may be hard (accurate would
607 // involve 3 square roots), could sum the squares which would be
608 // quick but inaccurate
611 left.Split(l1,r1); //subdivide left
612 right.Split(l2,r2); //subdivide right
614 //Test each cantidate against eachother
615 recurse_intersect(l1,l2);
616 recurse_intersect(l1,r2);
617 recurse_intersect(r1,l2);
618 recurse_intersect(r1,r2);
623 bool CIntersect::operator()(const bezier<Point> &c1, const bezier<Point> &c2)
627 //need to subdivide and check recursive bounding regions against eachother
628 //so track a list of dirty curves and compare compare compare
631 //temporary curves for subdivision
632 CIntersect intersector;
633 CIntersect::SCurve left,right;
635 //Make sure the parameters are normalized (so we don't compare unwanted parts of the curves,
636 // and don't miss any for that matter)
639 //Compile information about curve
640 clean_bez(c1,left.b);
641 left.rt = 0; left.st = 1;
642 Bound(left.aabb, left.b);
645 //Compile information about right curve
646 clean_bez(c2,right.b);
647 right.rt = 0; right.st = 1;
648 Bound(right.aabb, right.b);
650 //Perform Curve intersection
651 intersector.recurse_intersect(left,right);
653 //Get information about roots (yay! :P)
654 return times.size() != 0;
657 //point inside curve - return +/- hit up or down edge
658 int intersect_scurve(const CIntersect::SCurve &b, const Point &p)
660 //initial reject/approve etc.
663 *-----------*---------
672 *-----------*--------
673 1,2 are only regions not rejected
675 if(p[0] < b.aabb.minx || p[1] < b.aabb.miny || p[1] > b.aabb.maxy)
678 //approve only if to the right of rect around 2 end points
681 r.set_point(b.b[0][0],b.b[0][1]);
682 r.expand(b.b[3][0],b.b[3][1]);
684 if(p[0] >= r.maxx && p[1] <= r.maxy && p[1] >= r.miny)
686 float df = b.b[3][1] - b.b[0][1];
688 return df >= 0 ? 1 : -1;
692 //subdivide and check again!
693 CIntersect::SCurve l,r;
695 return intersect_scurve(l,p) + intersect_scurve(r,p);
698 int synfig::intersect(const bezier<Point> &b, const Point &p)
700 CIntersect::SCurve c(b,0,1);
702 return intersect_scurve(c,p);