]> git.donarmstrong.com Git - lilypond.git/blob - lily/beam.cc
patch::: 1.5.40.jcn1
[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--2002 Han-Wen Nienhuys <hanwen@cs.uu.nl>
7     Jan Nieuwenhuizen <janneke@gnu.org>
8
9 */
10
11 /*
12   [TODO]
13
14   * different left/right quanting: slope, multiplicity
15   
16   * Fix TODO
17   
18   * Junk stem_info.
19   
20   * Remove #'direction from beam.  A beam has no direction per se.
21     It may only set directions for stems.
22
23   * Rewrite stem_beams.
24     
25   */
26
27
28 #include <math.h> // tanh.
29
30 #include "molecule.hh" 
31 #include "directional-element-interface.hh"
32 #include "beaming.hh"
33 #include "beam.hh"
34 #include "misc.hh"
35 #include "least-squares.hh"
36 #include "stem.hh"
37 #include "paper-def.hh"
38 #include "lookup.hh"
39 #include "group-interface.hh"
40 #include "staff-symbol-referencer.hh"
41 #include "item.hh"
42 #include "spanner.hh"
43 #include "warn.hh"
44
45 void
46 Beam::add_stem (Grob *me, Grob *s)
47 {
48   Pointer_group_interface::add_grob (me, ly_symbol2scm ("stems"), s);
49   
50   s->add_dependency (me);
51
52   assert (!Stem::beam_l (s));
53   s->set_grob_property ("beam", me->self_scm ());
54
55   add_bound_item (dynamic_cast<Spanner*> (me), dynamic_cast<Item*> (s));
56 }
57
58 int
59 Beam::get_multiplicity (Grob *me) 
60 {
61   int m = 0;
62   for (SCM s = me->get_grob_property ("stems"); gh_pair_p (s); s = ly_cdr (s))
63     {
64       Grob *sc = unsmob_grob (ly_car (s));
65
66       if (Stem::has_interface (sc))
67         m = m >? Stem::beam_count (sc, LEFT) >? Stem::beam_count (sc, RIGHT);
68     }
69   return m;
70 }
71
72 /* After pre-processing all directions should be set.
73    Several post-processing routines (stem, slur, script) need stem/beam
74    direction.
75    Currenly, this means that beam has set all stem's directions.
76    [Alternatively, stems could set its own directions, according to
77    their beam, during 'final-pre-processing'.] */
78 MAKE_SCHEME_CALLBACK (Beam, before_line_breaking, 1);
79 SCM
80 Beam::before_line_breaking (SCM smob)
81 {
82   Grob *me =  unsmob_grob (smob);
83
84   /* Beams with less than 2 two stems don't make much sense, but could happen
85      when you do
86      
87      [r8 c8 r8].
88      
89     For a beam that  only has one stem, we try to do some disappearance magic:
90     we revert the flag, and move on to The Eternal Engraving Fields. */
91
92   int count = visible_stem_count (me);
93   if (count < 2)
94     {
95       me->warning (_ ("beam has less than two visible stems"));
96
97       SCM stems = me->get_grob_property ("stems");
98       if (scm_ilength (stems) == 1)
99         {
100           me->warning (_ ("Beam has less than two stems. Removing beam."));
101
102           unsmob_grob (gh_car (stems))->remove_grob_property ("beam");
103           me->suicide ();
104
105           return SCM_UNSPECIFIED;
106         }
107       else if (scm_ilength (stems) == 0)
108         {
109           me->suicide ();
110           return SCM_UNSPECIFIED;         
111         }
112     }
113   if (count >= 1)
114     {
115       if (!Directional_element_interface::get (me))
116         Directional_element_interface::set (me, get_default_dir (me));
117       
118       consider_auto_knees (me);
119       set_stem_directions (me);
120       set_stem_shorten (me);
121     }
122   return SCM_EOL;
123 }
124
125 Direction
126 Beam::get_default_dir (Grob *me) 
127 {
128   Drul_array<int> total;
129   total[UP]  = total[DOWN] = 0;
130   Drul_array<int> count; 
131   count[UP]  = count[DOWN] = 0;
132   Direction d = DOWN;
133
134   Link_array<Item> stems=
135         Pointer_group_interface__extract_grobs (me, (Item*)0, "stems");
136
137   for (int i=0; i <stems.size (); i++)
138     do {
139       Grob *s = stems[i];
140       Direction sd = Directional_element_interface::get (s);
141       int current = sd  ? (1 + d * sd)/2
142         : Stem::get_center_distance (s, (Direction)-d);
143
144       if (current)
145         {
146           total[d] += current;
147           count[d] ++;
148         }
149
150     } while (flip (&d) != DOWN);
151   
152   SCM func = me->get_grob_property ("dir-function");
153   SCM s = gh_call2 (func,
154                     gh_cons (gh_int2scm (count[UP]),
155                              gh_int2scm (count[DOWN])),
156                     gh_cons (gh_int2scm (total[UP]),
157                              gh_int2scm (total[DOWN])));
158
159   if (gh_number_p (s) && gh_scm2int (s))
160     return to_dir (s);
161   
162   /* If dir is not determined: get default */
163   return to_dir (me->get_grob_property ("neutral-direction"));
164 }
165
166
167 /* Set all stems with non-forced direction to beam direction.
168    Urg: non-forced should become `without/with unforced' direction,
169    once stem gets cleaned-up. */
170 void
171 Beam::set_stem_directions (Grob *me)
172 {
173   Link_array<Item> stems
174     =Pointer_group_interface__extract_grobs (me, (Item*) 0, "stems");
175   Direction d = Directional_element_interface::get (me);
176   
177   for (int i=0; i <stems.size (); i++)
178     {
179       Grob *s = stems[i];
180       SCM force = s->remove_grob_property ("dir-forced");
181       if (!gh_boolean_p (force) || !gh_scm2bool (force))
182         Directional_element_interface::set (s, d);
183     }
184
185
186 /* Simplistic auto-knees; only consider vertical gap between two
187    adjacent chords.
188
189   `Forced' stem directions are ignored.  If you don't want auto-knees,
190   don't set, or unset auto-knee-gap. */
191 void
192 Beam::consider_auto_knees (Grob *me)
193 {
194   SCM scm = me->get_grob_property ("auto-knee-gap");
195
196   if (gh_number_p (scm))
197     {
198       bool knee_b = false;
199       Real knee_y = 0;
200       Real staff_space = Staff_symbol_referencer::staff_space (me);
201       Real gap = gh_scm2double (scm) / staff_space;
202
203       Direction d = Directional_element_interface::get (me);
204       Link_array<Item> stems=
205         Pointer_group_interface__extract_grobs (me, (Item*)0, "stems");
206       
207       Grob *common = me->common_refpoint (stems[0], Y_AXIS);
208       for (int i=1; i < stems.size (); i++)
209         if (!Stem::invisible_b (stems[i]))
210           common = common->common_refpoint (stems[i], Y_AXIS);
211
212       int l = 0;
213       for (int i=1; i < stems.size (); i++)
214         {
215           if (!Stem::invisible_b (stems[i-1]))
216             l = i - 1;
217           if (Stem::invisible_b (stems[l]))
218             continue;
219           if (Stem::invisible_b (stems[i]))
220             continue;
221           
222           Real left = Stem::extremal_heads (stems[l])[d]
223             ->relative_coordinate (common, Y_AXIS);
224           Real right = Stem::extremal_heads (stems[i])[-d]
225             ->relative_coordinate (common, Y_AXIS);
226
227           Real dy = right - left;
228
229           if (abs (dy) >= gap)
230             {
231               knee_y = (right + left) / 2;
232               knee_b = true;
233               break;
234             }
235         }
236       
237       if (knee_b)
238         {
239           for (int i=0; i < stems.size (); i++)
240             {
241               if (Stem::invisible_b (stems[i]))
242                 continue;
243               Item *s = stems[i];         
244               Real y = Stem::extremal_heads (stems[i])[d]
245                 ->relative_coordinate (common, Y_AXIS);
246
247               Directional_element_interface::set (s, y < knee_y ? UP : DOWN);
248               s->set_grob_property ("dir-forced", SCM_BOOL_T);
249             }
250         }
251     }
252 }
253
254 /* Set stem's shorten property if unset.
255    TODO:
256    take some y-position (chord/beam/nearest?) into account
257    scmify forced-fraction */
258 void
259 Beam::set_stem_shorten (Grob *m)
260 {
261   Spanner*me = dynamic_cast<Spanner*> (m);
262
263   Real forced_fraction = forced_stem_count (me) / visible_stem_count (me);
264
265   int multiplicity = get_multiplicity (me);
266
267   SCM shorten = me->get_grob_property ("beamed-stem-shorten");
268   if (shorten == SCM_EOL)
269     return;
270
271   int sz = scm_ilength (shorten);
272   
273   Real staff_space = Staff_symbol_referencer::staff_space (me);
274   SCM shorten_elt = scm_list_ref (shorten,
275                                   gh_int2scm (multiplicity <? (sz - 1)));
276   Real shorten_f = gh_scm2double (shorten_elt) * staff_space;
277
278   /* your similar cute comment here */
279   shorten_f *= forced_fraction;
280   
281   me->set_grob_property ("shorten", gh_double2scm (shorten_f));
282 }
283
284 /*  Call list of y-dy-callbacks, that handle setting of
285     grob-properties y, dy.
286     
287     User may set grob-properties: y-position-hs and height-hs
288     (to be fixed) that override the calculated y and dy.
289     
290     Because y and dy cannot be calculated and quanted separately, we
291     always calculate both, then check for user override. */
292 MAKE_SCHEME_CALLBACK (Beam, after_line_breaking, 1);
293 SCM
294 Beam::after_line_breaking (SCM smob)
295 {
296   Grob *me = unsmob_grob (smob);
297   
298   /* Copy to mutable list. */
299   SCM s = ly_deep_copy (me->get_grob_property ("positions"));
300   me->set_grob_property ("positions", s);
301
302   if (ly_car (s) != SCM_BOOL_F)
303     return SCM_UNSPECIFIED;
304
305   SCM callbacks = me->get_grob_property ("position-callbacks");
306   for (SCM i = callbacks; gh_pair_p (i); i = ly_cdr (i))
307     gh_call1 (ly_car (i), smob);
308
309   return SCM_UNSPECIFIED;
310 }
311
312
313 MAKE_SCHEME_CALLBACK (Beam, least_squares, 1);
314 SCM
315 Beam::least_squares (SCM smob)
316 {
317   Grob *me = unsmob_grob (smob);
318
319   int count = visible_stem_count (me);
320   Interval pos (0, 0);
321   
322   if (count <= 1)
323     {
324       me->set_grob_property ("positions", ly_interval2scm (pos));
325       return SCM_UNSPECIFIED;
326     }
327   
328   Direction dir = Directional_element_interface::get (me);
329
330   Interval ideal (Stem::calc_stem_info (first_visible_stem (me)).idealy_f_,
331                   Stem::calc_stem_info (last_visible_stem (me)).idealy_f_);
332   if (!ideal.delta ())
333     {
334       Interval chord (Stem::chord_start_f (first_visible_stem (me)),
335                       Stem::chord_start_f (last_visible_stem (me)));
336       
337       /* Make simple beam on middle line have small tilt */
338       if (!ideal[LEFT] && chord.delta () && count == 2)
339         {
340           Direction d = (Direction)(sign (chord.delta ()) * dir);
341           pos[d] = gh_scm2double (me->get_grob_property ("thickness")) / 2
342             * dir;
343           pos[-d] = - pos[d];
344         }
345       else
346         pos = ideal;
347     }
348   else
349     {
350       Array<Offset> ideals;
351
352       // ugh -> use commonx
353       Real x0 = first_visible_stem (me)->relative_coordinate (0, X_AXIS);
354       Link_array<Item> stems=
355         Pointer_group_interface__extract_grobs (me, (Item*)0, "stems");
356
357       for (int i=0; i < stems.size (); i++)
358         {
359           Item* s = stems[i];
360           if (Stem::invisible_b (s))
361             continue;
362           ideals.push (Offset (s->relative_coordinate (0, X_AXIS) - x0,
363                                Stem::calc_stem_info (s).idealy_f_));
364         }
365       Real y; 
366       Real dydx;
367       minimise_least_squares (&dydx, &y, ideals);
368
369       Real dx = last_visible_stem (me)->relative_coordinate (0, X_AXIS) - x0;
370       Real dy = dydx * dx;
371       pos = Interval (y*dir, (y+dy) * dir);
372     }
373
374   me->set_grob_property ("positions", ly_interval2scm (pos));
375   return SCM_UNSPECIFIED;
376 }
377
378 MAKE_SCHEME_CALLBACK (Beam, check_concave, 1);
379 SCM
380 Beam::check_concave (SCM smob)
381 {
382   Grob *me = unsmob_grob (smob);
383
384   Link_array<Item> stems = 
385     Pointer_group_interface__extract_grobs (me, (Item*) 0, "stems");
386
387   for (int i = 0; i < stems.size ();)
388     {
389       if (Stem::invisible_b (stems[i]))
390         stems.del (i);
391       else
392         i++;
393     }
394   
395   if (stems.size () < 3)
396     return SCM_UNSPECIFIED;
397
398   /* Concaveness try #2: Sum distances of inner noteheads that
399      fall outside the interval of the two outer noteheads */
400   Real concave = 0;
401   Interval iv (Stem::chord_start_f (stems[0]),
402                Stem::chord_start_f (stems.top ()));
403   
404   if (iv[MAX] < iv[MIN])
405     iv.swap ();
406   
407   for (int i = 1; i < stems.size () - 1; i++)
408     {
409       Real c = 0;
410       Real f = Stem::chord_start_f (stems[i]);
411       if ((c = f - iv[MAX]) > 0)
412         concave += c;
413       else if ((c = f - iv[MIN]) < 0)
414         concave += c;
415     }
416   concave *= Directional_element_interface::get (me);
417       
418   Real concaveness = concave / (stems.size () - 2);
419   /* ugh: this is the a kludge to get input/regression/beam-concave.ly
420      to behave as baerenreiter. */
421   concaveness /= (stems.size () - 2);
422   
423   Real r = gh_scm2double (me->get_grob_property ("concaveness-threshold"));
424
425   /* TODO: some sort of damping iso -> plain horizontal */
426   if (concaveness > r)
427     {
428       Interval pos = ly_scm2interval (me->get_grob_property ("positions"));
429       Real r = pos.linear_combination (0);
430       me->set_grob_property ("positions", ly_interval2scm (Interval (r, r)));
431     }
432
433   return SCM_UNSPECIFIED;
434 }
435
436 /* This neat trick is by Werner Lemberg,
437    damped = tanh (slope)
438    corresponds with some tables in [Wanske] CHECKME */
439 MAKE_SCHEME_CALLBACK (Beam, slope_damping, 1);
440 SCM
441 Beam::slope_damping (SCM smob)
442 {
443   Grob *me = unsmob_grob (smob);
444
445   if (visible_stem_count (me) <= 1)
446     return SCM_UNSPECIFIED;
447
448   SCM s = me->get_grob_property ("damping"); 
449   int damping = gh_scm2int (s);
450
451   if (damping)
452     {
453       Interval pos = ly_scm2interval (me->get_grob_property ("positions"));
454       Real dy = pos.delta ();
455       
456       // ugh -> use commonx
457       Real dx = last_visible_stem (me)->relative_coordinate (0, X_AXIS)
458         - first_visible_stem (me)->relative_coordinate (0, X_AXIS);
459       Real dydx = dy && dx ? dy/dx : 0;
460       dydx = 0.6 * tanh (dydx) / damping;
461
462       Real damped_dy = dydx * dx;
463       pos[LEFT] += (dy - damped_dy) / 2;
464       pos[RIGHT] -= (dy - damped_dy) / 2;
465       
466       me->set_grob_property ("positions", ly_interval2scm (pos));
467     }
468     return SCM_UNSPECIFIED;
469 }
470
471
472 /* Prevent interference from stafflines. */
473 Interval
474 Beam::quantise_interval (Grob *me, Interval pos, Direction quant_dir)
475 {
476   int multiplicity = get_multiplicity (me);
477
478   Real staff_space = Staff_symbol_referencer::staff_space (me);
479   Real thick = me->paper_l ()->get_var ("stafflinethickness");
480
481   /* TODO:
482
483      - left and right should be different, depending on direction and
484      multiplicity
485
486      -use different left-position-quant-function,
487      right-position-quant-function for handier slope quanting? */
488   SCM proc = me->get_grob_property ("vertical-position-quant-function");
489   SCM quants = scm_apply (proc,
490                           me->self_scm (),
491                           scm_list_n (gh_int2scm (multiplicity),
492                                       gh_double2scm (1), /* junkme */
493                                       gh_double2scm (thick / staff_space),
494                                       /* HUH? */
495                                       SCM_EOL,
496                                       SCM_UNDEFINED));
497   
498   Array<Real> a;
499   for (SCM i = quants; gh_pair_p (i); i = ly_cdr (i))
500     a.push (gh_scm2double (ly_car (i)));
501   
502   if (a.size () <= 1)
503     return pos;
504
505   Direction dir = Directional_element_interface::get (me);
506   Interval left = quantise_iv (a, pos[LEFT]*dir/staff_space) * staff_space;
507   Interval right = quantise_iv (a, pos[RIGHT]*dir/staff_space) * staff_space;
508   
509   Real dy = pos.delta ();
510   Real ady = abs (dy);
511
512   // quant direction hints disabled for now
513   int q = 0;//(int)quant_dir;
514
515   /* TODO: make smart choice, find best left/right quants pair.
516
517      Slope should never be steeper than least_squares (before damping)
518      (save that value?)
519      Slope should never be reduced to zero.
520    */
521   Interval qpos (0, 20.0 *sign (dy));
522   Direction ldir = LEFT;
523   do
524     {
525       Direction rdir = LEFT;
526       do
527         {
528           Interval i (left[ldir]*dir, right[rdir]*dir);
529           if ((abs (abs (i.delta ()) - ady) <= abs (abs (qpos.delta ()) - ady)
530        && sign (i.delta ()) == sign (pos.delta ())
531        && (!q
532            || (i[LEFT]*q >= pos[LEFT]*q && i[RIGHT]*q >= pos[RIGHT]*q))))
533             qpos = i;
534         }
535       while (flip (&rdir) != LEFT);
536     }
537   while (flip (&ldir) != LEFT);
538   
539   return qpos;
540 }
541
542
543 /* Quantise vertical position (left and right) of beam.
544    Generalisation of [Ross]. */
545 MAKE_SCHEME_CALLBACK (Beam, quantise_position, 1);
546 SCM
547 Beam::quantise_position (SCM smob)
548 {
549   Grob *me = unsmob_grob (smob);
550
551   Interval pos = ly_scm2interval (me->get_grob_property ("positions"));
552   Real y_shift = check_stem_length_f (me, pos);
553   pos += y_shift;
554   pos = quantise_interval (me, pos, CENTER);
555   
556   me->set_grob_property ("positions", ly_interval2scm (pos));
557   set_stem_lengths (me);
558
559   pos = ly_scm2interval (me->get_grob_property ("positions"));
560   
561   y_shift = check_stem_length_f (me, pos);
562
563   Real half_space = Staff_symbol_referencer::staff_space (me) / 2;
564   /* HMMM */
565   if (y_shift > half_space / 4)
566     {
567       pos += y_shift;
568       int quant_dir = 0;
569       /* for significantly lengthened or shortened stems,
570          request quanting the other way.
571          HMMM */
572       if (abs (y_shift) > half_space / 2)
573         quant_dir = sign (y_shift) * Directional_element_interface::get (me);
574       pos = quantise_interval (me, pos, (Direction)quant_dir);
575     }
576   
577   me->set_grob_property ("positions", ly_interval2scm (pos));
578
579   return SCM_UNSPECIFIED;
580 }
581
582 MAKE_SCHEME_CALLBACK (Beam, end_after_line_breaking, 1);
583 SCM
584 Beam::end_after_line_breaking (SCM smob)
585 {
586   Grob *me = unsmob_grob (smob);
587   set_stem_lengths (me);
588   
589   return SCM_UNSPECIFIED;
590 }
591
592 Real
593 Beam::calc_stem_y_f (Grob *me, Item* s, Interval pos)
594 {
595   int beam_multiplicity = get_multiplicity (me);
596   int stem_multiplicity = (Stem::flag_i (s) - 2) >? 0;
597
598   SCM space_proc = me->get_grob_property ("space-function");
599   SCM space = gh_call1 (space_proc, gh_int2scm (beam_multiplicity));
600
601   Real thick = gh_scm2double (me->get_grob_property ("thickness"));
602   Real interbeam_f = gh_scm2double (space);
603
604   // ugh -> use commonx
605   Real x0 = first_visible_stem (me)->relative_coordinate (0, X_AXIS);
606   Real dx = last_visible_stem (me)->relative_coordinate (0, X_AXIS) - x0;
607   Real dy = pos.delta ();
608   Real stem_y = (dy && dx
609                  ? (s->relative_coordinate (0, X_AXIS) - x0) / dx
610                  * dy
611                  : 0) + pos[LEFT];
612
613   /* knee */
614   Direction dir  = Directional_element_interface::get (me);
615   Direction sdir = Directional_element_interface::get (s);
616   
617   /* knee */
618   if (dir!= sdir)
619     {
620       stem_y -= dir * (thick / 2 + (beam_multiplicity - 1) * interbeam_f);
621       
622       // huh, why not for first visible?
623       if (Staff_symbol_referencer::staff_symbol_l (s)
624           != Staff_symbol_referencer::staff_symbol_l (last_visible_stem (me)))
625         stem_y += Directional_element_interface::get (me)
626           * (beam_multiplicity - stem_multiplicity) * interbeam_f;
627     }
628
629   return stem_y;
630 }
631
632 /* Make very sure that we don't have stems that are too short.
633    Try our best not to have stems that are too long (think: knees).
634    
635    Optionally (testing): try to lengthen more, to reach more ideal
636    stem lengths */
637 Real
638 Beam::check_stem_length_f (Grob *me, Interval pos)
639 {
640   Real shorten = 0;
641   Real lengthen = 0;
642   Direction dir = Directional_element_interface::get (me);
643
644   Link_array<Item> stems=
645     Pointer_group_interface__extract_grobs (me, (Item*)0, "stems");
646
647   bool knee = false;
648   int ideal_lengthen_count = 0;
649   Real ideal_lengthen = 0;
650   int ideal_shorten_count = 0;
651   Real ideal_shorten = 0;
652   
653   for (int i=0; i < stems.size (); i++)
654     {
655       Item* s = stems[i];
656       if (Stem::invisible_b (s))
657         continue;
658
659       knee |= dir != Directional_element_interface::get (s);
660
661       Real stem_y = calc_stem_y_f (me, s, pos);
662       
663       stem_y *= dir;
664       Stem_info info = Stem::calc_stem_info (s);
665
666       shorten = shorten <? info.maxy_f_ - stem_y;
667       lengthen = lengthen >? info.miny_f_ - stem_y;
668
669       if (info.idealy_f_ - stem_y > 0)
670         {
671           ideal_lengthen += info.idealy_f_ - stem_y;
672           ideal_lengthen_count++;
673         }
674       else if (info.idealy_f_ - stem_y < 0)
675         {
676           ideal_shorten += info.idealy_f_ - stem_y;
677           ideal_shorten_count++;
678         }
679     }
680   
681   if (lengthen && shorten)
682     me->warning (_ ("weird beam vertical offset"));
683
684   if (ideal_lengthen_count)
685     lengthen = (ideal_lengthen / ideal_lengthen_count) >? lengthen;
686   if (knee && ideal_shorten_count)
687     shorten = (ideal_shorten / ideal_shorten_count) <? shorten;
688
689   if (lengthen && shorten)
690     return dir * (lengthen + shorten);
691     
692   return dir * (shorten ? shorten : lengthen);
693 }
694
695 /*
696   Hmm.  At this time, beam position and slope are determined.  Maybe,
697   stem directions and length should set to relative to the chord's
698   position of the beam.  */
699 void
700 Beam::set_stem_lengths (Grob *me)
701 {
702   Link_array<Item> stems=
703     Pointer_group_interface__extract_grobs (me, (Item*)0, "stems");
704
705   if (stems.size () <= 1)
706     return;
707   
708   Grob *common = me->common_refpoint (stems[0], Y_AXIS);
709   for (int i=1; i < stems.size (); i++)
710     if (!Stem::invisible_b (stems[i]))
711       common = common->common_refpoint (stems[i], Y_AXIS);
712
713   Direction dir = Directional_element_interface::get (me);
714   Interval pos = ly_scm2interval (me->get_grob_property ("positions"));
715   Real staff_space = Staff_symbol_referencer::staff_space (me);
716   Real thick = gh_scm2double (me->get_grob_property ("thickness"));
717   bool ps_testing = to_boolean (ly_symbol2scm ("ps-testing"));
718   for (int i=0; i < stems.size (); i++)
719     {
720       Item* s = stems[i];
721       if (Stem::invisible_b (s))
722         continue;
723
724       Real stem_y = calc_stem_y_f (me, s, pos);
725
726       // doesn't play well with dvips
727       if (ps_testing)
728         if (Stem::get_direction (s) == dir)
729           stem_y += Stem::get_direction (s) * thick / 2;
730       
731       /* caution: stem measures in staff-positions */
732       Real id = me->relative_coordinate (common, Y_AXIS)
733         - stems[i]->relative_coordinate (common, Y_AXIS);
734       Stem::set_stemend (s, (stem_y + id) / staff_space * 2);
735     }
736 }
737
738 void
739 Beam::set_beaming (Grob *me, Beaming_info_list *beaming)
740 {
741   Link_array<Grob> stems=
742     Pointer_group_interface__extract_grobs (me, (Grob *)0, "stems");
743   
744   Direction d = LEFT;
745   for (int i=0; i  < stems.size (); i++)
746     {
747       do
748         {
749           /* Don't overwrite user override (?) */
750           if (Stem::beam_count (stems[i], d) == -1
751               /* Don't set beaming for outside of outer stems */
752               && ! (d == LEFT && i == 0)
753               && ! (d == RIGHT && i == stems.size () -1))
754             {
755               int b = beaming->infos_.elem (i).beams_i_drul_[d];
756               Stem::set_beaming (stems[i], b, d);
757             }
758         }
759       while (flip (&d) != LEFT);
760     }
761 }
762
763
764
765 /*
766   beams to go with one stem.
767
768   FIXME: clean me up.
769   */
770 Molecule
771 Beam::stem_beams (Grob *me, Item *here, Item *next, Item *prev, Real dydx)
772 {
773   // ugh -> use commonx
774   if ((next
775        && !(next->relative_coordinate (0, X_AXIS)
776             > here->relative_coordinate (0, X_AXIS)))
777       || (prev
778           && !(prev->relative_coordinate (0, X_AXIS)
779                < here->relative_coordinate (0, X_AXIS))))
780     programming_error ("Beams are not left-to-right");
781
782   int multiplicity = get_multiplicity (me);
783
784   SCM space_proc = me->get_grob_property ("space-function");
785   SCM space = gh_call1 (space_proc, gh_int2scm (multiplicity));
786
787   Real thick = gh_scm2double (me->get_grob_property ("thickness"));
788   Real interbeam_f = gh_scm2double (space);
789     
790   Real bdy = interbeam_f;
791   
792   Molecule leftbeams;
793   Molecule rightbeams;
794
795   Real nw_f;
796   if (!Stem::first_head (here))
797     nw_f = 0;
798   else {
799     int t = Stem::type_i (here); 
800
801     SCM proc = me->get_grob_property ("flag-width-function");
802     SCM result = gh_call1 (proc, gh_int2scm (t));
803     nw_f = gh_scm2double (result);
804   }
805
806
807   Direction dir = Directional_element_interface::get (me);
808
809   /* [Tremolo] beams on whole notes may not have direction set? */
810  if (dir == CENTER)
811     dir = Directional_element_interface::get (here);
812
813
814   /* half beams extending to the left. */
815   if (prev)
816     {
817       int lhalfs= lhalfs = Stem::beam_count (here, LEFT)
818         - Stem::beam_count (prev, RIGHT);
819       int lwholebeams= Stem::beam_count (here, LEFT)
820         <? Stem::beam_count (prev, RIGHT);
821       
822       /* Half beam should be one note-width,
823          but let's make sure two half-beams never touch */
824
825       // FIXME: TODO (check) stem width / sloped beams
826       Real w = here->relative_coordinate (0, X_AXIS)
827         - prev->relative_coordinate (0, X_AXIS);
828       Real stem_w = gh_scm2double (prev->get_grob_property ("thickness"))
829         // URG
830         * me->paper_l ()->get_var ("stafflinethickness");
831
832       w = w/2 <? nw_f;
833       Molecule a;
834       if (lhalfs)               // generates warnings if not
835         a =  Lookup::beam (dydx, w + stem_w, thick);
836       a.translate (Offset (-w, -w * dydx));
837       a.translate_axis (-stem_w/2, X_AXIS);
838       for (int j = 0; j  < lhalfs; j++)
839         {
840           Molecule b (a);
841           b.translate_axis (-dir * bdy * (lwholebeams+j), Y_AXIS);
842           leftbeams.add_molecule (b);
843         }
844     }
845
846   if (next)
847     {
848       int rhalfs  = Stem::beam_count (here, RIGHT)
849         - Stem::beam_count (next, LEFT);
850       int rwholebeams= Stem::beam_count (here, RIGHT)
851         <? Stem::beam_count (next, LEFT);
852
853       Real w = next->relative_coordinate (0, X_AXIS)
854         - here->relative_coordinate (0, X_AXIS);
855
856       Real stem_w = gh_scm2double (next->get_grob_property ("thickness"))
857         // URG
858         * me->paper_l ()->get_var ("stafflinethickness");
859
860       Molecule a = Lookup::beam (dydx, w + stem_w, thick);
861       a.translate_axis (- stem_w/2, X_AXIS);
862       int j = 0;
863       Real gap_f = 0;
864       
865       SCM gap = me->get_grob_property ("gap");
866       if (gh_number_p (gap))
867         {
868           int gap_i = gh_scm2int ((gap));
869           int nogap = rwholebeams - gap_i;
870           
871           for (; j  < nogap; j++)
872             {
873               Molecule b (a);
874               b.translate_axis (-dir  * bdy * j, Y_AXIS);
875               rightbeams.add_molecule (b);
876             }
877           if (Stem::invisible_b (here))
878             gap_f = nw_f;
879           else
880             gap_f = nw_f / 2;
881           w -= 2 * gap_f;
882           a = Lookup::beam (dydx, w + stem_w, thick);
883         }
884
885       for (; j  < rwholebeams; j++)
886         {
887           Molecule b (a);
888           Real tx = 0;
889           if (Stem::invisible_b (here))
890             // ugh, see chord-tremolo.ly
891             tx = (-dir + 1) / 2 * nw_f * 1.5 + gap_f/4;
892           else
893             tx = gap_f;
894           b.translate (Offset (tx, -dir * bdy * j));
895           rightbeams.add_molecule (b);
896         }
897
898       w = w/2 <? nw_f;
899       if (rhalfs)
900         a = Lookup::beam (dydx, w, thick);
901
902       for (; j  < rwholebeams + rhalfs; j++)
903         {
904           Molecule b (a);
905           b.translate_axis (- dir * bdy * j, Y_AXIS);
906           rightbeams.add_molecule (b);
907         }
908
909     }
910   leftbeams.add_molecule (rightbeams);
911
912   /* Does beam quanting think  of the asymetry of beams? 
913      Refpoint is on bottom of symbol. (FIXTHAT) --hwn. */
914   return leftbeams;
915 }
916
917 MAKE_SCHEME_CALLBACK (Beam, brew_molecule, 1);
918 SCM
919 Beam::brew_molecule (SCM smob)
920 {
921   Grob *me =unsmob_grob (smob);
922
923   Molecule mol;
924   if (!gh_pair_p (me->get_grob_property ("stems")))
925     return SCM_EOL;
926   Real x0, dx;
927   Link_array<Item>stems = 
928     Pointer_group_interface__extract_grobs (me, (Item*) 0, "stems");  
929   if (visible_stem_count (me))
930     {
931       // ugh -> use commonx
932       x0 = first_visible_stem (me)->relative_coordinate (0, X_AXIS);
933       dx = last_visible_stem (me)->relative_coordinate (0, X_AXIS) - x0;
934     }
935   else
936     {
937       x0 = stems[0]->relative_coordinate (0, X_AXIS);
938       dx = stems.top ()->relative_coordinate (0, X_AXIS) - x0;
939     }
940
941   Interval pos = ly_scm2interval (me->get_grob_property ("positions"));
942   Real dy = pos.delta ();
943   Real dydx = dy && dx ? dy/dx : 0;
944
945   for (int i=0; i < stems.size (); i++)
946     {
947       Item *item = stems[i];
948       Item *prev = (i > 0)? stems[i-1] : 0;
949       Item *next = (i < stems.size ()-1) ? stems[i+1] :0;
950
951       Molecule sb = stem_beams (me, item, next, prev, dydx);
952       Real x = item->relative_coordinate (0, X_AXIS) - x0;
953       sb.translate (Offset (x, x * dydx + pos[LEFT]));
954       mol.add_molecule (sb);
955     }
956   
957   mol.translate_axis (x0 
958                       - dynamic_cast<Spanner*> (me)
959                       ->get_bound (LEFT)->relative_coordinate (0, X_AXIS),
960                       X_AXIS);
961
962   return mol.smobbed_copy ();
963 }
964
965 int
966 Beam::forced_stem_count (Grob *me) 
967 {
968   Link_array<Item>stems = 
969     Pointer_group_interface__extract_grobs (me, (Item*) 0, "stems");
970   int f = 0;
971   for (int i=0; i < stems.size (); i++)
972     {
973       Item *s = stems[i];
974
975       if (Stem::invisible_b (s))
976         continue;
977
978       if (((int)Stem::chord_start_f (s)) 
979         && (Stem::get_direction (s) != Stem::get_default_dir (s)))
980         f++;
981     }
982   return f;
983 }
984
985
986
987
988 /* TODO:
989    use filter and standard list functions.
990  */
991 int
992 Beam::visible_stem_count (Grob *me) 
993 {
994   Link_array<Item>stems = 
995     Pointer_group_interface__extract_grobs (me, (Item*) 0, "stems");
996   int c = 0;
997   for (int i = stems.size (); i--;)
998     {
999       if (!Stem::invisible_b (stems[i]))
1000         c++;
1001     }
1002   return c;
1003 }
1004
1005 Item*
1006 Beam::first_visible_stem (Grob *me) 
1007 {
1008   Link_array<Item>stems = 
1009     Pointer_group_interface__extract_grobs (me, (Item*) 0, "stems");
1010   
1011   for (int i = 0; i < stems.size (); i++)
1012     {
1013       if (!Stem::invisible_b (stems[i]))
1014         return stems[i];
1015     }
1016   return 0;
1017 }
1018
1019 Item*
1020 Beam::last_visible_stem (Grob *me) 
1021 {
1022   Link_array<Item>stems = 
1023     Pointer_group_interface__extract_grobs (me, (Item*) 0, "stems");
1024   for (int i = stems.size (); i--;)
1025     {
1026       if (!Stem::invisible_b (stems[i]))
1027         return stems[i];
1028     }
1029   return 0;
1030 }
1031
1032
1033 /*
1034   [TODO]
1035   handle rest under beam (do_post: beams are calculated now)
1036   what about combination of collisions and rest under beam.
1037
1038   Should lookup
1039     
1040     rest -> stem -> beam -> interpolate_y_position ()
1041 */
1042 MAKE_SCHEME_CALLBACK (Beam, rest_collision_callback, 2);
1043 SCM
1044 Beam::rest_collision_callback (SCM element_smob, SCM axis)
1045 {
1046   Grob *rest = unsmob_grob (element_smob);
1047   Axis a = (Axis) gh_scm2int (axis);
1048   
1049   assert (a == Y_AXIS);
1050
1051   Grob *st = unsmob_grob (rest->get_grob_property ("stem"));
1052   Grob *stem = st;
1053   if (!stem)
1054     return gh_double2scm (0.0);
1055   Grob *beam = unsmob_grob (stem->get_grob_property ("beam"));
1056   if (!beam
1057       || !Beam::has_interface (beam)
1058       || !Beam::visible_stem_count (beam))
1059     return gh_double2scm (0.0);
1060
1061   // make callback for rest from this.
1062   // todo: make sure this calced already.
1063
1064   //  Interval pos = ly_scm2interval (beam->get_grob_property ("positions"));
1065   Interval pos (0, 0);
1066   SCM s = beam->get_grob_property ("positions");
1067   if (gh_pair_p (s) && gh_number_p (ly_car (s)))
1068     pos = ly_scm2interval (s);
1069
1070   Real dy = pos.delta ();
1071   // ugh -> use commonx
1072   Real x0 = first_visible_stem (beam)->relative_coordinate (0, X_AXIS);
1073   Real dx = last_visible_stem (beam)->relative_coordinate (0, X_AXIS) - x0;
1074   Real dydx = dy && dx ? dy/dx : 0;
1075   
1076   Direction d = Stem::get_direction (stem);
1077   Real beamy = (stem->relative_coordinate (0, X_AXIS) - x0) * dydx + pos[LEFT];
1078
1079   Real staff_space =   Staff_symbol_referencer::staff_space (rest);
1080
1081   
1082   Real rest_dim = rest->extent (rest, Y_AXIS)[d]*2.0 / staff_space; // refp??
1083
1084   Real minimum_dist
1085     = gh_scm2double (rest->get_grob_property ("minimum-beam-collision-distance"));
1086   Real dist =
1087     minimum_dist +  -d  * (beamy - rest_dim) >? 0;
1088
1089   int stafflines = Staff_symbol_referencer::line_count (rest);
1090
1091   // move discretely by half spaces.
1092   int discrete_dist = int (ceil (dist));
1093
1094   // move by whole spaces inside the staff.
1095   if (discrete_dist < stafflines+1)
1096     discrete_dist = int (ceil (discrete_dist / 2.0)* 2.0);
1097
1098   return gh_double2scm (-d *  discrete_dist);
1099 }
1100
1101
1102 bool
1103 Beam::has_interface (Grob *me)
1104 {
1105   return me->has_interface (ly_symbol2scm ("beam-interface"));
1106 }
1107