Chris@147: /* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */ Chris@147: Chris@147: /* Chris@147: Sonic Visualiser Chris@147: An audio file viewer and annotation editor. Chris@147: Centre for Digital Music, Queen Mary, University of London. Chris@147: This file copyright 2006 Chris Cannam. Chris@147: Chris@147: This program is free software; you can redistribute it and/or Chris@147: modify it under the terms of the GNU General Public License as Chris@147: published by the Free Software Foundation; either version 2 of the Chris@147: License, or (at your option) any later version. See the file Chris@147: COPYING included with this distribution for more information. Chris@147: */ Chris@147: Chris@147: #include "PowerOfTwoZoomConstraint.h" Chris@147: Chris@1324: ZoomLevel Chris@1324: PowerOfTwoZoomConstraint::getNearestZoomLevel(ZoomLevel requested, Chris@1324: RoundingDirection dir) const Chris@1324: { Chris@1324: int blockSize; Chris@1324: Chris@1324: if (requested.zone == ZoomLevel::FramesPerPixel) { Chris@1324: blockSize = getNearestBlockSize(requested.level, dir); Chris@1324: if (blockSize > getMaxZoomLevel().level) { Chris@1324: blockSize = getMaxZoomLevel().level; Chris@1324: } Chris@1324: return { requested.zone, blockSize }; Chris@1324: } else { Chris@1324: RoundingDirection opposite = dir; Chris@1324: if (dir == RoundUp) opposite = RoundDown; Chris@1324: else if (dir == RoundDown) opposite = RoundUp; Chris@1324: blockSize = getNearestBlockSize(requested.level, opposite); Chris@1324: if (blockSize > getMinZoomLevel().level) { Chris@1324: blockSize = getMinZoomLevel().level; Chris@1324: } Chris@1324: if (blockSize == 1) { Chris@1324: return { ZoomLevel::FramesPerPixel, 1 }; Chris@1324: } else { Chris@1324: return { requested.zone, blockSize }; Chris@1324: } Chris@1324: } Chris@1324: } Chris@1324: Chris@929: int Chris@929: PowerOfTwoZoomConstraint::getNearestBlockSize(int req, Chris@1429: RoundingDirection dir) const Chris@147: { Chris@929: int result = 0; Chris@147: Chris@929: for (int bs = 1; ; bs *= 2) { Chris@1429: if (bs >= req) { Chris@1429: if (dir == RoundNearest) { Chris@1429: if (bs - req < req - bs/2) { Chris@1429: result = bs; Chris@1429: break; Chris@1429: } else { Chris@1429: result = bs/2; Chris@1429: break; Chris@1429: } Chris@1429: } else if (dir == RoundDown) { Chris@1429: result = bs/2; Chris@1429: break; Chris@1429: } else { Chris@1429: result = bs; Chris@1429: break; Chris@1429: } Chris@1429: } Chris@147: } Chris@147: Chris@1324: if (result > getMaxZoomLevel().level) result = getMaxZoomLevel().level; Chris@147: return result; Chris@147: } Chris@147: