]> git.donarmstrong.com Git - lilypond.git/blob - lily/slur-scoring.cc
(scm_from_double): more compat glue.
[lilypond.git] / lily / slur-scoring.cc
1 /*
2   slur-quanting.cc -- Score based slur formatting
3
4   source file of the GNU LilyPond music typesetter
5
6   (c) 1996--2004 Han-Wen Nienhuys <hanwen@cs.uu.nl>
7   Jan Nieuwenhuizen <janneke@gnu.org>
8 */
9
10 #include <math.h>
11
12 #include "accidental-interface.hh"
13 #include "beam.hh"
14 #include "directional-element-interface.hh"
15 #include "group-interface.hh"
16 #include "libc-extension.hh"
17 #include "lily-guile.hh"
18 #include "slur.hh"
19 #include "note-column.hh"
20 #include "output-def.hh"
21 #include "pitch.hh"
22 #include "bezier.hh"
23 #include "spanner.hh"
24 #include "staff-symbol-referencer.hh"
25 #include "staff-symbol.hh"
26 #include "stem.hh"
27 #include "warn.hh"
28 #include "paper-column.hh"
29
30
31 struct Slur_score
32 {
33   Drul_array<Offset> attachment_;
34   Real score_;
35   Bezier curve_;
36
37 #if DEBUG_SLUR_QUANTING
38   String score_card_;
39 #endif
40
41   Slur_score()
42   {
43     score_ = 0.0;
44   }
45 };
46
47 /*
48   TODO: put in details property.,
49
50   use lowercase.
51 */
52 struct Slur_score_parameters
53 {
54   int region_size_;
55   Real head_encompass_penalty_;
56   Real stem_encompass_penalty_;
57   Real closeness_factor_;
58   Real edge_attraction_factor_;
59   Real same_slope_penalty_;
60   Real steeper_slope_factor_;
61   Real non_horizontal_penalty_;
62   Real max_slope_;
63   Real max_slope_factor_;
64   Real extra_object_collision_;
65   Real accidental_collision_;
66   Real free_head_distance_;
67   Real extra_encompass_free_distance_;
68   Slur_score_parameters (Grob*);
69 };
70
71 /*
72   TODO:
73
74   - curve around flag for y coordinate
75   - better scoring.
76   - short-cut: try a smaller region first.
77   - collisions with accidentals
78   - collisions with articulations (staccato, portato, sforzato, ...)
79   - handle non-visible stems better.
80 */
81 struct Encompass_info
82 {
83   Real x_;
84   Real stem_;
85   Real head_;
86   Encompass_info ()
87   {
88     x_ = 0.0;
89     stem_ = 0.0;
90     head_ = 0.0;
91   }
92 };
93
94 struct Bound_info
95 {
96   Box stem_extent_;
97   Direction stem_dir_;
98   Item *bound_;
99   Grob *note_column_;
100   Grob *slur_head_;
101   Grob *staff_;
102   Grob *stem_;
103   Interval slur_head_extent_;
104   Real neighbor_y_;
105   Real staff_space_;
106
107   Bound_info ()
108   {
109     stem_ = 0;
110     neighbor_y_ = 0;
111     staff_ = 0;
112     slur_head_ = 0;
113     stem_dir_ = CENTER;
114     note_column_ = 0;
115   }
116 };
117
118 /*
119   TODO: create one object for passing all parameters.
120  */
121
122
123 static void
124 score_extra_encompass (Grob *me, Grob *common[],
125                        Slur_score_parameters *score_param,
126                        Drul_array<Bound_info> ,
127                        Drul_array<Offset> ,
128                        Array<Slur_score> * scores);
129 static void score_slopes (Grob *me, Grob *common[],
130                           Slur_score_parameters *score_param,
131                           Drul_array<Bound_info>,
132                           Drul_array<Offset> base_attach,
133                           Array<Slur_score> *scores);
134
135 static void score_edges (Grob *me, Grob *common[],
136                          Slur_score_parameters *score_param,
137                          Drul_array<Bound_info> extremes,
138                          Drul_array<Offset> base_attach,
139                          Array<Slur_score> *scores);
140 static void score_encompass (Grob *me, Grob *common[],
141                              Slur_score_parameters*,
142                              Drul_array<Bound_info>,
143                              Drul_array<Offset>, Array<Slur_score> *scores);
144 static Bezier avoid_staff_line (Grob *me, Grob **common,
145                                 Drul_array<Bound_info> extremes,
146                                 Bezier bez);
147
148 static Encompass_info get_encompass_info (Grob *me,
149                                           Grob *col,
150                                           Grob **common);
151 static Bezier get_bezier (Grob *me, 
152                           Grob **common,
153                           Slur_score_parameters*,
154                           Drul_array<Bound_info> extremes,
155                           Drul_array<Offset> attachments,
156                           Real r_0, Real h_inf);
157 static Direction get_default_dir (Grob *me);
158
159 static void set_end_points (Grob *);
160 static Real broken_trend_y (Grob *me, Grob **, Direction dir);
161 static Drul_array<Bound_info> get_bound_info (Spanner *me, Grob **common);
162
163 static void generate_curves (Grob *me, 
164                              Grob *common[],Slur_score_parameters*,
165                              Drul_array<Bound_info> extremes,
166                              Drul_array<Offset> base_attach,
167                              Array<Slur_score> *scores);
168 static Array<Slur_score> enumerate_attachments
169 (Grob *me, Grob *common[], Slur_score_parameters*,
170  Drul_array<Bound_info> extremes,
171  Drul_array<Offset> base_attachment, Drul_array<Real> end_ys);
172 static Drul_array<Offset> get_base_attachments
173 (Spanner *sp, Grob **common, Drul_array<Bound_info> extremes);
174 static Drul_array<Real> get_y_attachment_range
175 (Spanner *sp, Grob **common,
176  Slur_score_parameters*,
177  Drul_array<Bound_info> extremes,
178  Drul_array<Offset> base_attachment);
179
180
181 Real
182 get_detail (SCM alist, SCM sym)
183 {
184   SCM entry = scm_assq (sym, alist);
185   return robust_scm2double (ly_c_pair_p (entry)
186                             ? ly_cdr (entry) 
187                             : SCM_EOL,
188                             0.0);
189 }
190
191 void
192 init_score_param (Grob *me,
193                   Slur_score_parameters *score_param)
194 {
195   SCM details = me->get_property ("slur-details");
196   
197   score_param->region_size_ 
198     = (int) get_detail (details, ly_symbol2scm ("region-size"));
199   score_param->head_encompass_penalty_ 
200     = get_detail (details, ly_symbol2scm ("head-encompass-penalty"));
201   score_param->stem_encompass_penalty_ 
202     = get_detail (details, ly_symbol2scm ("stem-encompass-penalty"));
203   score_param->closeness_factor_ 
204     = get_detail (details, ly_symbol2scm ("closeness-factor"));
205   score_param->edge_attraction_factor_ 
206     = get_detail (details, ly_symbol2scm ("edge-attraction-factor"));
207   score_param->same_slope_penalty_ 
208     = get_detail (details, ly_symbol2scm ("same-slope-penalty"));
209   score_param->steeper_slope_factor_ 
210     = get_detail (details, ly_symbol2scm ("steeper-slope-factor"));
211   score_param->non_horizontal_penalty_ 
212     = get_detail (details, ly_symbol2scm ("non-horizontal-penalty"));
213   score_param->max_slope_ 
214     = get_detail (details, ly_symbol2scm ("max-slope"));
215   score_param->max_slope_factor_ 
216     = get_detail (details, ly_symbol2scm ("max-slope-factor"));
217   score_param->free_head_distance_ 
218     = get_detail (details, ly_symbol2scm ("free-head-distance"));
219   score_param->extra_object_collision_ 
220     = get_detail (details, ly_symbol2scm ("extra-object-collision"));
221   score_param->accidental_collision_ 
222     = get_detail (details, ly_symbol2scm ("accidental-collision"));
223   score_param->extra_encompass_free_distance_ 
224     = get_detail (details, ly_symbol2scm ("extra-encompass-free-distance"));
225 }
226
227
228 Slur_score_parameters::Slur_score_parameters(Grob *me)
229 {
230   init_score_param (me, this);
231 }
232
233 /* HDIR indicates the direction for the slur.  */
234 Real
235 broken_trend_y (Grob *me, Grob **common, Direction hdir)
236 {
237   /* A broken slur should maintain the same vertical trend
238      the unbroken slur would have had.  */
239   Real by = 0.0;
240   if (Spanner *mother = dynamic_cast<Spanner*> (me->original_))
241     {
242       int k = broken_spanner_index (dynamic_cast<Spanner*> (me));
243       int j = k + hdir;
244       if (j < 0 || j >= mother->broken_intos_.size ())
245         return by;
246
247       Grob *neighbor = mother->broken_intos_[j];
248       if (hdir == RIGHT)
249         neighbor->set_property ("direction",
250                                 me->get_property ("direction"));
251
252       Spanner *common_mother
253         = dynamic_cast<Spanner*> (common[Y_AXIS]->original_);
254       int common_k
255         = broken_spanner_index (dynamic_cast<Spanner*> (common[Y_AXIS]));
256       int common_j = common_k + hdir;
257
258       if (common_j < 0 || common_j >= common_mother->broken_intos_.size())
259         return by;
260
261       Grob *common_next_system = common_mother->broken_intos_[common_j];
262       Link_array<Grob> neighbor_cols
263         = Pointer_group_interface__extract_grobs (neighbor, (Grob *)0,
264                                                   "note-columns");
265
266       Grob *neighbor_col
267         = (hdir == RIGHT) ? neighbor_cols[0] : neighbor_cols.top ();
268       Grob *neighbor_common
269         = common_next_system->common_refpoint (neighbor_col, Y_AXIS);
270
271       Direction vdir = get_grob_direction (me);
272       Real neighbor_y
273         = neighbor_col->extent (neighbor_common, Y_AXIS)
274         .linear_combination (int(neighbor_cols.size()==1 ? CENTER : vdir))
275         - common_next_system->relative_coordinate (neighbor_common, Y_AXIS);
276
277       Link_array<Grob> my_cols
278         = Pointer_group_interface__extract_grobs (me, (Grob *)0,
279                                                   "note-columns");
280
281       Grob *extreme_col = (hdir == RIGHT) ? my_cols.top() : my_cols[0];
282       Real y = extreme_col->extent (common[Y_AXIS], Y_AXIS)
283         .linear_combination (int ((my_cols.size() == 1) ? CENTER : vdir));
284       by = (y*neighbor_cols.size() + neighbor_y*my_cols.size()) /
285         (my_cols.size() + neighbor_cols.size());
286     }
287   return by;
288 }
289
290 Encompass_info
291 get_encompass_info (Grob *me,
292                     Grob *col,
293                     Grob **common)
294 {
295   Grob *stem = unsmob_grob (col->get_property ("stem"));
296   Encompass_info ei;
297   Direction dir = get_grob_direction (me);
298
299   if (!stem)
300     {
301       programming_error ("No stem for note column?");
302       ei.x_ = col->relative_coordinate (common[X_AXIS], X_AXIS);
303       ei.head_ = ei.stem_ = col->extent (common[Y_AXIS],
304                                          Y_AXIS)[get_grob_direction (me)];
305       return ei;
306     }
307   Direction stem_dir = get_grob_direction (stem);
308
309   if (Grob *head = Note_column::first_head (col))
310     ei.x_ = head->extent (common[X_AXIS], X_AXIS).center ();
311   else
312     ei.x_ = col->extent (common[X_AXIS], X_AXIS).center ();
313
314   Grob *h = Stem::extremal_heads (stem)[Direction (dir)];
315   if (!h)
316     {
317       ei.head_ = ei.stem_ = col->extent (common[Y_AXIS], Y_AXIS)[dir];
318       return ei;
319     }
320
321   ei.head_ = h->extent (common[Y_AXIS], Y_AXIS)[dir];
322
323   if ((stem_dir == dir)
324       && !stem->extent (stem, Y_AXIS).is_empty ())
325     {
326       ei.stem_ = stem->extent (common[Y_AXIS], Y_AXIS)[dir];
327       if (Grob *b = Stem::get_beam (stem))
328         ei.stem_ += stem_dir * 0.5 * Beam::get_thickness (b);
329
330       Interval x = stem->extent (common[X_AXIS], X_AXIS);
331       ei.x_ = x.is_empty ()
332         ? stem->relative_coordinate (common[X_AXIS], X_AXIS)
333         : x.center ();
334     }
335   else
336     ei.stem_ = ei.head_;
337
338   return ei;
339 }
340
341
342 Direction
343 get_default_dir (Grob*me)
344 {
345   Link_array<Grob> encompasses
346     = Pointer_group_interface__extract_grobs (me, (Grob*) 0, "note-columns");
347
348   Direction d = DOWN;
349   for (int i= 0; i < encompasses.size (); i ++)
350     {
351       if (Note_column::dir (encompasses[i]) < 0)
352         {
353           d = UP;
354           break;
355         }
356     }
357   return d;
358 }
359
360
361
362 MAKE_SCHEME_CALLBACK (Slur, after_line_breaking,1);
363 SCM
364 Slur::after_line_breaking (SCM smob)
365 {
366   Spanner *me = dynamic_cast<Spanner*> (unsmob_grob (smob));
367   if (!scm_ilength (me->get_property ("note-columns")))
368     {
369       me->suicide ();
370       return SCM_UNSPECIFIED;
371     }
372
373   if (!get_grob_direction (me))
374     set_grob_direction (me, get_default_dir (me));
375
376   if (scm_ilength (me->get_property ("control-points")) < 4)
377     set_end_points (me);
378
379   return SCM_UNSPECIFIED;
380 }
381
382 Drul_array<Bound_info>
383 get_bound_info (Spanner* me, Grob **common)
384 {
385   Drul_array<Bound_info> extremes;
386   Direction d = LEFT;
387   Direction dir = get_grob_direction (me);
388
389   do
390     {
391       extremes[d].bound_ = me->get_bound (d);
392       if (Note_column::has_interface (extremes[d].bound_))
393         {
394           extremes[d].note_column_ = extremes[d].bound_;
395           extremes[d].stem_ = Note_column::get_stem (extremes[d].note_column_);
396           extremes[d].stem_dir_ = get_grob_direction (extremes[d].stem_);
397           extremes[d].stem_extent_[X_AXIS]
398             = extremes[d].stem_->extent (common[X_AXIS], X_AXIS);
399           extremes[d].stem_extent_[Y_AXIS]
400             = extremes[d].stem_->extent (common[Y_AXIS], Y_AXIS);
401           extremes[d].slur_head_
402             = Stem::extremal_heads (extremes[d].stem_)[dir];
403           if (!extremes[d].slur_head_
404               && Note_column::has_rests (extremes[d].bound_))
405             {
406               extremes[d].slur_head_ = Note_column::get_rest (extremes[d].bound_);
407             }
408
409           if (extremes[d].slur_head_)
410             extremes[d].slur_head_extent_
411               = extremes[d].slur_head_->extent (common[X_AXIS], X_AXIS);
412
413           extremes[d].staff_ = Staff_symbol_referencer
414             ::get_staff_symbol (extremes[d].stem_);
415           extremes[d].staff_space_ = Staff_symbol_referencer
416             ::staff_space (extremes[d].stem_);
417         }
418       else
419         extremes[d].neighbor_y_ = broken_trend_y (me, common, d);
420     }
421   while (flip (&d) != LEFT);
422   return extremes;
423 }
424
425 void
426 set_end_points (Grob *me)
427 {
428
429   
430   
431   Link_array<Grob> columns
432     = Pointer_group_interface__extract_grobs (me, (Grob *) 0, "note-columns");
433
434   if (columns.is_empty ())
435     {
436       me->suicide ();
437       return;
438     }
439
440   SCM eltlist = me->get_property ("note-columns");
441   SCM extra_list = me->get_property ("encompass-objects");
442   Spanner *sp = dynamic_cast<Spanner*> (me);
443
444   Grob *common[] = {0, 0};
445   for (int i = X_AXIS; i < NO_AXES; i++)
446     {
447       Axis a = (Axis)i;
448       common[a] = common_refpoint_of_list (eltlist, me, a);
449       common[a] = common_refpoint_of_list (extra_list, common[a], a);
450     }
451
452   common[X_AXIS] = common[X_AXIS]->common_refpoint (sp->get_bound (RIGHT),
453                                                     X_AXIS);
454   common[X_AXIS] = common[X_AXIS]->common_refpoint (sp->get_bound (LEFT),
455                                                     X_AXIS);
456
457   Drul_array<Bound_info> extremes = get_bound_info (sp, common);
458   Drul_array<Offset> base_attachment
459     = get_base_attachments (sp, common, extremes);
460   Slur_score_parameters params (me);
461   Drul_array<Real> end_ys
462     = get_y_attachment_range (sp, common, &params, extremes, base_attachment);
463   Array<Slur_score> scores = enumerate_attachments (me, common, &params,
464                                                     extremes, base_attachment,
465                                                     end_ys);
466
467   generate_curves (me, common, &params, extremes, base_attachment, &scores);
468   score_edges (me, common, &params,extremes, base_attachment, &scores);
469   score_slopes (me, common, &params,extremes, base_attachment, &scores);
470   score_encompass (me, common, &params,extremes, base_attachment, &scores);
471   score_extra_encompass (me, common, &params,extremes, base_attachment,
472                          &scores);
473
474   Real opt = 1e6;
475   int opt_idx = 0;
476   // why backwards?
477   for (int i = scores.size (); i--;)
478     {
479       if (scores[i].score_ < opt)
480         {
481           opt = scores[i].score_;
482           opt_idx = i;
483         }
484     }
485
486 #if DEBUG_SLUR_QUANTING
487   SCM inspect_quants = me->get_property ("inspect-quants");
488   if (to_boolean (me->get_paper ()
489                   ->lookup_variable (ly_symbol2scm ("debug-slur-quanting")))
490       && ly_c_pair_p (inspect_quants))
491     {
492       Drul_array<Real> ins = ly_scm2interval (inspect_quants);
493       Real mindist = 1e6;
494       for (int i = 0; i < scores.size (); i ++)
495         {
496           Real d =fabs (scores[i].attachment_[LEFT][Y_AXIS] - ins[LEFT])
497             + fabs (scores[i].attachment_[RIGHT][Y_AXIS] - ins[RIGHT]);
498           if (d < mindist)
499             {
500               opt_idx = i;
501               mindist= d;
502             }
503         }
504       if (mindist > 1e5)
505         programming_error ("Could not find quant.");
506     }
507   scores[opt_idx].score_card_ += to_string ("i%d", opt_idx);
508
509   // debug quanting
510   me->set_property ("quant-score",
511                     scm_makfrom0str (scores[opt_idx].score_card_.to_str0 ()));
512 #endif
513
514   Bezier b = scores[opt_idx].curve_;
515   SCM controls = SCM_EOL;
516   for (int i = 4; i--;)
517     {
518       Offset o = b.control_[i]
519         - Offset (me->relative_coordinate (common[X_AXIS], X_AXIS),
520                   me->relative_coordinate (common[Y_AXIS], Y_AXIS));
521       controls = scm_cons (ly_offset2scm (o), controls);
522     }
523   me->set_property ("control-points", controls);
524 }
525
526 /*
527   TODO: should analyse encompasses to determine sensible region, and
528   should limit slopes available. 
529  */
530
531 Drul_array<Real>
532 get_y_attachment_range (Spanner*me,
533                         Grob **common, Slur_score_parameters *score_param,
534                         Drul_array<Bound_info> extremes,
535                         Drul_array<Offset> base_attachment)
536 {
537   Drul_array<Real> end_ys;
538   Direction dir = get_grob_direction (me);
539   Direction d = LEFT;
540   do
541     {
542       if (extremes[d].note_column_)
543         {
544           end_ys[d] = dir
545             * ((dir * (base_attachment[d][Y_AXIS] +  score_param->region_size_* dir))
546                >? (dir * (dir + extremes[d].note_column_->extent(common[Y_AXIS],
547                                                                  Y_AXIS)[dir]))
548                >? (dir * base_attachment[-d][Y_AXIS]));
549         }
550       else
551         end_ys[d] = extremes[d].neighbor_y_ + score_param->region_size_ * dir;
552     }
553   while (flip (&d) != LEFT);
554
555   return end_ys;
556 }
557
558 bool
559 spanner_less (Spanner *s1, Spanner* s2)
560 {
561   Slice b1, b2;
562   Direction d  = LEFT;
563   do
564     {
565       b1[d] = s1->get_bound (d)->get_column ()->rank_;
566       b2[d] = s2->get_bound (d)->get_column ()->rank_;
567     } while (flip (&d) != LEFT);  
568
569   return b2[LEFT] <= b1[LEFT] && b2[RIGHT] >= b1[RIGHT]
570     && (b2[LEFT] != b1[LEFT] || b2[RIGHT] != b1[RIGHT]);
571 }
572
573
574 Drul_array<Offset>
575 get_base_attachments (Spanner *me,
576                       Grob **common, Drul_array<Bound_info> extremes)
577 {
578   Link_array<Grob> columns
579     = Pointer_group_interface__extract_grobs (me, (Grob *)0, "note-columns");
580   Drul_array<Offset> base_attachment;
581   Real staff_space = Staff_symbol_referencer::staff_space ((Grob *) me);
582   Direction dir = get_grob_direction (me);
583   Direction d = LEFT;
584   do
585     {
586       Grob *stem = extremes[d].stem_;
587       Grob *head = extremes[d].slur_head_;
588
589       Real x, y;
590       if (!extremes[d].note_column_)
591         {
592           y = extremes[d].neighbor_y_;
593           if (d== RIGHT)
594             x = extremes[d].bound_->extent (common[X_AXIS], X_AXIS)[d];
595           else
596             x = me->get_broken_left_end_align ();
597         }
598       else
599         {
600           bool same_beam =
601             (extremes[d].stem_ && extremes[-d].stem_
602              && Stem::get_beam (extremes[d].stem_) == Stem::get_beam (extremes[-d].stem_));
603
604           /*
605             fixme: X coord should also be set in this case.
606            */
607           if (stem
608               && extremes[d].stem_dir_ == dir
609               && Stem::get_beaming (stem, -d)
610               && (!spanner_less (me, Stem::get_beam (stem))
611                   || same_beam))
612             y = extremes[d].stem_extent_[Y_AXIS][dir];
613           else if (head)
614             y = head->extent (common[Y_AXIS], Y_AXIS)[dir];
615           y += dir * 0.5 * staff_space;
616
617           Real pos
618             = (y - extremes[d].staff_->relative_coordinate (common[Y_AXIS],
619                                                             Y_AXIS))
620             * 2.0 / Staff_symbol::staff_space (extremes[d].staff_);
621
622           /* start off staffline. */
623           if (fabs (pos - my_round (pos)) < 0.2
624               && Staff_symbol_referencer::on_staffline (head, (int) rint (pos))
625               && Staff_symbol_referencer::line_count (head) - 1 >= rint (pos)
626               )
627             // TODO: calc from slur thick & line thick, parameter.      
628             y += 1.5 * staff_space * dir / 10;
629
630           Grob * fh = Note_column::first_head (extremes[d].note_column_);
631           x =
632             (fh ? fh->extent (common[X_AXIS], X_AXIS)
633              : extremes[d].bound_->extent (common[X_AXIS], X_AXIS))
634             .linear_combination (CENTER);
635         }
636       base_attachment[d] = Offset (x, y);
637
638     } while (flip (&d) != LEFT);
639
640   return base_attachment;
641 }
642
643 void
644 generate_curves (Grob *me, Grob **common,
645                  Slur_score_parameters *score_param,
646                  Drul_array<Bound_info> extremes,
647                  Drul_array<Offset>,
648                  Array<Slur_score> *scores)
649 {
650   (void) common;
651   (void) extremes;
652   Real staff_space = Staff_symbol_referencer::staff_space ((Grob *) me);
653   Real r_0 = robust_scm2double (me->get_property ("ratio"), 0.33);
654   Real h_inf = staff_space * scm_to_double (me->get_property ("height-limit"));
655   for (int i = 0; i < scores->size(); i++)
656     {
657       Bezier bez= get_bezier (me, 
658                               common,
659                               score_param,
660                               extremes,
661                               (*scores)[i].attachment_, r_0, h_inf);
662       bez = avoid_staff_line (me, common, extremes, bez);
663       (*scores)[i].attachment_[LEFT] = bez.control_[0];
664       (*scores)[i].attachment_[RIGHT] = bez.control_[3];
665       (*scores)[i].curve_ = bez;
666     }
667 }
668
669 Bezier
670 avoid_staff_line (Grob *me, Grob **common,
671                   Drul_array<Bound_info> extremes,
672                   Bezier bez)
673 {
674   Offset horiz (1,0);
675   Array<Real> ts = bez.solve_derivative (horiz);
676   Real lt = me->get_paper ()->get_dimension (ly_symbol2scm ("linethickness"));
677   Real thick = robust_scm2double (me->get_property ("thickness"), 1.0) *  lt;
678
679   /* TODO: handle case of broken slur.  */
680   if (!ts.is_empty ()
681       && (extremes[LEFT].staff_ == extremes[RIGHT].staff_)
682       && extremes[LEFT].staff_ && extremes[RIGHT].staff_)
683     {
684       Real y = bez.curve_point (ts[0])[Y_AXIS];
685
686       Grob *staff = extremes[LEFT].staff_;
687
688       Real staff_space = extremes[LEFT].staff_space_;
689       Real p = 2 * (y - staff->relative_coordinate (common[Y_AXIS], Y_AXIS))
690         / staff_space;
691
692       Real distance = fabs (my_round (p) - p);  //  in halfspaces
693       if (distance < 4 * thick
694           && (int) fabs (my_round (p))
695           <= 2 * Staff_symbol_referencer::staff_radius (staff) + 0.1
696           && (int (fabs (my_round (p))) % 2
697               != Staff_symbol_referencer::line_count (staff) % 2))
698         {
699           Direction resolution_dir =
700             (distance ?  get_grob_direction (me) : Direction (sign (p - my_round(p))));
701
702           // TODO: parameter
703           Real newp = my_round (p) + resolution_dir
704             * 5 * thick;
705         
706           Real dy = (newp - p) * staff_space / 2.0;
707 #if 0
708           bez.translate (Offset (0, dy));
709 #else
710           bez.control_[1][Y_AXIS] += dy;
711           bez.control_[2][Y_AXIS] += dy;
712         
713 #endif
714         }
715     }
716   return bez;
717 }
718
719 Array<Slur_score>
720 enumerate_attachments (Grob *me, Grob *common[],
721                        Slur_score_parameters *score_param,
722                        Drul_array<Bound_info> extremes,
723                        Drul_array<Offset> base_attachment,
724                        Drul_array<Real> end_ys)
725 {
726   (void) common;
727   /*ugh.   */
728   Array<Slur_score> scores;
729
730   Direction dir = get_grob_direction (me);
731   Real staff_space = Staff_symbol_referencer::staff_space ((Grob *) me);
732
733   Drul_array<Offset> os;
734   os[LEFT] = base_attachment[LEFT];
735   Real minimum_length = staff_space
736     * robust_scm2double (me->get_property ("minimum-length"), 2.0);
737
738   for (int i = 0; dir * os[LEFT][Y_AXIS] <= dir * end_ys[LEFT]; i++)
739     {
740       os[RIGHT] = base_attachment[RIGHT];
741       for (int j = 0; dir * os[RIGHT][Y_AXIS] <= dir * end_ys[RIGHT]; j++)
742         {
743           Slur_score s;
744           Direction d = LEFT;
745           Drul_array<bool> attach_to_stem (false, false);
746           do
747             {
748               os[d][X_AXIS] = base_attachment[d][X_AXIS];
749               if (extremes[d].stem_
750                   && !Stem::is_invisible (extremes[d].stem_)
751                   && extremes[d].stem_dir_ == dir)
752                 {
753                   if (dir == -d
754                       && extremes[d].stem_extent_[Y_AXIS].contains (os[d][Y_AXIS]))
755                     {
756                       os[d][X_AXIS] =  extremes[d].slur_head_extent_[-d]
757                         - d * 0.3;
758                       attach_to_stem[d] = true;
759                     }
760                   else if (dir *extremes[d].stem_extent_[Y_AXIS][dir]
761                              < dir * os[d][Y_AXIS]
762                            && !extremes[d].stem_extent_[X_AXIS].is_empty()
763                            )
764                     
765                     os[d][X_AXIS] = extremes[d].stem_extent_[X_AXIS].center();
766                 }
767             }
768           while (flip (&d) != LEFT);
769
770           Offset dz;    
771           dz = os[RIGHT] - os[LEFT];
772           if (dz[X_AXIS] < minimum_length
773               || fabs (dz[Y_AXIS] / dz[X_AXIS]) > score_param->max_slope_
774               )
775             {
776               do
777                 {
778                   if (extremes[d].slur_head_)
779                     {
780                       os[d][X_AXIS] = extremes[d].slur_head_extent_.center ();
781                       attach_to_stem[d] = false;
782                     }
783                 }
784               while (flip (&d) != LEFT);
785             }
786
787           dz = os[RIGHT] - os[LEFT];
788           do
789             {
790               if (extremes[d].slur_head_
791                   && !attach_to_stem[d])
792                 {
793                   /* Horizontally move tilted slurs a little.  Move
794                      more for bigger tilts.
795                     
796                      TODO: parameter */
797                   os[d][X_AXIS]
798                     -= dir * extremes[d].slur_head_extent_.length ()
799                     * sin (dz.arg  ()) / 3;
800                 }
801             }
802           while (flip (&d) != LEFT);
803           
804           s.attachment_ = os;
805           scores.push (s);
806           
807           os[RIGHT][Y_AXIS] += dir * staff_space / 2;
808         }
809       
810       os[LEFT][Y_AXIS] += dir * staff_space / 2;
811     }
812   return scores;
813 }
814
815 void
816 score_encompass (Grob *me, Grob *common[],
817                  Slur_score_parameters *score_param,
818                  Drul_array<Bound_info> extremes,
819                  Drul_array<Offset> base_attach,
820                  Array<Slur_score> *scores)
821 {
822   (void) extremes;
823   (void) base_attach;
824
825   Link_array<Grob> encompasses
826     = Pointer_group_interface__extract_grobs (me, (Grob *)0, "note-columns");
827   Direction dir = get_grob_direction (me);
828
829   Array<Encompass_info> infos;
830
831   for (int i = 0; i < encompasses.size(); i++)
832     infos.push (get_encompass_info (me, encompasses[i], common));
833
834   for (int i = 0; i < scores->size (); i++)
835     {
836       Bezier const &bez (scores->elem (i).curve_);
837       Real demerit = 0.0;
838       for (int j = 0; j < infos.size(); j++)
839         {
840           Real x = infos[j].x_;
841
842           bool l_edge = j==0;
843           bool r_edge = j==infos.size()-1;
844           bool edge =  l_edge || r_edge;
845
846           if (!(x < scores->elem (i).attachment_[RIGHT][X_AXIS]
847                 && x > scores->elem (i).attachment_[LEFT][X_AXIS]))
848             continue;
849         
850           Real y = bez.get_other_coordinate (X_AXIS, x);
851           if (!edge)
852             {
853               Real head_dy = (y - infos[j].head_);
854               if (dir * head_dy < 0)
855                 demerit += score_param->head_encompass_penalty_;
856               else
857                 {
858                   Real hd = (head_dy)
859                     ? (1 / fabs (head_dy) - 1 / score_param->free_head_distance_)
860                     : score_param->head_encompass_penalty_;
861                   hd = (hd >? 0)<? score_param->head_encompass_penalty_;
862
863                   demerit += hd;        
864                 }
865             }   
866
867           if (dir * (y - infos[j].stem_) < 0)
868             {
869               Real stem_dem =score_param->stem_encompass_penalty_ ;
870               if ((l_edge && dir == UP)
871                   || (r_edge && dir == DOWN))
872                 stem_dem /= 5;
873
874               demerit +=  stem_dem;
875             }
876           else if (!edge)
877             {
878               Interval ext;
879               ext.add_point (infos[j].stem_);
880               ext.add_point (infos[j].head_);
881
882               // ?
883               demerit += -score_param->closeness_factor_
884                 * (dir
885                    * (y - (ext[dir] + dir * score_param->free_head_distance_))
886                    <? 0)
887                 / infos.size ();
888             }
889         }
890
891 #if DEBUG_SLUR_QUANTING
892       (*scores)[i].score_card_ += to_string ("C%.2f", demerit);
893 #endif
894
895       (*scores)[i].score_ += demerit;
896     }
897 }
898
899 void
900 score_extra_encompass (Grob *me, Grob *common[],
901                        Slur_score_parameters *score_param,
902                        Drul_array<Bound_info> extremes,
903                        Drul_array<Offset> base_attach,
904                        Array<Slur_score> *scores)
905 {
906   (void) base_attach;
907   (void) extremes;
908
909   Link_array<Grob> encompasses
910     = Pointer_group_interface__extract_grobs (me, (Grob *)0,
911                                               "encompass-objects");
912   Direction dir = get_grob_direction (me);
913   Real lt =  me->get_paper ()->get_dimension (ly_symbol2scm ("linethickness"));
914   Real thick = robust_scm2double (me->get_property ("thickness"), 1.0) * lt;
915
916   Array<Real> xidxs;
917   Array<Interval> yexts;
918   Array<Interval> xexts;
919
920   for (int i = encompasses.size (); i--; )
921     {
922       if (Slur::has_interface (encompasses[i]))
923         {
924           Grob * small_slur = encompasses[i];
925           Bezier b = Slur::get_curve (small_slur);
926
927           Offset z = b.curve_point (0.5);
928           z += Offset (small_slur->relative_coordinate (common[X_AXIS], X_AXIS),
929                        small_slur->relative_coordinate (common[Y_AXIS], Y_AXIS));
930
931           xexts.push (Interval (z[X_AXIS], z[X_AXIS]));
932           xidxs.push (0.0);
933           yexts.push (z[Y_AXIS] + thick * Interval (-0.5, 0.5));
934         }
935       else
936         {
937           Grob *g = encompasses [i];
938           Interval xe = g->extent (common[X_AXIS], X_AXIS);
939           Interval ye = g->extent (common[Y_AXIS], Y_AXIS);
940
941           Real xp = 0.0;
942
943           if (Accidental_interface::has_interface (g))
944             {
945               /* Begin copy accidental.cc */
946               bool parens = false;
947               if (to_boolean (g->get_property ("cautionary")))
948                 {
949                   SCM cstyle = g->get_property ("cautionary-style");
950                   parens = ly_c_equal_p (cstyle, ly_symbol2scm ("parentheses"));
951                 }
952         
953               SCM accs = g->get_property ("accidentals");
954               SCM scm_style = g->get_property ("style");
955               if (!ly_c_symbol_p (scm_style)
956                   && !parens
957                   && scm_ilength (accs) == 1)
958                 {
959                   /* End copy accidental.cc */
960                   switch (scm_to_int (ly_car (accs)))
961                     {
962                     case FLAT:
963                     case DOUBLE_FLAT:
964                       xp = LEFT;
965                       break ;
966                     case SHARP:
967                       xp = 0.5 * dir;
968                       break ;
969                     case NATURAL:
970                       xp = -dir;
971                       break; 
972                     }
973                 }
974             }
975
976           xidxs.push (xp);
977           ye.widen (thick * 0.5);
978           yexts.push (ye);
979           xexts.push (xe);
980         }
981     }
982   for (int i = 0; i < scores->size (); i++)
983     {
984       Real demerit = 0.0;
985       for (int j = 0; j < xidxs.size(); j++)
986         {
987           Drul_array<Offset> at = scores->elem (i).attachment_;
988           Interval slur_wid (at[LEFT][X_AXIS], at[RIGHT][X_AXIS]);
989
990           /*
991             to prevent numerical inaccuracies in
992             Bezier::get_other_coordinate().
993            */
994           slur_wid.widen (- 0.5 * thick);
995           Real x = xexts[j].linear_combination (xidxs[j]);
996           Real y = 0.0;
997           if (!slur_wid.contains (x))
998             {   
999               Direction contains_dir = CENTER;
1000               Direction d = LEFT;
1001               do
1002                 {
1003                   if (xexts[j].contains (at[d][X_AXIS]))
1004                     contains_dir = d; 
1005                 }
1006               while (flip (&d) != LEFT);
1007
1008               if (!contains_dir)
1009                 continue;
1010               else
1011                 y = at[contains_dir][Y_AXIS];
1012             }
1013           else
1014             {
1015               y = scores->elem (i).curve_.get_other_coordinate (X_AXIS, x);
1016             }
1017
1018           Real collision_demerit = 
1019                (Accidental_interface::has_interface (encompasses[j]))
1020             ? score_param->accidental_collision_
1021             : score_param->extra_object_collision_;
1022           
1023           Real dist = yexts[j].distance (y);
1024           demerit +=
1025             fabs (0 >? (score_param->extra_encompass_free_distance_ - dist)) /
1026             score_param->extra_encompass_free_distance_  * collision_demerit;
1027         }
1028 #if DEBUG_SLUR_QUANTING
1029       (*scores)[i].score_card_ += to_string ("X%.2f", demerit);
1030 #endif
1031       (*scores)[i].score_ += demerit;
1032     }
1033 }
1034
1035 void
1036 score_edges (Grob *me, Grob *common[],
1037              Slur_score_parameters * score_param,
1038              Drul_array<Bound_info> extremes,
1039              Drul_array<Offset> base_attach,
1040              Array<Slur_score> *scores)
1041 {
1042   (void) common;
1043   Direction dir = get_grob_direction (me);
1044
1045   for (int i = 0; i < scores->size (); i++)
1046     {
1047       Direction d = LEFT;
1048       do
1049         {
1050           Real y = scores->elem (i).attachment_[d][Y_AXIS];
1051           Real dy = fabs (y - base_attach[d][Y_AXIS]);
1052         
1053           Real factor = score_param->edge_attraction_factor_;
1054           Real demerit = factor * dy;
1055           if (extremes[d].stem_
1056               && extremes[d].stem_dir_ == dir
1057               && !Stem::get_beaming (extremes[d].stem_, -d)
1058               )
1059             demerit /= 5;
1060         
1061           (*scores)[i].score_ += demerit;
1062 #if DEBUG_SLUR_QUANTING
1063           (*scores)[i].score_card_ += to_string ("E%.2f", demerit);
1064 #endif
1065         }
1066       while (flip (&d) != LEFT);
1067     }
1068 }
1069
1070 void
1071 score_slopes (Grob *me, Grob *common[],
1072               Slur_score_parameters *score_param,
1073               Drul_array<Bound_info> extremes,
1074               Drul_array<Offset> base_attach,
1075               Array<Slur_score> * scores)
1076 {
1077   (void) me;
1078   (void) base_attach;
1079
1080   Drul_array<Real> ys;
1081   Direction d = LEFT;
1082   do
1083     {
1084       if (extremes[d].slur_head_)
1085         ys[d] = extremes[d].slur_head_->relative_coordinate (common[Y_AXIS],
1086                                                               Y_AXIS);
1087       else
1088         ys[d] = extremes[d].neighbor_y_;
1089     }
1090   while (flip (&d) != LEFT);
1091
1092   bool has_beams
1093     = (extremes[LEFT].stem_ && Stem::get_beam (extremes[LEFT].stem_))
1094     || (extremes[RIGHT].stem_ && Stem::get_beam (extremes[RIGHT].stem_));
1095
1096   Real dy = ys[RIGHT] - ys[LEFT];
1097   for (int i = 0; i < scores->size (); i++)
1098     {
1099       Offset slur_dz = (*scores)[i].attachment_[RIGHT]
1100         - (*scores)[i].attachment_[LEFT];
1101       Real slur_dy = slur_dz[Y_AXIS];
1102       Real demerit = 0.0;
1103
1104       demerit += ((fabs (slur_dy / slur_dz[X_AXIS])
1105                    - score_param->max_slope_) >? 0)
1106         * score_param->max_slope_factor_;
1107
1108       /* 0.2: account for staffline offset. */
1109       Real max_dy = (fabs (dy) + 0.2);
1110       if (has_beams)
1111         max_dy += 1.0;
1112
1113       demerit += score_param->steeper_slope_factor_
1114         * ((fabs (slur_dy) -max_dy) >? 0);
1115
1116       demerit += ((fabs (slur_dy/slur_dz[X_AXIS])
1117                    - score_param->max_slope_) >? 0)
1118         * score_param->max_slope_factor_;
1119
1120       if (sign (dy) == 0
1121           && sign (slur_dy) != 0)
1122         demerit += score_param->non_horizontal_penalty_;
1123
1124       if (sign (dy)
1125           && sign (slur_dy)
1126           && sign (slur_dy) != sign (dy))
1127         demerit += has_beams
1128           ? score_param->same_slope_penalty_ / 10
1129           : score_param->same_slope_penalty_;
1130
1131 #if DEBUG_SLUR_QUANTING
1132       (*scores)[i].score_card_ += to_string ("S%.2f", d);
1133 #endif
1134       (*scores)[i].score_ += demerit;
1135     }
1136
1137
1138   
1139 }
1140
1141
1142 Real
1143 fit_factor (Offset dz_unit, Offset dz_perp,
1144             Bezier curve, Direction d,  Array<Offset> const &avoid)
1145 {
1146   Real fit_factor = 0.0;
1147   Offset x0 = curve.control_[0];
1148   curve.translate (-x0);
1149   curve.rotate (-dz_unit.arg ());
1150   curve.scale (1, d);
1151
1152   Interval curve_xext;
1153   curve_xext.add_point (curve.control_[0][X_AXIS]);
1154   curve_xext.add_point (curve.control_[3][X_AXIS]);
1155   
1156   for (int i = 0; i < avoid.size (); i++)
1157     {
1158       Offset z = (avoid[i] - x0) ;
1159       Offset p (dot_product (z, dz_unit),
1160                 d* dot_product (z, dz_perp));
1161       if (!curve_xext.contains (p[X_AXIS]))
1162         continue;
1163       
1164       Real y = curve.get_other_coordinate (X_AXIS, p[X_AXIS]);
1165       if (y) 
1166         {
1167           fit_factor = fit_factor >? (p[Y_AXIS] / y);
1168         }
1169     }
1170   return fit_factor;
1171 }
1172             
1173
1174 Bezier
1175 get_bezier (Grob *me, 
1176             Grob **common,
1177             Slur_score_parameters *score_param,
1178             Drul_array<Bound_info> extremes,       
1179             Drul_array<Offset> attachments,
1180             Real r_0, Real h_inf)
1181 {
1182   Link_array<Grob> encompasses
1183     = Pointer_group_interface__extract_grobs (me, (Grob *)0, "note-columns");
1184   Direction dir = get_grob_direction (me);
1185
1186   Array<Offset> avoid;
1187   for (int i = 0; i < encompasses.size(); i++)
1188     {
1189       if (extremes[LEFT].note_column_ == encompasses[i]
1190           ||extremes[RIGHT].note_column_ == encompasses[i])
1191         continue;
1192
1193       Encompass_info inf (get_encompass_info (me, encompasses[i], common));
1194
1195       Real y = dir*((dir * inf.head_) >? (dir *inf.stem_));
1196       
1197       avoid.push (Offset (inf.x_,  y + dir * score_param->free_head_distance_));
1198     }
1199   
1200   Offset dz = attachments[RIGHT]- attachments[LEFT];;
1201   Offset dz_unit = dz;
1202   dz_unit *= 1 / dz.length();
1203   Offset dz_perp = dz_unit * Offset(0,1);
1204
1205   Real indent, height;
1206   get_slur_indent_height (&indent, &height, dz.length (), h_inf, r_0);
1207
1208   Real excentricity = robust_scm2double (me->get_property ("excentricity"), 0.0);
1209   Bezier curve;
1210
1211   Real x1 = (excentricity + indent);   
1212   Real x2 = (excentricity - indent);  
1213   curve.control_[0] = attachments[LEFT];
1214   curve.control_[1] = attachments[LEFT] + dz_perp * height * dir + dz_unit * x1;
1215   curve.control_[2] = attachments[RIGHT] + dz_perp * height * dir + dz_unit * x2;
1216   curve.control_[3] = attachments[RIGHT];
1217
1218
1219   Real ff = fit_factor (dz_unit, dz_perp, curve, dir, avoid);
1220   Real l = dz.length ();
1221
1222   /*
1223     This condition,
1224
1225     l^2 > 4h^2 +  3(i  1/3l)^2  - 1/3 l^2
1226
1227     is equivalent to:
1228
1229     |bez'(0)| < | bez'(.5)|
1230
1231     when (control2-control1) has the same direction as (control3 -
1232     control0).
1233     
1234    */
1235   Real max_h = sqrt (sqr (l)/3 - .75 * sqr (indent + l / 3));
1236   height = height >? ((height * ff) <? max_h); 
1237
1238   curve.control_[0] = attachments[LEFT];
1239   curve.control_[1] = attachments[LEFT] + dz_perp * height * dir + dz_unit * x1;
1240   curve.control_[2] = attachments[RIGHT] + dz_perp * height * dir + dz_unit * x2;
1241   curve.control_[3] = attachments[RIGHT];
1242   
1243   return curve;
1244 }