LCOV - code coverage report
Current view: top level - src/engraving/rendering/score - beamtremololayout.cpp Coverage Total Hit
Test: filtered_coverage.info Lines: 88.4 % 846 748
Test Date: 2026-11-19 04:14:36

            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              : 
      23              : #include "beamtremololayout.h"
      24              : 
      25              : #include <array>
      26              : 
      27              : #include "../dom/beam.h"
      28              : #include "../dom/chordrest.h"
      29              : #include "../dom/chord.h"
      30              : #include "../dom/jianpuoctavedot.h"
      31              : #include "../dom/measure.h"
      32              : #include "../dom/note.h"
      33              : #include "../dom/score.h"
      34              : #include "../dom/staff.h"
      35              : #include "../dom/stem.h"
      36              : #include "../dom/stemslash.h"
      37              : #include "../dom/system.h"
      38              : #include "../dom/tremolotwochord.h"
      39              : 
      40              : #include "tlayout.h"
      41              : #include "chordlayout.h"
      42              : #include "stemlayout.h"
      43              : 
      44              : #include "log.h"
      45              : 
      46              : using namespace mu;
      47              : using namespace mu::engraving;
      48              : using namespace mu::engraving::rendering::score;
      49              : 
      50              : constexpr std::array _maxSlopes = { 0, 1, 2, 3, 4, 5, 6, 7 };
      51              : 
      52        20581 : void BeamTremoloLayout::setupLData(const BeamBase* item, BeamBase::LayoutData* ldata, const LayoutContext& ctx)
      53              : {
      54        20581 :     bool isGrace = false;
      55        20581 :     IF_ASSERT_FAILED(item && (item->isBeam() || item->isType(ElementType::TREMOLO_TWOCHORD))) {
      56              :         // right now only beams and trems are supported
      57            0 :         return;
      58        20581 :     } else if (item->isBeam()) {
      59        20186 :         ldata->beamType = BeamType::BEAM;
      60        20186 :         ldata->beam = item_cast<const Beam*>(item);
      61        20186 :         ldata->up = ldata->beam->up();
      62        20186 :         ldata->trem = nullptr; // there can be many different trems in a beam, they will all be checked
      63        20186 :         isGrace = ldata->beam->elements().front()->isGrace();
      64              :     } else {
      65          395 :         ldata->trem = item_cast<const TremoloTwoChord*>(item);
      66          395 :         ldata->beamType = BeamType::TREMOLO;
      67              :         // check to see if there is a beam happening during this trem
      68              :         // if so, it needs to be taken into account in trem placement
      69          395 :         if (ldata->trem->chord1()->beam() && ldata->trem->chord1()->beam() == ldata->trem->chord2()->beam()) {
      70          120 :             ldata->beam = ldata->trem->chord1()->beam();
      71              :         } else {
      72          275 :             ldata->beam = nullptr;
      73              :         }
      74          395 :         ldata->up = computeTremoloUp(ldata);
      75              :         //! HACK Temporary
      76          395 :         const_cast<TremoloTwoChord*>(ldata->trem)->setUp(ldata->up);
      77          395 :         isGrace = ldata->trem->chord1()->isGrace();
      78              :     }
      79              : 
      80        20581 :     ldata->spatium = item->spatium();
      81        20581 :     ldata->tick = item->tick();
      82        20581 :     ldata->beamSpacing = ctx.conf().styleB(Sid::useWideBeams) ? 4 : 3;
      83        20581 :     ldata->beamDist = (ldata->beamSpacing / 4.0) * ldata->spatium * ldata->mag() * (isGrace ? ctx.conf().styleD(Sid::graceNoteMag) : 1.);
      84        20581 :     ldata->beamWidth = (ctx.conf().styleS(Sid::beamWidth).val() * ldata->spatium) * ldata->mag();
      85        20581 :     const StaffType* staffType = item->staffType();
      86        20581 :     ldata->tab = (staffType && staffType->isTabStaff()) ? staffType : nullptr;
      87        20581 :     ldata->isBesideTabStaff = ldata->tab && !ldata->tab->stemless() && !ldata->tab->stemThrough();
      88              : }
      89              : 
      90        13633 : int BeamTremoloLayout::minStemLength(const ChordRest* cr, const BeamBase::LayoutData* ldata)
      91              : {
      92              :     // min stem lengths in quarter spaces according to how many beams there are (starting with 1)
      93              :     static constexpr int BEAMS_COUNT = 9;
      94              :     static constexpr int minStemLengths[BEAMS_COUNT] = { 11, 13, 15, 18, 21, 24, 27, 30, 33 };
      95        13633 :     int beams = strokeCount(ldata, cr);
      96        13633 :     if (beams > BEAMS_COUNT) {
      97            0 :         LOGE() << "Beam count " << beams << " out of range (" << BEAMS_COUNT - 1 << ")";
      98            0 :         return minStemLengths[BEAMS_COUNT - 1];
      99              :     }
     100              : 
     101        13633 :     return minStemLengths[std::max(beams - 1, 0)];
     102              : }
     103              : 
     104         9261 : void BeamTremoloLayout::offsetBeamToRemoveCollisions(const BeamBase* item, const BeamBase::LayoutData* ldata,
     105              :                                                      const std::vector<ChordRest*>& chordRests,
     106              :                                                      int& dictator,
     107              :                                                      int& pointer,
     108              :                                                      const double startX, const double endX,
     109              :                                                      bool isFlat, bool isStartDictator)
     110              : {
     111         9261 :     if (endX == startX) {
     112            0 :         return;
     113              :     }
     114              : 
     115         9261 :     IF_ASSERT_FAILED(!isFlat || (isFlat == (dictator == pointer))) {
     116              :         // This will produce false positives if the pointer & dictator are not flat when they should be
     117            0 :         LOGE() << "Beam is flat, dictator and pointer should be equal";
     118            0 :         pointer = dictator;
     119              :     }
     120              : 
     121              :     // tolerance eliminates all possibilities of floating point rounding errors
     122         9261 :     const double tolerance = ldata->beamWidth * 0.25 * (ldata->up ? -1 : 1);
     123         9261 :     const bool isSmall = ldata->isGrace || ldata->mag() < 1.;
     124              : 
     125         9261 :     double startY = (isStartDictator ? dictator : pointer) * ldata->spatium / 4 + tolerance;
     126         9261 :     double endY = (isStartDictator ? pointer : dictator) * ldata->spatium / 4 + tolerance;
     127              : 
     128         9261 :     const ChordRest* firstChordRest = chordRests.front();
     129         9261 :     const ChordRest* lastChordRest = chordRests.back();
     130              : 
     131         9261 :     size_t curChordRest = 0;
     132        41429 :     for (ChordRest* chordRest : chordRests) {
     133        32168 :         if (!chordRest->isChord() || chordRest == ldata->elements.back() || chordRest == ldata->elements.front()) {
     134        18589 :             curChordRest++;
     135        18589 :             continue;
     136              :         }
     137              : 
     138        13579 :         int sameLineException = 0;
     139              : 
     140        13579 :         if (chordRest->isChord()
     141        13579 :             && ((curChordRest == 1 && firstChordRest->isChord()) || (curChordRest == chordRests.size() - 2 && lastChordRest->isChord()))) {
     142         9985 :             const Chord* innerChord = toChord(chordRest);
     143         9985 :             const Chord* outerChord = curChordRest == 1 && firstChordRest->isChord() ? toChord(firstChordRest) : toChord(lastChordRest);
     144         9985 :             const int innerLine = ldata->up ? innerChord->upNote()->line() : innerChord->downNote()->line();
     145         9985 :             const int outerLine = ldata->up ? outerChord->upNote()->line() : outerChord->downNote()->line();
     146              : 
     147         9985 :             if (innerLine == outerLine) {
     148         2851 :                 sameLineException = 1;
     149         7134 :             } else if (chordRests.size() == 3) {
     150         1493 :                 const ChordRest* otherOuterCR = outerChord == firstChordRest ? lastChordRest : firstChordRest;
     151         1493 :                 const Chord* otherOuterChord = otherOuterCR->isChord() ? toChord(otherOuterCR) : nullptr;
     152         1493 :                 if (!otherOuterChord) {
     153            0 :                     continue;
     154              :                 }
     155              : 
     156         1493 :                 const int otherOuterLine = ldata->up ? otherOuterChord->upNote()->line() : otherOuterChord->downNote()->line();
     157         1493 :                 if (innerLine == otherOuterLine) {
     158          184 :                     sameLineException = 1;
     159              :                 }
     160              :             }
     161              :         }
     162              : 
     163        13579 :         PointF anchor = chordBeamAnchor(ldata, chordRest, ChordBeamAnchorType::Middle) - item->pagePos();
     164              : 
     165        13579 :         const int minLen = minStemLength(chordRest, ldata) - sameLineException;
     166              : 
     167              :         // avoid division by zero for zero-length beams (can exist as a pre-layout state used
     168              :         // for horizontal spacing computations)
     169        13579 :         if (!muse::RealIsEqual(endX, startX)) {
     170        13579 :             const double proportionAlongX = (anchor.x() - startX) / (endX - startX);
     171              :             while (true) {
     172        19033 :                 const int slope = std::abs(dictator - pointer);
     173        19033 :                 double reduction = 0.0;
     174        19033 :                 if (!isFlat) {
     175         6382 :                     if (slope <= 3) {
     176         5916 :                         reduction = 0.25 * ldata->spatium;
     177          466 :                     } else if (slope <= 6) {
     178          415 :                         reduction = 0.5 * ldata->spatium;
     179              :                     } else { // slope > 6
     180           51 :                         reduction = 0.75 * ldata->spatium;
     181              :                     }
     182              :                 }
     183              :                 // Ensure the beam clears the anchor's height and inner note's stem minimum stem length is enforced
     184        19033 :                 const double desiredY = proportionAlongX * (endY - startY) + startY;    // start note stem len + extra for slope
     185        12849 :                 const bool beamClearsAnchor = (ldata->up && muse::RealIsEqualOrLess(desiredY, anchor.y() + reduction))
     186        31882 :                                               || (!ldata->up && muse::RealIsEqualOrMore(desiredY, anchor.y() - reduction));
     187              : 
     188        19033 :                 const Note* note = ldata->up ? toChord(chordRest)->downNote() : toChord(chordRest)->upNote();
     189        19033 :                 const double noteAnchor = (ldata->up ? note->stemUpSE().y() : note->stemDownNW().y()) + note->pagePos().y()
     190        19033 :                                           - item->pagePos().y();
     191              :                 // Resultant length in quarter spaces
     192        19033 :                 const int desiredLen = std::abs(round((desiredY - noteAnchor) / ldata->spatium * 4)) + 1;
     193              : 
     194        19033 :                 if (beamClearsAnchor && desiredLen >= round(minLen * chordRest->mag())) {
     195        13579 :                     break;
     196              :                 }
     197              : 
     198         5454 :                 if (isFlat || (isSmall && dictator == pointer)) {
     199         4977 :                     dictator += ldata->up ? -1 : 1;
     200         4977 :                     pointer += ldata->up ? -1 : 1;
     201          477 :                 } else if (std::abs(dictator - pointer) == 1) {
     202          225 :                     dictator += ldata->up ? -1 : 1;
     203              :                 } else {
     204          252 :                     pointer += ldata->up ? -1 : 1;
     205              :                 }
     206              : 
     207         5454 :                 startY = (isStartDictator ? dictator : pointer) * ldata->spatium / 4 + tolerance;
     208         5454 :                 endY = (isStartDictator ? pointer : dictator) * ldata->spatium / 4 + tolerance;
     209         5454 :             }
     210              :         }
     211        13579 :         curChordRest++;
     212              :     }
     213              : }
     214              : 
     215         8905 : void BeamTremoloLayout::offsetBeamWithAnchorShortening(const BeamBase::LayoutData* ldata, const std::vector<ChordRest*>& chordRests,
     216              :                                                        int& dictator, int& pointer, int staffLines, bool isStartDictator,
     217              :                                                        int stemLengthDictator, const int targetLine)
     218              : {
     219         8905 :     const Chord* startChord = nullptr;
     220         8905 :     const Chord* endChord = nullptr;
     221        40077 :     for (const ChordRest* cr : chordRests) {
     222        31172 :         if (cr->isChord()) {
     223        31105 :             endChord = toChord(cr);
     224        31105 :             if (!startChord) {
     225         8905 :                 startChord = toChord(cr);
     226              :             }
     227              :         }
     228              :     }
     229         8905 :     if (!startChord) {
     230              :         // beam full of only rests, don't adjust this
     231            0 :         return;
     232              :     }
     233              :     // min stem lengths according to how many beams there are (starting with 1)
     234              :     static constexpr int BEAMS_COUNT = 9;
     235              :     static constexpr int minStemLengths[BEAMS_COUNT] = { 11, 13, 15, 18, 21, 24, 27, 30, 33 };
     236         8905 :     int dictatorBeams = strokeCount(ldata, isStartDictator ? startChord : endChord);
     237         8905 :     int pointerBeams = strokeCount(ldata, isStartDictator ? endChord : startChord);
     238         8905 :     if (dictatorBeams > BEAMS_COUNT) {
     239            0 :         LOGE() << "Beam count " << dictatorBeams << " out of range (" << BEAMS_COUNT - 1 << ")";
     240            0 :         dictatorBeams =  BEAMS_COUNT - 1;
     241              :     }
     242         8905 :     if (pointerBeams > BEAMS_COUNT) {
     243            0 :         LOGE() << "Beam count " << pointerBeams << " out of range (" << BEAMS_COUNT - 1 << ")";
     244            0 :         pointerBeams =  BEAMS_COUNT - 1;
     245              :     }
     246              : 
     247         8905 :     int maxDictatorReduce = stemLengthDictator - minStemLengths[std::max(dictatorBeams - 1, 0)];
     248         8905 :     maxDictatorReduce = std::min(std::abs(dictator - targetLine), maxDictatorReduce);
     249              : 
     250         8905 :     bool isFlat = dictator == pointer;
     251         8905 :     const BeamBase::NotePosition startPos = BeamBase::NotePosition(startChord->line(), startChord->vStaffIdx());
     252         8905 :     const BeamBase::NotePosition endPos = BeamBase::NotePosition(endChord->line(), endChord->vStaffIdx());
     253         8905 :     bool isAscending = startPos > endPos;
     254         8905 :     int towardBeam = ldata->up ? -1 : 1;
     255         8905 :     int newDictator = dictator;
     256         8905 :     int newPointer = pointer;
     257         8905 :     int reduce = 0;
     258        30488 :     auto fourBeamException = [](int beams, int yPos) {
     259        30488 :         yPos += 400; // because there is some weirdness with modular division around zero, add
     260              :                      // a large multiple of 4 so that we can guarantee that yPos%4 will be correct
     261        30488 :         return beams >= 4 && (yPos % 4 == 2);
     262              :     };
     263        10472 :     while (!fourBeamException(dictatorBeams, newDictator)
     264        10472 :            && !isValidBeamPosition(ldata->up, newDictator, isStartDictator, isAscending, isFlat, staffLines, true)) {
     265         1644 :         if (++reduce > maxDictatorReduce) {
     266              :             // we can't shorten this stem at all. bring it back to default and start extending
     267           77 :             newDictator = dictator;
     268           77 :             newPointer = pointer;
     269          154 :             while (!isValidBeamPosition(ldata->up, newDictator, isStartDictator, isAscending, isFlat, staffLines, true)) {
     270           77 :                 newDictator += towardBeam;
     271           77 :                 newPointer += towardBeam;
     272              :             }
     273           77 :             break;
     274              :         }
     275         1567 :         newDictator += -towardBeam;
     276         1567 :         newPointer += -towardBeam;
     277              :     }
     278              : 
     279              :     // newDictator is guaranteed either valid, or ==dictator
     280              :     // first, constrain pointer to valid position
     281         8905 :     newPointer = ldata->up ? std::min(newPointer, targetLine) : std::max(newPointer, targetLine);
     282              :     // walk it back beamwards until we get a position that satisfies both pointer and dictator
     283        20016 :     while (!fourBeamException(dictatorBeams, newDictator) && !fourBeamException(pointerBeams, newPointer)
     284        29981 :            && (!isValidBeamPosition(ldata->up, newDictator, isStartDictator, isAscending, isFlat, staffLines, true)
     285         9965 :                || !isValidBeamPosition(ldata->up, newPointer, !isStartDictator, isAscending, isFlat, staffLines, true))) {
     286         1133 :         if (isFlat) {
     287            0 :             newDictator += towardBeam;
     288            0 :             newPointer += towardBeam;
     289         1133 :         } else if (std::abs(newDictator - newPointer) == 1) {
     290            0 :             newDictator += towardBeam;
     291              :         } else {
     292         1133 :             newPointer += towardBeam;
     293              :         }
     294              :     }
     295         8905 :     dictator = newDictator;
     296         8905 :     pointer = newPointer;
     297              : 
     298         8905 :     if (isFlat) {
     299         3845 :         pointer = dictator;
     300              :     }
     301              : }
     302              : 
     303        32330 : void BeamTremoloLayout::extendStem(const BeamBase::LayoutData* ldata, Chord* chord, double addition)
     304              : {
     305        32330 :     LayoutContext ctx(chord->score());
     306              : 
     307        32330 :     PointF anchor = chordBeamAnchor(ldata, chord, ChordBeamAnchorType::Middle);
     308              :     double desiredY;
     309        32330 :     if (ldata->endAnchor.x() > ldata->startAnchor.x()) {
     310        32193 :         double proportionAlongX = (anchor.x() - ldata->startAnchor.x()) / (ldata->endAnchor.x() - ldata->startAnchor.x());
     311        32193 :         desiredY = proportionAlongX * (ldata->endAnchor.y() - ldata->startAnchor.y()) + ldata->startAnchor.y();
     312              :     } else {
     313          137 :         desiredY = std::max(ldata->endAnchor.y(), ldata->startAnchor.y());
     314              :     }
     315              : 
     316        32330 :     if (chord->up()) {
     317        18179 :         chord->setBeamExtension(anchor.y() - desiredY + addition);
     318              :     } else {
     319        14151 :         chord->setBeamExtension(desiredY - anchor.y() + addition);
     320              :     }
     321        32330 :     TLayout::layoutStem(chord->stem(), chord->stem()->mutldata(), ctx.conf());
     322              : 
     323        32330 :     if (chord->stemSlash()) {
     324           63 :         TLayout::layoutStemSlash(chord->stemSlash(), chord->stemSlash()->mutldata(), ctx.conf());
     325              :     }
     326              : 
     327              :     // Update stem shape
     328        32330 :     Stem* stem = chord->stem();
     329       105293 :     for (ShapeElement& shapeEl : chord->segment()->staffShape(chord->vStaffIdx()).elements()) {
     330        72963 :         if (shapeEl.item() == stem) {
     331        23655 :             shapeEl = ShapeElement(stem->ldata()->bbox().translated(stem->pos() + chord->pos()), stem);
     332              :         }
     333              :     }
     334        32330 : }
     335              : 
     336       104182 : bool BeamTremoloLayout::isBeamInsideStaff(int yPos, int staffLines, bool allowFloater)
     337              : {
     338       104182 :     int aboveStaff = allowFloater ? -2 : -3;
     339       104182 :     int belowStaff = (staffLines - 1) * 4 + (allowFloater ? 2 : 3);
     340       104182 :     return yPos > aboveStaff && yPos < belowStaff;
     341              : }
     342              : 
     343         9261 : void BeamTremoloLayout::setSmallInnerBeamPos(const BeamBase::LayoutData* ldata, int& dictator, int& pointer, const int staffLines,
     344              :                                              const bool isFlat, const bool isSmall, const LayoutContext& ctx)
     345              : {
     346              :     // We only want this adjustment if the beam is small and flat
     347         9261 :     if (!isSmall || !isFlat) {
     348         9257 :         return;
     349              :     }
     350           97 :     bool noteOutsideStaff = false;
     351           97 :     int beamCount = 0;
     352          410 :     for (const ChordRest* cr : ldata->elements) {
     353          313 :         if (!cr->isChord()) {
     354            0 :             continue;
     355              :         }
     356          313 :         const Chord* c = toChord(cr);
     357          313 :         beamCount = std::max(beamCount, strokeCount(ldata, cr));
     358          313 :         noteOutsideStaff |= (c->downLine() < -2 && !ldata->up) || (c->upLine() >= 11 && ldata->up);
     359              :     }
     360              : 
     361              :     // AND stems have been extended to the second stave line when the notes are far enough outside of the stave
     362           97 :     if (!noteOutsideStaff) {
     363           93 :         return;
     364              :     }
     365              : 
     366              :     // Allow fractions of quarter spaces in inner beam position, as mag can change
     367            4 :     const double mag = ldata->isGrace ? ctx.conf().style().value(Sid::graceNoteMag).toDouble() : ldata->mag();
     368            4 :     const double innerBeam = dictator + (beamCount - 1) * (ldata->up ? ldata->beamSpacing : -ldata->beamSpacing) * mag;
     369            4 :     const int aboveStaff = 1;
     370            4 :     const int belowStaff = (staffLines - 1) * 4 - 1;
     371            4 :     int offset = 0;
     372              : 
     373              :     // Make sure the innermost beam is at least 0.5sp within the stave
     374            4 :     if (ldata->up) {
     375            0 :         offset = std::min(offset, int(std::floor(belowStaff - innerBeam)));
     376              :     } else {
     377            4 :         offset = std::max(offset, int(std::ceil(aboveStaff - innerBeam)));
     378              :     }
     379              : 
     380              :     // the beam is flat, so dictator and pointer should match
     381            4 :     dictator += offset;
     382            4 :     pointer = dictator;
     383              : }
     384              : 
     385        30756 : int BeamTremoloLayout::getOuterBeamPosOffset(const BeamBase::LayoutData* ldata, int innerBeam, int beamCount, int staffLines)
     386              : {
     387        30756 :     int spacing = (ldata->up ? -ldata->beamSpacing : ldata->beamSpacing);
     388        30756 :     int offset = (beamCount - 1) * spacing;
     389        30756 :     bool isInner = false;
     390        40968 :     while (offset != 0 && !isBeamInsideStaff(innerBeam + offset, staffLines, isInner)) {
     391        10212 :         offset -= spacing;
     392        10212 :         isInner = true;
     393              :     }
     394        30756 :     return offset;
     395              : }
     396              : 
     397        91215 : bool BeamTremoloLayout::isValidBeamPosition(const bool isUp, int yPos, bool isStart, bool isAscending, bool isFlat, int staffLines,
     398              :                                             bool isOuter)
     399              : {
     400              :     // outside the staff
     401        91215 :     bool slantsAway = (isUp && isAscending == isStart) || (!isUp && isAscending != isStart);
     402        91215 :     if (!isBeamInsideStaff(yPos, staffLines, isOuter && (slantsAway || isFlat))) {
     403        47483 :         return true;
     404              :     }
     405              : 
     406              :     // removes modulo weirdness with negative numbers (i.e., right above staff)
     407        43732 :     yPos += 8;
     408              :     // is floater
     409        43732 :     if (yPos % 4 == 2) {
     410         1960 :         return false;
     411              :     }
     412        41772 :     if (isFlat) {
     413        22970 :         return true;
     414              :     }
     415              :     // is on line
     416        18802 :     if (yPos % 4 == 0) {
     417         6569 :         return true;
     418              :     }
     419              :     // is sitting
     420        12233 :     if (yPos % 4 == 3) {
     421              :         // return true only if we're starting here and descending, or ascending and ending here
     422         6026 :         return isAscending != isStart;
     423              :     }
     424              :     // is hanging
     425              :     // return true only if we're starting here and ascending, or decending and ending here
     426         6207 :     return isAscending == isStart;
     427              : }
     428              : 
     429           32 : bool BeamTremoloLayout::is64thBeamPositionException(const int beamSpacing, int& yPos, int staffLines)
     430              : {
     431           32 :     if (beamSpacing == 4) {
     432            0 :         return false;
     433              :     }
     434           32 :     return yPos == 2 || yPos == staffLines * 4 - 2 || yPos == staffLines * 4 - 6 || yPos == -2;
     435              : }
     436              : 
     437        30078 : int BeamTremoloLayout::findValidBeamOffset(const BeamBase::LayoutData* ldata, int outer, int beamCount, int staffLines, bool isStart,
     438              :                                            bool isAscending, bool isFlat)
     439              : {
     440        30078 :     bool isBeamValid = false;
     441        30078 :     int offset = 0;
     442        30078 :     int innerBeam = outer + (beamCount - 1) * (ldata->up ? ldata->beamSpacing : -ldata->beamSpacing);
     443        60197 :     while (!isBeamValid) {
     444        30600 :         while (!isValidBeamPosition(ldata->up, innerBeam + offset, isStart, isAscending, isFlat, staffLines, beamCount < 2)) {
     445          481 :             offset += ldata->up ? -1 : 1;
     446              :         }
     447        30119 :         int outerMostBeam = innerBeam + offset + getOuterBeamPosOffset(ldata, innerBeam + offset, beamCount, staffLines);
     448        30119 :         if (isValidBeamPosition(ldata->up, outerMostBeam, isStart, isAscending, isFlat, staffLines, true)
     449        30119 :             || (beamCount == 4 && is64thBeamPositionException(ldata->beamSpacing, outerMostBeam, staffLines))) {
     450        30078 :             isBeamValid = true;
     451              :         } else {
     452           41 :             offset += ldata->up ? -1 : 1;
     453              :         }
     454              :     }
     455        30078 :     return offset;
     456              : }
     457              : 
     458         9026 : void BeamTremoloLayout::setValidBeamPositions(const BeamBase::LayoutData* ldata, int& dictator, int& pointer, int beamCountD,
     459              :                                               int beamCountP,
     460              :                                               int staffLines,
     461              :                                               bool isStartDictator,
     462              :                                               bool isFlat, bool isAscending)
     463              : {
     464         9026 :     bool areBeamsValid = false;
     465         9026 :     bool has3BeamsInsideStaff = beamCountD >= 3 || beamCountP >= 3;
     466         9163 :     while (!areBeamsValid && has3BeamsInsideStaff && ldata->beamSpacing != 4) {
     467          637 :         int dictatorInner = dictator + (beamCountD - 1) * (ldata->up ? ldata->beamSpacing : -ldata->beamSpacing);
     468              :         // use dictatorInner for both to simulate flat beams
     469          637 :         int outerDictatorOffset = getOuterBeamPosOffset(ldata, dictatorInner, beamCountD, staffLines);
     470          637 :         if (std::abs(outerDictatorOffset) <= ldata->beamSpacing) {
     471          500 :             has3BeamsInsideStaff = false;
     472          500 :             break;
     473              :         }
     474          137 :         int offsetD = findValidBeamOffset(ldata, dictator, beamCountD, staffLines, isStartDictator, false, true);
     475          137 :         int offsetP = findValidBeamOffset(ldata, pointer, beamCountP, staffLines, isStartDictator, false, true);
     476          137 :         int offset = (offsetD == 0 ? offsetP : offsetD);
     477          137 :         if (pointer == dictator) {
     478          123 :             dictator += offset;
     479              :         }
     480          137 :         pointer = dictator;
     481          137 :         if (offset == 0) {
     482          109 :             areBeamsValid = true;
     483              :         }
     484              :     }
     485         9026 :     if (isFlat) {
     486              :         // flat beams need more checks (non-dictator/pointer notes with floater inner beams)
     487         3870 :         areBeamsValid = false;
     488              :     }
     489        18199 :     while (!areBeamsValid) {
     490         9173 :         int dictatorOffset = findValidBeamOffset(ldata, dictator, beamCountD, staffLines, isStartDictator, isAscending, isFlat);
     491         9173 :         dictator += dictatorOffset;
     492         9173 :         pointer += dictatorOffset;
     493         9173 :         if (isFlat) {
     494         3870 :             pointer = dictator;
     495         3870 :             int currOffset = 0;
     496        19217 :             for (ChordRest* cr : ldata->elements) {
     497        15347 :                 if (!cr->isChord() && (cr != ldata->elements.front() && cr != ldata->elements.back())) {
     498           19 :                     continue;
     499              :                 }
     500              :                 // we can use dictator beam position because all of the notes have the same beam position
     501        15328 :                 int beamCount = strokeCount(ldata, cr);
     502        15328 :                 currOffset = findValidBeamOffset(ldata, dictator, beamCount, staffLines, isStartDictator, isAscending, isFlat);
     503        15328 :                 if (currOffset) {
     504            0 :                     break;
     505              :                 }
     506              :             }
     507              : 
     508         3870 :             if (currOffset == 0) {
     509         3870 :                 areBeamsValid = true;
     510              :             } else {
     511            0 :                 dictator += currOffset;
     512            0 :                 pointer += currOffset;
     513              :             }
     514              :         } else {
     515         5303 :             pointer += findValidBeamOffset(ldata, pointer, beamCountP, staffLines, !isStartDictator, isAscending, isFlat);
     516         5303 :             if ((ldata->up && pointer <= dictator) || (!ldata->up && pointer >= dictator)) {
     517          161 :                 dictator = pointer + (ldata->up ? -1 : 1);
     518              :             } else {
     519         5142 :                 areBeamsValid = true;
     520              :             }
     521              :         }
     522              :     }
     523         9026 : }
     524              : 
     525         5703 : void BeamTremoloLayout::addMiddleLineSlant(const BeamBase::LayoutData* ldata, int& dictator, int& pointer, int beamCount, int targetLine,
     526              :                                            int interval, int desiredSlant)
     527              : {
     528         5703 :     bool isSmall = ldata->mag() < 1. || ldata->isGrace;
     529         5703 :     if (interval == 0 || (!isSmall && beamCount > 2 && ldata->beamSpacing != 4) || noSlope(ldata->beam)) {
     530          494 :         return;
     531              :     }
     532         5209 :     bool isOnTargetLine = pointer == targetLine && (std::abs(pointer - dictator) < 2);
     533         5209 :     if (isOnTargetLine) {
     534          236 :         if (std::abs(desiredSlant) == 1 || interval == 1 || (beamCount == 2 && ldata->beamSpacing != 4 && !isSmall)) {
     535          120 :             dictator = targetLine + (ldata->up ? -1 : 1);
     536              :         } else {
     537          116 :             dictator = targetLine + (ldata->up ? -2 : 2);
     538              :         }
     539              :     }
     540              : }
     541              : 
     542         9302 : void BeamTremoloLayout::add8thSpaceSlant(BeamBase::LayoutData* ldata, PointF& dictatorAnchor, int dictator, int pointer, int beamCount,
     543              :                                          int interval, int targetLine, bool isFlat)
     544              : {
     545         9302 :     if (beamCount != 3 || noSlope(ldata->beam) || ldata->beamSpacing != 3) {
     546         8798 :         return;
     547              :     }
     548          504 :     if ((isFlat && dictator != targetLine) || (dictator != pointer) || interval == 0) {
     549          480 :         return;
     550              :     }
     551           24 :     if ((ldata->up && (dictator + 4) % 4 == 3) || (!ldata->up && (dictator + 4) % 4 == 1)) {
     552            4 :         return;
     553              :     }
     554           20 :     dictatorAnchor.setY(dictatorAnchor.y() + (ldata->up ? -0.125 * ldata->spatium : 0.125 * ldata->spatium));
     555           20 :     ldata->beamDist += 0.0625 * ldata->spatium;
     556              : }
     557              : 
     558          395 : bool BeamTremoloLayout::computeTremoloUp(const BeamBase::LayoutData* ldata)
     559              : {
     560          395 :     if (!ldata->beam || !ldata->beam->cross()) {
     561          395 :         return ldata->trem->up();
     562              :     }
     563            0 :     Chord* c1 = ldata->trem->chord1();
     564            0 :     Chord* c2 = ldata->trem->chord2();
     565            0 :     int staffMove = 0;
     566            0 :     for (ChordRest* cr : ldata->beam->elements()) {
     567            0 :         if (cr->staffMove() != 0) {
     568            0 :             staffMove = cr->staffMove();
     569            0 :             break;
     570              :         }
     571              :     }
     572              :     // for inset trems in cross-staff beams, there are two potentialities:
     573              :     // 1) both trem notes are on the same staff
     574            0 :     if (c1->staffMove() == c2->staffMove()) {
     575              :         // (in which case, up is opposite to the move)
     576            0 :         if (staffMove < 0) {
     577            0 :             return c1->staffMove() != staffMove;
     578              :         } else {
     579            0 :             return c1->staffMove() == staffMove;
     580              :         }
     581              :     } else {
     582              :         // or 2) the trem notes are between staves. what a pain.
     583            0 :         return ldata->trem->up();
     584              :     }
     585              : }
     586              : 
     587        87755 : int BeamTremoloLayout::strokeCount(const BeamBase::LayoutData* ldata, const ChordRest* cr)
     588              : {
     589        87755 :     if (cr->isRest()) {
     590            0 :         return cr->beams();
     591              :     }
     592        87755 :     int strokes = 0;
     593        87755 :     const Chord* c = toChord(cr);
     594        87755 :     if (ldata->beamType == BeamType::TREMOLO) {
     595         1650 :         strokes = ldata->trem->lines();
     596        86105 :     } else if (ldata->beamType == BeamType::BEAM && c->tremoloTwoChord()) {
     597          240 :         strokes = c->tremoloTwoChord()->lines();
     598              :     }
     599        87755 :     strokes += ldata->beam ? cr->beams() : 0;
     600        87755 :     return strokes;
     601              : }
     602              : 
     603        10456 : bool BeamTremoloLayout::calculateAnchors(const BeamBase* item, BeamBase::LayoutData* ldata, const LayoutContext& ctx,
     604              :                                          const std::vector<ChordRest*>& chordRests,
     605              :                                          const std::vector<BeamBase::NotePosition>& notePositions)
     606              : {
     607        10456 :     ldata->startAnchor = PointF();
     608        10456 :     ldata->endAnchor = PointF();
     609        10456 :     if (ldata->beamType == BeamType::TREMOLO && ldata->beam) {
     610              :         // this is a trem inside a beam, and we are currently calculating the anchors of the tremolo.
     611              :         // we can do this as long as the beam has been layed out first: it saves trem anchor positions
     612          120 :         ChordRest* cr1 = ldata->trem->chord1();
     613          120 :         ChordRest* cr2 = ldata->trem->chord2();
     614          120 :         double anchorX1 = chordBeamAnchorX(ldata, cr1, ChordBeamAnchorType::Middle);
     615          120 :         double anchorX2 = chordBeamAnchorX(ldata, cr2, ChordBeamAnchorType::Middle);
     616          120 :         for (const TremAnchor& t : ldata->beam->tremAnchors()) {
     617          120 :             if (t.chord1 == cr1) {
     618          120 :                 ldata->startAnchor = PointF(anchorX1, t.y1);
     619          120 :                 ldata->endAnchor = PointF(anchorX2, t.y2);
     620          120 :                 ldata->slope = (t.y2 - t.y1) / (anchorX2 - anchorX1);
     621          120 :                 return true;
     622              :             }
     623              :         }
     624              :         // if we finish the loop before we find the anchor for this tremolo, it could mean that the
     625              :         // beam hasn't been laid out yet
     626            0 :         return false;
     627              :     }
     628        10336 :     Chord* startChord = nullptr;
     629        10336 :     Chord* endChord = nullptr;
     630        10336 :     ChordRest* startCr = nullptr;
     631        10336 :     ChordRest* endCr = nullptr;
     632        10336 :     ldata->elements = chordRests;
     633        10336 :     if (chordRests.empty()) {
     634            0 :         return false;
     635              :     }
     636              : 
     637        10336 :     bool hasChordAboveBeam = false;
     638        10336 :     bool hasChordBelowBeam = false;
     639              : 
     640        10336 :     const bool isJianpuStaff = item->onJianpuStaff();
     641        10336 :     double beamDotStack = 0.0;
     642        10336 :     bool beamAbove = false;
     643        10336 :     double beamDistance = 0.0;
     644        10336 :     double dotDistance = 0.0;
     645              : 
     646        46666 :     for (auto chordRest : chordRests) {
     647        36330 :         if (!startCr) {
     648        10336 :             startCr = chordRest;
     649        10336 :             if (isJianpuStaff) {
     650         1004 :                 beamAbove = ctx.conf().styleV(Sid::jianpuDiminutionBeamPlacement).value<PlacementV>() == PlacementV::ABOVE;
     651         1004 :                 beamDistance = ctx.conf().styleAbsolute(Sid::jianpuDiminutionBeamDistance) * startCr->mag();
     652         1004 :                 dotDistance = ctx.conf().styleAbsolute(Sid::jianpuOctaveDotDistance) * startCr->mag();
     653              :             }
     654              :         }
     655              : 
     656        36330 :         endCr = chordRest;
     657        36330 :         if (chordRest->isChord()) {
     658        35695 :             if (!startChord) {
     659        10336 :                 startChord = toChord(chordRest);
     660        10336 :                 endChord = startChord;
     661              :             } else {
     662        25359 :                 endChord = toChord(chordRest);
     663              :             }
     664        35695 :             ChordLayout::layoutStem(toChord(chordRest), ctx);
     665              :         }
     666        36330 :         if (chordRest->isBelowCrossBeam(item)) {
     667        36284 :             hasChordBelowBeam = true;
     668              :         } else {
     669           46 :             hasChordAboveBeam = true;
     670              :         }
     671              : 
     672        36330 :         if (isJianpuStaff && beamAbove) {
     673              :             // For Jianpu staffs with beams above, we need to calculate the maximum possible stack
     674              :             // of beams and above octave dots for any single chord, so that we can offset the beam
     675              :             // accordingly to avoid collisions with the dots.
     676            0 :             int aboveDots = 0;
     677            0 :             const Chord* chord = chordRest->isChord() ? toChord(chordRest) : nullptr;
     678            0 :             if (chord) {
     679            0 :                 const std::vector<JianpuOctaveDot*>& dots = chord->upNote()->jianpuOctaveDots();
     680            0 :                 if (!dots.empty() && dots.front()->ldata()->above) {
     681            0 :                     aboveDots = static_cast<int>(dots.size());
     682              :                 }
     683              :             }
     684              : 
     685            0 :             const int beamLines = strokeCount(ldata, chordRest);
     686            0 :             const double beamStack = beamLines * beamDistance;
     687            0 :             const double dotStack = aboveDots > 0 ? aboveDots * dotDistance : 0.0;
     688            0 :             beamDotStack = std::max(beamDotStack, beamStack + dotStack);
     689              :         }
     690              :     }
     691              : 
     692        10336 :     if (isJianpuStaff) {
     693         1004 :         ldata->startAnchor = chordBeamAnchor(ldata, startCr, ChordBeamAnchorType::Start);
     694         1004 :         ldata->endAnchor = chordBeamAnchor(ldata, endCr, ChordBeamAnchorType::End);
     695              : 
     696              :         // Jianpu Y origin is at the center of the number.
     697         1004 :         const double halfHeight = item->staff()->staffTypeForElement(item)->jianpuBoxH() * startCr->mag() * .5;
     698              :         // ABOVE: offset up by height/2 + stacked beam and dot
     699              :         // BELOW (default): offset down by height/2 + distance
     700         1004 :         const double offsetY = beamAbove ? -(halfHeight + beamDotStack) : halfHeight + beamDistance;
     701         1004 :         ldata->startAnchor += PointF(0, offsetY);
     702         1004 :         ldata->endAnchor += PointF(0, offsetY);
     703         1004 :         return true;
     704              :     }
     705              : 
     706         9332 :     if (!startChord) {
     707              :         // we were passed a vector of only rests. we don't support beams across only rests
     708              :         // this beam will be deleted in LayoutBeams
     709            0 :         return false;
     710              :     }
     711         9332 :     ldata->isGrace = startChord->isGrace();
     712         9332 :     ldata->notePositions = notePositions;
     713              : 
     714              :     // Set cross staff beam position, above, below or between staves
     715         9332 :     ldata->crossStaffBeamPos = BeamBase::CrossStaffBeamPosition::INVALID;
     716         9332 :     if (item->minCRMove() != item->maxCRMove()) {
     717           26 :         if (hasChordAboveBeam && !hasChordBelowBeam) {
     718            0 :             ldata->crossStaffBeamPos = BeamBase::CrossStaffBeamPosition::BELOW;
     719           26 :         } else if (hasChordBelowBeam && !hasChordAboveBeam) {
     720            0 :             ldata->crossStaffBeamPos = BeamBase::CrossStaffBeamPosition::ABOVE;
     721           26 :         } else if (hasChordAboveBeam && hasChordBelowBeam) {
     722           26 :             ldata->crossStaffBeamPos = BeamBase::CrossStaffBeamPosition::BETWEEN;
     723              :         }
     724              :     }
     725              : 
     726         9332 :     if (calculateAnchorsCross(item, ldata, ctx.conf())) {
     727           26 :         return true;
     728              :     }
     729              : 
     730         9306 :     const int closestMove = ldata->crossStaffBeamPos == BeamBase::CrossStaffBeamPosition::ABOVE ? item->minCRMove() : item->maxCRMove();
     731         9306 :     const staff_idx_t closestStaffToBeam = ldata->crossStaffBeamPos == BeamBase::CrossStaffBeamPosition::ABOVE
     732         9306 :                                            || ldata->crossStaffBeamPos
     733         9306 :                                            == BeamBase::CrossStaffBeamPosition::BELOW ? item->staffIdx()
     734         9306 :                                            + closestMove : startChord->vStaffIdx();
     735              : 
     736         9306 :     std::vector<Chord*> chordsClosestToBeam;
     737              : 
     738        41675 :     for (ChordRest* cr : ldata->elements) {
     739        32369 :         if (cr->isChord() && cr->vStaffIdx() == closestStaffToBeam) {
     740        32294 :             chordsClosestToBeam.push_back(toChord(cr));
     741              :         }
     742              :     }
     743              : 
     744         9306 :     ldata->startAnchor = chordBeamAnchor(ldata, startChord, ChordBeamAnchorType::Start);
     745         9306 :     ldata->endAnchor = chordBeamAnchor(ldata, endChord, ChordBeamAnchorType::End);
     746              : 
     747         9306 :     double startLength = startChord->defaultStemLength();
     748         9306 :     double endLength = endChord->defaultStemLength();
     749         9306 :     double startAnchorBase = ldata->startAnchor.y() + (ldata->up ? startLength : -startLength);
     750         9306 :     double endAnchorBase = ldata->endAnchor.y() + (ldata->up ? endLength : -endLength);
     751         9306 :     int startNote = ldata->up ? startChord->upNote()->line() : startChord->downNote()->line();
     752         9306 :     int endNote = ldata->up ? endChord->upNote()->line() : endChord->downNote()->line();
     753         9306 :     if (ldata->tab) {
     754            4 :         startNote = ldata->up ? startChord->upString() : startChord->downString();
     755            4 :         endNote = ldata->up ? endChord->upString() : endChord->downString();
     756              :     }
     757         9306 :     staff_idx_t startStaff = startChord->vStaffIdx();
     758         9306 :     staff_idx_t endStaff = endChord->vStaffIdx();
     759         9306 :     BeamBase::NotePosition startPos = BeamBase::NotePosition(startNote, startStaff);
     760         9306 :     BeamBase::NotePosition endPos = BeamBase::NotePosition(endNote, endStaff);
     761              : 
     762         9306 :     const int interval = std::abs(startNote - endNote);
     763         9306 :     const bool isStartDictator = ldata->up ? startPos < endPos : startPos > endPos;
     764         9306 :     const double quarterSpace = ldata->spatium / 4;
     765         9306 :     PointF startAnchor = ldata->startAnchor - item->pagePos();
     766         9306 :     PointF endAnchor = ldata->endAnchor - item->pagePos();
     767         9306 :     int dictator = round((isStartDictator ? startAnchor.y() : endAnchor.y()) / quarterSpace);
     768         9306 :     int pointer = round((isStartDictator ? endAnchor.y() : startAnchor.y()) / quarterSpace);
     769              : 
     770         9306 :     const int staffLines = ctx.dom().staff(closestStaffToBeam)->lines(ldata->tick);
     771              :     // This is the middle of the stave if the notes are normal size or the second line from the bottom if notes are small
     772         9306 :     const int targetLine = getTargetStaffLine(ldata, ctx, startChord, endChord, staffLines, closestStaffToBeam, item->staffIdx());
     773              : 
     774              :     int slant
     775         9306 :         = computeDesiredSlant(item, ldata, startPos, endPos, chordsClosestToBeam, targetLine, dictator, pointer);
     776         9306 :     bool isFlat = slant == 0;
     777              :     SlopeConstraint specialSlant
     778         9306 :         = isFlat ? getSlopeConstraint(ldata, startPos, endPos) : SlopeConstraint::NO_CONSTRAINT;
     779         9306 :     bool forceFlat = specialSlant == SlopeConstraint::FLAT;
     780         9306 :     bool smallSlant = specialSlant == SlopeConstraint::SMALL_SLOPE;
     781         9306 :     if (isFlat) {
     782         3943 :         dictator = ldata->up ? std::min(pointer, dictator) : std::max(pointer, dictator);
     783         3943 :         pointer = dictator;
     784              :     } else {
     785         5363 :         if ((dictator > pointer) != (isStartDictator ? startPos > endPos : endPos > startPos)) {
     786            4 :             dictator = pointer - slant;
     787              :         } else {
     788         5359 :             pointer = dictator + slant;
     789              :         }
     790              :     }
     791         9306 :     bool isAscending = startPos > endPos;
     792         9306 :     int beamCountD = strokeCount(ldata, isStartDictator ? startChord : endChord);
     793         9306 :     int beamCountP = strokeCount(ldata, isStartDictator ? endChord : startChord);
     794              : 
     795         9306 :     int stemLengthStart = std::abs(round((startAnchorBase - ldata->startAnchor.y()) / ldata->spatium * 4));
     796         9306 :     int stemLengthEnd = std::abs(round((endAnchorBase - ldata->endAnchor.y()) / ldata->spatium * 4));
     797         9306 :     int stemLengthDictator = isStartDictator ? stemLengthStart : stemLengthEnd;
     798         9306 :     bool isSmall = ldata->mag() < 1. || ldata->isGrace;
     799         9306 :     if (endAnchor.x() > startAnchor.x()) {
     800              :         /* When beam layout is called before horizontal spacing (see LayoutMeasure::getNextMeasure() to
     801              :          * know why) the x positions aren't yet determined and may be all zero, which would cause the
     802              :          * following function to get stuck in a loop. The if() condition avoids that case. */
     803              : 
     804              :         // Make sure grace & small note inner beams are within the stave
     805         9261 :         setSmallInnerBeamPos(ldata, dictator, pointer, staffLines, isFlat, isSmall, ctx);
     806              : 
     807         9261 :         if (!isSmall) {
     808              :             // Adjust anchor stems
     809         8905 :             offsetBeamWithAnchorShortening(ldata, chordRests, dictator, pointer, staffLines, isStartDictator, stemLengthDictator,
     810              :                                            targetLine);
     811              :         }
     812              :         // Adjust inner stems
     813         9261 :         offsetBeamToRemoveCollisions(item, ldata, chordRests, dictator, pointer, startAnchor.x(), endAnchor.x(), isFlat, isStartDictator);
     814              :     }
     815              : 
     816         9306 :     int beamCount = std::max(beamCountD, beamCountP);
     817         9306 :     if (!ldata->tab) {
     818         9302 :         if (!ldata->isGrace) {
     819         9026 :             setValidBeamPositions(ldata, dictator, pointer, beamCountD, beamCountP, staffLines, isStartDictator, isFlat, isAscending);
     820              :         }
     821         9302 :         if (!forceFlat) {
     822         5703 :             addMiddleLineSlant(ldata, dictator, pointer, beamCount, targetLine, interval, smallSlant ? 1 : slant);
     823              :         }
     824              :     }
     825              : 
     826         9306 :     ldata->startAnchor.setY(quarterSpace * (isStartDictator ? dictator : pointer) + item->pagePos().y());
     827         9306 :     ldata->endAnchor.setY(quarterSpace * (isStartDictator ? pointer : dictator) + item->pagePos().y());
     828              : 
     829         9306 :     bool add8th = true;
     830         9306 :     if (item->isType(ElementType::BEAM) && item_cast<const Beam*>(item)->userModified()) {
     831            0 :         add8th = false;
     832              :     }
     833         9306 :     if (!ldata->tab && add8th) {
     834         9302 :         add8thSpaceSlant(ldata, isStartDictator ? ldata->startAnchor : ldata->endAnchor, dictator, pointer, beamCount, interval,
     835              :                          targetLine, isFlat);
     836              :     }
     837         9306 :     ldata->startAnchor.setX(chordBeamAnchorX(ldata, startCr, ChordBeamAnchorType::Start));
     838         9306 :     ldata->endAnchor.setX(chordBeamAnchorX(ldata, endCr, ChordBeamAnchorType::End));
     839         9306 :     return true;
     840         9306 : }
     841              : 
     842         9332 : bool BeamTremoloLayout::calculateAnchorsCross(const BeamBase* item, BeamBase::LayoutData* ldata,
     843              :                                               const LayoutConfiguration& conf)
     844              : {
     845         9332 :     if (ldata->crossStaffBeamPos != BeamBase::CrossStaffBeamPosition::BETWEEN) {
     846              :         // The beam is either not cross or above/below and must be layed out like a non-cross beam
     847         9306 :         return false;
     848              :     }
     849              : 
     850           26 :     double spatium = conf.spatium();
     851           26 :     ChordRest* startCr = ldata->elements.front();
     852           26 :     ChordRest* endCr = ldata->elements.back();
     853              : 
     854           26 :     const double quarterSpace = spatium / 4;
     855              :     // imagine a line of beamed notes all in a row on the same staff. the first and last of those
     856              :     // are the 'outside' notes, and the slant of the beam is going to be affected by the 'middle' notes
     857              :     // between them.
     858              :     // we have to keep track of this for both staves.
     859           26 :     Chord* topFirst = nullptr;
     860           26 :     Chord* topLast = nullptr;
     861           26 :     Chord* bottomFirst = nullptr;
     862           26 :     Chord* bottomLast = nullptr;
     863           26 :     int maxMiddleTopLine = std::numeric_limits<int>::min(); // lowest note in the top staff
     864           26 :     int minMiddleBottomLine = std::numeric_limits<int>::max(); // highest note in the bottom staff
     865           26 :     int prevTopLine = maxMiddleTopLine; // previous note's line position (top)
     866           26 :     int prevBottomLine = minMiddleBottomLine; // previous note's line position (bottom)
     867              :     // if the immediate neighbor of one of the two 'outside' notes on either the top or bottom
     868              :     // are the same as that outside note, we need to record it so that we can add a 1/4 space slant.
     869           26 :     bool secondTopIsSame = false;
     870           26 :     bool secondBottomIsSame = false;
     871           26 :     bool penultimateTopIsSame = false;
     872           26 :     bool penultimateBottomIsSame = false;
     873           26 :     double maxY = std::numeric_limits<double>::max();
     874           26 :     double minY = std::numeric_limits<double>::min();
     875              :     // Get switches between above & below the beam
     876              :     // The direction is neutral if there is more than one switch
     877           26 :     bool prevBelowBeam = ldata->elements.front()->isBelowCrossBeam(item);
     878           26 :     bool hasBeamSideSwitch = false;
     879           26 :     int beamSideSwitchDirection = 0;
     880              : 
     881              :     // Get switches between staves on the same side of a beam
     882              :     // The direction is neutral is there is more than one switch
     883           26 :     staff_idx_t prevStaff = ldata->elements.front()->vStaffIdx();
     884           26 :     bool hasStaffSwitch = false;
     885           26 :     int staffSwitchDirection = 0;
     886              : 
     887              :     // Find the notes on the top and bottom of staves
     888              :     //
     889           26 :     bool checkNextTop = false;
     890           26 :     bool checkNextBottom = false;
     891          115 :     for (ChordRest* cr : ldata->elements) {
     892           89 :         if (!cr->isChord()) {
     893            0 :             continue;
     894              :         }
     895           89 :         Chord* c = toChord(cr);
     896              : 
     897           89 :         if (c->isBelowCrossBeam(item) == prevBelowBeam) {
     898           42 :             c->vStaffIdx();
     899           42 :             if (prevStaff != c->vStaffIdx()) {
     900            0 :                 int diff = static_cast<int>(prevStaff - c->vStaffIdx());
     901            0 :                 staffSwitchDirection = hasStaffSwitch ? 0 : (diff < 0 ? -1 : 1);
     902            0 :                 hasStaffSwitch = true;
     903              :             }
     904              :         }
     905           89 :         prevStaff = c->vStaffIdx();
     906              : 
     907           89 :         if (c->isBelowCrossBeam(item)) {
     908              :             // this chord is on the bottom staff
     909           43 :             if (penultimateBottomIsSame) {
     910              :                 // the chord we took as the penultimate bottom note wasn't.
     911              :                 // so treat it properly as a middle note
     912            0 :                 minMiddleBottomLine = std::min(minMiddleBottomLine, prevBottomLine);
     913            0 :                 penultimateBottomIsSame = false;
     914              :             }
     915           43 :             checkNextTop = false; // we are no longer looking for the second note in the top
     916              :                                   // staff being the same as the first--this note is on the bottom.
     917           43 :             if (!bottomFirst) {
     918           26 :                 bottomFirst = c;
     919           26 :                 checkNextBottom = true; // this was the first bottom note, so check for second next time
     920              :             } else {
     921           17 :                 penultimateBottomIsSame = prevBottomLine == c->line();
     922           17 :                 if (!penultimateBottomIsSame) {
     923           17 :                     minMiddleBottomLine = std::min(minMiddleBottomLine, prevBottomLine);
     924              :                 }
     925           17 :                 if (checkNextBottom) {
     926              :                     // this is the second bottom note, so we should see if this one is same line as first
     927           11 :                     secondBottomIsSame = c->line() == bottomFirst->line();
     928           11 :                     checkNextBottom = false;
     929              :                 } else {
     930            6 :                     prevBottomLine = c->line();
     931              :                 }
     932           17 :                 bottomLast = c;
     933              :             }
     934           43 :             if (!prevBelowBeam) {
     935           22 :                 beamSideSwitchDirection = hasBeamSideSwitch ? 0 : -1;
     936           22 :                 hasBeamSideSwitch = true;
     937              :             }
     938           43 :             prevBelowBeam = true;
     939           43 :             maxY = std::min(maxY, chordBeamAnchorY(ldata, toChord(c)));
     940              :         } else {
     941              :             // this chord is on the top staff
     942           46 :             if (penultimateTopIsSame) {
     943              :                 // the chord we took as the penultimate top note wasn't.
     944              :                 // so treat it properly as a middle note
     945            0 :                 maxMiddleTopLine = std::max(maxMiddleTopLine, prevTopLine);
     946            0 :                 penultimateTopIsSame = false;
     947              :             }
     948           46 :             checkNextBottom = false; // no longer looking for a bottom second note since this is on top
     949           46 :             if (!topFirst) {
     950           26 :                 topFirst = c;
     951           26 :                 checkNextTop = true;
     952              :             } else {
     953           20 :                 penultimateTopIsSame = prevTopLine == c->line();
     954           20 :                 if (!penultimateTopIsSame) {
     955           20 :                     maxMiddleTopLine = std::max(maxMiddleTopLine, prevTopLine);
     956              :                 }
     957           20 :                 if (checkNextTop) {
     958            5 :                     secondTopIsSame = c->line() == topFirst->line();
     959            5 :                     checkNextTop = false;
     960              :                 } else {
     961           15 :                     prevTopLine = c->line();
     962              :                 }
     963           20 :                 topLast = c;
     964              :             }
     965           46 :             if (prevBelowBeam) {
     966           25 :                 beamSideSwitchDirection = hasBeamSideSwitch ? 0 : 1;
     967           25 :                 hasBeamSideSwitch = true;
     968              :             }
     969           46 :             prevBelowBeam = false;
     970           46 :             minY = std::max(minY, chordBeamAnchorY(ldata, toChord(c)));
     971              :         }
     972              :     }
     973              : 
     974           26 :     double yMidPoint = (maxY + minY) / 2;
     975           26 :     if (item->isBeam()) {
     976              :         // Cross-staff beams may have segments both above and below the midline.
     977              :         // Compute the y-difference between the top and bottom segment and aim for centering in between.
     978           26 :         const Beam* beam = toBeam(item);
     979           26 :         const std::vector<BeamSegment*>& beamSegments = beam->beamSegments();
     980           26 :         const Chord* limitingChordAbove = beam->ldata()->limitingChordAbove;
     981           26 :         const Chord* limitingChordBelow = beam->ldata()->limitingChordBelow;
     982           26 :         if (!beamSegments.empty() && limitingChordAbove && limitingChordBelow) {
     983           16 :             double yCenterSegment = 0.5 * (beamSegments.front()->line.y1() + beamSegments.front()->line.y2());
     984              : 
     985           16 :             const BeamSegment* topBeamSegmentForChordAbove = beam->topLevelSegmentForElement(limitingChordAbove);
     986           16 :             double yTopSegAbove = 0.5 * (topBeamSegmentForChordAbove->line.y1() + topBeamSegmentForChordAbove->line.y2());
     987           16 :             double distAbove = yTopSegAbove - yCenterSegment;
     988              : 
     989           16 :             const BeamSegment* topBeamSegmentForChordBelow = beam->topLevelSegmentForElement(limitingChordBelow);
     990           16 :             double yTopSegBelow = 0.5 * (topBeamSegmentForChordBelow->line.y1() + topBeamSegmentForChordBelow->line.y2());
     991           16 :             double distBelow = yTopSegBelow - yCenterSegment;
     992              : 
     993           16 :             double averageDist = 0.5 * (distAbove + distBelow);
     994           16 :             yMidPoint -= 0.5 * averageDist;
     995              :         }
     996              :     }
     997              : 
     998           26 :     ldata->startAnchor.setY(yMidPoint);
     999           26 :     ldata->endAnchor.setY(yMidPoint);
    1000           26 :     ldata->startAnchor.setX(chordBeamAnchorX(ldata, startCr, ChordBeamAnchorType::Start));
    1001           26 :     ldata->endAnchor.setX(chordBeamAnchorX(ldata, endCr, ChordBeamAnchorType::End));
    1002              : 
    1003           26 :     ldata->slope = 0;
    1004              : 
    1005              :     // Calculates & sets slope
    1006           26 :     if (!noSlope(ldata->beam)) {
    1007           26 :         int topFirstLine = topFirst ? topFirst->downNote()->line() : 0;
    1008           26 :         int topLastLine = topLast ? topLast->downNote()->line() : 0;
    1009           26 :         int bottomFirstLine = bottomFirst ? bottomFirst->upNote()->line() : 0;
    1010           26 :         int bottomLastLine = bottomLast ? bottomLast->upNote()->line() : 0;
    1011           26 :         bool constrainTopToQuarter = false;
    1012           26 :         bool constrainBottomToQuarter = false;
    1013           26 :         if ((topFirstLine > topLastLine && secondTopIsSame)
    1014           26 :             || (topFirstLine < topLastLine && penultimateTopIsSame)) {
    1015            0 :             constrainTopToQuarter = true;
    1016              :         }
    1017           26 :         if ((bottomFirstLine < bottomLastLine && secondBottomIsSame)
    1018           26 :             || (bottomFirstLine > bottomLastLine && penultimateBottomIsSame)) {
    1019            0 :             constrainBottomToQuarter = true;
    1020              :         }
    1021           26 :         if (!topLast && !bottomLast && topFirst && bottomFirst) {
    1022              :             // if there are only two notes, one on each staff, special case
    1023              :             // take max slope into account
    1024              :             double yFirst, yLast;
    1025              :             // we can't rely on comparing topFirst and bottomFirst ->tick() because beamed
    1026              :             // graces have the same tick
    1027            3 :             if (ldata->elements[0] == topFirst) {
    1028            3 :                 yFirst = StemLayout::stemPos(topFirst).y();
    1029            3 :                 yLast = StemLayout::stemPos(bottomFirst).y();
    1030              :             } else {
    1031            0 :                 yFirst = StemLayout::stemPos(bottomFirst).y();
    1032            0 :                 yLast = StemLayout::stemPos(topFirst).y();
    1033              :             }
    1034            3 :             int desiredSlant = round((yFirst - yLast) / spatium);
    1035            3 :             int slant = std::min(std::abs(desiredSlant), getMaxSlope(ldata));
    1036            3 :             slant *= (desiredSlant < 0) ? -quarterSpace : quarterSpace;
    1037            3 :             ldata->startAnchor.ry() += (slant / 2);
    1038            3 :             ldata->endAnchor.ry() -= (slant / 2);
    1039            3 :         } else {
    1040              :             // Get the direction of groups of notes on top and bottom staves and the direction of switches between sides of the beam and switches between staves
    1041              :             // Directions are up, down or neutral
    1042           23 :             bool forceHoriz = false;
    1043           23 :             bool singleNoteTop = false;
    1044           23 :             bool singleNoteBottom = false;
    1045              : 
    1046           23 :             int topSlant = topFirstLine - topLastLine;
    1047           23 :             if (constrainTopToQuarter && topSlant != 0) {
    1048            0 :                 topSlant = topFirstLine < topLastLine ? -1 : 1;
    1049              :             }
    1050           23 :             if (!topLast) {
    1051              :                 // If there's only one note, set direction to neutral
    1052            3 :                 topSlant = 0;
    1053            3 :                 singleNoteTop = true;
    1054              :             }
    1055           23 :             int bottomSlant = bottomFirstLine - bottomLastLine;
    1056           23 :             if (constrainBottomToQuarter && bottomSlant != 0) {
    1057            0 :                 bottomSlant = bottomFirstLine < bottomLastLine ? -1 : 1;
    1058              :             }
    1059           23 :             if (!bottomLast) {
    1060              :                 // If there's only one note, set direction to neutral
    1061            6 :                 bottomSlant = 0;
    1062            6 :                 singleNoteBottom = true;
    1063              :             }
    1064           23 :             if ((maxMiddleTopLine >= std::max(topFirstLine, topLastLine)
    1065           23 :                  || (minMiddleBottomLine <= std::min(bottomFirstLine, bottomLastLine)))) {
    1066            0 :                 forceHoriz = true;
    1067              :             }
    1068              : 
    1069           23 :             const int topSlantDir = topSlant <= 0 ? (topSlant == 0 ? 0 : -1) : 1;
    1070           23 :             const int bottomSlantDir = bottomSlant <= 0 ? (bottomSlant == 0 ? 0 : -1) : 1;
    1071              :             // Check all directions which aren't neutral (0) match
    1072              :             // If there is any contradiction between top staff direction, bottom direction, beam side switch direction and staff switch direction, force horizontal
    1073              :             // If all are neutral, force horizontal
    1074           23 :             int overallDirection = 0;
    1075           58 :             for (int direction : { topSlantDir, bottomSlantDir, beamSideSwitchDirection, staffSwitchDirection }) {
    1076           50 :                 if (direction != 0) {
    1077           15 :                     overallDirection = direction;
    1078           15 :                     break;
    1079              :                 }
    1080              :             }
    1081              : 
    1082           23 :             const bool overallSlantFlat = overallDirection == 0;
    1083           23 :             const bool topSlantOverallDiff = (topSlantDir != 0 && topSlantDir != overallDirection);
    1084           23 :             const bool bottomSlantOverallDiff = (bottomSlantDir != 0 && bottomSlantDir != overallDirection);
    1085           23 :             const bool beamSideSwitchOverallDiff = (beamSideSwitchDirection != 0 && beamSideSwitchDirection != overallDirection);
    1086           23 :             const bool staffSwitchOverallDiff = (staffSwitchDirection != 0 && staffSwitchDirection != overallDirection);
    1087           17 :             const bool flattenNeutralBeamSideSwitch = beamSideSwitchDirection == 0 && (topSlantDir != bottomSlantDir)
    1088           40 :                                                       && !(singleNoteTop || singleNoteBottom);
    1089              : 
    1090           23 :             forceHoriz = forceHoriz || overallSlantFlat || flattenNeutralBeamSideSwitch
    1091           46 :                          || (topSlantOverallDiff || bottomSlantOverallDiff || beamSideSwitchOverallDiff || staffSwitchOverallDiff);
    1092              : 
    1093           23 :             if (!forceHoriz) {
    1094            9 :                 int slant = 0;
    1095            9 :                 if (topSlant == 0) {
    1096            3 :                     slant = bottomSlant;
    1097            6 :                 } else if (bottomSlant == 0) {
    1098            6 :                     slant = topSlant;
    1099              :                 } else {
    1100            0 :                     slant = (std::abs(topSlant) < std::abs(bottomSlant)) ? topSlant : bottomSlant;
    1101              :                 }
    1102              : 
    1103            9 :                 const int absSlant = std::min(std::abs(slant), getMaxSlope(ldata));
    1104            9 :                 const double slope = absSlant * ((slant < 0) ? -quarterSpace : quarterSpace);
    1105            9 :                 ldata->startAnchor.ry() += (slope / 2);
    1106            9 :                 ldata->endAnchor.ry() -= (slope / 2);
    1107              :             }
    1108              :         }
    1109           26 :         ldata->slope = (ldata->endAnchor.y() - ldata->startAnchor.y()) / (ldata->endAnchor.x() - ldata->startAnchor.x());
    1110              :     }
    1111           26 :     return true;
    1112              : }
    1113              : 
    1114         5801 : bool BeamTremoloLayout::noSlope(const Beam* beam)
    1115              : {
    1116         5801 :     return beam && beam->noSlope();
    1117              : }
    1118              : 
    1119         9306 : int BeamTremoloLayout::getTargetStaffLine(const BeamBase::LayoutData* ldata, const LayoutContext& ctx,
    1120              :                                           const ChordRest* startChord, const ChordRest* endChord,
    1121              :                                           const int staffLines, const staff_idx_t beamClosestStaffIdx, const staff_idx_t actualBeamStaffIdx)
    1122              : {
    1123         9306 :     bool isFullSize = muse::RealIsEqual(ldata->mag(), 1.0) && !ldata->isGrace;
    1124         9306 :     bool useWideBeams = ctx.conf().styleB(Sid::useWideBeams);
    1125         9306 :     int startBeams = strokeCount(ldata, startChord);
    1126         9306 :     int endBeams = strokeCount(ldata, endChord);
    1127        18612 :     int startTargetLine = StemLayout::minStaffOverlap(ldata->up, staffLines, startBeams, false,
    1128         9306 :                                                       ldata->beamSpacing / 4.0, useWideBeams, isFullSize);
    1129        18612 :     int endTargetLine = StemLayout::minStaffOverlap(ldata->up, staffLines, endBeams, false,
    1130         9306 :                                                     ldata->beamSpacing / 4.0, useWideBeams, !ldata->isGrace);
    1131              : 
    1132         9306 :     int diff = 0;
    1133              :     // Get diff between beam closest staff and actual staff, unless its full cross?
    1134         9306 :     if (ldata->crossStaffBeamPos == BeamBase::CrossStaffBeamPosition::ABOVE
    1135         9306 :         || ldata->crossStaffBeamPos == BeamBase::CrossStaffBeamPosition::BELOW) {
    1136              :         // Make sure we calculate the distance to the target line on the stave closest to the beam
    1137            0 :         const System* curSys = startChord->measure()->system();
    1138            0 :         const int dir = ldata->up ? -1 : 1;
    1139            0 :         if (curSys && beamClosestStaffIdx != actualBeamStaffIdx) {
    1140            0 :             diff = std::round(std::abs(curSys->staffYpage(beamClosestStaffIdx) - curSys->staffYpage(
    1141            0 :                                            actualBeamStaffIdx)) / ldata->spatium * 4 * dir);
    1142              :         }
    1143              :     }
    1144              :     // offset target line by 1 or -1 since the anchor is at the middle of the beam,
    1145              :     // not at the tip of the stem
    1146         9306 :     if (ldata->up) {
    1147         4807 :         return std::min(startTargetLine + diff, endTargetLine + diff) + 1;
    1148              :     }
    1149         4499 :     return std::max(startTargetLine + diff, endTargetLine + diff) - 1;
    1150              : }
    1151              : 
    1152         9306 : int BeamTremoloLayout::computeDesiredSlant(const BeamBase* item, const BeamBase::LayoutData* ldata, const BeamBase::NotePosition& startPos,
    1153              :                                            const BeamBase::NotePosition& endPos, std::vector<Chord*> closestChordsToBeam,
    1154              :                                            int targetLine, int dictator, int pointer)
    1155              : {
    1156         9306 :     if (item->isType(ElementType::BEAM) && item_cast<const Beam*>(item)->noSlope()) {
    1157           50 :         return 0;
    1158              :     }
    1159         9256 :     int dictatorExtension = targetLine - dictator; // we need to make sure that beams extended to the middle line
    1160         9256 :     int pointerExtension = targetLine - pointer;  // are properly treated as flat.
    1161         9256 :     if (ldata->up) {
    1162         4777 :         dictatorExtension = std::min(dictatorExtension, 0);
    1163         4777 :         pointerExtension = std::min(pointerExtension, 0);
    1164              :     } else {
    1165         4479 :         dictatorExtension = std::max(dictatorExtension, 0);
    1166         4479 :         pointerExtension = std::max(pointerExtension, 0);
    1167              :     }
    1168         9256 :     if (dictator + dictatorExtension == targetLine && pointer + pointerExtension == targetLine) {
    1169          239 :         return 0;
    1170              :     }
    1171         9017 :     if (startPos == endPos) {
    1172         3040 :         return 0;
    1173              :     }
    1174         5977 :     SlopeConstraint slopeConstrained = getSlopeConstraint(ldata, startPos, endPos);
    1175         5977 :     if (slopeConstrained == SlopeConstraint::FLAT) {
    1176          614 :         return 0;
    1177         5363 :     } else if (slopeConstrained == SlopeConstraint::SMALL_SLOPE) {
    1178          144 :         return dictator > pointer ? -1 : 1;
    1179              :     }
    1180              : 
    1181              :     // calculate max slope based on distance between first and last chords
    1182         5219 :     int maxSlope = getMaxSlope(ldata);
    1183              : 
    1184         5219 :     if (ldata->crossStaffBeamPos == BeamBase::CrossStaffBeamPosition::ABOVE
    1185         5219 :         || ldata->crossStaffBeamPos == BeamBase::CrossStaffBeamPosition::BELOW) {
    1186              :         // Calculate slant between first and last notes
    1187            0 :         int beamDir = startPos == endPos ? 0 : (startPos > endPos ? 1 : -1);
    1188              : 
    1189              :         // Calculate slant between notes on stave closest to the beam
    1190            0 :         size_t closestChordsSize = closestChordsToBeam.size();
    1191            0 :         BeamBase::NotePosition closestStartPos(closestChordsSize > 0 ? closestChordsToBeam.front()->line() : 0,
    1192            0 :                                                closestChordsSize > 0 ? closestChordsToBeam.front()->vStaffIdx() : 0);
    1193            0 :         BeamBase::NotePosition closestEndPos(closestChordsSize > 0 ? closestChordsToBeam.back()->line() : 0,
    1194            0 :                                              closestChordsSize > 0 ? closestChordsToBeam.back()->vStaffIdx() : 0);
    1195            0 :         int staveClosestToBeamDir = closestStartPos == closestEndPos ? 0 : (closestStartPos > closestEndPos ? 1 : -1);
    1196              : 
    1197              :         // Contradiction, beam must be flat
    1198            0 :         if (beamDir != staveClosestToBeamDir && beamDir != 0 && staveClosestToBeamDir != 0) {
    1199            0 :             return 0;
    1200              :         }
    1201              : 
    1202              :         // When the notes on the stave closest to the beam have a neutral direction, set a slant of 1/-1 in the direction of the staff change between first and last chords
    1203            0 :         if (staveClosestToBeamDir == 0 && beamDir != 0) {
    1204            0 :             if (startPos.staff != endPos.staff) {
    1205            0 :                 return std::abs(beamDir) * (ldata->up ? 1 : -1);
    1206              :             }
    1207              :         }
    1208              :     }
    1209              : 
    1210              :     // calculate max slope based on note interval
    1211         5219 :     int interval = std::min(std::abs(endPos.line - startPos.line), (int)_maxSlopes.size() - 1);
    1212         5219 :     return std::min(maxSlope, _maxSlopes[interval]) * (ldata->up ? 1 : -1);
    1213              : }
    1214              : 
    1215         9920 : SlopeConstraint BeamTremoloLayout::getSlopeConstraint(const BeamBase::LayoutData* ldata, const BeamBase::NotePosition& startPos,
    1216              :                                                       const BeamBase::NotePosition& endPos)
    1217              : {
    1218         9920 :     if (ldata->notePositions.empty()) {
    1219          176 :         return SlopeConstraint::NO_CONSTRAINT;
    1220              :     }
    1221              : 
    1222              :     // 0 to constrain to flat, 1 to constrain to 0.25, <0 for no constraint
    1223         9744 :     if (startPos == endPos) {
    1224         2981 :         return SlopeConstraint::FLAT;
    1225         6763 :     } else if (ldata->beamType == BeamType::TREMOLO) {
    1226              :         // tremolos don't need the small slope constraint since they only have two notes
    1227          260 :         return SlopeConstraint::NO_CONSTRAINT;
    1228              :     }
    1229              : 
    1230              :     // if a note is more extreme than the endpoints, slope is 0
    1231              :     // p.s. _notes is a sorted vector
    1232         6503 :     const std::vector<ChordRest*>& elements = ldata->elements;
    1233         6503 :     const std::vector<BeamBase::NotePosition>& notePositions = ldata->notePositions;
    1234              : 
    1235         6503 :     if (elements.size() > 2) {
    1236         4709 :         if (ldata->up) {
    1237         2899 :             BeamBase::NotePosition higherEnd = std::min(startPos, endPos);
    1238         2899 :             if (higherEnd > notePositions[0]) {
    1239          878 :                 return SlopeConstraint::FLAT; // a note is higher in the staff than the highest end
    1240              :             }
    1241         2495 :             if (higherEnd == notePositions[0] && higherEnd >= notePositions[1]) {
    1242          474 :                 if (higherEnd > notePositions[1]) {
    1243            0 :                     return SlopeConstraint::FLAT; // a note is higher in the staff than the highest end
    1244              :                 }
    1245          474 :                 size_t chordCount = elements.size();
    1246          474 :                 if (chordCount >= 3 && notePositions.size() >= 3) {
    1247          474 :                     bool middleNoteHigherThanHigherEnd = higherEnd >= notePositions[2];
    1248          474 :                     if (middleNoteHigherThanHigherEnd) {
    1249           78 :                         return SlopeConstraint::FLAT; // two notes are the same as the highest end (notes [0] [1] and [2] higher than or same as higherEnd)
    1250              :                     }
    1251          396 :                     Chord* secondNote = elements[1]->isChord() ? toChord(elements[1]) : nullptr;
    1252              :                     Chord* secondToLastNote
    1253          396 :                         = elements[chordCount - 2]->isChord() ? toChord(elements[chordCount - 2]) : nullptr;
    1254          538 :                     bool secondNoteSameHeightAsHigherEnd = startPos < endPos && secondNote && BeamBase::NotePosition(
    1255          142 :                         secondNote->upLine(), secondNote->vStaffIdx()) == higherEnd;
    1256          650 :                     bool secondToLastNoteSameHeightAsHigherEnd = endPos.line < startPos.line && secondToLastNote && BeamBase::NotePosition(
    1257          254 :                         secondToLastNote->upLine(), secondToLastNote->vStaffIdx()) == higherEnd;
    1258          396 :                     if (!(secondNoteSameHeightAsHigherEnd || secondToLastNoteSameHeightAsHigherEnd)) {
    1259          346 :                         return SlopeConstraint::FLAT; // only one note same as higher end, but it is not a neighbor
    1260              :                     } else {
    1261              :                         // there is a single note next to the highest one with equivalent height
    1262              :                         // and they are neighbors. this is our exception, so
    1263              :                         // the slope may be a max of 0.25.
    1264           50 :                         return SlopeConstraint::SMALL_SLOPE;
    1265              :                     }
    1266              :                 } else {
    1267            0 :                     return SlopeConstraint::FLAT; // only two notes in entire beam, in this case startNote == endNote
    1268              :                 }
    1269              :             }
    1270              :         } else {
    1271         1810 :             BeamBase::NotePosition lowerEnd = std::max(startPos, endPos);
    1272         1810 :             if (lowerEnd < notePositions[notePositions.size() - 1]) {
    1273          502 :                 return SlopeConstraint::FLAT;
    1274              :             }
    1275         1602 :             if (lowerEnd == notePositions[notePositions.size() - 1]
    1276         1602 :                 && lowerEnd <= notePositions[notePositions.size() - 2]) {
    1277          294 :                 if (lowerEnd < notePositions[notePositions.size() - 2]) {
    1278            0 :                     return SlopeConstraint::FLAT;
    1279              :                 }
    1280          294 :                 size_t chordCount = elements.size();
    1281          294 :                 if (chordCount >= 3 && notePositions.size() >= 3) {
    1282          294 :                     bool middleNoteLowerThanLowerEnd = lowerEnd <= notePositions[notePositions.size() - 3];
    1283          294 :                     if (middleNoteLowerThanLowerEnd) {
    1284           44 :                         return SlopeConstraint::FLAT;
    1285              :                     }
    1286          250 :                     const Chord* secondNote = elements[1]->isChord() ? toChord(elements[1]) : nullptr;
    1287              :                     const Chord* secondToLastNote
    1288          250 :                         = elements[chordCount - 2]->isChord() ? toChord(elements[chordCount - 2]) : nullptr;
    1289          250 :                     const BeamBase::NotePosition secondNotePos = secondNote ? BeamBase::NotePosition(
    1290          250 :                         secondNote->downLine(), secondNote->vStaffIdx()) : BeamBase::NotePosition(0, muse::nidx);
    1291          250 :                     const BeamBase::NotePosition secondToLastNotePos = secondToLastNote ? BeamBase::NotePosition(
    1292          250 :                         secondToLastNote->downLine(), secondToLastNote->vStaffIdx()) : BeamBase::NotePosition(0, muse::nidx);
    1293              : 
    1294          250 :                     bool secondNoteSameHeightAsLowerEnd = startPos.line > endPos.line && secondNotePos == lowerEnd;
    1295          250 :                     bool secondToLastNoteSameHeightAsLowerEnd = endPos.line > startPos.line && secondToLastNotePos == lowerEnd;
    1296          250 :                     if (!(secondNoteSameHeightAsLowerEnd || secondToLastNoteSameHeightAsLowerEnd)) {
    1297          156 :                         return SlopeConstraint::FLAT;
    1298              :                     } else {
    1299           94 :                         return SlopeConstraint::SMALL_SLOPE;
    1300              :                     }
    1301              :                 } else {
    1302            0 :                     return SlopeConstraint::FLAT;
    1303              :                 }
    1304              :             }
    1305              :         }
    1306              :     }
    1307         5123 :     return SlopeConstraint::NO_CONSTRAINT;
    1308              : }
    1309              : 
    1310         5231 : int BeamTremoloLayout::getMaxSlope(const BeamBase::LayoutData* ldata)
    1311              : {
    1312              :     // for 2-indexed interval i (seconds, thirds, etc.)
    1313              :     // maxSlopes[i] = max slope of beam for notes with interval i
    1314              : 
    1315              :     // calculate max slope based on distance between first and last chords
    1316         5231 :     double endX = chordBeamAnchorX(ldata, ldata->elements[ldata->elements.size() - 1], ChordBeamAnchorType::Start);
    1317         5231 :     double startX = chordBeamAnchorX(ldata, ldata->elements[0], ChordBeamAnchorType::End);
    1318         5231 :     double beamWidth = endX - startX;
    1319         5231 :     beamWidth /= ldata->spatium;
    1320         5231 :     int maxSlope = _maxSlopes.back();
    1321         5231 :     if (beamWidth < 3.0) {
    1322         2100 :         maxSlope = _maxSlopes[1];
    1323         3131 :     } else if (beamWidth < 5.0) {
    1324          500 :         maxSlope = _maxSlopes[2];
    1325         2631 :     } else if (beamWidth < 7.5) {
    1326          901 :         maxSlope = _maxSlopes[3];
    1327         1730 :     } else if (beamWidth < 10.0) {
    1328         1043 :         maxSlope = _maxSlopes[4];
    1329          687 :     } else if (beamWidth < 15.0) {
    1330          258 :         maxSlope = _maxSlopes[5];
    1331          429 :     } else if (beamWidth < 20.0) {
    1332          371 :         maxSlope = _maxSlopes[6];
    1333              :     } else {
    1334           58 :         maxSlope = _maxSlopes[7];
    1335              :     }
    1336              : 
    1337         5231 :     return maxSlope;
    1338              : }
    1339              : 
    1340            0 : int BeamTremoloLayout::getBeamCount(const BeamBase::LayoutData* ldata, const std::vector<const ChordRest*>& chordRests)
    1341              : {
    1342            0 :     int maxBeams = 0;
    1343            0 :     for (const ChordRest* chordRest : chordRests) {
    1344            0 :         if (chordRest->isChord() && strokeCount(ldata, chordRest) > maxBeams) {
    1345            0 :             maxBeams = strokeCount(ldata, chordRest);
    1346              :         }
    1347              :     }
    1348            0 :     return maxBeams;
    1349              : }
    1350              : 
    1351       144875 : double BeamTremoloLayout::chordBeamAnchorX(const BeamBase::LayoutData* ldata, const ChordRest* cr, ChordBeamAnchorType anchorType)
    1352              : {
    1353       144875 :     bool isJianpu = cr->onJianpuStaff();
    1354       144875 :     double pagePosX = ldata->trem ? ldata->trem->pagePos().x() : ldata->beam ? ldata->beam->pagePos().x() : 0.0;
    1355       144875 :     double crPosX = cr->pagePos().x() - pagePosX;
    1356       137645 :     auto stemPosX = [cr, crPosX]() { return StemLayout::stemPosX(cr) + crPosX; };
    1357              : 
    1358       144875 :     if (!isJianpu && (!cr->isChord() || !toChord(cr)->stem())) {
    1359          548 :         if (ldata->up) {
    1360          300 :             return stemPosX();
    1361              :         } else {
    1362              :             // rests always return the right side of the glyph as their stemPosX
    1363              :             // so we need to adjust back to the left side if stems are down
    1364          248 :             return stemPosX() - StemLayout::stemPosX(cr);
    1365              :         }
    1366              :     }
    1367       144327 :     const Chord* chord = cr->isChord() ? toChord(cr) : nullptr;
    1368       144327 :     const Stem* stem = chord ? chord->stem() : nullptr;
    1369              : 
    1370         3630 :     auto crWidth = [cr]() { return cr->ldata()->bbox().width(); };
    1371        91685 :     auto stemWidth = [stem]() { return stem ? stem->lineWidthMag() : 0.0; };
    1372              : 
    1373       144327 :     switch (anchorType) {
    1374        49016 :     case ChordBeamAnchorType::Start:
    1375        49016 :         if (isJianpu) {
    1376         3600 :             return crPosX;
    1377              :         }
    1378        45416 :         if (ldata->tab) {
    1379           16 :             return stemPosX() - 0.5 * stemWidth();
    1380              :         }
    1381        45400 :         if (chord && chord->up()) {
    1382        23663 :             return stemPosX() - stemWidth();
    1383              :         }
    1384        21737 :         break;
    1385        46280 :     case ChordBeamAnchorType::Middle:
    1386        46280 :         if (isJianpu) {
    1387           30 :             return crPosX + crWidth() / 2;
    1388              :         }
    1389        46250 :         if (ldata->tab) {
    1390           12 :             return stemPosX();
    1391              :         }
    1392        46238 :         return chord && chord->up() ? stemPosX() - 0.5 * stemWidth() : stemPosX() + 0.5 * stemWidth();
    1393              : 
    1394        49031 :     case ChordBeamAnchorType::End:
    1395        49031 :         if (isJianpu) {
    1396         3600 :             return crPosX + crWidth();
    1397              :         }
    1398        45431 :         if (ldata->tab) {
    1399           16 :             return stemPosX() + 0.5 * stemWidth();
    1400              :         }
    1401        45415 :         if (chord && !chord->up()) {
    1402        21752 :             return stemPosX() + stemWidth();
    1403              :         }
    1404        23663 :         break;
    1405              :     }
    1406              : 
    1407        45400 :     return stemPosX();
    1408              : }
    1409              : 
    1410        87727 : double BeamTremoloLayout::chordBeamAnchorY(const BeamBase::LayoutData* ldata, const ChordRest* cr)
    1411              : {
    1412        87727 :     if (!cr->isChord()) {
    1413          564 :         return cr->pagePos().y();
    1414              :     }
    1415              : 
    1416        87163 :     const Chord* chord = toChord(cr);
    1417        87163 :     if (chord->onJianpuStaff()) {
    1418         3500 :         return chord->upNote()->pagePos().y();
    1419              :     }
    1420              : 
    1421        83663 :     Note* note = cr->up() ? chord->downNote() : chord->upNote();
    1422        83663 :     PointF position = note->pagePos();
    1423              : 
    1424        83663 :     int upValue = chord->up() ? -1 : 1;
    1425        83663 :     double beamOffset = ldata->beamWidth / 2 * upValue;
    1426              : 
    1427        83663 :     if (ldata->isBesideTabStaff) {
    1428            0 :         double stemLength = StemLayout::tabStemLength(chord, ldata->tab) * (ldata->up ? -1 : 1);
    1429            0 :         double y = StemLayout::tabRestStemPosY(chord, ldata->tab) + stemLength;
    1430            0 :         y *= ldata->spatium;
    1431            0 :         y -= beamOffset;
    1432            0 :         return y + chord->pagePos().y();
    1433              :     }
    1434              : 
    1435        83663 :     return position.y() - note->offset().y() + (chord->defaultStemLength() * upValue) - beamOffset;
    1436              : }
    1437              : 
    1438        87638 : PointF BeamTremoloLayout::chordBeamAnchor(const BeamBase::LayoutData* ldata, const ChordRest* cr, ChordBeamAnchorType anchorType)
    1439              : {
    1440        87638 :     return PointF(chordBeamAnchorX(ldata, cr, anchorType), chordBeamAnchorY(ldata, cr));
    1441              : }
        

Generated by: LCOV version 2.0-1