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