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