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