Merge branch 'cairocanvas' of git.ardour.org:ardour/ardour into cairocanvas
[ardour.git] / libs / canvas / curve.cc
1 /*
2     Copyright (C) 2013 Paul Davis
3
4     This program is free software; you can redistribute it and/or modify
5     it under the terms of the GNU General Public License as published by
6     the Free Software Foundation; either version 2 of the License, or
7     (at your option) any later version.
8
9     This program is distributed in the hope that it will be useful,
10     but WITHOUT ANY WARRANTY; without even the implied warranty of
11     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12     GNU General Public License for more details.
13
14     You should have received a copy of the GNU General Public License
15     along with this program; if not, write to the Free Software
16     Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
17
18 */
19
20 #include <cmath>
21 #include <exception>
22 #include <algorithm>
23
24 #include "canvas/curve.h"
25
26 using namespace ArdourCanvas;
27 using std::min;
28 using std::max;
29
30 Curve::Curve (Group* parent)
31         : Item (parent)
32         , PolyItem (parent)
33         , Fill (parent)
34         , n_samples (0)
35         , points_per_segment (16)
36         , curve_type (CatmullRomCentripetal)
37 {
38 }
39
40 /** When rendering the curve, we will always draw a fixed number of straight
41  * line segments to span the x-axis extent of the curve. More segments:
42  * smoother visual rendering. Less rendering: closer to a visibily poly-line
43  * render.
44  */
45 void
46 Curve::set_points_per_segment (uint32_t n)
47 {
48         /* this only changes our appearance rather than the bounding box, so we
49            just need to schedule a redraw rather than notify the parent of any
50            changes
51         */
52         points_per_segment = n;
53         interpolate ();
54         redraw ();
55 }
56
57 void
58 Curve::compute_bounding_box () const
59 {
60         PolyItem::compute_bounding_box ();
61
62         /* possibly add extents of any point indicators here if we ever do that */
63 }
64
65 void
66 Curve::set (Points const& p)
67 {
68         PolyItem::set (p);
69         interpolate ();
70 }
71
72 void
73 Curve::interpolate ()
74 {
75         samples.clear ();
76         interpolate (_points, points_per_segment, CatmullRomCentripetal, false, samples);
77         n_samples = samples.size();
78 }
79
80 /* Cartmull-Rom code from http://stackoverflow.com/questions/9489736/catmull-rom-curve-with-no-cusps-and-no-self-intersections/19283471#19283471
81  * 
82  * Thanks to Ted for his Java version, which I translated into Ardour-idiomatic
83  * C++ here.
84  */
85
86 /**
87  * Calculate the same values but introduces the ability to "parameterize" the t
88  * values used in the calculation. This is based on Figure 3 from
89  * http://www.cemyuksel.com/research/catmullrom_param/catmullrom.pdf
90  *
91  * @param p An array of double values of length 4, where interpolation
92  * occurs from p1 to p2.
93  * @param time An array of time measures of length 4, corresponding to each
94  * p value.
95  * @param t the actual interpolation ratio from 0 to 1 representing the
96  * position between p1 and p2 to interpolate the value.
97  */
98 static double 
99 __interpolate (double p[4], double time[4], double t) 
100 {
101         const double L01 = p[0] * (time[1] - t) / (time[1] - time[0]) + p[1] * (t - time[0]) / (time[1] - time[0]);
102         const double L12 = p[1] * (time[2] - t) / (time[2] - time[1]) + p[2] * (t - time[1]) / (time[2] - time[1]);
103         const double L23 = p[2] * (time[3] - t) / (time[3] - time[2]) + p[3] * (t - time[2]) / (time[3] - time[2]);
104         const double L012 = L01 * (time[2] - t) / (time[2] - time[0]) + L12 * (t - time[0]) / (time[2] - time[0]);
105         const double L123 = L12 * (time[3] - t) / (time[3] - time[1]) + L23 * (t - time[1]) / (time[3] - time[1]);
106         const double C12 = L012 * (time[2] - t) / (time[2] - time[1]) + L123 * (t - time[1]) / (time[2] - time[1]);
107         return C12;
108 }   
109
110 /**
111  * Given a list of control points, this will create a list of points_per_segment
112  * points spaced uniformly along the resulting Catmull-Rom curve.
113  *
114  * @param points The list of control points, leading and ending with a 
115  * coordinate that is only used for controling the spline and is not visualized.
116  * @param index The index of control point p0, where p0, p1, p2, and p3 are
117  * used in order to create a curve between p1 and p2.
118  * @param points_per_segment The total number of uniformly spaced interpolated
119  * points to calculate for each segment. The larger this number, the
120  * smoother the resulting curve.
121  * @param curve_type Clarifies whether the curve should use uniform, chordal
122  * or centripetal curve types. Uniform can produce loops, chordal can
123  * produce large distortions from the original lines, and centripetal is an
124  * optimal balance without spaces.
125  * @return the list of coordinates that define the CatmullRom curve
126  * between the points defined by index+1 and index+2.
127  */
128 static void
129 _interpolate (const Points& points, Points::size_type index, int points_per_segment, Curve::SplineType curve_type, Points& results) 
130 {
131         double x[4];
132         double y[4];
133         double time[4];
134
135         for (int i = 0; i < 4; i++) {
136                 x[i] = points[index + i].x;
137                 y[i] = points[index + i].y;
138                 time[i] = i;
139         }
140         
141         double tstart = 1;
142         double tend = 2;
143
144         if (curve_type != Curve::CatmullRomUniform) {
145                 double total = 0;
146                 for (int i = 1; i < 4; i++) {
147                         double dx = x[i] - x[i - 1];
148                         double dy = y[i] - y[i - 1];
149                         if (curve_type == Curve::CatmullRomCentripetal) {
150                                 total += pow (dx * dx + dy * dy, .25);
151                         } else {
152                                 total += pow (dx * dx + dy * dy, .5);
153                         }
154                         time[i] = total;
155                 }
156                 tstart = time[1];
157                 tend = time[2];
158         }
159
160         int segments = points_per_segment - 1;
161         results.push_back (points[index + 1]);
162
163         for (int i = 1; i < segments; i++) {
164                 double xi = __interpolate (x, time, tstart + (i * (tend - tstart)) / segments);
165                 double yi = __interpolate (y, time, tstart + (i * (tend - tstart)) / segments);
166                 results.push_back (Duple (xi, yi));
167         }
168
169         results.push_back (points[index + 2]);
170 }
171
172 /**
173  * This method will calculate the Catmull-Rom interpolation curve, returning
174  * it as a list of Coord coordinate objects.  This method in particular
175  * adds the first and last control points which are not visible, but required
176  * for calculating the spline.
177  *
178  * @param coordinates The list of original straight line points to calculate
179  * an interpolation from.
180  * @param points_per_segment The integer number of equally spaced points to
181  * return along each curve.  The actual distance between each
182  * point will depend on the spacing between the control points.
183  * @return The list of interpolated coordinates.
184  * @param curve_type Chordal (stiff), Uniform(floppy), or Centripetal(medium)
185  * @throws gov.ca.water.shapelite.analysis.CatmullRomException if
186  * points_per_segment is less than 2.
187  */
188
189 void
190 Curve::interpolate (const Points& coordinates, uint32_t points_per_segment, SplineType curve_type, bool closed, Points& results)
191 {
192         if (points_per_segment < 2) {
193                 return;
194         }
195         
196         // Cannot interpolate curves given only two points.  Two points
197         // is best represented as a simple line segment.
198         if (coordinates.size() < 3) {
199                 results = coordinates;
200                 return;
201         }
202
203         // Copy the incoming coordinates. We need to modify it during interpolation
204         Points vertices = coordinates;
205         
206         // Test whether the shape is open or closed by checking to see if
207         // the first point intersects with the last point.  M and Z are ignored.
208         if (closed) {
209                 // Use the second and second from last points as control points.
210                 // get the second point.
211                 Duple p2 = vertices[1];
212                 // get the point before the last point
213                 Duple pn1 = vertices[vertices.size() - 2];
214                 
215                 // insert the second from the last point as the first point in the list
216                 // because when the shape is closed it keeps wrapping around to
217                 // the second point.
218                 vertices.insert(vertices.begin(), pn1);
219                 // add the second point to the end.
220                 vertices.push_back(p2);
221         } else {
222                 // The shape is open, so use control points that simply extend
223                 // the first and last segments
224                 
225                 // Get the change in x and y between the first and second coordinates.
226                 double dx = vertices[1].x - vertices[0].x;
227                 double dy = vertices[1].y - vertices[0].y;
228                 
229                 // Then using the change, extrapolate backwards to find a control point.
230                 double x1 = vertices[0].x - dx;
231                 double y1 = vertices[0].y - dy;
232                 
233                 // Actaully create the start point from the extrapolated values.
234                 Duple start (x1, y1);
235                 
236                 // Repeat for the end control point.
237                 int n = vertices.size() - 1;
238                 dx = vertices[n].x - vertices[n - 1].x;
239                 dy = vertices[n].y - vertices[n - 1].y;
240                 double xn = vertices[n].x + dx;
241                 double yn = vertices[n].y + dy;
242                 Duple end (xn, yn);
243                 
244                 // insert the start control point at the start of the vertices list.
245                 vertices.insert (vertices.begin(), start);
246                 
247                 // append the end control ponit to the end of the vertices list.
248                 vertices.push_back (end);
249         }
250         
251         // When looping, remember that each cycle requires 4 points, starting
252         // with i and ending with i+3.  So we don't loop through all the points.
253         
254         for (Points::size_type i = 0; i < vertices.size() - 3; i++) {
255
256                 // Actually calculate the Catmull-Rom curve for one segment.
257                 Points r;
258
259                 _interpolate (vertices, i, points_per_segment, curve_type, r);
260  
261                 // Since the middle points are added twice, once for each bordering
262                 // segment, we only add the 0 index result point for the first
263                 // segment.  Otherwise we will have duplicate points.
264
265                 if (results.size() > 0) {
266                         r.erase (r.begin());
267                 }
268                 
269                 // Add the coordinates for the segment to the result list.
270
271                 results.insert (results.end(), r.begin(), r.end());
272         }
273 }
274
275 /** Given a fractional position within the x-axis range of the
276  * curve, return the corresponding y-axis value
277  */
278
279 double
280 Curve::map_value (double x) const
281 {
282         if (x > 0.0 && x < 1.0) {
283
284                 double f;
285                 Points::size_type index;
286                 
287                 /* linearly interpolate between two of our smoothed "samples"
288                  */
289                 
290                 x = x * (n_samples - 1);
291                 index = (Points::size_type) x; // XXX: should we explicitly use floor()?
292                 f = x - index;
293
294                 return (1.0 - f) * samples[index].y + f * samples[index+1].y;
295                 
296         } else if (x >= 1.0) {
297                 return samples.back().y;
298         } else {
299                 return samples.front().y;
300         }
301 }
302
303 void
304 Curve::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) const
305 {
306         if (!_outline || _points.size() < 2 || !_bounding_box) {
307                 return;
308         }
309
310         Rect self = item_to_window (_bounding_box.get());
311         boost::optional<Rect> d = self.intersection (area);
312         assert (d);
313         Rect draw = d.get ();
314
315         /* Our approach is to always draw n_segments across our total size.
316          *
317          * This is very inefficient if we are asked to only draw a small
318          * section of the curve. For now we rely on cairo clipping to help
319          * with this.
320          */
321         
322
323         setup_outline_context (context);
324
325         if (_points.size() == 2) {
326
327                 /* straight line */
328
329                 Duple window_space;
330
331                 window_space = item_to_window (_points.front());
332                 context->move_to (window_space.x, window_space.y);
333                 window_space = item_to_window (_points.back());
334                 context->line_to (window_space.x, window_space.y);
335
336                 context->stroke ();
337
338         } else {
339
340                 /* curve of at least 3 points */
341
342                 /* x-axis limits of the curve, in window space coordinates */
343
344                 Duple w1 = item_to_window (Duple (_points.front().x, 0.0));
345                 Duple w2 = item_to_window (Duple (_points.back().x, 0.0));
346
347                 /* clamp actual draw to area bound by points, rather than our bounding box which is slightly different */
348
349                 context->save ();
350                 context->rectangle (draw.x0, draw.y0, draw.width(), draw.height());
351                 context->clip ();
352
353                 /* expand drawing area by several pixels on each side to avoid cairo stroking effects at the boundary.
354                    they will still occur, but cairo's clipping will hide them.
355                  */
356
357                 draw = draw.expand (4.0);
358
359                 /* now clip it to the actual points in the curve */
360                 
361                 if (draw.x0 < w1.x) {
362                         draw.x0 = w1.x;
363                 }
364
365                 if (draw.x1 >= w2.x) {
366                         draw.x1 = w2.x;
367                 }
368
369                 /* full width of the curve */
370                 const double xextent = _points.back().x - _points.front().x;
371                 /* Determine where the first drawn point will be */
372                 Duple item_space = window_to_item (Duple (draw.x0, 0)); /* y value is irrelevant */
373                 /* determine the fractional offset of this location into the overall extent of the curve */
374                 const double xfract_offset = (item_space.x - _points.front().x)/xextent;
375                 const uint32_t pixels = draw.width ();
376                 Duple window_space;
377
378                 /* draw the first point */
379
380                 for (uint32_t pixel = 0; pixel < pixels; ++pixel) {
381
382                         /* fractional distance into the total horizontal extent of the curve */
383                         double xfract = xfract_offset + (pixel / xextent);
384                         /* compute vertical coordinate (item-space) at that location */
385                         double y = map_value (xfract);
386                         
387                         /* convert to window space for drawing */
388                         window_space = item_to_window (Duple (0.0, y)); /* x-value is irrelevant */
389
390                         /* we are moving across the draw area pixel-by-pixel */
391                         window_space.x = draw.x0 + pixel;
392                         
393                         /* plot this point */
394                         if (pixel == 0) {
395                                 context->move_to (window_space.x, window_space.y);
396                         } else {
397                                 context->line_to (window_space.x, window_space.y);
398                         }
399                 }
400
401                 context->stroke ();
402                 context->restore ();
403         }
404
405 #if 1
406         /* add points */
407         
408         setup_fill_context (context);
409         for (Points::const_iterator p = _points.begin(); p != _points.end(); ++p) {
410                 Duple window_space (item_to_window (*p));
411                 context->arc (window_space.x, window_space.y, 5.0, 0.0, 2 * M_PI);
412                 context->stroke ();
413         }
414 #endif
415 }
416
417 bool
418 Curve::covers (Duple const & pc) const
419 {
420         Duple point = canvas_to_item (pc);
421
422         /* O(N) N = number of points, and not accurate */
423
424         for (Points::const_iterator p = _points.begin(); p != _points.end(); ++p) {
425
426                 const Coord dx = point.x - (*p).x;
427                 const Coord dy = point.y - (*p).y;
428                 const Coord dx2 = dx * dx;
429                 const Coord dy2 = dy * dy;
430
431                 if ((dx2 < 2.0 && dy2 < 2.0) || (dx2 + dy2 < 4.0)) {
432                         return true;
433                 }
434         }
435
436         return false;
437 }