Line data Source code
1 : /*
2 : * SPDX-License-Identifier: GPL-3.0-only
3 : * MuseScore-Studio-CLA-applies
4 : *
5 : * MuseScore Studio
6 : * Music Composition & Notation
7 : *
8 : * Copyright (C) 2023 MuseScore Limited and others
9 : *
10 : * This program is free software: you can redistribute it and/or modify
11 : * it under the terms of the GNU General Public License version 3 as
12 : * published by the Free Software Foundation.
13 : *
14 : * This program is distributed in the hope that it will be useful,
15 : * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 : * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 : * GNU General Public License for more details.
18 : *
19 : * You should have received a copy of the GNU General Public License
20 : * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 : */
22 : #include "beamlayout.h"
23 :
24 : #include <unordered_map>
25 : #include <set>
26 :
27 : #include "containers.h"
28 :
29 : #include "dom/beam.h"
30 : #include "dom/drumset.h"
31 : #include "dom/part.h"
32 : #include "dom/tremolotwochord.h"
33 : #include "dom/tremolosinglechord.h"
34 : #include "dom/chord.h"
35 : #include "dom/factory.h"
36 : #include "dom/measure.h"
37 : #include "dom/rest.h"
38 : #include "dom/score.h"
39 : #include "dom/segment.h"
40 : #include "dom/staff.h"
41 : #include "dom/system.h"
42 : #include "dom/timesig.h"
43 : #include "dom/tuplet.h"
44 : #include "dom/utils.h"
45 : #include "dom/note.h"
46 :
47 : #include "layoutcontext.h"
48 : #include "tlayout.h"
49 : #include "chordlayout.h"
50 : #include "beamtremololayout.h"
51 : #include "tremololayout.h"
52 : #include "restlayout.h"
53 :
54 : #include "log.h"
55 :
56 : using namespace mu::engraving;
57 : using namespace mu::engraving::rendering::score;
58 :
59 10093 : void BeamLayout::layout(Beam* item, const LayoutContext& ctx)
60 : {
61 10103 : TRACEFUNC;
62 :
63 10093 : Beam::LayoutData* ldata = item->mutldata();
64 : // all of the beam layout code depends on _elements being in order by tick
65 : // this may not be the case if two cr's were recently swapped.
66 10093 : std::sort(item->elements().begin(), item->elements().end(),
67 51944 : [](const ChordRest* a, const ChordRest* b) -> bool {
68 51944 : return a->tick() < b->tick();
69 : });
70 10093 : System* system = item->system();
71 :
72 10093 : std::vector<ChordRest*> crl;
73 :
74 10093 : size_t n = 0;
75 45978 : for (ChordRest* cr : item->elements()) {
76 35885 : auto newSystem = cr->measure()->system();
77 35885 : if (newSystem && newSystem != system) {
78 : SpannerSegmentType st;
79 0 : if (n == 0) {
80 0 : st = SpannerSegmentType::BEGIN;
81 : } else {
82 0 : st = SpannerSegmentType::MIDDLE;
83 : }
84 0 : ++n;
85 0 : if (item->beamFragments().size() < n) {
86 0 : item->beamFragments().push_back(new BeamFragment);
87 : }
88 0 : layout2(item, ctx, crl, st, static_cast<int>(n) - 1);
89 0 : crl.clear();
90 0 : system = cr->measure()->system();
91 : }
92 35885 : crl.push_back(cr);
93 : }
94 :
95 10093 : Shape beamShape(Shape::Type::Composite);
96 :
97 10093 : if (!crl.empty()) {
98 : SpannerSegmentType st;
99 10093 : if (n == 0) {
100 10093 : st = SpannerSegmentType::SINGLE;
101 : } else {
102 0 : st = SpannerSegmentType::END;
103 : }
104 10093 : if (item->beamFragments().size() < (n + 1)) {
105 3160 : item->beamFragments().push_back(new BeamFragment);
106 : }
107 10093 : layout2(item, ctx, crl, st, static_cast<int>(n));
108 :
109 24227 : for (const BeamSegment* bs : item->beamSegments()) {
110 14134 : beamShape.add(bs->shape());
111 : }
112 : }
113 :
114 10093 : ldata->setShape(beamShape);
115 :
116 : // The beam may have changed shape. one-note trems within this beam need to be layed out here
117 45978 : for (ChordRest* cr : item->elements()) {
118 35885 : ChordLayout::computeUp(cr, ctx);
119 35885 : if (cr->isChord() && toChord(cr)->tremoloSingleChord()) {
120 142 : TremoloLayout::layout(toChord(cr)->tremoloSingleChord(), ctx);
121 : }
122 : }
123 10093 : }
124 :
125 0 : void BeamLayout::layoutIfNeed(Beam* item, const LayoutContext& ctx)
126 : {
127 0 : if (!item->ldata()->isValid()) {
128 0 : BeamLayout::layout(item, ctx);
129 : }
130 0 : }
131 :
132 : //---------------------------------------------------------
133 : // - remove beam segments
134 : // - detach from system
135 : // - calculate stem direction and set chord
136 : //---------------------------------------------------------
137 5136 : void BeamLayout::layout1(Beam* item, LayoutContext& ctx)
138 : {
139 5136 : Beam::LayoutData* ldata = item->mutldata();
140 :
141 5136 : const StaffType* staffType = item->staffType();
142 5136 : item->setTab((staffType && staffType->isTabStaff()) ? staffType : nullptr);
143 5136 : item->setIsBesideTabStaff(item->tab() && !item->tab()->stemless() && !item->tab()->stemThrough());
144 :
145 : // TAB's with stem beside staves have special layout
146 5136 : if (item->isBesideTabStaff()) {
147 0 : item->setUp(!item->tab()->stemsDown());
148 0 : item->setSlope(0.0);
149 0 : item->setCross(false);
150 0 : item->setMinMove(0);
151 0 : item->setMaxMove(0);
152 0 : for (ChordRest* cr : item->elements()) {
153 0 : if (cr->isChord()) {
154 0 : item->setUp(cr->up());
155 0 : break;
156 : }
157 : }
158 86 : return;
159 : }
160 :
161 5136 : if (item->staff()->isDrumStaff(item->tick())) {
162 86 : if (item->direction() != DirectionV::AUTO) {
163 28 : item->setUp(item->direction() == DirectionV::UP);
164 58 : } else if (item->isGrace()) {
165 2 : item->setUp(true);
166 : } else {
167 : // search through the beam for the first chord with explicit stem direction and use that.
168 : // if there is no explicit stem direction, default to the direction of the first stem.
169 56 : bool firstUp = false;
170 56 : bool firstChord = true;
171 65 : for (ChordRest* cr : item->elements()) {
172 61 : if (!cr->isChord()) {
173 0 : item->setUp(firstUp);
174 0 : continue;
175 : }
176 61 : Chord* chord = toChord(cr);
177 61 : DirectionV crDirection = toChord(cr)->stemDirection();
178 61 : if (crDirection != DirectionV::AUTO) {
179 52 : item->setUp(crDirection == DirectionV::UP);
180 52 : break;
181 : }
182 9 : if (firstChord) {
183 4 : const Staff* staff = item->staff();
184 4 : const Part* part = staff ? staff->part() : nullptr;
185 4 : const Drumset* ds = part ? part->instrument(item->tick())->drumset() : nullptr;
186 4 : firstUp = ds ? ds->stemDirection(chord->upNote()->pitch()) == DirectionV::UP : chord->up();
187 4 : firstChord = false;
188 : }
189 9 : item->setUp(firstUp);
190 : }
191 : }
192 325 : for (ChordRest* cr : item->elements()) {
193 239 : ChordLayout::computeUp(cr, ctx);
194 239 : if (cr->isChord()) {
195 239 : ChordLayout::layoutStem(toChord(cr), ctx);
196 : }
197 : }
198 86 : return;
199 : }
200 :
201 5050 : if (item->onJianpuStaff() && item->isStyled(Pid::BEAM_NO_SLOPE)) {
202 505 : item->setNoSlope(true);
203 : }
204 :
205 5050 : item->setMinMove(std::numeric_limits<int>::max());
206 5050 : item->setMaxMove(std::numeric_limits<int>::min());
207 5050 : double mag = 0.0;
208 :
209 5050 : item->notePositions().clear();
210 5050 : staff_idx_t staffIdx = muse::nidx;
211 22997 : for (ChordRest* cr : item->elements()) {
212 17947 : double m = cr->isSmall() ? ctx.conf().styleD(Sid::smallNoteMag) : 1.0;
213 17947 : mag = std::max(mag, m);
214 17947 : if (cr->isChord()) {
215 17618 : Chord* chord = toChord(cr);
216 17618 : staffIdx = chord->vStaffIdx();
217 17618 : int i = chord->staffMove();
218 17618 : item->setMinMove(std::min(item->minCRMove(), i));
219 17618 : item->setMaxMove(std::max(item->maxCRMove(), i));
220 :
221 36618 : for (int distance : chord->noteDistances()) {
222 19000 : item->notePositions().push_back(BeamBase::NotePosition(distance, cr->vStaffIdx()));
223 17618 : }
224 : }
225 : }
226 :
227 5050 : std::sort(item->notePositions().begin(), item->notePositions().end());
228 5050 : ldata->setMag(mag);
229 :
230 5050 : item->setCross(item->minCRMove() != item->maxCRMove());
231 :
232 : //
233 : // determine beam stem direction
234 : //
235 5050 : if (item->elements().empty()) {
236 0 : return;
237 : }
238 5050 : ChordRest* firstNote = item->elements().front();
239 5050 : Measure* measure = firstNote->measure();
240 5050 : bool hasMultipleVoices = measure->hasVoices(firstNote->staffIdx(), item->tick(), item->ticks());
241 5050 : if (computeUpForMovedCross(item)) {
242 5044 : } else if (item->direction() != DirectionV::AUTO) {
243 986 : item->setUp(item->direction() == DirectionV::UP);
244 4058 : } else if (item->maxCRMove() > 0) {
245 17 : item->setUp(false);
246 4041 : } else if (item->minCRMove() < 0) {
247 4 : item->setUp(true);
248 4037 : } else if (item->isGrace()) {
249 90 : if (hasMultipleVoices) {
250 6 : item->setUp(firstNote->track() % 2 == 0);
251 : } else {
252 84 : item->setUp(true);
253 : }
254 3947 : } else if (item->notePositions().size()) {
255 3947 : if (hasMultipleVoices) {
256 517 : item->setUp(firstNote->track() % 2 == 0);
257 : } else {
258 3430 : if (const Chord* chord = item->findChordWithCustomStemDirection()) {
259 20 : item->setUp(chord->stemDirection() == DirectionV::UP);
260 : } else {
261 3410 : std::set<BeamBase::NotePosition> notePosSet(item->notePositions().begin(), item->notePositions().end());
262 3410 : std::vector<int> noteLines;
263 3410 : noteLines.reserve(notePosSet.size());
264 12891 : for (BeamBase::NotePosition pos : notePosSet) {
265 9481 : noteLines.push_back(pos.line);
266 : }
267 3410 : item->setUp(ChordLayout::computeAutoStemDirection(noteLines) > 0);
268 3410 : }
269 : }
270 : } else {
271 0 : item->setUp(true);
272 : }
273 :
274 5050 : int middleStaffLine = firstNote->staffType()->middleLine();
275 24050 : for (size_t i = 0; i < item->notePositions().size(); i++) {
276 19000 : item->notePositions()[i].line += middleStaffLine;
277 : }
278 :
279 5050 : bool isEntirelyMoved = false;
280 5050 : if (item->minCRMove() == item->maxCRMove() && item->minCRMove() != 0) {
281 45 : isEntirelyMoved = true;
282 45 : item->setStaffIdx(staffIdx);
283 45 : if (item->direction() == DirectionV::AUTO) {
284 13 : item->setUp(item->maxCRMove() > 0);
285 : }
286 5005 : } else if (item->elements().size()) {
287 5005 : item->setStaffIdx(item->elements().at(0)->staffIdx());
288 : }
289 5050 : item->setFullCross(isEntirelyMoved);
290 :
291 5050 : item->setSlope(0.0);
292 :
293 22997 : for (ChordRest* cr : item->elements()) {
294 17947 : bool prevUp = cr->up();
295 17947 : ChordLayout::computeUp(cr, ctx);
296 17947 : if (cr->isChord() && cr->up() != prevUp) {
297 1619 : ChordLayout::layoutChords1(ctx, cr->segment(), cr->staffIdx());
298 1619 : cr->segment()->createShape(cr->staffIdx());
299 1619 : if (toChord(cr)->isGrace()) {
300 0 : ChordLayout::layoutStem(toChord(cr), ctx);
301 : }
302 : }
303 : }
304 : }
305 :
306 10093 : void BeamLayout::layout2(Beam* item, const LayoutContext& ctx, const std::vector<ChordRest*>& chordRests, SpannerSegmentType, int frag)
307 : {
308 10103 : TRACEFUNC;
309 :
310 10093 : BeamTremoloLayout::setupLData(item, item->mutldata(), ctx);
311 10093 : ChordRest* startCr = nullptr;
312 10093 : ChordRest* endCr = nullptr;
313 10093 : if (chordRests.empty()) {
314 0 : return;
315 : }
316 10093 : bool isJianpuStaff = item->onJianpuStaff();
317 45978 : for (ChordRest* chordRest : chordRests) {
318 35885 : if (chordRest->isChord() || isJianpuStaff) {
319 35810 : if (!startCr) {
320 10093 : startCr = chordRest;
321 10093 : endCr = startCr;
322 : } else {
323 25717 : endCr = chordRest;
324 : }
325 :
326 35810 : if (chordRest->isChord()) {
327 35250 : ChordLayout::layoutStem(toChord(chordRest), ctx);
328 : }
329 : }
330 : }
331 10093 : if (!startCr) {
332 : // we were passed a vector of only rests. we don't support beams across only rests except on Jianpu staves
333 : // this beam will be deleted in LayoutBeams
334 0 : return;
335 : }
336 :
337 10093 : item->setBeamSpacing(ctx.conf().styleB(Sid::useWideBeams) ? 4 : 3);
338 10093 : item->setBeamDist((item->beamSpacing() / 4.0) * item->spatium() * item->mag());
339 10093 : item->setBeamWidth(item->absoluteFromSpatium(ctx.conf().styleS(Sid::beamWidth)) * item->mag());
340 :
341 10093 : item->setStartAnchor(BeamTremoloLayout::chordBeamAnchor(item->ldata(), startCr, ChordBeamAnchorType::Start));
342 10093 : item->setEndAnchor(BeamTremoloLayout::chordBeamAnchor(item->ldata(), endCr, ChordBeamAnchorType::End));
343 :
344 10093 : double graceScale = 1.0;
345 10093 : if (item->isGrace()) {
346 288 : graceScale = ctx.conf().styleD(Sid::graceNoteMag);
347 288 : item->setBeamDist(item->beamDist() * graceScale);
348 288 : item->setBeamWidth(item->beamWidth() * graceScale);
349 : }
350 :
351 10093 : if (isJianpuStaff) {
352 1013 : item->setBeamWidth(ctx.conf().styleAbsolute(Sid::jianpuDiminutionBeamThickness) * item->mag() * graceScale);
353 1013 : item->setBeamDist(ctx.conf().styleAbsolute(Sid::jianpuDiminutionBeamDistance) * item->mag() * graceScale);
354 : }
355 :
356 10093 : int fragmentIndex = item->directionIdx();
357 10093 : if (item->userModified()) {
358 32 : BeamTremoloLayout::setupLData(item, item->mutldata(), ctx);
359 32 : double startY = item->beamFragments()[frag]->py1[fragmentIndex];
360 32 : double endY = item->beamFragments()[frag]->py2[fragmentIndex];
361 32 : if (ctx.conf().styleB(Sid::snapCustomBeamsToGrid)) {
362 32 : const double quarterSpace = item->spatium() / 4;
363 32 : startY = round(startY / quarterSpace) * quarterSpace;
364 32 : endY = round(endY / quarterSpace) * quarterSpace;
365 : }
366 32 : startY += item->pagePos().y();
367 32 : endY += item->pagePos().y();
368 32 : item->startAnchor().setY(startY);
369 32 : item->endAnchor().setY(endY);
370 32 : item->mutldata()->setAnchors(item->startAnchor(), item->endAnchor());
371 32 : item->computeAndSetSlope();
372 32 : createBeamSegments(item, ctx, chordRests);
373 32 : BeamLayout::setTremAnchors(item, ctx);
374 32 : return;
375 : }
376 :
377 : // anchor represents the middle of the beam, not the tip of the stem
378 : // location depends on _isBesideTabStaff
379 :
380 10061 : if (isJianpuStaff) {
381 1004 : BeamTremoloLayout::setupLData(item, item->mutldata(), ctx);
382 1004 : BeamTremoloLayout::calculateAnchors(item, item->mutldata(), ctx, chordRests, item->notePositions());
383 1004 : item->setStartAnchor(item->ldata()->startAnchor);
384 1004 : item->setEndAnchor(item->ldata()->endAnchor);
385 1004 : item->setSlope(0.0);
386 9057 : } else if (!item->isBesideTabStaff()) {
387 9057 : BeamTremoloLayout::setupLData(item, item->mutldata(), ctx);
388 9057 : BeamTremoloLayout::calculateAnchors(item, item->mutldata(), ctx, chordRests, item->notePositions());
389 9057 : item->setStartAnchor(item->ldata()->startAnchor);
390 9057 : item->setEndAnchor(item->ldata()->endAnchor);
391 9057 : item->computeAndSetSlope();
392 9057 : item->setBeamDist(item->ldata()->beamDist);
393 : } else {
394 0 : item->setSlope(0.0);
395 0 : Chord* startChord2 = nullptr;
396 0 : for (ChordRest* cr : chordRests) {
397 0 : if (cr->isChord()) {
398 0 : startChord2 = toChord(cr);
399 0 : break;
400 : }
401 : }
402 0 : BeamTremoloLayout::setupLData(item, item->mutldata(), ctx);
403 0 : double x1 = BeamTremoloLayout::chordBeamAnchorX(item->ldata(), chordRests.front(), ChordBeamAnchorType::Start);
404 0 : double x2 = BeamTremoloLayout::chordBeamAnchorX(item->ldata(), chordRests.back(), ChordBeamAnchorType::End);
405 0 : double y = BeamTremoloLayout::chordBeamAnchorY(item->ldata(), startChord2);
406 0 : item->startAnchor() = PointF(x1, y);
407 0 : item->endAnchor() = PointF(x2, y);
408 0 : item->mutldata()->setAnchors(item->startAnchor(), item->endAnchor());
409 : }
410 :
411 10061 : item->beamFragments()[frag]->py1[fragmentIndex] = item->startAnchor().y() - item->pagePos().y();
412 10061 : item->beamFragments()[frag]->py2[fragmentIndex] = item->endAnchor().y() - item->pagePos().y();
413 :
414 10061 : createBeamSegments(item, ctx, chordRests);
415 10061 : setTremAnchors(item, ctx);
416 10093 : }
417 :
418 300346 : bool BeamLayout::isStartOfNonCrossBeam(ChordRest* cr)
419 : {
420 300346 : Beam* b = cr->beam();
421 300346 : if (b && b->elements().front() == cr) {
422 14816 : if (b->cross()) {
423 30 : return false;
424 : }
425 :
426 14786 : return true;
427 : }
428 :
429 285530 : return false;
430 : }
431 :
432 103657 : bool BeamLayout::isStartOfCrossBeam(ChordRest* cr)
433 : {
434 103657 : Beam* b = cr->beam();
435 103657 : if (b && b->elements().front() == cr) {
436 4946 : if (b->cross()) {
437 10 : return true;
438 : }
439 : }
440 :
441 103647 : return false;
442 : }
443 :
444 : //---------------------------------------------------------
445 : // restoreBeams
446 : //---------------------------------------------------------
447 :
448 214 : void BeamLayout::restoreBeams(Measure* m, LayoutContext& ctx)
449 : {
450 535 : for (Segment* s = m->first(SegmentType::ChordRest); s; s = s->next(SegmentType::ChordRest)) {
451 1985 : for (EngravingItem* e : s->elist()) {
452 1664 : if (e && e->isChordRest()) {
453 418 : ChordRest* cr = toChordRest(e);
454 418 : Beam* b = cr->beam();
455 418 : if (b && !b->elements().empty() && b->elements().front() == cr) {
456 0 : TLayout::layoutBeam(b, ctx);
457 0 : b->addSkyline(m->system()->staff(b->staffIdx())->skyline());
458 : }
459 : }
460 : }
461 : }
462 214 : }
463 :
464 254 : bool BeamLayout::measureMayHaveBeamsJoinedIntoNext(const Measure* measure)
465 : {
466 254 : const MeasureBase* next = measure->next();
467 254 : if (!(next && next->isMeasure())) {
468 13 : return false;
469 : }
470 :
471 241 : const Measure* nextMeasure = toMeasure(next);
472 241 : const Segment* firstCrSeg = nextMeasure->findFirstR(SegmentType::ChordRest, Fraction(0, 1));
473 241 : if (!firstCrSeg) {
474 0 : return false;
475 : }
476 :
477 1549 : for (const EngravingItem* item : firstCrSeg->elist()) {
478 1308 : if (!item) {
479 976 : continue;
480 : }
481 332 : BeamMode beamMode = toChordRest(item)->beamMode();
482 332 : if (beamMode == BeamMode::MID || beamMode == BeamMode::BEGIN16 || beamMode == BeamMode::BEGIN32) {
483 0 : return true;
484 : }
485 : }
486 :
487 241 : return false;
488 : }
489 :
490 : //---------------------------------------------------------
491 : // breakCrossMeasureBeams
492 : //---------------------------------------------------------
493 :
494 7905 : void BeamLayout::breakCrossMeasureBeams(Measure* measure, LayoutContext& ctx)
495 : {
496 7905 : MeasureBase* mbNext = measure->next();
497 7905 : if (!mbNext || !mbNext->isMeasure()) {
498 4234 : return;
499 : }
500 :
501 3671 : Measure* next = toMeasure(mbNext);
502 3671 : const size_t ntracks = ctx.dom().ntracks();
503 3671 : Segment* fstSeg = next->first(SegmentType::ChordRest);
504 3671 : if (!fstSeg) {
505 0 : return;
506 : }
507 :
508 26367 : for (size_t track = 0; track < ntracks; ++track) {
509 22696 : const Staff* stf = ctx.dom().staff(track2staff(track));
510 :
511 : // don’t compute beams for invisible staves and tablature without stems
512 22696 : if (!stf->show() || (stf->isTabStaff(measure->tick()) && stf->staffType(measure->tick())->stemless())) {
513 22694 : continue;
514 : }
515 :
516 21228 : EngravingItem* e = fstSeg->element(static_cast<int>(track));
517 21228 : if (!e || !e->isChordRest()) {
518 15738 : continue;
519 : }
520 :
521 5490 : ChordRest* cr = toChordRest(e);
522 5490 : Beam* beam = cr->beam();
523 5490 : if (!beam || beam->elements().front()->measure() == next) { // no beam or not cross-measure beam
524 5488 : continue;
525 : }
526 :
527 2 : std::vector<ChordRest*> mElements;
528 2 : std::vector<ChordRest*> nextElements;
529 :
530 16 : for (ChordRest* beamCR : beam->elements()) {
531 14 : if (beamCR->tick() < next->tick()) {
532 6 : mElements.push_back(beamCR);
533 : } else {
534 8 : nextElements.push_back(beamCR);
535 : }
536 : }
537 :
538 2 : if (mElements.size() == 1) {
539 0 : mElements[0]->removeDeleteBeam(false);
540 : }
541 :
542 2 : Beam* newBeam = nullptr;
543 2 : if (nextElements.size() > 1) {
544 2 : newBeam = Factory::createBeam(ctx.mutDom().score());
545 2 : newBeam->setGenerated(true);
546 2 : newBeam->setTrack(track);
547 : }
548 :
549 2 : const bool nextBeamed = bool(newBeam);
550 10 : for (ChordRest* nextCR : nextElements) {
551 8 : nextCR->removeDeleteBeam(nextBeamed);
552 8 : if (newBeam) {
553 8 : newBeam->add(nextCR);
554 : }
555 : }
556 :
557 2 : if (newBeam) {
558 2 : layout1(newBeam, ctx);
559 : }
560 2 : }
561 : }
562 :
563 26 : static bool beamNoContinue(BeamMode mode)
564 : {
565 26 : return mode == BeamMode::END || mode == BeamMode::NONE || mode == BeamMode::INVALID;
566 : }
567 :
568 : #define beamModeMid(a) (a == BeamMode::MID || a == BeamMode::BEGIN16 || a == BeamMode::BEGIN32)
569 :
570 4948 : static Beam* createBeamIfNeed(LayoutContext& ctx, ChordRest* first, track_idx_t track)
571 : {
572 4948 : Beam* beam = first->beam();
573 4948 : if (!beam || beam->elements().front() != first) {
574 1222 : beam = Factory::createBeam(ctx.mutDom().score());
575 1222 : beam->setGenerated(true);
576 1222 : beam->setTrack(track);
577 1222 : first->replaceBeam(beam);
578 : }
579 4948 : return beam;
580 : }
581 :
582 : //---------------------------------------------------------
583 : // beamGraceNotes
584 : //---------------------------------------------------------
585 :
586 104978 : void BeamLayout::beamGraceNotes(LayoutContext& ctx, Chord* mainNote, bool after)
587 : {
588 104978 : ChordRest* a1 = 0; // start of (potential) beam
589 104978 : Beam* beam = 0; // current beam
590 104978 : BeamMode bm = BeamMode::AUTO;
591 104978 : std::vector<Chord*> graceNotes = after ? mainNote->graceNotesAfter() : mainNote->graceNotesBefore();
592 :
593 104978 : if (beam) {
594 0 : beam->setIsGrace(true);
595 : }
596 :
597 105866 : for (ChordRest* cr : graceNotes) {
598 888 : bm = Groups::baseBeamMode(cr);
599 888 : if ((cr->durationType().type() <= DurationType::V_QUARTER) || (bm == BeamMode::NONE)) {
600 279 : if (beam) {
601 5 : beam->setIsGrace(true);
602 5 : layout1(beam, ctx);
603 5 : beam = 0;
604 : }
605 279 : if (a1) {
606 1 : a1->removeDeleteBeam(false);
607 1 : a1 = 0;
608 : }
609 279 : cr->removeDeleteBeam(false);
610 279 : continue;
611 : }
612 609 : if (beam) {
613 72 : bool beamEnd = bm == BeamMode::BEGIN;
614 72 : if (!beamEnd) {
615 72 : cr->replaceBeam(beam);
616 72 : cr = 0;
617 72 : beamEnd = (bm == BeamMode::END);
618 : }
619 72 : if (beamEnd) {
620 28 : beam->setIsGrace(true);
621 28 : layout1(beam, ctx);
622 28 : beam = 0;
623 : }
624 : }
625 609 : if (!cr) {
626 72 : continue;
627 : }
628 537 : if (a1 == 0) {
629 445 : if (cr->onJianpuStaff()) {
630 4 : beam = createBeamIfNeed(ctx, cr, mainNote->track());
631 : } else {
632 441 : a1 = cr;
633 : }
634 : } else {
635 92 : if (!beamModeMid(bm) && (bm == BeamMode::BEGIN)) {
636 0 : a1->removeDeleteBeam(false);
637 0 : a1 = cr;
638 : } else {
639 92 : beam = createBeamIfNeed(ctx, a1, mainNote->track());
640 92 : cr->replaceBeam(beam);
641 92 : a1 = 0;
642 : }
643 : }
644 : }
645 104978 : if (beam) {
646 63 : beam->setIsGrace(true);
647 63 : layout1(beam, ctx);
648 104915 : } else if (a1) {
649 348 : a1->removeDeleteBeam(false);
650 : }
651 104978 : }
652 :
653 33826 : void BeamLayout::createBeams(LayoutContext& ctx, Measure* measure)
654 : {
655 33841 : TRACEFUNC;
656 :
657 238094 : for (track_idx_t track = 0; track < ctx.dom().ntracks(); ++track) {
658 204268 : const Staff* stf = ctx.dom().staff(track2staff(track));
659 :
660 : // don’t compute beams for invisible staves and tablature without stems
661 204268 : if (!stf->show() || (stf->isTabStaff(measure->tick()) && stf->staffType(measure->tick())->stemless())) {
662 9716 : continue;
663 : }
664 :
665 194552 : ChordRest* a1 = nullptr; // start of (potential) beam
666 194552 : bool firstCR = true;
667 194552 : Beam* beam = nullptr; // current beam
668 194552 : BeamMode bm = BeamMode::AUTO;
669 194552 : ChordRest* prev = nullptr;
670 194552 : std::unordered_map<int, TDuration> beatSubdivision;
671 :
672 : // if this measure is simple meter (actually X/4),
673 : // then perform a prepass to determine the subdivision of each beat
674 :
675 194552 : beatSubdivision.clear();
676 194552 : TimeSig* ts = stf->timeSig(measure->tick());
677 194552 : const SegmentType st = SegmentType::ChordRest;
678 194552 : if (ts && ts->denominator() == 4) {
679 187792 : Fraction stretch = ts->stretch();
680 565076 : for (Segment* s = measure->first(st); s; s = s->next(st)) {
681 377284 : ChordRest* mcr = toChordRest(s->element(track));
682 377284 : if (mcr == 0) {
683 285672 : continue;
684 : }
685 91612 : int beat = (mcr->rtick() * stretch).ticks() / Constants::DIVISION;
686 91612 : if (muse::contains(beatSubdivision, beat)) {
687 12914 : beatSubdivision[beat] = std::min(beatSubdivision[beat], mcr->durationType());
688 : } else {
689 78698 : beatSubdivision[beat] = mcr->durationType();
690 : }
691 : }
692 : }
693 :
694 588420 : for (Segment* segment = measure->first(st); segment; segment = segment->next(st)) {
695 393868 : ChordRest* cr = segment->cr(track);
696 393868 : if (!cr) {
697 298417 : continue;
698 : }
699 :
700 95451 : if (cr->isChord()) {
701 52489 : Chord* chord = toChord(cr);
702 53377 : for (Chord* c : chord->graceNotes()) {
703 888 : c->setBeamlet(nullptr); // Will be defined during beam layout
704 : }
705 : }
706 95451 : cr->setBeamlet(nullptr); // Will be defined during beam layout
707 :
708 95451 : if (firstCR) {
709 49946 : firstCR = false;
710 : // Handle cross-measure beams
711 49946 : BeamMode mode = cr->beamMode();
712 49946 : if (mode == BeamMode::MID || mode == BeamMode::END || mode == BeamMode::BEGIN16 || mode == BeamMode::BEGIN32) {
713 26 : ChordRest* prevCR = ctx.mutDom().findCR(measure->tick() - Fraction::eps(), track);
714 26 : if (prevCR) {
715 26 : Beam* prevBeam = prevCR->beam();
716 26 : const Measure* pm = prevCR->measure();
717 26 : if (!beamNoContinue(prevCR->beamMode())
718 26 : && !pm->lineBreak() && !pm->pageBreak() && !pm->sectionBreak()
719 26 : && ctx.state().prevMeasure()
720 52 : && !(prevCR->isChord() && prevCR->durationType().type() <= DurationType::V_QUARTER)) {
721 26 : beam = prevBeam;
722 26 : if (prevCR->isChord()) {
723 22 : if (Hook* hook = toChord(prevCR)->hook()) {
724 0 : ctx.mutDom().doUndoRemoveElement(hook);
725 0 : prevCR->segment()->staffShape(prevCR->vStaffIdx()).remove_if([hook](const ShapeElement& el) {
726 0 : return el.item() == hook;
727 : });
728 : }
729 : }
730 : //a1 = beam ? beam->elements().front() : prevCR;
731 26 : a1 = beam ? nullptr : prevCR; // when beam is found, a1 is no longer required.
732 0 : } else if (prevBeam && prevBeam == cr->beam() && prevBeam->elements().front() == prevCR) {
733 : // remove the beam from the previous chordrest because we do not currently
734 : // support cross-system beams
735 0 : prevCR->removeDeleteBeam(false);
736 : }
737 : }
738 : }
739 : }
740 :
741 95451 : bool hasAllRest = cr->beam() && cr->beam()->hasAllRests();
742 95451 : bool isARestBeamStart = cr->isRest() && cr->beamMode() == BeamMode::BEGIN;
743 95451 : if (hasAllRest && !isARestBeamStart) {
744 3 : cr->removeDeleteBeam(false);
745 : }
746 :
747 : // handle grace notes
748 : // (tied chords?)
749 95451 : if (cr->isChord()) {
750 52489 : Chord* chord = toChord(cr);
751 52489 : beamGraceNotes(ctx, chord, false); // grace before
752 52489 : beamGraceNotes(ctx, chord, true); // grace after
753 : }
754 :
755 95451 : bm = Groups::actualBeamMode(cr, prev, &beatSubdivision);
756 95451 : if (cr->isRest() && bm == BeamMode::NONE && cr->onJianpuStaff()) {
757 : // Jianpu rest can be beamed
758 280 : bm = BeamMode::AUTO;
759 : }
760 :
761 95451 : prev = cr;
762 :
763 : // Rests of any duration can be beamed over, if required
764 95451 : bool canBeBeamed = cr->durationType().type() > DurationType::V_QUARTER || cr->isRest();
765 95451 : if (!canBeBeamed || (bm == BeamMode::NONE)) {
766 76716 : bool removeBeam = true;
767 76716 : if (beam) {
768 1165 : layout1(beam, ctx);
769 1165 : removeBeam = (beam->elements().size() <= 1 || beam->hasAllRests());
770 1165 : beam = 0;
771 : }
772 76716 : if (a1) {
773 983 : if (removeBeam) {
774 983 : a1->removeDeleteBeam(false);
775 : }
776 983 : a1 = 0;
777 : }
778 76716 : cr->removeDeleteBeam(false);
779 76716 : continue;
780 76716 : }
781 :
782 18735 : if (beam) {
783 10000 : bool beamEnd = (bm == BeamMode::BEGIN);
784 10000 : if (!beamEnd) {
785 8154 : cr->replaceBeam(beam);
786 8154 : cr = 0;
787 8154 : beamEnd = (bm == BeamMode::END);
788 : }
789 10000 : if (beamEnd) {
790 1982 : layout1(beam, ctx);
791 1982 : beam = 0;
792 : }
793 : }
794 18735 : if (!cr) {
795 8154 : continue;
796 : }
797 :
798 10581 : if (a1 == 0) {
799 6102 : if (cr->onJianpuStaff()) {
800 499 : beam = createBeamIfNeed(ctx, cr, track);
801 : } else {
802 5603 : a1 = cr;
803 : }
804 : } else {
805 169 : if (!beamModeMid(bm)
806 4680 : &&
807 : (bm == BeamMode::BEGIN
808 32 : || (a1->segment()->segmentType() != cr->segment()->segmentType())
809 4511 : || (a1->endTick() < cr->tick())
810 : )
811 : ) {
812 126 : a1->removeDeleteBeam(false);
813 126 : a1 = cr;
814 : } else {
815 4353 : beam = createBeamIfNeed(ctx, a1, track);
816 4353 : cr->replaceBeam(beam);
817 4353 : a1 = 0;
818 : }
819 : }
820 : }
821 194552 : if (beam) {
822 1731 : layout1(beam, ctx);
823 192821 : } else if (a1) {
824 267 : Fraction nextTick = a1->endTick();
825 267 : Measure* m = (nextTick >= measure->endTick() ? measure->nextMeasure() : measure);
826 267 : ChordRest* nextCR = (m ? m->findChordRest(nextTick, track) : nullptr);
827 267 : Beam* b = a1->beam();
828 279 : if (!(b && !b->elements().empty() && !b->hasAllRests() && b->elements().front() == a1 && nextCR
829 12 : && beamModeMid(nextCR->beamMode()))) {
830 263 : a1->removeDeleteBeam(false);
831 : }
832 : }
833 194552 : }
834 33826 : }
835 :
836 : /************************************************************
837 : * layoutNonCrossBeams()
838 : * layout all non-cross-staff beams starting on this segment
839 : * **********************************************************/
840 :
841 197669 : void BeamLayout::layoutNonCrossBeams(ChordRest* cr, LayoutContext& ctx)
842 : {
843 197669 : if (cr->isChord()) {
844 109803 : for (Chord* grace : toChord(cr)->graceNotes()) {
845 1826 : layoutNonCrossBeams(grace, ctx);
846 : }
847 : }
848 :
849 197669 : if (!BeamLayout::isStartOfNonCrossBeam(cr)) {
850 187783 : return;
851 : }
852 :
853 9886 : Beam* beam = cr->beam();
854 :
855 9886 : TLayout::layoutBeam(beam, ctx);
856 :
857 9886 : if (!beam->tremAnchors().empty()) {
858 : // there are inset tremolos in here
859 120 : for (ChordRest* beamCr : beam->elements()) {
860 80 : if (!beamCr->isChord()) {
861 0 : continue;
862 : }
863 80 : Chord* c = toChord(beamCr);
864 80 : if (c->tremoloTwoChord()) {
865 80 : TremoloLayout::layout(c->tremoloTwoChord(), ctx);
866 : }
867 : }
868 : }
869 :
870 9886 : if (!cr->onJianpuStaff()) {
871 40148 : for (ChordRest* beamCR : beam->elements()) {
872 31268 : if (beamCR->isRest() && beamCR->vStaffIdx() == beam->staffIdx()) {
873 58 : verticalAdjustBeamedRests(toRest(beamCR), beam, ctx);
874 : }
875 : }
876 : }
877 : }
878 :
879 58 : void BeamLayout::verticalAdjustBeamedRests(Rest* rest, Beam* beam, LayoutContext& ctx)
880 : {
881 58 : const double spatium = rest->spatium();
882 : static constexpr Fraction rest32nd(1, 32);
883 58 : const bool up = beam->up();
884 58 : const BeamMode restBeamMode = rest->beamMode();
885 58 : const bool firstRest = beam->elements().front() == rest
886 58 : && (restBeamMode == BeamMode::BEGIN || restBeamMode == BeamMode::BEGIN16 || restBeamMode == BeamMode::BEGIN32
887 0 : || restBeamMode == BeamMode::MID);
888 :
889 : double restToBeamPadding;
890 58 : if (rest->ticks() <= rest32nd) {
891 2 : restToBeamPadding = 0.2 * spatium;
892 : } else {
893 56 : restToBeamPadding = 0.35 * spatium;
894 : }
895 :
896 58 : const Shape beamShape = beam->shape().translate(beam->pagePos());
897 58 : const Shape restShape = rest->shape().translate(rest->pagePos() - rest->offset());
898 58 : const double minBeamToRestXDist = up && firstRest ? 0.1 * spatium : 0.0;
899 :
900 : const double restToBeamClearance = up
901 58 : ? beamShape.verticalClearance(restShape, minBeamToRestXDist)
902 32 : : restShape.verticalClearance(beamShape);
903 58 : const double lineDistance = rest->staff()->lineDistance(rest->tick()) * spatium;
904 :
905 58 : int clearanceInSteps = std::ceil(restToBeamClearance / lineDistance);
906 58 : up ? rest->verticalClearance().setAbove(clearanceInSteps) : rest->verticalClearance().setBelow(clearanceInSteps);
907 :
908 58 : if (restToBeamClearance > restToBeamPadding) {
909 49 : return;
910 : }
911 :
912 9 : const bool restIsLocked = rest->verticalClearance().locked();
913 9 : if (!restIsLocked) {
914 9 : double overlap = (restToBeamPadding - restToBeamClearance);
915 9 : int lineMoves = ceil(overlap / lineDistance);
916 9 : lineMoves *= up ? 1 : -1;
917 9 : double yMove = lineMoves * lineDistance;
918 9 : rest->mutldata()->moveY(yMove);
919 9 : for (Rest* mergedRest : rest->ldata()->mergedRests) {
920 0 : mergedRest->mutldata()->moveY(yMove);
921 : }
922 :
923 9 : Segment* segment = rest->segment();
924 9 : staff_idx_t staffIdx = rest->vStaffIdx();
925 9 : const Staff* staff = ctx.dom().staff(staffIdx);
926 9 : std::vector<Chord*> chords;
927 9 : std::vector<Rest*> rests;
928 9 : collectChordsAndRest(segment, staffIdx, chords, rests);
929 9 : RestLayout::resolveRestVSChord(rests, chords, staff, segment);
930 9 : RestLayout::resolveRestVSRest(rests, staff, segment, ctx, /*considerBeams*/ true);
931 9 : }
932 :
933 9 : TLayout::layoutBeam(beam, ctx);
934 :
935 9 : rest->segment()->createShape(rest->vStaffIdx());
936 107 : }
937 :
938 106 : void BeamLayout::checkCrossPosAndStemConsistency(Beam* beam, LayoutContext& ctx)
939 : {
940 106 : if (!beam->cross() || !beam->userModified()) {
941 106 : return;
942 : }
943 :
944 0 : int correctCrossStaffIdx = 0;
945 0 : bool inconsistencyFound = false;
946 :
947 0 : for (ChordRest* cr : beam->elements()) {
948 0 : if (!cr->isChord()) {
949 0 : continue;
950 : }
951 0 : Chord* chord = toChord(cr);
952 0 : bool currentUp = chord->up();
953 0 : bool actualUp = ChordLayout::isChordPosBelowBeam(chord, beam);
954 0 : if (actualUp != currentUp) {
955 0 : inconsistencyFound = true;
956 0 : chord->setUp(actualUp);
957 0 : ChordLayout::layoutChords1(ctx, chord->segment(), chord->staffIdx());
958 0 : chord->segment()->createShape(chord->staffIdx());
959 : }
960 0 : if (actualUp) {
961 0 : correctCrossStaffIdx = std::min(correctCrossStaffIdx, chord->staffMove());
962 : } else {
963 0 : correctCrossStaffIdx = std::max(correctCrossStaffIdx, chord->staffMove() + 1);
964 : }
965 : }
966 :
967 0 : int beamCrossStaffIdx = beam->crossStaffIdx();
968 0 : if (beamCrossStaffIdx != correctCrossStaffIdx) {
969 0 : inconsistencyFound = true;
970 0 : int curCrossStaffMove = beam->crossStaffMove();
971 0 : int diff = correctCrossStaffIdx - beamCrossStaffIdx;
972 0 : beam->setProperty(Pid::BEAM_CROSS_STAFF_MOVE, curCrossStaffMove + diff);
973 : }
974 :
975 0 : if (inconsistencyFound) {
976 0 : BeamLayout::layout(beam, ctx);
977 : }
978 : }
979 :
980 10093 : void BeamLayout::createBeamSegments(Beam* item, const LayoutContext& ctx, const std::vector<ChordRest*>& chordRests)
981 : {
982 10093 : item->clearBeamSegments();
983 :
984 10093 : bool levelHasBeam = false;
985 10093 : int level = 0;
986 10093 : constexpr size_t noLastChord = std::numeric_limits<size_t>::max();
987 10093 : size_t numCr = chordRests.size();
988 10093 : bool frenchStyleBeams = ctx.conf().styleB(Sid::frenchStyleBeams);
989 23470 : do {
990 23470 : levelHasBeam = false;
991 23470 : ChordRest* startCr = nullptr;
992 23470 : ChordRest* endCr = nullptr;
993 23470 : bool breakBeam = false;
994 23470 : bool previousBreak16 = false;
995 23470 : bool previousBreak32 = false;
996 23470 : size_t lastChordIndex = noLastChord;
997 :
998 111773 : for (size_t i = 0; i < numCr; i++) {
999 88303 : ChordRest* chordRest = chordRests[i];
1000 88303 : ChordRest* prevChordRest = i < 1 ? nullptr : chordRests[i - 1];
1001 :
1002 : // Jianpu rest can be beamed like normal chords
1003 88303 : if (level < chordRest->beams() && (!chordRest->isRest() || item->onJianpuStaff())) {
1004 49353 : levelHasBeam = true;
1005 : }
1006 88303 : bool isBroken16 = false;
1007 88303 : bool isBroken32 = false;
1008 :
1009 : // updates isBroken16 and isBroken32
1010 88303 : item->calcBeamBreaks(chordRest, prevChordRest, level, isBroken16, isBroken32);
1011 88303 : breakBeam = isBroken16 || isBroken32;
1012 88303 : bool skipRest = false;
1013 88303 : BeamMode beamMode = chordRest->beamMode();
1014 89670 : if (chordRest->isRest() && level >= chordRest->beams()
1015 89670 : && (beamMode == BeamMode::MID || beamMode == BeamMode::BEGIN16 || beamMode == BeamMode::BEGIN32)) {
1016 : // if the level is lower than both the previous and next real chords, don't break here
1017 123 : size_t nextChordIndex = i + 1;
1018 155 : while (nextChordIndex < numCr && chordRests[nextChordIndex]->isRest()) {
1019 32 : ++nextChordIndex;
1020 : }
1021 123 : if (lastChordIndex < numCr && nextChordIndex < numCr) {
1022 123 : Chord* lastChord = toChord(chordRests[lastChordIndex]);
1023 123 : Chord* nextChord = toChord(chordRests[nextChordIndex]);
1024 : // we have both chords (not rests) on either side of this rest, so if the level is lower than both we can
1025 : // just continue the beam through here
1026 : // this creates situations where we can have the second beam of a pair of 16th notes continuing through
1027 : // an 8th rest, for example, even though an 8th note would very obviously break the beam
1028 : // this is desired for BeamType::MID on rests.
1029 123 : if (level < lastChord->beams() && level < nextChord->beams()) {
1030 0 : skipRest = (isBroken16 && level < 1) || (isBroken32 && level < 2) || (!isBroken16 && !isBroken32);
1031 : }
1032 : }
1033 : }
1034 88303 : if ((level < chordRest->beams() && !breakBeam) || skipRest) {
1035 48440 : endCr = chordRest;
1036 48440 : if (!startCr || (startCr->isRest() && startCr != item->elements().front())) {
1037 13097 : startCr = chordRest;
1038 : }
1039 39863 : } else if (level >= chordRest->beams() && chordRest->isRest() && !breakBeam) {
1040 : // This rest has duration longer than the beam value, but it may still go
1041 : // under the beam if the next chords or rests are beamed
1042 773 : continue;
1043 : } else {
1044 39090 : if (lastChordIndex < item->elements().size() && (chordRest->isRest() || (endCr && endCr->isRest()))) {
1045 : // we broke the beam on this chordrest, but the last cr of the beam segment can't end on a rest
1046 : // so it ends on lastChord
1047 6 : ChordRest* lastCr = toChordRest(item->elements()[lastChordIndex]);
1048 6 : if (lastCr && startCr && lastCr->tick() >= startCr->tick()) {
1049 6 : endCr = lastCr;
1050 6 : lastChordIndex = noLastChord;
1051 : }
1052 : }
1053 39090 : if (startCr && endCr && levelHasBeam) {
1054 1700 : if (startCr == endCr && startCr->isChord()) {
1055 214 : bool isBeamletBefore = calcIsBeamletBefore(item,
1056 : toChord(startCr),
1057 214 : static_cast<int>(muse::indexOf(item->elements(), startCr)),
1058 : level,
1059 : previousBreak16,
1060 : previousBreak32);
1061 214 : createBeamletSegment(item, ctx, toChord(startCr), isBeamletBefore, level);
1062 1486 : } else if (startCr != endCr) {
1063 1486 : createBeamSegment(item, startCr, endCr, level, frenchStyleBeams);
1064 : }
1065 : }
1066 39090 : bool setCr = chordRest && chordRest->isChord() && breakBeam && level < chordRest->beams();
1067 39090 : startCr = setCr ? chordRest : nullptr;
1068 39090 : endCr = setCr ? chordRest : nullptr;
1069 : }
1070 87530 : previousBreak16 = isBroken16;
1071 87530 : previousBreak32 = isBroken32;
1072 87530 : if (chordRest && chordRest->isChord()) {
1073 86936 : lastChordIndex = i;
1074 : }
1075 : }
1076 :
1077 : // if the beam ends on the last chord
1078 23470 : if (startCr && (endCr || breakBeam)) {
1079 12434 : if ((startCr == endCr || !endCr) && startCr->isChord()) {
1080 : // this chord is either the last chord, or the first (followed by a rest)
1081 201 : bool isBefore = !(startCr == chordRests.front());
1082 201 : createBeamletSegment(item, ctx, toChord(startCr), isBefore, level);
1083 : } else {
1084 12233 : createBeamSegment(item, startCr, endCr, level, frenchStyleBeams);
1085 : }
1086 : }
1087 23470 : level++;
1088 : } while (levelHasBeam);
1089 10093 : }
1090 :
1091 214 : bool BeamLayout::calcIsBeamletBefore(const Beam* item, Chord* chord, int i, int level, bool isAfter16Break, bool isAfter32Break)
1092 : {
1093 : // if first or last chord in beam group
1094 214 : if (i == 0) {
1095 146 : return false;
1096 68 : } else if (i == static_cast<int>(item->elements().size()) - 1) {
1097 0 : return true;
1098 : }
1099 : // if first or last chord in tuplet
1100 68 : Tuplet* tuplet = chord->tuplet();
1101 68 : if (tuplet && chord == tuplet->elements().front()) {
1102 10 : return false;
1103 58 : } else if (tuplet && chord == tuplet->elements().back()) {
1104 14 : return true;
1105 : }
1106 :
1107 : // next note has a beam break
1108 44 : ChordRest* nextChordRest = item->elements()[i + 1];
1109 44 : ChordRest* currChordRest = item->elements()[i];
1110 44 : ChordRest* prevChordRest = item->elements()[i - 1];
1111 44 : if (nextChordRest->isChord()) {
1112 44 : bool nextBreak16 = false;
1113 44 : bool nextBreak32 = false;
1114 44 : bool currBreak16 = false;
1115 44 : bool currBreak32 = false;
1116 44 : item->calcBeamBreaks(currChordRest, prevChordRest, prevChordRest->beams(), currBreak16, currBreak32);
1117 44 : item->calcBeamBreaks(nextChordRest, currChordRest, level, nextBreak16, nextBreak32);
1118 44 : if ((nextBreak16 && level >= 1) || (!currBreak16 && nextBreak32 && level >= 2)) {
1119 26 : return true;
1120 : }
1121 : }
1122 :
1123 : // if previous or next chord has more beams, point in that direction
1124 18 : int previousChordLevel = -1;
1125 18 : int nextChordLevel = -1;
1126 18 : int previousOffset = 1;
1127 18 : while (i - previousOffset >= 0) {
1128 18 : ChordRest* previous = item->elements()[i - previousOffset];
1129 18 : if (previous->isChord()) {
1130 18 : previousChordLevel = toChord(previous)->beams();
1131 18 : if (isAfter16Break) {
1132 10 : previousChordLevel = std::min(previousChordLevel, 1);
1133 8 : } else if (isAfter32Break) {
1134 0 : previousChordLevel = std::min(previousChordLevel, 2);
1135 : }
1136 18 : break;
1137 : }
1138 0 : ++previousOffset;
1139 : }
1140 :
1141 18 : int nextOffset = 1;
1142 18 : while (i + nextOffset < static_cast<int>(item->elements().size())) {
1143 18 : ChordRest* next = item->elements()[i + nextOffset];
1144 18 : if (next->isChord()) {
1145 18 : nextChordLevel = toChord(next)->beams();
1146 18 : break;
1147 : }
1148 0 : ++nextOffset;
1149 : }
1150 18 : int chordLevelDifference = nextChordLevel - previousChordLevel;
1151 18 : if (chordLevelDifference != 0) {
1152 10 : return chordLevelDifference < 0;
1153 : }
1154 :
1155 : // if the chord ends a subdivision of the beat
1156 8 : Fraction baseTick = tuplet ? tuplet->tick() : chord->measure()->tick();
1157 8 : Fraction stretch = chord->staff()->timeStretch(baseTick);
1158 8 : Fraction tickNext = (nextChordRest->tick() - baseTick) * stretch;
1159 8 : if (tuplet) {
1160 : // for tuplets with odd ratios, apply ratio
1161 : // for tuplets with even ratios, use actual beat
1162 0 : Fraction ratio = tuplet->ratio();
1163 0 : if (ratio.numerator() & 1) {
1164 0 : tickNext *= ratio;
1165 : }
1166 : }
1167 :
1168 : static const int BEAM_TUPLET_TOLERANCE = 6;
1169 8 : int tickLargeSize = chord->ticks().ticks() * 2;
1170 8 : int remainder = tickNext.ticks() % tickLargeSize;
1171 8 : if (remainder <= BEAM_TUPLET_TOLERANCE || (tickLargeSize - remainder) <= BEAM_TUPLET_TOLERANCE) {
1172 4 : return true;
1173 : }
1174 :
1175 : // default case
1176 4 : return false;
1177 : }
1178 :
1179 11549 : static inline int computeStemLengthAdjustmentSteps(const ChordRest* cr, bool isStartOrEnd, bool isAbove, bool frenchStyleBeams,
1180 : int level, int beamsAbove, int beamsBelow)
1181 : {
1182 11549 : if (isAbove == cr->up()) { // beam segment on opposite side
1183 34 : if (!frenchStyleBeams || isStartOrEnd) {
1184 : // lengthen
1185 34 : return level - (isAbove ? beamsBelow : beamsAbove);
1186 : }
1187 : } else { // beamlet on the note side
1188 11515 : if (frenchStyleBeams && !isStartOrEnd) {
1189 : // shorten
1190 0 : return (isAbove ? beamsBelow : beamsAbove) - level;
1191 : }
1192 : }
1193 :
1194 11515 : return 0;
1195 : }
1196 :
1197 13737 : void BeamLayout::createBeamSegment(Beam* item, ChordRest* startCr, ChordRest* endCr, int level, bool frenchStyleBeams)
1198 : {
1199 13737 : const bool isFirstSubgroup = startCr == item->elements().front();
1200 13737 : const bool isLastSubgroup = endCr == item->elements().back();
1201 13737 : const bool firstUp = startCr->up();
1202 13737 : const bool lastUp = endCr->up();
1203 13737 : bool overallUp = item->up();
1204 13737 : if (isFirstSubgroup == isLastSubgroup) {
1205 : // this subgroup is either the only one in the beam, or in the middle
1206 12056 : if (firstUp == lastUp) {
1207 : // the "outside notes" of this subgroup go the same direction so use them
1208 : // to determine the side of the beams
1209 12036 : overallUp = firstUp;
1210 : } else {
1211 : // no perfect way to solve this problem, for now we'll base it on the number of
1212 : // up and down stemmed notes in this subgroup
1213 : int upStems, downStems;
1214 20 : upStems = downStems = 0;
1215 62 : for (ChordRest* cr : item->elements()) {
1216 62 : if (!cr->isChord() || cr->tick() < startCr->tick()) {
1217 0 : continue;
1218 : }
1219 62 : if (cr->tick() > endCr->tick()) {
1220 0 : break;
1221 : }
1222 :
1223 62 : ++(toChord(cr)->up() ? upStems : downStems);
1224 :
1225 62 : if (cr == endCr) {
1226 20 : break;
1227 : }
1228 : }
1229 20 : if (upStems == downStems) {
1230 : // we are officially bamboozled. for now we can just use the default
1231 : // direction based on the staff we're on I guess
1232 14 : overallUp = item->up();
1233 : } else {
1234 : // use the direction with the most stems
1235 6 : overallUp = upStems > downStems;
1236 : }
1237 : }
1238 1681 : } else if (isFirstSubgroup) {
1239 1096 : overallUp = lastUp;
1240 585 : } else if (isLastSubgroup) {
1241 585 : overallUp = firstUp;
1242 : }
1243 :
1244 13737 : const double startX = BeamTremoloLayout::chordBeamAnchorX(item->ldata(), startCr, ChordBeamAnchorType::Start);
1245 13737 : const double endX = BeamTremoloLayout::chordBeamAnchorX(item->ldata(), endCr, ChordBeamAnchorType::End);
1246 :
1247 13737 : double startY = item->slope() * (startX - item->startAnchor().x()) + item->startAnchor().y() - item->pagePos().y();
1248 13737 : double endY = item->slope() * (endX - item->startAnchor().x()) + item->startAnchor().y() - item->pagePos().y();
1249 :
1250 13737 : int beamsBelow = 0; // how many beams below level 0?
1251 13737 : int beamsAbove = 0; // how many beams above level 0?
1252 :
1253 : // avoid adjusting for beams on opposite side of level 0
1254 13737 : if (level != 0) {
1255 11226 : for (const BeamSegment* beam : item->beamSegments()) {
1256 7582 : if (beam->level == 0 || beam->endTick < startCr->tick() || beam->startTick > endCr->tick()) {
1257 5779 : continue;
1258 : }
1259 1803 : ++(beam->above ? beamsAbove : beamsBelow);
1260 : }
1261 :
1262 3644 : const int upValue = (overallUp || item->onJianpuStaff()) ? -1 : 1;
1263 3644 : const int extraBeamAdjust = overallUp ? beamsAbove : beamsBelow;
1264 3644 : const double verticalOffset = item->beamDist() * (level - extraBeamAdjust) * upValue;
1265 :
1266 3644 : if (muse::RealIsEqual(item->growLeft(), item->growRight())) {
1267 3628 : startY -= verticalOffset * item->growLeft();
1268 3628 : endY -= verticalOffset * item->growLeft();
1269 : } else {
1270 : // Feathered beams
1271 16 : double startProportionAlongX = (startX - item->startAnchor().x()) / (item->endAnchor().x() - item->startAnchor().x());
1272 16 : double endProportionAlongX = (endX - item->startAnchor().x()) / (item->endAnchor().x() - item->startAnchor().x());
1273 :
1274 16 : double grow1 = startProportionAlongX * (item->growRight() - item->growLeft()) + item->growLeft();
1275 16 : double grow2 = endProportionAlongX * (item->growRight() - item->growLeft()) + item->growLeft();
1276 :
1277 16 : startY -= verticalOffset * grow1;
1278 16 : endY -= verticalOffset * grow2;
1279 : }
1280 : }
1281 :
1282 13737 : BeamSegment* b = new BeamSegment(item);
1283 13737 : b->above = !overallUp;
1284 13737 : b->level = level;
1285 13737 : b->line = LineF(startX, startY, endX, endY);
1286 13737 : b->startTick = startCr->tick();
1287 13737 : b->endTick = endCr->tick();
1288 13737 : item->beamSegments().push_back(b);
1289 :
1290 13737 : if (level > 0) {
1291 3644 : ++(b->above ? beamsAbove : beamsBelow);
1292 : }
1293 :
1294 : // extend stems properly
1295 54703 : for (ChordRest* cr : item->elements()) {
1296 53661 : if (!cr->isChord() || cr->tick() < startCr->tick()) {
1297 4544 : continue;
1298 : }
1299 49117 : if (cr->tick() > endCr->tick()) {
1300 568 : break;
1301 : }
1302 :
1303 48549 : Chord* chord = toChord(cr);
1304 48549 : if (!chord->stem()) {
1305 5140 : continue;
1306 : }
1307 :
1308 43409 : double _up = chord->up() ? -1.0 : 1.0;
1309 :
1310 43409 : if (level == 0) {
1311 31860 : BeamTremoloLayout::extendStem(item->ldata(), chord, 0.0);
1312 : // HACK: extend the bounding box of the stem (NOT the stem itself) by half beam width.
1313 : // This way the bbox of the stem covers also the beam position. Hugely helps with all the collision checks.
1314 31860 : chord->stem()->mutldata()->beamCorrection = _up * item->beamWidth() / 2;
1315 : } else {
1316 11549 : bool isStartOrEnd = cr == startCr || cr == endCr;
1317 11549 : int visualStemLengthAdjustmentSteps = computeStemLengthAdjustmentSteps(cr, isStartOrEnd, b->above, frenchStyleBeams,
1318 : level, beamsAbove, beamsBelow);
1319 11549 : if (visualStemLengthAdjustmentSteps != 0) {
1320 34 : double grow = item->growLeft();
1321 34 : if (!muse::RealIsEqual(item->growLeft(), item->growRight())) {
1322 0 : double anchorX = BeamTremoloLayout::chordBeamAnchorX(item->ldata(), chord, ChordBeamAnchorType::Middle);
1323 0 : double proportionAlongX = (anchorX - item->startAnchor().x()) / (item->endAnchor().x() - item->startAnchor().x());
1324 0 : grow = proportionAlongX * (item->growRight() - item->growLeft()) + item->growLeft();
1325 : }
1326 :
1327 34 : double visualStemLengthAdjustment = grow * visualStemLengthAdjustmentSteps * item->beamDist();
1328 :
1329 34 : if (frenchStyleBeams) {
1330 : // Even if we visually shorten the stem, we need the 'original' length for collisions.
1331 0 : int bboxStemLengthAdjustmentSteps = computeStemLengthAdjustmentSteps(cr, isStartOrEnd, b->above,
1332 : /*frenchStyleBeams*/ false,
1333 : level, beamsAbove, beamsBelow);
1334 0 : chord->stem()->mutldata()->beamCorrection = _up * item->beamWidth() / 2 + _up * grow
1335 0 : * (bboxStemLengthAdjustmentSteps - visualStemLengthAdjustmentSteps)
1336 0 : * item->beamDist();
1337 : }
1338 34 : BeamTremoloLayout::extendStem(item->ldata(), chord, visualStemLengthAdjustment);
1339 : }
1340 : }
1341 :
1342 43409 : if (cr == endCr) {
1343 12127 : break;
1344 : }
1345 : }
1346 13737 : }
1347 :
1348 415 : void BeamLayout::createBeamletSegment(Beam* item, const LayoutContext& ctx, ChordRest* cr, bool isBefore, int level)
1349 : {
1350 : // Jianpu uses a full-width beam across the same chord/rest instead of a beamlet.
1351 415 : if (item->onJianpuStaff()) {
1352 18 : createBeamSegment(item, cr, cr, level, ctx.conf().styleB(Sid::frenchStyleBeams));
1353 18 : return;
1354 : }
1355 :
1356 397 : const double startX = BeamTremoloLayout::chordBeamAnchorX(item->ldata(), cr,
1357 : isBefore
1358 : ? ChordBeamAnchorType::End
1359 : : ChordBeamAnchorType::Start);
1360 :
1361 397 : const double beamletLength = ctx.conf().styleAbsolute(Sid::beamMinLen) * cr->mag();
1362 :
1363 397 : const double endX = startX + (isBefore ? -beamletLength : beamletLength);
1364 :
1365 397 : double startY = item->slope() * (startX - item->startAnchor().x()) + item->startAnchor().y() - item->pagePos().y();
1366 397 : double endY = item->slope() * (endX - startX) + startY;
1367 :
1368 : // how many beams past level 0 (i.e. beams on the other side of level 0 for this subgroup)
1369 397 : int extraBeamAdjust = 0;
1370 :
1371 : // avoid adjusting for beams on opposite side of level 0
1372 1332 : for (const BeamSegment* beam : item->beamSegments()) {
1373 935 : if (beam->level == 0 || beam->line.x2() < startX || beam->line.x1() > endX) {
1374 802 : continue;
1375 : }
1376 :
1377 133 : if (cr->up() == beam->above) {
1378 0 : extraBeamAdjust++;
1379 : }
1380 : }
1381 :
1382 397 : const int upValue = (cr->up() || item->onJianpuStaff()) ? -1 : 1;
1383 397 : const double verticalOffset = item->beamDist() * (level - extraBeamAdjust) * upValue;
1384 :
1385 397 : if (muse::RealIsEqual(item->growLeft(), item->growRight())) {
1386 397 : startY -= verticalOffset * item->growLeft();
1387 397 : endY -= verticalOffset * item->growLeft();
1388 : } else {
1389 : // Feathered beams
1390 0 : double startProportionAlongX = (startX - item->startAnchor().x()) / (item->endAnchor().x() - item->startAnchor().x());
1391 0 : double endProportionAlongX = (endX - item->startAnchor().x()) / (item->endAnchor().x() - item->startAnchor().x());
1392 :
1393 0 : double grow1 = startProportionAlongX * (item->growRight() - item->growLeft()) + item->growLeft();
1394 0 : double grow2 = endProportionAlongX * (item->growRight() - item->growLeft()) + item->growLeft();
1395 :
1396 0 : startY -= verticalOffset * grow1;
1397 0 : endY -= verticalOffset * grow2;
1398 : }
1399 :
1400 397 : BeamSegment* b = new BeamSegment(item);
1401 397 : b->above = !cr->up();
1402 397 : b->level = level;
1403 397 : b->line = LineF(startX, startY, endX, endY);
1404 397 : b->isBeamlet = true;
1405 397 : b->isBefore = isBefore;
1406 397 : cr->setBeamlet(b);
1407 :
1408 397 : ChordLayout::fillShape(cr, cr->mutldata(), ctx.conf());
1409 : //! NOTE Moved from ChordRest::setBeamlet
1410 397 : cr->segment()->createShape(cr->vStaffIdx());
1411 397 : item->beamSegments().push_back(b);
1412 : }
1413 :
1414 5050 : bool BeamLayout::computeUpForMovedCross(Beam* item)
1415 : {
1416 5050 : if (!item->cross()) {
1417 5034 : return false;
1418 : }
1419 16 : bool isAboveAllChords = true;
1420 16 : bool isBelowAllChords = true;
1421 63 : for (ChordRest* cr : item->elements()) {
1422 47 : if (cr->isBelowCrossBeam(item)) {
1423 29 : isBelowAllChords = false;
1424 : } else {
1425 18 : isAboveAllChords = false;
1426 : }
1427 : }
1428 :
1429 16 : if (isAboveAllChords) {
1430 6 : item->setUp(true);
1431 6 : return true;
1432 : }
1433 :
1434 10 : if (isBelowAllChords) {
1435 0 : item->setUp(false);
1436 0 : return true;
1437 : }
1438 :
1439 10 : return false;
1440 : }
1441 :
1442 133 : PointF BeamLayout::chordBeamAnchor(const Beam* item, const ChordRest* chord, ChordBeamAnchorType anchorType)
1443 : {
1444 133 : return BeamTremoloLayout::chordBeamAnchor(item->ldata(), chord, anchorType);
1445 : }
1446 :
1447 0 : double BeamLayout::chordBeamAnchorY(const Beam* item, const ChordRest* chord)
1448 : {
1449 0 : return BeamTremoloLayout::chordBeamAnchorY(item->ldata(), chord);
1450 : }
1451 :
1452 10093 : void BeamLayout::setTremAnchors(Beam* item, const LayoutContext& ctx)
1453 : {
1454 10093 : item->tremAnchors().clear();
1455 45978 : for (ChordRest* cr : item->elements()) {
1456 35885 : if (!cr || !cr->isChord()) {
1457 635 : continue;
1458 : }
1459 35250 : Chord* c = toChord(cr);
1460 35250 : TremoloTwoChord* t = c ? c->tremoloTwoChord() : nullptr;
1461 35250 : if (t && t->chord1() == c && t->chord2()->beam() == item) {
1462 : // there is an inset tremolo here!
1463 : // figure out up / down
1464 40 : bool tremUp = t->up();
1465 40 : if (item->userModified()) {
1466 0 : tremUp = c->up();
1467 40 : } else if (item->cross() && t->chord1()->staffMove() == t->chord2()->staffMove()) {
1468 0 : tremUp = t->chord1()->staffMove() == item->maxCRMove();
1469 : }
1470 40 : TremAnchor tremAnchor;
1471 40 : tremAnchor.chord1 = c;
1472 40 : int regularBeams = c->beams(); // non-tremolo strokes
1473 40 : double scale = t->spatium() * t->mag();
1474 :
1475 : // find the left-side anchor
1476 40 : double width = item->endAnchor().x() - item->startAnchor().x();
1477 40 : double height = item->endAnchor().y() - item->startAnchor().y();
1478 40 : double x = chordBeamAnchor(item, c, ChordBeamAnchorType::Middle).x();
1479 40 : double proportionAlongX = (x - item->startAnchor().x()) / width;
1480 40 : double y = item->startAnchor().y() + (proportionAlongX * height);
1481 40 : y += regularBeams * (ctx.conf().styleB(Sid::useWideBeams) ? 1.0 : 0.75) * scale * (tremUp ? 1. : -1.);
1482 40 : tremAnchor.y1 = y;
1483 : // find the right-side anchor
1484 40 : x = chordBeamAnchor(item, t->chord2(), ChordBeamAnchorType::Middle).x();
1485 40 : proportionAlongX = (x - item->startAnchor().x()) / width;
1486 40 : y = item->startAnchor().y() + (proportionAlongX * height);
1487 40 : y += regularBeams * (ctx.conf().styleB(Sid::useWideBeams) ? 1.0 : 0.75) * scale * (tremUp ? 1. : -1.);
1488 40 : tremAnchor.y2 = y;
1489 40 : item->tremAnchors().push_back(tremAnchor);
1490 : }
1491 : }
1492 10093 : }
|