]> git.donarmstrong.com Git - lilypond.git/blob - lily/beam-quanting.cc
Divide collision Y extent by staff_space; add regression test.
[lilypond.git] / lily / beam-quanting.cc
1 /*
2   This file is part of LilyPond, the GNU music typesetter.
3
4   Copyright (C) 1997--2011 Han-Wen Nienhuys <hanwen@xs4all.nl>
5   Jan Nieuwenhuizen <janneke@gnu.org>
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 "beam-scoring-problem.hh"
22
23 #include <algorithm>
24 #include <queue>  
25 #include <set>
26 using namespace std;
27
28 #include "align-interface.hh"
29 #include "beam.hh"
30 #include "direction.hh"
31 #include "directional-element-interface.hh"
32 #include "grob.hh"
33 #include "international.hh"
34 #include "libc-extension.hh"
35 #include "main.hh"
36 #include "output-def.hh"
37 #include "pointer-group-interface.hh"
38 #include "staff-symbol-referencer.hh"
39 #include "stencil.hh"
40 #include "stem.hh"
41 #include "warn.hh"
42
43 Real
44 get_detail (SCM alist, SCM sym, Real def)
45 {
46   SCM entry = scm_assq (sym, alist);
47
48   if (scm_is_pair (entry))
49     return robust_scm2double (scm_cdr (entry), def);
50   return def;
51 }
52
53 void
54 Beam_quant_parameters::fill (Grob *him)
55 {
56   SCM details = him->get_property ("details");
57
58   // General
59   BEAM_EPS = get_detail (details, ly_symbol2scm ("beam-eps"), 1e-3);
60   REGION_SIZE = get_detail (details, ly_symbol2scm ("region-size"), 2);
61
62   // forbidden quants
63   SECONDARY_BEAM_DEMERIT = get_detail (details, ly_symbol2scm ("secondary-beam-demerit"), 10.0);
64   STEM_LENGTH_DEMERIT_FACTOR = get_detail (details, ly_symbol2scm ("stem-length-demerit-factor"), 5);
65   HORIZONTAL_INTER_QUANT_PENALTY = get_detail (details, ly_symbol2scm ("horizontal-inter-quant"), 500);
66
67   STEM_LENGTH_LIMIT_PENALTY = get_detail (details, ly_symbol2scm ("stem-length-limit-penalty"), 5000);
68   DAMPING_DIRECTION_PENALTY = get_detail (details, ly_symbol2scm ("damping-direction-penalty"), 800);
69   HINT_DIRECTION_PENALTY = get_detail (details, ly_symbol2scm ("hint-direction-penalty"), 20);
70   MUSICAL_DIRECTION_FACTOR = get_detail (details, ly_symbol2scm ("musical-direction-factor"), 400);
71   IDEAL_SLOPE_FACTOR = get_detail (details, ly_symbol2scm ("ideal-slope-factor"), 10);
72   ROUND_TO_ZERO_SLOPE = get_detail (details, ly_symbol2scm ("round-to-zero-slope"), 0.02);
73
74   // Collisions
75   COLLISION_PENALTY = get_detail (details, ly_symbol2scm ("collision-penalty"), 500);
76   COLLISION_PADDING = get_detail (details, ly_symbol2scm ("collision-padding"), 0.5);
77   STEM_COLLISION_FACTOR = get_detail (details, ly_symbol2scm ("stem-collision-factor"), 0.1);
78 }
79
80 // Add x if x is positive, add |x|*fac if x is negative.
81 static Real
82 shrink_extra_weight (Real x, Real fac)
83 {
84   return fabs (x) * ((x < 0) ? fac : 1.0);
85 }
86
87 /****************************************************************/
88
89 Beam_configuration::Beam_configuration ()
90 {
91   y = Interval (0.0, 0.0);
92   demerits = 0.0;
93   next_scorer_todo = ORIGINAL_DISTANCE;
94 }
95
96 bool Beam_configuration::done () const
97 {
98   return next_scorer_todo >= NUM_SCORERS;
99 }
100
101 void Beam_configuration::add (Real demerit, const string &reason)
102 {
103   demerits += demerit;
104
105 #if DEBUG_BEAM_SCORING
106   if (demerit) 
107     score_card_ += to_string (" %s %.2f", reason.c_str (), demerit);
108 #endif
109 }
110   
111 Beam_configuration* Beam_configuration::new_config (Interval start,
112                                                     Interval offset)
113 {
114   Beam_configuration* qs = new Beam_configuration;
115   qs->y = Interval (int (start[LEFT]) + offset[LEFT],
116                     int (start[RIGHT]) + offset[RIGHT]);
117
118   // This orders the sequence so we try combinations closest to the
119   // the ideal offset first.
120   Real start_score = abs (offset[RIGHT]) + abs (offset[LEFT]);
121   qs->demerits = start_score / 1000.0;
122   qs->next_scorer_todo = ORIGINAL_DISTANCE + 1;
123   
124   return qs;
125 }
126
127 Real
128 Beam_scoring_problem::y_at (Real x, Beam_configuration const* p) const {
129   return p->y[LEFT] + (x - x_span[LEFT]) * p->y.delta() / x_span.delta();
130 }
131
132 /****************************************************************/
133
134 /*
135   TODO:
136
137   - Make all demerits customisable
138
139   - Add demerits for quants per se, as to forbid a specific quant
140   entirely
141 */
142
143 // This is a temporary hack to see how much we can gain by using a
144 // priority queue on the beams to score.
145 static int score_count = 0;
146 LY_DEFINE (ly_beam_score_count, "ly:beam-score-count", 0, 0, 0,
147            (),
148            "count number of beam scores.") {
149   return scm_from_int (score_count);
150 }
151
152 void Beam_scoring_problem::add_collision (Real x, Interval y,
153                                           Real score_factor)
154 {
155   if (edge_dirs[LEFT] == edge_dirs[RIGHT]) {
156     Direction d = edge_dirs[LEFT];
157
158     Real quant_range_y = quant_range[LEFT][-d] +
159       (x - x_span[LEFT]) * (quant_range[RIGHT][-d] - quant_range[LEFT][-d]) / x_span.delta();
160
161     if (d*(quant_range_y - minmax(d, y[UP], y[DOWN])) > 0) {
162       return;
163     }
164   }
165
166   Beam_collision c;
167   c.beam_y_.set_empty ();
168
169   for (vsize j = 0; j < segments_.size (); j++)
170     {
171       if (segments_[j].horizontal_.contains(x))
172         c.beam_y_.add_point (segments_[j].vertical_count_ * beam_translation);
173       if (segments_[j].horizontal_[LEFT] > x)
174         break;
175     }
176   c.beam_y_.widen (0.5 * beam_thickness);
177   
178   c.x_ = x;
179
180   y *= 1/staff_space;
181   c.y_ = y;
182   c.base_penalty_ = score_factor;
183   collisions_.push_back (c);
184 }
185
186 void Beam_scoring_problem::init_collisions (vector<Grob*> grobs)
187 {
188   Grob* common_x = NULL;
189   segments_ = Beam::get_beam_segments (beam, &common_x);
190   vector_sort (segments_, beam_segment_less);
191   if (common[X_AXIS] != common_x)
192     {
193       programming_error ("Disagree on common x. Skipping collisions in beam scoring.");
194       return;
195     }
196
197   set<Grob*> stems;
198   for (vsize i = 0; i < grobs.size (); i++) {
199     Box b;
200     for (Axis a = X_AXIS; a < NO_AXES; incr (a))
201       b[a] = grobs[i]->extent(common[a], a);
202
203     Real width = b[X_AXIS].length ();
204     Real width_factor = sqrt (width / staff_space);
205
206     Direction d = LEFT;
207     do
208       add_collision (b[X_AXIS][d], b[Y_AXIS], width_factor);
209     while (flip (&d) != LEFT);
210
211     Grob* stem = unsmob_grob (grobs[i]->get_object ("stem"));
212     if (stem && Stem::has_interface (stem) && Stem::is_normal_stem (stem))
213       {
214         stems.insert (stem);
215       }
216   }
217   
218   for (set<Grob*>::const_iterator it(stems.begin ()); it != stems.end (); it++)
219     {
220       Grob *s = *it;
221       Real x = s->extent (common[X_AXIS], X_AXIS).center();
222
223       Direction stem_dir = get_grob_direction (*it);
224       Interval y;
225       y.set_full ();
226       y[-stem_dir] = Stem::chord_start_y (*it) + (*it)->relative_coordinate (common[Y_AXIS], Y_AXIS)
227         - beam->relative_coordinate (common[Y_AXIS], Y_AXIS);
228
229       Real factor = parameters.STEM_COLLISION_FACTOR;
230       if (!unsmob_grob (s->get_object ("beam"))
231           && !Stem::flag (s).is_empty ())
232         factor = 1.0; 
233       add_collision (x, y, factor);
234     }
235 }
236   
237 void Beam_scoring_problem::init_stems ()
238 {
239   extract_grob_set (beam, "covered-grobs", collisions);
240   extract_grob_set (beam, "stems", stems);
241   for (int a = 2; a--;)
242     {
243       common[a] = common_refpoint_of_array (stems, beam, Axis (a));
244       common[a] = common_refpoint_of_array (collisions, common[a], Axis (a));
245     }
246   
247   Drul_array<Grob *> edge_stems(Beam::first_normal_stem (beam),
248                                 Beam::last_normal_stem (beam));
249   Direction d = LEFT;
250   do
251     x_span[d] = edge_stems[d] ? edge_stems[d]->relative_coordinate (common[X_AXIS], X_AXIS) : 0.0;
252   while (flip (&d) != LEFT);
253   
254   Drul_array<bool> dirs_found (0, 0);
255   for (vsize i = 0; i < stems.size (); i++)
256     {
257       Grob *s = stems[i];
258       if (!Stem::is_normal_stem (s))
259         continue;
260       
261       Stem_info si (Stem::get_stem_info (s));
262       si.scale (1 / staff_space);
263       stem_infos.push_back (si);
264       dirs_found[si.dir_] = true;
265
266       bool f = to_boolean (s->get_property ("french-beaming"))
267         && s != edge_stems[LEFT] && s != edge_stems[RIGHT];
268
269       Real y = Beam::calc_stem_y (beam, s, common, x_span[LEFT], x_span[RIGHT], CENTER, 
270                                   Interval (0, 0), f);
271       base_lengths.push_back (y / staff_space);
272       stem_xpositions.push_back (s->relative_coordinate (common[X_AXIS], X_AXIS));
273     }
274   
275   edge_dirs = Drul_array<Direction> (CENTER, CENTER);
276   if (stem_infos.size ())
277     {
278       edge_dirs = Drul_array<Direction> (stem_infos[0].dir_,
279                                          stem_infos.back().dir_);
280     }
281
282   is_xstaff = Align_interface::has_interface (common[Y_AXIS]);
283   is_knee = dirs_found[LEFT] && dirs_found[RIGHT];
284   
285   staff_radius = Staff_symbol_referencer::staff_radius (beam);
286   edge_beam_counts =  Drul_array<int>
287     (Stem::beam_multiplicity (stems[0]).length () + 1,
288      Stem::beam_multiplicity (stems.back ()).length () + 1);
289
290   // TODO - why are we dividing by staff_space?
291   beam_translation = Beam::get_beam_translation (beam) / staff_space;
292
293   d = LEFT;
294   do
295     {
296       quant_range[d].set_full ();
297       if (!edge_stems[d])
298         continue;
299       
300       Real stem_offset = edge_stems[d]->relative_coordinate (common[Y_AXIS], Y_AXIS)
301         - beam->relative_coordinate (common[Y_AXIS], Y_AXIS);
302       Interval heads = Stem::head_positions(edge_stems[d]) * 0.5 * staff_space;
303
304       Direction ed = edge_dirs[d];
305       heads.widen(0.5 * staff_space
306                   + (edge_beam_counts[d] - 1) * beam_translation + beam_thickness * .5);
307       quant_range[d][-ed] = heads[ed] + stem_offset;
308     }
309   while (flip (&d) != LEFT);
310
311   init_collisions (collisions);
312 }
313
314 Beam_scoring_problem::Beam_scoring_problem (Grob *me, Drul_array<Real> ys)
315 {
316   beam = me;
317   unquanted_y = ys;
318     
319   /*
320     Calculations are relative to a unit-scaled staff, i.e. the quants are
321     divided by the current staff_space.
322   */
323   staff_space = Staff_symbol_referencer::staff_space (me);
324   beam_thickness = Beam::get_beam_thickness (me) / staff_space;
325   line_thickness = Staff_symbol_referencer::line_thickness (me) / staff_space;
326
327   // This is the least-squares DY, corrected for concave beams.
328   musical_dy = robust_scm2double (me->get_property ("least-squares-dy"), 0);
329
330   parameters.fill (me);
331   init_stems ();
332 }
333
334 void
335 Beam_scoring_problem::generate_quants (vector<Beam_configuration*> *scores) const
336 {
337   int region_size = (int) parameters.REGION_SIZE;
338
339   // Knees and collisions are harder, lets try some more possibilities
340   if (is_knee)
341     region_size += 2;
342   if (collisions_.size ())
343     region_size += 2;
344   
345   Real straddle = 0.0;
346   Real sit = (beam_thickness - line_thickness) / 2;
347   Real inter = 0.5;
348   Real hang = 1.0 - (beam_thickness - line_thickness) / 2;
349   Real base_quants [] = {straddle, sit, inter, hang};
350   int num_base_quants = int (sizeof (base_quants) / sizeof (Real));
351
352   /*
353     Asymetry ? should run to <= region_size ?
354   */
355   vector<Real> unshifted_quants;
356   for (int i = -region_size; i < region_size; i++)
357     for (int j = 0; j < num_base_quants; j++)
358       {
359         unshifted_quants.push_back (i + base_quants[j]);
360       }
361
362   for (vsize i = 0; i < unshifted_quants.size (); i++)
363     for (vsize j = 0; j < unshifted_quants.size (); j++)
364       {
365         Beam_configuration *c =
366           Beam_configuration::new_config (unquanted_y,
367                                           Interval (unshifted_quants[i],
368                                                     unshifted_quants[j]));
369         
370         Direction d = LEFT;
371         do
372           {
373             if (!quant_range[d].contains (c->y[d]))
374               {
375                 delete c;
376                 c = NULL;
377                 break;
378               }
379           }
380         while (flip (&d) != LEFT);
381         if (c)   
382           scores->push_back (c);
383       }
384     
385 }
386
387
388 void Beam_scoring_problem::one_scorer (Beam_configuration* config) const
389 {
390   score_count ++;
391   switch (config->next_scorer_todo) {
392   case SLOPE_IDEAL:
393     score_slope_ideal (config);
394     break;
395   case SLOPE_DIRECTION:
396     score_slope_direction (config);
397     break;
398   case SLOPE_MUSICAL:
399     score_slope_musical (config);
400     break;
401   case FORBIDDEN:
402     score_forbidden_quants (config);
403     break;
404   case STEM_LENGTHS:
405     score_stem_lengths (config);
406     break;
407   case COLLISIONS:
408     score_collisions (config);
409     break;
410   case HORIZONTAL_INTER:
411     score_horizontal_inter_quants (config);
412     break;
413     
414   case NUM_SCORERS:
415   case ORIGINAL_DISTANCE:
416   default:
417     assert (false);
418   }
419   config->next_scorer_todo++;
420 }                                  
421
422
423 Beam_configuration *
424 Beam_scoring_problem::force_score (SCM inspect_quants, const vector<Beam_configuration*> &configs) const
425 {
426   Drul_array<Real> ins = ly_scm2interval (inspect_quants);
427   Real mindist = 1e6;
428   Beam_configuration *best = NULL; 
429   for (vsize i = 0; i < configs.size (); i++)
430     {
431       Real d = fabs (configs[i]->y[LEFT]- ins[LEFT]) + fabs (configs[i]->y[RIGHT] - ins[RIGHT]);
432       if (d < mindist)
433         {
434           best = configs[i];
435           mindist = d;
436         }
437     }
438   if (mindist > 1e5)
439     programming_error ("cannot find quant");
440
441   while (!best->done ())
442     one_scorer (best);
443       
444   return best;
445 }
446
447 Drul_array<Real>
448 Beam_scoring_problem::solve () const {
449   vector<Beam_configuration*> configs;
450   generate_quants (&configs);
451
452   if (configs.empty ())
453     {
454       programming_error ("No viable beam quanting found.  Using unquanted y value.");
455       return unquanted_y;
456     }
457
458   Beam_configuration *best = NULL;  
459
460   bool debug =
461     to_boolean (beam->layout ()->lookup_variable (ly_symbol2scm ("debug-beam-scoring")));
462   SCM inspect_quants = beam->get_property ("inspect-quants");
463   if (scm_is_pair (inspect_quants)) 
464     {
465       debug = true;
466       best = force_score (inspect_quants, configs);
467     }
468   else
469     {
470       std::priority_queue<Beam_configuration*, std::vector<Beam_configuration*>,
471                           Beam_configuration_less> queue;
472       for (vsize i = 0; i < configs.size(); i++)
473         queue.push(configs[i]);
474
475       /*
476         TODO
477
478         It would be neat if we generated new configurations on the
479         fly, depending on the best complete score so far, eg.
480
481         if (best->done()) {
482           if (best->demerits < sqrt(queue.size())
483             break;
484           while (best->demerits > sqrt(queue.size()) {
485             generate and insert new configuration
486           }
487         }
488
489         that would allow us to do away with region_size altogether.
490       */
491       while (true) {
492         best = queue.top ();
493         if (best->done ())
494           break;
495
496         queue.pop ();
497         one_scorer (best);
498         queue.push (best);
499       }
500     }
501
502   Interval final_positions = best->y;
503
504 #if DEBUG_BEAM_SCORING
505   if (debug)
506     {
507       // debug quanting
508       int completed = 0;
509       for (vsize i = 0; i < configs.size (); i++)
510         {
511           if (configs[i]->done ())
512             completed++;
513         }
514
515       string card = best->score_card_ + to_string (" c%d/%d", completed, configs.size());
516       beam->set_property ("annotation", ly_string2scm (card));
517     }
518 #endif
519
520   junk_pointers (configs);
521   return final_positions;
522 }
523
524 void
525 Beam_scoring_problem::score_stem_lengths (Beam_configuration* config) const
526 {
527   Real limit_penalty = parameters.STEM_LENGTH_LIMIT_PENALTY;
528   Drul_array<Real> score (0, 0);
529   Drul_array<int> count (0, 0);
530
531   for (vsize i = 0; i < stem_xpositions.size (); i++)
532     {
533       Real x = stem_xpositions[i];
534       Real dx = x_span.delta ();
535       Real beam_y = dx
536         ? config->y[RIGHT] * (x - x_span[LEFT]) / dx + config->y[LEFT] * (x_span[RIGHT] - x) / dx
537         : (config->y[RIGHT] + config->y[LEFT]) / 2;
538       Real current_y = beam_y + base_lengths[i];
539       Real length_pen = parameters.STEM_LENGTH_DEMERIT_FACTOR;
540
541       Stem_info info = stem_infos[i];
542       Direction d = info.dir_;
543
544       score[d] += limit_penalty * max (0.0, (d * (info.shortest_y_ - current_y)));
545
546       Real ideal_diff = d * (current_y - info.ideal_y_);
547       Real ideal_score = shrink_extra_weight (ideal_diff, 1.5);
548
549       /* We introduce a power, to make the scoring strictly
550          convex. Otherwise a symmetric knee beam (up/down/up/down)
551          does not have an optimum in the middle. */
552       if (is_knee)
553         ideal_score = pow (ideal_score, 1.1);
554
555       score[d] += length_pen * ideal_score;
556       count[d]++;
557     }
558
559   /* Divide by number of stems, to make the measure scale-free. */
560   Direction d = DOWN;
561   do
562     score[d] /= max (count[d], 1);
563   while (flip (&d) != DOWN);
564
565   config->add (score[LEFT] + score[RIGHT], "L");
566 }
567
568 void
569 Beam_scoring_problem::score_slope_direction (Beam_configuration *config) const
570 {
571   Real dy = config->y.delta ();
572   Real damped_dy = unquanted_y.delta();
573   Real dem = 0.0;
574   /*
575     DAMPING_DIRECTION_PENALTY is a very harsh measure, while for
576     complex beaming patterns, horizontal is often a good choice.
577
578     TODO: find a way to incorporate the complexity of the beam in this
579     penalty.
580   */
581   if (sign (damped_dy) != sign (dy))
582     {
583       if (!dy)
584         {
585           if (fabs (damped_dy / x_span.delta ()) > parameters.ROUND_TO_ZERO_SLOPE)
586             dem += parameters.DAMPING_DIRECTION_PENALTY;
587           else
588             dem += parameters.HINT_DIRECTION_PENALTY;
589         }
590       else
591         dem += parameters.DAMPING_DIRECTION_PENALTY;
592     }
593
594   config->add (dem, "Sd");
595 }
596
597 // Score for going against the direction of the musical pattern 
598 void
599 Beam_scoring_problem::score_slope_musical (Beam_configuration *config) const
600 {
601   Real dy = config->y.delta ();
602   Real dem = parameters.MUSICAL_DIRECTION_FACTOR
603     * max (0.0, (fabs (dy) - fabs (musical_dy)));
604   config->add (dem, "Sm");
605 }
606
607 // Score deviation from calculated ideal slope.
608 void
609 Beam_scoring_problem::score_slope_ideal (Beam_configuration *config) const
610 {
611   Real dy = config->y.delta ();
612   Real damped_dy = unquanted_y.delta();
613   Real dem = 0.0;
614   
615   Real slope_penalty = parameters.IDEAL_SLOPE_FACTOR;
616
617   /* Xstaff beams tend to use extreme slopes to get short stems. We
618      put in a penalty here. */
619   if (is_xstaff)
620     slope_penalty *= 10;
621
622   /* Huh, why would a too steep beam be better than a too flat one ? */
623   dem += shrink_extra_weight (fabs (damped_dy) - fabs (dy), 1.5)
624     * slope_penalty;
625
626   config->add (dem, "Si");
627 }
628
629 static Real
630 my_modf (Real x)
631 {
632   return x - floor (x);
633 }
634
635 // TODO - there is some overlap with forbidden quants, but for
636 // horizontal beams, it is much more serious to have stafflines
637 // appearing in the wrong place, so we have a separate scorer.
638 void
639 Beam_scoring_problem::score_horizontal_inter_quants (Beam_configuration *config) const
640 {
641   if (config->y.delta () == 0.0
642       && abs (config->y[LEFT]) < staff_radius * staff_space)
643     {
644       Real yshift = config->y[LEFT] - 0.5 * staff_space;
645       if (fabs (my_round (yshift) - yshift) < 0.01 * staff_space)
646         config->add (parameters.HORIZONTAL_INTER_QUANT_PENALTY, "H");
647     }
648 }
649
650 /*
651   TODO: The fixed value SECONDARY_BEAM_DEMERIT is probably flawed:
652   because for 32nd and 64th beams the forbidden quants are relatively
653   more important than stem lengths.
654 */
655 void
656 Beam_scoring_problem::score_forbidden_quants (Beam_configuration *config) const
657 {
658   Real dy = config->y.delta ();
659
660   Real extra_demerit = parameters.SECONDARY_BEAM_DEMERIT /
661     max (edge_beam_counts[LEFT], edge_beam_counts[RIGHT]);
662
663   Direction d = LEFT;
664   Real dem = 0.0;
665   Real eps = parameters.BEAM_EPS;
666   
667   do
668     {
669       for (int j = 1; j <= edge_beam_counts[d]; j++)
670         {
671           Direction stem_dir = edge_dirs[d];
672
673           /*
674             The 2.2 factor is to provide a little leniency for
675             borderline cases. If we do 2.0, then the upper outer line
676             will be in the gap of the (2, sit) quant, leading to a
677             false demerit.
678           */
679           Real gap1 = config->y[d] - stem_dir * ((j - 1) * beam_translation + beam_thickness / 2 - line_thickness / 2.2);
680           Real gap2 = config->y[d] - stem_dir * (j * beam_translation - beam_thickness / 2 + line_thickness / 2.2);
681
682           Interval gap;
683           gap.add_point (gap1);
684           gap.add_point (gap2);
685
686           for (Real k = -staff_radius;
687                k <= staff_radius + eps; k += 1.0)
688             if (gap.contains (k))
689               {
690                 Real dist = min (fabs (gap[UP] - k), fabs (gap[DOWN] - k));
691
692                 /*
693                   this parameter is tuned to grace-stem-length.ly
694                 */
695                 Real fixed_demerit = 0.4;
696
697                 dem += extra_demerit
698                   * (fixed_demerit
699                      + (1 - fixed_demerit) * (dist / gap.length ()) * 2);
700               }
701         }
702     }
703   while ((flip (&d)) != LEFT);
704
705   if (max (edge_beam_counts[LEFT], edge_beam_counts[RIGHT]) >= 2)
706     {
707       Real straddle = 0.0;
708       Real sit = (beam_thickness - line_thickness) / 2;
709       Real inter = 0.5;
710       Real hang = 1.0 - (beam_thickness - line_thickness) / 2;
711
712       Direction d = LEFT;
713       do
714         {
715           if (edge_beam_counts[d] >= 2
716               && fabs (config->y[d] - edge_dirs[d] * beam_translation) < staff_radius + inter)
717             {
718               // TODO up/down symmetry.
719               if (edge_dirs[d] == UP && dy <= eps
720                   && fabs (my_modf (config->y[d]) - sit) < eps)
721                 dem += extra_demerit;
722
723               if (edge_dirs[d] == DOWN && dy >= eps
724                   && fabs (my_modf (config->y[d]) - hang) < eps)
725                 dem += extra_demerit;
726             }
727
728           if (edge_beam_counts[d] >= 3
729               && fabs (config->y[d] - 2 * edge_dirs[d] * beam_translation) < staff_radius + inter)
730             {
731               // TODO up/down symmetry.
732               if (edge_dirs[d] == UP && dy <= eps
733                   && fabs (my_modf (config->y[d]) - straddle) < eps)
734                 dem += extra_demerit;
735
736               if (edge_dirs[d] == DOWN && dy >= eps
737                   && fabs (my_modf (config->y[d]) - straddle) < eps)
738                 dem += extra_demerit;
739             }
740         }
741       while (flip (&d) != LEFT);
742     }
743
744   config->add (dem, "F");
745 }
746
747 void
748 Beam_scoring_problem::score_collisions (Beam_configuration *config) const
749 {  
750   Real demerits = 0.0;
751   for (vsize i = 0; i < collisions_.size (); i++)
752     {
753       Interval collision_y = collisions_[i].y_;
754       Real x = collisions_[i].x_;
755
756       Real center_beam_y = y_at (x, config);
757       Interval beam_y = center_beam_y + collisions_[i].beam_y_;
758
759       Real dist = infinity_f;
760       if (!intersection (beam_y, collision_y).is_empty ())
761         dist = 0.0;
762       else
763         dist = min (beam_y.distance (collision_y[DOWN]),
764                     beam_y.distance (collision_y[UP]));
765
766       Real scale_free = 
767         max (parameters.COLLISION_PADDING - dist, 0.0)/
768         parameters.COLLISION_PADDING;
769       demerits +=
770         collisions_[i].base_penalty_ *
771         pow (scale_free, 3) * parameters.COLLISION_PENALTY;
772     }
773
774   config->add (demerits, "C");
775