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