]> git.donarmstrong.com Git - lilypond.git/blob - lily/beam.cc
(parse_symbol_list): Bugfix.
[lilypond.git] / lily / beam.cc
1 /*
2   beam.cc -- implement Beam
3
4   source file of the GNU LilyPond music typesetter
5
6   (c) 1997--2005 Han-Wen Nienhuys <hanwen@cs.uu.nl>
7   Jan Nieuwenhuizen <janneke@gnu.org>
8 */
9
10 /*
11   TODO:
12
13   - Determine auto knees based on positions if it's set by the user.
14
15   - the code is littered with * and / staff_space calls for
16   #'positions. Consider moving to real-world coordinates?
17
18   Problematic issue is user tweaks (user tweaks are in staff-coordinates.)
19
20   Notes:
21
22   - Stems run to the Y-center of the beam.
23
24   - beam_translation is the offset between Y centers of the beam.
25 */
26
27 #include <math.h> // tanh.
28
29 #include "beam.hh"
30 #include "interval-set.hh"
31 #include "directional-element-interface.hh"
32 #include "beaming.hh"
33 #include "misc.hh"
34 #include "least-squares.hh"
35 #include "stem.hh"
36 #include "output-def.hh"
37 #include "lookup.hh"
38 #include "pointer-group-interface.hh"
39 #include "staff-symbol-referencer.hh"
40 #include "item.hh"
41 #include "spanner.hh"
42 #include "warn.hh"
43
44 #if DEBUG_QUANTING
45 #include "text-interface.hh" // debug output.
46 #include "font-interface.hh" // debug output.
47 #endif
48
49 void
50 Beam::add_stem (Grob *me, Grob *s)
51 {
52   Pointer_group_interface::add_grob (me, ly_symbol2scm ("stems"), s);
53
54   s->add_dependency (me);
55
56   assert (!Stem::get_beam (s));
57   s->set_object ("beam", me->self_scm ());
58
59   add_bound_item (dynamic_cast<Spanner *> (me), dynamic_cast<Item *> (s));
60 }
61
62 Real
63 Beam::get_thickness (Grob *me)
64 {
65   return robust_scm2double (me->get_property ("thickness"), 0)
66     * Staff_symbol_referencer::staff_space (me);
67 }
68
69 /* Return the translation between 2 adjoining beams. */
70 Real
71 Beam::get_beam_translation (Grob *me)
72 {
73   SCM func = me->get_property ("space-function");
74
75   if (ly_is_procedure (func))
76     {
77       SCM s = scm_call_2 (func, me->self_scm (), scm_from_int (get_beam_count (me)));
78       return scm_to_double (s);
79     }
80   else
81     {
82       return 0.81;
83     }
84 }
85
86 /* Maximum beam_count. */
87 int
88 Beam::get_beam_count (Grob *me)
89 {
90   int m = 0;
91
92   extract_grob_set (me, "stems", stems);
93   for (int i = 0; i < stems.size (); i++)
94     {
95       Grob *stem = stems[i];
96       m = max (m, (Stem::beam_multiplicity (stem).length () + 1));
97     }
98   return m;
99 }
100
101 /*
102   Space return space between beams.
103 */
104 MAKE_SCHEME_CALLBACK (Beam, space_function, 2);
105 SCM
106 Beam::space_function (SCM smob, SCM beam_count)
107 {
108   Grob *me = unsmob_grob (smob);
109
110   Real staff_space = Staff_symbol_referencer::staff_space (me);
111   Real line = Staff_symbol_referencer::line_thickness (me);
112   Real thickness = get_thickness (me);
113
114   Real beam_translation = scm_to_int (beam_count) < 4
115     ? (2 * staff_space + line - thickness) / 2.0
116     : (3 * staff_space + line - thickness) / 3.0;
117
118   return scm_from_double (beam_translation);
119 }
120
121 /* After pre-processing all directions should be set.
122    Several post-processing routines (stem, slur, script) need stem/beam
123    direction.
124    Currenly, this means that beam has set all stem's directions.
125    [Alternatively, stems could set its own directions, according to
126    their beam, during 'final-pre-processing'.] */
127 MAKE_SCHEME_CALLBACK (Beam, before_line_breaking, 1);
128 SCM
129 Beam::before_line_breaking (SCM smob)
130 {
131   Grob *me = unsmob_grob (smob);
132
133   /* Beams with less than 2 two stems don't make much sense, but could happen
134      when you do
135
136      [r8 c8 r8].
137
138      For a beam that  only has one stem, we try to do some disappearance magic:
139      we revert the flag, and move on to The Eternal Engraving Fields. */
140
141   int count = visible_stem_count (me);
142   if (count < 2)
143     {
144       extract_grob_set (me, "stems", stems);
145       if (stems.size () == 1)
146         {
147           me->warning (_ ("removing beam with less than two stems"));
148
149           stems[0]->set_object ("beam", SCM_EOL);
150           me->suicide ();
151
152           return SCM_UNSPECIFIED;
153         }
154       else if (stems.size () == 0)
155         {
156           me->suicide ();
157           return SCM_UNSPECIFIED;
158         }
159     }
160   if (count >= 1)
161     {
162       Direction d = get_default_dir (me);
163
164       consider_auto_knees (me);
165       set_stem_directions (me, d);
166
167       connect_beams (me);
168
169       set_stem_shorten (me);
170     }
171
172   return SCM_EOL;
173 }
174
175 /* We want a maximal number of shared beams, but if there is choice, we
176  * take the one that is closest to the end of the stem. This is for
177  * situations like
178  *
179  *        x
180  *       |
181  *       |
182  *   |===|
183  *   |=
184  *   |
185  *  x
186  */
187 int
188 position_with_maximal_common_beams (SCM left_beaming, SCM right_beaming,
189                                     Direction left_dir,
190                                     Direction right_dir)
191 {
192   Slice lslice = int_list_to_slice (scm_cdr (left_beaming));
193
194   int best_count = 0;
195   int best_start = 0;
196   for (int i = lslice[-left_dir];
197        (i - lslice[left_dir]) * left_dir <= 0; i += left_dir)
198     {
199       int count = 0;
200       for (SCM s = scm_car (right_beaming); scm_is_pair (s); s = scm_cdr (s))
201         {
202           int k = -right_dir * scm_to_int (scm_car (s)) + i;
203           if (scm_c_memq (scm_from_int (k), left_beaming) != SCM_BOOL_F)
204             count++;
205         }
206
207       if (count >= best_count)
208         {
209           best_count = count;
210           best_start = i;
211         }
212     }
213
214   return best_start;
215 }
216
217 void
218 Beam::connect_beams (Grob *me)
219 {
220   extract_grob_set (me, "stems", stems);
221
222   Slice last_int;
223   last_int.set_empty ();
224   SCM last_beaming = SCM_EOL;
225   Direction last_dir = CENTER;
226   for (int i = 0; i < stems.size (); i++)
227     {
228       Grob *this_stem = stems[i];
229       SCM this_beaming = this_stem->get_property ("beaming");
230
231       Direction this_dir = get_grob_direction (this_stem);
232       if (scm_is_pair (last_beaming) && scm_is_pair (this_beaming))
233         {
234           int start_point = position_with_maximal_common_beams
235             (last_beaming, this_beaming,
236              last_dir, this_dir);
237
238           Direction d = LEFT;
239           Slice new_slice;
240           do
241             {
242               if (d == RIGHT && i == stems.size () - 1)
243                 continue;
244
245               new_slice.set_empty ();
246               SCM s = index_get_cell (this_beaming, d);
247               for (; scm_is_pair (s); s = scm_cdr (s))
248                 {
249                   int new_beam_pos
250                     = start_point - this_dir * scm_to_int (scm_car (s));
251
252                   new_slice.add_point (new_beam_pos);
253                   scm_set_car_x (s, scm_from_int (new_beam_pos));
254                 }
255             }
256           while (flip (&d) != LEFT);
257
258           if (!new_slice.is_empty ())
259             last_int = new_slice;
260         }
261       else
262         {
263           scm_set_car_x (this_beaming, SCM_EOL);
264           SCM s = scm_cdr (this_beaming);
265           for (; scm_is_pair (s); s = scm_cdr (s))
266             {
267               int np = -this_dir * scm_to_int (scm_car (s));
268               scm_set_car_x (s, scm_from_int (np));
269               last_int.add_point (np);
270             }
271         }
272
273       if (i == stems.size () -1)
274         scm_set_cdr_x (this_beaming, SCM_EOL);
275
276       if (scm_ilength (scm_cdr (this_beaming)) > 0)
277         {
278           last_beaming = this_beaming;
279           last_dir = this_dir;
280         }
281     }
282 }
283
284 /*
285   TODO: should not make beams per stem, but per Y-level; probably when
286   someone wants to sponsor feathered beaming.
287 */
288 MAKE_SCHEME_CALLBACK (Beam, print, 1);
289 SCM
290 Beam::print (SCM grob)
291 {
292   Spanner *me = unsmob_spanner (grob);
293   position_beam (me);
294
295   extract_grob_set (me, "stems", stems);
296   Grob *xcommon = common_refpoint_of_array (stems, me, X_AXIS);
297
298   xcommon = me->get_bound (LEFT)->common_refpoint (xcommon, X_AXIS);
299   xcommon = me->get_bound (RIGHT)->common_refpoint (xcommon, X_AXIS);
300
301   Real x0, dx;
302   if (visible_stem_count (me))
303     {
304       // ugh -> use commonx
305       x0 = first_visible_stem (me)->relative_coordinate (xcommon, X_AXIS);
306       dx = last_visible_stem (me)->relative_coordinate (xcommon, X_AXIS) - x0;
307     }
308   else
309     {
310       x0 = stems[0]->relative_coordinate (xcommon, X_AXIS);
311       dx = stems.top ()->relative_coordinate (xcommon, X_AXIS) - x0;
312     }
313
314   SCM posns = me->get_property ("positions");
315   Drul_array<Real> pos;
316   if (!is_number_pair (posns))
317     {
318       programming_error ("no beam positions?");
319       pos = Interval (0, 0);
320     }
321   else
322     pos = ly_scm2realdrul (posns);
323
324   scale_drul (&pos, Staff_symbol_referencer::staff_space (me));
325
326   Real dy = pos[RIGHT] - pos[LEFT];
327   Real slope = (dy && dx) ? dy / dx : 0;
328
329   Real thick = get_thickness (me);
330   Real bdy = get_beam_translation (me);
331
332   SCM last_beaming = SCM_EOL;
333   Real last_xposn = -1;
334   Real last_stem_width = -1;
335
336   Real gap_length = robust_scm2double (me->get_property ("gap"), 0.0);
337
338   Stencil the_beam;
339   Real lt = me->get_layout ()->get_dimension (ly_symbol2scm ("linethickness"));
340
341   for (int i = 0; i <= stems.size (); i++)
342     {
343       Grob *stem = (i < stems.size ()) ? stems[i] : 0;
344
345       SCM this_beaming = stem ? stem->get_property ("beaming") : SCM_EOL;
346       Real xposn = stem ? stem->relative_coordinate (xcommon, X_AXIS) : 0.0;
347       Real stem_width = stem ? robust_scm2double (stem->get_property ("thickness"), 1.0) * lt : 0;
348       Direction stem_dir = stem ? to_dir (stem->get_property ("direction")) : CENTER;
349       /*
350         We do the space left of ST, with lfliebertjes pointing to the
351         right from the left stem, and rfliebertjes pointing left from
352         right stem.
353       */
354       SCM left = (i > 0) ? scm_cdr (last_beaming) : SCM_EOL;
355       SCM right = stem ? scm_car (this_beaming) : SCM_EOL;
356
357       Array<int> full_beams;
358       Array<int> lfliebertjes;
359       Array<int> rfliebertjes;
360
361       for (SCM s = left;
362            scm_is_pair (s); s = scm_cdr (s))
363         {
364           int b = scm_to_int (scm_car (s));
365           if (scm_c_memq (scm_car (s), right) != SCM_BOOL_F)
366             full_beams.push (b);
367           else
368             lfliebertjes.push (b);
369         }
370       for (SCM s = right;
371            scm_is_pair (s); s = scm_cdr (s))
372         {
373           int b = scm_to_int (scm_car (s));
374           if (scm_c_memq (scm_car (s), left) == SCM_BOOL_F)
375             rfliebertjes.push (b);
376         }
377
378       Drul_array<Real> break_overshoot
379         = robust_scm2drul (me->get_property ("break-overshoot"),
380                            Drul_array<Real> (-0.5, 0.0));
381
382       Real w = (i > 0 && stem)
383         ? (xposn - last_xposn)
384         : break_overshoot[ (i == 0) ? LEFT : RIGHT];
385
386       Real stem_offset = 0.0;
387       if (i > 0)
388         {
389           w += last_stem_width / 2;
390           stem_offset = -last_stem_width / 2;
391         }
392
393       if (stem)
394         w += stem_width / 2;
395
396       Real blot = me->get_layout ()->get_dimension (ly_symbol2scm ("blotdiameter"));
397       Stencil whole = Lookup::beam (slope, w, thick, blot);
398       Stencil gapped;
399
400       int gap_count = 0;
401       if (scm_is_number (me->get_property ("gap-count")))
402         {
403           gap_count = scm_to_int (me->get_property ("gap-count"));
404           gapped = Lookup::beam (slope, w - 2 * gap_length, thick, blot);
405
406           full_beams.sort (default_compare);
407           if (stem_dir == UP)
408             full_beams.reverse ();
409         }
410
411       int k = 0;
412       for (int j = full_beams.size (); j--;)
413         {
414           Stencil b (whole);
415
416           if (k++ < gap_count)
417             {
418               b = gapped;
419               b.translate_axis (gap_length, X_AXIS);
420             }
421           b.translate_axis (last_xposn - x0 + stem_offset, X_AXIS);
422           b.translate_axis (slope * (last_xposn - x0) + bdy * full_beams[j], Y_AXIS);
423
424           the_beam.add_stencil (b);
425         }
426
427       if (lfliebertjes.size () || rfliebertjes.size ())
428         {
429           Real nw_f;
430
431           if (stem)
432             {
433               int t = Stem::duration_log (stem);
434
435               SCM proc = me->get_property ("flag-width-function");
436               SCM result = scm_call_1 (proc, scm_from_int (t));
437               nw_f = scm_to_double (result);
438             }
439           else
440             nw_f = break_overshoot[RIGHT] / 2;
441
442           /* Half beam should be one note-width,
443              but let's make sure two half-beams never touch */
444           Real lw = nw_f;
445           Real rw = nw_f;
446           if (i > 0)
447             rw = min (nw_f, ((xposn - last_xposn) / 2));
448           else
449             rw = xposn - me->get_bound (LEFT)->extent (xcommon, X_AXIS)[RIGHT]
450               + break_overshoot[LEFT];
451
452           if (stem)
453             lw = min (nw_f, ((xposn - last_xposn) / 2));
454           else
455             lw = me->get_bound (RIGHT)->relative_coordinate (xcommon, X_AXIS)
456               - last_xposn
457               + break_overshoot[RIGHT];
458
459           Stencil rhalf = Lookup::beam (slope, rw, thick, blot);
460           Stencil lhalf = Lookup::beam (slope, lw, thick, blot);
461           for (int j = lfliebertjes.size (); j--;)
462             {
463               Stencil b (lhalf);
464               b.translate_axis (last_xposn - x0, X_AXIS);
465               b.translate_axis (slope * (last_xposn - x0) + bdy * lfliebertjes[j], Y_AXIS);
466               the_beam.add_stencil (b);
467             }
468           for (int j = rfliebertjes.size (); j--;)
469             {
470               Stencil b (rhalf);
471               b.translate_axis (xposn - x0 - rw, X_AXIS);
472               b.translate_axis (slope * (xposn - x0 - rw)
473                                 + bdy * rfliebertjes[j], Y_AXIS);
474               the_beam.add_stencil (b);
475             }
476         }
477
478       last_xposn = xposn;
479       last_stem_width = stem_width;
480       last_beaming = this_beaming;
481     }
482
483   the_beam.translate_axis (x0 - me->relative_coordinate (xcommon, X_AXIS), X_AXIS);
484   the_beam.translate_axis (pos[LEFT], Y_AXIS);
485
486 #if (DEBUG_QUANTING)
487   SCM quant_score = me->get_property ("quant-score");
488   if (to_boolean (me->get_layout ()->lookup_variable (ly_symbol2scm ("debug-beam-quanting")))
489       && scm_is_string (quant_score))
490     {
491
492       /*
493         This code prints the demerits for each beam. Perhaps this
494         should be switchable for those who want to twiddle with the
495         parameters.
496       */
497       String str;
498       SCM properties = Font_interface::text_font_alist_chain (me);
499
500       Direction stem_dir = stems.size () ? to_dir (stems[0]->get_property ("direction")) : UP;
501
502       Stencil tm = *unsmob_stencil (Text_interface::interpret_markup
503                                     (me->get_layout ()->self_scm (), properties, quant_score));
504       the_beam.add_at_edge (Y_AXIS, stem_dir, tm, 1.0, 0);
505     }
506 #endif
507
508   return the_beam.smobbed_copy ();
509 }
510
511 Direction
512 Beam::get_default_dir (Grob *me)
513 {
514   Drul_array<int> total;
515   total[UP] = total[DOWN] = 0;
516   Drul_array<int> count;
517   count[UP] = count[DOWN] = 0;
518   Direction d = DOWN;
519
520   extract_grob_set (me, "stems", stems);
521
522   for (int i = 0; i < stems.size (); i++)
523     do
524       {
525         Grob *s = stems[i];
526         Direction sd = get_grob_direction (s);
527
528         int center_distance = max (int (- d * Stem::head_positions (s) [-d]), 0);
529         int current = sd ? (1 + d * sd) / 2 : center_distance;
530
531         if (current)
532           {
533             total[d] += current;
534             count[d]++;
535           }
536       }
537     while (flip (&d) != DOWN);
538
539   SCM func = me->get_property ("dir-function");
540   SCM s = scm_call_2 (func,
541                       scm_cons (scm_from_int (count[UP]),
542                                 scm_from_int (count[DOWN])),
543                       scm_cons (scm_from_int (total[UP]),
544                                 scm_from_int (total[DOWN])));
545
546   if (scm_is_number (s) && scm_to_int (s))
547     return to_dir (s);
548
549   /* If dir is not determined: get default */
550   return to_dir (me->get_property ("neutral-direction"));
551 }
552
553 /* Set all stems with non-forced direction to beam direction.
554    Urg: non-forced should become `without/with unforced' direction,
555    once stem gets cleaned-up. */
556 void
557 Beam::set_stem_directions (Grob *me, Direction d)
558 {
559   extract_grob_set (me, "stems", stems);
560
561   for (int i = 0; i < stems.size (); i++)
562     {
563       Grob *s = stems[i];
564
565       SCM forcedir = s->get_property ("direction");
566       if (!to_dir (forcedir))
567         set_grob_direction (s, d);
568     }
569 }
570
571 /*
572   Only try horizontal beams for knees.  No reliable detection of
573   anything else is possible here, since we don't know funky-beaming
574   settings, or X-distances (slopes!)  People that want sloped
575   knee-beams, should set the directions manually.
576
577
578   TODO:
579
580   this routine should take into account the stemlength scoring
581   of a possible knee/nonknee beam.
582 */
583 void
584 Beam::consider_auto_knees (Grob *me)
585 {
586   SCM scm = me->get_property ("auto-knee-gap");
587   if (!scm_is_number (scm))
588     return;
589
590   Interval_set gaps;
591
592   gaps.set_full ();
593
594   extract_grob_set (me, "stems", stems);
595
596   Grob *common = common_refpoint_of_array (stems, me, Y_AXIS);
597   Real staff_space = Staff_symbol_referencer::staff_space (me);
598
599   Array<Interval> head_extents_array;
600   for (int i = 0; i < stems.size (); i++)
601     {
602       Grob *stem = stems[i];
603       if (Stem::is_invisible (stem))
604         continue;
605
606       Interval head_extents = Stem::head_positions (stem);
607       if (!head_extents.is_empty ())
608         {
609           head_extents[LEFT] += -1;
610           head_extents[RIGHT] += 1;
611           head_extents *= staff_space * 0.5;
612
613           /*
614             We could subtract beam Y position, but this routine only
615             sets stem directions, a constant shift does not have an
616             influence.
617           */
618           head_extents += stem->relative_coordinate (common, Y_AXIS);
619
620           if (to_dir (stem->get_property ("direction")))
621             {
622               Direction stemdir = to_dir (stem->get_property ("direction"));
623               head_extents[-stemdir] = -stemdir * infinity_f;
624             }
625         }
626       head_extents_array.push (head_extents);
627
628       gaps.remove_interval (head_extents);
629     }
630
631   Interval max_gap;
632   Real max_gap_len = 0.0;
633
634   for (int i = gaps.allowed_regions_.size () -1; i >= 0; i--)
635     {
636       Interval gap = gaps.allowed_regions_[i];
637
638       /*
639         the outer gaps are not knees.
640       */
641       if (isinf (gap[LEFT]) || isinf (gap[RIGHT]))
642         continue;
643
644       if (gap.length () >= max_gap_len)
645         {
646           max_gap_len = gap.length ();
647           max_gap = gap;
648         }
649     }
650
651   Real beam_translation = get_beam_translation (me);
652   Real beam_thickness = Beam::get_thickness (me);
653   int beam_count = Beam::get_beam_count (me);
654   Real height_of_beams = beam_thickness / 2
655     + (beam_count - 1) * beam_translation;
656   Real threshold = scm_to_double (scm) + height_of_beams;
657
658   if (max_gap_len > threshold)
659     {
660       int j = 0;
661       for (int i = 0; i < stems.size (); i++)
662         {
663           Grob *stem = stems[i];
664           if (Stem::is_invisible (stem))
665             continue;
666
667           Interval head_extents = head_extents_array[j++];
668
669           Direction d = (head_extents.center () < max_gap.center ())
670             ? UP : DOWN;
671
672           stem->set_property ("direction", scm_from_int (d));
673
674           head_extents.intersect (max_gap);
675           assert (head_extents.is_empty () || head_extents.length () < 1e-6);
676         }
677     }
678 }
679
680 /* Set stem's shorten property if unset.
681
682 TODO:
683 take some y-position (chord/beam/nearest?) into account
684 scmify forced-fraction
685
686 This is done in beam because the shorten has to be uniform over the
687 entire beam.
688 */
689 void
690 Beam::set_stem_shorten (Grob *me)
691 {
692   /*
693     shortening looks silly for x staff beams
694   */
695   if (is_knee (me))
696     return;
697
698   Real forced_fraction = 1.0 * forced_stem_count (me)
699     / visible_stem_count (me);
700
701   int beam_count = get_beam_count (me);
702
703   SCM shorten_list = me->get_property ("beamed-stem-shorten");
704   if (shorten_list == SCM_EOL)
705     return;
706
707   Real staff_space = Staff_symbol_referencer::staff_space (me);
708
709   SCM shorten_elt
710     = robust_list_ref (beam_count -1, shorten_list);
711   Real shorten_f = scm_to_double (shorten_elt) * staff_space;
712
713   /* your similar cute comment here */
714   shorten_f *= forced_fraction;
715
716   if (shorten_f)
717     me->set_property ("shorten", scm_from_double (shorten_f));
718 }
719
720 /*  Call list of y-dy-callbacks, that handle setting of
721     grob-properties
722 */
723 MAKE_SCHEME_CALLBACK (Beam, after_line_breaking, 1);
724 SCM
725 Beam::after_line_breaking (SCM smob)
726 {
727   Grob *me = unsmob_grob (smob);
728
729   position_beam (me);
730   return SCM_UNSPECIFIED;
731 }
732
733 void
734 Beam::position_beam (Grob *me)
735 {
736   if (!me->is_live ())
737     return;
738   if (to_boolean (me->get_property ("positioning-done")))
739     return;
740
741   me->set_property ("positioning-done", SCM_BOOL_T);
742
743   /* Copy to mutable list. */
744   SCM s = ly_deep_copy (me->get_property ("positions"));
745   me->set_property ("positions", s);
746
747   if (scm_car (s) == SCM_BOOL_F)
748     {
749       // one wonders if such genericity is necessary  --hwn.
750       SCM callbacks = me->get_property ("position-callbacks");
751       for (SCM i = callbacks; scm_is_pair (i); i = scm_cdr (i))
752         scm_call_1 (scm_car (i), me->self_scm ());
753     }
754
755   set_stem_lengths (me);
756 }
757
758 void
759 set_minimum_dy (Grob *me, Real *dy)
760 {
761   if (*dy)
762     {
763       /*
764         If dy is smaller than the smallest quant, we
765         get absurd direction-sign penalties.
766       */
767
768       Real ss = Staff_symbol_referencer::staff_space (me);
769       Real thickness = Beam::get_thickness (me) / ss;
770       Real slt = Staff_symbol_referencer::line_thickness (me) / ss;
771       Real sit = (thickness - slt) / 2;
772       Real inter = 0.5;
773       Real hang = 1.0 - (thickness - slt) / 2;
774
775       *dy = sign (*dy) * max (fabs (*dy),
776                               min (min (sit, inter), hang));
777     }
778 }
779
780 /*
781   Compute  a first approximation to the beam slope.
782 */
783 MAKE_SCHEME_CALLBACK (Beam, least_squares, 1);
784 SCM
785 Beam::least_squares (SCM smob)
786 {
787   Grob *me = unsmob_grob (smob);
788
789   int count = visible_stem_count (me);
790   Interval pos (0, 0);
791
792   if (count < 1)
793     {
794       me->set_property ("positions", ly_interval2scm (pos));
795       return SCM_UNSPECIFIED;
796     }
797
798   Array<Real> x_posns;
799   extract_grob_set (me, "stems", stems);
800   Grob *commonx = common_refpoint_of_array (stems, me, X_AXIS);
801   Grob *commony = common_refpoint_of_array (stems, me, Y_AXIS);
802
803   Real my_y = me->relative_coordinate (commony, Y_AXIS);
804
805   Grob *fvs = first_visible_stem (me);
806   Grob *lvs = last_visible_stem (me);
807
808   Interval ideal (Stem::get_stem_info (fvs).ideal_y_
809                   + fvs->relative_coordinate (commony, Y_AXIS) -my_y,
810                   Stem::get_stem_info (lvs).ideal_y_
811                   + lvs->relative_coordinate (commony, Y_AXIS) - my_y);
812
813   Real x0 = first_visible_stem (me)->relative_coordinate (commonx, X_AXIS);
814   for (int i = 0; i < stems.size (); i++)
815     {
816       Grob *s = stems[i];
817
818       Real x = s->relative_coordinate (commonx, X_AXIS) - x0;
819       x_posns.push (x);
820     }
821   Real dx = last_visible_stem (me)->relative_coordinate (commonx, X_AXIS) - x0;
822
823   Real y = 0;
824   Real slope = 0;
825   Real dy = 0;
826
827   if (!ideal.delta ())
828     {
829       Interval chord (Stem::chord_start_y (first_visible_stem (me)),
830                       Stem::chord_start_y (last_visible_stem (me)));
831
832       /* Simple beams (2 stems) on middle line should be allowed to be
833          slightly sloped.
834
835          However, if both stems reach middle line,
836          ideal[LEFT] == ideal[RIGHT] and ideal.delta () == 0.
837
838          For that case, we apply artificial slope */
839       if (!ideal[LEFT] && chord.delta () && count == 2)
840         {
841           /* FIXME. -> UP */
842           Direction d = (Direction) (sign (chord.delta ()) * UP);
843           pos[d] = get_thickness (me) / 2;
844           pos[-d] = -pos[d];
845         }
846       else
847         pos = ideal;
848
849       /*
850         For broken beams this doesn't work well. In this case, the
851         slope esp. of the first part of a broken beam should predict
852         where the second part goes.
853       */
854       me->set_property ("least-squares-dy",
855                         scm_from_double (pos[RIGHT] - pos[LEFT]));
856     }
857   else
858     {
859       Array<Offset> ideals;
860       for (int i = 0; i < stems.size (); i++)
861         {
862           Grob *s = stems[i];
863           if (Stem::is_invisible (s))
864             continue;
865           ideals.push (Offset (x_posns[i],
866                                Stem::get_stem_info (s).ideal_y_
867                                + s->relative_coordinate (commony, Y_AXIS)
868                                - my_y));
869         }
870
871       minimise_least_squares (&slope, &y, ideals);
872
873       dy = slope * dx;
874
875       set_minimum_dy (me, &dy);
876       me->set_property ("least-squares-dy", scm_from_double (dy));
877       pos = Interval (y, (y + dy));
878     }
879
880   /*
881     "position" is relative to the staff.
882   */
883   scale_drul (&pos, 1 / Staff_symbol_referencer::staff_space (me));
884
885   me->set_property ("positions", ly_interval2scm (pos));
886
887   return SCM_UNSPECIFIED;
888 }
889
890 /*
891   We can't combine with previous function, since check concave and
892   slope damping comes first.
893
894   TODO: we should use the concaveness to control the amount of damping
895   applied.
896 */
897 MAKE_SCHEME_CALLBACK (Beam, shift_region_to_valid, 1);
898 SCM
899 Beam::shift_region_to_valid (SCM grob)
900 {
901   Grob *me = unsmob_grob (grob);
902   /*
903     Code dup.
904   */
905   Array<Real> x_posns;
906   extract_grob_set (me, "stems", stems);
907   Grob *commonx = common_refpoint_of_array (stems, me, X_AXIS);
908   Grob *commony = common_refpoint_of_array (stems, me, Y_AXIS);
909
910   Grob *fvs = first_visible_stem (me);
911
912   if (!fvs)
913     return SCM_UNSPECIFIED;
914
915   Real x0 = fvs->relative_coordinate (commonx, X_AXIS);
916   for (int i = 0; i < stems.size (); i++)
917     {
918       Grob *s = stems[i];
919
920       Real x = s->relative_coordinate (commonx, X_AXIS) - x0;
921       x_posns.push (x);
922     }
923
924   Grob *lvs = last_visible_stem (me);
925   if (!lvs)
926     return SCM_UNSPECIFIED;
927
928   Real dx = lvs->relative_coordinate (commonx, X_AXIS) - x0;
929
930   Drul_array<Real> pos = ly_scm2interval (me->get_property ("positions"));
931
932   scale_drul (&pos, Staff_symbol_referencer::staff_space (me));
933
934   Real dy = pos[RIGHT] - pos[LEFT];
935   Real y = pos[LEFT];
936   Real slope = dx ? (dy / dx) : 0.0;
937
938   /*
939     Shift the positions so that we have a chance of finding good
940     quants (i.e. no short stem failures.)
941   */
942   Interval feasible_left_point;
943   feasible_left_point.set_full ();
944   for (int i = 0; i < stems.size (); i++)
945     {
946       Grob *s = stems[i];
947       if (Stem::is_invisible (s))
948         continue;
949
950       Direction d = Stem::get_direction (s);
951
952       Real left_y
953         = Stem::get_stem_info (s).shortest_y_
954         - slope * x_posns [i];
955
956       /*
957         left_y is now relative to the stem S. We want relative to
958         ourselves, so translate:
959       */
960       left_y
961         += + s->relative_coordinate (commony, Y_AXIS)
962         - me->relative_coordinate (commony, Y_AXIS);
963
964       Interval flp;
965       flp.set_full ();
966       flp[-d] = left_y;
967
968       feasible_left_point.intersect (flp);
969     }
970
971   if (feasible_left_point.is_empty ())
972     warning (_ ("no viable initial configuration found: may not find good beam slope"));
973   else if (!feasible_left_point.contains (y))
974     {
975       const int REGION_SIZE = 2; // UGH UGH
976       if (isinf (feasible_left_point[DOWN]))
977         y = feasible_left_point[UP] - REGION_SIZE;
978       else if (isinf (feasible_left_point[UP]))
979         y = feasible_left_point[DOWN]+ REGION_SIZE;
980       else
981         y = feasible_left_point.center ();
982     }
983
984   pos = Drul_array<Real> (y, (y + dy));
985   scale_drul (&pos, 1 / Staff_symbol_referencer::staff_space (me));
986
987   me->set_property ("positions", ly_interval2scm (pos));
988   return SCM_UNSPECIFIED;
989 }
990
991 /* This neat trick is by Werner Lemberg,
992    damped = tanh (slope)
993    corresponds with some tables in [Wanske] CHECKME */
994 MAKE_SCHEME_CALLBACK (Beam, slope_damping, 1);
995 SCM
996 Beam::slope_damping (SCM smob)
997 {
998   Grob *me = unsmob_grob (smob);
999
1000   if (visible_stem_count (me) <= 1)
1001     return SCM_UNSPECIFIED;
1002
1003   SCM s = me->get_property ("damping");
1004   Real damping = scm_to_double (s);
1005
1006   if (damping)
1007     {
1008       Drul_array<Real> pos = ly_scm2interval (me->get_property ("positions"));
1009       scale_drul (&pos, Staff_symbol_referencer::staff_space (me));
1010
1011       Real dy = pos[RIGHT] - pos[LEFT];
1012
1013       Grob *fvs = first_visible_stem (me);
1014       Grob *lvs = last_visible_stem (me);
1015
1016       Grob *commonx = fvs->common_refpoint (lvs, X_AXIS);
1017
1018       Real dx = last_visible_stem (me)->relative_coordinate (commonx, X_AXIS)
1019         - first_visible_stem (me)->relative_coordinate (commonx, X_AXIS);
1020
1021       Real slope = dy && dx ? dy / dx : 0;
1022
1023       Real concaveness = robust_scm2double (me->get_property ("concaveness"), 0.0);
1024
1025       slope = 0.6 * tanh (slope) / (damping + concaveness);
1026
1027       Real damped_dy = slope * dx;
1028
1029       set_minimum_dy (me, &damped_dy);
1030
1031       pos[LEFT] += (dy - damped_dy) / 2;
1032       pos[RIGHT] -= (dy - damped_dy) / 2;
1033
1034       scale_drul (&pos, 1 / Staff_symbol_referencer::staff_space (me));
1035
1036       me->set_property ("positions", ly_interval2scm (pos));
1037     }
1038   return SCM_UNSPECIFIED;
1039 }
1040
1041 /*
1042   Report slice containing the numbers that are both in (car BEAMING)
1043   and (cdr BEAMING)
1044 */
1045 Slice
1046 where_are_the_whole_beams (SCM beaming)
1047 {
1048   Slice l;
1049
1050   for (SCM s = scm_car (beaming); scm_is_pair (s); s = scm_cdr (s))
1051     {
1052       if (scm_c_memq (scm_car (s), scm_cdr (beaming)) != SCM_BOOL_F)
1053
1054         l.add_point (scm_to_int (scm_car (s)));
1055     }
1056
1057   return l;
1058 }
1059
1060 /* Return the Y position of the stem-end, given the Y-left, Y-right
1061    in POS for stem S.  This Y position is relative to S. */
1062 Real
1063 Beam::calc_stem_y (Grob *me, Grob *s, Grob ** common,
1064                    Real xl, Real xr,
1065                    Drul_array<Real> pos, bool french)
1066 {
1067   Real beam_translation = get_beam_translation (me);
1068
1069   Real r = s->relative_coordinate (common[X_AXIS], X_AXIS) - xl;
1070   Real dy = pos[RIGHT] - pos[LEFT];
1071   Real dx = xr - xl;
1072   Real stem_y_beam0 = (dy && dx
1073                        ? r / dx
1074                        * dy
1075                        : 0) + pos[LEFT];
1076
1077   Direction my_dir = get_grob_direction (s);
1078   SCM beaming = s->get_property ("beaming");
1079
1080   Real stem_y = stem_y_beam0;
1081   if (french)
1082     {
1083       Slice bm = where_are_the_whole_beams (beaming);
1084       if (!bm.is_empty ())
1085         stem_y += beam_translation * bm[-my_dir];
1086     }
1087   else
1088     {
1089       Slice bm = Stem::beam_multiplicity (s);
1090       if (!bm.is_empty ())
1091         stem_y += bm[my_dir] * beam_translation;
1092     }
1093
1094   Real id = me->relative_coordinate (common[Y_AXIS], Y_AXIS)
1095     - s->relative_coordinate (common[Y_AXIS], Y_AXIS);
1096
1097   return stem_y + id;
1098 }
1099
1100 /*
1101   Hmm.  At this time, beam position and slope are determined.  Maybe,
1102   stem directions and length should set to relative to the chord's
1103   position of the beam.  */
1104 void
1105 Beam::set_stem_lengths (Grob *me)
1106 {
1107   extract_grob_set (me, "stems", stems);
1108   if (!stems.size ())
1109     return;
1110
1111   Grob *common[2];
1112   for (int a = 2; a--;)
1113     common[a] = common_refpoint_of_array (stems, me, Axis (a));
1114
1115   Drul_array<Real> pos = ly_scm2realdrul (me->get_property ("positions"));
1116   Real staff_space = Staff_symbol_referencer::staff_space (me);
1117   scale_drul (&pos, staff_space);
1118
1119   bool gap = false;
1120   Real thick = 0.0;
1121   if (scm_is_number (me->get_property ("gap-count"))
1122       &&scm_to_int (me->get_property ("gap-count")))
1123     {
1124       gap = true;
1125       thick = get_thickness (me);
1126     }
1127
1128   // ugh -> use commonx
1129   Grob *fvs = first_visible_stem (me);
1130   Grob *lvs = last_visible_stem (me);
1131
1132   Real xl = fvs ? fvs->relative_coordinate (common[X_AXIS], X_AXIS) : 0.0;
1133   Real xr = lvs ? lvs->relative_coordinate (common[X_AXIS], X_AXIS) : 0.0;
1134
1135   for (int i = 0; i < stems.size (); i++)
1136     {
1137       Grob *s = stems[i];
1138       if (Stem::is_invisible (s))
1139         continue;
1140
1141       bool french = to_boolean (s->get_property ("french-beaming"));
1142       Real stem_y = calc_stem_y (me, s, common,
1143                                  xl, xr,
1144                                  pos, french && s != lvs && s!= fvs);
1145
1146       /*
1147         Make the stems go up to the end of the beam. This doesn't matter
1148         for normal beams, but for tremolo beams it looks silly otherwise.
1149       */
1150       if (gap)
1151         stem_y += thick * 0.5 * get_grob_direction (s);
1152
1153       Stem::set_stemend (s, 2 * stem_y / staff_space);
1154     }
1155 }
1156
1157 void
1158 Beam::set_beaming (Grob *me, Beaming_info_list *beaming)
1159 {
1160   extract_grob_set (me, "stems", stems);
1161
1162   Direction d = LEFT;
1163   for (int i = 0; i < stems.size (); i++)
1164     {
1165       /*
1166         Don't overwrite user settings.
1167       */
1168
1169       do
1170         {
1171           /* Don't set beaming for outside of outer stems */
1172           if ((d == LEFT && i == 0)
1173               || (d == RIGHT && i == stems.size () -1))
1174             continue;
1175
1176           Grob *stem = stems[i];
1177           SCM beaming_prop = stem->get_property ("beaming");
1178           if (beaming_prop == SCM_EOL
1179               || index_get_cell (beaming_prop, d) == SCM_EOL)
1180             {
1181               int b = beaming->infos_.elem (i).beams_i_drul_[d];
1182               if (i > 0
1183                   && i < stems.size () -1
1184                   && Stem::is_invisible (stem))
1185                 b = min (b, beaming->infos_.elem (i).beams_i_drul_[-d]);
1186
1187               Stem::set_beaming (stem, b, d);
1188             }
1189         }
1190       while (flip (&d) != LEFT);
1191     }
1192 }
1193
1194 int
1195 Beam::forced_stem_count (Grob *me)
1196 {
1197   extract_grob_set (me, "stems", stems);
1198
1199   int f = 0;
1200   for (int i = 0; i < stems.size (); i++)
1201     {
1202       Grob *s = stems[i];
1203
1204       if (Stem::is_invisible (s))
1205         continue;
1206
1207       /* I can imagine counting those boundaries as a half forced stem,
1208          but let's count them full for now. */
1209       if (abs (Stem::chord_start_y (s)) > 0.1
1210           && (Stem::get_direction (s) != Stem::get_default_dir (s)))
1211         f++;
1212     }
1213   return f;
1214 }
1215
1216 int
1217 Beam::visible_stem_count (Grob *me)
1218 {
1219   extract_grob_set (me, "stems", stems);
1220   int c = 0;
1221   for (int i = stems.size (); i--;)
1222     {
1223       if (!Stem::is_invisible (stems[i]))
1224         c++;
1225     }
1226   return c;
1227 }
1228
1229 Grob *
1230 Beam::first_visible_stem (Grob *me)
1231 {
1232   extract_grob_set (me, "stems", stems);
1233
1234   for (int i = 0; i < stems.size (); i++)
1235     {
1236       if (!Stem::is_invisible (stems[i]))
1237         return stems[i];
1238     }
1239   return 0;
1240 }
1241
1242 Grob *
1243 Beam::last_visible_stem (Grob *me)
1244 {
1245   extract_grob_set (me, "stems", stems);
1246
1247   for (int i = stems.size (); i--;)
1248     {
1249       if (!Stem::is_invisible (stems[i]))
1250         return stems[i];
1251     }
1252   return 0;
1253 }
1254
1255 /*
1256   [TODO]
1257
1258   handle rest under beam (do_post: beams are calculated now)
1259   what about combination of collisions and rest under beam.
1260
1261   Should lookup
1262
1263   rest -> stem -> beam -> interpolate_y_position ()
1264 */
1265 MAKE_SCHEME_CALLBACK (Beam, rest_collision_callback, 2);
1266 SCM
1267 Beam::rest_collision_callback (SCM element_smob, SCM axis)
1268 {
1269   Grob *rest = unsmob_grob (element_smob);
1270   (void) axis;
1271
1272   if (scm_is_number (rest->get_property ("staff-position")))
1273     return scm_from_int (0);
1274
1275   assert (scm_to_int (axis) == Y_AXIS);
1276
1277   Grob *st = unsmob_grob (rest->get_object ("stem"));
1278   Grob *stem = st;
1279   if (!stem)
1280     return scm_from_double (0.0);
1281   Grob *beam = unsmob_grob (stem->get_object ("beam"));
1282   if (!beam
1283       || !Beam::has_interface (beam)
1284       || !Beam::visible_stem_count (beam))
1285     return scm_from_double (0.0);
1286
1287   Drul_array<Real> pos (0, 0);
1288   SCM s = beam->get_property ("positions");
1289   if (scm_is_pair (s) && scm_is_number (scm_car (s)))
1290     pos = ly_scm2interval (s);
1291   else
1292     {
1293       /*
1294         UGH. TODO: fix dependency tracking.
1295       */
1296       position_beam (beam);
1297       pos = ly_scm2interval (beam->get_property ("positions"));
1298     }
1299
1300   Real staff_space = Staff_symbol_referencer::staff_space (rest);
1301
1302   scale_drul (&pos, staff_space);
1303
1304   Real dy = pos[RIGHT] - pos[LEFT];
1305
1306   // ugh -> use commonx
1307   Real x0 = first_visible_stem (beam)->relative_coordinate (0, X_AXIS);
1308   Real dx = last_visible_stem (beam)->relative_coordinate (0, X_AXIS) - x0;
1309   Real slope = dy && dx ? dy / dx : 0;
1310
1311   Direction d = Stem::get_direction (stem);
1312   Real stem_y = pos[LEFT] + (stem->relative_coordinate (0, X_AXIS) - x0) * slope;
1313
1314   Real beam_translation = get_beam_translation (beam);
1315   Real beam_thickness = Beam::get_thickness (beam);
1316
1317   /*
1318     TODO: this is not strictly correct for 16th knee beams.
1319   */
1320   int beam_count
1321     = Stem::beam_multiplicity (stem).length () + 1;
1322
1323   Real height_of_my_beams = beam_thickness / 2
1324     + (beam_count - 1) * beam_translation;
1325   Real beam_y = stem_y - d * height_of_my_beams;
1326
1327   Grob *common_y = rest->common_refpoint (beam, Y_AXIS);
1328
1329   Real rest_dim = rest->extent (common_y, Y_AXIS)[d];
1330   Real minimum_distance
1331     = + staff_space * (robust_scm2double (stem->get_property ("stemlet-length"), 0.0)
1332                        + robust_scm2double (rest->get_property ("minimum-distance"), 0.0));
1333
1334   Real shift = d * min (((beam_y - d * minimum_distance) - rest_dim) * d, 0.0);
1335
1336   shift /= staff_space;
1337   Real rad = Staff_symbol_referencer::line_count (rest) * staff_space / 2;
1338
1339   /* Always move discretely by half spaces */
1340   shift = ceil (fabs (shift * 2.0)) / 2.0 * sign (shift);
1341
1342   /* Inside staff, move by whole spaces*/
1343   if ((rest->extent (common_y, Y_AXIS)[d] + staff_space * shift) * d
1344       < rad
1345       || (rest->extent (common_y, Y_AXIS)[-d] + staff_space * shift) * -d
1346       < rad)
1347     shift = ceil (fabs (shift)) * sign (shift);
1348
1349   return scm_from_double (staff_space * shift);
1350 }
1351
1352 bool
1353 Beam::is_knee (Grob *me)
1354 {
1355   SCM k = me->get_property ("knee");
1356   if (scm_is_bool (k))
1357     return ly_scm2bool (k);
1358
1359   bool knee = false;
1360   int d = 0;
1361   extract_grob_set (me, "stems", stems);
1362   for (int i = stems.size (); i--;)
1363     {
1364       Direction dir = get_grob_direction (stems[i]);
1365       if (d && d != dir)
1366         {
1367           knee = true;
1368           break;
1369         }
1370       d = dir;
1371     }
1372
1373   me->set_property ("knee", ly_bool2scm (knee));
1374
1375   return knee;
1376 }
1377
1378 int
1379 Beam::get_direction_beam_count (Grob *me, Direction d)
1380 {
1381   extract_grob_set (me, "stems", stems);
1382   int bc = 0;
1383
1384   for (int i = stems.size (); i--;)
1385     {
1386       /*
1387         Should we take invisible stems into account?
1388       */
1389       if (Stem::get_direction (stems[i]) == d)
1390         bc = max (bc, (Stem::beam_multiplicity (stems[i]).length () + 1));
1391     }
1392
1393   return bc;
1394 }
1395
1396 ADD_INTERFACE (Beam, "beam-interface",
1397                "A beam. \n\n"
1398                "The @code{thickness} property is the weight of beams, and is measured "
1399                "in  staffspace",
1400                "knee positioning-done position-callbacks "
1401                "concaveness dir-function quant-score auto-knee-gap gap "
1402                "gap-count chord-tremolo beamed-stem-shorten shorten least-squares-dy "
1403                "details damping inspect-quants flag-width-function "
1404                "neutral-direction positions space-function break-overshoot "
1405                "thickness");
1406