]> git.donarmstrong.com Git - lilypond.git/blob - lily/tie-formatting-problem.cc
Doc-de: fixing linkage
[lilypond.git] / lily / tie-formatting-problem.cc
1 /*
2   This file is part of LilyPond, the GNU music typesetter.
3
4   Copyright (C) 2005--2011 Han-Wen Nienhuys <hanwen@xs4all.nl>
5
6
7   LilyPond is free software: you can redistribute it and/or modify
8   it under the terms of the GNU General Public License as published by
9   the Free Software Foundation, either version 3 of the License, or
10   (at your option) any later version.
11
12   LilyPond is distributed in the hope that it will be useful,
13   but WITHOUT ANY WARRANTY; without even the implied warranty of
14   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15   GNU General Public License for more details.
16
17   You should have received a copy of the GNU General Public License
18   along with LilyPond.  If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include <cstdio>
22 #include "tie-formatting-problem.hh"
23
24 #include "axis-group-interface.hh"
25 #include "paper-column.hh"
26 #include "bezier.hh"
27 #include "directional-element-interface.hh"
28 #include "libc-extension.hh"
29 #include "misc.hh"
30 #include "note-head.hh"
31 #include "rhythmic-head.hh"
32 #include "spanner.hh"
33 #include "staff-symbol-referencer.hh"
34 #include "stem.hh"
35 #include "tie-configuration.hh"
36 #include "tie.hh"
37 #include "warn.hh"
38 #include "pointer-group-interface.hh"
39 #include "output-def.hh"
40
41 void
42 Tie_formatting_problem::print_ties_configuration (Ties_configuration const *ties)
43 {
44   for (vsize i = 0; i < ties->size (); i++)
45     {
46       char const *man_pos = (specifications_[i].has_manual_position_) ? "(M)" : "";
47       char const *man_dir = (specifications_[i].has_manual_dir_) ? "(M)" : "";
48       char const *dir = (ties->at (i).dir_ == UP) ? "up" : "dn";
49
50       printf ("(P%d%s, %s%s) ", ties->at (i).position_, man_pos, dir, man_dir);
51     }
52   printf ("\n");
53 }
54
55 Interval
56 Tie_formatting_problem::get_attachment (Real y, Drul_array<int> columns) const
57 {
58   Interval attachments (0, 0);
59   Direction d = LEFT;
60   do
61     {
62       Tuple2<int> key (columns[d], int (d));
63       Chord_outline_map::const_iterator i (chord_outlines_.find (key));
64       if (i == chord_outlines_.end ())
65         programming_error ("Cannot find chord outline");
66       else
67         attachments[d] = i->second.height (y);
68     }
69   while (flip (&d) != LEFT);
70
71   return attachments;
72 }
73
74 Tie_formatting_problem::Tie_formatting_problem ()
75 {
76   x_refpoint_ = 0;
77   y_refpoint_ = 0;
78   use_horizontal_spacing_ = true;
79 }
80
81 Tie_formatting_problem::~Tie_formatting_problem ()
82 {
83   for (Tie_configuration_map::const_iterator i (possibilities_.begin ());
84        i != possibilities_.end (); i++)
85     delete (*i).second;
86 }
87
88 void
89 Tie_formatting_problem::set_column_chord_outline (vector<Item *> bounds,
90                                                   Direction dir,
91                                                   int column_rank)
92 {
93   Real staff_space = Staff_symbol_referencer::staff_space (bounds[0]);
94
95   vector<Box> boxes;
96   vector<Box> head_boxes;
97
98   Grob *stem = 0;
99   for (vsize i = 0; i < bounds.size (); i++)
100     {
101       Grob *head = bounds[i];
102       if (!Note_head::has_interface (head))
103         continue;
104
105       if (!stem)
106         stem = unsmob_grob (head->get_object ("stem"));
107
108       Real p = Staff_symbol_referencer::get_position (head);
109       Interval y ((p - 1) * 0.5 * staff_space,
110                   (p + 1) * 0.5 * staff_space);
111
112       Interval x = head->extent (x_refpoint_, X_AXIS);
113       head_boxes.push_back (Box (x, y));
114       boxes.push_back (Box (x, y));
115
116       Grob *dots = Rhythmic_head::get_dots (head);
117       if (dir == LEFT && dots)
118         {
119           Interval x = dots->extent (x_refpoint_, X_AXIS);
120           int p = int (Staff_symbol_referencer::get_position (dots));
121
122           /*
123             TODO: shouldn't this use column-rank dependent key?
124           */
125           dot_positions_.insert (p);
126           dot_x_.unite (x);
127
128           Interval y (dots->extent (dots, Y_AXIS));
129           y.translate (p * staff_space * 0.5);
130
131           boxes.push_back (Box (x, y));
132         }
133     }
134
135   Tuple2<int> key (column_rank, int (dir));
136
137   if (stem)
138     {
139       if (Stem::is_normal_stem (stem))
140         {
141           Interval x;
142           x.add_point (stem->relative_coordinate (x_refpoint_, X_AXIS));
143           x.widen (staff_space / 20); // ugh.
144           Interval y;
145
146           Real stem_end_position = 0.0;
147           if (Stem::is_cross_staff (stem))
148             stem_end_position = get_grob_direction (stem) * infinity_f;
149           else
150             {
151               if (use_horizontal_spacing_ || !Stem::get_beam (stem))
152                 stem_end_position = Stem::stem_end_position (stem) * staff_space * .5;
153               else
154                 stem_end_position = Stem::note_head_positions (stem)[get_grob_direction (stem)]
155                                     * staff_space * .5;
156             }
157
158           y.add_point (stem_end_position);
159
160           Direction stemdir = get_grob_direction (stem);
161           y.add_point (Stem::head_positions (stem)[-stemdir]
162                        * staff_space * .5);
163
164           /*
165             add extents of stem.
166           */
167           boxes.push_back (Box (x, y));
168
169           stem_extents_[key].unite (Box (x, y));
170
171           if (dir == LEFT)
172             {
173               Box flag_box = Stem::get_translated_flag (stem).extent_box ();
174               flag_box.translate ( Offset (x[RIGHT], X_AXIS));
175               boxes.push_back (flag_box);
176             }
177         }
178       else
179         {
180           Grob *head = Stem::support_head (stem);
181
182           /*
183             In case of invisible stem, don't pass x-center of heads.
184           */
185           Real x_center = head->extent (x_refpoint_, X_AXIS).center ();
186           Interval x_ext;
187           x_ext[-dir] = x_center;
188           x_ext[dir] = infinity_f * dir;
189           Interval y_ext;
190           for (vsize j = 0; j < head_boxes.size (); j++)
191             y_ext.unite (head_boxes[j][Y_AXIS]);
192
193           boxes.push_back (Box (x_ext, y_ext));
194         }
195
196       extract_grob_set (stem, "note-heads", heads);
197       for (vsize i = 0; i < heads.size (); i++)
198         {
199           if (find (bounds.begin (), bounds.end (), dynamic_cast<Item *> (heads[i])) == bounds.end ())
200             {
201               /*
202                 other untied notes in the same chord.
203               */
204
205               Interval y = Staff_symbol_referencer::extent_in_staff (heads[i]);
206               Interval x = heads[i]->extent (x_refpoint_, X_AXIS);
207               boxes.push_back (Box (x, y));
208             }
209
210           Grob *acc = unsmob_grob (heads[i]->get_object ("accidental-grob"));
211           if (acc)
212             acc->get_property ("stencil"); /* trigger tie-related suicide */
213
214           if (acc && acc->is_live () && dir == RIGHT)
215             {
216               boxes.push_back (Box (acc->extent (x_refpoint_, X_AXIS),
217                                     Staff_symbol_referencer::extent_in_staff (acc)));
218             }
219
220           head_positions_[column_rank].add_point (int (Staff_symbol_referencer::get_position (heads[i])));
221         }
222
223     }
224
225   Direction updowndir = DOWN;
226   do
227     {
228       Interval x;
229       Interval y;
230       if (head_boxes.size ())
231         {
232           Box b = boundary (head_boxes, updowndir, 0);
233           x = b[X_AXIS];
234           x[-dir] = b[X_AXIS].linear_combination (-dir / 2);
235           y[-updowndir] = b[Y_AXIS][updowndir];
236           y[updowndir] = updowndir * infinity_f;
237         }
238
239       if (!x.is_empty ())
240         boxes.push_back (Box (x, y));
241     }
242   while (flip (&updowndir) != DOWN);
243
244   /* todo: the horizon_padding is somewhat arbitrary */
245   chord_outlines_[key] = Skyline (boxes, details_.skyline_padding_, Y_AXIS, -dir);
246   if (bounds[0]->break_status_dir ())
247     {
248       Interval iv (Axis_group_interface::staff_extent (bounds[0], x_refpoint_, X_AXIS, y_refpoint_, Y_AXIS));
249       if (iv.is_empty ())
250         iv.add_point (bounds[0]->relative_coordinate (x_refpoint_, X_AXIS));
251
252       chord_outlines_[key].set_minimum_height (iv[-dir]);
253     }
254   else
255     {
256       Interval x;
257       for (vsize j = 0; j < head_boxes.size (); j++)
258         {
259           x.unite (head_boxes[j][X_AXIS]);
260         }
261
262       chord_outlines_[key].set_minimum_height (x[dir]);
263     }
264
265   head_extents_[key].set_empty ();
266   for (vsize i = 0; i < head_boxes.size (); i++)
267     {
268       head_extents_[key].unite (head_boxes[i]);
269     }
270 }
271
272 void
273 Tie_formatting_problem::set_chord_outline (vector<Item *> bounds,
274                                            Direction dir)
275
276 {
277   vector<int> ranks;
278   for (vsize i = 0; i < bounds.size (); i++)
279     ranks.push_back (bounds[i]->get_column ()->get_rank ());
280
281   vector_sort (ranks, less<int> ());
282   uniq (ranks);
283
284   for (vsize i = 0; i < ranks.size (); i++)
285     {
286       vector<Item *> col_items;
287       for (vsize j = 0; j < bounds.size (); j++)
288         {
289           if (bounds[j]->get_column ()->get_rank () == ranks[i])
290             col_items.push_back (bounds[j]);
291         }
292
293       set_column_chord_outline (col_items, dir, ranks[i]);
294     }
295 }
296
297 void
298 Tie_formatting_problem::from_tie (Grob *tie)
299 {
300   vector<Grob *> ties;
301   ties.push_back (tie);
302   from_ties (ties);
303
304   details_.from_grob (tie);
305 }
306
307 Grob *
308 Tie_formatting_problem::common_x_refpoint () const
309 {
310   return x_refpoint_;
311 }
312
313 void
314 Tie_formatting_problem::from_ties (vector<Grob *> const &ties)
315 {
316   if (ties.empty ())
317     return;
318
319   x_refpoint_ = ties[0];
320   y_refpoint_ = ties[0];
321   for (vsize i = 0; i < ties.size (); i++)
322     {
323       Spanner *tie = dynamic_cast<Spanner *> (ties[i]);
324       Item *l = tie->get_bound (LEFT);
325       Item *r = tie->get_bound (RIGHT);
326
327       x_refpoint_ = l->common_refpoint (x_refpoint_, X_AXIS);
328       x_refpoint_ = r->common_refpoint (x_refpoint_, X_AXIS);
329
330       if (!l->break_status_dir ())
331         y_refpoint_ = l->common_refpoint (y_refpoint_, Y_AXIS);
332       if (!r->break_status_dir ())
333         y_refpoint_ = r->common_refpoint (y_refpoint_, Y_AXIS);
334     }
335
336   details_.from_grob (ties[0]);
337
338   Direction d = LEFT;
339   do
340     {
341       vector<Item *> bounds;
342
343       for (vsize i = 0; i < ties.size (); i++)
344         {
345           Item *it = dynamic_cast<Spanner *> (ties[i])->get_bound (d);
346           if (it->break_status_dir ())
347             it = it->get_column ();
348
349           bounds.push_back (it);
350         }
351
352       set_chord_outline (bounds, d);
353     }
354   while (flip (&d) != LEFT);
355
356   for (vsize i = 0; i < ties.size (); i++)
357     {
358       Tie_specification spec;
359       spec.from_grob (ties[i]);
360
361       do
362         {
363           spec.note_head_drul_[d] = Tie::head (ties[i], d);
364           spec.column_ranks_[d] = Tie::get_column_rank (ties[i], d);
365         }
366       while (flip (&d) != LEFT);
367       specifications_.push_back (spec);
368     }
369 }
370
371 void
372 Tie_formatting_problem::from_semi_ties (vector<Grob *> const &semi_ties, Direction head_dir)
373 {
374   if (semi_ties.empty ())
375     return;
376
377   use_horizontal_spacing_ = false;
378   details_.from_grob (semi_ties[0]);
379   vector<Item *> heads;
380
381   int column_rank = -1;
382   for (vsize i = 0; i < semi_ties.size (); i++)
383     {
384       Tie_specification spec;
385       Item *head = unsmob_item (semi_ties[i]->get_object ("note-head"));
386
387       if (!head)
388         programming_error ("LV tie without head?!");
389
390       if (head)
391         {
392           spec.position_ = int (Staff_symbol_referencer::get_position (head));
393         }
394
395       spec.from_grob (semi_ties[i]);
396
397       spec.note_head_drul_[head_dir] = head;
398       column_rank = Tie::get_column_rank (semi_ties[i], head_dir);
399       spec.column_ranks_ = Drul_array<int> (column_rank, column_rank);
400       heads.push_back (head);
401       specifications_.push_back (spec);
402     }
403
404   x_refpoint_ = semi_ties[0];
405   y_refpoint_ = semi_ties[0];
406
407   for (vsize i = 0; i < semi_ties.size (); i++)
408     {
409       x_refpoint_ = semi_ties[i]->common_refpoint (x_refpoint_, X_AXIS);
410       y_refpoint_ = semi_ties[i]->common_refpoint (y_refpoint_, Y_AXIS);
411     }
412   for (vsize i = 0; i < heads.size (); i++)
413     {
414       x_refpoint_ = heads[i]->common_refpoint (x_refpoint_, X_AXIS);
415       y_refpoint_ = heads[i]->common_refpoint (y_refpoint_, Y_AXIS);
416     }
417
418   set_chord_outline (heads, head_dir);
419
420   Tuple2<int> head_key (column_rank, head_dir);
421   Tuple2<int> open_key (column_rank, -head_dir);
422   Real extremal = chord_outlines_[head_key].max_height ();
423
424   chord_outlines_[open_key] = Skyline (head_dir);
425   chord_outlines_[open_key].set_minimum_height (extremal - head_dir * 1.5);
426 }
427
428 Tie_specification
429 Tie_formatting_problem::get_tie_specification (int i) const
430 {
431   return specifications_[i];
432 }
433
434 /*
435   Return configuration, create it if necessary.
436 */
437 Tie_configuration *
438 Tie_formatting_problem::get_configuration (int pos, Direction dir, Drul_array<int> columns,
439                                            bool tune_dy) const
440 {
441   int key_components[] =
442   {
443     pos, dir, columns[LEFT], columns[RIGHT]
444   };
445   Tuple<int, 4> key (key_components);
446
447   Tie_configuration_map::const_iterator f = possibilities_.find (key);
448   if (f != possibilities_.end ())
449     {
450       return (*f).second;
451     }
452
453   Tie_configuration *conf = generate_configuration (pos, dir, columns, tune_dy);
454   ((Tie_formatting_problem *) this)->possibilities_[key] = conf;
455   return conf;
456 }
457
458 Tie_configuration *
459 Tie_formatting_problem::generate_configuration (int pos, Direction dir,
460                                                 Drul_array<int> columns, bool y_tune) const
461 {
462   Tie_configuration *conf = new Tie_configuration;
463   conf->position_ = pos;
464   conf->dir_ = dir;
465
466   conf->column_ranks_ = columns;
467
468   Real y = conf->position_ * 0.5 * details_.staff_space_;
469
470   if (dot_positions_.find (pos) != dot_positions_.end ())
471     {
472       conf->delta_y_ += dir * 0.25 * details_.staff_space_;
473       y_tune = false;
474     }
475
476   if (y_tune
477       && max (fabs (get_head_extent (columns[LEFT], LEFT, Y_AXIS)[dir] - y),
478               fabs (get_head_extent (columns[RIGHT], RIGHT, Y_AXIS)[dir] - y)) < 0.25
479       && !Staff_symbol_referencer::on_line (details_.staff_symbol_referencer_, pos))
480     {
481       conf->delta_y_
482         = (get_head_extent (columns[LEFT], LEFT, Y_AXIS)[dir] - y)
483           + dir * details_.outer_tie_vertical_gap_;
484     }
485
486   if (y_tune)
487     {
488       conf->attachment_x_ = get_attachment (y + conf->delta_y_, conf->column_ranks_);
489       Real h = conf->height (details_);
490
491       /*
492         TODO:
493
494         - should make sliding criterion, should flatten ties if
495
496         - they're just the wrong (ie. touching line at top & bottom)
497         size.
498
499        */
500       if (head_positions_slice (columns[LEFT]).contains (pos)
501           || head_positions_slice (columns[RIGHT]).contains (pos)
502           || abs (pos) < 2 * Staff_symbol_referencer::staff_radius (details_.staff_symbol_referencer_))
503         {
504           if (h < details_.intra_space_threshold_ * 0.5 * details_.staff_space_)
505             {
506               if (!Staff_symbol_referencer::on_line (details_.staff_symbol_referencer_, pos)
507                   && abs (pos) < 2 * Staff_symbol_referencer::staff_radius (details_.staff_symbol_referencer_))
508                 {
509                   conf->center_tie_vertically (details_);
510                 }
511               else if (Staff_symbol_referencer::on_line (details_.staff_symbol_referencer_, pos))
512                 {
513                   conf->delta_y_ += dir *
514                                     details_.tip_staff_line_clearance_ * 0.5 * details_.staff_space_;
515                 }
516             }
517           else
518             {
519               Real top_y = y + conf->delta_y_ + conf->dir_ * h;
520               Real top_pos = top_y / (0.5 * details_.staff_space_);
521               int round_pos = int (my_round (top_pos));
522
523               /* TODO: should use other variable? */
524               Real clearance = details_.center_staff_line_clearance_;
525               if (fabs (top_pos - round_pos) < clearance
526                   && Staff_symbol_referencer::on_staff_line (details_.staff_symbol_referencer_,
527                                                              round_pos))
528                 {
529                   Real new_y = (round_pos + clearance * conf->dir_) * 0.5 * details_.staff_space_;
530                   conf->delta_y_ = (new_y - top_y);
531                 }
532             }
533         }
534     }
535   conf->attachment_x_ = get_attachment (y + conf->delta_y_, conf->column_ranks_);
536   if (conf->height (details_) < details_.intra_space_threshold_ * 0.5 * details_.staff_space_)
537     {
538       /*
539         This is less sensible for long ties, since those are more
540         horizontal.
541       */
542       Interval close_by = get_attachment (y
543                                           + conf->delta_y_
544                                           + (dir * details_.intra_space_threshold_ * 0.25
545                                              * details_.staff_space_),
546                                           conf->column_ranks_);
547
548       conf->attachment_x_.intersect (close_by);
549     }
550
551   conf->attachment_x_.widen ( - details_.x_gap_);
552
553   if (conf->column_span_length ())
554     {
555       /*
556         avoid the stems that we attach to as well. We don't do this
557         for semities (span length = 0)
558
559         It would be better to check D against HEAD-DIRECTION if
560         applicable.
561       */
562       Direction d = LEFT;
563       do
564         {
565           Real y = conf->position_ * details_.staff_space_ * 0.5 + conf->delta_y_;
566           if (get_stem_extent (conf->column_ranks_[d], d, X_AXIS).is_empty ()
567               || !get_stem_extent (conf->column_ranks_[d], d, Y_AXIS).contains (y))
568             continue;
569
570           conf->attachment_x_[d]
571             = d * min (d * conf->attachment_x_[d],
572                        d * (get_stem_extent (conf->column_ranks_[d], d, X_AXIS)[-d] - d * details_.stem_gap_));
573         }
574       while (flip (&d) != LEFT);
575     }
576   return conf;
577 }
578
579 Interval
580 Tie_formatting_problem::get_head_extent (int col, Direction d, Axis a) const
581 {
582   Column_extent_map::const_iterator i = head_extents_.find (Tuple2<int> (col, int (d)));
583   if (i != head_extents_.end ())
584     return (*i).second[a];
585   else
586     return Interval ();
587 }
588
589 Interval
590 Tie_formatting_problem::get_stem_extent (int col, Direction d, Axis a) const
591 {
592   Column_extent_map::const_iterator i = stem_extents_.find (Tuple2<int> (col, int (d)));
593   if (i != stem_extents_.end ())
594     return (*i).second[a];
595   else
596     return Interval ();
597 }
598
599 /**
600    TIE_IDX and TIES_CONF are optional.
601  */
602 Real
603 Tie_formatting_problem::score_aptitude (Tie_configuration *conf,
604                                         Tie_specification const &spec,
605                                         Ties_configuration *ties_conf, int tie_idx) const
606 {
607   Real penalty = 0.0;
608   Real curve_y = conf->position_ * details_.staff_space_ * 0.5 + conf->delta_y_;
609   Real tie_y = spec.position_ * details_.staff_space_ * 0.5;
610   if (sign (curve_y - tie_y) != conf->dir_)
611     {
612       Real p = details_.wrong_direction_offset_penalty_;
613       if (ties_conf)
614         ties_conf->add_tie_score (p, tie_idx, "wrong dir");
615       else
616         penalty += p;
617     }
618
619   {
620     Real relevant_dist = max (fabs (curve_y - tie_y) - 0.5, 0.0);
621     Real p = details_.vertical_distance_penalty_factor_ * convex_amplifier (1.0, 0.9, relevant_dist);
622     if (ties_conf)
623       ties_conf->add_tie_score (p, tie_idx, "vdist");
624     else
625       penalty += p;
626   }
627
628   Direction d = LEFT;
629   do
630     {
631       if (!spec.note_head_drul_[d])
632         continue;
633
634       Interval head_x = spec.note_head_drul_[d]->extent (x_refpoint_, X_AXIS);
635       Real dist = head_x.distance (conf->attachment_x_[d]);
636
637       /*
638         TODO: flatten with log or sqrt.
639        */
640       Real p = details_.horizontal_distance_penalty_factor_
641                * convex_amplifier (1.25, 1.0, dist);
642       if (ties_conf)
643         ties_conf->add_tie_score (p, tie_idx,
644                                   (d == LEFT) ? "lhdist" : "rhdist");
645       else
646         penalty += p;
647
648     }
649   while (flip (&d) != LEFT);
650
651   if (ties_conf
652       && ties_conf->size () == 1)
653     {
654       Direction d = LEFT;
655       Drul_array<Grob *> stems (0, 0);
656       do
657         {
658           if (!spec.note_head_drul_[d])
659             continue;
660
661           Grob *stem = unsmob_grob (spec.note_head_drul_[d]->get_object ("stem"));
662           if (stem
663               && Stem::is_normal_stem (stem))
664             stems[d] = stem;
665         }
666       while (flip (&d) != LEFT);
667
668       bool tie_stem_dir_ok = true;
669       bool tie_position_dir_ok = true;
670       if (stems[LEFT] && !stems[RIGHT])
671         tie_stem_dir_ok = conf->dir_ != get_grob_direction (stems[LEFT]);
672       else if (!stems[LEFT] && stems[RIGHT])
673         tie_stem_dir_ok = conf->dir_ != get_grob_direction (stems[RIGHT]);
674       else if (stems[LEFT] && stems[RIGHT]
675                && get_grob_direction (stems[LEFT]) == get_grob_direction (stems[RIGHT]))
676         tie_stem_dir_ok = conf->dir_ != get_grob_direction (stems[LEFT]);
677       else if (spec.position_)
678         tie_position_dir_ok = conf->dir_ == sign (spec.position_);
679
680       if (!tie_stem_dir_ok)
681         ties_conf->add_score (details_.same_dir_as_stem_penalty_, "tie/stem dir");
682       if (!tie_position_dir_ok)
683         ties_conf->add_score (details_.same_dir_as_stem_penalty_, "tie/pos dir");
684     }
685
686   return penalty;
687 }
688
689 Slice
690 Tie_formatting_problem::head_positions_slice (int rank) const
691 {
692   Position_extent_map::const_iterator i (head_positions_.find (rank));
693   if (i != head_positions_.end ())
694     {
695       return (*i).second;
696     }
697   Slice empty;
698   return empty;
699 }
700
701 /*
702   Score a configuration, ie. how well these ties looks without regard
703   to the note heads that they should connect to.
704  */
705 void
706 Tie_formatting_problem::score_configuration (Tie_configuration *conf) const
707 {
708   if (conf->scored_)
709     {
710       return;
711     }
712
713   Real length = conf->attachment_x_.length ();
714
715   Real length_penalty
716     = peak_around (0.33 * details_.min_length_, details_.min_length_, length);
717   conf->add_score (details_.min_length_penalty_factor_
718                    * length_penalty, "minlength");
719
720   Real tip_pos = conf->position_ + conf->delta_y_ / 0.5 * details_.staff_space_;
721   Real tip_y = tip_pos * details_.staff_space_ * 0.5;
722   Real height = conf->height (details_);
723
724   Real top_y = tip_y + conf->dir_ * height;
725   Real top_pos = 2 * top_y / details_.staff_space_;
726   Real round_top_pos = rint (top_pos);
727   if (Staff_symbol_referencer::on_line (details_.staff_symbol_referencer_,
728                                         int (round_top_pos))
729       && Staff_symbol_referencer::staff_radius (details_.staff_symbol_referencer_) > top_y)
730     {
731       conf->add_score (details_.staff_line_collision_penalty_
732                        * peak_around (0.1 * details_.center_staff_line_clearance_,
733                                       details_.center_staff_line_clearance_,
734                                       fabs (top_pos - round_top_pos)),
735                        "line center");
736     }
737
738   int rounded_tip_pos = int (rint (tip_pos));
739   if (Staff_symbol_referencer::on_line (details_.staff_symbol_referencer_, rounded_tip_pos)
740       && (head_positions_slice (conf->column_ranks_[LEFT]).contains (rounded_tip_pos)
741           || head_positions_slice (conf->column_ranks_[RIGHT]).contains (rounded_tip_pos)
742           || abs (rounded_tip_pos) < 2 * Staff_symbol_referencer::staff_radius (details_.staff_symbol_referencer_))
743      )
744     {
745       conf->add_score (details_.staff_line_collision_penalty_
746                        * peak_around (0.1 * details_.tip_staff_line_clearance_,
747                                       details_.tip_staff_line_clearance_,
748                                       fabs (tip_pos - rint (tip_pos))),
749                        "tipline");
750     }
751
752   if (!dot_x_.is_empty ())
753     {
754       /* use left edge? */
755       Real x = dot_x_.center ();
756
757       Bezier b = conf->get_transformed_bezier (details_);
758       if (b.control_point_extent (X_AXIS).contains (x))
759         {
760           Real y = b.get_other_coordinate (X_AXIS, x);
761
762           for (set<int>::const_iterator i (dot_positions_.begin ());
763                i != dot_positions_.end (); i++)
764             {
765               int dot_pos = (*i);
766               conf->add_score (details_.dot_collision_penalty_
767                                * peak_around (.1 * details_.dot_collision_clearance_,
768                                               details_.dot_collision_clearance_,
769                                               fabs (dot_pos * details_.staff_space_ * 0.5 - y)),
770                                "dot collision");
771             }
772         }
773     }
774
775   conf->scored_ = true;
776 }
777
778 void
779 Tie_formatting_problem::score_ties_aptitude (Ties_configuration *ties) const
780 {
781   if (ties->size () != specifications_.size ())
782     {
783       programming_error ("Huh? Mismatch between sizes.");
784       return;
785     }
786
787   for (vsize i = 0; i < ties->size (); i++)
788     score_aptitude (&ties->at (i), specifications_[i],
789                     ties, i);
790 }
791
792 void
793 Tie_formatting_problem::score_ties (Ties_configuration *ties) const
794 {
795   if (ties->scored_)
796     return;
797
798   score_ties_configuration (ties);
799   score_ties_aptitude (ties);
800   ties->scored_ = true;
801 }
802
803 void
804 Tie_formatting_problem::score_ties_configuration (Ties_configuration *ties) const
805 {
806   for (vsize i = 0; i < ties->size (); i++)
807     {
808       score_configuration (&ties->at (i));
809       ties->add_tie_score (ties->at (i).score (), i, "conf");
810     }
811
812   Real last_edge = 0.0;
813   Real last_center = 0.0;
814   for (vsize i = 0; i < ties->size (); i++)
815     {
816       Bezier b (ties->at (i).get_transformed_bezier (details_));
817
818       Real center = b.curve_point (0.5)[Y_AXIS];
819       Real edge = b.curve_point (0.0)[Y_AXIS];
820
821       if (i)
822         {
823           if (edge <= last_edge)
824             ties->add_score (details_.tie_column_monotonicity_penalty_, "monoton edge");
825           if (center <= last_center)
826             ties->add_score (details_.tie_column_monotonicity_penalty_, "monoton cent");
827
828           ties->add_score (details_.tie_tie_collision_penalty_ *
829                            peak_around (0.1 * details_.tie_tie_collision_distance_,
830                                         details_.tie_tie_collision_distance_,
831                                         fabs (center - last_center)),
832                            "tietie center");
833           ties->add_score (details_.tie_tie_collision_penalty_ *
834                            peak_around (0.1 * details_.tie_tie_collision_distance_,
835                                         details_.tie_tie_collision_distance_,
836                                         fabs (edge - last_edge)), "tietie edge");
837         }
838
839       last_edge = edge;
840       last_center = center;
841     }
842
843   if (ties->size () > 1)
844     {
845       ties->add_score (details_.outer_tie_length_symmetry_penalty_factor_
846                        * fabs (ties->at (0).attachment_x_.length () - ties->back ().attachment_x_.length ()),
847                        "length symm");
848
849       ties->add_score (details_.outer_tie_vertical_distance_symmetry_penalty_factor_
850                        * fabs (fabs (specifications_[0].position_ * 0.5 * details_.staff_space_
851                                      - (ties->at (0).position_ * 0.5 * details_.staff_space_
852                                         + ties->at (0).delta_y_))
853                                -
854                                fabs (specifications_.back ().position_ * 0.5 * details_.staff_space_
855                                      - (ties->back ().position_ * 0.5 * details_.staff_space_
856                                         + ties->back ().delta_y_))),
857                        "pos symmetry");
858     }
859 }
860
861 /*
862   Generate with correct X-attachments and beziers, copying delta_y_
863   from TIES_CONFIG if necessary.
864 */
865 Ties_configuration
866 Tie_formatting_problem::generate_ties_configuration (Ties_configuration const &ties_config)
867 {
868   Ties_configuration copy;
869   for (vsize i = 0; i < ties_config.size (); i++)
870     {
871       Tie_configuration *ptr = get_configuration (ties_config[i].position_, ties_config[i].dir_,
872                                                   ties_config[i].column_ranks_,
873                                                   !specifications_[i].has_manual_delta_y_);
874       if (specifications_[i].has_manual_delta_y_)
875         {
876           ptr->delta_y_
877             = (specifications_[i].manual_position_ - ties_config[i].position_)
878               * 0.5 * details_.staff_space_;
879         }
880       copy.push_back (*ptr);
881     }
882
883   return copy;
884 }
885
886 Ties_configuration
887 Tie_formatting_problem::generate_base_chord_configuration ()
888 {
889   Ties_configuration ties_config;
890   for (vsize i = 0; i < specifications_.size (); i++)
891     {
892       Tie_configuration conf;
893       if (specifications_[i].has_manual_dir_)
894         conf.dir_ = specifications_[i].manual_dir_;
895       if (specifications_[i].has_manual_position_)
896         {
897           conf.position_ = (int) my_round (specifications_[i].manual_position_);
898           if (specifications_[i].has_manual_delta_y_)
899             conf.delta_y_ = (specifications_[i].manual_position_ - conf.position_)
900                             * 0.5 * details_.staff_space_;
901         }
902       else
903         {
904           conf.position_ = specifications_[i].position_;
905         }
906
907       conf.column_ranks_ = specifications_[i].column_ranks_;
908       ties_config.push_back (conf);
909     }
910
911   set_ties_config_standard_directions (&ties_config);
912   for (vsize i = 0; i < ties_config.size (); i++)
913     if (!specifications_[i].manual_position_)
914       ties_config[i].position_ += ties_config[i].dir_;
915
916   ties_config = generate_ties_configuration (ties_config);
917
918   return ties_config;
919 }
920
921 Ties_configuration
922 Tie_formatting_problem::find_best_variation (Ties_configuration const &base,
923                                              vector<Tie_configuration_variation> const &vars)
924 {
925   Ties_configuration best = base;
926
927   /*
928     This simply is 1-opt: we have K substitions, and we try applying
929     exactly every one for each.
930   */
931   for (vsize i = 0; i < vars.size (); i++)
932     {
933       Ties_configuration variant (base);
934       for (vsize j = 0; j < vars[i].index_suggestion_pairs_.size (); j++)
935         variant[vars[i].index_suggestion_pairs_[j].first] = *vars[i].index_suggestion_pairs_[j].second;
936
937       variant.reset_score ();
938       score_ties (&variant);
939
940       if (variant.score () < best.score ())
941         {
942           best = variant;
943         }
944     }
945
946   return best;
947 }
948
949 Ties_configuration
950 Tie_formatting_problem::generate_optimal_configuration ()
951 {
952   Ties_configuration base = generate_base_chord_configuration ();
953   score_ties (&base);
954
955   vector<Tie_configuration_variation> vars;
956   if (specifications_.size () > 1)
957     vars = generate_collision_variations (base);
958   else
959     vars = generate_single_tie_variations (base);
960
961   Ties_configuration best = find_best_variation (base, vars);
962
963   if (specifications_.size () > 1)
964     {
965       vars = generate_extremal_tie_variations (best);
966       best = find_best_variation (best, vars);
967     }
968   return best;
969 }
970
971 void
972 Tie_formatting_problem::set_ties_config_standard_directions (Ties_configuration *tie_configs)
973 {
974   if (tie_configs->empty ())
975     return;
976
977   if (!tie_configs->at (0).dir_)
978     {
979       if (tie_configs->size () == 1)
980         tie_configs->at (0).dir_ = Direction (sign (tie_configs->at (0).position_));
981
982       if (!tie_configs->at (0).dir_)
983         tie_configs->at (0).dir_
984           = (tie_configs->size () > 1) ? DOWN : details_.neutral_direction_;
985     }
986
987   if (!tie_configs->back ().dir_)
988     tie_configs->back ().dir_ = UP;
989
990   /*
991     Seconds
992    */
993   for (vsize i = 1; i < tie_configs->size (); i++)
994     {
995       Real diff = (tie_configs->at (i).position_
996                    - tie_configs->at (i - 1).position_);
997
998       Real span_diff
999         = specifications_[i].column_span () - specifications_[i - 1].column_span ();
1000       if (span_diff && fabs (diff) <= 2)
1001         {
1002           if (span_diff > 0)
1003             tie_configs->at (i).dir_ = UP;
1004           else if (span_diff < 0)
1005             tie_configs->at (i - 1).dir_ = DOWN;
1006         }
1007       else if (fabs (diff) <= 1)
1008         {
1009           if (!tie_configs->at (i - 1).dir_)
1010             tie_configs->at (i - 1).dir_ = DOWN;
1011           if (!tie_configs->at (i).dir_)
1012             tie_configs->at (i).dir_ = UP;
1013         }
1014     }
1015
1016   for (vsize i = 1; i + 1 < tie_configs->size (); i++)
1017     {
1018       Tie_configuration &conf = tie_configs->at (i);
1019       if (conf.dir_)
1020         continue;
1021
1022       Direction position_dir
1023         = Direction (sign (conf.position_));
1024       if (!position_dir)
1025         position_dir = DOWN;
1026
1027       conf.dir_ = position_dir;
1028     }
1029 }
1030
1031 vector<Tie_configuration_variation>
1032 Tie_formatting_problem::generate_extremal_tie_variations (Ties_configuration const &ties) const
1033 {
1034   vector<Tie_configuration_variation> vars;
1035   Direction d = DOWN;
1036   for (int i = 1; i <= details_.multi_tie_region_size_; i++)
1037     {
1038       Drul_array<Tie_configuration *> configs (0, 0);
1039       do
1040         {
1041           const Tie_configuration &config = boundary (ties, d, 0);
1042           if (config.dir_ == d
1043               && !boundary (specifications_, d, 0).has_manual_position_)
1044             {
1045               Tie_configuration_variation var;
1046               configs[d] = get_configuration (config.position_ + d * i, d,
1047                                               config.column_ranks_,
1048                                               true);
1049               var.add_suggestion ((d == DOWN) ? 0 : ties.size () - 1,
1050                                   configs[d]);
1051               vars.push_back (var);
1052             }
1053         }
1054       while (flip (&d) != DOWN);
1055       if (configs[LEFT] && configs[RIGHT])
1056         {
1057           Tie_configuration_variation var;
1058           var.add_suggestion (0, configs[DOWN]);
1059           var.add_suggestion (ties.size () - 1, configs[UP]);
1060           vars.push_back (var);
1061         }
1062     }
1063
1064   return vars;
1065 }
1066
1067 vector<Tie_configuration_variation>
1068 Tie_formatting_problem::generate_single_tie_variations (Ties_configuration const &ties) const
1069 {
1070   vector<Tie_configuration_variation> vars;
1071
1072   int sz = details_.single_tie_region_size_;
1073   if (specifications_[0].has_manual_position_)
1074     sz = 1;
1075   for (int i = 0; i < sz; i++)
1076     {
1077       Direction d = LEFT;
1078       do
1079         {
1080           if (i == 0
1081               && ties[0].dir_ == d)
1082             continue;
1083
1084           int p = ties[0].position_ + i * d;
1085
1086           if (!specifications_[0].has_manual_dir_
1087               || d == specifications_[0].manual_dir_)
1088             {
1089               Tie_configuration_variation var;
1090               var.add_suggestion (0,
1091                                   get_configuration (p,
1092                                                      d, specifications_[0].column_ranks_,
1093                                                      !specifications_[0].has_manual_delta_y_));
1094               vars.push_back (var);
1095             }
1096         }
1097       while (flip (&d) != LEFT);
1098     }
1099   return vars;
1100 }
1101
1102 vector<Tie_configuration_variation>
1103 Tie_formatting_problem::generate_collision_variations (Ties_configuration const &ties) const
1104 {
1105   Real center_distance_tolerance = 0.25;
1106
1107   vector<Tie_configuration_variation> vars;
1108   Real last_center = 0.0;
1109   for (vsize i = 0; i < ties.size (); i++)
1110     {
1111       Bezier b (ties[i].get_transformed_bezier (details_));
1112
1113       Real center = b.curve_point (0.5)[Y_AXIS];
1114
1115       if (i)
1116         {
1117           if (center <= last_center + center_distance_tolerance)
1118             {
1119               if (!specifications_[i].has_manual_dir_)
1120                 {
1121                   Tie_configuration_variation var;
1122                   var.add_suggestion (i,
1123                                       get_configuration (specifications_[i].position_
1124                                                          - ties[i].dir_,
1125                                                          - ties[i].dir_,
1126
1127                                                          ties[i].column_ranks_,
1128                                                          !specifications_[i].has_manual_delta_y_
1129                                                         ));
1130
1131                   vars.push_back (var);
1132                 }
1133
1134               if (!specifications_[i - 1].has_manual_dir_)
1135                 {
1136                   Tie_configuration_variation var;
1137                   var.add_suggestion (i - 1,
1138                                       get_configuration (specifications_[i - 1].position_
1139                                                          - ties[i - 1].dir_,
1140                                                          - ties[i - 1].dir_,
1141                                                          specifications_[i - 1].column_ranks_,
1142                                                          !specifications_[i - 1].has_manual_delta_y_));
1143
1144                   vars.push_back (var);
1145                 }
1146
1147               if (i == 1 && !specifications_[i - 1].has_manual_position_
1148                   && ties[i - 1].dir_ == DOWN)
1149                 {
1150                   Tie_configuration_variation var;
1151                   var.add_suggestion (i - 1,
1152                                       get_configuration (specifications_[i - 1].position_ - 1, DOWN,
1153                                                          specifications_[i - 1].column_ranks_,
1154                                                          !specifications_[i - 1].has_manual_delta_y_
1155                                                         ));
1156                   vars.push_back (var);
1157                 }
1158               if (i == ties.size () && !specifications_[i].has_manual_position_
1159                   && ties[i].dir_ == UP)
1160                 {
1161                   Tie_configuration_variation var;
1162                   var.add_suggestion (i,
1163                                       get_configuration (specifications_[i].position_
1164                                                          + 1, UP,
1165                                                          specifications_[i].column_ranks_,
1166                                                          !specifications_[i].has_manual_delta_y_
1167                                                         ));
1168                   vars.push_back (var);
1169                 }
1170             }
1171           else if (dot_positions_.find (ties[i].position_) != dot_positions_.end ()
1172                    && !specifications_[i].has_manual_position_)
1173             {
1174               Tie_configuration_variation var;
1175               var.add_suggestion (i,
1176                                   get_configuration (ties[i].position_ + ties[i].dir_,
1177                                                      ties[i].dir_,
1178                                                      ties[i].column_ranks_,
1179                                                      !specifications_[i].has_manual_delta_y_
1180                                                     ));
1181               vars.push_back (var);
1182             }
1183
1184         }
1185
1186       last_center = center;
1187     }
1188
1189   return vars;
1190 }
1191
1192 void
1193 Tie_formatting_problem::set_manual_tie_configuration (SCM manual_configs)
1194 {
1195   vsize k = 0;
1196   for (SCM s = manual_configs;
1197        scm_is_pair (s) && k < specifications_.size (); s = scm_cdr (s))
1198     {
1199       SCM entry = scm_car (s);
1200       if (scm_is_pair (entry))
1201         {
1202           Tie_specification &spec = specifications_[k];
1203
1204           if (scm_is_number (scm_car (entry)))
1205             {
1206               spec.has_manual_position_ = true;
1207               spec.manual_position_ = scm_to_double (scm_car (entry));
1208               spec.has_manual_delta_y_ = (scm_inexact_p (scm_car (entry)) == SCM_BOOL_T);
1209             }
1210
1211           if (scm_is_number (scm_cdr (entry)))
1212             {
1213               spec.has_manual_dir_ = true;
1214               spec.manual_dir_ = Direction (scm_to_int (scm_cdr (entry)));
1215             }
1216         }
1217       k++;
1218     }
1219 }
1220
1221 void
1222 Tie_formatting_problem::set_debug_scoring (Ties_configuration const &base)
1223 {
1224 #if DEBUG_TIE_SCORING
1225   if (to_boolean (x_refpoint_->layout ()
1226                   ->lookup_variable (ly_symbol2scm ("debug-tie-scoring"))))
1227     {
1228       for (vsize i = 0; i < base.size (); i++)
1229         {
1230           string card = base.complete_tie_card (i);
1231           specifications_[i].tie_grob_->set_property ("annotation",
1232                                                       ly_string2scm (card));
1233         }
1234     }
1235 #endif
1236 }