remove debug messages, for now
[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 <exception>
21 #include <algorithm>
22
23 #include "canvas/curve.h"
24
25 using namespace ArdourCanvas;
26 using std::min;
27 using std::max;
28
29 Curve::Curve (Group* parent)
30         : Item (parent)
31         , PolyItem (parent)
32         , Fill (parent)
33         , n_samples (0)
34         , n_segments (512)
35 {
36         set_n_samples (256);
37 }
38
39 /** Set the number of points to compute when we smooth the data points into a
40  * curve. 
41  */
42 void
43 Curve::set_n_samples (Points::size_type n)
44 {
45         /* this only changes our appearance rather than the bounding box, so we
46            just need to schedule a redraw rather than notify the parent of any
47            changes
48         */
49         n_samples = n;
50         samples.assign (n_samples, Duple (0.0, 0.0));
51         interpolate ();
52 }
53
54 /** When rendering the curve, we will always draw a fixed number of straight
55  * line segments to span the x-axis extent of the curve. More segments:
56  * smoother visual rendering. Less rendering: closer to a visibily poly-line
57  * render.
58  */
59 void
60 Curve::set_n_segments (uint32_t n)
61 {
62         /* this only changes our appearance rather than the bounding box, so we
63            just need to schedule a redraw rather than notify the parent of any
64            changes
65         */
66         n_segments = n;
67         redraw ();
68 }
69
70 void
71 Curve::compute_bounding_box () const
72 {
73         PolyItem::compute_bounding_box ();
74
75         /* possibly add extents of any point indicators here if we ever do that */
76 }
77
78 void
79 Curve::set (Points const& p)
80 {
81         PolyItem::set (p);
82         interpolate ();
83 }
84
85 void
86 Curve::interpolate ()
87 {
88         Points::size_type npoints = _points.size ();
89
90         if (npoints < 3) {
91                 return;
92         }
93
94         Duple p;
95         double boundary;
96
97         const double xfront = _points.front().x;
98         const double xextent = _points.back().x - xfront;
99
100         /* initialize boundary curve points */
101
102         p = _points.front();
103         boundary = round (((p.x - xfront)/xextent) * (n_samples - 1));
104
105         for (Points::size_type i = 0; i < boundary; ++i) {
106                 samples[i] = Duple (i, p.y);
107         }
108
109         p = _points.back();
110         boundary = round (((p.x - xfront)/xextent) * (n_samples - 1));
111
112         for (Points::size_type i = boundary; i < n_samples; ++i) {
113                 samples[i] = Duple (i, p.y);
114         }
115
116         for (int i = 0; i < (int) npoints - 1; ++i) {
117
118                 Points::size_type p1, p2, p3, p4;
119                 
120                 p1 = max (i - 1, 0);
121                 p2 = i;
122                 p3 = i + 1;
123                 p4 = min (i + 2, (int) npoints - 1);
124
125                 smooth (p1, p2, p3, p4, xfront, xextent);
126         }
127         
128         /* make sure that actual data points are used with their exact values */
129
130         for (Points::const_iterator p = _points.begin(); p != _points.end(); ++p) {
131                 uint32_t idx = (((*p).x - xfront)/xextent) * (n_samples - 1);
132                 samples[idx].y = (*p).y;
133         }
134 }
135
136 /*
137  * This function calculates the curve values between the control points
138  * p2 and p3, taking the potentially existing neighbors p1 and p4 into
139  * account.
140  *
141  * This function uses a cubic bezier curve for the individual segments and
142  * calculates the necessary intermediate control points depending on the
143  * neighbor curve control points.
144  *
145  */
146
147 void
148 Curve::smooth (Points::size_type p1, Points::size_type p2, Points::size_type p3, Points::size_type p4,
149                double xfront, double xextent)
150 {
151         int i;
152         double x0, x3;
153         double y0, y1, y2, y3;
154         double dx, dy;
155         double slope;
156
157         /* the outer control points for the bezier curve. */
158
159         x0 = _points[p2].x;
160         y0 = _points[p2].y;
161         x3 = _points[p3].x;
162         y3 = _points[p3].y;
163
164         /*
165          * the x values of the inner control points are fixed at
166          * x1 = 2/3*x0 + 1/3*x3   and  x2 = 1/3*x0 + 2/3*x3
167          * this ensures that the x values increase linearily with the
168          * parameter t and enables us to skip the calculation of the x
169          * values altogehter - just calculate y(t) evenly spaced.
170          */
171
172         dx = x3 - x0;
173         dy = y3 - y0;
174
175         if (dx <= 0) {
176                 /* error? */
177                 return;
178         }
179
180         if (p1 == p2 && p3 == p4) {
181                 /* No information about the neighbors,
182                  * calculate y1 and y2 to get a straight line
183                  */
184                 y1 = y0 + dy / 3.0;
185                 y2 = y0 + dy * 2.0 / 3.0;
186
187         } else if (p1 == p2 && p3 != p4) {
188
189                 /* only the right neighbor is available. Make the tangent at the
190                  * right endpoint parallel to the line between the left endpoint
191                  * and the right neighbor. Then point the tangent at the left towards
192                  * the control handle of the right tangent, to ensure that the curve
193                  * does not have an inflection point.
194                  */
195                 slope = (_points[p4].y - y0) / (_points[p4].x - x0);
196
197                 y2 = y3 - slope * dx / 3.0;
198                 y1 = y0 + (y2 - y0) / 2.0;
199
200         } else if (p1 != p2 && p3 == p4) {
201
202                 /* see previous case */
203                 slope = (y3 - _points[p1].y) / (x3 - _points[p1].x);
204
205                 y1 = y0 + slope * dx / 3.0;
206                 y2 = y3 + (y1 - y3) / 2.0;
207
208
209         } else /* (p1 != p2 && p3 != p4) */ {
210
211                 /* Both neighbors are available. Make the tangents at the endpoints
212                  * parallel to the line between the opposite endpoint and the adjacent
213                  * neighbor.
214                  */
215
216                 slope = (y3 - _points[p1].y) / (x3 - _points[p1].x);
217
218                 y1 = y0 + slope * dx / 3.0;
219
220                 slope = (_points[p4].y - y0) / (_points[p4].x - x0);
221
222                 y2 = y3 - slope * dx / 3.0;
223         }
224
225         /*
226          * finally calculate the y(t) values for the given bezier values. We can
227          * use homogenously distributed values for t, since x(t) increases linearily.
228          */
229
230         dx = dx / xextent;
231
232         int limit = round (dx * (n_samples - 1));
233         const int idx_offset = round (((x0 - xfront)/xextent) * (n_samples - 1));
234
235         for (i = 0; i <= limit; i++) {
236                 double y, t;
237                 Points::size_type index;
238
239                 t = i / dx / (n_samples - 1);
240                 
241                 y =     y0 * (1-t) * (1-t) * (1-t) +
242                         3 * y1 * (1-t) * (1-t) * t     +
243                         3 * y2 * (1-t) * t     * t     +
244                         y3 * t     * t     * t;
245
246                 index = i + idx_offset;
247                 
248                 if (index < n_samples) {
249                         Duple d (i, max (y, 0.0));
250                         samples[index] = d;
251                 }
252         }
253 }
254
255 /** Given a position within the x-axis range of the
256  * curve, return the corresponding y-axis value
257  */
258
259 double
260 Curve::map_value (double x) const
261 {
262         if (x > 0.0 && x < 1.0) {
263
264                 double f;
265                 Points::size_type index;
266                 
267                 /* linearly interpolate between two of our smoothed "samples"
268                  */
269                 
270                 x = x * (n_samples - 1);
271                 index = (Points::size_type) x; // XXX: should we explicitly use floor()?
272                 f = x - index;
273
274                 return (1.0 - f) * samples[index].y + f * samples[index+1].y;
275                 
276         } else if (x >= 1.0) {
277                 return samples.back().y;
278         } else {
279                 return samples.front().y;
280         }
281 }
282
283 void
284 Curve::render (Rect const & area, Cairo::RefPtr<Cairo::Context> context) const
285 {
286         if (!_outline || _points.size() < 2) {
287                 return;
288         }
289
290         /* Our approach is to always draw n_segments across our total size.
291          *
292          * This is very inefficient if we are asked to only draw a small
293          * section of the curve. For now we rely on cairo clipping to help
294          * with this.
295          */
296         
297         double x;
298         double y;
299
300         context->save ();
301         context->rectangle (area.x0, area.y0, area.width(),area.height());
302         context->clip ();
303
304         setup_outline_context (context);
305
306         if (_points.size() == 2) {
307
308                 /* straight line */
309
310                 Duple window_space;
311
312                 window_space = item_to_window (_points.front());
313                 context->move_to (window_space.x, window_space.y);
314                 window_space = item_to_window (_points.back());
315                 context->line_to (window_space.x, window_space.y);
316
317         } else {
318
319                 /* curve of at least 3 points */
320
321                 const double xfront = _points.front().x;
322                 const double xextent = _points.back().x - xfront;
323
324                 /* move through points to find the first one inside the
325                  * rendering area 
326                  */
327                 
328                 Points::const_iterator edge = _points.end();
329                 bool edge_found = false;
330
331                 for (Points::const_iterator p = _points.begin(); p != _points.end(); ++p) {
332                         Duple w (item_to_window (Duple ((*p).x, 0.0)));
333                         if (w.x >= area.x0) {
334                                 edge_found = true;
335                                 break;
336                         }
337                         edge = p;
338                         
339                 }
340
341                 if (edge == _points.end()) {
342                         if (edge_found) {
343                                 edge = _points.begin();
344                         } else {
345                                 return;
346                         }
347                 }
348
349                 std::cerr << "Start drawing " << distance (_points.begin(), edge) << " into points\n";
350                 
351                 x = (*edge).x;
352                 y = map_value (0.0);
353                 
354                 Duple window_space = item_to_window (Duple (x, y));
355                 context->move_to (window_space.x, window_space.y);
356                 
357                 /* if the extent of this curve (in pixels) is small, then we don't need
358                  * many segments.
359                  */
360                 
361                 uint32_t nsegs = area.width();
362                 double last_x = 0;
363                 double xoffset = (x-xfront)/xextent;
364
365                 // std::cerr << " draw " << nsegs << " segments\n";
366
367                 for (uint32_t n = 1; n < nsegs; ++n) {
368
369                         /* compute item space x coordinate of the start of this segment */
370                         
371                         x = xoffset + (n / (double) nsegs);
372                         y = map_value (x);
373
374                         x += xfront + (xextent * x);
375
376                         // std::cerr << "hspan @ " << x << ' ' << x - last_x << std::endl;
377                         last_x = x;
378
379                         window_space = item_to_window (Duple (x, y));
380                         context->line_to (window_space.x, window_space.y);
381
382                         if (window_space.x > area.x1) {
383                                 /* we're done - the last point was outside the redraw area along the x-axis */
384                                 break;
385                         }
386                 }
387         }
388
389         context->stroke ();
390
391         /* add points */
392         
393         setup_fill_context (context);
394         for (Points::const_iterator p = _points.begin(); p != _points.end(); ++p) {
395                 Duple window_space (item_to_window (*p));
396                 context->arc (window_space.x, window_space.y, 5.0, 0.0, 2 * M_PI);
397                 context->stroke ();
398         }
399
400         context->restore ();
401 }
402
403 bool
404 Curve::covers (Duple const & pc) const
405 {
406         Duple point = canvas_to_item (pc);
407
408         /* O(N) N = number of points, and not accurate */
409
410         for (Points::const_iterator p = _points.begin(); p != _points.end(); ++p) {
411
412                 const Coord dx = point.x - (*p).x;
413                 const Coord dy = point.y - (*p).y;
414                 const Coord dx2 = dx * dx;
415                 const Coord dy2 = dy * dy;
416
417                 if ((dx2 < 2.0 && dy2 < 2.0) || (dx2 + dy2 < 4.0)) {
418                         return true;
419                 }
420         }
421
422         return false;
423 }