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