]> git.donarmstrong.com Git - lilypond.git/blob - lily/stem.cc
release: 1.5.8
[lilypond.git] / lily / stem.cc
1 /*
2   stem.cc -- implement Stem
3
4   source file of the GNU LilyPond music typesetter
5
6   (c) 1996--2001 Han-Wen Nienhuys <hanwen@cs.uu.nl>
7     Jan Nieuwenhuizen <janneke@gnu.org>
8
9   TODO: This is way too hairy
10 */
11 #include <math.h>               // m_pi
12
13 #include "lookup.hh"
14 #include "directional-element-interface.hh"
15 #include "note-head.hh"
16 #include "stem.hh"
17 #include "debug.hh"
18 #include "paper-def.hh"
19 #include "rhythmic-head.hh"
20 #include "font-interface.hh"
21 #include "molecule.hh"
22 #include "paper-column.hh"
23 #include "misc.hh"
24 #include "beam.hh"
25 #include "rest.hh"
26 #include "group-interface.hh"
27 #include "staff-symbol-referencer.hh"
28 #include "spanner.hh"
29 #include "side-position-interface.hh"
30
31 void
32 Stem::set_beaming (Grob*me ,int i,  Direction d)
33 {
34   SCM pair = me->get_grob_property ("beaming");
35   
36   if (!gh_pair_p (pair))
37     {
38       pair = gh_cons (gh_int2scm (0),gh_int2scm (0));
39       me->      set_grob_property ("beaming", pair);
40     }
41   index_set_cell (pair, d, gh_int2scm (i));
42 }
43
44 int
45 Stem::beam_count (Grob*me,Direction d)
46 {
47   SCM p=me->get_grob_property ("beaming");
48   if (gh_pair_p (p))
49     return gh_scm2int (index_cell (p,d));
50   else
51     return 0;
52 }
53
54 Interval
55 Stem::head_positions (Grob*me) 
56 {
57   if (!heads_i (me))
58     {
59       Interval iv;
60       return iv;
61     }
62
63   Drul_array<Grob*> e (extremal_heads (me));
64
65   return Interval (Staff_symbol_referencer::position_f (e[DOWN]),
66                    Staff_symbol_referencer::position_f (e[UP]));
67 }
68
69
70 Real
71 Stem::chord_start_f (Grob*me) 
72 {
73   return head_positions (me)[get_direction (me)]
74     * Staff_symbol_referencer::staff_space (me)/2.0;
75 }
76
77 Real
78 Stem::stem_end_position (Grob*me) 
79 {
80   SCM p =me->get_grob_property ("stem-end-position");
81   Real pos;
82   if (!gh_number_p (p))
83     {
84
85       pos = get_default_stem_end_position (me);
86       me->set_grob_property ("stem-end-position", gh_double2scm (pos));
87     }
88   else
89     pos = gh_scm2double (p);
90
91   return pos;
92 }
93
94 Direction
95 Stem::get_direction (Grob*me)
96 {
97   Direction d = Directional_element_interface::get (me);
98
99   if (!d)
100     {
101        d = get_default_dir (me);
102        // urg, AAARGH!
103        Directional_element_interface::set (me, d);
104     }
105   return d ;
106 }
107
108
109 void
110 Stem::set_stemend (Grob*me, Real se)
111 {
112   // todo: margins
113   Direction d= get_direction (me);
114   
115   if (d && d * head_positions (me)[get_direction (me)] >= se*d)
116     warning (_ ("Weird stem size; check for narrow beams"));
117
118   me->set_grob_property ("stem-end-position", gh_double2scm (se));
119 }
120
121 int
122 Stem::type_i (Grob*me) 
123 {
124   return first_head (me) ?  Rhythmic_head::balltype_i (first_head (me)) : 2;
125 }
126
127 /*
128   Note head that determines hshift for upstems
129  */ 
130 Grob*
131 Stem::support_head (Grob*me)
132 {
133   SCM h = me->get_grob_property ("support-head");
134   Grob * nh = unsmob_grob (h);
135   if (nh)
136     return nh;
137   else if (heads_i (me) == 1)
138     {
139       /*
140         UGH.
141        */
142       
143       return unsmob_grob (gh_car (me->get_grob_property ("heads")));
144     }
145   else
146     return first_head (me);
147 }
148
149
150 int
151 Stem::heads_i (Grob*me)
152 {
153   return  Pointer_group_interface::count (me, "heads");
154 }
155
156 /*
157   The note head which forms one end of the stem.  
158  */
159 Grob*
160 Stem::first_head (Grob*me)
161 {
162   return extremal_heads (me)[-get_direction (me)];
163 }
164
165 /*
166   START is part where stem reaches `last' head. 
167  */
168 Drul_array<Grob*>
169 Stem::extremal_heads (Grob*me) 
170 {
171   const int inf = 1000000;
172   Drul_array<int> extpos;
173   extpos[DOWN] = inf;
174   extpos[UP] = -inf;  
175   
176   Drul_array<Grob *> exthead;
177   exthead[LEFT] = exthead[RIGHT] =0;
178   
179   for (SCM s = me->get_grob_property ("heads"); gh_pair_p (s); s = gh_cdr (s))
180     {
181       Grob * n = unsmob_grob (gh_car (s));
182
183       
184       int p = int (Staff_symbol_referencer::position_f (n));
185
186       Direction d = LEFT;
187       do {
188       if (d* p > d* extpos[d])
189         {
190           exthead[d] = n;
191           extpos[d] = p;
192         }
193       } while (flip (&d) != DOWN);
194     }
195
196   return exthead;
197 }
198
199 void
200 Stem::add_head (Grob*me, Grob *n)
201 {
202   n->set_grob_property ("stem", me->self_scm ());
203   n->add_dependency (me);
204
205   if (Note_head::has_interface (n))
206     {
207       Pointer_group_interface::add_element (me, "heads",n);
208     }
209   else
210     {
211       n->set_grob_property ("rest", n->self_scm ());
212     }
213 }
214
215 bool
216 Stem::invisible_b (Grob*me)
217 {
218   return ! (heads_i (me) && Rhythmic_head::balltype_i (support_head (me)) >= 1);
219 }
220
221 int
222 Stem::get_center_distance (Grob*me, Direction d)
223 {
224   int staff_center = 0;
225   int distance = (int) (d* (head_positions (me)[d] - staff_center));
226   return distance >? 0;
227 }
228
229 Direction
230 Stem::get_default_dir (Grob*me) 
231 {
232   int du = get_center_distance (me,UP);
233   int dd = get_center_distance (me,DOWN);
234
235   if (sign (dd - du))
236     return Direction (sign (dd -du));
237
238   return to_dir (me->get_grob_property ("neutral-direction"));
239 }
240
241 Real
242 Stem::get_default_stem_end_position (Grob*me) 
243 {
244   bool grace_b = to_boolean (me->get_grob_property ("grace"));
245   SCM s;
246   Array<Real> a;
247
248   Real length_f = 0.;
249   SCM scm_len = me->get_grob_property ("length");
250   if (gh_number_p (scm_len))
251     {
252       length_f = gh_scm2double (scm_len);
253     }
254   else
255     {
256       s = me->get_grob_property ("lengths");
257       for (SCM q = s; q != SCM_EOL; q = gh_cdr (q))
258         a.push (gh_scm2double (gh_car (q)));
259                 
260       // stem uses half-spaces
261       length_f = a[ ((flag_i (me) - 2) >? 0) <? (a.size () - 1)] * 2;
262     }
263
264
265   a.clear ();
266   s = me->get_grob_property ("stem-shorten");
267   for (SCM q = s; gh_pair_p (q); q = gh_cdr (q))
268     a.push (gh_scm2double (gh_car (q)));
269
270
271   // stem uses half-spaces
272
273   // fixme: use gh_list_ref () iso. array[]
274   Real shorten_f = a[ ((flag_i (me) - 2) >? 0) <? (a.size () - 1)] * 2;
275
276   /* URGURGURG
277      'set-default-stemlen' sets direction too
278    */
279   Direction dir = get_direction (me);
280   if (!dir)
281     {
282       dir = get_default_dir (me);
283       Directional_element_interface::set (me, dir);
284     }
285   
286   /* 
287     stems in unnatural (forced) direction should be shortened, 
288     according to [Roush & Gourlay]
289    */
290   if (( (int)chord_start_f (me))
291       && (get_direction (me) != get_default_dir (me)))
292     length_f -= shorten_f;
293
294   Interval hp = head_positions (me);  
295   Real st = hp[dir] + dir * length_f;
296
297
298   
299
300   /*
301     Make a little room if we have a flag and there is a dot.
302
303     TODO:
304
305     maybe  we should consider moving the dot to the right?
306   */
307   if (!beam_l (me)
308       && flag_i (me))
309     {
310       Grob * closest_to_flag = extremal_heads (me)[dir];
311       Grob * dots = closest_to_flag
312         ? Rhythmic_head::dots_l (closest_to_flag ) : 0;
313
314       if (dots)
315         {
316           Real dp = Staff_symbol_referencer::position_f  (dots);
317           Real flagy =  flag (me).extent (Y_AXIS)[-dir] * 2; // should divide by staffspace
318
319           /*
320             Very gory: add myself to the X-support of the parent,
321             which should be a dot-column.
322            */
323           if (dir * (st + flagy -  dp) < 0.5)
324             Side_position_interface::add_support (dots->parent_l (X_AXIS), me);
325
326           /*
327             previous approach was to lengthen the stem. This is not
328             good typesetting practice.  */
329         }
330     }
331
332
333   bool no_extend_b = to_boolean (me->get_grob_property ("no-stem-extend"));
334    if (!grace_b && !no_extend_b && dir * st < 0) // junkme?
335       st = 0.0;
336
337   return st;
338 }
339
340 /*
341   Number of hooks on the flag, ie. the log of the duration.
342  */
343 int
344 Stem::flag_i (Grob*me) 
345 {
346   SCM s = me->get_grob_property ("duration-log");
347   return (gh_number_p (s)) ? gh_scm2int (s) : 2;
348 }
349
350 void
351 Stem::position_noteheads (Grob*me)
352 {
353   if (!heads_i (me))
354     return;
355   
356   Link_array<Grob> heads =
357     Pointer_group_interface__extract_elements (me, (Grob*)0, "heads");
358
359   heads.sort (compare_position);
360   Direction dir =get_direction (me);
361   
362   if (dir < 0)
363     heads.reverse ();
364
365
366   Grob *hed = support_head (me);
367   Real w = hed->extent (hed, X_AXIS)[dir];
368   for (int i=0; i < heads.size (); i++)
369     {
370       heads[i]->translate_axis (w - heads[i]->extent (heads[i], X_AXIS)[dir], X_AXIS);
371     }
372   
373   bool parity= true;            // todo: make me settable.
374   int lastpos = int (Staff_symbol_referencer::position_f (heads[0]));
375   for (int i=1; i < heads.size (); i ++)
376     {
377       Real p = Staff_symbol_referencer::position_f (heads[i]);
378       int dy =abs (lastpos- (int)p);
379
380       if (dy <= 1)
381         {
382           if (parity)
383             {
384               Real l = heads[i]->extent (heads[i], X_AXIS).length ();
385               heads[i]->translate_axis (l * get_direction (me), X_AXIS);
386             }
387           parity = !parity;
388         }
389       else
390         parity = true;
391       
392       lastpos = int (p);
393     }
394 }
395
396 MAKE_SCHEME_CALLBACK (Stem,before_line_breaking,1);
397 SCM
398 Stem::before_line_breaking (SCM smob)
399 {
400   Grob*me = unsmob_grob (smob);
401   stem_end_position (me);       // ugh. Trigger direction calc.
402   position_noteheads (me);
403
404   if (invisible_b (me))
405     {
406       me->remove_grob_property ("molecule-callback");
407       // suicide ();
408     }
409   
410   set_spacing_hints (me);
411   return SCM_UNSPECIFIED;
412 }
413
414
415 /*
416   ugh.
417   When in a beam with tuplet brackets, brew_mol is called early,
418   caching a wrong value.
419  */
420 MAKE_SCHEME_CALLBACK (Stem, height, 2);
421 SCM
422 Stem::height (SCM smob, SCM ax)
423 {
424   Axis a = (Axis)gh_scm2int (ax);
425   Grob * me = unsmob_grob (smob);
426   assert (a == Y_AXIS);
427
428   SCM mol = me->get_uncached_molecule ();
429   Interval iv;
430   if (mol != SCM_EOL)
431     iv = unsmob_molecule (mol)->extent (a);
432   return ly_interval2scm (iv);
433 }
434
435
436 /**
437    set stem directions for hinting the optical spacing correction.
438
439    Modifies DIR_LIST property of the Stem's Paper_column
440
441    TODO: more advanced: supply height of noteheads as well, for more advanced spacing possibilities
442  */
443 void
444 Stem::set_spacing_hints (Grob*me) 
445 {
446   if (!invisible_b (me))
447     {
448       SCM scmdir  = gh_int2scm (get_direction (me));
449
450       Item* item = dynamic_cast<Item*> (me);
451       Item * col =  item->column_l ();
452       SCM dirlist =col->get_grob_property ("dir-list");
453       if (scm_c_memq (scmdir, dirlist) == SCM_BOOL_F)
454         {
455           dirlist = gh_cons (scmdir, dirlist);
456           col->set_grob_property ("dir-list", dirlist);
457         }
458     }
459 }
460
461 Molecule
462 Stem::flag (Grob*me)
463 {
464   // TODO: rename flag-style into something more appropriate,
465   // e.g. "stroke-style", maybe with values "" (i.e. no stroke),
466   // "single" and "double".  Needs more discussion.
467   String style, fstyle, stafflineOffs;
468   SCM fst = me->get_grob_property ("flag-style");
469   if (gh_string_p (fst))
470     {
471       fstyle = ly_scm2string (fst);
472     }
473
474   SCM st = me->get_grob_property ("style");
475   if (gh_symbol_p (st))
476     {
477       style = (ly_scm2string (scm_symbol_to_string (st)));
478     }
479   else
480     {
481       style = "";
482     }
483   if (String::compare_i (style, "mensural") == 0)
484       // Mensural notation: For notes on staff lines, use different
485       // flags than for notes between staff lines.  The idea is that
486       // flags are always vertically aligned with the staff lines,
487       // regardless if the note head is on a staff line or between two
488       // staff lines.  In other words, the inner end of a flag always
489       // touches a staff line.
490     {
491         // Urrgh!  We have to detect wether this stem ends on a staff
492         // line or between two staff lines.  But we can not call
493         // stem_end_position(me) or get_default_stem_end_position(me),
494         // since this encounters the flag and hence results in an
495         // infinite recursion.  However, in pure mensural notation,
496         // there are no multiple note heads attached to a single stem,
497         // neither is there usually need for using the stem_shorten
498         // property (except for 32th and 64th notes, but that is not a
499         // problem since the stem length in this case is augmented by
500         // an integral multiple of staff_space).  Hence, it should be
501         // sufficient to just take the first note head, assume it's
502         // the only one, look if it's on a staff line, and select the
503         // flag's shape accordingly.  In the worst case, the shape
504         // looks slightly misplaced, but that will usually be the
505         // programmer's fault (e.g. when trying to attach multiple
506         // note heads to a single stem in mensural notation).
507         Grob *firstHead = first_head(me);
508         int sz = Staff_symbol_referencer::line_count (me)-1;
509         int p = (int)rint (Staff_symbol_referencer::position_f (firstHead));
510         stafflineOffs = (((p ^ sz) & 0x1) == 0) ? "1" : "0";
511     }
512   else
513     {
514         stafflineOffs = "";
515     }
516   char c = (get_direction (me) == UP) ? 'u' : 'd';
517   Molecule m =
518       Font_interface::get_default_font (me)->
519       find_by_name (String ("flags-") + style + to_str (c) + stafflineOffs +
520                     to_str (flag_i (me)));
521   if (!fstyle.empty_b ())
522     m.add_molecule (Font_interface::get_default_font (me)->find_by_name (String ("flags-") + to_str (c) + fstyle));
523   return m;
524 }
525
526 MAKE_SCHEME_CALLBACK (Stem,dim_callback,2);
527 SCM
528 Stem::dim_callback (SCM e, SCM ax)
529 {
530   Axis a = (Axis) gh_scm2int (ax);
531   assert (a == X_AXIS);
532   Grob *se = unsmob_grob (e);
533   Interval r (0, 0);
534   if (unsmob_grob (se->get_grob_property ("beam")) || abs (flag_i (se)) <= 2)
535     ;   // TODO!
536   else
537     {
538       r = flag (se).extent (X_AXIS);
539     }
540   return ly_interval2scm (r);
541 }
542  
543
544
545 MAKE_SCHEME_CALLBACK (Stem,brew_molecule,1);
546
547 SCM
548 Stem::brew_molecule (SCM smob) 
549 {
550   Grob*me = unsmob_grob (smob);
551   Molecule mol;
552   Direction d = get_direction (me);
553   
554   
555   Real y1 = Staff_symbol_referencer::position_f (first_head (me));
556   Real y2 = stem_end_position (me);
557   
558   Interval stem_y (y1,y2);
559   stem_y.unite (Interval (y2,y1));
560
561   // dy?
562   Real dy = Staff_symbol_referencer::staff_space (me)/2.0;
563     
564   if (Grob *hed = support_head (me))
565     {
566       Interval head_height = hed->extent (hed,Y_AXIS);
567       Real y_attach = Note_head::stem_attachment_coordinate ( hed, Y_AXIS);
568
569       y_attach = head_height.linear_combination (y_attach);
570       stem_y[Direction (-d)] += d * 2*y_attach;
571     }
572   
573   if (!invisible_b (me))
574     {
575       Real stem_width = gh_scm2double (me->get_grob_property ("thickness"))
576         // URG
577         * me->paper_l ()->get_var ("stafflinethickness");
578       
579       Molecule ss =Lookup::filledbox (Box (Interval (-stem_width/2, stem_width/2),
580                                            Interval (stem_y[DOWN]*dy, stem_y[UP]*dy)));
581       mol.add_molecule (ss);
582     }
583
584   if (!beam_l (me) && abs (flag_i (me)) > 2)
585     {
586       Molecule fl = flag (me);
587       fl.translate_axis (stem_y[d]*dy, Y_AXIS);
588       mol.add_molecule (fl);
589     }
590
591   return mol.smobbed_copy ();
592 }
593
594 /*
595   move the stem to right of the notehead if it is up.
596  */
597 MAKE_SCHEME_CALLBACK (Stem,off_callback,2);
598 SCM
599 Stem::off_callback (SCM element_smob, SCM)
600 {
601   Grob *me = unsmob_grob (element_smob);
602   
603   Real r=0;
604   if (Grob * f = first_head (me))
605     {
606       Interval head_wid = f->extent (f,X_AXIS);
607
608       Real attach =
609         Note_head::stem_attachment_coordinate(f, X_AXIS);
610
611       Direction d = get_direction (me);
612
613       Real real_attach = head_wid.linear_combination (d * attach);
614
615       r = real_attach;
616
617       /*
618         If not centered: correct for stem thickness.
619        */
620       if (attach)
621         {
622           Real rule_thick
623             = gh_scm2double (me->get_grob_property ("thickness"))
624             * me->paper_l ()->get_var ("stafflinethickness");
625
626           
627           r += - d * rule_thick * 0.5;
628         }
629     }
630   return gh_double2scm (r);
631 }
632
633
634
635 Grob*
636 Stem::beam_l (Grob*me)
637 {
638   SCM b=  me->get_grob_property ("beam");
639   return unsmob_grob (b);
640 }
641
642
643 // ugh still very long.
644 Stem_info
645 Stem::calc_stem_info (Grob*me) 
646 {
647   Grob * beam = beam_l (me);
648
649   Direction beam_dir = Directional_element_interface::get (beam);
650   if (!beam_dir)
651     {
652       programming_error ("Beam dir not set.");
653       beam_dir = UP;
654     }
655     
656
657   Real staff_space = Staff_symbol_referencer::staff_space (me);
658   Real half_space = staff_space / 2;
659   int multiplicity = Beam::get_multiplicity (beam);
660
661
662   SCM space_proc = beam->get_grob_property ("space-function");
663   SCM space = gh_call1 (space_proc, gh_int2scm (multiplicity));
664   Real interbeam_f = gh_scm2double (space) * staff_space;
665
666   Real thick = gh_scm2double (beam->get_grob_property ("thickness"));
667   Stem_info info; 
668   info.idealy_f_ = chord_start_f (me);
669
670   // for simplicity, we calculate as if dir == UP
671   info.idealy_f_ *= beam_dir;
672   SCM grace_prop = me->get_grob_property ("grace");
673
674   bool grace_b = to_boolean (grace_prop);
675   
676   Array<Real> a;
677   SCM s;
678   
679   s = me->get_grob_property ("beamed-minimum-lengths");
680   a.clear ();
681   for (SCM q = s; q != SCM_EOL; q = gh_cdr (q))
682     a.push (gh_scm2double (gh_car (q)));
683
684
685   Real minimum_length = a[multiplicity <? (a.size () - 1)] * staff_space;
686   s = me->get_grob_property ("beamed-lengths");
687
688   a.clear ();
689   for (SCM q = s; q != SCM_EOL; q = gh_cdr (q))
690     a.push (gh_scm2double (gh_car (q)));
691
692   Real stem_length =  a[multiplicity <? (a.size () - 1)] * staff_space;
693
694   if (!beam_dir || (beam_dir == Directional_element_interface::get (me)))
695     /* normal beamed stem */
696     {
697       if (multiplicity)
698         {
699           info.idealy_f_ += thick + (multiplicity - 1) * interbeam_f;
700         }
701       info.miny_f_ = info.idealy_f_;
702       info.maxy_f_ = INT_MAX;
703
704       info.idealy_f_ += stem_length;
705       info.miny_f_ += minimum_length;
706
707       /*
708         lowest beam of (UP) beam must never be lower than second staffline
709
710         Hmm, reference (Wanske?)
711
712         Although this (additional) rule is probably correct,
713         I expect that highest beam (UP) should also never be lower
714         than middle staffline, just as normal stems.
715         
716       */
717       bool no_extend_b = to_boolean (me->get_grob_property ("no-stem-extend"));
718       if (!grace_b && !no_extend_b)
719         {
720           /* highest beam of (UP) beam must never be lower than middle
721              staffline
722              lowest beam of (UP) beam must never be lower than second staffline
723            */
724           info.miny_f_ =
725             info.miny_f_ >? 0
726             >? (- 2 * half_space - thick
727                 + (multiplicity > 0) * thick
728                 + interbeam_f * (multiplicity - 1));
729         }
730     }
731   else
732     /* knee */
733     {
734       info.idealy_f_ -= thick;
735       info.maxy_f_ = info.idealy_f_;
736       info.miny_f_ = -INT_MAX;
737
738       info.idealy_f_ -= stem_length;
739       info.maxy_f_ -= minimum_length;
740     }
741   
742   info.idealy_f_ = (info.maxy_f_ <? info.idealy_f_) >? info.miny_f_;
743
744   s = beam->get_grob_property ("shorten");
745   if (gh_number_p (s))
746     info.idealy_f_ -= gh_scm2double (s);
747
748  Grob *common = me->common_refpoint (beam, Y_AXIS);
749   Real interstaff_f = beam_dir *
750  (me->relative_coordinate (common, Y_AXIS)
751      - beam->relative_coordinate (common, Y_AXIS));
752
753   info.idealy_f_ += interstaff_f;
754   info.miny_f_ += interstaff_f;
755   info.maxy_f_ += interstaff_f ;
756
757   return info;
758 }
759
760 bool
761 Stem::has_interface (Grob*m)
762 {
763   return m && m->has_interface (ly_symbol2scm ("stem-interface"));
764 }
765
766 void
767 Stem::set_interface (Grob*me)
768 {    
769   me->set_interface (ly_symbol2scm ("stem-interface"));
770 }