The JUCE cross-platform C++ framework, with DISTRHO/KXStudio specific changes
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

613 lines
23KB

  1. /*
  2. ==============================================================================
  3. This file is part of the juce_core module of the JUCE library.
  4. Copyright (c) 2013 - Raw Material Software Ltd.
  5. Permission to use, copy, modify, and/or distribute this software for any purpose with
  6. or without fee is hereby granted, provided that the above copyright notice and this
  7. permission notice appear in all copies.
  8. THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH REGARD
  9. TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN
  10. NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
  11. DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER
  12. IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN
  13. CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
  14. ------------------------------------------------------------------------------
  15. NOTE! This permissive ISC license applies ONLY to files within the juce_core module!
  16. All other JUCE modules are covered by a dual GPL/commercial license, so if you are
  17. using any other modules, be sure to check that you also comply with their license.
  18. For more details, visit www.juce.com
  19. ==============================================================================
  20. */
  21. #ifndef JUCE_MATHSFUNCTIONS_H_INCLUDED
  22. #define JUCE_MATHSFUNCTIONS_H_INCLUDED
  23. //==============================================================================
  24. /*
  25. This file sets up some handy mathematical typdefs and functions.
  26. */
  27. //==============================================================================
  28. // Definitions for the int8, int16, int32, int64 and pointer_sized_int types.
  29. /** A platform-independent 8-bit signed integer type. */
  30. typedef signed char int8;
  31. /** A platform-independent 8-bit unsigned integer type. */
  32. typedef unsigned char uint8;
  33. /** A platform-independent 16-bit signed integer type. */
  34. typedef signed short int16;
  35. /** A platform-independent 16-bit unsigned integer type. */
  36. typedef unsigned short uint16;
  37. /** A platform-independent 32-bit signed integer type. */
  38. typedef signed int int32;
  39. /** A platform-independent 32-bit unsigned integer type. */
  40. typedef unsigned int uint32;
  41. #if JUCE_MSVC
  42. /** A platform-independent 64-bit integer type. */
  43. typedef __int64 int64;
  44. /** A platform-independent 64-bit unsigned integer type. */
  45. typedef unsigned __int64 uint64;
  46. #else
  47. /** A platform-independent 64-bit integer type. */
  48. typedef long long int64;
  49. /** A platform-independent 64-bit unsigned integer type. */
  50. typedef unsigned long long uint64;
  51. #endif
  52. #ifndef DOXYGEN
  53. /** A macro for creating 64-bit literals.
  54. Historically, this was needed to support portability with MSVC6, and is kept here
  55. so that old code will still compile, but nowadays every compiler will support the
  56. LL and ULL suffixes, so you should use those in preference to this macro.
  57. */
  58. #define literal64bit(longLiteral) (longLiteral##LL)
  59. #endif
  60. #if JUCE_64BIT
  61. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  62. typedef int64 pointer_sized_int;
  63. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  64. typedef uint64 pointer_sized_uint;
  65. #elif JUCE_MSVC
  66. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  67. typedef _W64 int pointer_sized_int;
  68. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  69. typedef _W64 unsigned int pointer_sized_uint;
  70. #else
  71. /** A signed integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  72. typedef int pointer_sized_int;
  73. /** An unsigned integer type that's guaranteed to be large enough to hold a pointer without truncating it. */
  74. typedef unsigned int pointer_sized_uint;
  75. #endif
  76. #if JUCE_MSVC
  77. typedef pointer_sized_int ssize_t;
  78. #endif
  79. //==============================================================================
  80. // Some indispensible min/max functions
  81. /** Returns the larger of two values. */
  82. template <typename Type>
  83. inline Type jmax (const Type a, const Type b) { return (a < b) ? b : a; }
  84. /** Returns the larger of three values. */
  85. template <typename Type>
  86. inline Type jmax (const Type a, const Type b, const Type c) { return (a < b) ? ((b < c) ? c : b) : ((a < c) ? c : a); }
  87. /** Returns the larger of four values. */
  88. template <typename Type>
  89. inline Type jmax (const Type a, const Type b, const Type c, const Type d) { return jmax (a, jmax (b, c, d)); }
  90. /** Returns the smaller of two values. */
  91. template <typename Type>
  92. inline Type jmin (const Type a, const Type b) { return (b < a) ? b : a; }
  93. /** Returns the smaller of three values. */
  94. template <typename Type>
  95. inline Type jmin (const Type a, const Type b, const Type c) { return (b < a) ? ((c < b) ? c : b) : ((c < a) ? c : a); }
  96. /** Returns the smaller of four values. */
  97. template <typename Type>
  98. inline Type jmin (const Type a, const Type b, const Type c, const Type d) { return jmin (a, jmin (b, c, d)); }
  99. /** Remaps a normalised value (between 0 and 1) to a target range.
  100. This effectively returns (targetRangeMin + value0To1 * (targetRangeMax - targetRangeMin))
  101. */
  102. template <class Type>
  103. static Type jmap (Type value0To1, Type targetRangeMin, Type targetRangeMax)
  104. {
  105. return targetRangeMin + value0To1 * (targetRangeMax - targetRangeMin);
  106. }
  107. /** Remaps a value from a source range to a target range. */
  108. template <class Type>
  109. static Type jmap (Type sourceValue, Type sourceRangeMin, Type sourceRangeMax, Type targetRangeMin, Type targetRangeMax)
  110. {
  111. return targetRangeMin + ((targetRangeMax - targetRangeMin) * (sourceValue - sourceRangeMin)) / (sourceRangeMax - sourceRangeMin);
  112. }
  113. /** Scans an array of values, returning the minimum value that it contains. */
  114. template <typename Type>
  115. const Type findMinimum (const Type* data, int numValues)
  116. {
  117. if (numValues <= 0)
  118. return Type();
  119. Type result (*data++);
  120. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  121. {
  122. const Type& v = *data++;
  123. if (v < result) result = v;
  124. }
  125. return result;
  126. }
  127. /** Scans an array of values, returning the maximum value that it contains. */
  128. template <typename Type>
  129. const Type findMaximum (const Type* values, int numValues)
  130. {
  131. if (numValues <= 0)
  132. return Type();
  133. Type result (*values++);
  134. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  135. {
  136. const Type& v = *values++;
  137. if (result < v) result = v;
  138. }
  139. return result;
  140. }
  141. /** Scans an array of values, returning the minimum and maximum values that it contains. */
  142. template <typename Type>
  143. void findMinAndMax (const Type* values, int numValues, Type& lowest, Type& highest)
  144. {
  145. if (numValues <= 0)
  146. {
  147. lowest = Type();
  148. highest = Type();
  149. }
  150. else
  151. {
  152. Type mn (*values++);
  153. Type mx (mn);
  154. while (--numValues > 0) // (> 0 rather than >= 0 because we've already taken the first sample)
  155. {
  156. const Type& v = *values++;
  157. if (mx < v) mx = v;
  158. if (v < mn) mn = v;
  159. }
  160. lowest = mn;
  161. highest = mx;
  162. }
  163. }
  164. //==============================================================================
  165. /** Constrains a value to keep it within a given range.
  166. This will check that the specified value lies between the lower and upper bounds
  167. specified, and if not, will return the nearest value that would be in-range. Effectively,
  168. it's like calling jmax (lowerLimit, jmin (upperLimit, value)).
  169. Note that it expects that lowerLimit <= upperLimit. If this isn't true,
  170. the results will be unpredictable.
  171. @param lowerLimit the minimum value to return
  172. @param upperLimit the maximum value to return
  173. @param valueToConstrain the value to try to return
  174. @returns the closest value to valueToConstrain which lies between lowerLimit
  175. and upperLimit (inclusive)
  176. @see jlimit0To, jmin, jmax
  177. */
  178. template <typename Type>
  179. inline Type jlimit (const Type lowerLimit,
  180. const Type upperLimit,
  181. const Type valueToConstrain) noexcept
  182. {
  183. jassert (lowerLimit <= upperLimit); // if these are in the wrong order, results are unpredictable..
  184. return (valueToConstrain < lowerLimit) ? lowerLimit
  185. : ((upperLimit < valueToConstrain) ? upperLimit
  186. : valueToConstrain);
  187. }
  188. /** Returns true if a value is at least zero, and also below a specified upper limit.
  189. This is basically a quicker way to write:
  190. @code valueToTest >= 0 && valueToTest < upperLimit
  191. @endcode
  192. */
  193. template <typename Type>
  194. inline bool isPositiveAndBelow (Type valueToTest, Type upperLimit) noexcept
  195. {
  196. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  197. return Type() <= valueToTest && valueToTest < upperLimit;
  198. }
  199. template <>
  200. inline bool isPositiveAndBelow (const int valueToTest, const int upperLimit) noexcept
  201. {
  202. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  203. return static_cast <unsigned int> (valueToTest) < static_cast <unsigned int> (upperLimit);
  204. }
  205. /** Returns true if a value is at least zero, and also less than or equal to a specified upper limit.
  206. This is basically a quicker way to write:
  207. @code valueToTest >= 0 && valueToTest <= upperLimit
  208. @endcode
  209. */
  210. template <typename Type>
  211. inline bool isPositiveAndNotGreaterThan (Type valueToTest, Type upperLimit) noexcept
  212. {
  213. jassert (Type() <= upperLimit); // makes no sense to call this if the upper limit is itself below zero..
  214. return Type() <= valueToTest && valueToTest <= upperLimit;
  215. }
  216. template <>
  217. inline bool isPositiveAndNotGreaterThan (const int valueToTest, const int upperLimit) noexcept
  218. {
  219. jassert (upperLimit >= 0); // makes no sense to call this if the upper limit is itself below zero..
  220. return static_cast <unsigned int> (valueToTest) <= static_cast <unsigned int> (upperLimit);
  221. }
  222. //==============================================================================
  223. /** Handy function to swap two values. */
  224. template <typename Type>
  225. inline void swapVariables (Type& variable1, Type& variable2)
  226. {
  227. std::swap (variable1, variable2);
  228. }
  229. /** Handy function for avoiding unused variables warning. */
  230. template <typename Type1>
  231. void ignoreUnused (const Type1&) noexcept {}
  232. template <typename Type1, typename Type2>
  233. void ignoreUnused (const Type1&, const Type2&) noexcept {}
  234. template <typename Type1, typename Type2, typename Type3>
  235. void ignoreUnused (const Type1&, const Type2&, const Type3&) noexcept {}
  236. template <typename Type1, typename Type2, typename Type3, typename Type4>
  237. void ignoreUnused (const Type1&, const Type2&, const Type3&, const Type4&) noexcept {}
  238. /** Handy function for getting the number of elements in a simple const C array.
  239. E.g.
  240. @code
  241. static int myArray[] = { 1, 2, 3 };
  242. int numElements = numElementsInArray (myArray) // returns 3
  243. @endcode
  244. */
  245. template <typename Type, int N>
  246. inline int numElementsInArray (Type (&array)[N])
  247. {
  248. (void) array; // (required to avoid a spurious warning in MS compilers)
  249. (void) sizeof (0[array]); // This line should cause an error if you pass an object with a user-defined subscript operator
  250. return N;
  251. }
  252. //==============================================================================
  253. // Some useful maths functions that aren't always present with all compilers and build settings.
  254. /** Using juce_hypot is easier than dealing with the different types of hypot function
  255. that are provided by the various platforms and compilers. */
  256. template <typename Type>
  257. inline Type juce_hypot (Type a, Type b) noexcept
  258. {
  259. #if JUCE_MSVC
  260. return static_cast<Type> (_hypot (a, b));
  261. #else
  262. return static_cast<Type> (hypot (a, b));
  263. #endif
  264. }
  265. #ifndef DOXYGEN
  266. template <>
  267. inline float juce_hypot (float a, float b) noexcept
  268. {
  269. #if JUCE_MSVC
  270. return (_hypotf (a, b));
  271. #else
  272. return (hypotf (a, b));
  273. #endif
  274. }
  275. #endif
  276. /** 64-bit abs function. */
  277. inline int64 abs64 (const int64 n) noexcept
  278. {
  279. return (n >= 0) ? n : -n;
  280. }
  281. #if JUCE_MSVC && ! defined (DOXYGEN) // The MSVC libraries omit these functions for some reason...
  282. template<typename Type> Type asinh (Type x) noexcept { return std::log (x + std::sqrt (x * x + (Type) 1)); }
  283. template<typename Type> Type acosh (Type x) noexcept { return std::log (x + std::sqrt (x * x - (Type) 1)); }
  284. template<typename Type> Type atanh (Type x) noexcept { return (std::log (x + (Type) 1) - std::log (((Type) 1) - x)) / (Type) 2; }
  285. #endif
  286. //==============================================================================
  287. /** A predefined value for Pi, at double-precision.
  288. @see float_Pi
  289. */
  290. const double double_Pi = 3.1415926535897932384626433832795;
  291. /** A predefined value for Pi, at single-precision.
  292. @see double_Pi
  293. */
  294. const float float_Pi = 3.14159265358979323846f;
  295. /** Converts an angle in degrees to radians. */
  296. template <typename FloatType>
  297. inline FloatType degreesToRadians (FloatType degrees) noexcept { return degrees * static_cast<FloatType> (double_Pi / 180.0); }
  298. /** Converts an angle in radians to degrees. */
  299. template <typename FloatType>
  300. inline FloatType radiansToDegrees (FloatType radians) noexcept { return radians * static_cast<FloatType> (180.0 / double_Pi); }
  301. //==============================================================================
  302. /** The isfinite() method seems to vary between platforms, so this is a
  303. platform-independent function for it.
  304. */
  305. template <typename NumericType>
  306. inline bool juce_isfinite (NumericType) noexcept
  307. {
  308. return true; // Integer types are always finite
  309. }
  310. template <>
  311. inline bool juce_isfinite (float value) noexcept
  312. {
  313. #if JUCE_WINDOWS
  314. return _finite (value) != 0;
  315. #else
  316. return std::isfinite (value);
  317. #endif
  318. }
  319. template <>
  320. inline bool juce_isfinite (double value) noexcept
  321. {
  322. #if JUCE_WINDOWS
  323. return _finite (value) != 0;
  324. #else
  325. return std::isfinite (value);
  326. #endif
  327. }
  328. //==============================================================================
  329. #if JUCE_MSVC
  330. #pragma optimize ("t", off)
  331. #ifndef __INTEL_COMPILER
  332. #pragma float_control (precise, on, push)
  333. #endif
  334. #endif
  335. /** Fast floating-point-to-integer conversion.
  336. This is faster than using the normal c++ cast to convert a float to an int, and
  337. it will round the value to the nearest integer, rather than rounding it down
  338. like the normal cast does.
  339. Note that this routine gets its speed at the expense of some accuracy, and when
  340. rounding values whose floating point component is exactly 0.5, odd numbers and
  341. even numbers will be rounded up or down differently.
  342. */
  343. template <typename FloatType>
  344. inline int roundToInt (const FloatType value) noexcept
  345. {
  346. #ifdef __INTEL_COMPILER
  347. #pragma float_control (precise, on, push)
  348. #endif
  349. union { int asInt[2]; double asDouble; } n;
  350. n.asDouble = ((double) value) + 6755399441055744.0;
  351. #if JUCE_BIG_ENDIAN
  352. return n.asInt [1];
  353. #else
  354. return n.asInt [0];
  355. #endif
  356. }
  357. inline int roundToInt (int value) noexcept
  358. {
  359. return value;
  360. }
  361. #if JUCE_MSVC
  362. #ifndef __INTEL_COMPILER
  363. #pragma float_control (pop)
  364. #endif
  365. #pragma optimize ("", on) // resets optimisations to the project defaults
  366. #endif
  367. /** Fast floating-point-to-integer conversion.
  368. This is a slightly slower and slightly more accurate version of roundDoubleToInt(). It works
  369. fine for values above zero, but negative numbers are rounded the wrong way.
  370. */
  371. inline int roundToIntAccurate (const double value) noexcept
  372. {
  373. #ifdef __INTEL_COMPILER
  374. #pragma float_control (pop)
  375. #endif
  376. return roundToInt (value + 1.5e-8);
  377. }
  378. /** Fast floating-point-to-integer conversion.
  379. This is faster than using the normal c++ cast to convert a double to an int, and
  380. it will round the value to the nearest integer, rather than rounding it down
  381. like the normal cast does.
  382. Note that this routine gets its speed at the expense of some accuracy, and when
  383. rounding values whose floating point component is exactly 0.5, odd numbers and
  384. even numbers will be rounded up or down differently. For a more accurate conversion,
  385. see roundDoubleToIntAccurate().
  386. */
  387. inline int roundDoubleToInt (const double value) noexcept
  388. {
  389. return roundToInt (value);
  390. }
  391. /** Fast floating-point-to-integer conversion.
  392. This is faster than using the normal c++ cast to convert a float to an int, and
  393. it will round the value to the nearest integer, rather than rounding it down
  394. like the normal cast does.
  395. Note that this routine gets its speed at the expense of some accuracy, and when
  396. rounding values whose floating point component is exactly 0.5, odd numbers and
  397. even numbers will be rounded up or down differently.
  398. */
  399. inline int roundFloatToInt (const float value) noexcept
  400. {
  401. return roundToInt (value);
  402. }
  403. //==============================================================================
  404. /** Returns true if the specified integer is a power-of-two. */
  405. template <typename IntegerType>
  406. bool isPowerOfTwo (IntegerType value)
  407. {
  408. return (value & (value - 1)) == 0;
  409. }
  410. /** Returns the smallest power-of-two which is equal to or greater than the given integer. */
  411. inline int nextPowerOfTwo (int n) noexcept
  412. {
  413. --n;
  414. n |= (n >> 1);
  415. n |= (n >> 2);
  416. n |= (n >> 4);
  417. n |= (n >> 8);
  418. n |= (n >> 16);
  419. return n + 1;
  420. }
  421. /** Returns the number of bits in a 32-bit integer. */
  422. inline int countNumberOfBits (uint32 n) noexcept
  423. {
  424. n -= ((n >> 1) & 0x55555555);
  425. n = (((n >> 2) & 0x33333333) + (n & 0x33333333));
  426. n = (((n >> 4) + n) & 0x0f0f0f0f);
  427. n += (n >> 8);
  428. n += (n >> 16);
  429. return (int) (n & 0x3f);
  430. }
  431. /** Returns the number of bits in a 64-bit integer. */
  432. inline int countNumberOfBits (uint64 n) noexcept
  433. {
  434. return countNumberOfBits ((uint32) n) + countNumberOfBits ((uint32) (n >> 32));
  435. }
  436. /** Performs a modulo operation, but can cope with the dividend being negative.
  437. The divisor must be greater than zero.
  438. */
  439. template <typename IntegerType>
  440. IntegerType negativeAwareModulo (IntegerType dividend, const IntegerType divisor) noexcept
  441. {
  442. jassert (divisor > 0);
  443. dividend %= divisor;
  444. return (dividend < 0) ? (dividend + divisor) : dividend;
  445. }
  446. /** Returns the square of its argument. */
  447. template <typename NumericType>
  448. NumericType square (NumericType n) noexcept
  449. {
  450. return n * n;
  451. }
  452. //==============================================================================
  453. #if JUCE_INTEL || defined (DOXYGEN)
  454. /** This macro can be applied to a float variable to check whether it contains a denormalised
  455. value, and to normalise it if necessary.
  456. On CPUs that aren't vulnerable to denormalisation problems, this will have no effect.
  457. */
  458. #define JUCE_UNDENORMALISE(x) { (x) += 0.1f; (x) -= 0.1f; }
  459. #else
  460. #define JUCE_UNDENORMALISE(x)
  461. #endif
  462. //==============================================================================
  463. /** This namespace contains a few template classes for helping work out class type variations.
  464. */
  465. namespace TypeHelpers
  466. {
  467. #if JUCE_VC8_OR_EARLIER
  468. #define PARAMETER_TYPE(type) const type&
  469. #else
  470. /** The ParameterType struct is used to find the best type to use when passing some kind
  471. of object as a parameter.
  472. Of course, this is only likely to be useful in certain esoteric template situations.
  473. Because "typename TypeHelpers::ParameterType<SomeClass>::type" is a bit of a mouthful, there's
  474. a PARAMETER_TYPE(SomeClass) macro that you can use to get the same effect.
  475. E.g. "myFunction (PARAMETER_TYPE (int), PARAMETER_TYPE (MyObject))"
  476. would evaluate to "myfunction (int, const MyObject&)", keeping any primitive types as
  477. pass-by-value, but passing objects as a const reference, to avoid copying.
  478. */
  479. template <typename Type> struct ParameterType { typedef const Type& type; };
  480. #if ! DOXYGEN
  481. template <typename Type> struct ParameterType <Type&> { typedef Type& type; };
  482. template <typename Type> struct ParameterType <Type*> { typedef Type* type; };
  483. template <> struct ParameterType <char> { typedef char type; };
  484. template <> struct ParameterType <unsigned char> { typedef unsigned char type; };
  485. template <> struct ParameterType <short> { typedef short type; };
  486. template <> struct ParameterType <unsigned short> { typedef unsigned short type; };
  487. template <> struct ParameterType <int> { typedef int type; };
  488. template <> struct ParameterType <unsigned int> { typedef unsigned int type; };
  489. template <> struct ParameterType <long> { typedef long type; };
  490. template <> struct ParameterType <unsigned long> { typedef unsigned long type; };
  491. template <> struct ParameterType <int64> { typedef int64 type; };
  492. template <> struct ParameterType <uint64> { typedef uint64 type; };
  493. template <> struct ParameterType <bool> { typedef bool type; };
  494. template <> struct ParameterType <float> { typedef float type; };
  495. template <> struct ParameterType <double> { typedef double type; };
  496. #endif
  497. /** A helpful macro to simplify the use of the ParameterType template.
  498. @see ParameterType
  499. */
  500. #define PARAMETER_TYPE(a) typename TypeHelpers::ParameterType<a>::type
  501. #endif
  502. /** These templates are designed to take a type, and if it's a double, they return a double
  503. type; for anything else, they return a float type.
  504. */
  505. template <typename Type> struct SmallestFloatType { typedef float type; };
  506. template <> struct SmallestFloatType <double> { typedef double type; };
  507. }
  508. //==============================================================================
  509. #endif // JUCE_MATHSFUNCTIONS_H_INCLUDED