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