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