]> git.donarmstrong.com Git - lilypond.git/blob - lily/lookup.cc
Issue 4550 (2/2) Avoid "using namespace std;" in included files
[lilypond.git] / lily / lookup.cc
1 /*
2   This file is part of LilyPond, the GNU music typesetter.
3
4   Copyright (C) 1997--2015 Han-Wen Nienhuys <hanwen@xs4all.nl>
5
6   Jan Nieuwenhuizen <janneke@gnu.org>
7
8   LilyPond is free software: you can redistribute it and/or modify
9   it under the terms of the GNU General Public License as published by
10   the Free Software Foundation, either version 3 of the License, or
11   (at your option) any later version.
12
13   LilyPond is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18   You should have received a copy of the GNU General Public License
19   along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
20 */
21
22 #include "lookup.hh"
23
24 #include <cmath>
25 #include <cctype>
26
27 #include "line-interface.hh"
28 #include "warn.hh"
29 #include "international.hh"
30 #include "dimensions.hh"
31 #include "bezier.hh"
32 #include "file-path.hh"
33 #include "main.hh"
34 #include "lily-guile.hh"
35
36 using std::vector;
37
38 Stencil
39 Lookup::beam (Real slope, Real width, Real thick, Real blot)
40 {
41   Box b;
42
43   Offset p;
44
45   p = Offset (0, thick / 2);
46   b.add_point (p);
47   p += Offset (1, -1) * (blot / 2);
48
49   SCM points = SCM_EOL;
50
51   points = scm_cons (scm_from_double (p[X_AXIS]),
52                      scm_cons (scm_from_double (p[Y_AXIS]),
53                                points));
54
55   p = Offset (0, -thick / 2);
56   b.add_point (p);
57   p += Offset (1, 1) * (blot / 2);
58
59   points = scm_cons (scm_from_double (p[X_AXIS]),
60                      scm_cons (scm_from_double (p[Y_AXIS]),
61                                points));
62
63   p = Offset (width, width * slope - thick / 2);
64   b.add_point (p);
65   p += Offset (-1, 1) * (blot / 2);
66
67   points = scm_cons (scm_from_double (p[X_AXIS]),
68                      scm_cons (scm_from_double (p[Y_AXIS]),
69                                points));
70
71   p = Offset (width, width * slope + thick / 2);
72   b.add_point (p);
73   p += Offset (-1, -1) * (blot / 2);
74
75   points = scm_cons (scm_from_double (p[X_AXIS]),
76                      scm_cons (scm_from_double (p[Y_AXIS]),
77                                points));
78
79   SCM expr = scm_list_n (ly_symbol2scm ("polygon"),
80                          ly_quote_scm (points),
81                          scm_from_double (blot),
82                          SCM_BOOL_T,
83                          SCM_UNDEFINED);
84
85   return Stencil (b, expr);
86 }
87
88 Stencil
89 Lookup::rotated_box (Real slope, Real width, Real thick, Real blot)
90 {
91   vector<Offset> pts;
92   Offset rot = Offset (1, slope).direction ();
93
94   pts.push_back (Offset (0, -thick / 2) * rot);
95   pts.push_back (Offset (width, -thick / 2) * rot);
96   pts.push_back (Offset (width, thick / 2) * rot);
97   pts.push_back (Offset (0, thick / 2) * rot);
98   return Lookup::round_filled_polygon (pts, blot);
99 }
100
101 Stencil
102 Lookup::horizontal_line (Interval w, Real th)
103 {
104   SCM at = scm_list_n (ly_symbol2scm ("draw-line"),
105                        scm_from_double (th),
106                        scm_from_double (w[LEFT]),
107                        scm_from_double (0),
108                        scm_from_double (w[RIGHT]),
109                        scm_from_double (0),
110                        SCM_UNDEFINED);
111
112   Box box;
113   box[X_AXIS] = w;
114   box[Y_AXIS] = Interval (-th / 2, th / 2);
115
116   return Stencil (box, at);
117 }
118
119 Stencil
120 Lookup::blank (Box b)
121 {
122   return Stencil (b, scm_string (SCM_EOL));
123 }
124
125 Stencil
126 Lookup::circle (Real rad, Real thick, bool filled)
127 {
128   Box b (Interval (-rad, rad), Interval (-rad, rad));
129   return Stencil (b, scm_list_4 (ly_symbol2scm ("circle"),
130                                  scm_from_double (rad),
131                                  scm_from_double (thick),
132                                  scm_from_bool (filled)));
133 }
134
135 Stencil
136 Lookup::filled_box (Box b)
137 {
138   return round_filled_box (b, 0.0);
139 }
140
141 /*
142  * round filled box:
143  *
144  *   __________________________________
145  *  /     \  ^           /     \      ^
146  * |         |blot              |     |
147  * |       | |dia       |       |     |
148  * |         |meter             |     |
149  * |\ _ _ /  v           \ _ _ /|     |
150  * |                            |     |
151  * |                            |     | Box
152  * |                    <------>|     | extent
153  * |                      blot  |     | (Y_AXIS)
154  * |                    diameter|     |
155  * |                            |     |
156  * |  _ _                  _ _  |     |
157  * |/     \              /     \|     |
158  * |                            |     |
159  * |       |            |       |     |
160  * |                            |     |
161  * x\_____/______________\_____/|_____v
162  * |(0, 0)                       |
163  * |                            |
164  * |                            |
165  * |<-------------------------->|
166  *       Box extent (X_AXIS)
167  */
168 Stencil
169 Lookup::round_filled_box (Box b, Real blotdiameter)
170 {
171   Real width = b.x ().delta ();
172   blotdiameter = std::min (blotdiameter, width);
173   Real height = b.y ().delta ();
174   blotdiameter = std::min (blotdiameter, height);
175
176   if (blotdiameter < 0.0)
177     {
178       if (!isinf (blotdiameter))
179         warning (_f ("Not drawing a box with negative dimension, %.2f by %.2f.",
180                      width, height));
181       return Stencil (b, SCM_EOL);
182     }
183
184   SCM at = (scm_list_n (ly_symbol2scm ("round-filled-box"),
185                         scm_from_double (-b[X_AXIS][LEFT]),
186                         scm_from_double (b[X_AXIS][RIGHT]),
187                         scm_from_double (-b[Y_AXIS][DOWN]),
188                         scm_from_double (b[Y_AXIS][UP]),
189                         scm_from_double (blotdiameter),
190                         SCM_UNDEFINED));
191
192   return Stencil (b, at);
193 }
194
195 /*
196  * Create Stencil that represents a filled polygon with round edges.
197  *
198  * LIMITATIONS:
199  *
200  * (a) Only outer (convex) edges are rounded.
201  *
202  * (b) This algorithm works as expected only for polygons whose edges
203  * do not intersect.  For example, the polygon ((0, 0), (q, 0), (0,
204  * q), (q, q)) has an intersection at point (q/2, q/2) and therefore
205  * will give a strange result.  Even non-adjacent edges that just
206  * touch each other will in general not work as expected for non-null
207  * blotdiameter.
208  *
209  * (c) Given a polygon ((x0, y0), (x1, y1), ... , (x (n-1), y (n-1))),
210  * if there is a natural number k such that blotdiameter is greater
211  * than the maximum of { | (x (k mod n), y (k mod n)) - (x ((k+1) mod n),
212  * y ((k+1) mod n)) |, | (x (k mod n), y (k mod n)) - (x ((k+2) mod n),
213  * y ((k+2) mod n)) |, | (x ((k+1) mod n), y ((k+1) mod n)) - (x ((k+2)
214  * mod n), y ((k+2) mod n)) | }, then the outline of the rounded
215  * polygon will exceed the outline of the core polygon.  In other
216  * words: Do not draw rounded polygons that have a leg smaller or
217  * thinner than blotdiameter (or set blotdiameter to a sufficiently
218  * small value -- maybe even 0.0)!
219  *
220  * NOTE: Limitations (b) and (c) arise from the fact that round edges
221  * are made by moulding sharp edges to round ones rather than adding
222  * to a core filled polygon.  For details of these two different
223  * approaches, see the thread upon the ledger lines patch that started
224  * on March 25, 2002 on the devel mailing list.  The below version of
225  * round_filled_polygon () sticks to the moulding model, which the
226  * majority of the list participants finally voted for.  This,
227  * however, results in the above limitations and a much increased
228  * complexity of the algorithm, since it has to compute a shrinked
229  * polygon -- which is not trivial define precisely and unambigously.
230  * With the other approach, one simply could move a circle of size
231  * blotdiameter along all edges of the polygon (which is what the
232  * postscript routine in the backend effectively does, but on the
233  * shrinked polygon). --jr
234  *
235  * An extra parameter "extroversion" has been added since staying just
236  * inside of a polygon will reduce its visual size when tracing a
237  * rounded path.  If extroversion is zero, the polygon is just traced
238  * as-is.  If it is -1 (the default) the drawing will stay just within
239  * the given polygon.  If it is 1, the traced line will stay just
240  * outside of the given polygon.
241  */
242 Stencil
243 Lookup::round_filled_polygon (vector<Offset> const &points,
244                               Real blotdiameter,
245                               Real extroversion)
246 {
247   /* TODO: Maybe print a warning if one of the above limitations
248      applies to the given polygon.  However, this is quite complicated
249      to check. */
250
251   const Real epsilon = 0.01;
252
253 #ifdef DEBUG
254   /* remove consecutive duplicate points */
255   for (vsize i = 0; i < points.size (); i++)
256     {
257       int next = (i + 1) % points.size ();
258       Real d = (points[i] - points[next]).length ();
259       if (d < epsilon)
260         programming_error ("Polygon should not have duplicate points");
261     }
262 #endif
263
264   /* special cases: degenerated polygons */
265   if (points.size () == 0)
266     return Stencil ();
267   if (points.size () == 1)
268     {
269       Stencil circ = circle (0.5 * (1.0 + extroversion) * blotdiameter, 0, true);
270       circ.translate (points[0]);
271       return circ;
272     }
273   if (points.size () == 2)
274     return Line_interface::make_line ((1.0 + extroversion) * blotdiameter, points[0], points[1]);
275
276   vector<Offset> shrunk_points;
277
278   if (extroversion == 0.0)
279     {
280       shrunk_points = points;
281     }
282   else
283     {
284       /* shrink polygon in size by 0.5 * blotdiameter */
285
286       // first we need to determine the orientation of the polygon in
287       // order to decide whether shrinking means moving the polygon to the
288       // left or to the right of the outline.  We do that by calculating
289       // (double) the oriented area of the polygon.  We first determine the
290       // center and do the area calculations relative to it.
291       // Mathematically, the result is not affected by this shift, but
292       // numerically a lot of cancellation is going on and this keeps its
293       // effects in check.
294
295       Offset center;
296       for (vsize i = 0; i < points.size (); i++)
297         center += points[i];
298       center /= points.size ();
299
300       Real area = 0.0;
301       Offset last = points.back () - center;
302
303       for (vsize i = 0; i < points.size (); i++)
304         {
305           Offset here = points[i] - center;
306           area += cross_product (last, here);
307           last = here;
308         }
309
310       bool ccw = area >= 0.0;  // true if whole shape is counterclockwise oriented
311
312       shrunk_points.resize (points.size ());
313
314       for (vsize i = 0; i < points.size (); i++)
315         {
316           int i0 = i;
317           int i1 = (i + 1) % points.size ();
318           int i2 = (i + 2) % points.size ();
319           Offset p0 = points[i0];
320           Offset p1 = points[i1];
321           Offset p2 = points[i2];
322           Offset p01 = p1 - p0;
323           Offset p12 = p2 - p1;
324           Offset inward0 = Offset(-p01[Y_AXIS], p01[X_AXIS]).direction ();
325           Offset inward2 = Offset(-p12[Y_AXIS], p12[X_AXIS]).direction ();
326
327           if (!ccw)
328             {
329               inward0 = -inward0;
330               inward2 = -inward2;
331             }
332
333           Offset middle = 0.5*(inward0 + inward2);
334
335           // "middle" now is a vector in the right direction for the
336           // shrinkage.  Its size needs to be large enough that the
337           // projection on either of the inward vectors has a size of 1.
338
339           Real proj = dot_product (middle, inward0);
340
341           // What's the size of proj?  Assuming that we have a corner
342           // angle of phi where 0 corresponds to a continuing line, the
343           // length of middle is 0.5 |(1+cos phi, sin phi)| = cos (phi/2),
344           // so its projection has length
345           // cos^2 (phi/2) = 0.5 + 0.5 cos (phi).
346           // We don't really want to move inwards more than 3 blob
347           // diameters corresponding to 6 blob radii.  So
348           // cos (phi/2) = 1/6 gives phi ~ 161, meaning that a 20 degree
349           // corner necessitates moving 3 blob diameters from the corner
350           // in order to stay inside the lines.  Ruler and circle agree.
351           // 0.03 is close enough to 1/36.  Basically we want to keep the
352           // shape from inverting from pulling too far inward.
353           // 3 diameters is pretty much a handwaving guess.
354
355           if (abs (proj) < 0.03)
356             proj = proj < 0 ? -0.03 : 0.03;
357
358           shrunk_points[i1] = p1 - (0.5 * blotdiameter / proj) * middle
359                           * extroversion;
360         }
361     }
362
363   /* build scm expression and bounding box */
364   SCM shrunk_points_scm = SCM_EOL;
365   Box box;
366   Box shrunk_box;
367   for (vsize i = 0; i < shrunk_points.size (); i++)
368     {
369       SCM x = scm_from_double (shrunk_points[i][X_AXIS]);
370       SCM y = scm_from_double (shrunk_points[i][Y_AXIS]);
371       shrunk_points_scm = scm_cons (x, scm_cons (y, shrunk_points_scm));
372       box.add_point (points[i]);
373       shrunk_box.add_point (shrunk_points[i]);
374     }
375   shrunk_box.widen (0.5*blotdiameter, 0.5*blotdiameter);
376   box.unite (shrunk_box);
377   SCM polygon_scm = scm_list_n (ly_symbol2scm ("polygon"),
378                                 ly_quote_scm (shrunk_points_scm),
379                                 scm_from_double (blotdiameter),
380                                 SCM_BOOL_T,
381                                 SCM_UNDEFINED);
382
383   Stencil polygon = Stencil (box, polygon_scm);
384   return polygon;
385 }
386
387 /*
388   TODO: deprecate?
389 */
390 Stencil
391 Lookup::frame (Box b, Real thick, Real blot)
392 {
393   Stencil m;
394   for (Axis a = X_AXIS; a < NO_AXES; a = Axis (a + 1))
395     {
396       Axis o = Axis ((a + 1) % NO_AXES);
397       for (LEFT_and_RIGHT (d))
398         {
399           Box edges;
400           edges[a] = b[a][d] + 0.5 * thick * Interval (-1, 1);
401           edges[o][DOWN] = b[o][DOWN] - thick / 2;
402           edges[o][UP] = b[o][UP] + thick / 2;
403
404           m.add_stencil (round_filled_box (edges, blot));
405         }
406     }
407   return m;
408 }
409
410 /*
411   Make a smooth curve along the points
412 */
413 Stencil
414 Lookup::slur (Bezier curve, Real curvethick, Real linethick,
415               SCM dash_details)
416 {
417   Stencil return_value;
418
419   /*
420       calculate the offset for the two beziers that make the sandwich
421       for the slur
422   */
423   Real alpha = (curve.control_[3] - curve.control_[0]).arg ();
424   Bezier back = curve;
425   Offset perp = curvethick * complex_exp (Offset (0, alpha + M_PI / 2)) * 0.5;
426   back.control_[1] += perp;
427   back.control_[2] += perp;
428
429   curve.control_[1] -= perp;
430   curve.control_[2] -= perp;
431
432   if (!scm_is_pair (dash_details))
433     {
434       /* solid slur  */
435       return_value = bezier_sandwich (back, curve, linethick);
436     }
437   else
438     {
439       /* dashed or combination slur */
440       int num_segments = scm_to_int (scm_length (dash_details));
441       for (int i = 0; i < num_segments; i++)
442         {
443           SCM dash_pattern = scm_list_ref (dash_details, scm_from_int (i));
444           Real t_min = robust_scm2double (scm_car (dash_pattern), 0);
445           Real t_max = robust_scm2double (scm_cadr (dash_pattern), 1.0);
446           Real dash_fraction
447             = robust_scm2double (scm_caddr (dash_pattern), 1.0);
448           Real dash_period
449             = robust_scm2double (scm_cadddr (dash_pattern), 0.75);
450           Bezier back_segment = back.extract (t_min, t_max);
451           Bezier curve_segment = curve.extract (t_min, t_max);
452           if (dash_fraction == 1.0)
453             return_value.add_stencil (bezier_sandwich (back_segment,
454                                                        curve_segment,
455                                                        linethick));
456           else
457             {
458               Bezier back_dash, curve_dash;
459               Real seg_length = (back_segment.control_[3]
460                                  - back_segment.control_[0]).length ();
461               int pattern_count = (int) (seg_length / dash_period);
462               Real pattern_length = 1.0 / (pattern_count + dash_fraction);
463               Real start_t, end_t;
464               for (int p = 0; p <= pattern_count; p++)
465                 {
466                   start_t = p * pattern_length;
467                   end_t = (p + dash_fraction) * pattern_length;
468                   back_dash
469                     = back_segment.extract (start_t, end_t);
470                   curve_dash
471                     = curve_segment.extract (start_t, end_t);
472                   return_value.add_stencil (bezier_sandwich (back_dash,
473                                                              curve_dash,
474                                                              linethick));
475                 }
476             }
477         }
478     }
479   return return_value;
480 }
481
482 /*
483  * Bezier Sandwich:
484  *
485  *                               .|
486  *                        .       |
487  *              top .             |
488  *              . curve           |
489  *          .                     |
490  *       .                        |
491  *     .                          |
492  *    |                           |
493  *    |                          .|
494  *    |                     .
495  *    |         bottom .
496  *    |            . curve
497  *    |         .
498  *    |      .
499  *    |   .
500  *    | .
501  *    |.
502  *    |
503  *
504  */
505 Stencil
506 Lookup::bezier_sandwich (Bezier top_curve, Bezier bottom_curve, Real thickness)
507 {
508   SCM commands = scm_list_n (ly_symbol2scm ("moveto"),
509                              scm_from_double (top_curve.control_[0][X_AXIS]),
510                              scm_from_double (top_curve.control_[0][Y_AXIS]),
511                              ly_symbol2scm ("curveto"),
512                              scm_from_double (top_curve.control_[1][X_AXIS]),
513                              scm_from_double (top_curve.control_[1][Y_AXIS]),
514                              scm_from_double (top_curve.control_[2][X_AXIS]),
515                              scm_from_double (top_curve.control_[2][Y_AXIS]),
516                              scm_from_double (top_curve.control_[3][X_AXIS]),
517                              scm_from_double (top_curve.control_[3][Y_AXIS]),
518                              ly_symbol2scm ("lineto"),
519                              scm_from_double (bottom_curve.control_[3][X_AXIS]),
520                              scm_from_double (bottom_curve.control_[3][Y_AXIS]),
521                              ly_symbol2scm ("curveto"),
522                              scm_from_double (bottom_curve.control_[2][X_AXIS]),
523                              scm_from_double (bottom_curve.control_[2][Y_AXIS]),
524                              scm_from_double (bottom_curve.control_[1][X_AXIS]),
525                              scm_from_double (bottom_curve.control_[1][Y_AXIS]),
526                              scm_from_double (bottom_curve.control_[0][X_AXIS]),
527                              scm_from_double (bottom_curve.control_[0][Y_AXIS]),
528                              ly_symbol2scm ("closepath"),
529                              SCM_UNDEFINED);
530
531   SCM horizontal_bend = scm_list_n (ly_symbol2scm ("path"),
532                                     scm_from_double (thickness),
533                                     ly_quote_scm (commands),
534                                     ly_quote_scm (ly_symbol2scm ("round")),
535                                     ly_quote_scm (ly_symbol2scm ("round")),
536                                     SCM_BOOL_T,
537                                     SCM_UNDEFINED);
538
539   Interval x_extent = top_curve.extent (X_AXIS);
540   x_extent.unite (bottom_curve.extent (X_AXIS));
541   Interval y_extent = top_curve.extent (Y_AXIS);
542   y_extent.unite (bottom_curve.extent (Y_AXIS));
543   Box b (x_extent, y_extent);
544
545   b.widen (0.5 * thickness, 0.5 * thickness);
546   return Stencil (b, horizontal_bend);
547 }
548
549 Stencil
550 Lookup::repeat_slash (Real w, Real s, Real t)
551 {
552
553   Real x_width = sqrt ((t * t) + ((t / s) * (t / s)));
554   Real height = w * s;
555
556   SCM controls = scm_list_n (ly_symbol2scm ("moveto"),
557                              scm_from_double (0),
558                              scm_from_double (0),
559                              ly_symbol2scm ("rlineto"),
560                              scm_from_double (x_width),
561                              scm_from_double (0),
562                              ly_symbol2scm ("rlineto"),
563                              scm_from_double (w),
564                              scm_from_double (height),
565                              ly_symbol2scm ("rlineto"),
566                              scm_from_double (-x_width),
567                              scm_from_double (0),
568                              ly_symbol2scm ("closepath"),
569                              SCM_UNDEFINED);
570
571   SCM slashnodot = scm_list_n (ly_symbol2scm ("path"),
572                                scm_from_double (0),
573                                ly_quote_scm (controls),
574                                ly_quote_scm (ly_symbol2scm ("round")),
575                                ly_quote_scm (ly_symbol2scm ("round")),
576                                SCM_BOOL_T,
577                                SCM_UNDEFINED);
578
579   Box b (Interval (0, w + sqrt (sqr (t / s) + sqr (t))),
580          Interval (0, w * s));
581
582   return Stencil (b, slashnodot); //  http://slashnodot.org
583 }
584
585 Stencil
586 Lookup::bracket (Axis a, Interval iv, Real thick, Real protrude, Real blot)
587 {
588   Box b;
589   Axis other = Axis ((a + 1) % 2);
590   b[a] = iv;
591   b[other] = Interval (-1, 1) * thick * 0.5;
592
593   Stencil m = round_filled_box (b, blot);
594
595   b[a] = Interval (iv[UP] - thick, iv[UP]);
596   Interval oi = Interval (-thick / 2, thick / 2 + fabs (protrude));
597   oi *= sign (protrude);
598   b[other] = oi;
599   m.add_stencil (round_filled_box (b, blot));
600   b[a] = Interval (iv[DOWN], iv[DOWN] + thick);
601   m.add_stencil (round_filled_box (b, blot));
602
603   return m;
604 }
605
606 Stencil
607 Lookup::triangle (Interval iv, Real thick, Real protrude)
608 {
609   Box b;
610   b[X_AXIS] = Interval (0, iv.length ());
611   b[Y_AXIS] = Interval (std::min (0., protrude), std::max (0.0, protrude));
612
613   vector<Offset> points;
614   points.push_back (Offset (iv[LEFT], 0));
615   points.push_back (Offset (iv[RIGHT], 0));
616   points.push_back (Offset (iv.center (), protrude));
617   points.push_back (Offset (iv[LEFT], 0));  // close triangle
618
619   return points_to_line_stencil (thick, points);
620
621 }
622
623 Stencil
624 Lookup::points_to_line_stencil (Real thick, vector<Offset> const &points)
625 {
626   Stencil ret;
627   for (vsize i = 1; i < points.size (); i++)
628     {
629       if (points[i - 1].is_sane () && points[i].is_sane ())
630         {
631           Stencil line
632             = Line_interface::make_line (thick, points[i - 1], points[i]);
633           ret.add_stencil (line);
634         }
635     }
636   return ret;
637 }