summaryrefslogtreecommitdiff
path: root/lily/beam.cc
blob: 5b50831fca15d6a80e39da9839420cd8e0edc6be (about) (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
/*
  beam.cc -- implement Beam

  source file of the GNU LilyPond music typesetter

  (c)  1997--2000 Han-Wen Nienhuys <hanwen@cs.uu.nl>
    Jan Nieuwenhuizen <janneke@gnu.org>

*/

/*
  [TODO]
    * less hairy code
    * move paper vars to scm

    remove *-hs variables.
*/


#include <math.h> // tanh.
#include "directional-element-interface.hh"
#include "beaming.hh"
#include "dimensions.hh"
#include "beam.hh"
#include "misc.hh"
#include "debug.hh"
#include "least-squares.hh"
#include "stem.hh"
#include "paper-def.hh"
#include "lookup.hh"
#include "group-interface.hh"
#include "staff-symbol-referencer.hh"
#include "cross-staff.hh"

Beam::Beam (SCM s)
  : Spanner (s)
{
  Pointer_group_interface g (this, "stems");
  g.set_interface ();

  set_elt_property ("height", gh_int2scm (0)); // ugh.
  set_elt_property ("y-position" ,gh_int2scm (0));
}

void
Beam::add_stem (Stem*s)
{
  Pointer_group_interface gi (this, "stems");
  gi.add_element (s);
  
  s->add_dependency (this);

  assert (!s->beam_l ());
  s->set_elt_pointer ("beam", self_scm_);

  add_bound_item (this, s);
}

int
Beam::get_multiplicity () const
{
  int m = 0;
  for (SCM s = get_elt_pointer ("stems"); gh_pair_p (s); s = gh_cdr (s))
    {
      Score_element * sc = unsmob_element (gh_car (s));

      if (Stem * st = dynamic_cast<Stem*> (sc))
	m = m >? st->beam_count (LEFT) >? st->beam_count (RIGHT);
    }
  return m;
}

/*
  After pre-processing all directions should be set.
  Several post-processing routines (stem, slur, script) need stem/beam
  direction.
  Currenly, this means that beam has set all stem's directions.
  [Alternatively, stems could set its own directions, according to
   their beam, during 'final-pre-processing'.]
 */
GLUE_SCORE_ELEMENT(Beam,before_line_breaking);
SCM
Beam::member_before_line_breaking ()
{
  // Why?
  if (visible_stem_count () < 2)
    {
      warning (_ ("beam has less than two stems"));

    }

  if (!Directional_element_interface (this).get ())
    Directional_element_interface (this).set (get_default_dir ());

  auto_knees ();
  set_stem_directions ();
  set_stem_shorten ();

  return SCM_EOL;
}

/*
 FIXME
 */
Direction
Beam::get_default_dir () const
{
  Drul_array<int> total;
  total[UP]  = total[DOWN] = 0;
  Drul_array<int> count; 
  count[UP]  = count[DOWN] = 0;
  Direction d = DOWN;

  for (int i=0; i <stem_count (); i++)
    do { // HUH -- waar slaat dit op?
      Stem *s = stem (i);
      Direction sd = Directional_element_interface (s).get ();
      int current = sd	? (1 + d * sd)/2
	: s->get_center_distance ((Direction)-d);

      if (current)
	{
	  total[d] += current;
	  count[d] ++;
	}

    } while (flip(&d) != DOWN);
  

  SCM s = scm_eval (gh_list (ly_symbol2scm ("beam-dir-algorithm"),
			     ly_quote_scm (gh_cons (gh_int2scm (count[UP]),
						    gh_int2scm (count[DOWN]))),
			     ly_quote_scm (gh_cons (gh_int2scm (total[UP]),
						    gh_int2scm (total[DOWN]))),
			     SCM_UNDEFINED));
  if (gh_number_p (s) && gh_scm2int (s))
    return to_dir (s);
  
  /*
    If dir is not determined: get from paper
  */
  return (Direction)(int)
    paper_l ()->get_var ("stem_default_neutral_direction");
}


/*
  Set all stems with non-forced direction to beam direction.
  Urg: non-forced should become `without/with unforced' direction,
       once stem gets cleaned-up.
 */
void
Beam::set_stem_directions ()
{
  Direction d = Directional_element_interface (this).get ();
  for (int i=0; i <stem_count (); i++)
    {
      Stem *s = stem (i);
      SCM force = s->remove_elt_property ("dir-forced");
      if (!gh_boolean_p (force) || !gh_scm2bool (force))
	Directional_element_interface (s).set (d);
    }
} 

void
Beam::auto_knees ()
{
  if (!auto_knee ("auto-interstaff-knee-gap", true))
    auto_knee ("auto-knee-gap", false);
}

/*
  Simplistic auto-knees; only consider vertical gap between two
  adjacent chords.

  `Forced' stem directions are ignored.  If you don't want auto-knees,
  don't set, or unset autoKneeGap/autoInterstaffKneeGap.
 */
bool
Beam::auto_knee (String gap_str, bool interstaff_b)
{
  bool knee_b = false;
  int knee_y = 0;
  SCM gap = get_elt_property (gap_str);
  Direction d = Directional_element_interface (this).get ();
  
  if (gh_number_p (gap))
    {
      int auto_gap_i = gh_scm2int (gap);
      for (int i=1; i < stem_count (); i++)
        {
	  bool is_b = (bool)(calc_interstaff_dist (stem (i), this) 
	    - calc_interstaff_dist (stem (i-1), this));
	  int l_y = (int)(stem (i-1)->head_positions()[d])
	    + (int)calc_interstaff_dist (stem (i-1), this);
	  int r_y = (int)(stem (i)->head_positions()[d])
	    + (int)calc_interstaff_dist (stem (i), this);
	  int gap_i = r_y - l_y;

	  if ((abs (gap_i) >= auto_gap_i) && (!interstaff_b || is_b))
	    {
	      knee_y = (r_y + l_y) / 2;
	      knee_b = true;
	      break;
	    }
	}
    }
  if (knee_b)
    {
      for (int i=0; i < stem_count (); i++)
        {
	  Item *s = stem(i);	  
	  int y = (int)(stem (i)->head_positions()[d])
	    + (int)calc_interstaff_dist (s, this);


	  Directional_element_interface (s).set (y < knee_y ? UP : DOWN);
	  s->set_elt_property ("dir-forced", SCM_BOOL_T);
	}
    }
  return knee_b;
}

/*
 Set stem's shorten property if unset.
 TODO:
    take some y-position (chord/beam/nearest?) into account
    scmify forced-fraction
 */
void
Beam::set_stem_shorten ()
{
  if (!visible_stem_count ())
    return;

  Real forced_fraction = forced_stem_count () / visible_stem_count ();
  if (forced_fraction < 0.5)
    return;

  int multiplicity = get_multiplicity ();

  // grace stems?
  SCM shorten = scm_eval (ly_symbol2scm ("beamed-stem-shorten"));

  if (shorten == SCM_EOL)
    return;

  int sz = scm_ilength (shorten);
  
  Staff_symbol_referencer_interface st (this);
  Real staff_space = st.staff_space ();
  SCM shorten_elt = scm_list_ref (shorten, gh_int2scm (multiplicity <? (sz - 1)));
  Real shorten_f = gh_scm2double (shorten_elt) * staff_space;

  /* cute, but who invented this -- how to customise ? */
  if (forced_fraction < 1)
    shorten_f /= 2;

  for (int i=0; i < stem_count (); i++)
    {
      Stem* s = stem (i);
      if (s->invisible_b ())
        continue;
      if (gh_number_p (s->get_elt_property ("shorten")))
	s->set_elt_property ("shorten", gh_double2scm (shorten_f));
    }
}

/*
  Set elt properties height and y-position if not set.
  Adjust stem lengths to reach beam.
 */
GLUE_SCORE_ELEMENT(Beam,after_line_breaking);
SCM
Beam::member_after_line_breaking ()
{
  /* first, calculate y, dy */
  Real y, dy;
  calc_default_position_and_height (&y, &dy);
  if (visible_stem_count ())
    {
      if (suspect_slope_b (y, dy))
	dy = 0;

      Real damped_dy = calc_slope_damping_f (dy);
      Real quantised_dy = quantise_dy_f (damped_dy);

      y += (dy - quantised_dy) / 2;
      dy = quantised_dy;
    }
  /*
    until here, we used only stem_info, which acts as if dir=up
   */
  y *= Directional_element_interface (this).get ();
  dy *= Directional_element_interface (this).get ();

  Staff_symbol_referencer_interface st (this);
  Real half_space = st.staff_space () / 2;

  /* check for user-override of dy */
  SCM s = remove_elt_property ("height-hs");
  if (gh_number_p (s))
    {
      dy = gh_scm2double (s) * half_space;
    }
  set_elt_property ("height", gh_double2scm (dy));

  /* check for user-override of y */
  s = remove_elt_property ("y-position-hs");
  if (gh_number_p (s))
    {
      y = gh_scm2double (s) * half_space;
    }
  else
    { 
      /* we can modify y, so we should quantise y */
      Real y_shift = check_stem_length_f (y, dy);
      y += y_shift;
      y = quantise_y_f (y, dy, 0);
      set_stem_length (y, dy);
      y_shift = check_stem_length_f (y, dy);

      if (y_shift > half_space / 4)
	{
	  y += y_shift;

	  /*
	    for significantly lengthened or shortened stems,
	    request quanting the other way.
	  */
	  int quant_dir = 0;
	  if (abs (y_shift) > half_space / 2)
	    quant_dir = sign (y_shift) * Directional_element_interface (this).get ();
	  y = quantise_y_f (y, dy, quant_dir);
	}
    }
  // UGH. Y is not in staff position unit?
  // Ik dacht datwe daar juist van weg wilden?
  set_stem_length (y, dy);
  set_elt_property ("y-position", gh_double2scm (y));


  return SCM_UNDEFINED;
}

/*
  See Documentation/tex/fonts.doc
 */
void
Beam::calc_default_position_and_height (Real* y, Real* dy) const
{
  *y = 0;
  *dy = 0;  
  if (visible_stem_count () <= 1)
    return;

  Real first_ideal = first_visible_stem ()->calc_stem_info ().idealy_f_;
  if (first_ideal == last_visible_stem ()->calc_stem_info ().idealy_f_)
    {
      *dy = 0;
      *y = first_ideal;
      return;
    }

  Array<Offset> ideals;
  Real x0 = first_visible_stem ()->relative_coordinate (0, X_AXIS);
  for (int i=0; i < stem_count (); i++)
    {
      Stem* s = stem (i);
      if (s->invisible_b ())
        continue;
      ideals.push (Offset (s->relative_coordinate (0, X_AXIS) - x0, 
			   s->calc_stem_info ().idealy_f_));
    }
  Real dydx;
  minimise_least_squares (&dydx, y, ideals); // duh, takes references

  Real dx = last_visible_stem ()->relative_coordinate (0, X_AXIS) - x0;
  *dy = dydx * dx;
}

bool
Beam::suspect_slope_b (Real y, Real dy) const
{
  /* first, calculate y, dy */
  /*
    steep slope running against lengthened stem is suspect
  */
  Real first_ideal = first_visible_stem ()->calc_stem_info ().idealy_f_;
  Real last_ideal = last_visible_stem ()->calc_stem_info ().idealy_f_;
  Real lengthened = paper_l ()->get_var ("beam_lengthened");
  Real steep = paper_l ()->get_var ("beam_steep_slope");

  Real dx = last_visible_stem ()->relative_coordinate (0, X_AXIS) - first_visible_stem ()->relative_coordinate (0, X_AXIS);
  Real dydx = dy && dx ? dy/dx : 0;

  if (((y - first_ideal > lengthened) && (dydx > steep))
      || ((y + dy - last_ideal > lengthened) && (dydx < -steep)))
    {
      return true;
    }
  return false;
}

/*
  This neat trick is by Werner Lemberg,
  damped = tanh (slope)
  corresponds with some tables in [Wanske]
*/
Real
Beam::calc_slope_damping_f (Real dy) const
{
  SCM damp = get_elt_property ("damping"); // remove?
  int damping = 1;		// ugh.
  if (gh_number_p (damp))
    damping = gh_scm2int (damp);

  if (damping)
    {
      Real dx = last_visible_stem ()->relative_coordinate (0, X_AXIS)
	- first_visible_stem ()->relative_coordinate (0, X_AXIS);
      Real dydx = dy && dx ? dy/dx : 0;
      dydx = 0.6 * tanh (dydx) / damping;
      return dydx * dx;
    }
  return dy;
}

Real
Beam::calc_stem_y_f (Stem* s, Real y, Real dy) const
{
  Real thick = gh_scm2double (get_elt_property ("beam-thickness"));
  thick *= paper_l ()->get_var ("staffspace");
  
  int beam_multiplicity = get_multiplicity ();
  int stem_multiplicity = (s->flag_i () - 2) >? 0;

  Real interbeam_f = paper_l ()->interbeam_f (beam_multiplicity);
  Real x0 = first_visible_stem ()->relative_coordinate (0, X_AXIS);
  Real dx = last_visible_stem ()->relative_coordinate (0, X_AXIS) - x0;
  Real stem_y = (dy && dx ? (s->relative_coordinate (0, X_AXIS) - x0) / dx * dy : 0) + y;

  /* knee */
   Direction dir  = Directional_element_interface(this).get ();
   Direction sdir = Directional_element_interface (s).get ();
   
    /* knee */
   if (dir!= sdir)
      {
       stem_y -= dir 
	* (thick / 2 + (beam_multiplicity - 1) * interbeam_f);

      Staff_symbol_referencer_interface me (s);
      Staff_symbol_referencer_interface last (last_visible_stem ());
      
      // huh, why not for first visible?
      if (//(s != first_visible_stem ()) &&
	  me.staff_symbol_l () != last.staff_symbol_l ())
	stem_y += Directional_element_interface (this).get ()
	  * (beam_multiplicity - stem_multiplicity) * interbeam_f;
    }
  return stem_y;
}

Real
Beam::check_stem_length_f (Real y, Real dy) const
{
  Real shorten = 0;
  Real lengthen = 0;
  Direction dir = Directional_element_interface (this).get ();
  
  for (int i=0; i < stem_count (); i++)
    {
      Stem* s = stem (i);
      if (s->invisible_b ())
	continue;

      Real stem_y = calc_stem_y_f (s, y, dy);
	
      stem_y *= dir;
      Stem_info info = s->calc_stem_info ();

      // if (0 > info.maxy_f_ - stem_y)
      shorten = shorten <? info.maxy_f_ - stem_y;
      // if (0 < info.miny_f_ - stem_y)
      lengthen = lengthen >? info.miny_f_ - stem_y; 
    }

  if (lengthen && shorten)
    warning (_ ("weird beam vertical offset"));

  /* when all stems are too short, normal stems win */
  return dir * ((shorten) ?  shorten : lengthen);
}

/*
  Hmm.  At this time, beam position and slope are determined.  Maybe,
  stem directions and length should set to relative to the chord's
  position of the beam.  */
void
Beam::set_stem_length (Real y, Real dy)
{
  Staff_symbol_referencer_interface st (this);
  Real half_space = st.staff_space ()/2;
  for (int i=0; i < stem_count (); i++)
    {
      Stem* s = stem (i);
      if (s->invisible_b ())
	continue;

      Real stem_y = calc_stem_y_f (s, y, dy);

      /* caution: stem measures in staff-positions */
      s->set_stemend ((stem_y + calc_interstaff_dist (s, this)) / half_space);
    }
}

/*
  [Ross] (simplification of)
  Set dy complying with:
    - zero
    - thick / 2 + staffline_f / 2
    - thick + staffline_f
  + n * staff_space
*/
Real
Beam::quantise_dy_f (Real dy) const
{
  Array<Real> a;
  for (SCM s = scm_eval (ly_symbol2scm ("beam-height-quants")); s !=SCM_EOL; s = gh_cdr (s))
    a.push (gh_scm2double (gh_car (s)));
  
  if (a.size () <= 1)
    return dy;

  Staff_symbol_referencer_interface st (this);
  Real staff_space = st.staff_space ();
  
  Interval iv = quantise_iv (a, abs (dy)/staff_space) * staff_space;
  Real q = (abs (dy) - iv[SMALLER] <= iv[BIGGER] - abs (dy))
    ? iv[SMALLER]
    : iv[BIGGER];
  
  return q * sign (dy);
}

/*
  Prevent interference from stafflines and beams.
  See Documentation/tex/fonts.doc

  We only need to quantise the (left) y-position of the beam,
  since dy is quantised too.
  if extend_b then stems must *not* get shorter
 */
Real
Beam::quantise_y_f (Real y, Real dy, int quant_dir)
{
  int multiplicity = get_multiplicity ();
  Staff_symbol_referencer_interface st (this);
  Real staff_space = st.staff_space ();
  SCM quants = scm_eval (gh_list (ly_symbol2scm ("beam-vertical-position-quants"),
				  gh_int2scm (multiplicity),
				  gh_double2scm (dy/staff_space),
				  SCM_UNDEFINED));

  Array<Real> a;

  for (; quants != SCM_EOL; quants = gh_cdr (quants))
    a.push (gh_scm2double (gh_car (quants)));

  if (a.size () <= 1)
    return y;

  Real up_y = Directional_element_interface (this).get () * y;
  Interval iv = quantise_iv (a, up_y/staff_space) * staff_space;

  Real q = up_y - iv[SMALLER] <= iv[BIGGER] - up_y 
    ? iv[SMALLER] : iv[BIGGER];
  if (quant_dir)
    q = iv[(Direction)quant_dir];

  return q * Directional_element_interface (this).get ();
}

void
Beam::set_beaming (Beaming_info_list *beaming)
{
  Direction d = LEFT;
  for (int i=0; i  < stem_count (); i++)
    {
      do
	{
	  if (stem (i)->beam_count (d) == 0)
	    stem (i)->set_beaming ( beaming->infos_.elem (i).beams_i_drul_[d],d);
	}
      while (flip (&d) != LEFT);
    }
}



/*
  beams to go with one stem.

  BURP
  clean  me up.
  */
Molecule
Beam::stem_beams (Stem *here, Stem *next, Stem *prev) const
{
  if ((next && !(next->relative_coordinate (0, X_AXIS) > here->relative_coordinate (0, X_AXIS))) ||
      (prev && !(prev->relative_coordinate (0, X_AXIS) < here->relative_coordinate (0, X_AXIS))))
      programming_error ("Beams are not left-to-right");

  Real staffline_f = paper_l ()->get_var ("stafflinethickness");
  int multiplicity = get_multiplicity ();


  Real interbeam_f = paper_l ()->interbeam_f (multiplicity);
  Real thick = gh_scm2double (get_elt_property ("beam-thickness"));
  thick *= paper_l ()->get_var ("staffspace");
    
  Real bdy = interbeam_f;
  Real stemdx = staffline_f;

  Real dx = visible_stem_count () ?
    last_visible_stem ()->relative_coordinate (0, X_AXIS) - first_visible_stem ()->relative_coordinate (0, X_AXIS)
    : 0.0;
  Real dy = gh_scm2double (get_elt_property ("height"));
  Real dydx = dy && dx ? dy/dx : 0;

  Molecule leftbeams;
  Molecule rightbeams;

  // UGH
  Real nw_f;
  if (!here->first_head ())
    nw_f = 0;
  else if (here->type_i ()== 1)
    nw_f = paper_l ()->get_var ("wholewidth");
  else if (here->type_i () == 2)
    nw_f = paper_l ()->get_var ("notewidth") * 0.8;
  else
    nw_f = paper_l ()->get_var ("quartwidth");


  Direction dir = Directional_element_interface (this).get ();
  
  /* half beams extending to the left. */
  if (prev)
    {
      int lhalfs= lhalfs = here->beam_count (LEFT) - prev->beam_count (RIGHT);
      int lwholebeams= here->beam_count (LEFT) <? prev->beam_count (RIGHT) ;
      /*
       Half beam should be one note-width, 
       but let's make sure two half-beams never touch
       */
      Real w = here->relative_coordinate (0, X_AXIS) - prev->relative_coordinate (0, X_AXIS);
      w = w/2 <? nw_f;
      Molecule a;
      if (lhalfs)		// generates warnings if not
	a =  lookup_l ()->beam (dydx, w, thick);
      a.translate (Offset (-w, -w * dydx));
      for (int j = 0; j  < lhalfs; j++)
	{
	  Molecule b (a);
	  b.translate_axis (-dir * bdy * (lwholebeams+j), Y_AXIS);
	  leftbeams.add_molecule (b);
	}
    }

  if (next)
    {
      int rhalfs  = here->beam_count (RIGHT) - next->beam_count (LEFT);
      int rwholebeams= here->beam_count (RIGHT) <? next->beam_count (LEFT) ;

      Real w = next->relative_coordinate (0, X_AXIS) - here->relative_coordinate (0, X_AXIS);
      Molecule a = lookup_l ()->beam (dydx, w + stemdx, thick);
      a.translate_axis( - stemdx/2, X_AXIS);
      int j = 0;
      Real gap_f = 0;

      SCM gap = get_elt_property ("beam-gap");
      if (gh_number_p (gap))
	{
	  int gap_i = gh_scm2int ( (gap));
	  int nogap = rwholebeams - gap_i;
	  
	  for (; j  < nogap; j++)
	    {
	      Molecule b (a);
	      b.translate_axis (-dir  * bdy * j, Y_AXIS);
	      rightbeams.add_molecule (b);
	    }
	  // TODO: notehead widths differ for different types
	  gap_f = nw_f / 2;
	  w -= 2 * gap_f;
	  a = lookup_l ()->beam (dydx, w + stemdx, thick);
	}

      for (; j  < rwholebeams; j++)
	{
	  Molecule b (a);
	  b.translate (Offset (here->invisible_b () ? 0 : gap_f, -dir * bdy * j));
	  rightbeams.add_molecule (b);
	}

      w = w/2 <? nw_f;
      if (rhalfs)
	a = lookup_l ()->beam (dydx, w, thick);

      for (; j  < rwholebeams + rhalfs; j++)
	{
	  Molecule b (a);
	  b.translate_axis (- dir * bdy * j, Y_AXIS);
	  rightbeams.add_molecule (b);
	}

    }
  leftbeams.add_molecule (rightbeams);

  /*
    Does beam quanting think  of the asymetry of beams? 
    Refpoint is on bottom of symbol. (FIXTHAT) --hwn.
   */
  return leftbeams;
}

GLUE_SCORE_ELEMENT(Beam,brew_molecule);
SCM
Beam::member_brew_molecule () const
{
  Molecule mol;
  if (!stem_count ())
    return SCM_EOL;
  Real x0,dx;
  if (visible_stem_count ())
    {
      x0 = first_visible_stem ()->relative_coordinate (0, X_AXIS);
      dx = last_visible_stem ()->relative_coordinate (0, X_AXIS) - x0;
    }
  else
    {
      x0 = stem (0)->relative_coordinate (0, X_AXIS);
      dx = stem_top ()->relative_coordinate (0, X_AXIS) - x0;
    }
  
  
  Real dy = gh_scm2double (get_elt_property ("height"));
  Real dydx = dy && dx ? dy/dx : 0;
  Real y = gh_scm2double (get_elt_property ("y-position"));
  for (int j=0; j <stem_count (); j++)
    {
      Stem *i = stem (j);
      Stem * prev = (j > 0)? stem (j-1) : 0;
      Stem * next = (j < stem_count ()-1) ? stem (j+1) :0;

      Molecule sb = stem_beams (i, next, prev);
      Real x = i->relative_coordinate (0, X_AXIS)-x0;
      sb.translate (Offset (x, x * dydx + y));
      mol.add_molecule (sb);
    }
  mol.translate_axis (x0 
    - get_bound (LEFT)->relative_coordinate (0, X_AXIS), X_AXIS);

  return mol.create_scheme ();
}

int
Beam::forced_stem_count () const
{
  int f = 0;
  for (int i=0; i < stem_count (); i++)
    {
      Stem *s = stem (i);

      if (s->invisible_b ())
	continue;

      if (((int)s->chord_start_f ()) 
        && (s->get_direction () != s->get_default_dir ()))
        f++;
    }
  return f;
}

/*
  TODO: Fix this class. This is wildly inefficient.
  And it sux.  Yet another array/list 'interface'.
 */
Stem *
Beam::stem (int i) const
{
  return Pointer_group_interface__extract_elements ((Beam*) this, (Stem*) 0, "stems")[i];
}

int
Beam::stem_count () const
{
  Pointer_group_interface gi (this, "stems");
  return gi.count ();
}

Stem*
Beam::stem_top () const
{
  SCM s = get_elt_pointer ("stems");
  
  return gh_pair_p (s) ? dynamic_cast<Stem*> (unsmob_element (gh_car (s))) : 0;
}

/* burp */
int
Beam::visible_stem_count () const
{
  int c = 0;
  for (int i = 0; i < stem_count (); i++)
    {
      if (!stem (i)->invisible_b ())
        c++;
    }
  return c;
}

Stem*
Beam::first_visible_stem () const
{
  for (int i = 0; i < stem_count (); i++)
    {
      Stem* s = stem (i);
      if (!s->invisible_b ())
        return s;
    }
  return 0;
}

Stem*
Beam::last_visible_stem () const
{
  for (int i = stem_count (); i > 0; i--)
    {
      Stem* s = stem (i - 1);
      if (!s->invisible_b ())
        return s;
    }
  return 0;
}


/*
  [TODO]
  handle rest under beam (do_post: beams are calculated now)
  what about combination of collisions and rest under beam.

  Should lookup
    
    rest -> stem -> beam -> interpolate_y_position ()
*/
Real
Beam::rest_collision_callback (Score_element const *rest, Axis a )
{
  assert (a == Y_AXIS);

  Score_element * st = unsmob_element (rest->get_elt_pointer ("stem"));
  Stem * stem  = dynamic_cast<Stem*> (st);
  if (!stem)
    return 0.0;
  Beam * beam = dynamic_cast<Beam*> (unsmob_element (stem->get_elt_pointer ("beam"))); 
  if (!beam || !beam->visible_stem_count ())
    return 0.0;

  // make callback for rest from this.
  Real beam_dy = 0;
  Real beam_y = 0;


  // todo: make sure this calced already.
  SCM s = beam->get_elt_property ("height");
  if (gh_number_p (s))
    beam_dy = gh_scm2double (s);
  
  s = beam->get_elt_property ("y-position");
  if (gh_number_p (s))
    beam_y = gh_scm2double (s);
  
  Real x0 = beam->first_visible_stem ()->relative_coordinate (0, X_AXIS);
  Real dx = beam->last_visible_stem ()->relative_coordinate (0, X_AXIS) - x0;
  Real dydx = beam_dy && dx ? beam_dy/dx : 0;

  Direction d = stem->get_direction ();
  Real beamy = (stem->relative_coordinate (0, X_AXIS) - x0) * dydx + beam_y;

  Staff_symbol_referencer_interface si (rest);

  Real staff_space = si.staff_space ();      
  Real rest_dim = rest->extent (Y_AXIS)[d]*2.0 / staff_space ;

  Real minimum_dist
    = gh_scm2double (rest->get_elt_property ("minimum-beam-collision-distance"));
  Real dist =
    minimum_dist +  -d  * (beamy - rest_dim) >? 0;

  int stafflines = si.line_count ();

  // move discretely by half spaces.
  int discrete_dist = int (ceil (dist));

  // move by whole spaces inside the staff.
  if (discrete_dist < stafflines+1)
    discrete_dist = int (ceil (discrete_dist / 2.0)* 2.0);

  return  (-d *  discrete_dist);
}