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