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