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