forked from musescore/MuseScore
-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
layout.cpp
5436 lines (4918 loc) · 233 KB
/
layout.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//=============================================================================
// MuseScore
// Music Composition & Notation
//
// Copyright (C) 2002-2016 Werner Schweer
//
// This program is free software; you can redistribute it and/or modify
// it under the terms of the GNU General Public License version 2
// as published by the Free Software Foundation and appearing in
// the file LICENCE.GPL
//=============================================================================
#include "accidental.h"
#include "arpeggio.h"
#include "barline.h"
#include "beam.h"
#include "box.h"
#include "chord.h"
#include "clef.h"
#include "element.h"
#include "fingering.h"
#include "glissando.h"
#include "harmony.h"
#include "key.h"
#include "keysig.h"
#include "layoutbreak.h"
#include "layout.h"
#include "lyrics.h"
#include "marker.h"
#include "measure.h"
#include "mmrestrange.h"
#include "mscore.h"
#include "notedot.h"
#include "note.h"
#include "ottava.h"
#include "page.h"
#include "part.h"
#include "repeat.h"
#include "score.h"
#include "segment.h"
#include "sig.h"
#include "slur.h"
#include "staff.h"
#include "stem.h"
#include "stemslash.h"
#include "sticking.h"
#include "style.h"
#include "sym.h"
#include "system.h"
#include "text.h"
#include "tie.h"
#include "timesig.h"
#include "tremolo.h"
#include "tuplet.h"
#include "undo.h"
#include "utils.h"
#include "volta.h"
#include "breath.h"
#include "tempotext.h"
#include "systemdivider.h"
#include "hook.h"
#include "ambitus.h"
#include "hairpin.h"
#include "stafflines.h"
#include "articulation.h"
#include "bracket.h"
#include "spacer.h"
#include "fermata.h"
#include "measurenumber.h"
namespace Ms {
// #define PAGE_DEBUG
#ifdef PAGE_DEBUG
#define PAGEDBG(...) qDebug(__VA_ARGS__)
#else
#define PAGEDBG(...) ;
#endif
//---------------------------------------------------------
// rebuildBspTree
//---------------------------------------------------------
void Score::rebuildBspTree()
{
for (Page* page : pages())
page->rebuildBspTree();
}
//---------------------------------------------------------
// layoutSegmentElements
//---------------------------------------------------------
static void layoutSegmentElements(Segment* segment, int startTrack, int endTrack)
{
for (int track = startTrack; track < endTrack; ++track) {
if (Element* e = segment->element(track))
e->layout();
}
}
#if 0
//---------------------------------------------------------
// vUp
// reurns true if chord should be treated as up
// for purpose of setting horizontal position
// for most chords, this is just chord->up()
// but for notes on cross-staff beams, we take care to produce more consistent results
// since the initial guess for up() may change during layout
//---------------------------------------------------------
static bool vUp(Chord* chord)
{
if (!chord)
return true;
else if (!chord->beam() || !chord->beam()->cross()) {
return chord->up();
}
else {
// cross-staff beam: we cannot know the actual direction of this chord until the beam layout,
// but that's too late - it won't work to lay out as if the chord is up on pass one but then down on pass two
// so just assign a logical direction based on attributes that won't change
// so chords can be laid out consistently on both passes
bool up;
if (chord->stemDirection() != Direction::AUTO)
up = chord->stemDirection() == Direction::UP;
else if (chord->staffMove())
up = chord->staffMove() > 0;
else if (chord->track() < chord->beam()->track())
up = false;
else if (chord->track() > chord->beam()->track())
up = true;
else if (chord->measure()->hasVoices(chord->staffIdx(), chord->tick(), chord->actualTicks()))
up = !(chord->track() % 2);
else
up = !chord->staff()->isTop();
return up;
}
}
#endif
//---------------------------------------------------------
// layoutChords1
// - layout upstem and downstem chords
// - offset as necessary to avoid conflict
//---------------------------------------------------------
void Score::layoutChords1(Segment* segment, int staffIdx)
{
const Staff* staff = Score::staff(staffIdx);
const int startTrack = staffIdx * VOICES;
const int endTrack = startTrack + VOICES;
const Fraction tick = segment->tick();
if (staff->isTabStaff(tick)) {
layoutSegmentElements(segment, startTrack, endTrack);
return;
}
bool crossBeamFound = false;
std::vector<Note*> upStemNotes;
std::vector<Note*> downStemNotes;
int upVoices = 0;
int downVoices = 0;
qreal nominalWidth = noteHeadWidth() * staff->mag(tick);
qreal maxUpWidth = 0.0;
qreal maxDownWidth = 0.0;
qreal maxUpMag = 0.0;
qreal maxDownMag = 0.0;
// dots and hooks can affect layout of notes as well as vice versa
int upDots = 0;
int downDots = 0;
bool upHooks = false;
bool downHooks = false;
// also check for grace notes
bool upGrace = false;
bool downGrace = false;
for (int track = startTrack; track < endTrack; ++track) {
Element* e = segment->element(track);
if (e && e->isChord()) {
Chord* chord = toChord(e);
if (chord->beam() && chord->beam()->cross())
crossBeamFound = true;
bool hasGraceBefore = false;
for (Chord* c : chord->graceNotes()) {
if (c->isGraceBefore())
hasGraceBefore = true;
layoutChords2(c->notes(), c->up()); // layout grace note noteheads
layoutChords3(c->notes(), staff, 0); // layout grace note chords
}
if (chord->up()) {
++upVoices;
upStemNotes.insert(upStemNotes.end(), chord->notes().begin(), chord->notes().end());
upDots = qMax(upDots, chord->dots());
maxUpMag = qMax(maxUpMag, chord->mag());
if (!upHooks)
upHooks = chord->hook();
if (hasGraceBefore)
upGrace = true;
}
else {
++downVoices;
downStemNotes.insert(downStemNotes.end(), chord->notes().begin(), chord->notes().end());
downDots = qMax(downDots, chord->dots());
maxDownMag = qMax(maxDownMag, chord->mag());
if (!downHooks)
downHooks = chord->hook();
if (hasGraceBefore)
downGrace = true;
}
}
}
if (upVoices + downVoices) {
// TODO: use track as secondary sort criteria?
// otherwise there might be issues with unisons between voices
// in some corner cases
maxUpWidth = nominalWidth * maxUpMag;
maxDownWidth = nominalWidth * maxDownMag;
// layout upstem noteheads
if (upVoices > 1) {
std::sort(upStemNotes.begin(), upStemNotes.end(),
[](Note* n1, const Note* n2) ->bool {return n1->line() > n2->line(); } );
}
if (upVoices) {
qreal hw = layoutChords2(upStemNotes, true);
maxUpWidth = qMax(maxUpWidth, hw);
}
// layout downstem noteheads
if (downVoices > 1) {
std::sort(downStemNotes.begin(), downStemNotes.end(),
[](Note* n1, const Note* n2) ->bool {return n1->line() > n2->line(); } );
}
if (downVoices) {
qreal hw = layoutChords2(downStemNotes, false);
maxDownWidth = qMax(maxDownWidth, hw);
}
qreal sp = staff->spatium(tick);
qreal upOffset = 0.0; // offset to apply to upstem chords
qreal downOffset = 0.0; // offset to apply to downstem chords
qreal dotAdjust = 0.0; // additional chord offset to account for dots
qreal dotAdjustThreshold = 0.0; // if it exceeds this amount
// centering adjustments for whole note, breve, and small chords
qreal centerUp = 0.0; // offset to apply in order to center upstem chords
qreal oversizeUp = 0.0; // adjustment to oversized upstem chord needed if laid out to the right
qreal centerDown = 0.0; // offset to apply in order to center downstem chords
qreal centerAdjustUp = 0.0; // adjustment to upstem chord needed after centering donwstem chord
qreal centerAdjustDown = 0.0; // adjustment to downstem chord needed after centering upstem chord
// only center chords if they differ from nominal by at least this amount
// this avoids unnecessary centering on differences due only to floating point roundoff
// it also allows for the possibility of disabling centering
// for notes only "slightly" larger than nominal, like half notes
// but this will result in them not being aligned with each other between voices
// unless you change to left alignment as described in the comments below
qreal centerThreshold = 0.01 * sp;
// amount by which actual width exceeds nominal, adjusted for staff mag() only
qreal headDiff = maxUpWidth - nominalWidth;
// amount by which actual width exceeds nominal, adjusted for staff & chord/note mag()
qreal headDiff2 = maxUpWidth - nominalWidth * (maxUpMag / staff->mag(tick));
if (headDiff > centerThreshold) {
// larger than nominal
centerUp = headDiff * -0.5;
// maxUpWidth is true width, but we no longer will care about that
// instead, we care only about portion to right of origin
maxUpWidth += centerUp;
// to left align rather than center, delete both of the above
if (headDiff2 > centerThreshold) {
// if max notehead is wider than nominal with chord/note mag() applied
// then noteheads extend to left of origin
// because stemPosX() is based on nominal width
// so we need to correct for that too
centerUp += headDiff2;
oversizeUp = headDiff2;
}
}
else if (-headDiff > centerThreshold) {
// smaller than nominal
centerUp = -headDiff * 0.5;
if (headDiff2 > centerThreshold) {
// max notehead is wider than nominal with chord/note mag() applied
// perform same adjustment as above
centerUp += headDiff2;
oversizeUp = headDiff2;
}
centerAdjustDown = centerUp;
}
headDiff = maxDownWidth - nominalWidth;
if (headDiff > centerThreshold) {
// larger than nominal
centerDown = headDiff * -0.5;
// to left align rather than center, change the above to
//centerAdjustUp = headDiff;
maxDownWidth = nominalWidth - centerDown;
}
else if (-headDiff > centerThreshold) {
// smaller than nominal
centerDown = -headDiff * 0.5;
centerAdjustUp = centerDown;
}
// handle conflict between upstem and downstem chords
if (upVoices && downVoices) {
Note* bottomUpNote = upStemNotes.front();
Note* topDownNote = downStemNotes.back();
int separation;
// TODO: handle conflicts for cross-staff notes and notes on cross-staff beams
// for now we simply treat these as though there is no conflict
if (bottomUpNote->chord()->staffMove() == topDownNote->chord()->staffMove() && !crossBeamFound)
separation = topDownNote->line() - bottomUpNote->line();
else
separation = 2; // no conflict
QVector<Note*> overlapNotes;
overlapNotes.reserve(8);
if (separation == 1) {
// second
downOffset = maxUpWidth;
// align stems if present, leave extra room if not
if (topDownNote->chord()->stem() && bottomUpNote->chord()->stem())
downOffset -= topDownNote->chord()->stem()->lineWidth();
else
downOffset += 0.1 * sp;
}
else if (separation < 1) {
// overlap (possibly unison)
// build list of overlapping notes
for (size_t i = 0, n = upStemNotes.size(); i < n; ++i) {
if (upStemNotes[i]->line() >= topDownNote->line() - 1)
overlapNotes.append(upStemNotes[i]);
else
break;
}
for (size_t i = downStemNotes.size(); i > 0; --i) { // loop most probably needs to be in this reverse order
if (downStemNotes[i-1]->line() <= bottomUpNote->line() + 1)
overlapNotes.append(downStemNotes[i-1]);
else
break;
}
std::sort(overlapNotes.begin(), overlapNotes.end(),
[](Note* n1, const Note* n2) ->bool {return n1->line() > n2->line(); } );
// determine nature of overlap
bool shareHeads = true; // can all overlapping notes share heads?
bool matchPending = false; // looking for a unison match
bool conflictUnison = false; // unison found
bool conflictSecondUpHigher = false; // second found
bool conflictSecondDownHigher = false; // second found
int lastLine = 1000;
Note* p = overlapNotes[0];
for (int i = 0, count = overlapNotes.size(); i < count; ++i) {
Note* n = overlapNotes[i];
NoteHead::Type nHeadType;
NoteHead::Type pHeadType;
Chord* nchord = n->chord();
Chord* pchord = p->chord();
if (n->mirror()) {
if (separation < 0) {
// don't try to share heads if there is any mirroring
shareHeads = false;
// don't worry about conflicts involving mirrored notes
continue;
}
}
int line = n->line();
int d = lastLine - line;
switch (d) {
case 0:
// unison
conflictUnison = true;
matchPending = false;
nHeadType = (n->headType() == NoteHead::Type::HEAD_AUTO) ? n->chord()->durationType().headType() : n->headType();
pHeadType = (p->headType() == NoteHead::Type::HEAD_AUTO) ? p->chord()->durationType().headType() : p->headType();
// the most important rules for sharing noteheads on unisons between voices are
// that notes must be one same line with same tpc
// noteheads must be unmirrored and of same group
// and chords must be same size (or else sharing code won't work)
if (n->headGroup() != p->headGroup() || n->tpc() != p->tpc() || n->mirror() || p->mirror() || nchord->isSmall() != pchord->isSmall()) {
shareHeads = false;
}
else {
// noteheads are potentially shareable
// it is more subjective at this point
// current default is to require *either* of the following:
// 1) both chords have same number of dots, both have stems, and both noteheads are same type and are full size (automatic match)
// or 2) one or more of the noteheads is not of type AUTO, but is explicitly set to match the other (user-forced match)
// or 3) exactly one of the noteheads is invisible (user-forced match)
// thus user can force notes to be shared despite differing number of dots or either being stemless
// by setting one of the notehead types to match the other or by making one notehead invisible
// TODO: consider adding a style option, staff properties, or note property to control sharing
if ((nchord->dots() != pchord->dots() || !nchord->stem() || !pchord->stem() || nHeadType != pHeadType || n->isSmall() || p->isSmall()) &&
((n->headType() == NoteHead::Type::HEAD_AUTO && p->headType() == NoteHead::Type::HEAD_AUTO) || nHeadType != pHeadType) &&
(n->visible() == p->visible())) {
shareHeads = false;
}
}
break;
case 1:
// second
// trust that this won't be a problem for single unison
if (separation < 0) {
if (n->chord()->up())
conflictSecondUpHigher = true;
else
conflictSecondDownHigher = true;
shareHeads = false;
}
break;
default:
// no conflict
if (matchPending)
shareHeads = false;
matchPending = true;
}
p = n;
lastLine = line;
}
if (matchPending)
shareHeads = false;
// calculate offsets
if (shareHeads) {
for (int i = overlapNotes.size() - 1; i >= 1; i -= 2) {
Note* previousNote = overlapNotes[i-1];
Note* n = overlapNotes[i];
if (!(previousNote->chord()->isNudged() || n->chord()->isNudged())) {
if (previousNote->chord()->dots() == n->chord()->dots()) {
// hide one set dots
bool onLine = !(previousNote->line() & 1);
if (onLine) {
// hide dots for lower voice
if (previousNote->voice() & 1)
previousNote->setDotsHidden(true);
else
n->setDotsHidden(true);
}
else {
// hide dots for upper voice
if (!(previousNote->voice() & 1))
previousNote->setDotsHidden(true);
else
n->setDotsHidden(true);
}
}
// formerly we hid noteheads in an effort to fix playback
// but this doesn't work for cases where noteheads cannot be shared
// so better to solve the problem elsewhere
}
}
}
else if (conflictUnison && separation == 0 && (!downGrace || upGrace))
downOffset = maxUpWidth + 0.3 * sp;
else if (conflictUnison)
upOffset = maxDownWidth + 0.3 * sp;
else if (conflictSecondUpHigher)
upOffset = maxDownWidth + 0.2 * sp;
else if ((downHooks && !upHooks) && !(upDots && !downDots))
downOffset = maxUpWidth + 0.3 * sp;
else if (conflictSecondDownHigher) {
if (downDots && !upDots)
downOffset = maxUpWidth + 0.3 * sp;
else {
upOffset = maxDownWidth - 0.2 * sp;
if (downHooks)
upOffset += 0.3 * sp;
}
}
else {
// no direct conflict, so parts can overlap (downstem on left)
// just be sure that stems clear opposing noteheads
qreal clearLeft = 0.0, clearRight = 0.0;
if (topDownNote->chord()->stem())
clearLeft = topDownNote->chord()->stem()->lineWidth() + 0.3 * sp;
if (bottomUpNote->chord()->stem())
clearRight = bottomUpNote->chord()->stem()->lineWidth() + qMax(maxDownWidth - maxUpWidth, 0.0) + 0.3 * sp;
else
downDots = 0; // no need to adjust for dots in this case
upOffset = qMax(clearLeft, clearRight);
if (downHooks) {
// we will need more space to avoid collision with hook
// but we won't need as much dot adjustment
upOffset = qMax(upOffset, maxDownWidth + 0.1 * sp);
dotAdjustThreshold = maxUpWidth - 0.3 * sp;
}
// if downstem chord is small, don't center
// and we might not need as much dot adjustment either
if (centerDown > 0.0) {
centerDown = 0.0;
centerAdjustUp = 0.0;
dotAdjustThreshold = (upOffset - maxDownWidth) + maxUpWidth - 0.3 * sp;
}
}
}
// adjust for dots
if ((upDots && !downDots) || (downDots && !upDots)) {
// only one sets of dots
// place between chords
int dots;
qreal mag;
if (upDots) {
dots = upDots;
mag = maxUpMag;
}
else {
dots = downDots;
mag = maxDownMag;
}
qreal dotWidth = segment->symWidth(SymId::augmentationDot);
// first dot
dotAdjust = styleP(Sid::dotNoteDistance) + dotWidth;
// additional dots
if (dots > 1)
dotAdjust += styleP(Sid::dotDotDistance) * (dots - 1);
dotAdjust *= mag;
// only by amount over threshold
dotAdjust = qMax(dotAdjust - dotAdjustThreshold, 0.0);
}
if (separation == 1)
dotAdjust += 0.1 * sp;
}
// apply chord offsets
for (int track = startTrack; track < endTrack; ++track) {
Element* e = segment->element(track);
if (e && e->isChord()) {
Chord* chord = toChord(e);
if (chord->up()) {
if (upOffset != 0.0) {
chord->rxpos() += upOffset + centerAdjustUp + oversizeUp;
if (downDots && !upDots)
chord->rxpos() += dotAdjust;
}
else
chord->rxpos() += centerUp;
}
else {
if (downOffset != 0.0) {
chord->rxpos() += downOffset + centerAdjustDown;
if (upDots && !downDots)
chord->rxpos() += dotAdjust;
}
else
chord->rxpos() += centerDown;
}
}
}
// layout chords
std::vector<Note*> notes;
if (upVoices)
notes.insert(notes.end(), upStemNotes.begin(), upStemNotes.end());
if (downVoices)
notes.insert(notes.end(), downStemNotes.begin(), downStemNotes.end());
if (upVoices + downVoices > 1)
std::sort(notes.begin(), notes.end(),
[](Note* n1, const Note* n2) ->bool {return n1->line() > n2->line(); } );
layoutChords3(notes, staff, segment);
}
layoutSegmentElements(segment, startTrack, endTrack);
}
//---------------------------------------------------------
// layoutChords2
// - determine which notes need mirroring
// - this is called once for each stem direction
// eg, once for voices 1&3, once for 2&4
// with all notes combined and sorted to resemble one chord
// - return maximum non-mirrored notehead width
//---------------------------------------------------------
qreal Score::layoutChords2(std::vector<Note*>& notes, bool up)
{
int startIdx, endIdx, incIdx;
qreal maxWidth = 0.0;
// loop in correct direction so that first encountered notehead wins conflict
if (up) {
// loop bottom up
startIdx = 0;
endIdx = int(notes.size());
incIdx = 1;
}
else {
// loop top down
startIdx = int(notes.size()) - 1;
endIdx = -1;
incIdx = -1;
}
int ll = 1000; // line of previous notehead
// hack: start high so first note won't show as conflict
bool lvisible = false; // was last note visible?
bool mirror = false; // should current notehead be mirrored?
// value is retained and may be used on next iteration
// to track mirror status of previous note
bool isLeft = notes[startIdx]->chord()->up(); // is notehead on left?
int lmove = notes[startIdx]->chord()->staffMove(); // staff offset of last note (for cross-staff beaming)
for (int idx = startIdx; idx != endIdx; idx += incIdx) {
Note* note = notes[idx]; // current note
int line = note->line(); // line of current note
Chord* chord = note->chord();
int move = chord->staffMove(); // staff offset of current note
// there is a conflict
// if this is same or adjacent line as previous note (and chords are on same staff!)
// but no need to do anything about it if either note is invisible
bool conflict = (qAbs(ll - line) < 2) && (lmove == move) && note->visible() && lvisible;
// this note is on opposite side of stem as previous note
// if there is a conflict
// or if this the first note *after* a conflict
if (conflict || (chord->up() != isLeft))
isLeft = !isLeft;
// determine if we would need to mirror current note
// to get it to the correct side
// this would be needed to get a note to left or downstem or right of upstem
// whether or not we actually do this is determined later (based on user mirror property)
bool nmirror = (chord->up() != isLeft);
// by default, notes and dots are not hidden
// this may be changed later to allow unisons to share noteheads
note->setHidden(false);
note->setDotsHidden(false);
// be sure chord position is initialized
// chord may be moved to the right later
// if there are conflicts between voices
chord->rxpos() = 0.0;
// let user mirror property override the default we calculated
if (note->userMirror() == MScore::DirectionH::AUTO) {
mirror = nmirror;
}
else {
mirror = note->chord()->up();
if (note->userMirror() == MScore::DirectionH::LEFT)
mirror = !mirror;
}
note->setMirror(mirror);
// accumulate return value
if (!mirror)
maxWidth = qMax(maxWidth, note->bboxRightPos());
// prepare for next iteration
lvisible = note->visible();
lmove = move;
ll = line;
}
return maxWidth;
}
//---------------------------------------------------------
// AcEl
//---------------------------------------------------------
struct AcEl {
Note* note;
qreal x; // actual x position of this accidental relative to origin
qreal top; // top of accidental bbox relative to staff
qreal bottom; // bottom of accidental bbox relative to staff
int line; // line of note
int next; // index of next accidental of same pitch class (ascending list)
qreal width; // width of accidental
qreal ascent; // amount (in sp) vertical strokes extend above body
qreal descent; // amount (in sp) vertical strokes extend below body
qreal rightClear; // amount (in sp) to right of last vertical stroke above body
qreal leftClear; // amount (in sp) to left of last vertical stroke below body
};
//---------------------------------------------------------
// resolveAccidentals
// lx = calculated position of rightmost edge of left accidental relative to origin
//---------------------------------------------------------
static bool resolveAccidentals(AcEl* left, AcEl* right, qreal& lx, qreal pd, qreal sp)
{
AcEl* upper;
AcEl* lower;
if (left->line >= right->line) {
upper = right;
lower = left;
}
else {
upper = left;
lower = right;
}
qreal gap = lower->top - upper->bottom;
// no conflict at all if there is sufficient vertical gap between accidentals
// the arrangement of accidentals into columns assumes accidentals an octave apart *do* clear
if (gap >= pd || lower->line - upper->line >= 7)
return false;
qreal allowableOverlap = qMax(upper->descent, lower->ascent) - pd;
// accidentals that are "close" (small gap or even slight overlap)
if (qAbs(gap) <= 0.33 * sp) {
// acceptable with slight offset
// if one of the accidentals can subsume the overlap
// and both accidentals allow it
if (-gap <= allowableOverlap && qMin(upper->descent, lower->ascent) > 0.0) {
qreal align = qMin(left->width, right->width);
lx = qMin(lx, right->x + align - pd);
return true;
}
}
// amount by which overlapping accidentals will be separated
// for example, the vertical stems of two flat signs
// these need more space than we would need between non-overlapping accidentals
qreal overlapShift = pd * 1.41;
// accidentals with more significant overlap
// acceptable if one accidental can subsume overlap
if (left == lower && -gap <= allowableOverlap) {
qreal offset = qMax(left->rightClear, right->leftClear);
offset = qMin(offset, left->width) - overlapShift;
lx = qMin(lx, right->x + offset);
return true;
}
// accidentals with even more overlap
// can work if both accidentals can subsume overlap
if (left == lower && -gap <= upper->descent + lower->ascent - pd) {
qreal offset = qMin(left->rightClear, right->leftClear) - overlapShift;
if (offset > 0.0) {
lx = qMin(lx, right->x + offset);
return true;
}
}
// otherwise, there is real conflict
lx = qMin(lx, right->x - pd);
return true;
}
//---------------------------------------------------------
// layoutAccidental
//---------------------------------------------------------
static QPair<qreal, qreal> layoutAccidental(AcEl* me, AcEl* above, AcEl* below, qreal colOffset, QVector<Note*>& leftNotes, qreal pnd, qreal pd, qreal sp)
{
qreal lx = colOffset;
Accidental* acc = me->note->accidental();
qreal mag = acc->mag();
pnd *= mag;
pd *= mag;
Chord* chord = me->note->chord();
Staff* staff = chord->staff();
Fraction tick = chord->tick();
// extra space for ledger lines
qreal ledgerAdjust = 0.0;
qreal ledgerVerticalClear = 0.0;
bool ledgerAbove = chord->upNote()->line() <= -2;
bool ledgerBelow = chord->downNote()->line() >= staff->lines(tick) * 2;
if (ledgerAbove || ledgerBelow) {
// ledger lines are present
// check for collision with lines above & below staff
// note that on 1-line staff, both collisions are possible at once
// TODO: account for cutouts in accidental
qreal lds = staff->lineDistance(tick) * sp;
if ((ledgerAbove && me->top + lds <= pnd) || (ledgerBelow && staff->lines(tick) * lds - me->bottom <= pnd)) {
ledgerAdjust = -acc->score()->styleS(Sid::ledgerLineLength).val() * sp;
ledgerVerticalClear = acc->score()->styleS(Sid::ledgerLineWidth).val() * 0.5 * sp;
lx = qMin(lx, ledgerAdjust);
}
}
// clear left notes
int lns = leftNotes.size();
for (int i = 0; i < lns; ++i) {
Note* ln = leftNotes[i];
int lnLine = ln->line();
qreal lnTop = (lnLine - 1) * 0.5 * sp;
qreal lnBottom = lnTop + sp;
if (me->top - lnBottom <= pnd && lnTop - me->bottom <= pnd) {
qreal lnLedgerAdjust = 0.0;
if (lnLine <= -2 || lnLine >= staff->lines(tick) * 2) {
// left note has a ledger line we probably need to clear horizontally as well
// except for accidentals that clear the last extended ledger line vertically
// in these cases, the accidental may tuck closer
Note* lastLnNote = lnLine < 0 ? leftNotes[0] : leftNotes[lns - 1];
int lastLnLine = lastLnNote->line();
qreal ledgerY = (lastLnLine / 2) * sp;
if (me->line < 0 && ledgerY - me->bottom < ledgerVerticalClear)
lnLedgerAdjust = ledgerAdjust;
else if (me->line > 0 && me->top - ledgerY < ledgerVerticalClear)
lnLedgerAdjust = ledgerAdjust;
}
// undercut note above if possible
if (lnBottom - me->top <= me->ascent - pnd)
lx = qMin(lx, ln->x() + ln->chord()->x() + lnLedgerAdjust + me->rightClear);
else
lx = qMin(lx, ln->x() + ln->chord()->x() + lnLedgerAdjust);
}
else if (lnTop > me->bottom)
break;
}
// clear other accidentals
bool conflictAbove = false;
bool conflictBelow = false;
if (above)
conflictAbove = resolveAccidentals(me, above, lx, pd, sp);
if (below)
conflictBelow = resolveAccidentals(me, below, lx, pd, sp);
if (conflictAbove || conflictBelow)
me->x = lx - acc->width() - acc->bbox().x();
else if (colOffset != 0.0)
me->x = lx - pd - acc->width() - acc->bbox().x();
else
me->x = lx - pnd - acc->width() - acc->bbox().x();
return QPair<qreal, qreal> (me->x, me->x + me->width);
}
//---------------------------------------------------------
// layoutChords3
// - calculate positions of notes, accidentals, dots
//---------------------------------------------------------
void Score::layoutChords3(std::vector<Note*>& notes, const Staff* staff, Segment* segment)
{
//---------------------------------------------------
// layout accidentals
// find column for dots
//---------------------------------------------------
QVector<Note*> leftNotes; // notes to left of origin
leftNotes.reserve(8);
QVector<AcEl> aclist; // accidentals
aclist.reserve(8);
// track columns of octave-separated accidentals
int columnBottom[7] = { -1, -1, -1, -1, -1, -1, -1 };
Fraction tick = notes.front()->chord()->segment()->tick();
qreal sp = staff->spatium(tick);
qreal stepDistance = sp * staff->lineDistance(tick) * .5;
int stepOffset = staff->staffType(tick)->stepOffset();
qreal lx = 10000.0; // leftmost notehead position
qreal upDotPosX = 0.0;
qreal downDotPosX = 0.0;
int nNotes = int(notes.size());
int nAcc = 0;
for (int i = nNotes-1; i >= 0; --i) {
Note* note = notes[i];
Accidental* ac = note->accidental();
if (ac && !note->fixed()) {
ac->layout();
if (!ac->visible()) {
ac->setPos(ac->bbox().x() - ac->width(), 0.0);
}
else {
AcEl acel;
acel.note = note;
int line = note->line();
acel.line = line;
acel.x = 0.0;
acel.top = line * 0.5 * sp + ac->bbox().top();
acel.bottom = line * 0.5 * sp + ac->bbox().bottom();
acel.width = ac->width();
QPointF bboxNE = ac->symBbox(ac->symbol()).topRight();
QPointF bboxSW = ac->symBbox(ac->symbol()).bottomLeft();
QPointF cutOutNE = ac->symCutOutNE(ac->symbol());
QPointF cutOutSW = ac->symCutOutSW(ac->symbol());
if (!cutOutNE.isNull()) {
acel.ascent = cutOutNE.y() - bboxNE.y();
acel.rightClear = bboxNE.x() - cutOutNE.x();
}
else {
acel.ascent = 0.0;
acel.rightClear = 0.0;
}
if (!cutOutSW.isNull()) {
acel.descent = bboxSW.y() - cutOutSW.y();
acel.leftClear = cutOutSW.x() - bboxSW.x();
}
else {
acel.descent = 0.0;
acel.leftClear = 0.0;
}
int pitchClass = (line + 700) % 7;
acel.next = columnBottom[pitchClass];
columnBottom[pitchClass] = nAcc;
aclist.append(acel);
++nAcc;
}
}
Chord* chord = note->chord();
bool _up = chord->up();
if (chord->stemSlash())
chord->stemSlash()->layout();
qreal overlapMirror;
Stem* stem = chord->stem();
if (stem)
overlapMirror = stem->lineWidth();
else if (chord->durationType().headType() == NoteHead::Type::HEAD_WHOLE)
overlapMirror = styleP(Sid::stemWidth) * chord->mag();
else
overlapMirror = 0.0;
qreal x = 0.0;
if (note->mirror())
if (_up)
x = chord->stemPosX() - overlapMirror;
else
x = -note->headBodyWidth() + overlapMirror;
else if (_up)
x = chord->stemPosX() - note->headBodyWidth();
qreal ny = (note->line() + stepOffset) * stepDistance;
if (note->rypos() != ny) {
note->rypos() = ny;
if (chord->stem()) {
chord->stem()->layout();
if (chord->hook())
chord->hook()->rypos() = chord->stem()->hookPos().y();
}
}
note->rxpos() = x;
// find leftmost non-mirrored note to set as X origin for accidental layout
// a mirrored note that extends to left of segment X origin
// will displace accidentals only if there is conflict
qreal sx = x + chord->x(); // segment-relative X position of note
if (note->mirror() && !chord->up() && sx < 0.0)
leftNotes.append(note);
else if (sx < lx)
lx = sx;
qreal xx = x + note->headBodyWidth() + chord->pos().x();
Direction dotPosition = note->userDotPosition();
if (chord->dots()) {
if (chord->up())
upDotPosX = qMax(upDotPosX, xx);
else {
downDotPosX = qMax(downDotPosX, xx);
}
if (dotPosition == Direction::AUTO && nNotes > 1 && note->visible() && !note->dotsHidden()) {
// resolve dot conflicts
int line = note->line();
Note* above = (i < nNotes - 1) ? notes[i+1] : 0;
if (above && (!above->visible() || above->dotsHidden()))
above = 0;
int intervalAbove = above ? line - above->line() : 1000;
Note* below = (i > 0) ? notes[i-1] : 0;
if (below && (!below->visible() || below->dotsHidden()))
below = 0;
int intervalBelow = below ? below->line() - line : 1000;
if ((line & 1) == 0) {
// line
if (intervalAbove == 1 && intervalBelow != 1)
dotPosition = Direction::DOWN;
else if (intervalBelow == 1 && intervalAbove != 1)
dotPosition = Direction::UP;
else if (intervalAbove == 0 && above->chord()->dots()) {
// unison
if (((above->voice() & 1) == (note->voice() & 1))) {
above->setDotY(Direction::UP);
dotPosition = Direction::DOWN;
}
}
}
else {
// space
if (intervalAbove == 0 && above->chord()->dots()) {