]> git.donarmstrong.com Git - lilypond.git/blob - lily/beam.cc
patch::: 1.3.93.jcn2
[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--2000 Han-Wen Nienhuys <hanwen@cs.uu.nl>
7     Jan Nieuwenhuizen <janneke@gnu.org>
8
9 */
10
11 /*
12   [TODO]
13   * shorter! (now +- 1000 lines)
14     * less hairy code
15     * move paper vars to scm
16
17   remove *-hs variables, and do all y-position stuff in staff-space.
18 */
19
20
21 #include <math.h> // tanh.
22
23
24 #include "directional-element-interface.hh"
25 #include "beaming.hh"
26 #include "beam.hh"
27 #include "misc.hh"
28 #include "least-squares.hh"
29 #include "stem.hh"
30 #include "paper-def.hh"
31 #include "lookup.hh"
32 #include "group-interface.hh"
33 #include "staff-symbol-referencer.hh"
34 #include "cross-staff.hh"
35 #include "item.hh"
36 #include "spanner.hh"
37 #include "warn.hh"
38
39 void
40 Beam::add_stem (Score_element*me, Score_element*s)
41 {
42   Pointer_group_interface gi (me, "stems");
43   gi.add_element (s);
44   
45   s->add_dependency (me);
46
47   assert (!Stem::beam_l (s));
48   s->set_elt_property ("beam", me->self_scm ());
49
50   add_bound_item (dynamic_cast<Spanner*> (me), dynamic_cast<Item*> (s));
51 }
52
53 int
54 Beam::get_multiplicity (Score_element*me) 
55 {
56   int m = 0;
57   for (SCM s = me->get_elt_property ("stems"); gh_pair_p (s); s = gh_cdr (s))
58     {
59       Score_element * sc = unsmob_element (gh_car (s));
60
61       if (Stem::has_interface (sc))
62         m = m >? Stem::beam_count (sc,LEFT) >? Stem::beam_count (sc,RIGHT);
63     }
64   return m;
65 }
66
67 /*
68   After pre-processing all directions should be set.
69   Several post-processing routines (stem, slur, script) need stem/beam
70   direction.
71   Currenly, this means that beam has set all stem's directions.
72   [Alternatively, stems could set its own directions, according to
73    their beam, during 'final-pre-processing'.]
74  */
75 MAKE_SCHEME_CALLBACK(Beam,before_line_breaking,1);
76 SCM
77 Beam::before_line_breaking (SCM smob)
78 {
79   Score_element * me =  unsmob_element (smob);
80
81   // Why?
82   if (visible_stem_count (me) < 2)
83     {
84       warning (_ ("beam has less than two stems"));
85     }
86
87   if (!Directional_element_interface::get (me))
88     Directional_element_interface::set (me, get_default_dir (me));
89
90   auto_knees (me);
91   set_stem_directions (me);
92   set_stem_shorten (me);
93
94   return SCM_EOL;
95 }
96
97 Direction
98 Beam::get_default_dir (Score_element*me) 
99 {
100   Drul_array<int> total;
101   total[UP]  = total[DOWN] = 0;
102   Drul_array<int> count; 
103   count[UP]  = count[DOWN] = 0;
104   Direction d = DOWN;
105
106   Link_array<Item> stems=
107         Pointer_group_interface__extract_elements (me, (Item*)0, "stems");
108
109   for (int i=0; i <stems.size (); i++)
110     do { // HUH -- waar slaat dit op?
111       Score_element *s = stems[i];
112       Direction sd = Directional_element_interface::get (s);
113       int current = sd  ? (1 + d * sd)/2
114         : Stem::get_center_distance (s, (Direction)-d);
115
116       if (current)
117         {
118           total[d] += current;
119           count[d] ++;
120         }
121
122     } while (flip(&d) != DOWN);
123   
124   SCM func = me->get_elt_property ("dir-function");
125   SCM s = gh_call2 (func,
126                     gh_cons (gh_int2scm (count[UP]),
127                              gh_int2scm (count[DOWN])),
128                     gh_cons (gh_int2scm (total[UP]),
129                              gh_int2scm (total[DOWN])));
130
131   if (gh_number_p (s) && gh_scm2int (s))
132     return to_dir (s);
133   
134   /*
135     If dir is not determined: get default
136   */
137   return to_dir (me->get_elt_property ("default-neutral-direction"));
138 }
139
140
141 /*
142   Set all stems with non-forced direction to beam direction.
143   Urg: non-forced should become `without/with unforced' direction,
144        once stem gets cleaned-up.
145  */
146 void
147 Beam::set_stem_directions (Score_element*me)
148 {
149   Link_array<Item> stems
150     =Pointer_group_interface__extract_elements (me,  (Item*) 0, "stems");
151   Direction d = Directional_element_interface::get (me);
152   
153   for (int i=0; i <stems.size (); i++)
154     {
155       Score_element *s = stems[i];
156       SCM force = s->remove_elt_property ("dir-forced");
157       if (!gh_boolean_p (force) || !gh_scm2bool (force))
158         Directional_element_interface ::set (s,d);
159     }
160
161
162 void
163 Beam::auto_knees (Score_element*me)
164 {
165   if (!auto_knee (me,"auto-interstaff-knee-gap", true))
166     auto_knee (me, "auto-knee-gap", false);
167 }
168
169 /*
170   Simplistic auto-knees; only consider vertical gap between two
171   adjacent chords.
172
173   `Forced' stem directions are ignored.  If you don't want auto-knees,
174   don't set, or unset autoKneeGap/autoInterstaffKneeGap.
175  */
176 bool
177 Beam::auto_knee (Score_element*me, String gap_str, bool interstaff_b)
178 {
179   bool knee_b = false;
180   int knee_y = 0;
181   SCM gap = me->get_elt_property (gap_str.ch_C());
182
183   Direction d = Directional_element_interface::get (me);
184       Link_array<Item> stems=
185         Pointer_group_interface__extract_elements (me, (Item*)0, "stems");
186   
187   if (gh_number_p (gap))
188     {
189       Spanner*sp = dynamic_cast<Spanner*> (me);
190       int auto_gap_i = gh_scm2int (gap);
191       for (int i=1; i < stems.size (); i++)
192         {
193           bool is_b = (bool)(calc_interstaff_dist (stems[i], sp) 
194             - calc_interstaff_dist (stems[i-1], sp));
195           int l_y = (int)(Stem::head_positions(stems[i-1])[d])
196             + (int)calc_interstaff_dist (stems[i-1], sp);
197           int r_y = (int)(Stem::head_positions(stems[i])[d])
198             + (int)calc_interstaff_dist (stems[i], sp);
199           int gap_i = r_y - l_y;
200
201           if ((abs (gap_i) >= auto_gap_i) && (!interstaff_b || is_b))
202             {
203               knee_y = (r_y + l_y) / 2;
204               knee_b = true;
205               break;
206             }
207         }
208     }
209   if (knee_b)
210     {
211       for (int i=0; i < stems.size (); i++)
212         {
213           Item *s = stems[i];     
214           int y = (int)(Stem::head_positions(s)[d])
215             + (int)calc_interstaff_dist (s, dynamic_cast<Spanner*> (me));
216
217           Directional_element_interface::set (s,y < knee_y ? UP : DOWN);
218           s->set_elt_property ("dir-forced", SCM_BOOL_T);
219         }
220     }
221   return knee_b;
222 }
223
224 /*
225  Set stem's shorten property if unset.
226  TODO:
227     take some y-position (chord/beam/nearest?) into account
228     scmify forced-fraction
229  */
230 void
231 Beam::set_stem_shorten (Score_element*m)
232 {
233   Spanner*me = dynamic_cast<Spanner*> (m);
234   if (!visible_stem_count (me))
235     return;
236
237   Real forced_fraction = forced_stem_count (me) / visible_stem_count (me);
238   if (forced_fraction < 0.5)
239     return;
240
241   int multiplicity = get_multiplicity (me);
242
243   SCM shorten = me->get_elt_property ("beamed-stem-shorten");
244   if (shorten == SCM_EOL)
245     return;
246
247   int sz = scm_ilength (shorten);
248   
249   Real staff_space = Staff_symbol_referencer::staff_space (me);
250   SCM shorten_elt = scm_list_ref (shorten, gh_int2scm (multiplicity <? (sz - 1)));
251   Real shorten_f = gh_scm2double (shorten_elt) * staff_space;
252
253   /* cute, but who invented me -- how to customise ? */
254   if (forced_fraction < 1)
255     shorten_f /= 2;
256
257   Link_array<Item> stems=
258     Pointer_group_interface__extract_elements (me, (Item*)0, "stems");
259
260   for (int i=0; i < stems.size (); i++)
261     {
262       Item* s = stems[i];
263       if (Stem::invisible_b (s))
264         continue;
265       if (gh_number_p (s->get_elt_property ("shorten")))
266         s->set_elt_property ("shorten", gh_double2scm (shorten_f));
267     }
268 }
269
270 /*
271   Set elt properties height and y-position if not set.
272   Adjust stem lengths to reach beam.
273  */
274 MAKE_SCHEME_CALLBACK(Beam,after_line_breaking,1);
275 SCM
276 Beam::after_line_breaking (SCM smob)
277 {
278   Score_element * me =  unsmob_element (smob);
279
280   /* first, calculate y, dy */
281   Real y, dy;
282   calc_default_position_and_height (me, &y, &dy);
283   if (visible_stem_count (me))
284     {
285       if (suspect_slope_b (me, y, dy))
286         dy = 0;
287
288       Real damped_dy = calc_slope_damping_f (me, dy);
289       Real quantised_dy = quantise_dy_f (me, damped_dy);
290
291       y += (dy - quantised_dy) / 2;
292       dy = quantised_dy;
293     }
294   /*
295     until here, we used only stem_info, which acts as if dir=up
296    */
297   y *= Directional_element_interface::get (me);
298   dy *= Directional_element_interface::get (me);
299
300
301   Real half_space = Staff_symbol_referencer::staff_space (me) / 2;
302
303   /* weird: why do we do calc_position_and_height () ? regardless of
304      this setting?
305
306   */
307   /* check for user-override of dy */
308   SCM s = me->remove_elt_property ("height-hs");
309   if (gh_number_p (s))
310     {
311       dy = gh_scm2double (s) * half_space;
312     }
313   me->set_elt_property ("height", gh_double2scm (dy));
314
315   /* check for user-override of y */
316   s = me->remove_elt_property ("y-position-hs");
317   if (gh_number_p (s))
318     {
319       y = gh_scm2double (s) * half_space;
320     }
321   else
322     { 
323       /* we can modify y, so we should quantise y */
324       Real y_shift = check_stem_length_f (me, y, dy);
325       y += y_shift;
326       y = quantise_y_f (me,y, dy, 0);
327       set_stem_length (me, y, dy);
328       y_shift = check_stem_length_f (me, y, dy);
329
330       if (y_shift > half_space / 4)
331         {
332           y += y_shift;
333
334           /*
335             for significantly lengthened or shortened stems,
336             request quanting the other way.
337           */
338           int quant_dir = 0;
339           if (abs (y_shift) > half_space / 2)
340             quant_dir = sign (y_shift) * Directional_element_interface::get (me);
341           y = quantise_y_f (me, y, dy, quant_dir);
342         }
343     }
344   // UGH. Y is not in staff position unit?
345   // Ik dacht datwe daar juist van weg wilden?
346   set_stem_length (me, y, dy);
347   me->set_elt_property ("y-position", gh_double2scm (y));
348
349   return SCM_UNSPECIFIED;
350 }
351
352 /*
353   See Documentation/tex/fonts.doc
354  */
355 void
356 Beam::calc_default_position_and_height (Score_element*me,Real* y, Real* dy) 
357 {
358   *y = 0;
359   *dy = 0;  
360   if (visible_stem_count (me) <= 1)
361     return;
362
363   Real first_ideal = Stem::calc_stem_info (first_visible_stem (me)).idealy_f_;
364   if (first_ideal == Stem::calc_stem_info (last_visible_stem (me)).idealy_f_)
365     {
366       *dy = 0;
367       *y = first_ideal;
368       return;
369     }
370
371   Array<Offset> ideals;
372
373   // ugh -> use commonx
374   Real x0 = first_visible_stem (me)->relative_coordinate (0, X_AXIS);
375   Link_array<Item> stems=
376     Pointer_group_interface__extract_elements (me, (Item*)0, "stems");
377
378   for (int i=0; i < stems.size (); i++)
379     {
380       Item* s = stems[i];
381       if (Stem::invisible_b (s))
382         continue;
383       ideals.push (Offset (s->relative_coordinate (0, X_AXIS) - x0, 
384                            Stem::calc_stem_info (s).idealy_f_));
385     }
386   Real dydx;
387   minimise_least_squares (&dydx, y, ideals); // duh, takes references
388
389   Real dx = last_visible_stem (me)->relative_coordinate (0, X_AXIS) - x0;
390   *dy = dydx * dx;
391 }
392
393 bool
394 Beam::suspect_slope_b (Score_element*me, Real y, Real dy) 
395 {
396   /* first, calculate y, dy */
397   /*
398     steep slope running against lengthened stem is suspect
399   */
400   Real ss = me->paper_l ()->get_var ("staffspace");
401   Real first_ideal = Stem::calc_stem_info (first_visible_stem (me)).idealy_f_;
402   Real last_ideal = Stem::calc_stem_info (last_visible_stem (me)).idealy_f_;
403   Real lengthened = gh_scm2double (me->get_elt_property ("outer-stem-length-limit")) * ss;
404   Real steep = gh_scm2double (me->get_elt_property ("slope-limit"));
405
406   // ugh -> use commonx
407   Real dx = last_visible_stem (me)->relative_coordinate (0, X_AXIS) - first_visible_stem (me)->relative_coordinate (0, X_AXIS);
408   Real dydx = dy && dx ? dy/dx : 0;
409
410   if (((y - first_ideal > lengthened) && (dydx > steep))
411       || ((y + dy - last_ideal > lengthened) && (dydx < -steep)))
412     {
413       return true;
414     }
415   return false;
416 }
417
418 /*
419   This neat trick is by Werner Lemberg,
420   damped = tanh (slope)
421   corresponds with some tables in [Wanske]
422 */
423 Real
424 Beam::calc_slope_damping_f (Score_element*me,Real dy) 
425 {
426   SCM damp = me->get_elt_property ("damping"); 
427   int damping = gh_scm2int (damp);
428
429   if (damping)
430     {
431   // ugh -> use commonx
432       Real dx = last_visible_stem (me)->relative_coordinate (0, X_AXIS)
433         - first_visible_stem (me)->relative_coordinate (0, X_AXIS);
434       Real dydx = dy && dx ? dy/dx : 0;
435       dydx = 0.6 * tanh (dydx) / damping;
436       return dydx * dx;
437     }
438   return dy;
439 }
440
441 Real
442 Beam::calc_stem_y_f (Score_element*me,Item* s, Real y, Real dy) 
443 {
444   int beam_multiplicity = get_multiplicity (me);
445   int stem_multiplicity = (Stem::flag_i (s) - 2) >? 0;
446
447   Real staffspace = me->paper_l ()->get_var ("staffspace");
448   
449   SCM space_proc = me->get_elt_property ("space-function");
450   SCM space = gh_call1 (space_proc, gh_int2scm (beam_multiplicity));
451
452   Real thick = gh_scm2double (me->get_elt_property ("thickness")) *staffspace;
453   Real interbeam_f = gh_scm2double (space) * staffspace;
454
455   // ugh -> use commonx
456   Real x0 = first_visible_stem (me)->relative_coordinate (0, X_AXIS);
457   Real dx = last_visible_stem (me)->relative_coordinate (0, X_AXIS) - x0;
458   Real stem_y = (dy && dx ? (s->relative_coordinate (0, X_AXIS) - x0) / dx * dy : 0) + y;
459
460   /* knee */
461    Direction dir  = Directional_element_interface::get (me);
462    Direction sdir = Directional_element_interface::get (s);
463    
464     /* knee */
465    if (dir!= sdir)
466       {
467        stem_y -= dir 
468         * (thick / 2 + (beam_multiplicity - 1) * interbeam_f);
469
470
471       
472       // huh, why not for first visible?
473        if (Staff_symbol_referencer::staff_symbol_l (s)
474            != Staff_symbol_referencer::staff_symbol_l (last_visible_stem (me)))
475          stem_y += Directional_element_interface::get (me)
476            * (beam_multiplicity - stem_multiplicity) * interbeam_f;
477       }
478
479   return stem_y;
480 }
481
482 Real
483 Beam::check_stem_length_f (Score_element*me,Real y, Real dy) 
484 {
485   Real shorten = 0;
486   Real lengthen = 0;
487   Direction dir = Directional_element_interface::get (me);
488
489   Link_array<Item> stems=
490     Pointer_group_interface__extract_elements (me, (Item*)0, "stems");
491
492   for (int i=0; i < stems.size(); i++)
493     {
494       Item* s = stems[i];
495       if (Stem::invisible_b (s))
496         continue;
497
498       Real stem_y = calc_stem_y_f (me, s, y, dy);
499         
500       stem_y *= dir;
501       Stem_info info = Stem::calc_stem_info (s);
502
503       // if (0 > info.maxy_f_ - stem_y)
504       shorten = shorten <? info.maxy_f_ - stem_y;
505       // if (0 < info.miny_f_ - stem_y)
506       lengthen = lengthen >? info.miny_f_ - stem_y; 
507     }
508
509   if (lengthen && shorten)
510     warning (_ ("weird beam vertical offset"));
511
512   /* when all stems are too short, normal stems win */
513   return dir * ((shorten) ?  shorten : lengthen);
514 }
515
516 /*
517   Hmm.  At this time, beam position and slope are determined.  Maybe,
518   stem directions and length should set to relative to the chord's
519   position of the beam.  */
520 void
521 Beam::set_stem_length (Score_element*me,Real y, Real dy)
522 {
523   Real half_space = Staff_symbol_referencer::staff_space (me)/2;
524   Link_array<Item> stems=
525     Pointer_group_interface__extract_elements (me, (Item*)0, "stems");
526
527
528   for (int i=0; i < stems.size (); i++)
529     {
530       Item* s = stems[i];
531       if (Stem::invisible_b (s))
532         continue;
533
534       Real stem_y = calc_stem_y_f (me, s, y, dy);
535
536       /* caution: stem measures in staff-positions */
537       Stem::set_stemend (s,(stem_y + calc_interstaff_dist (s, dynamic_cast<Spanner*> (me))) / half_space);
538     }
539 }
540
541 /*
542   [Ross] (simplification of)
543   Set dy complying with:
544     - zero
545     - thick / 2 + staffline_f / 2
546     - thick + staffline_f
547   + n * staff_space
548 */
549 Real
550 Beam::quantise_dy_f (Score_element*me,Real dy) 
551 {
552   Array<Real> a;
553
554   SCM proc = me->get_elt_property ("height-quants");
555   SCM quants = gh_call2 (proc, me->self_scm (),
556                          gh_double2scm (me->paper_l ()->get_var ("stafflinethickness")
557                                         / me->paper_l ()->get_var ("staffspace")));
558   
559   
560   for (SCM s = quants; gh_pair_p (s); s = gh_cdr (s))
561     a.push (gh_scm2double (gh_car (s)));
562   
563   if (a.size () <= 1)
564     return dy;
565
566   Real staff_space = Staff_symbol_referencer::staff_space (me);
567   
568   Interval iv = quantise_iv (a, abs (dy)/staff_space) * staff_space;
569   Real q = (abs (dy) - iv[SMALLER] <= iv[BIGGER] - abs (dy))
570     ? iv[SMALLER]
571     : iv[BIGGER];
572   
573   return q * sign (dy);
574 }
575
576 /*
577   Prevent interference from stafflines and beams.
578   See Documentation/tex/fonts.doc
579
580   We only need to quantise the (left) y-position of the beam,
581   since dy is quantised too.
582   if extend_b then stems must *not* get shorter
583  */
584 Real
585 Beam::quantise_y_f (Score_element*me,Real y, Real dy, int quant_dir)
586 {
587   int multiplicity = get_multiplicity (me);
588
589   Real staff_space = Staff_symbol_referencer::staff_space (me);
590   Real thick = me->paper_l ()->get_var ("stafflinethickness");
591
592
593   SCM proc = me->get_elt_property ("vertical-position-quant-function");
594   SCM quants = scm_apply (proc,
595                           me->self_scm (),
596                           gh_list (gh_int2scm (multiplicity),
597                                    gh_double2scm (dy/staff_space),
598                                    gh_double2scm (thick/staff_space),
599                                    SCM_EOL, SCM_UNDEFINED));
600   
601   Array<Real> a;
602
603   for (; gh_pair_p (quants); quants = gh_cdr (quants))
604     a.push (gh_scm2double (gh_car (quants)));
605
606   if (a.size () <= 1)
607     return y;
608
609   Real up_y = Directional_element_interface::get (me) * y;
610   Interval iv = quantise_iv (a, up_y/staff_space) * staff_space;
611
612   Real q = up_y - iv[SMALLER] <= iv[BIGGER] - up_y 
613     ? iv[SMALLER] : iv[BIGGER];
614   if (quant_dir)
615     q = iv[(Direction)quant_dir];
616
617   return q * Directional_element_interface::get (me);
618 }
619
620 void
621 Beam::set_beaming (Score_element*me,Beaming_info_list *beaming)
622 {
623   Link_array<Score_element> stems=
624     Pointer_group_interface__extract_elements (me, (Score_element*)0, "stems");
625   
626   Direction d = LEFT;
627   for (int i=0; i  < stems.size(); i++)
628     {
629       do
630         {
631           if (Stem::beam_count (stems[i], d) == 0)
632             Stem::set_beaming ( stems[i], beaming->infos_.elem (i).beams_i_drul_[d],d);
633         }
634       while (flip (&d) != LEFT);
635     }
636 }
637
638
639
640 /*
641   beams to go with one stem.
642
643   FIXME: clean me up.
644   */
645 Molecule
646 Beam::stem_beams (Score_element*me,Item *here, Item *next, Item *prev) 
647 {
648   // ugh -> use commonx
649   if ((next && !(next->relative_coordinate (0, X_AXIS) > here->relative_coordinate (0, X_AXIS))) ||
650       (prev && !(prev->relative_coordinate (0, X_AXIS) < here->relative_coordinate (0, X_AXIS))))
651       programming_error ("Beams are not left-to-right");
652
653   Real staffline_f = me->paper_l ()->get_var ("stafflinethickness");
654   int multiplicity = get_multiplicity (me);
655   Real staffspace =me->paper_l ()->get_var ("staffspace");
656
657   SCM space_proc = me->get_elt_property ("space-function");
658   SCM space = gh_call1 (space_proc, gh_int2scm (multiplicity));
659
660   Real thick = gh_scm2double (me->get_elt_property ("thickness")) *staffspace;
661   Real interbeam_f = gh_scm2double (space) * staffspace;
662     
663   Real bdy = interbeam_f;
664   Real stemdx = staffline_f;
665
666     // ugh -> use commonx
667   Real dx = visible_stem_count (me) ?
668     last_visible_stem (me)->relative_coordinate (0, X_AXIS) - first_visible_stem (me)->relative_coordinate (0, X_AXIS)
669     : 0.0;
670   Real dy = gh_scm2double (me->get_elt_property ("height"));
671   Real dydx = dy && dx ? dy/dx : 0;
672
673   Molecule leftbeams;
674   Molecule rightbeams;
675
676   Real nw_f;
677   if (!Stem::first_head (here))
678     nw_f = 0;
679   else {
680     int t = Stem::type_i (here); 
681
682     SCM proc = me->get_elt_property ("flag-width-function");
683     SCM result = gh_call1 (proc, gh_int2scm (t));
684     nw_f = gh_scm2double (result) * staffspace;
685   }
686
687
688   Direction dir = Directional_element_interface::get (me);
689   
690   /* half beams extending to the left. */
691   if (prev)
692     {
693       int lhalfs= lhalfs = Stem::beam_count (here,LEFT) - Stem::beam_count (prev,RIGHT);
694       int lwholebeams= Stem::beam_count (here,LEFT) <? Stem::beam_count (prev,RIGHT) ;
695       /*
696        Half beam should be one note-width, 
697        but let's make sure two half-beams never touch
698        */
699       Real w = here->relative_coordinate (0, X_AXIS) - prev->relative_coordinate (0, X_AXIS);
700       w = w/2 <? nw_f;
701       Molecule a;
702       if (lhalfs)               // generates warnings if not
703         a =  me->lookup_l ()->beam (dydx, w, thick);
704       a.translate (Offset (-w, -w * dydx));
705       for (int j = 0; j  < lhalfs; j++)
706         {
707           Molecule b (a);
708           b.translate_axis (-dir * bdy * (lwholebeams+j), Y_AXIS);
709           leftbeams.add_molecule (b);
710         }
711     }
712
713   if (next)
714     {
715       int rhalfs  = Stem::beam_count (here,RIGHT) - Stem::beam_count (next,LEFT);
716       int rwholebeams= Stem::beam_count (here,RIGHT) <? Stem::beam_count (next,LEFT) ;
717
718       Real w = next->relative_coordinate (0, X_AXIS) - here->relative_coordinate (0, X_AXIS);
719       Molecule a = me->lookup_l ()->beam (dydx, w + stemdx, thick);
720       a.translate_axis( - stemdx/2, X_AXIS);
721       int j = 0;
722       Real gap_f = 0;
723
724       SCM gap = me->get_elt_property ("gap");
725       if (gh_number_p (gap))
726         {
727           int gap_i = gh_scm2int ( (gap));
728           int nogap = rwholebeams - gap_i;
729           
730           for (; j  < nogap; j++)
731             {
732               Molecule b (a);
733               b.translate_axis (-dir  * bdy * j, Y_AXIS);
734               rightbeams.add_molecule (b);
735             }
736           // TODO: notehead widths differ for different types
737           gap_f = nw_f / 2;
738           w -= 2 * gap_f;
739           a = me->lookup_l ()->beam (dydx, w + stemdx, thick);
740         }
741
742       for (; j  < rwholebeams; j++)
743         {
744           Molecule b (a);
745           b.translate (Offset (Stem::invisible_b (here) ? 0 : gap_f, -dir * bdy * j));
746           rightbeams.add_molecule (b);
747         }
748
749       w = w/2 <? nw_f;
750       if (rhalfs)
751         a = me->lookup_l ()->beam (dydx, w, thick);
752
753       for (; j  < rwholebeams + rhalfs; j++)
754         {
755           Molecule b (a);
756           b.translate_axis (- dir * bdy * j, Y_AXIS);
757           rightbeams.add_molecule (b);
758         }
759
760     }
761   leftbeams.add_molecule (rightbeams);
762
763   /*
764     Does beam quanting think  of the asymetry of beams? 
765     Refpoint is on bottom of symbol. (FIXTHAT) --hwn.
766    */
767   return leftbeams;
768 }
769
770 MAKE_SCHEME_CALLBACK(Beam,brew_molecule,1);
771 SCM
772 Beam::brew_molecule (SCM smob)
773 {
774   Score_element * me =unsmob_element (smob);
775
776   Molecule mol;
777   if (!gh_pair_p (me->get_elt_property ("stems")))
778     return SCM_EOL;
779   Real x0,dx;
780   Link_array<Item>stems = 
781     Pointer_group_interface__extract_elements (me, (Item*) 0, "stems");  
782   if (visible_stem_count (me))
783     {
784   // ugh -> use commonx
785       x0 = first_visible_stem (me)->relative_coordinate (0, X_AXIS);
786       dx = last_visible_stem (me)->relative_coordinate (0, X_AXIS) - x0;
787     }
788   else
789     {
790       x0 = stems[0]->relative_coordinate (0, X_AXIS);
791       dx = stems.top()->relative_coordinate (0, X_AXIS) - x0;
792     }
793   
794   
795   Real dy = gh_scm2double (me->get_elt_property ("height"));
796   Real dydx = dy && dx ? dy/dx : 0;
797   Real y = gh_scm2double (me->get_elt_property ("y-position"));
798
799
800   for (int j=0; j <stems.size  (); j++)
801     {
802       Item *i = stems[j];
803       Item * prev = (j > 0)? stems[j-1] : 0;
804       Item * next = (j < stems.size()-1) ? stems[j+1] :0;
805
806       Molecule sb = stem_beams (me, i, next, prev);
807       Real x = i->relative_coordinate (0, X_AXIS)-x0;
808       sb.translate (Offset (x, x * dydx + y));
809       mol.add_molecule (sb);
810     }
811   mol.translate_axis (x0 
812     - dynamic_cast<Spanner*> (me)->get_bound (LEFT)->relative_coordinate (0, X_AXIS), X_AXIS);
813
814   return mol.create_scheme ();
815 }
816
817 int
818 Beam::forced_stem_count (Score_element*me) 
819 {
820   Link_array<Item>stems = 
821     Pointer_group_interface__extract_elements ( me, (Item*) 0, "stems");
822   int f = 0;
823   for (int i=0; i < stems.size (); i++)
824     {
825       Item *s = stems[i];
826
827       if (Stem::invisible_b (s))
828         continue;
829
830       if (((int)Stem::chord_start_f (s)) 
831         && (Stem::get_direction (s ) != Stem::get_default_dir (s )))
832         f++;
833     }
834   return f;
835 }
836
837
838
839
840 /* TODO:
841    use filter and standard list functions.
842  */
843 int
844 Beam::visible_stem_count (Score_element*me) 
845 {
846   Link_array<Item>stems = 
847     Pointer_group_interface__extract_elements (me, (Item*) 0, "stems");
848   int c = 0;
849   for (int i = stems.size (); i--;)
850     {
851       if (!Stem::invisible_b (stems[i]))
852         c++;
853     }
854   return c;
855 }
856
857 Item*
858 Beam::first_visible_stem(Score_element*me) 
859 {
860   Link_array<Item>stems = 
861     Pointer_group_interface__extract_elements ( me, (Item*) 0, "stems");
862   
863   for (int i = 0; i < stems.size (); i++)
864     {
865       if (!Stem::invisible_b (stems[i]))
866         return stems[i];
867     }
868   return 0;
869 }
870
871 Item*
872 Beam::last_visible_stem(Score_element*me) 
873 {
874   Link_array<Item>stems = 
875     Pointer_group_interface__extract_elements ( me, (Item*) 0, "stems");
876   for (int i = stems.size (); i--;)
877     {
878       if (!Stem::invisible_b (stems[i]))
879         return stems[i];
880     }
881   return 0;
882 }
883
884
885 /*
886   [TODO]
887   handle rest under beam (do_post: beams are calculated now)
888   what about combination of collisions and rest under beam.
889
890   Should lookup
891     
892     rest -> stem -> beam -> interpolate_y_position ()
893 */
894 MAKE_SCHEME_CALLBACK(Beam,rest_collision_callback,1);
895 SCM
896 Beam::rest_collision_callback (SCM element_smob, SCM axis)
897 {
898   Score_element *rest = unsmob_element (element_smob);
899   Axis a = (Axis) gh_scm2int (axis);
900   
901   assert (a == Y_AXIS);
902
903   Score_element * st = unsmob_element (rest->get_elt_property ("stem"));
904   Score_element * stem = st;
905   if (!stem)
906     return gh_double2scm (0.0);
907   Score_element * beam = unsmob_element (stem->get_elt_property ("beam"));
908   if (!beam || !Beam::has_interface (beam) || !Beam::visible_stem_count (beam))
909     return gh_double2scm (0.0);
910
911   // make callback for rest from this.
912   Real beam_dy = 0;
913   Real beam_y = 0;
914
915
916   // todo: make sure this calced already.
917   SCM s = beam->get_elt_property ("height");
918   if (gh_number_p (s))
919     beam_dy = gh_scm2double (s);
920   
921   s = beam->get_elt_property ("y-position");
922   if (gh_number_p (s))
923     beam_y = gh_scm2double (s);
924   
925   // ugh -> use commonx
926   Real x0 = first_visible_stem(beam)->relative_coordinate (0, X_AXIS);
927   Real dx = last_visible_stem(beam)->relative_coordinate (0, X_AXIS) - x0;
928   Real dydx = beam_dy && dx ? beam_dy/dx : 0;
929
930   Direction d = Stem::get_direction (stem);
931   Real beamy = (stem->relative_coordinate (0, X_AXIS) - x0) * dydx + beam_y;
932
933   Real staff_space =   Staff_symbol_referencer::staff_space (rest);
934   Real rest_dim = rest->extent (Y_AXIS)[d]*2.0 / staff_space ;
935
936   Real minimum_dist
937     = gh_scm2double (rest->get_elt_property ("minimum-beam-collision-distance"));
938   Real dist =
939     minimum_dist +  -d  * (beamy - rest_dim) >? 0;
940
941   int stafflines = Staff_symbol_referencer::line_count (rest);
942
943   // move discretely by half spaces.
944   int discrete_dist = int (ceil (dist));
945
946   // move by whole spaces inside the staff.
947   if (discrete_dist < stafflines+1)
948     discrete_dist = int (ceil (discrete_dist / 2.0)* 2.0);
949
950   return  (-d *  discrete_dist);
951 }
952
953
954 bool
955 Beam::has_interface (Score_element*me)
956 {
957   return me->has_interface (ly_symbol2scm ("beam-interface"));
958 }
959
960 void
961 Beam::set_interface (Score_element*me)
962 {
963   Pointer_group_interface g (me, "stems");
964   g.set_interface ();
965
966   /*
967     why the init? No way to tell difference between default and user
968     override.  */
969   me->set_elt_property ("height", gh_int2scm (0)); // ugh.
970   me->set_elt_property ("y-position" ,gh_int2scm (0));
971   me->set_interface (ly_symbol2scm("beam-interface"));
972 }