Get the style color and number just once
[LibreOffice.git] / basegfx / source / numeric / ftools.cxx
blobd603d4e6df4528b8a619e25010886460fddfc729
1 /* -*- Mode: C++; tab-width: 4; indent-tabs-mode: nil; c-basic-offset: 4 -*- */
2 /*
3 * This file is part of the LibreOffice project.
5 * This Source Code Form is subject to the terms of the Mozilla Public
6 * License, v. 2.0. If a copy of the MPL was not distributed with this
7 * file, You can obtain one at http://mozilla.org/MPL/2.0/.
9 * This file incorporates work covered by the following license notice:
11 * Licensed to the Apache Software Foundation (ASF) under one or more
12 * contributor license agreements. See the NOTICE file distributed
13 * with this work for additional information regarding copyright
14 * ownership. The ASF licenses this file to you under the Apache
15 * License, Version 2.0 (the "License"); you may not use this file
16 * except in compliance with the License. You may obtain a copy of
17 * the License at http://www.apache.org/licenses/LICENSE-2.0 .
20 #include <basegfx/numeric/ftools.hxx>
22 namespace basegfx
24 double snapToNearestMultiple(double v, const double fStep)
26 if(fTools::equalZero(fStep))
28 // with a zero step, all snaps to 0.0
29 return 0.0;
31 else
33 const double fHalfStep(fStep * 0.5);
34 const double fChange(fHalfStep - fmod(v + fHalfStep, fStep));
36 if(basegfx::fTools::equal(fabs(v), fabs(fChange)))
38 return 0.0;
40 else
42 return v + fChange;
47 double snapToZeroRange(double v, double fWidth)
49 if(fTools::equalZero(fWidth))
51 // with no range all snaps to range bound
52 return 0.0;
54 else
56 if(v < 0.0 || v > fWidth)
58 double fRetval(fmod(v, fWidth));
60 if(fRetval < 0.0)
62 fRetval += fWidth;
65 return fRetval;
67 else
69 return v;
74 double snapToRange(double v, double fLow, double fHigh)
76 if(fTools::equal(fLow, fHigh))
78 // with no range all snaps to range bound
79 return 0.0;
81 else
83 if(fLow > fHigh)
85 // correct range order. Evtl. assert this (?)
86 std::swap(fLow, fHigh);
89 if(v < fLow || v > fHigh)
91 return snapToZeroRange(v - fLow, fHigh - fLow) + fLow;
93 else
95 return v;
100 double normalizeToRange(double v, const double fRange)
102 if(fRange <= 0.0)
104 // with a zero (or less) range, all normalizes to 0.0
105 return 0.0;
108 if(v < 0.0)
110 if(fTools::moreOrEqual(v, -fRange))
112 // in range [-fRange, 0.0[, shift one step
113 return v + fRange;
116 // re-calculate
117 return v - (floor(v/fRange)*fRange);
119 else
121 if(fTools::less(v, fRange))
123 // already in range [0.0, fRange[, nothing to do
124 return v;
127 // re-calculate
128 return v - (floor(v/fRange)*fRange);
131 } // end of namespace basegfx
133 /* vim:set shiftwidth=4 softtabstop=4 expandtab: */